blob: 6131d440b94524ad3088f43c50594be168ac8062 [file] [log] [blame]
Isabelle Taylord404ea12018-02-19 17:28:01 +00001/*
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#include "src/traced/probes/probes_producer.h"
18
19#include <stdio.h>
Anna Zappone4ea73c02018-03-09 16:01:21 +000020#include <sys/stat.h>
Primiano Tucci52526602018-03-29 22:53:10 +010021
22#include <algorithm>
Anna Zappone27ac99c2018-03-06 14:25:35 +000023#include <queue>
Isabelle Taylord404ea12018-02-19 17:28:01 +000024#include <string>
25
26#include "perfetto/base/logging.h"
Hector Dearman0ff07c72018-03-15 09:54:46 +000027#include "perfetto/base/weak_ptr.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000028#include "perfetto/traced/traced.h"
29#include "perfetto/tracing/core/data_source_config.h"
30#include "perfetto/tracing/core/data_source_descriptor.h"
Hector Dearmana89cc572018-02-23 12:02:58 +000031#include "perfetto/tracing/core/ftrace_config.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000032#include "perfetto/tracing/core/trace_config.h"
33#include "perfetto/tracing/core/trace_packet.h"
Anna Zappone2a6f9042018-03-14 13:26:07 +000034#include "src/traced/probes/filesystem/inode_file_data_source.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000035
Anna Zappone27ac99c2018-03-06 14:25:35 +000036#include "perfetto/trace/filesystem/inode_file_map.pbzero.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000037#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000038#include "perfetto/trace/trace_packet.pbzero.h"
39
40namespace perfetto {
41namespace {
42
Primiano Tucci3cbb10a2018-04-10 17:52:40 +010043constexpr uint32_t kInitialConnectionBackoffMs = 100;
44constexpr uint32_t kMaxConnectionBackoffMs = 30 * 1000;
Primiano Tucci578d7842018-03-29 15:27:05 +010045constexpr char kFtraceSourceName[] = "linux.ftrace";
46constexpr char kProcessStatsSourceName[] = "linux.process_stats";
47constexpr char kInodeMapSourceName[] = "linux.inode_file_map";
Isabelle Taylord404ea12018-02-19 17:28:01 +000048
49} // namespace.
50
51// State transition diagram:
52// +----------------------------+
53// v +
54// NotStarted -> NotConnected -> Connecting -> Connected
55// ^ +
56// +--------------+
57//
58
Hector Dearmanc8488032018-03-02 13:12:01 +000059ProbesProducer::ProbesProducer() {}
Isabelle Taylord404ea12018-02-19 17:28:01 +000060ProbesProducer::~ProbesProducer() = default;
61
62void ProbesProducer::OnConnect() {
63 PERFETTO_DCHECK(state_ == kConnecting);
64 state_ = kConnected;
65 ResetConnectionBackoff();
66 PERFETTO_LOG("Connected to the service");
67
68 DataSourceDescriptor ftrace_descriptor;
69 ftrace_descriptor.set_name(kFtraceSourceName);
Primiano Tucci9daa4832018-03-28 23:28:17 +010070 endpoint_->RegisterDataSource(ftrace_descriptor);
Isabelle Taylord404ea12018-02-19 17:28:01 +000071
72 DataSourceDescriptor process_stats_descriptor;
73 process_stats_descriptor.set_name(kProcessStatsSourceName);
Primiano Tucci9daa4832018-03-28 23:28:17 +010074 endpoint_->RegisterDataSource(process_stats_descriptor);
Anna Zappone27ac99c2018-03-06 14:25:35 +000075
76 DataSourceDescriptor inode_map_descriptor;
Hector Dearman0ff07c72018-03-15 09:54:46 +000077 inode_map_descriptor.set_name(kInodeMapSourceName);
Primiano Tucci9daa4832018-03-28 23:28:17 +010078 endpoint_->RegisterDataSource(inode_map_descriptor);
Isabelle Taylord404ea12018-02-19 17:28:01 +000079}
80
81void ProbesProducer::OnDisconnect() {
82 PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
Isabelle Taylord404ea12018-02-19 17:28:01 +000083 PERFETTO_LOG("Disconnected from tracing service");
Primiano Tuccie56411c2018-03-30 01:15:02 +010084 if (state_ == kConnected)
85 return task_runner_->PostTask([this] { this->Restart(); });
Isabelle Taylord404ea12018-02-19 17:28:01 +000086
Primiano Tuccie56411c2018-03-30 01:15:02 +010087 state_ = kNotConnected;
88 IncreaseConnectionBackoff();
Isabelle Taylord404ea12018-02-19 17:28:01 +000089 task_runner_->PostDelayedTask([this] { this->Connect(); },
90 connection_backoff_ms_);
91}
92
Primiano Tuccie56411c2018-03-30 01:15:02 +010093void ProbesProducer::Restart() {
94 // We lost the connection with the tracing service. At this point we need
95 // to reset all the data sources. Trying to handle that manually is going to
96 // be error prone. What we do here is simply desroying the instance and
97 // recreating it again.
98 // TODO(hjd): Add e2e test for this.
99
100 base::TaskRunner* task_runner = task_runner_;
101 const char* socket_name = socket_name_;
102
103 // Invoke destructor and then the constructor again.
104 this->~ProbesProducer();
105 new (this) ProbesProducer();
106
107 ConnectWithRetries(socket_name, task_runner);
108}
109
Hector Dearman0ff07c72018-03-15 09:54:46 +0000110void ProbesProducer::CreateDataSourceInstance(DataSourceInstanceID instance_id,
111 const DataSourceConfig& config) {
112 // TODO(hjd): This a hack since we don't actually know the session id. For
113 // now we'll assume anything wit hthe same target buffer is in the same
114 // session.
115 TracingSessionID session_id = config.target_buffer();
116
117 if (config.name() == kFtraceSourceName) {
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100118 if (!CreateFtraceDataSourceInstance(session_id, instance_id, config))
119 failed_sources_.insert(instance_id);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000120 } else if (config.name() == kInodeMapSourceName) {
121 CreateInodeFileDataSourceInstance(session_id, instance_id, config);
122 } else if (config.name() == kProcessStatsSourceName) {
123 CreateProcessStatsDataSourceInstance(session_id, instance_id, config);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000124 } else {
125 PERFETTO_ELOG("Data source name: %s not recognised.",
Hector Dearman0ff07c72018-03-15 09:54:46 +0000126 config.name().c_str());
127 return;
128 }
129
130 std::map<TracingSessionID, InodeFileDataSource*> file_sources;
131 std::map<TracingSessionID, ProcessStatsDataSource*> ps_sources;
132 for (const auto& pair : file_map_sources_)
133 file_sources[pair.second->session_id()] = pair.second.get();
134 for (const auto& pair : process_stats_sources_)
135 ps_sources[pair.second->session_id()] = pair.second.get();
136
137 for (const auto& id_to_source : delegates_) {
138 const std::unique_ptr<SinkDelegate>& source = id_to_source.second;
139 if (session_id != source->session_id())
140 continue;
141 if (!source->ps_source() && ps_sources.count(session_id))
142 source->set_ps_source(ps_sources[session_id]->GetWeakPtr());
143 if (!source->file_source() && file_sources.count(session_id))
144 source->set_file_source(file_sources[session_id]->GetWeakPtr());
Isabelle Taylord404ea12018-02-19 17:28:01 +0000145 }
146}
147
Anna Zappone27ac99c2018-03-06 14:25:35 +0000148void ProbesProducer::AddWatchdogsTimer(DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000149 const DataSourceConfig& config) {
150 if (config.trace_duration_ms() != 0)
Anna Zappone27ac99c2018-03-06 14:25:35 +0000151 watchdogs_.emplace(id, base::Watchdog::GetInstance()->CreateFatalTimer(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000152 5000 + 2 * config.trace_duration_ms()));
Anna Zappone27ac99c2018-03-06 14:25:35 +0000153}
154
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100155bool ProbesProducer::CreateFtraceDataSourceInstance(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000156 TracingSessionID session_id,
Isabelle Taylord404ea12018-02-19 17:28:01 +0000157 DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000158 const DataSourceConfig& config) {
Isabelle Taylord404ea12018-02-19 17:28:01 +0000159 // Don't retry if FtraceController::Create() failed once.
160 // This can legitimately happen on user builds where we cannot access the
161 // debug paths, e.g., because of SELinux rules.
162 if (ftrace_creation_failed_)
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100163 return false;
Isabelle Taylord404ea12018-02-19 17:28:01 +0000164
165 // Lazily create on the first instance.
166 if (!ftrace_) {
167 ftrace_ = FtraceController::Create(task_runner_);
168
169 if (!ftrace_) {
170 PERFETTO_ELOG("Failed to create FtraceController");
171 ftrace_creation_failed_ = true;
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100172 return false;
Isabelle Taylord404ea12018-02-19 17:28:01 +0000173 }
174
175 ftrace_->DisableAllEvents();
176 ftrace_->ClearTrace();
177 }
178
179 PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000180 config.target_buffer());
Isabelle Taylord404ea12018-02-19 17:28:01 +0000181
Hector Dearman0ff07c72018-03-15 09:54:46 +0000182 FtraceConfig proto_config = config.ftrace_config();
Isabelle Taylord404ea12018-02-19 17:28:01 +0000183
184 // TODO(hjd): Static cast is bad, target_buffer() should return a BufferID.
185 auto trace_writer = endpoint_->CreateTraceWriter(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000186 static_cast<BufferID>(config.target_buffer()));
Hector Dearmanc8488032018-03-02 13:12:01 +0000187 auto delegate = std::unique_ptr<SinkDelegate>(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000188 new SinkDelegate(session_id, task_runner_, std::move(trace_writer)));
Isabelle Taylord404ea12018-02-19 17:28:01 +0000189 auto sink = ftrace_->CreateSink(std::move(proto_config), delegate.get());
Hector Dearmanee3c49d2018-02-28 14:10:22 +0000190 if (!sink) {
191 PERFETTO_ELOG("Failed to start tracing (maybe someone else is using it?)");
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100192 return false;
Hector Dearmanee3c49d2018-02-28 14:10:22 +0000193 }
Hector Dearman210dc6f2018-03-12 10:51:07 +0000194 delegate->set_sink(std::move(sink));
Isabelle Taylord404ea12018-02-19 17:28:01 +0000195 delegates_.emplace(id, std::move(delegate));
Hector Dearman0ff07c72018-03-15 09:54:46 +0000196 AddWatchdogsTimer(id, config);
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100197 return true;
Anna Zappone27ac99c2018-03-06 14:25:35 +0000198}
199
Anna Zappone2a6f9042018-03-14 13:26:07 +0000200void ProbesProducer::CreateInodeFileDataSourceInstance(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000201 TracingSessionID session_id,
Anna Zappone27ac99c2018-03-06 14:25:35 +0000202 DataSourceInstanceID id,
Primiano Tuccidae35652018-03-29 18:32:02 +0100203 DataSourceConfig source_config) {
Anna Zappone27ac99c2018-03-06 14:25:35 +0000204 PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
205 id, source_config.target_buffer());
206 auto trace_writer = endpoint_->CreateTraceWriter(
207 static_cast<BufferID>(source_config.target_buffer()));
Anna Zappone2a6f9042018-03-14 13:26:07 +0000208 if (system_inodes_.empty())
Hector Dearman7fabd702018-03-28 12:37:15 +0100209 CreateStaticDeviceToInodeMap("/system", &system_inodes_);
Primiano Tuccidae35652018-03-29 18:32:02 +0100210 auto file_map_source =
211 std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
212 std::move(source_config), task_runner_, session_id, &system_inodes_,
213 &cache_, std::move(trace_writer)));
Anna Zappone27ac99c2018-03-06 14:25:35 +0000214 file_map_sources_.emplace(id, std::move(file_map_source));
215 AddWatchdogsTimer(id, source_config);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000216}
217
218void ProbesProducer::CreateProcessStatsDataSourceInstance(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000219 TracingSessionID session_id,
Hector Dearman77451692018-03-08 16:21:13 +0000220 DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000221 const DataSourceConfig& config) {
Hector Dearman77451692018-03-08 16:21:13 +0000222 PERFETTO_DCHECK(process_stats_sources_.count(id) == 0);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000223 auto trace_writer = endpoint_->CreateTraceWriter(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000224 static_cast<BufferID>(config.target_buffer()));
Hector Dearmanebf07c72018-03-13 10:31:05 +0000225 auto source = std::unique_ptr<ProcessStatsDataSource>(
Isabelle Taylor2c31b802018-04-04 14:55:58 +0100226 new ProcessStatsDataSource(session_id, std::move(trace_writer), config));
Hector Dearmanebf07c72018-03-13 10:31:05 +0000227 auto it_and_inserted = process_stats_sources_.emplace(id, std::move(source));
228 PERFETTO_DCHECK(it_and_inserted.second);
Isabelle Taylor2c31b802018-04-04 14:55:58 +0100229 const auto& quirks =
230 it_and_inserted.first->second->config().process_stats_config().quirks();
231 if (std::find(quirks.begin(), quirks.end(),
232 ProcessStatsConfig::DISABLE_INITIAL_DUMP) != quirks.end()) {
Hector Dearman1b9c58a2018-03-29 18:45:06 +0100233 PERFETTO_DLOG("Initial process tree dump is disabled.");
234 return;
235 }
Hector Dearmanebf07c72018-03-13 10:31:05 +0000236 it_and_inserted.first->second->WriteAllProcesses();
Isabelle Taylord404ea12018-02-19 17:28:01 +0000237}
238
239void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
240 PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
Hector Dearman77451692018-03-08 16:21:13 +0000241 // |id| could be the id of any of the datasources we handle:
Hector Dearmanaa69aff2018-03-26 19:49:23 +0100242 PERFETTO_DCHECK((failed_sources_.count(id) + delegates_.count(id) +
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100243 process_stats_sources_.count(id) +
Hector Dearman77451692018-03-08 16:21:13 +0000244 file_map_sources_.count(id)) == 1);
Hector Dearmanbcb56fb2018-03-26 13:59:24 +0100245 failed_sources_.erase(id);
Hector Dearman77451692018-03-08 16:21:13 +0000246 delegates_.erase(id);
247 process_stats_sources_.erase(id);
248 file_map_sources_.erase(id);
249 watchdogs_.erase(id);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000250}
251
Primiano Tuccidca727d2018-04-04 11:31:55 +0200252void ProbesProducer::OnTracingSetup() {}
Isabelle Taylor69faa902018-03-21 15:42:03 +0000253
Primiano Tuccid52e6272018-04-06 19:06:53 +0200254void ProbesProducer::Flush(FlushRequestID flush_request_id,
255 const DataSourceInstanceID* data_source_ids,
256 size_t num_data_sources) {
257 for (size_t i = 0; i < num_data_sources; i++) {
258 DataSourceInstanceID ds_id = data_source_ids[i];
259 {
260 auto it = process_stats_sources_.find(ds_id);
261 if (it != process_stats_sources_.end())
262 it->second->Flush();
263 }
264 {
265 auto it = file_map_sources_.find(ds_id);
266 if (it != file_map_sources_.end())
267 it->second->Flush();
268 }
269 {
270 auto it = delegates_.find(ds_id);
271 if (it != delegates_.end())
272 it->second->Flush();
273 }
274 }
275 endpoint_->NotifyFlushComplete(flush_request_id);
276}
277
Isabelle Taylord404ea12018-02-19 17:28:01 +0000278void ProbesProducer::ConnectWithRetries(const char* socket_name,
279 base::TaskRunner* task_runner) {
280 PERFETTO_DCHECK(state_ == kNotStarted);
281 state_ = kNotConnected;
282
283 ResetConnectionBackoff();
284 socket_name_ = socket_name;
285 task_runner_ = task_runner;
286 Connect();
287}
288
289void ProbesProducer::Connect() {
290 PERFETTO_DCHECK(state_ == kNotConnected);
291 state_ = kConnecting;
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100292 endpoint_ = ProducerIPCClient::Connect(
Primiano Tucci578d7842018-03-29 15:27:05 +0100293 socket_name_, this, "perfetto.traced_probes", task_runner_);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000294}
295
296void ProbesProducer::IncreaseConnectionBackoff() {
297 connection_backoff_ms_ *= 2;
298 if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
299 connection_backoff_ms_ = kMaxConnectionBackoffMs;
300}
301
302void ProbesProducer::ResetConnectionBackoff() {
303 connection_backoff_ms_ = kInitialConnectionBackoffMs;
304}
305
Hector Dearman0ff07c72018-03-15 09:54:46 +0000306ProbesProducer::SinkDelegate::SinkDelegate(TracingSessionID id,
307 base::TaskRunner* task_runner,
Hector Dearmanc8488032018-03-02 13:12:01 +0000308 std::unique_ptr<TraceWriter> writer)
Hector Dearman0ff07c72018-03-15 09:54:46 +0000309 : session_id_(id),
310 task_runner_(task_runner),
Hector Dearmanc8488032018-03-02 13:12:01 +0000311 writer_(std::move(writer)),
312 weak_factory_(this) {}
Isabelle Taylord404ea12018-02-19 17:28:01 +0000313
314ProbesProducer::SinkDelegate::~SinkDelegate() = default;
315
Primiano Tuccid52e6272018-04-06 19:06:53 +0200316void ProbesProducer::SinkDelegate::Flush() {
317 // TODO(primiano): this still doesn't flush data from the kernel ftrace
318 // buffers (see b/73886018). We should do that and delay the
319 // NotifyFlushComplete() until the ftrace data has been drained from the
320 // kernel ftrace buffer and written in the SMB.
321 if (writer_ && (!trace_packet_ || trace_packet_->is_finalized()))
322 writer_->Flush();
323}
324
Isabelle Taylord404ea12018-02-19 17:28:01 +0000325ProbesProducer::FtraceBundleHandle
326ProbesProducer::SinkDelegate::GetBundleForCpu(size_t) {
327 trace_packet_ = writer_->NewTracePacket();
328 return FtraceBundleHandle(trace_packet_->set_ftrace_events());
329}
330
Hector Dearmanc8488032018-03-02 13:12:01 +0000331void ProbesProducer::SinkDelegate::OnBundleComplete(
332 size_t,
333 FtraceBundleHandle,
334 const FtraceMetadata& metadata) {
Isabelle Taylord404ea12018-02-19 17:28:01 +0000335 trace_packet_->Finalize();
Hector Dearman0ff07c72018-03-15 09:54:46 +0000336
Anna Zappone8ce30872018-03-19 17:01:15 +0000337 if (file_source_ && !metadata.inode_and_device.empty()) {
338 auto inodes = metadata.inode_and_device;
Hector Dearman0ff07c72018-03-15 09:54:46 +0000339 auto weak_file_source = file_source_;
340 task_runner_->PostTask([weak_file_source, inodes] {
341 if (weak_file_source)
342 weak_file_source->OnInodes(inodes);
Hector Dearmanc8488032018-03-02 13:12:01 +0000343 });
344 }
Isabelle Taylor2c31b802018-04-04 14:55:58 +0100345 if (ps_source_ && !metadata.pids.empty()) {
346 const auto& quirks = ps_source_->config().process_stats_config().quirks();
347 if (std::find(quirks.begin(), quirks.end(),
348 ProcessStatsConfig::DISABLE_ON_DEMAND) != quirks.end()) {
349 return;
350 }
351 const auto& pids = metadata.pids;
352 auto weak_ps_source = ps_source_;
353 task_runner_->PostTask([weak_ps_source, pids] {
354 if (weak_ps_source)
355 weak_ps_source->OnPids(pids);
356 });
357 }
Hector Dearmanc8488032018-03-02 13:12:01 +0000358}
359
Isabelle Taylord404ea12018-02-19 17:28:01 +0000360} // namespace perfetto