1 /*
2 * Copyright (C) 2017 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/tracing/ipc/consumer/consumer_ipc_client_impl.h"
18
19 #include <string.h>
20
21 #include <cinttypes>
22
23 #include "perfetto/base/task_runner.h"
24 #include "perfetto/ext/ipc/client.h"
25 #include "perfetto/ext/tracing/core/consumer.h"
26 #include "perfetto/ext/tracing/core/observable_events.h"
27 #include "perfetto/ext/tracing/core/trace_stats.h"
28 #include "perfetto/tracing/core/trace_config.h"
29 #include "perfetto/tracing/core/tracing_service_state.h"
30
31 // TODO(fmayer): Add a test to check to what happens when ConsumerIPCClientImpl
32 // gets destroyed w.r.t. the Consumer pointer. Also think to lifetime of the
33 // Consumer* during the callbacks.
34
35 namespace perfetto {
36
37 // static. (Declared in include/tracing/ipc/consumer_ipc_client.h).
Connect(const char * service_sock_name,Consumer * consumer,base::TaskRunner * task_runner)38 std::unique_ptr<TracingService::ConsumerEndpoint> ConsumerIPCClient::Connect(
39 const char* service_sock_name,
40 Consumer* consumer,
41 base::TaskRunner* task_runner) {
42 return std::unique_ptr<TracingService::ConsumerEndpoint>(
43 new ConsumerIPCClientImpl(service_sock_name, consumer, task_runner));
44 }
45
ConsumerIPCClientImpl(const char * service_sock_name,Consumer * consumer,base::TaskRunner * task_runner)46 ConsumerIPCClientImpl::ConsumerIPCClientImpl(const char* service_sock_name,
47 Consumer* consumer,
48 base::TaskRunner* task_runner)
49 : consumer_(consumer),
50 ipc_channel_(
51 ipc::Client::CreateInstance({service_sock_name, /*sock_retry=*/false},
52 task_runner)),
53 consumer_port_(this /* event_listener */),
54 weak_ptr_factory_(this) {
55 ipc_channel_->BindService(consumer_port_.GetWeakPtr());
56 }
57
58 ConsumerIPCClientImpl::~ConsumerIPCClientImpl() = default;
59
60 // Called by the IPC layer if the BindService() succeeds.
OnConnect()61 void ConsumerIPCClientImpl::OnConnect() {
62 connected_ = true;
63 consumer_->OnConnect();
64 }
65
OnDisconnect()66 void ConsumerIPCClientImpl::OnDisconnect() {
67 PERFETTO_DLOG("Tracing service connection failure");
68 connected_ = false;
69 consumer_->OnDisconnect(); // Note: may delete |this|.
70 }
71
EnableTracing(const TraceConfig & trace_config,base::ScopedFile fd)72 void ConsumerIPCClientImpl::EnableTracing(const TraceConfig& trace_config,
73 base::ScopedFile fd) {
74 if (!connected_) {
75 PERFETTO_DLOG("Cannot EnableTracing(), not connected to tracing service");
76 return;
77 }
78
79 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
80 if (fd) {
81 consumer_->OnTracingDisabled(
82 "Passing FDs for write_into_file is not supported on Windows");
83 return;
84 }
85 #endif
86
87 protos::gen::EnableTracingRequest req;
88 *req.mutable_trace_config() = trace_config;
89 ipc::Deferred<protos::gen::EnableTracingResponse> async_response;
90 auto weak_this = weak_ptr_factory_.GetWeakPtr();
91 async_response.Bind(
92 [weak_this](
93 ipc::AsyncResult<protos::gen::EnableTracingResponse> response) {
94 if (weak_this)
95 weak_this->OnEnableTracingResponse(std::move(response));
96 });
97
98 // |fd| will be closed when this function returns, but it's fine because the
99 // IPC layer dup()'s it when sending the IPC.
100 consumer_port_.EnableTracing(req, std::move(async_response), *fd);
101 }
102
ChangeTraceConfig(const TraceConfig & trace_config)103 void ConsumerIPCClientImpl::ChangeTraceConfig(const TraceConfig& trace_config) {
104 if (!connected_) {
105 PERFETTO_DLOG(
106 "Cannot ChangeTraceConfig(), not connected to tracing service");
107 return;
108 }
109
110 ipc::Deferred<protos::gen::ChangeTraceConfigResponse> async_response;
111 async_response.Bind(
112 [](ipc::AsyncResult<protos::gen::ChangeTraceConfigResponse> response) {
113 if (!response)
114 PERFETTO_DLOG("ChangeTraceConfig() failed");
115 });
116 protos::gen::ChangeTraceConfigRequest req;
117 *req.mutable_trace_config() = trace_config;
118 consumer_port_.ChangeTraceConfig(req, std::move(async_response));
119 }
120
StartTracing()121 void ConsumerIPCClientImpl::StartTracing() {
122 if (!connected_) {
123 PERFETTO_DLOG("Cannot StartTracing(), not connected to tracing service");
124 return;
125 }
126
127 ipc::Deferred<protos::gen::StartTracingResponse> async_response;
128 async_response.Bind(
129 [](ipc::AsyncResult<protos::gen::StartTracingResponse> response) {
130 if (!response)
131 PERFETTO_DLOG("StartTracing() failed");
132 });
133 protos::gen::StartTracingRequest req;
134 consumer_port_.StartTracing(req, std::move(async_response));
135 }
136
DisableTracing()137 void ConsumerIPCClientImpl::DisableTracing() {
138 if (!connected_) {
139 PERFETTO_DLOG("Cannot DisableTracing(), not connected to tracing service");
140 return;
141 }
142
143 ipc::Deferred<protos::gen::DisableTracingResponse> async_response;
144 async_response.Bind(
145 [](ipc::AsyncResult<protos::gen::DisableTracingResponse> response) {
146 if (!response)
147 PERFETTO_DLOG("DisableTracing() failed");
148 });
149 consumer_port_.DisableTracing(protos::gen::DisableTracingRequest(),
150 std::move(async_response));
151 }
152
ReadBuffers()153 void ConsumerIPCClientImpl::ReadBuffers() {
154 if (!connected_) {
155 PERFETTO_DLOG("Cannot ReadBuffers(), not connected to tracing service");
156 return;
157 }
158
159 ipc::Deferred<protos::gen::ReadBuffersResponse> async_response;
160
161 // The IPC layer guarantees that callbacks are destroyed after this object
162 // is destroyed (by virtue of destroying the |consumer_port_|). In turn the
163 // contract of this class expects the caller to not destroy the Consumer class
164 // before having destroyed this class. Hence binding |this| here is safe.
165 async_response.Bind(
166 [this](ipc::AsyncResult<protos::gen::ReadBuffersResponse> response) {
167 OnReadBuffersResponse(std::move(response));
168 });
169 consumer_port_.ReadBuffers(protos::gen::ReadBuffersRequest(),
170 std::move(async_response));
171 }
172
OnReadBuffersResponse(ipc::AsyncResult<protos::gen::ReadBuffersResponse> response)173 void ConsumerIPCClientImpl::OnReadBuffersResponse(
174 ipc::AsyncResult<protos::gen::ReadBuffersResponse> response) {
175 if (!response) {
176 PERFETTO_DLOG("ReadBuffers() failed");
177 return;
178 }
179 std::vector<TracePacket> trace_packets;
180 for (auto& resp_slice : response->slices()) {
181 const std::string& slice_data = resp_slice.data();
182 Slice slice = Slice::Allocate(slice_data.size());
183 memcpy(slice.own_data(), slice_data.data(), slice.size);
184 partial_packet_.AddSlice(std::move(slice));
185 if (resp_slice.last_slice_for_packet())
186 trace_packets.emplace_back(std::move(partial_packet_));
187 }
188 if (!trace_packets.empty() || !response.has_more())
189 consumer_->OnTraceData(std::move(trace_packets), response.has_more());
190 }
191
OnEnableTracingResponse(ipc::AsyncResult<protos::gen::EnableTracingResponse> response)192 void ConsumerIPCClientImpl::OnEnableTracingResponse(
193 ipc::AsyncResult<protos::gen::EnableTracingResponse> response) {
194 std::string error;
195 // |response| might be empty when the request gets rejected (if the connection
196 // with the service is dropped all outstanding requests are auto-rejected).
197 if (!response) {
198 error =
199 "EnableTracing IPC request rejected. This is likely due to a loss of "
200 "the traced connection";
201 } else {
202 error = response->error();
203 }
204 if (!response || response->disabled())
205 consumer_->OnTracingDisabled(error);
206 }
207
FreeBuffers()208 void ConsumerIPCClientImpl::FreeBuffers() {
209 if (!connected_) {
210 PERFETTO_DLOG("Cannot FreeBuffers(), not connected to tracing service");
211 return;
212 }
213
214 protos::gen::FreeBuffersRequest req;
215 ipc::Deferred<protos::gen::FreeBuffersResponse> async_response;
216 async_response.Bind(
217 [](ipc::AsyncResult<protos::gen::FreeBuffersResponse> response) {
218 if (!response)
219 PERFETTO_DLOG("FreeBuffers() failed");
220 });
221 consumer_port_.FreeBuffers(req, std::move(async_response));
222 }
223
Flush(uint32_t timeout_ms,FlushCallback callback)224 void ConsumerIPCClientImpl::Flush(uint32_t timeout_ms, FlushCallback callback) {
225 if (!connected_) {
226 PERFETTO_DLOG("Cannot Flush(), not connected to tracing service");
227 return callback(/*success=*/false);
228 }
229
230 protos::gen::FlushRequest req;
231 req.set_timeout_ms(static_cast<uint32_t>(timeout_ms));
232 ipc::Deferred<protos::gen::FlushResponse> async_response;
233 async_response.Bind(
234 [callback](ipc::AsyncResult<protos::gen::FlushResponse> response) {
235 callback(!!response);
236 });
237 consumer_port_.Flush(req, std::move(async_response));
238 }
239
Detach(const std::string & key)240 void ConsumerIPCClientImpl::Detach(const std::string& key) {
241 if (!connected_) {
242 PERFETTO_DLOG("Cannot Detach(), not connected to tracing service");
243 return;
244 }
245
246 protos::gen::DetachRequest req;
247 req.set_key(key);
248 ipc::Deferred<protos::gen::DetachResponse> async_response;
249 auto weak_this = weak_ptr_factory_.GetWeakPtr();
250
251 async_response.Bind(
252 [weak_this](ipc::AsyncResult<protos::gen::DetachResponse> response) {
253 if (weak_this)
254 weak_this->consumer_->OnDetach(!!response);
255 });
256 consumer_port_.Detach(req, std::move(async_response));
257 }
258
Attach(const std::string & key)259 void ConsumerIPCClientImpl::Attach(const std::string& key) {
260 if (!connected_) {
261 PERFETTO_DLOG("Cannot Attach(), not connected to tracing service");
262 return;
263 }
264
265 {
266 protos::gen::AttachRequest req;
267 req.set_key(key);
268 ipc::Deferred<protos::gen::AttachResponse> async_response;
269 auto weak_this = weak_ptr_factory_.GetWeakPtr();
270
271 async_response.Bind(
272 [weak_this](ipc::AsyncResult<protos::gen::AttachResponse> response) {
273 if (!weak_this)
274 return;
275 if (!response) {
276 weak_this->consumer_->OnAttach(/*success=*/false, TraceConfig());
277 return;
278 }
279 const TraceConfig& trace_config = response->trace_config();
280
281 // If attached successfully, also attach to the end-of-trace
282 // notificaton callback, via EnableTracing(attach_notification_only).
283 protos::gen::EnableTracingRequest enable_req;
284 enable_req.set_attach_notification_only(true);
285 ipc::Deferred<protos::gen::EnableTracingResponse> enable_resp;
286 enable_resp.Bind(
287 [weak_this](
288 ipc::AsyncResult<protos::gen::EnableTracingResponse> resp) {
289 if (weak_this)
290 weak_this->OnEnableTracingResponse(std::move(resp));
291 });
292 weak_this->consumer_port_.EnableTracing(enable_req,
293 std::move(enable_resp));
294
295 weak_this->consumer_->OnAttach(/*success=*/true, trace_config);
296 });
297 consumer_port_.Attach(req, std::move(async_response));
298 }
299 }
300
GetTraceStats()301 void ConsumerIPCClientImpl::GetTraceStats() {
302 if (!connected_) {
303 PERFETTO_DLOG("Cannot GetTraceStats(), not connected to tracing service");
304 return;
305 }
306
307 protos::gen::GetTraceStatsRequest req;
308 ipc::Deferred<protos::gen::GetTraceStatsResponse> async_response;
309
310 // The IPC layer guarantees that callbacks are destroyed after this object
311 // is destroyed (by virtue of destroying the |consumer_port_|). In turn the
312 // contract of this class expects the caller to not destroy the Consumer class
313 // before having destroyed this class. Hence binding |this| here is safe.
314 async_response.Bind(
315 [this](ipc::AsyncResult<protos::gen::GetTraceStatsResponse> response) {
316 if (!response) {
317 consumer_->OnTraceStats(/*success=*/false, TraceStats());
318 return;
319 }
320 consumer_->OnTraceStats(/*success=*/true, response->trace_stats());
321 });
322 consumer_port_.GetTraceStats(req, std::move(async_response));
323 }
324
ObserveEvents(uint32_t enabled_event_types)325 void ConsumerIPCClientImpl::ObserveEvents(uint32_t enabled_event_types) {
326 if (!connected_) {
327 PERFETTO_DLOG("Cannot ObserveEvents(), not connected to tracing service");
328 return;
329 }
330
331 protos::gen::ObserveEventsRequest req;
332 for (uint32_t i = 0; i < 32; i++) {
333 const uint32_t event_id = 1u << i;
334 if (enabled_event_types & event_id)
335 req.add_events_to_observe(static_cast<ObservableEvents::Type>(event_id));
336 }
337
338 ipc::Deferred<protos::gen::ObserveEventsResponse> async_response;
339 // The IPC layer guarantees that callbacks are destroyed after this object
340 // is destroyed (by virtue of destroying the |consumer_port_|). In turn the
341 // contract of this class expects the caller to not destroy the Consumer class
342 // before having destroyed this class. Hence binding |this| here is safe.
343 async_response.Bind(
344 [this](ipc::AsyncResult<protos::gen::ObserveEventsResponse> response) {
345 // Skip empty response, which the service sends to close the stream.
346 if (!response.has_more()) {
347 PERFETTO_DCHECK(!response.success());
348 return;
349 }
350 consumer_->OnObservableEvents(response->events());
351 });
352 consumer_port_.ObserveEvents(req, std::move(async_response));
353 }
354
QueryServiceState(QueryServiceStateCallback callback)355 void ConsumerIPCClientImpl::QueryServiceState(
356 QueryServiceStateCallback callback) {
357 if (!connected_) {
358 PERFETTO_DLOG(
359 "Cannot QueryServiceState(), not connected to tracing service");
360 return;
361 }
362
363 auto it = pending_query_svc_reqs_.insert(pending_query_svc_reqs_.end(),
364 {std::move(callback), {}});
365 protos::gen::QueryServiceStateRequest req;
366 ipc::Deferred<protos::gen::QueryServiceStateResponse> async_response;
367 auto weak_this = weak_ptr_factory_.GetWeakPtr();
368 async_response.Bind(
369 [weak_this,
370 it](ipc::AsyncResult<protos::gen::QueryServiceStateResponse> response) {
371 if (weak_this)
372 weak_this->OnQueryServiceStateResponse(std::move(response), it);
373 });
374 consumer_port_.QueryServiceState(req, std::move(async_response));
375 }
376
OnQueryServiceStateResponse(ipc::AsyncResult<protos::gen::QueryServiceStateResponse> response,PendingQueryServiceRequests::iterator req_it)377 void ConsumerIPCClientImpl::OnQueryServiceStateResponse(
378 ipc::AsyncResult<protos::gen::QueryServiceStateResponse> response,
379 PendingQueryServiceRequests::iterator req_it) {
380 PERFETTO_DCHECK(req_it->callback);
381
382 if (!response) {
383 auto callback = std::move(req_it->callback);
384 pending_query_svc_reqs_.erase(req_it);
385 callback(false, TracingServiceState());
386 return;
387 }
388
389 // The QueryServiceState response can be split in several chunks if the
390 // service has several data sources. The client is supposed to merge all the
391 // replies. The easiest way to achieve this is to re-serialize the partial
392 // response and then re-decode the merged result in one shot.
393 std::vector<uint8_t>& merged_resp = req_it->merged_resp;
394 std::vector<uint8_t> part = response->service_state().SerializeAsArray();
395 merged_resp.insert(merged_resp.end(), part.begin(), part.end());
396
397 if (response.has_more())
398 return;
399
400 // All replies have been received. Decode the merged result and reply to the
401 // callback.
402 protos::gen::TracingServiceState svc_state;
403 bool ok = svc_state.ParseFromArray(merged_resp.data(), merged_resp.size());
404 if (!ok)
405 PERFETTO_ELOG("Failed to decode merged QueryServiceStateResponse");
406 auto callback = std::move(req_it->callback);
407 pending_query_svc_reqs_.erase(req_it);
408 callback(ok, std::move(svc_state));
409 }
410
QueryCapabilities(QueryCapabilitiesCallback callback)411 void ConsumerIPCClientImpl::QueryCapabilities(
412 QueryCapabilitiesCallback callback) {
413 if (!connected_) {
414 PERFETTO_DLOG(
415 "Cannot QueryCapabilities(), not connected to tracing service");
416 return;
417 }
418
419 protos::gen::QueryCapabilitiesRequest req;
420 ipc::Deferred<protos::gen::QueryCapabilitiesResponse> async_response;
421 async_response.Bind(
422 [callback](
423 ipc::AsyncResult<protos::gen::QueryCapabilitiesResponse> response) {
424 if (!response) {
425 // If the IPC fails, we are talking to an older version of the service
426 // that didn't support QueryCapabilities at all. In this case return
427 // an empty capabilities message.
428 callback(TracingServiceCapabilities());
429 } else {
430 callback(response->capabilities());
431 }
432 });
433 consumer_port_.QueryCapabilities(req, std::move(async_response));
434 }
435
SaveTraceForBugreport(SaveTraceForBugreportCallback callback)436 void ConsumerIPCClientImpl::SaveTraceForBugreport(
437 SaveTraceForBugreportCallback callback) {
438 if (!connected_) {
439 PERFETTO_DLOG(
440 "Cannot SaveTraceForBugreport(), not connected to tracing service");
441 return;
442 }
443
444 protos::gen::SaveTraceForBugreportRequest req;
445 ipc::Deferred<protos::gen::SaveTraceForBugreportResponse> async_response;
446 async_response.Bind(
447 [callback](ipc::AsyncResult<protos::gen::SaveTraceForBugreportResponse>
448 response) {
449 if (!response) {
450 // If the IPC fails, we are talking to an older version of the service
451 // that didn't support SaveTraceForBugreport at all.
452 callback(
453 false,
454 "The tracing service doesn't support SaveTraceForBugreport()");
455 } else {
456 callback(response->success(), response->msg());
457 }
458 });
459 consumer_port_.SaveTraceForBugreport(req, std::move(async_response));
460 }
461
CloneSession(TracingSessionID tsid)462 void ConsumerIPCClientImpl::CloneSession(TracingSessionID tsid) {
463 if (!connected_) {
464 PERFETTO_DLOG("Cannot CloneSession(), not connected to tracing service");
465 return;
466 }
467
468 protos::gen::CloneSessionRequest req;
469 req.set_session_id(tsid);
470 ipc::Deferred<protos::gen::CloneSessionResponse> async_response;
471 auto weak_this = weak_ptr_factory_.GetWeakPtr();
472
473 async_response.Bind(
474 [weak_this](
475 ipc::AsyncResult<protos::gen::CloneSessionResponse> response) {
476 if (!weak_this)
477 return;
478 if (!response) {
479 // If the IPC fails, we are talking to an older version of the service
480 // that didn't support CloneSession at all.
481 weak_this->consumer_->OnSessionCloned(
482 {false, "CloneSession IPC not supported", {}});
483 } else {
484 base::Uuid uuid(response->uuid_lsb(), response->uuid_msb());
485 weak_this->consumer_->OnSessionCloned(
486 {response->success(), response->error(), uuid});
487 }
488 });
489 consumer_port_.CloneSession(req, std::move(async_response));
490 }
491 } // namespace perfetto
492