summaryrefslogtreecommitdiff
path: root/base/trace_event/trace_event_system_stats_monitor.h
blob: 14aa5681fe46e0c484d33fafbdc50a81d693bc8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_
#define BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_

#include "base/base_export.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/process/process_metrics.h"
#include "base/timer/timer.h"
#include "base/trace_event/trace_log.h"

namespace base {

class SingleThreadTaskRunner;

namespace trace_event {

// Watches for chrome://tracing to be enabled or disabled. When tracing is
// enabled, also enables system events profiling. This class is the preferred
// way to turn system tracing on and off.
class BASE_EXPORT TraceEventSystemStatsMonitor
    : public TraceLog::EnabledStateObserver {
 public:
  // Length of time interval between stat profiles.
  static const int kSamplingIntervalMilliseconds = 2000;

  // |task_runner| must be the primary thread for the client
  // process, e.g. the UI thread in a browser.
  explicit TraceEventSystemStatsMonitor(
      scoped_refptr<SingleThreadTaskRunner> task_runner);

  ~TraceEventSystemStatsMonitor() override;

  // base::trace_event::TraceLog::EnabledStateChangedObserver overrides:
  void OnTraceLogEnabled() override;
  void OnTraceLogDisabled() override;

  // Retrieves system profiling at the current time.
  void DumpSystemStats();

 private:
  FRIEND_TEST_ALL_PREFIXES(TraceSystemStatsMonitorTest,
                           TraceEventSystemStatsMonitor);

  bool IsTimerRunningForTest() const;

  void StartProfiling();

  void StopProfiling();

  // Ensures the observer starts and stops tracing on the primary thread.
  scoped_refptr<SingleThreadTaskRunner> task_runner_;

  // Timer to schedule system profile dumps.
  RepeatingTimer dump_timer_;

  WeakPtrFactory<TraceEventSystemStatsMonitor> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(TraceEventSystemStatsMonitor);
};

// Converts system memory profiling stats in |input| to
// trace event compatible JSON and appends to |output|. Visible for testing.
BASE_EXPORT void AppendSystemProfileAsTraceFormat(const SystemMetrics&
                                                  system_stats,
                                                  std::string* output);

}  // namespace trace_event
}  // namespace base

#endif  // BASE_TRACE_EVENT_TRACE_EVENT_SYSTEM_STATS_MONITOR_H_