1 /*
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>
20 #include <sys/stat.h>
21
22 #include <algorithm>
23 #include <queue>
24 #include <string>
25
26 #include "perfetto/base/logging.h"
27 #include "perfetto/ext/base/utils.h"
28 #include "perfetto/ext/base/watchdog.h"
29 #include "perfetto/ext/base/weak_ptr.h"
30 #include "perfetto/ext/traced/traced.h"
31 #include "perfetto/ext/tracing/core/trace_packet.h"
32 #include "perfetto/ext/tracing/ipc/producer_ipc_client.h"
33 #include "perfetto/tracing/core/data_source_config.h"
34 #include "perfetto/tracing/core/data_source_descriptor.h"
35 #include "perfetto/tracing/core/trace_config.h"
36 #include "src/android_stats/statsd_logging_helper.h"
37 #include "src/traced/probes/android_log/android_log_data_source.h"
38 #include "src/traced/probes/common/cpu_freq_info.h"
39 #include "src/traced/probes/filesystem/inode_file_data_source.h"
40 #include "src/traced/probes/ftrace/ftrace_data_source.h"
41 #include "src/traced/probes/initial_display_state/initial_display_state_data_source.h"
42 #include "src/traced/probes/metatrace/metatrace_data_source.h"
43 #include "src/traced/probes/packages_list/packages_list_data_source.h"
44 #include "src/traced/probes/power/android_power_data_source.h"
45 #include "src/traced/probes/probes_data_source.h"
46 #include "src/traced/probes/ps/process_stats_data_source.h"
47 #include "src/traced/probes/sys_stats/sys_stats_data_source.h"
48 #include "src/traced/probes/system_info/system_info_data_source.h"
49
50 #include "protos/perfetto/config/ftrace/ftrace_config.gen.h"
51 #include "protos/perfetto/trace/filesystem/inode_file_map.pbzero.h"
52 #include "protos/perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
53 #include "protos/perfetto/trace/ftrace/ftrace_stats.pbzero.h"
54 #include "protos/perfetto/trace/trace_packet.pbzero.h"
55
56 namespace perfetto {
57 namespace {
58
59 constexpr uint32_t kInitialConnectionBackoffMs = 100;
60 constexpr uint32_t kMaxConnectionBackoffMs = 30 * 1000;
61
62 // Should be larger than FtraceController::kControllerFlushTimeoutMs.
63 constexpr uint32_t kFlushTimeoutMs = 1000;
64
65 constexpr size_t kTracingSharedMemSizeHintBytes = 1024 * 1024;
66 constexpr size_t kTracingSharedMemPageSizeHintBytes = 32 * 1024;
67
68 ProbesDataSource::Descriptor const* const kAllDataSources[]{
69 &FtraceDataSource::descriptor, //
70 &ProcessStatsDataSource::descriptor, //
71 &InodeFileDataSource::descriptor, //
72 &SysStatsDataSource::descriptor, //
73 &AndroidPowerDataSource::descriptor, //
74 &AndroidLogDataSource::descriptor, //
75 &PackagesListDataSource::descriptor, //
76 &MetatraceDataSource::descriptor, //
77 &SystemInfoDataSource::descriptor, //
78 &InitialDisplayStateDataSource::descriptor, //
79 };
80 } // namespace
81
82 // State transition diagram:
83 // +----------------------------+
84 // v +
85 // NotStarted -> NotConnected -> Connecting -> Connected
86 // ^ +
87 // +--------------+
88 //
89
90 ProbesProducer* ProbesProducer::instance_ = nullptr;
91
GetInstance()92 ProbesProducer* ProbesProducer::GetInstance() {
93 return instance_;
94 }
95
ProbesProducer()96 ProbesProducer::ProbesProducer() : weak_factory_(this) {
97 PERFETTO_CHECK(instance_ == nullptr);
98 instance_ = this;
99 }
100
~ProbesProducer()101 ProbesProducer::~ProbesProducer() {
102 instance_ = nullptr;
103 // The ftrace data sources must be deleted before the ftrace controller.
104 data_sources_.clear();
105 ftrace_.reset();
106 }
107
OnConnect()108 void ProbesProducer::OnConnect() {
109 PERFETTO_DCHECK(state_ == kConnecting);
110 state_ = kConnected;
111 ResetConnectionBackoff();
112 PERFETTO_LOG("Connected to the service");
113
114 // Register all the data sources.
115 for (const FtraceDataSource::Descriptor* desc : kAllDataSources) {
116 DataSourceDescriptor proto_desc;
117 proto_desc.set_name(desc->name);
118 proto_desc.set_will_notify_on_start(true);
119 proto_desc.set_will_notify_on_stop(true);
120 using Flags = ProbesDataSource::Descriptor::Flags;
121 if (desc->flags & Flags::kHandlesIncrementalState)
122 proto_desc.set_handles_incremental_state_clear(true);
123 endpoint_->RegisterDataSource(proto_desc);
124 }
125 }
126
OnDisconnect()127 void ProbesProducer::OnDisconnect() {
128 PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
129 PERFETTO_LOG("Disconnected from tracing service");
130 if (state_ == kConnected)
131 return task_runner_->PostTask([this] { this->Restart(); });
132
133 state_ = kNotConnected;
134 IncreaseConnectionBackoff();
135 task_runner_->PostDelayedTask([this] { this->Connect(); },
136 connection_backoff_ms_);
137 }
138
Restart()139 void ProbesProducer::Restart() {
140 // We lost the connection with the tracing service. At this point we need
141 // to reset all the data sources. Trying to handle that manually is going to
142 // be error prone. What we do here is simply destroying the instance and
143 // recreating it again.
144
145 base::TaskRunner* task_runner = task_runner_;
146 const char* socket_name = socket_name_;
147
148 // Invoke destructor and then the constructor again.
149 this->~ProbesProducer();
150 new (this) ProbesProducer();
151
152 ConnectWithRetries(socket_name, task_runner);
153 }
154
SetupDataSource(DataSourceInstanceID instance_id,const DataSourceConfig & config)155 void ProbesProducer::SetupDataSource(DataSourceInstanceID instance_id,
156 const DataSourceConfig& config) {
157 PERFETTO_DLOG("SetupDataSource(id=%" PRIu64 ", name=%s)", instance_id,
158 config.name().c_str());
159 PERFETTO_DCHECK(data_sources_.count(instance_id) == 0);
160 TracingSessionID session_id = config.tracing_session_id();
161 PERFETTO_CHECK(session_id > 0);
162
163 std::unique_ptr<ProbesDataSource> data_source;
164 if (config.name() == FtraceDataSource::descriptor.name) {
165 data_source = CreateFtraceDataSource(session_id, config);
166 } else if (config.name() == InodeFileDataSource::descriptor.name) {
167 data_source = CreateInodeFileDataSource(session_id, config);
168 } else if (config.name() == ProcessStatsDataSource::descriptor.name) {
169 data_source = CreateProcessStatsDataSource(session_id, config);
170 } else if (config.name() == SysStatsDataSource::descriptor.name) {
171 data_source = CreateSysStatsDataSource(session_id, config);
172 } else if (config.name() == AndroidPowerDataSource::descriptor.name) {
173 data_source = CreateAndroidPowerDataSource(session_id, config);
174 } else if (config.name() == AndroidLogDataSource::descriptor.name) {
175 data_source = CreateAndroidLogDataSource(session_id, config);
176 } else if (config.name() == PackagesListDataSource::descriptor.name) {
177 data_source = CreatePackagesListDataSource(session_id, config);
178 } else if (config.name() == MetatraceDataSource::descriptor.name) {
179 data_source = CreateMetatraceDataSource(session_id, config);
180 } else if (config.name() == SystemInfoDataSource::descriptor.name) {
181 data_source = CreateSystemInfoDataSource(session_id, config);
182 } else if (config.name() == InitialDisplayStateDataSource::descriptor.name) {
183 data_source = CreateInitialDisplayStateDataSource(session_id, config);
184 }
185
186 if (!data_source) {
187 PERFETTO_ELOG("Failed to create data source '%s'", config.name().c_str());
188 return;
189 }
190
191 session_data_sources_.emplace(session_id, data_source.get());
192 data_sources_[instance_id] = std::move(data_source);
193 }
194
StartDataSource(DataSourceInstanceID instance_id,const DataSourceConfig & config)195 void ProbesProducer::StartDataSource(DataSourceInstanceID instance_id,
196 const DataSourceConfig& config) {
197 PERFETTO_DLOG("StartDataSource(id=%" PRIu64 ", name=%s)", instance_id,
198 config.name().c_str());
199 auto it = data_sources_.find(instance_id);
200 if (it == data_sources_.end()) {
201 // Can happen if SetupDataSource() failed (e.g. ftrace was busy).
202 PERFETTO_ELOG("Data source id=%" PRIu64 " not found", instance_id);
203 return;
204 }
205 ProbesDataSource* data_source = it->second.get();
206 if (data_source->started)
207 return;
208 if (config.trace_duration_ms() != 0) {
209 uint32_t timeout = 5000 + 2 * config.trace_duration_ms();
210 watchdogs_.emplace(
211 instance_id, base::Watchdog::GetInstance()->CreateFatalTimer(timeout));
212 }
213 data_source->started = true;
214 data_source->Start();
215 endpoint_->NotifyDataSourceStarted(instance_id);
216 }
217
CreateFtraceDataSource(TracingSessionID session_id,const DataSourceConfig & config)218 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateFtraceDataSource(
219 TracingSessionID session_id,
220 const DataSourceConfig& config) {
221 // Don't retry if FtraceController::Create() failed once.
222 // This can legitimately happen on user builds where we cannot access the
223 // debug paths, e.g., because of SELinux rules.
224 if (ftrace_creation_failed_)
225 return nullptr;
226
227 // Lazily create on the first instance.
228 if (!ftrace_) {
229 ftrace_ = FtraceController::Create(task_runner_, this);
230
231 if (!ftrace_) {
232 PERFETTO_ELOG("Failed to create FtraceController");
233 ftrace_creation_failed_ = true;
234 return nullptr;
235 }
236
237 ftrace_->DisableAllEvents();
238 ftrace_->ClearTrace();
239 }
240
241 PERFETTO_LOG("Ftrace setup (target_buf=%" PRIu32 ")", config.target_buffer());
242 const BufferID buffer_id = static_cast<BufferID>(config.target_buffer());
243 FtraceConfig ftrace_config;
244 ftrace_config.ParseFromString(config.ftrace_config_raw());
245 std::unique_ptr<FtraceDataSource> data_source(new FtraceDataSource(
246 ftrace_->GetWeakPtr(), session_id, std::move(ftrace_config),
247 endpoint_->CreateTraceWriter(buffer_id)));
248 if (!ftrace_->AddDataSource(data_source.get())) {
249 PERFETTO_ELOG("Failed to setup ftrace");
250 return nullptr;
251 }
252 return std::unique_ptr<ProbesDataSource>(std::move(data_source));
253 }
254
CreateInodeFileDataSource(TracingSessionID session_id,DataSourceConfig source_config)255 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateInodeFileDataSource(
256 TracingSessionID session_id,
257 DataSourceConfig source_config) {
258 PERFETTO_LOG("Inode file map setup (target_buf=%" PRIu32 ")",
259 source_config.target_buffer());
260 auto buffer_id = static_cast<BufferID>(source_config.target_buffer());
261 if (system_inodes_.empty())
262 CreateStaticDeviceToInodeMap("/system", &system_inodes_);
263 return std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
264 std::move(source_config), task_runner_, session_id, &system_inodes_,
265 &cache_, endpoint_->CreateTraceWriter(buffer_id)));
266 }
267
CreateProcessStatsDataSource(TracingSessionID session_id,const DataSourceConfig & config)268 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateProcessStatsDataSource(
269 TracingSessionID session_id,
270 const DataSourceConfig& config) {
271 auto buffer_id = static_cast<BufferID>(config.target_buffer());
272 return std::unique_ptr<ProcessStatsDataSource>(new ProcessStatsDataSource(
273 task_runner_, session_id, endpoint_->CreateTraceWriter(buffer_id), config,
274 std::unique_ptr<CpuFreqInfo>(new CpuFreqInfo())));
275 }
276
CreateAndroidPowerDataSource(TracingSessionID session_id,const DataSourceConfig & config)277 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateAndroidPowerDataSource(
278 TracingSessionID session_id,
279 const DataSourceConfig& config) {
280 auto buffer_id = static_cast<BufferID>(config.target_buffer());
281 return std::unique_ptr<ProbesDataSource>(
282 new AndroidPowerDataSource(config, task_runner_, session_id,
283 endpoint_->CreateTraceWriter(buffer_id)));
284 }
285
CreateAndroidLogDataSource(TracingSessionID session_id,const DataSourceConfig & config)286 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateAndroidLogDataSource(
287 TracingSessionID session_id,
288 const DataSourceConfig& config) {
289 auto buffer_id = static_cast<BufferID>(config.target_buffer());
290 return std::unique_ptr<ProbesDataSource>(
291 new AndroidLogDataSource(config, task_runner_, session_id,
292 endpoint_->CreateTraceWriter(buffer_id)));
293 }
294
CreatePackagesListDataSource(TracingSessionID session_id,const DataSourceConfig & config)295 std::unique_ptr<ProbesDataSource> ProbesProducer::CreatePackagesListDataSource(
296 TracingSessionID session_id,
297 const DataSourceConfig& config) {
298 auto buffer_id = static_cast<BufferID>(config.target_buffer());
299 return std::unique_ptr<ProbesDataSource>(new PackagesListDataSource(
300 config, session_id, endpoint_->CreateTraceWriter(buffer_id)));
301 }
302
CreateSysStatsDataSource(TracingSessionID session_id,const DataSourceConfig & config)303 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateSysStatsDataSource(
304 TracingSessionID session_id,
305 const DataSourceConfig& config) {
306 auto buffer_id = static_cast<BufferID>(config.target_buffer());
307 return std::unique_ptr<SysStatsDataSource>(
308 new SysStatsDataSource(task_runner_, session_id,
309 endpoint_->CreateTraceWriter(buffer_id), config));
310 }
311
CreateMetatraceDataSource(TracingSessionID session_id,const DataSourceConfig & config)312 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateMetatraceDataSource(
313 TracingSessionID session_id,
314 const DataSourceConfig& config) {
315 auto buffer_id = static_cast<BufferID>(config.target_buffer());
316 return std::unique_ptr<ProbesDataSource>(new MetatraceDataSource(
317 task_runner_, session_id, endpoint_->CreateTraceWriter(buffer_id)));
318 }
319
CreateSystemInfoDataSource(TracingSessionID session_id,const DataSourceConfig & config)320 std::unique_ptr<ProbesDataSource> ProbesProducer::CreateSystemInfoDataSource(
321 TracingSessionID session_id,
322 const DataSourceConfig& config) {
323 auto buffer_id = static_cast<BufferID>(config.target_buffer());
324 return std::unique_ptr<ProbesDataSource>(new SystemInfoDataSource(
325 session_id, endpoint_->CreateTraceWriter(buffer_id),
326 std::unique_ptr<CpuFreqInfo>(new CpuFreqInfo())));
327 }
328
329 std::unique_ptr<ProbesDataSource>
CreateInitialDisplayStateDataSource(TracingSessionID session_id,const DataSourceConfig & config)330 ProbesProducer::CreateInitialDisplayStateDataSource(
331 TracingSessionID session_id,
332 const DataSourceConfig& config) {
333 auto buffer_id = static_cast<BufferID>(config.target_buffer());
334 return std::unique_ptr<ProbesDataSource>(new InitialDisplayStateDataSource(
335 task_runner_, config, session_id,
336 endpoint_->CreateTraceWriter(buffer_id)));
337 }
338
StopDataSource(DataSourceInstanceID id)339 void ProbesProducer::StopDataSource(DataSourceInstanceID id) {
340 PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
341 auto it = data_sources_.find(id);
342 if (it == data_sources_.end()) {
343 // Can happen if SetupDataSource() failed (e.g. ftrace was busy).
344 PERFETTO_ELOG("Cannot stop data source id=%" PRIu64 ", not found", id);
345 return;
346 }
347 ProbesDataSource* data_source = it->second.get();
348
349 // MetatraceDataSource special case: re-flush and ack the stop (to record the
350 // flushes of other data sources).
351 if (data_source->descriptor == &MetatraceDataSource::descriptor)
352 data_source->Flush(FlushRequestID{0}, [] {});
353
354 endpoint_->NotifyDataSourceStopped(id);
355
356 TracingSessionID session_id = data_source->tracing_session_id;
357 auto range = session_data_sources_.equal_range(session_id);
358 for (auto kv = range.first; kv != range.second; kv++) {
359 if (kv->second != data_source)
360 continue;
361 session_data_sources_.erase(kv);
362 break;
363 }
364 data_sources_.erase(it);
365 watchdogs_.erase(id);
366 }
367
OnTracingSetup()368 void ProbesProducer::OnTracingSetup() {
369 // shared_memory() can be null in test environments when running in-process.
370 if (endpoint_->shared_memory()) {
371 base::Watchdog::GetInstance()->SetMemoryLimit(
372 endpoint_->shared_memory()->size() + base::kWatchdogDefaultMemorySlack,
373 base::kWatchdogDefaultMemoryWindow);
374 }
375 }
376
Flush(FlushRequestID flush_request_id,const DataSourceInstanceID * data_source_ids,size_t num_data_sources)377 void ProbesProducer::Flush(FlushRequestID flush_request_id,
378 const DataSourceInstanceID* data_source_ids,
379 size_t num_data_sources) {
380 PERFETTO_DCHECK(flush_request_id);
381 auto weak_this = weak_factory_.GetWeakPtr();
382
383 // Issue a Flush() to all started data sources.
384 bool flush_queued = false;
385 for (size_t i = 0; i < num_data_sources; i++) {
386 DataSourceInstanceID ds_id = data_source_ids[i];
387 auto it = data_sources_.find(ds_id);
388 if (it == data_sources_.end() || !it->second->started)
389 continue;
390 pending_flushes_.emplace(flush_request_id, ds_id);
391 flush_queued = true;
392 auto flush_callback = [weak_this, flush_request_id, ds_id] {
393 if (weak_this)
394 weak_this->OnDataSourceFlushComplete(flush_request_id, ds_id);
395 };
396 it->second->Flush(flush_request_id, flush_callback);
397 }
398
399 // If there is nothing to flush, ack immediately.
400 if (!flush_queued) {
401 endpoint_->NotifyFlushComplete(flush_request_id);
402 return;
403 }
404
405 // Otherwise, post the timeout task.
406 task_runner_->PostDelayedTask(
407 [weak_this, flush_request_id] {
408 if (weak_this)
409 weak_this->OnFlushTimeout(flush_request_id);
410 },
411 kFlushTimeoutMs);
412 }
413
OnDataSourceFlushComplete(FlushRequestID flush_request_id,DataSourceInstanceID ds_id)414 void ProbesProducer::OnDataSourceFlushComplete(FlushRequestID flush_request_id,
415 DataSourceInstanceID ds_id) {
416 PERFETTO_DLOG("Flush %" PRIu64 " acked by data source %" PRIu64,
417 flush_request_id, ds_id);
418 auto range = pending_flushes_.equal_range(flush_request_id);
419 for (auto it = range.first; it != range.second; it++) {
420 if (it->second == ds_id) {
421 pending_flushes_.erase(it);
422 break;
423 }
424 }
425
426 if (pending_flushes_.count(flush_request_id))
427 return; // Still waiting for other data sources to ack.
428
429 PERFETTO_DLOG("All data sources acked to flush %" PRIu64, flush_request_id);
430 endpoint_->NotifyFlushComplete(flush_request_id);
431 }
432
OnFlushTimeout(FlushRequestID flush_request_id)433 void ProbesProducer::OnFlushTimeout(FlushRequestID flush_request_id) {
434 if (pending_flushes_.count(flush_request_id) == 0)
435 return; // All acked.
436 PERFETTO_ELOG("Flush(%" PRIu64 ") timed out", flush_request_id);
437 pending_flushes_.erase(flush_request_id);
438 endpoint_->NotifyFlushComplete(flush_request_id);
439 }
440
ClearIncrementalState(const DataSourceInstanceID * data_source_ids,size_t num_data_sources)441 void ProbesProducer::ClearIncrementalState(
442 const DataSourceInstanceID* data_source_ids,
443 size_t num_data_sources) {
444 for (size_t i = 0; i < num_data_sources; i++) {
445 DataSourceInstanceID ds_id = data_source_ids[i];
446 auto it = data_sources_.find(ds_id);
447 if (it == data_sources_.end() || !it->second->started)
448 continue;
449
450 it->second->ClearIncrementalState();
451 }
452 }
453
454 // This function is called by the FtraceController in batches, whenever it has
455 // read one or more pages from one or more cpus and written that into the
456 // userspace tracing buffer. If more than one ftrace data sources are active,
457 // this call typically happens after writing for all session has been handled.
OnFtraceDataWrittenIntoDataSourceBuffers()458 void ProbesProducer::OnFtraceDataWrittenIntoDataSourceBuffers() {
459 TracingSessionID last_session_id = 0;
460 FtraceMetadata* metadata = nullptr;
461 InodeFileDataSource* inode_data_source = nullptr;
462 ProcessStatsDataSource* ps_data_source = nullptr;
463
464 // unordered_multimap guarantees that entries with the same key are contiguous
465 // in the iteration.
466 for (auto it = session_data_sources_.begin(); /* check below*/; it++) {
467 // If this is the last iteration or the session id has changed,
468 // dispatch the metadata update to the linked data sources, if any.
469 if (it == session_data_sources_.end() || it->first != last_session_id) {
470 bool has_inodes = metadata && !metadata->inode_and_device.empty();
471 bool has_pids = metadata && !metadata->pids.empty();
472 bool has_rename_pids = metadata && !metadata->rename_pids.empty();
473 if (has_inodes && inode_data_source)
474 inode_data_source->OnInodes(metadata->inode_and_device);
475 // Ordering the rename pids before the seen pids is important so that any
476 // renamed processes get scraped in the OnPids call.
477 if (has_rename_pids && ps_data_source)
478 ps_data_source->OnRenamePids(metadata->rename_pids);
479 if (has_pids && ps_data_source)
480 ps_data_source->OnPids(metadata->pids);
481 if (metadata)
482 metadata->Clear();
483 metadata = nullptr;
484 inode_data_source = nullptr;
485 ps_data_source = nullptr;
486 if (it == session_data_sources_.end())
487 break;
488 last_session_id = it->first;
489 }
490 ProbesDataSource* ds = it->second;
491 if (!ds->started)
492 continue;
493
494 if (ds->descriptor == &FtraceDataSource::descriptor) {
495 metadata = static_cast<FtraceDataSource*>(ds)->mutable_metadata();
496 } else if (ds->descriptor == &InodeFileDataSource::descriptor) {
497 inode_data_source = static_cast<InodeFileDataSource*>(ds);
498 } else if (ds->descriptor == &ProcessStatsDataSource::descriptor) {
499 // A trace session might have declared more than one ps data source.
500 // In those cases we often use one for a full dump on startup (
501 // targeting a dedicated buffer) and another one for on-demand dumps
502 // targeting the main buffer.
503 // Only use the one that has on-demand dumps enabled, if any.
504 auto ps = static_cast<ProcessStatsDataSource*>(ds);
505 if (ps->on_demand_dumps_enabled())
506 ps_data_source = ps;
507 }
508 } // for (session_data_sources_)
509 }
510
ConnectWithRetries(const char * socket_name,base::TaskRunner * task_runner)511 void ProbesProducer::ConnectWithRetries(const char* socket_name,
512 base::TaskRunner* task_runner) {
513 PERFETTO_DCHECK(state_ == kNotStarted);
514 state_ = kNotConnected;
515
516 ResetConnectionBackoff();
517 socket_name_ = socket_name;
518 task_runner_ = task_runner;
519 Connect();
520 }
521
Connect()522 void ProbesProducer::Connect() {
523 PERFETTO_DCHECK(state_ == kNotConnected);
524 state_ = kConnecting;
525 endpoint_ = ProducerIPCClient::Connect(
526 socket_name_, this, "perfetto.traced_probes", task_runner_,
527 TracingService::ProducerSMBScrapingMode::kDisabled,
528 kTracingSharedMemSizeHintBytes, kTracingSharedMemPageSizeHintBytes);
529 }
530
IncreaseConnectionBackoff()531 void ProbesProducer::IncreaseConnectionBackoff() {
532 connection_backoff_ms_ *= 2;
533 if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
534 connection_backoff_ms_ = kMaxConnectionBackoffMs;
535 }
536
ResetConnectionBackoff()537 void ProbesProducer::ResetConnectionBackoff() {
538 connection_backoff_ms_ = kInitialConnectionBackoffMs;
539 }
540
ActivateTrigger(std::string trigger)541 void ProbesProducer::ActivateTrigger(std::string trigger) {
542 android_stats::MaybeLogTriggerEvent(
543 PerfettoTriggerAtom::kProbesProducerTrigger, trigger);
544
545 task_runner_->PostTask([this, trigger]() {
546 if (!endpoint_) {
547 android_stats::MaybeLogTriggerEvent(
548 PerfettoTriggerAtom::kProbesProducerTriggerFail, trigger);
549 return;
550 }
551 endpoint_->ActivateTriggers({trigger});
552 });
553 }
554
555 } // namespace perfetto
556