Simplify VolumeManager by removing 'ready' event.
[chromium-blink-merge.git] / dbus / object_proxy.cc
blobf2c4ebd7932f61c3b80ef043cab1426c89d3bf18
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "dbus/bus.h"
7 #include "base/bind.h"
8 #include "base/logging.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/metrics/histogram.h"
11 #include "base/strings/string_piece.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/task_runner_util.h"
14 #include "base/threading/thread.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "dbus/dbus_statistics.h"
17 #include "dbus/message.h"
18 #include "dbus/object_path.h"
19 #include "dbus/object_proxy.h"
20 #include "dbus/scoped_dbus_error.h"
22 namespace dbus {
24 namespace {
26 const char kErrorServiceUnknown[] = "org.freedesktop.DBus.Error.ServiceUnknown";
28 // Used for success ratio histograms. 1 for success, 0 for failure.
29 const int kSuccessRatioHistogramMaxValue = 2;
31 // The path of D-Bus Object sending NameOwnerChanged signal.
32 const char kDBusSystemObjectPath[] = "/org/freedesktop/DBus";
34 // The D-Bus Object interface.
35 const char kDBusSystemObjectInterface[] = "org.freedesktop.DBus";
37 // The D-Bus Object address.
38 const char kDBusSystemObjectAddress[] = "org.freedesktop.DBus";
40 // The NameOwnerChanged member in |kDBusSystemObjectInterface|.
41 const char kNameOwnerChangedMember[] = "NameOwnerChanged";
43 // Gets the absolute signal name by concatenating the interface name and
44 // the signal name. Used for building keys for method_table_ in
45 // ObjectProxy.
46 std::string GetAbsoluteSignalName(
47 const std::string& interface_name,
48 const std::string& signal_name) {
49 return interface_name + "." + signal_name;
52 // An empty function used for ObjectProxy::EmptyResponseCallback().
53 void EmptyResponseCallbackBody(Response* /*response*/) {
56 } // namespace
58 ObjectProxy::ObjectProxy(Bus* bus,
59 const std::string& service_name,
60 const ObjectPath& object_path,
61 int options)
62 : bus_(bus),
63 service_name_(service_name),
64 object_path_(object_path),
65 filter_added_(false),
66 ignore_service_unknown_errors_(
67 options & IGNORE_SERVICE_UNKNOWN_ERRORS) {
70 ObjectProxy::~ObjectProxy() {
73 // Originally we tried to make |method_call| a const reference, but we
74 // gave up as dbus_connection_send_with_reply_and_block() takes a
75 // non-const pointer of DBusMessage as the second parameter.
76 scoped_ptr<Response> ObjectProxy::CallMethodAndBlock(MethodCall* method_call,
77 int timeout_ms) {
78 bus_->AssertOnDBusThread();
80 if (!bus_->Connect() ||
81 !method_call->SetDestination(service_name_) ||
82 !method_call->SetPath(object_path_))
83 return scoped_ptr<Response>();
85 DBusMessage* request_message = method_call->raw_message();
87 ScopedDBusError error;
89 // Send the message synchronously.
90 const base::TimeTicks start_time = base::TimeTicks::Now();
91 DBusMessage* response_message =
92 bus_->SendWithReplyAndBlock(request_message, timeout_ms, error.get());
93 // Record if the method call is successful, or not. 1 if successful.
94 UMA_HISTOGRAM_ENUMERATION("DBus.SyncMethodCallSuccess",
95 response_message ? 1 : 0,
96 kSuccessRatioHistogramMaxValue);
97 statistics::AddBlockingSentMethodCall(service_name_,
98 method_call->GetInterface(),
99 method_call->GetMember());
101 if (!response_message) {
102 LogMethodCallFailure(method_call->GetInterface(),
103 method_call->GetMember(),
104 error.is_set() ? error.name() : "unknown error type",
105 error.is_set() ? error.message() : "");
106 return scoped_ptr<Response>();
108 // Record time spent for the method call. Don't include failures.
109 UMA_HISTOGRAM_TIMES("DBus.SyncMethodCallTime",
110 base::TimeTicks::Now() - start_time);
112 return Response::FromRawMessage(response_message);
115 void ObjectProxy::CallMethod(MethodCall* method_call,
116 int timeout_ms,
117 ResponseCallback callback) {
118 CallMethodWithErrorCallback(method_call, timeout_ms, callback,
119 base::Bind(&ObjectProxy::OnCallMethodError,
120 this,
121 method_call->GetInterface(),
122 method_call->GetMember(),
123 callback));
126 void ObjectProxy::CallMethodWithErrorCallback(MethodCall* method_call,
127 int timeout_ms,
128 ResponseCallback callback,
129 ErrorCallback error_callback) {
130 bus_->AssertOnOriginThread();
132 const base::TimeTicks start_time = base::TimeTicks::Now();
134 if (!method_call->SetDestination(service_name_) ||
135 !method_call->SetPath(object_path_)) {
136 // In case of a failure, run the error callback with NULL.
137 DBusMessage* response_message = NULL;
138 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
139 this,
140 callback,
141 error_callback,
142 start_time,
143 response_message);
144 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
145 return;
148 // Increment the reference count so we can safely reference the
149 // underlying request message until the method call is complete. This
150 // will be unref'ed in StartAsyncMethodCall().
151 DBusMessage* request_message = method_call->raw_message();
152 dbus_message_ref(request_message);
154 base::Closure task = base::Bind(&ObjectProxy::StartAsyncMethodCall,
155 this,
156 timeout_ms,
157 request_message,
158 callback,
159 error_callback,
160 start_time);
161 statistics::AddSentMethodCall(service_name_,
162 method_call->GetInterface(),
163 method_call->GetMember());
165 // Wait for the response in the D-Bus thread.
166 bus_->GetDBusTaskRunner()->PostTask(FROM_HERE, task);
169 void ObjectProxy::ConnectToSignal(const std::string& interface_name,
170 const std::string& signal_name,
171 SignalCallback signal_callback,
172 OnConnectedCallback on_connected_callback) {
173 bus_->AssertOnOriginThread();
175 base::PostTaskAndReplyWithResult(
176 bus_->GetDBusTaskRunner(),
177 FROM_HERE,
178 base::Bind(&ObjectProxy::ConnectToSignalInternal,
179 this,
180 interface_name,
181 signal_name,
182 signal_callback),
183 base::Bind(on_connected_callback,
184 interface_name,
185 signal_name));
188 void ObjectProxy::SetNameOwnerChangedCallback(
189 NameOwnerChangedCallback callback) {
190 bus_->AssertOnOriginThread();
192 name_owner_changed_callback_ = callback;
195 void ObjectProxy::Detach() {
196 bus_->AssertOnDBusThread();
198 if (filter_added_) {
199 if (!bus_->RemoveFilterFunction(&ObjectProxy::HandleMessageThunk, this)) {
200 LOG(ERROR) << "Failed to remove filter function";
204 for (std::set<std::string>::iterator iter = match_rules_.begin();
205 iter != match_rules_.end(); ++iter) {
206 ScopedDBusError error;
207 bus_->RemoveMatch(*iter, error.get());
208 if (error.is_set()) {
209 // There is nothing we can do to recover, so just print the error.
210 LOG(ERROR) << "Failed to remove match rule: " << *iter;
213 match_rules_.clear();
216 // static
217 ObjectProxy::ResponseCallback ObjectProxy::EmptyResponseCallback() {
218 return base::Bind(&EmptyResponseCallbackBody);
221 ObjectProxy::OnPendingCallIsCompleteData::OnPendingCallIsCompleteData(
222 ObjectProxy* in_object_proxy,
223 ResponseCallback in_response_callback,
224 ErrorCallback in_error_callback,
225 base::TimeTicks in_start_time)
226 : object_proxy(in_object_proxy),
227 response_callback(in_response_callback),
228 error_callback(in_error_callback),
229 start_time(in_start_time) {
232 ObjectProxy::OnPendingCallIsCompleteData::~OnPendingCallIsCompleteData() {
235 void ObjectProxy::StartAsyncMethodCall(int timeout_ms,
236 DBusMessage* request_message,
237 ResponseCallback response_callback,
238 ErrorCallback error_callback,
239 base::TimeTicks start_time) {
240 bus_->AssertOnDBusThread();
242 if (!bus_->Connect() || !bus_->SetUpAsyncOperations()) {
243 // In case of a failure, run the error callback with NULL.
244 DBusMessage* response_message = NULL;
245 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
246 this,
247 response_callback,
248 error_callback,
249 start_time,
250 response_message);
251 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
253 dbus_message_unref(request_message);
254 return;
257 DBusPendingCall* pending_call = NULL;
259 bus_->SendWithReply(request_message, &pending_call, timeout_ms);
261 // Prepare the data we'll be passing to OnPendingCallIsCompleteThunk().
262 // The data will be deleted in OnPendingCallIsCompleteThunk().
263 OnPendingCallIsCompleteData* data =
264 new OnPendingCallIsCompleteData(this, response_callback, error_callback,
265 start_time);
267 // This returns false only when unable to allocate memory.
268 const bool success = dbus_pending_call_set_notify(
269 pending_call,
270 &ObjectProxy::OnPendingCallIsCompleteThunk,
271 data,
272 NULL);
273 CHECK(success) << "Unable to allocate memory";
274 dbus_pending_call_unref(pending_call);
276 // It's now safe to unref the request message.
277 dbus_message_unref(request_message);
280 void ObjectProxy::OnPendingCallIsComplete(DBusPendingCall* pending_call,
281 ResponseCallback response_callback,
282 ErrorCallback error_callback,
283 base::TimeTicks start_time) {
284 bus_->AssertOnDBusThread();
286 DBusMessage* response_message = dbus_pending_call_steal_reply(pending_call);
287 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
288 this,
289 response_callback,
290 error_callback,
291 start_time,
292 response_message);
293 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
296 void ObjectProxy::RunResponseCallback(ResponseCallback response_callback,
297 ErrorCallback error_callback,
298 base::TimeTicks start_time,
299 DBusMessage* response_message) {
300 bus_->AssertOnOriginThread();
302 bool method_call_successful = false;
303 if (!response_message) {
304 // The response is not received.
305 error_callback.Run(NULL);
306 } else if (dbus_message_get_type(response_message) ==
307 DBUS_MESSAGE_TYPE_ERROR) {
308 // This will take |response_message| and release (unref) it.
309 scoped_ptr<ErrorResponse> error_response(
310 ErrorResponse::FromRawMessage(response_message));
311 error_callback.Run(error_response.get());
312 // Delete the message on the D-Bus thread. See below for why.
313 bus_->GetDBusTaskRunner()->PostTask(
314 FROM_HERE,
315 base::Bind(&base::DeletePointer<ErrorResponse>,
316 error_response.release()));
317 } else {
318 // This will take |response_message| and release (unref) it.
319 scoped_ptr<Response> response(Response::FromRawMessage(response_message));
320 // The response is successfully received.
321 response_callback.Run(response.get());
322 // The message should be deleted on the D-Bus thread for a complicated
323 // reason:
325 // libdbus keeps track of the number of bytes in the incoming message
326 // queue to ensure that the data size in the queue is manageable. The
327 // bookkeeping is partly done via dbus_message_unref(), and immediately
328 // asks the client code (Chrome) to stop monitoring the underlying
329 // socket, if the number of bytes exceeds a certian number, which is set
330 // to 63MB, per dbus-transport.cc:
332 // /* Try to default to something that won't totally hose the system,
333 // * but doesn't impose too much of a limitation.
334 // */
335 // transport->max_live_messages_size = _DBUS_ONE_MEGABYTE * 63;
337 // The monitoring of the socket is done on the D-Bus thread (see Watch
338 // class in bus.cc), hence we should stop the monitoring from D-Bus
339 // thread, not from the current thread here, which is likely UI thread.
340 bus_->GetDBusTaskRunner()->PostTask(
341 FROM_HERE,
342 base::Bind(&base::DeletePointer<Response>, response.release()));
344 method_call_successful = true;
345 // Record time spent for the method call. Don't include failures.
346 UMA_HISTOGRAM_TIMES("DBus.AsyncMethodCallTime",
347 base::TimeTicks::Now() - start_time);
349 // Record if the method call is successful, or not. 1 if successful.
350 UMA_HISTOGRAM_ENUMERATION("DBus.AsyncMethodCallSuccess",
351 method_call_successful,
352 kSuccessRatioHistogramMaxValue);
355 void ObjectProxy::OnPendingCallIsCompleteThunk(DBusPendingCall* pending_call,
356 void* user_data) {
357 OnPendingCallIsCompleteData* data =
358 reinterpret_cast<OnPendingCallIsCompleteData*>(user_data);
359 ObjectProxy* self = data->object_proxy;
360 self->OnPendingCallIsComplete(pending_call,
361 data->response_callback,
362 data->error_callback,
363 data->start_time);
364 delete data;
367 bool ObjectProxy::ConnectToSignalInternal(const std::string& interface_name,
368 const std::string& signal_name,
369 SignalCallback signal_callback) {
370 bus_->AssertOnDBusThread();
372 const std::string absolute_signal_name =
373 GetAbsoluteSignalName(interface_name, signal_name);
375 if (!bus_->Connect() || !bus_->SetUpAsyncOperations())
376 return false;
378 // We should add the filter only once. Otherwise, HandleMessage() will
379 // be called more than once.
380 if (!filter_added_) {
381 if (bus_->AddFilterFunction(&ObjectProxy::HandleMessageThunk, this)) {
382 filter_added_ = true;
383 } else {
384 LOG(ERROR) << "Failed to add filter function";
387 // Add a match rule so the signal goes through HandleMessage().
388 const std::string match_rule =
389 base::StringPrintf("type='signal', interface='%s', path='%s'",
390 interface_name.c_str(),
391 object_path_.value().c_str());
392 // Add a match_rule listening NameOwnerChanged for the well-known name
393 // |service_name_|.
394 const std::string name_owner_changed_match_rule =
395 base::StringPrintf(
396 "type='signal',interface='org.freedesktop.DBus',"
397 "member='NameOwnerChanged',path='/org/freedesktop/DBus',"
398 "sender='org.freedesktop.DBus',arg0='%s'",
399 service_name_.c_str());
401 const bool success =
402 AddMatchRuleWithCallback(match_rule,
403 absolute_signal_name,
404 signal_callback) &&
405 AddMatchRuleWithoutCallback(name_owner_changed_match_rule,
406 "org.freedesktop.DBus.NameOwnerChanged");
408 // Try getting the current name owner. It's not guaranteed that we can get
409 // the name owner at this moment, as the service may not yet be started. If
410 // that's the case, we'll get the name owner via NameOwnerChanged signal,
411 // as soon as the service is started.
412 UpdateNameOwnerAndBlock();
414 return success;
417 DBusHandlerResult ObjectProxy::HandleMessage(
418 DBusConnection* connection,
419 DBusMessage* raw_message) {
420 bus_->AssertOnDBusThread();
422 if (dbus_message_get_type(raw_message) != DBUS_MESSAGE_TYPE_SIGNAL)
423 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
425 // raw_message will be unrefed on exit of the function. Increment the
426 // reference so we can use it in Signal.
427 dbus_message_ref(raw_message);
428 scoped_ptr<Signal> signal(
429 Signal::FromRawMessage(raw_message));
431 // Verify the signal comes from the object we're proxying for, this is
432 // our last chance to return DBUS_HANDLER_RESULT_NOT_YET_HANDLED and
433 // allow other object proxies to handle instead.
434 const ObjectPath path = signal->GetPath();
435 if (path != object_path_) {
436 if (path.value() == kDBusSystemObjectPath &&
437 signal->GetMember() == kNameOwnerChangedMember) {
438 // Handle NameOwnerChanged separately
439 return HandleNameOwnerChanged(signal.Pass());
441 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
444 const std::string interface = signal->GetInterface();
445 const std::string member = signal->GetMember();
447 statistics::AddReceivedSignal(service_name_, interface, member);
449 // Check if we know about the signal.
450 const std::string absolute_signal_name = GetAbsoluteSignalName(
451 interface, member);
452 MethodTable::const_iterator iter = method_table_.find(absolute_signal_name);
453 if (iter == method_table_.end()) {
454 // Don't know about the signal.
455 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
457 VLOG(1) << "Signal received: " << signal->ToString();
459 std::string sender = signal->GetSender();
460 if (service_name_owner_ != sender) {
461 LOG(ERROR) << "Rejecting a message from a wrong sender.";
462 UMA_HISTOGRAM_COUNTS("DBus.RejectedSignalCount", 1);
463 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
466 const base::TimeTicks start_time = base::TimeTicks::Now();
467 if (bus_->HasDBusThread()) {
468 // Post a task to run the method in the origin thread.
469 // Transfer the ownership of |signal| to RunMethod().
470 // |released_signal| will be deleted in RunMethod().
471 Signal* released_signal = signal.release();
472 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE,
473 base::Bind(&ObjectProxy::RunMethod,
474 this,
475 start_time,
476 iter->second,
477 released_signal));
478 } else {
479 const base::TimeTicks start_time = base::TimeTicks::Now();
480 // If the D-Bus thread is not used, just call the callback on the
481 // current thread. Transfer the ownership of |signal| to RunMethod().
482 Signal* released_signal = signal.release();
483 RunMethod(start_time, iter->second, released_signal);
486 return DBUS_HANDLER_RESULT_HANDLED;
489 void ObjectProxy::RunMethod(base::TimeTicks start_time,
490 std::vector<SignalCallback> signal_callbacks,
491 Signal* signal) {
492 bus_->AssertOnOriginThread();
494 for (std::vector<SignalCallback>::iterator iter = signal_callbacks.begin();
495 iter != signal_callbacks.end(); ++iter)
496 iter->Run(signal);
498 // Delete the message on the D-Bus thread. See comments in
499 // RunResponseCallback().
500 bus_->GetDBusTaskRunner()->PostTask(
501 FROM_HERE,
502 base::Bind(&base::DeletePointer<Signal>, signal));
504 // Record time spent for handling the signal.
505 UMA_HISTOGRAM_TIMES("DBus.SignalHandleTime",
506 base::TimeTicks::Now() - start_time);
509 DBusHandlerResult ObjectProxy::HandleMessageThunk(
510 DBusConnection* connection,
511 DBusMessage* raw_message,
512 void* user_data) {
513 ObjectProxy* self = reinterpret_cast<ObjectProxy*>(user_data);
514 return self->HandleMessage(connection, raw_message);
517 void ObjectProxy::LogMethodCallFailure(
518 const base::StringPiece& interface_name,
519 const base::StringPiece& method_name,
520 const base::StringPiece& error_name,
521 const base::StringPiece& error_message) const {
522 if (ignore_service_unknown_errors_ && error_name == kErrorServiceUnknown)
523 return;
524 LOG(ERROR) << "Failed to call method: "
525 << interface_name << "." << method_name
526 << ": object_path= " << object_path_.value()
527 << ": " << error_name << ": " << error_message;
530 void ObjectProxy::OnCallMethodError(const std::string& interface_name,
531 const std::string& method_name,
532 ResponseCallback response_callback,
533 ErrorResponse* error_response) {
534 if (error_response) {
535 // Error message may contain the error message as string.
536 MessageReader reader(error_response);
537 std::string error_message;
538 reader.PopString(&error_message);
539 LogMethodCallFailure(interface_name,
540 method_name,
541 error_response->GetErrorName(),
542 error_message);
544 response_callback.Run(NULL);
547 bool ObjectProxy::AddMatchRuleWithCallback(
548 const std::string& match_rule,
549 const std::string& absolute_signal_name,
550 SignalCallback signal_callback) {
551 DCHECK(!match_rule.empty());
552 DCHECK(!absolute_signal_name.empty());
553 bus_->AssertOnDBusThread();
555 if (match_rules_.find(match_rule) == match_rules_.end()) {
556 ScopedDBusError error;
557 bus_->AddMatch(match_rule, error.get());
558 if (error.is_set()) {
559 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
560 << error.name() << ": " << error.message();
561 return false;
562 } else {
563 // Store the match rule, so that we can remove this in Detach().
564 match_rules_.insert(match_rule);
565 // Add the signal callback to the method table.
566 method_table_[absolute_signal_name].push_back(signal_callback);
567 return true;
569 } else {
570 // We already have the match rule.
571 method_table_[absolute_signal_name].push_back(signal_callback);
572 return true;
576 bool ObjectProxy::AddMatchRuleWithoutCallback(
577 const std::string& match_rule,
578 const std::string& absolute_signal_name) {
579 DCHECK(!match_rule.empty());
580 DCHECK(!absolute_signal_name.empty());
581 bus_->AssertOnDBusThread();
583 if (match_rules_.find(match_rule) != match_rules_.end())
584 return true;
586 ScopedDBusError error;
587 bus_->AddMatch(match_rule, error.get());
588 if (error.is_set()) {
589 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
590 << error.name() << ": " << error.message();
591 return false;
593 // Store the match rule, so that we can remove this in Detach().
594 match_rules_.insert(match_rule);
595 return true;
598 void ObjectProxy::UpdateNameOwnerAndBlock() {
599 bus_->AssertOnDBusThread();
600 // Errors should be suppressed here, as the service may not be yet running
601 // when connecting to signals of the service, which is just fine.
602 // The ObjectProxy will be notified when the service is launched via
603 // NameOwnerChanged signal. See also comments in ConnectToSignalInternal().
604 service_name_owner_ =
605 bus_->GetServiceOwnerAndBlock(service_name_, Bus::SUPPRESS_ERRORS);
608 DBusHandlerResult ObjectProxy::HandleNameOwnerChanged(
609 scoped_ptr<Signal> signal) {
610 DCHECK(signal);
611 bus_->AssertOnDBusThread();
613 // Confirm the validity of the NameOwnerChanged signal.
614 if (signal->GetMember() == kNameOwnerChangedMember &&
615 signal->GetInterface() == kDBusSystemObjectInterface &&
616 signal->GetSender() == kDBusSystemObjectAddress) {
617 MessageReader reader(signal.get());
618 std::string name, old_owner, new_owner;
619 if (reader.PopString(&name) &&
620 reader.PopString(&old_owner) &&
621 reader.PopString(&new_owner) &&
622 name == service_name_) {
623 service_name_owner_ = new_owner;
624 bus_->GetOriginTaskRunner()->PostTask(
625 FROM_HERE,
626 base::Bind(&ObjectProxy::RunNameOwnerChangedCallback,
627 this, old_owner, new_owner));
631 // Always return unhandled to let other object proxies handle the same
632 // signal.
633 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
636 void ObjectProxy::RunNameOwnerChangedCallback(const std::string& old_owner,
637 const std::string& new_owner) {
638 bus_->AssertOnOriginThread();
639 if (!name_owner_changed_callback_.is_null())
640 name_owner_changed_callback_.Run(old_owner, new_owner);
643 } // namespace dbus