blob: e56eb7345dea04837623bd6f7e4841b7c408196c [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"
Primiano Tuccifd8240d2018-08-01 09:34:54 +010027#include "perfetto/base/utils.h"
Hector Dearman0ff07c72018-03-15 09:54:46 +000028#include "perfetto/base/weak_ptr.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000029#include "perfetto/traced/traced.h"
30#include "perfetto/tracing/core/data_source_config.h"
31#include "perfetto/tracing/core/data_source_descriptor.h"
Hector Dearmana89cc572018-02-23 12:02:58 +000032#include "perfetto/tracing/core/ftrace_config.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000033#include "perfetto/tracing/core/trace_config.h"
34#include "perfetto/tracing/core/trace_packet.h"
Primiano Tuccic2eb5102018-05-15 10:40:01 +010035#include "perfetto/tracing/ipc/producer_ipc_client.h"
Anna Zappone2a6f9042018-03-14 13:26:07 +000036#include "src/traced/probes/filesystem/inode_file_data_source.h"
Primiano Tuccifd8240d2018-08-01 09:34:54 +010037#include "src/traced/probes/ftrace/ftrace_data_source.h"
38#include "src/traced/probes/probes_data_source.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000039
Anna Zappone27ac99c2018-03-06 14:25:35 +000040#include "perfetto/trace/filesystem/inode_file_map.pbzero.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000041#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
Hector Dearman3afb1e02018-04-27 16:46:52 +010042#include "perfetto/trace/ftrace/ftrace_stats.pbzero.h"
Isabelle Taylord404ea12018-02-19 17:28:01 +000043#include "perfetto/trace/trace_packet.pbzero.h"
44
45namespace perfetto {
46namespace {
47
Primiano Tucci3cbb10a2018-04-10 17:52:40 +010048constexpr uint32_t kInitialConnectionBackoffMs = 100;
49constexpr uint32_t kMaxConnectionBackoffMs = 30 * 1000;
Primiano Tucci578d7842018-03-29 15:27:05 +010050constexpr char kFtraceSourceName[] = "linux.ftrace";
51constexpr char kProcessStatsSourceName[] = "linux.process_stats";
52constexpr char kInodeMapSourceName[] = "linux.inode_file_map";
Isabelle Taylord404ea12018-02-19 17:28:01 +000053
54} // namespace.
55
56// State transition diagram:
57// +----------------------------+
58// v +
59// NotStarted -> NotConnected -> Connecting -> Connected
60// ^ +
61// +--------------+
62//
63
Primiano Tuccifd8240d2018-08-01 09:34:54 +010064ProbesProducer::ProbesProducer() : weak_factory_(this) {}
65ProbesProducer::~ProbesProducer() {
66 // The ftrace data sources must be deleted before the ftrace controller.
67 data_sources_.clear();
68 ftrace_.reset();
69}
Isabelle Taylord404ea12018-02-19 17:28:01 +000070
71void ProbesProducer::OnConnect() {
72 PERFETTO_DCHECK(state_ == kConnecting);
73 state_ = kConnected;
74 ResetConnectionBackoff();
75 PERFETTO_LOG("Connected to the service");
76
77 DataSourceDescriptor ftrace_descriptor;
78 ftrace_descriptor.set_name(kFtraceSourceName);
Primiano Tucci9daa4832018-03-28 23:28:17 +010079 endpoint_->RegisterDataSource(ftrace_descriptor);
Isabelle Taylord404ea12018-02-19 17:28:01 +000080
81 DataSourceDescriptor process_stats_descriptor;
82 process_stats_descriptor.set_name(kProcessStatsSourceName);
Primiano Tucci9daa4832018-03-28 23:28:17 +010083 endpoint_->RegisterDataSource(process_stats_descriptor);
Anna Zappone27ac99c2018-03-06 14:25:35 +000084
85 DataSourceDescriptor inode_map_descriptor;
Hector Dearman0ff07c72018-03-15 09:54:46 +000086 inode_map_descriptor.set_name(kInodeMapSourceName);
Primiano Tucci9daa4832018-03-28 23:28:17 +010087 endpoint_->RegisterDataSource(inode_map_descriptor);
Isabelle Taylord404ea12018-02-19 17:28:01 +000088}
89
90void ProbesProducer::OnDisconnect() {
91 PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
Isabelle Taylord404ea12018-02-19 17:28:01 +000092 PERFETTO_LOG("Disconnected from tracing service");
Primiano Tuccie56411c2018-03-30 01:15:02 +010093 if (state_ == kConnected)
94 return task_runner_->PostTask([this] { this->Restart(); });
Isabelle Taylord404ea12018-02-19 17:28:01 +000095
Primiano Tuccie56411c2018-03-30 01:15:02 +010096 state_ = kNotConnected;
97 IncreaseConnectionBackoff();
Isabelle Taylord404ea12018-02-19 17:28:01 +000098 task_runner_->PostDelayedTask([this] { this->Connect(); },
99 connection_backoff_ms_);
100}
101
Primiano Tuccie56411c2018-03-30 01:15:02 +0100102void ProbesProducer::Restart() {
103 // We lost the connection with the tracing service. At this point we need
104 // to reset all the data sources. Trying to handle that manually is going to
105 // be error prone. What we do here is simply desroying the instance and
106 // recreating it again.
107 // TODO(hjd): Add e2e test for this.
108
109 base::TaskRunner* task_runner = task_runner_;
110 const char* socket_name = socket_name_;
111
112 // Invoke destructor and then the constructor again.
113 this->~ProbesProducer();
114 new (this) ProbesProducer();
115
116 ConnectWithRetries(socket_name, task_runner);
117}
118
Hector Dearman0ff07c72018-03-15 09:54:46 +0000119void ProbesProducer::CreateDataSourceInstance(DataSourceInstanceID instance_id,
120 const DataSourceConfig& config) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100121 PERFETTO_DCHECK(data_sources_.count(instance_id) == 0);
Primiano Tucci03de28f2018-08-01 11:29:46 +0100122 TracingSessionID session_id = config.tracing_session_id();
123 PERFETTO_CHECK(session_id > 0);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000124
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100125 std::unique_ptr<ProbesDataSource> data_source;
Hector Dearman0ff07c72018-03-15 09:54:46 +0000126 if (config.name() == kFtraceSourceName) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100127 data_source = CreateFtraceDataSource(session_id, instance_id, config);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000128 } else if (config.name() == kInodeMapSourceName) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100129 data_source = CreateInodeFileDataSource(session_id, instance_id, config);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000130 } else if (config.name() == kProcessStatsSourceName) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100131 data_source = CreateProcessStatsDataSource(session_id, instance_id, config);
132 }
133
134 if (!data_source) {
135 PERFETTO_ELOG("Failed to create data source '%s'", config.name().c_str());
Hector Dearman0ff07c72018-03-15 09:54:46 +0000136 return;
137 }
138
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100139 session_data_sources_.emplace(session_id, data_source.get());
140 data_sources_[instance_id] = std::move(data_source);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000141
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100142 if (config.trace_duration_ms() != 0) {
143 uint32_t timeout = 5000 + 2 * config.trace_duration_ms();
144 watchdogs_.emplace(
145 instance_id, base::Watchdog::GetInstance()->CreateFatalTimer(timeout));
Isabelle Taylord404ea12018-02-19 17:28:01 +0000146 }
147}
148
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100149std::unique_ptr<ProbesDataSource> ProbesProducer::CreateFtraceDataSource(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000150 TracingSessionID session_id,
Isabelle Taylord404ea12018-02-19 17:28:01 +0000151 DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000152 const DataSourceConfig& config) {
Isabelle Taylord404ea12018-02-19 17:28:01 +0000153 // Don't retry if FtraceController::Create() failed once.
154 // This can legitimately happen on user builds where we cannot access the
155 // debug paths, e.g., because of SELinux rules.
156 if (ftrace_creation_failed_)
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100157 return nullptr;
Isabelle Taylord404ea12018-02-19 17:28:01 +0000158
159 // Lazily create on the first instance.
160 if (!ftrace_) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100161 ftrace_ = FtraceController::Create(task_runner_, this);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000162
163 if (!ftrace_) {
164 PERFETTO_ELOG("Failed to create FtraceController");
165 ftrace_creation_failed_ = true;
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100166 return nullptr;
Isabelle Taylord404ea12018-02-19 17:28:01 +0000167 }
168
169 ftrace_->DisableAllEvents();
170 ftrace_->ClearTrace();
171 }
172
173 PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000174 config.target_buffer());
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100175 const BufferID buffer_id = static_cast<BufferID>(config.target_buffer());
176 std::unique_ptr<FtraceDataSource> data_source(new FtraceDataSource(
177 ftrace_->GetWeakPtr(), session_id, config.ftrace_config(),
178 endpoint_->CreateTraceWriter(buffer_id)));
179 if (!ftrace_->AddDataSource(data_source.get())) {
180 PERFETTO_ELOG(
181 "Failed to start tracing (too many concurrent sessions or ftrace is "
182 "already in use)");
183 return nullptr;
Hector Dearmanee3c49d2018-02-28 14:10:22 +0000184 }
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100185 return std::move(data_source);
Anna Zappone27ac99c2018-03-06 14:25:35 +0000186}
187
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100188std::unique_ptr<ProbesDataSource> ProbesProducer::CreateInodeFileDataSource(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000189 TracingSessionID session_id,
Anna Zappone27ac99c2018-03-06 14:25:35 +0000190 DataSourceInstanceID id,
Primiano Tuccidae35652018-03-29 18:32:02 +0100191 DataSourceConfig source_config) {
Anna Zappone27ac99c2018-03-06 14:25:35 +0000192 PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
193 id, source_config.target_buffer());
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100194 auto buffer_id = static_cast<BufferID>(source_config.target_buffer());
Anna Zappone2a6f9042018-03-14 13:26:07 +0000195 if (system_inodes_.empty())
Hector Dearman7fabd702018-03-28 12:37:15 +0100196 CreateStaticDeviceToInodeMap("/system", &system_inodes_);
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100197 return std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
198 std::move(source_config), task_runner_, session_id, &system_inodes_,
199 &cache_, endpoint_->CreateTraceWriter(buffer_id)));
Isabelle Taylord404ea12018-02-19 17:28:01 +0000200}
201
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100202std::unique_ptr<ProbesDataSource> ProbesProducer::CreateProcessStatsDataSource(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000203 TracingSessionID session_id,
Hector Dearman77451692018-03-08 16:21:13 +0000204 DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000205 const DataSourceConfig& config) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100206 base::ignore_result(id);
207 auto buffer_id = static_cast<BufferID>(config.target_buffer());
208 auto data_source =
209 std::unique_ptr<ProcessStatsDataSource>(new ProcessStatsDataSource(
210 session_id, endpoint_->CreateTraceWriter(buffer_id), config));
Primiano Tuccie8d75952018-05-02 11:30:12 +0100211 if (config.process_stats_config().scan_all_processes_on_start()) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100212 data_source->WriteAllProcesses();
Primiano Tuccie8d75952018-05-02 11:30:12 +0100213 }
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100214 return std::move(data_source);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000215}
216
217void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
218 PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100219 auto it = data_sources_.find(id);
220 if (it == data_sources_.end()) {
221 PERFETTO_ELOG("Cannot stop data source id=%" PRIu64 ", not found", id);
222 return;
223 }
224 ProbesDataSource* data_source = it->second.get();
225 TracingSessionID session_id = data_source->tracing_session_id;
226 auto range = session_data_sources_.equal_range(session_id);
227 for (auto kv = range.first; kv != range.second; kv++) {
228 if (kv->second != data_source)
229 continue;
230 session_data_sources_.erase(kv);
231 break;
232 }
233 data_sources_.erase(it);
Hector Dearman77451692018-03-08 16:21:13 +0000234 watchdogs_.erase(id);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000235}
236
Primiano Tuccidca727d2018-04-04 11:31:55 +0200237void ProbesProducer::OnTracingSetup() {}
Isabelle Taylor69faa902018-03-21 15:42:03 +0000238
Primiano Tuccid52e6272018-04-06 19:06:53 +0200239void ProbesProducer::Flush(FlushRequestID flush_request_id,
240 const DataSourceInstanceID* data_source_ids,
241 size_t num_data_sources) {
242 for (size_t i = 0; i < num_data_sources; i++) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100243 auto it = data_sources_.find(data_source_ids[i]);
244 if (it == data_sources_.end())
245 continue;
246 it->second->Flush();
Primiano Tuccid52e6272018-04-06 19:06:53 +0200247 }
248 endpoint_->NotifyFlushComplete(flush_request_id);
249}
250
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100251// This function is called by the FtraceController in batches, whenever it has
252// read one or more pages from one or more cpus and written that into the
253// userspace tracing buffer. If more than one ftrace data sources are active,
254// this call typically happens after writing for all session has been handled.
255void ProbesProducer::OnFtraceDataWrittenIntoDataSourceBuffers() {
256 TracingSessionID last_session_id = 0;
257 FtraceMetadata* metadata = nullptr;
258 InodeFileDataSource* inode_data_source = nullptr;
259 ProcessStatsDataSource* ps_data_source = nullptr;
260
261 // unordered_multimap guarantees that entries with the same key are contiguous
262 // in the iteration.
263 for (auto it = session_data_sources_.begin(); /* check below*/; it++) {
264 // If this is the last iteration or this is the session id has changed,
265 // dispatch the metadata update to the linked data sources, if any.
266 if (it == session_data_sources_.end() || it->first != last_session_id) {
267 bool has_inodes = metadata && !metadata->inode_and_device.empty();
268 bool has_pids = metadata && !metadata->pids.empty();
269 if (has_inodes && inode_data_source)
270 inode_data_source->OnInodes(metadata->inode_and_device);
271 if (has_pids && ps_data_source)
272 ps_data_source->OnPids(metadata->pids);
273 if (metadata)
274 metadata->Clear();
275 metadata = nullptr;
276 inode_data_source = nullptr;
277 ps_data_source = nullptr;
278 if (it == session_data_sources_.end())
279 break;
280 last_session_id = it->first;
281 }
282 ProbesDataSource* ds = it->second;
283 switch (ds->type_id) {
284 case FtraceDataSource::kTypeId:
285 metadata = static_cast<FtraceDataSource*>(ds)->mutable_metadata();
286 break;
287 case InodeFileDataSource::kTypeId:
288 inode_data_source = static_cast<InodeFileDataSource*>(ds);
289 break;
290 case ProcessStatsDataSource::kTypeId:
291 ps_data_source = static_cast<ProcessStatsDataSource*>(ds);
292 break;
293 default:
294 PERFETTO_DCHECK(false);
295 } // switch (type_id)
296 } // for (session_data_sources_)
297}
298
Isabelle Taylord404ea12018-02-19 17:28:01 +0000299void ProbesProducer::ConnectWithRetries(const char* socket_name,
300 base::TaskRunner* task_runner) {
301 PERFETTO_DCHECK(state_ == kNotStarted);
302 state_ = kNotConnected;
303
304 ResetConnectionBackoff();
305 socket_name_ = socket_name;
306 task_runner_ = task_runner;
307 Connect();
308}
309
310void ProbesProducer::Connect() {
311 PERFETTO_DCHECK(state_ == kNotConnected);
312 state_ = kConnecting;
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100313 endpoint_ = ProducerIPCClient::Connect(
Primiano Tucci578d7842018-03-29 15:27:05 +0100314 socket_name_, this, "perfetto.traced_probes", task_runner_);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000315}
316
317void ProbesProducer::IncreaseConnectionBackoff() {
318 connection_backoff_ms_ *= 2;
319 if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
320 connection_backoff_ms_ = kMaxConnectionBackoffMs;
321}
322
323void ProbesProducer::ResetConnectionBackoff() {
324 connection_backoff_ms_ = kInitialConnectionBackoffMs;
325}
326
Isabelle Taylord404ea12018-02-19 17:28:01 +0000327} // namespace perfetto