1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_
6 #define BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_
7 
8 #include "base/base_export.h"
9 #include "base/gtest_prod_util.h"
10 #include "base/macros.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/process/process_metrics.h"
14 #include "base/timer/timer.h"
15 #include "base/trace_event/trace_log.h"
16 
17 namespace base {
18 
19 class SingleThreadTaskRunner;
20 
21 namespace trace_event {
22 
23 // Watches for chrome://tracing to be enabled or disabled. When tracing is
24 // enabled, also enables system events profiling. This class is the preferred
25 // way to turn system tracing on and off.
26 class BASE_EXPORT TraceEventSystemStatsMonitor
27     : public TraceLog::EnabledStateObserver {
28  public:
29   // Length of time interval between stat profiles.
30   static const int kSamplingIntervalMilliseconds = 2000;
31 
32   // |task_runner| must be the primary thread for the client
33   // process, e.g. the UI thread in a browser.
34   explicit TraceEventSystemStatsMonitor(
35       scoped_refptr<SingleThreadTaskRunner> task_runner);
36 
37   ~TraceEventSystemStatsMonitor() override;
38 
39   // base::trace_event::TraceLog::EnabledStateChangedObserver overrides:
40   void OnTraceLogEnabled() override;
41   void OnTraceLogDisabled() override;
42 
43   // Retrieves system profiling at the current time.
44   void DumpSystemStats();
45 
46  private:
47   FRIEND_TEST_ALL_PREFIXES(TraceSystemStatsMonitorTest,
48                            TraceEventSystemStatsMonitor);
49 
50   bool IsTimerRunningForTest() const;
51 
52   void StartProfiling();
53 
54   void StopProfiling();
55 
56   // Ensures the observer starts and stops tracing on the primary thread.
57   scoped_refptr<SingleThreadTaskRunner> task_runner_;
58 
59   // Timer to schedule system profile dumps.
60   RepeatingTimer dump_timer_;
61 
62   WeakPtrFactory<TraceEventSystemStatsMonitor> weak_factory_;
63 
64   DISALLOW_COPY_AND_ASSIGN(TraceEventSystemStatsMonitor);
65 };
66 
67 // Converts system memory profiling stats in |input| to
68 // trace event compatible JSON and appends to |output|. Visible for testing.
69 BASE_EXPORT void AppendSystemProfileAsTraceFormat(const SystemMetrics&
70                                                   system_stats,
71                                                   std::string* output);
72 
73 }  // namespace trace_event
74 }  // namespace base
75 
76 #endif  // BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_
77