1 /*
2 * Copyright (C) 2018 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 INCLUDE_PERFETTO_EXT_BASE_WATCHDOG_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_WATCHDOG_H_
19
20 #include <functional>
21
22 #include "perfetto/base/build_config.h"
23
24 // The POSIX watchdog is only supported on Linux and Android in non-embedder
25 // builds.
26 #if PERFETTO_BUILDFLAG(PERFETTO_WATCHDOG)
27 #include "perfetto/ext/base/watchdog_posix.h"
28 #else
29 #include "perfetto/ext/base/watchdog_noop.h"
30 #endif
31
32 namespace perfetto {
33 namespace base {
34
35 // Used only to add more details to crash reporting.
36 enum class WatchdogCrashReason {
37 kUnspecified = 0,
38 kCpuGuardrail = 1,
39 kMemGuardrail = 2,
40 kTaskRunnerHung = 3,
41 kTraceDidntStop = 4,
42 };
43
44 // Make the limits more relaxed on desktop, where multi-GB traces are likely.
45 // Multi-GB traces can take bursts of cpu time to write into disk at the end of
46 // the trace.
47 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
48 constexpr uint32_t kWatchdogDefaultCpuLimit = 75;
49 constexpr uint32_t kWatchdogDefaultCpuWindow = 5 * 60 * 1000; // 5 minutes.
50 #else
51 constexpr uint32_t kWatchdogDefaultCpuLimit = 90;
52 constexpr uint32_t kWatchdogDefaultCpuWindow = 10 * 60 * 1000; // 10 minutes.
53 #endif
54
55 // The default memory margin we give to our processes. This is used as as a
56 // constant to put on top of the trace buffers.
57 constexpr uint64_t kWatchdogDefaultMemorySlack = 32 * 1024 * 1024; // 32 MiB.
58 constexpr uint32_t kWatchdogDefaultMemoryWindow = 30 * 1000; // 30 seconds.
59
RunTaskWithWatchdogGuard(const std::function<void ()> & task)60 inline void RunTaskWithWatchdogGuard(const std::function<void()>& task) {
61 // Maximum time a single task can take in a TaskRunner before the
62 // program suicides.
63 constexpr int64_t kWatchdogMillis = 30000; // 30s
64
65 Watchdog::Timer handle = base::Watchdog::GetInstance()->CreateFatalTimer(
66 kWatchdogMillis, WatchdogCrashReason::kTaskRunnerHung);
67 task();
68
69 // Suppress unused variable warnings in the client library amalgamated build.
70 (void)kWatchdogDefaultCpuLimit;
71 (void)kWatchdogDefaultCpuWindow;
72 (void)kWatchdogDefaultMemorySlack;
73 (void)kWatchdogDefaultMemoryWindow;
74 }
75
76 } // namespace base
77 } // namespace perfetto
78
79 #endif // INCLUDE_PERFETTO_EXT_BASE_WATCHDOG_H_
80