blob: 1fd3ad572d52a088747ff464a32868e8b17350f7 [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);
122
Hector Dearman0ff07c72018-03-15 09:54:46 +0000123 // TODO(hjd): This a hack since we don't actually know the session id. For
124 // now we'll assume anything wit hthe same target buffer is in the same
125 // session.
126 TracingSessionID session_id = config.target_buffer();
127
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100128 std::unique_ptr<ProbesDataSource> data_source;
Hector Dearman0ff07c72018-03-15 09:54:46 +0000129 if (config.name() == kFtraceSourceName) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100130 data_source = CreateFtraceDataSource(session_id, instance_id, config);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000131 } else if (config.name() == kInodeMapSourceName) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100132 data_source = CreateInodeFileDataSource(session_id, instance_id, config);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000133 } else if (config.name() == kProcessStatsSourceName) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100134 data_source = CreateProcessStatsDataSource(session_id, instance_id, config);
135 }
136
137 if (!data_source) {
138 PERFETTO_ELOG("Failed to create data source '%s'", config.name().c_str());
Hector Dearman0ff07c72018-03-15 09:54:46 +0000139 return;
140 }
141
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100142 session_data_sources_.emplace(session_id, data_source.get());
143 data_sources_[instance_id] = std::move(data_source);
Hector Dearman0ff07c72018-03-15 09:54:46 +0000144
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100145 if (config.trace_duration_ms() != 0) {
146 uint32_t timeout = 5000 + 2 * config.trace_duration_ms();
147 watchdogs_.emplace(
148 instance_id, base::Watchdog::GetInstance()->CreateFatalTimer(timeout));
Isabelle Taylord404ea12018-02-19 17:28:01 +0000149 }
150}
151
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100152std::unique_ptr<ProbesDataSource> ProbesProducer::CreateFtraceDataSource(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000153 TracingSessionID session_id,
Isabelle Taylord404ea12018-02-19 17:28:01 +0000154 DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000155 const DataSourceConfig& config) {
Isabelle Taylord404ea12018-02-19 17:28:01 +0000156 // Don't retry if FtraceController::Create() failed once.
157 // This can legitimately happen on user builds where we cannot access the
158 // debug paths, e.g., because of SELinux rules.
159 if (ftrace_creation_failed_)
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100160 return nullptr;
Isabelle Taylord404ea12018-02-19 17:28:01 +0000161
162 // Lazily create on the first instance.
163 if (!ftrace_) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100164 ftrace_ = FtraceController::Create(task_runner_, this);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000165
166 if (!ftrace_) {
167 PERFETTO_ELOG("Failed to create FtraceController");
168 ftrace_creation_failed_ = true;
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100169 return nullptr;
Isabelle Taylord404ea12018-02-19 17:28:01 +0000170 }
171
172 ftrace_->DisableAllEvents();
173 ftrace_->ClearTrace();
174 }
175
176 PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000177 config.target_buffer());
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100178 const BufferID buffer_id = static_cast<BufferID>(config.target_buffer());
179 std::unique_ptr<FtraceDataSource> data_source(new FtraceDataSource(
180 ftrace_->GetWeakPtr(), session_id, config.ftrace_config(),
181 endpoint_->CreateTraceWriter(buffer_id)));
182 if (!ftrace_->AddDataSource(data_source.get())) {
183 PERFETTO_ELOG(
184 "Failed to start tracing (too many concurrent sessions or ftrace is "
185 "already in use)");
186 return nullptr;
Hector Dearmanee3c49d2018-02-28 14:10:22 +0000187 }
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100188 return std::move(data_source);
Anna Zappone27ac99c2018-03-06 14:25:35 +0000189}
190
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100191std::unique_ptr<ProbesDataSource> ProbesProducer::CreateInodeFileDataSource(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000192 TracingSessionID session_id,
Anna Zappone27ac99c2018-03-06 14:25:35 +0000193 DataSourceInstanceID id,
Primiano Tuccidae35652018-03-29 18:32:02 +0100194 DataSourceConfig source_config) {
Anna Zappone27ac99c2018-03-06 14:25:35 +0000195 PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
196 id, source_config.target_buffer());
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100197 auto buffer_id = static_cast<BufferID>(source_config.target_buffer());
Anna Zappone2a6f9042018-03-14 13:26:07 +0000198 if (system_inodes_.empty())
Hector Dearman7fabd702018-03-28 12:37:15 +0100199 CreateStaticDeviceToInodeMap("/system", &system_inodes_);
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100200 return std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
201 std::move(source_config), task_runner_, session_id, &system_inodes_,
202 &cache_, endpoint_->CreateTraceWriter(buffer_id)));
Isabelle Taylord404ea12018-02-19 17:28:01 +0000203}
204
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100205std::unique_ptr<ProbesDataSource> ProbesProducer::CreateProcessStatsDataSource(
Hector Dearman0ff07c72018-03-15 09:54:46 +0000206 TracingSessionID session_id,
Hector Dearman77451692018-03-08 16:21:13 +0000207 DataSourceInstanceID id,
Hector Dearman0ff07c72018-03-15 09:54:46 +0000208 const DataSourceConfig& config) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100209 base::ignore_result(id);
210 auto buffer_id = static_cast<BufferID>(config.target_buffer());
211 auto data_source =
212 std::unique_ptr<ProcessStatsDataSource>(new ProcessStatsDataSource(
213 session_id, endpoint_->CreateTraceWriter(buffer_id), config));
Primiano Tuccie8d75952018-05-02 11:30:12 +0100214 if (config.process_stats_config().scan_all_processes_on_start()) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100215 data_source->WriteAllProcesses();
Primiano Tuccie8d75952018-05-02 11:30:12 +0100216 }
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100217 return std::move(data_source);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000218}
219
220void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
221 PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100222 auto it = data_sources_.find(id);
223 if (it == data_sources_.end()) {
224 PERFETTO_ELOG("Cannot stop data source id=%" PRIu64 ", not found", id);
225 return;
226 }
227 ProbesDataSource* data_source = it->second.get();
228 TracingSessionID session_id = data_source->tracing_session_id;
229 auto range = session_data_sources_.equal_range(session_id);
230 for (auto kv = range.first; kv != range.second; kv++) {
231 if (kv->second != data_source)
232 continue;
233 session_data_sources_.erase(kv);
234 break;
235 }
236 data_sources_.erase(it);
Hector Dearman77451692018-03-08 16:21:13 +0000237 watchdogs_.erase(id);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000238}
239
Primiano Tuccidca727d2018-04-04 11:31:55 +0200240void ProbesProducer::OnTracingSetup() {}
Isabelle Taylor69faa902018-03-21 15:42:03 +0000241
Primiano Tuccid52e6272018-04-06 19:06:53 +0200242void ProbesProducer::Flush(FlushRequestID flush_request_id,
243 const DataSourceInstanceID* data_source_ids,
244 size_t num_data_sources) {
245 for (size_t i = 0; i < num_data_sources; i++) {
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100246 auto it = data_sources_.find(data_source_ids[i]);
247 if (it == data_sources_.end())
248 continue;
249 it->second->Flush();
Primiano Tuccid52e6272018-04-06 19:06:53 +0200250 }
251 endpoint_->NotifyFlushComplete(flush_request_id);
252}
253
Primiano Tuccifd8240d2018-08-01 09:34:54 +0100254// This function is called by the FtraceController in batches, whenever it has
255// read one or more pages from one or more cpus and written that into the
256// userspace tracing buffer. If more than one ftrace data sources are active,
257// this call typically happens after writing for all session has been handled.
258void ProbesProducer::OnFtraceDataWrittenIntoDataSourceBuffers() {
259 TracingSessionID last_session_id = 0;
260 FtraceMetadata* metadata = nullptr;
261 InodeFileDataSource* inode_data_source = nullptr;
262 ProcessStatsDataSource* ps_data_source = nullptr;
263
264 // unordered_multimap guarantees that entries with the same key are contiguous
265 // in the iteration.
266 for (auto it = session_data_sources_.begin(); /* check below*/; it++) {
267 // If this is the last iteration or this is the session id has changed,
268 // dispatch the metadata update to the linked data sources, if any.
269 if (it == session_data_sources_.end() || it->first != last_session_id) {
270 bool has_inodes = metadata && !metadata->inode_and_device.empty();
271 bool has_pids = metadata && !metadata->pids.empty();
272 if (has_inodes && inode_data_source)
273 inode_data_source->OnInodes(metadata->inode_and_device);
274 if (has_pids && ps_data_source)
275 ps_data_source->OnPids(metadata->pids);
276 if (metadata)
277 metadata->Clear();
278 metadata = nullptr;
279 inode_data_source = nullptr;
280 ps_data_source = nullptr;
281 if (it == session_data_sources_.end())
282 break;
283 last_session_id = it->first;
284 }
285 ProbesDataSource* ds = it->second;
286 switch (ds->type_id) {
287 case FtraceDataSource::kTypeId:
288 metadata = static_cast<FtraceDataSource*>(ds)->mutable_metadata();
289 break;
290 case InodeFileDataSource::kTypeId:
291 inode_data_source = static_cast<InodeFileDataSource*>(ds);
292 break;
293 case ProcessStatsDataSource::kTypeId:
294 ps_data_source = static_cast<ProcessStatsDataSource*>(ds);
295 break;
296 default:
297 PERFETTO_DCHECK(false);
298 } // switch (type_id)
299 } // for (session_data_sources_)
300}
301
Isabelle Taylord404ea12018-02-19 17:28:01 +0000302void ProbesProducer::ConnectWithRetries(const char* socket_name,
303 base::TaskRunner* task_runner) {
304 PERFETTO_DCHECK(state_ == kNotStarted);
305 state_ = kNotConnected;
306
307 ResetConnectionBackoff();
308 socket_name_ = socket_name;
309 task_runner_ = task_runner;
310 Connect();
311}
312
313void ProbesProducer::Connect() {
314 PERFETTO_DCHECK(state_ == kNotConnected);
315 state_ = kConnecting;
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100316 endpoint_ = ProducerIPCClient::Connect(
Primiano Tucci578d7842018-03-29 15:27:05 +0100317 socket_name_, this, "perfetto.traced_probes", task_runner_);
Isabelle Taylord404ea12018-02-19 17:28:01 +0000318}
319
320void ProbesProducer::IncreaseConnectionBackoff() {
321 connection_backoff_ms_ *= 2;
322 if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
323 connection_backoff_ms_ = kMaxConnectionBackoffMs;
324}
325
326void ProbesProducer::ResetConnectionBackoff() {
327 connection_backoff_ms_ = kInitialConnectionBackoffMs;
328}
329
Isabelle Taylord404ea12018-02-19 17:28:01 +0000330} // namespace perfetto