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 #include "watchdog.h"
18
19 #include <chrono>
20 #include <functional>
21
22 #include <systemd/sd-daemon.h>
23
24 namespace android::automotive::agl::utils {
25
SystemdWatchdog()26 SystemdWatchdog::SystemdWatchdog() : mThread(std::bind(&SystemdWatchdog::WatchdogThread, this)) {}
27
WatchdogThread()28 void SystemdWatchdog::WatchdogThread() {
29 uint64_t usec = 0;
30 int r = sd_watchdog_enabled(0, &usec);
31 if (r < 0) {
32 fprintf(stderr, "watchdog error: %d\n", r);
33 return;
34 }
35 // function returned, but watchdog not applicable
36 if (r == 0) return;
37 if (usec == 0) {
38 fprintf(stderr, "watchdog interval of 0 does not make sense!\n");
39 return;
40 }
41
42 usec = (2 * usec) / 3; // give us breathing room here
43 if (usec == 0) usec = 1;
44
45 sd_notify(0, "READY=1");
46
47 std::chrono::duration<uint64_t, std::micro> mInterval{usec};
48 while (true) {
49 std::this_thread::sleep_for(mInterval);
50 if (IsHealthy())
51 sd_notify(0, "WATCHDOG=1");
52 else
53 sd_notify(0, "WATCHDOG=trigger");
54 }
55 }
56
57 } // namespace android::automotive::agl::utils
58