1 /**
2  * Copyright (c) 2020, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef CPP_WATCHDOG_SERVER_SRC_WATCHDOGPROCESSSERVICE_H_
18 #define CPP_WATCHDOG_SERVER_SRC_WATCHDOGPROCESSSERVICE_H_
19 
20 #include "AIBinderDeathRegistrationWrapper.h"
21 
22 #include <aidl/android/automotive/watchdog/ICarWatchdogClient.h>
23 #include <aidl/android/automotive/watchdog/TimeoutLength.h>
24 #include <aidl/android/automotive/watchdog/internal/ICarWatchdogMonitor.h>
25 #include <aidl/android/automotive/watchdog/internal/ICarWatchdogServiceForSystem.h>
26 #include <aidl/android/automotive/watchdog/internal/ProcessIdentifier.h>
27 #include <android-base/chrono_utils.h>
28 #include <android-base/result.h>
29 #include <android/binder_auto_utils.h>
30 #include <android/hidl/manager/1.0/IServiceManager.h>
31 #include <android/util/ProtoOutputStream.h>
32 #include <cutils/multiuser.h>
33 #include <utils/Looper.h>
34 #include <utils/Mutex.h>
35 #include <utils/RefBase.h>
36 #include <utils/String16.h>
37 #include <utils/StrongPointer.h>
38 #include <utils/Vector.h>
39 
40 #include <IVhalClient.h>
41 #include <VehicleHalTypes.h>
42 
43 #include <optional>
44 #include <unordered_map>
45 #include <unordered_set>
46 #include <vector>
47 
48 namespace android {
49 namespace automotive {
50 namespace watchdog {
51 
52 // Forward declaration for testing use only.
53 namespace internal {
54 
55 class WatchdogProcessServicePeer;
56 
57 }  // namespace internal
58 
59 class WatchdogServiceHelperInterface;
60 class PackageInfoResolverInterface;
61 
62 class WatchdogProcessServiceInterface : virtual public android::RefBase {
63 public:
64     virtual android::base::Result<void> start() = 0;
65     virtual void terminate() = 0;
66     virtual void onDump(int fd) = 0;
67     virtual void onDumpProto(android::util::ProtoOutputStream& outProto) = 0;
68     virtual void doHealthCheck(int what) = 0;
69     virtual void handleBinderDeath(void* cookie) = 0;
70     virtual ndk::ScopedAStatus registerClient(
71             const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>& client,
72             aidl::android::automotive::watchdog::TimeoutLength timeout) = 0;
73     virtual ndk::ScopedAStatus unregisterClient(
74             const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>&
75                     client) = 0;
76     virtual ndk::ScopedAStatus registerCarWatchdogService(
77             const ndk::SpAIBinder& binder,
78             const android::sp<WatchdogServiceHelperInterface>& helper) = 0;
79     virtual void unregisterCarWatchdogService(const ndk::SpAIBinder& binder) = 0;
80     virtual ndk::ScopedAStatus registerMonitor(
81             const std::shared_ptr<
82                     aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor>&
83                     monitor) = 0;
84     virtual ndk::ScopedAStatus unregisterMonitor(
85             const std::shared_ptr<
86                     aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor>&
87                     monitor) = 0;
88     virtual ndk::ScopedAStatus tellClientAlive(
89             const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>& client,
90             int32_t sessionId) = 0;
91     virtual ndk::ScopedAStatus tellCarWatchdogServiceAlive(
92             const std::shared_ptr<
93                     aidl::android::automotive::watchdog::internal::ICarWatchdogServiceForSystem>&
94                     service,
95             const std::vector<aidl::android::automotive::watchdog::internal::ProcessIdentifier>&
96                     clientsNotResponding,
97             int32_t sessionId) = 0;
98     virtual ndk::ScopedAStatus tellDumpFinished(
99             const std::shared_ptr<
100                     aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor>& monitor,
101             const aidl::android::automotive::watchdog::internal::ProcessIdentifier&
102                     processIdentifier) = 0;
103     virtual void setEnabled(bool isEnabled) = 0;
104     virtual void onUserStateChange(userid_t userId, bool isStarted) = 0;
105     virtual void onAidlVhalPidFetched(int32_t) = 0;
106 };
107 
108 class WatchdogProcessService final : public WatchdogProcessServiceInterface {
109 public:
110     explicit WatchdogProcessService(const android::sp<Looper>& handlerLooper);
111     WatchdogProcessService(
112             const std::function<std::shared_ptr<
113                     android::frameworks::automotive::vhal::IVhalClient>()>& tryCreateVhalClientFunc,
114             const std::function<android::sp<android::hidl::manager::V1_0::IServiceManager>()>&
115                     tryGetHidlServiceManagerFunc,
116             const std::function<int64_t(pid_t)>& getStartTimeForPidFunc,
117             const std::chrono::nanoseconds& vhalPidCachingRetryDelayNs,
118             const sp<Looper>& handlerLooper,
119             const sp<AIBinderDeathRegistrationWrapperInterface>& deathRegistrationWrapper);
120     ~WatchdogProcessService();
121 
122     android::base::Result<void> start() override;
123     void terminate() override;
124     void onDump(int fd) override;
125     void onDumpProto(util::ProtoOutputStream& outProto) override;
126     void doHealthCheck(int what) override;
127     void handleBinderDeath(void* cookie) override;
128     ndk::ScopedAStatus registerClient(
129             const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>& client,
130             aidl::android::automotive::watchdog::TimeoutLength timeout) override;
131     ndk::ScopedAStatus unregisterClient(
132             const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>& client)
133             override;
134     ndk::ScopedAStatus registerCarWatchdogService(
135             const ndk::SpAIBinder& binder,
136             const android::sp<WatchdogServiceHelperInterface>& helper) override;
137     void unregisterCarWatchdogService(const ndk::SpAIBinder& binder) override;
138     ndk::ScopedAStatus registerMonitor(
139             const std::shared_ptr<
140                     aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor>& monitor)
141             override;
142     ndk::ScopedAStatus unregisterMonitor(
143             const std::shared_ptr<
144                     aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor>& monitor)
145             override;
146     ndk::ScopedAStatus tellClientAlive(
147             const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>& client,
148             int32_t sessionId) override;
149     ndk::ScopedAStatus tellCarWatchdogServiceAlive(
150             const std::shared_ptr<
151                     aidl::android::automotive::watchdog::internal::ICarWatchdogServiceForSystem>&
152                     service,
153             const std::vector<aidl::android::automotive::watchdog::internal::ProcessIdentifier>&
154                     clientsNotResponding,
155             int32_t sessionId) override;
156     ndk::ScopedAStatus tellDumpFinished(
157             const std::shared_ptr<
158                     aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor>& monitor,
159             const aidl::android::automotive::watchdog::internal::ProcessIdentifier&
160                     processIdentifier) override;
161     void setEnabled(bool isEnabled) override;
162     void onUserStateChange(userid_t userId, bool isStarted) override;
163     void onAidlVhalPidFetched(int32_t) override;
164 
165 private:
166     enum ClientType {
167         Regular,
168         Service,
169     };
170 
171     class ClientInfo {
172     public:
ClientInfo(const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient> & client,pid_t pid,userid_t userId,uint64_t startTimeMillis,const WatchdogProcessService & service)173         ClientInfo(const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient>&
174                            client,
175                    pid_t pid, userid_t userId, uint64_t startTimeMillis,
176                    const WatchdogProcessService& service) :
177               kPid(pid),
178               kUserId(userId),
179               kStartTimeMillis(startTimeMillis),
180               kType(ClientType::Regular),
181               kService(service),
182               kClient(client) {}
ClientInfo(const android::sp<WatchdogServiceHelperInterface> & helper,const ndk::SpAIBinder & binder,pid_t pid,userid_t userId,uint64_t startTimeMillis,const WatchdogProcessService & service)183         ClientInfo(const android::sp<WatchdogServiceHelperInterface>& helper,
184                    const ndk::SpAIBinder& binder, pid_t pid, userid_t userId,
185                    uint64_t startTimeMillis, const WatchdogProcessService& service) :
186               kPid(pid),
187               kUserId(userId),
188               kStartTimeMillis(startTimeMillis),
189               kType(ClientType::Service),
190               kService(service),
191               kWatchdogServiceHelper(helper),
192               kWatchdogServiceBinder(binder) {}
193 
194         std::string toString() const;
195         AIBinder* getAIBinder() const;
196         ndk::ScopedAStatus linkToDeath(AIBinder_DeathRecipient* recipient) const;
197         ndk::ScopedAStatus unlinkToDeath(AIBinder_DeathRecipient* recipient) const;
198         ndk::ScopedAStatus checkIfAlive(
199                 aidl::android::automotive::watchdog::TimeoutLength timeout) const;
200         ndk::ScopedAStatus prepareProcessTermination() const;
201 
202         const pid_t kPid;
203         const userid_t kUserId;
204         const int64_t kStartTimeMillis;
205         const ClientType kType;
206         const WatchdogProcessService& kService;
207         const std::shared_ptr<aidl::android::automotive::watchdog::ICarWatchdogClient> kClient;
208         const android::sp<WatchdogServiceHelperInterface> kWatchdogServiceHelper;
209         const ndk::SpAIBinder kWatchdogServiceBinder;
210 
211         int sessionId;
212         std::string packageName;
213     };
214 
215     struct HeartBeat {
216         int64_t eventTime;
217         int64_t value;
218     };
219 
220     typedef std::unordered_map<int, ClientInfo> PingedClientMap;
221 
222     class PropertyChangeListener final :
223           public android::frameworks::automotive::vhal::ISubscriptionCallback {
224     public:
PropertyChangeListener(const android::sp<WatchdogProcessService> & service)225         explicit PropertyChangeListener(const android::sp<WatchdogProcessService>& service) :
226               kService(service) {}
227 
228         void onPropertyEvent(const std::vector<
229                              std::unique_ptr<android::frameworks::automotive::vhal::IHalPropValue>>&
230                                      values) override;
231 
232         void onPropertySetError(
233                 const std::vector<android::frameworks::automotive::vhal::HalPropError>& errors)
234                 override;
235 
236     private:
237         const android::sp<WatchdogProcessService> kService;
238     };
239 
240     class MessageHandlerImpl final : public MessageHandler {
241     public:
MessageHandlerImpl(const android::sp<WatchdogProcessService> & service)242         explicit MessageHandlerImpl(const android::sp<WatchdogProcessService>& service) :
243               kService(service) {}
244 
245         void handleMessage(const Message& message) override;
246 
247     private:
248         const android::sp<WatchdogProcessService> kService;
249     };
250 
251 private:
252     android::base::Result<void> registerClient(
253             const ClientInfo& clientInfo,
254             aidl::android::automotive::watchdog::TimeoutLength timeout);
255     ndk::ScopedAStatus unregisterClientLocked(
256             const std::vector<aidl::android::automotive::watchdog::TimeoutLength>& timeouts,
257             const ndk::SpAIBinder& binder, ClientType clientType);
258     ndk::ScopedAStatus tellClientAliveLocked(const ndk::SpAIBinder& binder, int32_t sessionId);
259     android::base::Result<void> startHealthCheckingLocked(
260             aidl::android::automotive::watchdog::TimeoutLength timeout);
261     android::base::Result<void> dumpAndKillClientsIfNotResponding(
262             aidl::android::automotive::watchdog::TimeoutLength timeout);
263     android::base::Result<void> dumpAndKillAllProcesses(
264             const std::vector<aidl::android::automotive::watchdog::internal::ProcessIdentifier>&
265                     processesNotResponding,
266             bool reportToVhal);
267     int32_t getNewSessionId();
268     android::base::Result<void> updateVhal(
269             const aidl::android::hardware::automotive::vehicle::VehiclePropValue& value);
270     android::base::Result<void> connectToVhal();
271     void subscribeToVhalHeartBeat();
272     const sp<WatchdogServiceHelperInterface> getWatchdogServiceHelperLocked();
273     void cacheVhalProcessIdentifier();
274     void cacheVhalProcessIdentifierForPid(int32_t pid);
275     android::base::Result<void> requestAidlVhalPid();
276     void reportWatchdogAliveToVhal();
277     void reportTerminatedProcessToVhal(
278             const std::vector<aidl::android::automotive::watchdog::internal::ProcessIdentifier>&
279                     processesNotResponding);
280     android::base::Result<std::string> readProcCmdLine(int32_t pid);
281     void handleVhalDeath();
282     void queryVhalProperties();
283     void updateVhalHeartBeat(int64_t value);
284     void checkVhalHealth();
285     void resetVhalInfoLocked();
286     void terminateVhal();
287 
288     using ClientInfoMap = std::unordered_map<uintptr_t, ClientInfo>;
289     using Processor = std::function<void(ClientInfoMap&, ClientInfoMap::const_iterator)>;
290     bool findClientAndProcessLocked(
291             const std::vector<aidl::android::automotive::watchdog::TimeoutLength>& timeouts,
292             AIBinder* binder, const Processor& processor);
293     bool findClientAndProcessLocked(
294             const std::vector<aidl::android::automotive::watchdog::TimeoutLength>& timeouts,
295             uintptr_t binderPtrId, const Processor& processor);
296     std::chrono::nanoseconds getTimeoutDurationNs(
297             const aidl::android::automotive::watchdog::TimeoutLength& timeout);
298     static int toProtoClientType(ClientType clientType);
299 
300 private:
301     const std::function<std::shared_ptr<android::frameworks::automotive::vhal::IVhalClient>()>
302             kTryCreateVhalClientFunc;
303     const std::function<android::sp<android::hidl::manager::V1_0::IServiceManager>()>
304             kTryGetHidlServiceManagerFunc;
305     const std::function<int64_t(pid_t)> kGetStartTimeForPidFunc;
306     const std::chrono::nanoseconds kVhalPidCachingRetryDelayNs;
307 
308     android::sp<Looper> mHandlerLooper;
309     android::sp<MessageHandlerImpl> mMessageHandler;
310     ndk::ScopedAIBinder_DeathRecipient mClientBinderDeathRecipient;
311     std::unordered_set<aidl::android::hardware::automotive::vehicle::VehicleProperty>
312             mNotSupportedVhalProperties;
313     std::shared_ptr<PropertyChangeListener> mPropertyChangeListener;
314     // mLastSessionId is accessed only within main thread. No need for mutual-exclusion.
315     int32_t mLastSessionId;
316     bool mServiceStarted;
317     std::chrono::milliseconds mVhalHealthCheckWindowMillis;
318     std::optional<std::chrono::nanoseconds> mOverriddenClientHealthCheckWindowNs;
319     std::shared_ptr<android::frameworks::automotive::vhal::IVhalClient::OnBinderDiedCallbackFunc>
320             mVhalBinderDiedCallback;
321     android::sp<AIBinderDeathRegistrationWrapperInterface> mDeathRegistrationWrapper;
322     android::sp<PackageInfoResolverInterface> mPackageInfoResolver;
323 
324     android::Mutex mMutex;
325 
326     std::unordered_map<aidl::android::automotive::watchdog::TimeoutLength, ClientInfoMap>
327             mClientsByTimeout GUARDED_BY(mMutex);
328     std::unordered_map<aidl::android::automotive::watchdog::TimeoutLength, PingedClientMap>
329             mPingedClients GUARDED_BY(mMutex);
330     std::unordered_set<userid_t> mStoppedUserIds GUARDED_BY(mMutex);
331     std::shared_ptr<aidl::android::automotive::watchdog::internal::ICarWatchdogMonitor> mMonitor
332             GUARDED_BY(mMutex);
333     bool mIsEnabled GUARDED_BY(mMutex);
334     std::shared_ptr<android::frameworks::automotive::vhal::IVhalClient> mVhalService
335             GUARDED_BY(mMutex);
336     std::optional<aidl::android::automotive::watchdog::internal::ProcessIdentifier>
337             mVhalProcessIdentifier GUARDED_BY(mMutex);
338     int32_t mTotalVhalPidCachingAttempts GUARDED_BY(mMutex);
339     HeartBeat mVhalHeartBeat GUARDED_BY(mMutex);
340 
341     // For unit tests.
342     friend class internal::WatchdogProcessServicePeer;
343 };
344 
345 }  // namespace watchdog
346 }  // namespace automotive
347 }  // namespace android
348 
349 #endif  // CPP_WATCHDOG_SERVER_SRC_WATCHDOGPROCESSSERVICE_H_
350