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 #pragma once
18 
19 #include <aidl/android/automotive/watchdog/BnCarWatchdog.h>
20 #include <aidl/android/automotive/watchdog/BnCarWatchdogClient.h>
21 #include <utils/Looper.h>
22 #include <utils/Mutex.h>
23 #include <utils/String16.h>
24 
25 namespace aidl {
26 namespace android {
27 namespace automotive {
28 namespace watchdog {
29 
30 struct CommandParam {
31     std::string timeout;
32     int inactiveAfterInSec;
33     int terminateAfterInSec;
34     bool forcedKill;
35     bool verbose;
36 };
37 
38 struct HealthCheckSession {
39     HealthCheckSession(int32_t sessionId = -1,
40                        TimeoutLength sessionTimeout = TimeoutLength::TIMEOUT_NORMAL) :
idHealthCheckSession41           id(sessionId),
42           timeout(sessionTimeout) {}
43 
44     int32_t id;
45     TimeoutLength timeout;
46 };
47 
48 class WatchdogClient : public BnCarWatchdogClient {
49 public:
50     explicit WatchdogClient(const ::android::sp<::android::Looper>& handlerLooper);
51 
52     ndk::ScopedAStatus checkIfAlive(int32_t sessionId, TimeoutLength timeout) override;
53     ndk::ScopedAStatus prepareProcessTermination() override;
54 
55     bool initialize(const CommandParam& param);
56     void finalize();
57 
58 private:
59     class MessageHandlerImpl : public ::android::MessageHandler {
60     public:
61         explicit MessageHandlerImpl(WatchdogClient* client);
62         void handleMessage(const ::android::Message& message) override;
63 
64     private:
65         WatchdogClient* mClient;
66     };
67 
68 private:
69     void respondToWatchdog();
70     void becomeInactive();
71     void terminateProcess();
72     void registerClient(const std::string& timeout);
73     void unregisterClient();
74 
75 private:
76     ::android::sp<::android::Looper> mHandlerLooper;
77     ::android::sp<MessageHandlerImpl> mMessageHandler;
78     bool mForcedKill;
79     bool mVerbose;
80     ::android::Mutex mMutex;
81     std::shared_ptr<ICarWatchdog> mWatchdogServer GUARDED_BY(mMutex);
82     std::shared_ptr<ICarWatchdogClient> mTestClient GUARDED_BY(mMutex);
83     bool mIsClientActive GUARDED_BY(mMutex);
84     HealthCheckSession mSession GUARDED_BY(mMutex);
85 };
86 
87 }  // namespace watchdog
88 }  // namespace automotive
89 }  // namespace android
90 }  // namespace aidl
91