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 #include "base/trace_event/trace_event_system_stats_monitor.h"
6
7 #include <memory>
8
9 #include "base/debug/leak_annotations.h"
10 #include "base/json/json_writer.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/macros.h"
14 #include "base/process/process_metrics.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/threading/thread_local_storage.h"
18 #include "base/threading/thread_task_runner_handle.h"
19 #include "base/trace_event/trace_event.h"
20
21 namespace base {
22 namespace trace_event {
23
24 namespace {
25
26 /////////////////////////////////////////////////////////////////////////////
27 // Holds profiled system stats until the tracing system needs to serialize it.
28 class SystemStatsHolder : public base::trace_event::ConvertableToTraceFormat {
29 public:
30 SystemStatsHolder() = default;
31 ~SystemStatsHolder() override = default;
32
33 // Fills system_metrics_ with profiled system memory and disk stats.
34 // Uses the previous stats to compute rates if this is not the first profile.
35 void GetSystemProfilingStats();
36
37 // base::trace_event::ConvertableToTraceFormat overrides:
AppendAsTraceFormat(std::string * out) const38 void AppendAsTraceFormat(std::string* out) const override {
39 AppendSystemProfileAsTraceFormat(system_stats_, out);
40 }
41
42 private:
43 SystemMetrics system_stats_;
44
45 DISALLOW_COPY_AND_ASSIGN(SystemStatsHolder);
46 };
47
GetSystemProfilingStats()48 void SystemStatsHolder::GetSystemProfilingStats() {
49 system_stats_ = SystemMetrics::Sample();
50 }
51
52 } // namespace
53
54 //////////////////////////////////////////////////////////////////////////////
55
TraceEventSystemStatsMonitor(scoped_refptr<SingleThreadTaskRunner> task_runner)56 TraceEventSystemStatsMonitor::TraceEventSystemStatsMonitor(
57 scoped_refptr<SingleThreadTaskRunner> task_runner)
58 : task_runner_(task_runner),
59 weak_factory_(this) {
60 // Force the "system_stats" category to show up in the trace viewer.
61 TraceLog::GetCategoryGroupEnabled(TRACE_DISABLED_BY_DEFAULT("system_stats"));
62
63 // Allow this to be instantiated on unsupported platforms, but don't run.
64 TraceLog::GetInstance()->AddEnabledStateObserver(this);
65 }
66
~TraceEventSystemStatsMonitor()67 TraceEventSystemStatsMonitor::~TraceEventSystemStatsMonitor() {
68 if (dump_timer_.IsRunning())
69 StopProfiling();
70 TraceLog::GetInstance()->RemoveEnabledStateObserver(this);
71 }
72
OnTraceLogEnabled()73 void TraceEventSystemStatsMonitor::OnTraceLogEnabled() {
74 // Check to see if system tracing is enabled.
75 bool enabled;
76
77 TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT(
78 "system_stats"), &enabled);
79 if (!enabled)
80 return;
81 task_runner_->PostTask(
82 FROM_HERE, base::BindOnce(&TraceEventSystemStatsMonitor::StartProfiling,
83 weak_factory_.GetWeakPtr()));
84 }
85
OnTraceLogDisabled()86 void TraceEventSystemStatsMonitor::OnTraceLogDisabled() {
87 task_runner_->PostTask(
88 FROM_HERE, base::BindOnce(&TraceEventSystemStatsMonitor::StopProfiling,
89 weak_factory_.GetWeakPtr()));
90 }
91
StartProfiling()92 void TraceEventSystemStatsMonitor::StartProfiling() {
93 // Watch for the tracing framework sending enabling more than once.
94 if (dump_timer_.IsRunning())
95 return;
96
97 dump_timer_.Start(FROM_HERE,
98 TimeDelta::FromMilliseconds(TraceEventSystemStatsMonitor::
99 kSamplingIntervalMilliseconds),
100 base::Bind(&TraceEventSystemStatsMonitor::
101 DumpSystemStats,
102 weak_factory_.GetWeakPtr()));
103 }
104
105 // If system tracing is enabled, dumps a profile to the tracing system.
DumpSystemStats()106 void TraceEventSystemStatsMonitor::DumpSystemStats() {
107 std::unique_ptr<SystemStatsHolder> dump_holder(new SystemStatsHolder());
108 dump_holder->GetSystemProfilingStats();
109
110 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
111 TRACE_DISABLED_BY_DEFAULT("system_stats"),
112 "base::TraceEventSystemStatsMonitor::SystemStats", this,
113 std::move(dump_holder));
114 }
115
StopProfiling()116 void TraceEventSystemStatsMonitor::StopProfiling() {
117 dump_timer_.Stop();
118 }
119
IsTimerRunningForTest() const120 bool TraceEventSystemStatsMonitor::IsTimerRunningForTest() const {
121 return dump_timer_.IsRunning();
122 }
123
AppendSystemProfileAsTraceFormat(const SystemMetrics & system_metrics,std::string * output)124 void AppendSystemProfileAsTraceFormat(const SystemMetrics& system_metrics,
125 std::string* output) {
126 std::string tmp;
127 base::JSONWriter::Write(*system_metrics.ToValue(), &tmp);
128 *output += tmp;
129 }
130
131 } // namespace trace_event
132 } // namespace base
133