Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(195)

Side by Side Diff: dbus/bus.cc

Issue 7491029: Implement Bus and ObjectProxy classes for our D-Bus library. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: another clang challenge Created 9 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « dbus/bus.h ('k') | dbus/dbus.gyp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2011 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.
4 //
5 // TODO(satorux):
6 // - Handle "disconnected" signal.
7 // - Add support for signal sending
8 // - Add support for signal monitoring
9 // - Collect metrics (ex. # of method calls, method call time, etc.)
10
11 #include "dbus/bus.h"
12
13 #include "base/bind.h"
14 #include "base/logging.h"
15 #include "base/message_loop.h"
16 #include "base/stl_util.h"
17 #include "base/threading/thread.h"
18 #include "base/threading/thread_restrictions.h"
19 #include "dbus/exported_object.h"
20 #include "dbus/object_proxy.h"
21 #include "dbus/scoped_dbus_error.h"
22
23 namespace dbus {
24
25 namespace {
26
27 // The class is used for watching the file descriptor used for D-Bus
28 // communication.
29 class Watch : public base::MessagePumpLibevent::Watcher {
30 public:
31 Watch(DBusWatch* watch)
32 : raw_watch_(watch) {
33 dbus_watch_set_data(raw_watch_, this, NULL);
34 }
35
36 ~Watch() {
37 dbus_watch_set_data(raw_watch_, NULL, NULL);
38 }
39
40 // Returns true if the underlying file descriptor is ready to be watched.
41 bool IsReadyToBeWatched() {
42 return dbus_watch_get_enabled(raw_watch_);
43 }
44
45 // Starts watching the underlying file descriptor.
46 void StartWatching() {
47 const int file_descriptor = dbus_watch_get_unix_fd(raw_watch_);
48 const int flags = dbus_watch_get_flags(raw_watch_);
49
50 MessageLoopForIO::Mode mode = MessageLoopForIO::WATCH_READ;
51 if ((flags & DBUS_WATCH_READABLE) && (flags & DBUS_WATCH_WRITABLE))
52 mode = MessageLoopForIO::WATCH_READ_WRITE;
53 else if (flags & DBUS_WATCH_READABLE)
54 mode = MessageLoopForIO::WATCH_READ;
55 else if (flags & DBUS_WATCH_WRITABLE)
56 mode = MessageLoopForIO::WATCH_WRITE;
57 else
58 NOTREACHED();
59
60 const bool persistent = true; // Watch persistently.
61 const bool success = MessageLoopForIO::current()->WatchFileDescriptor(
62 file_descriptor,
63 persistent,
64 mode,
65 &file_descriptor_watcher_,
66 this);
67 CHECK(success) << "Unable to allocate memory";
68 }
69
70 // Stops watching the underlying file descriptor.
71 void StopWatching() {
72 file_descriptor_watcher_.StopWatchingFileDescriptor();
73 }
74
75 private:
76 // Implement MessagePumpLibevent::Watcher.
77 virtual void OnFileCanReadWithoutBlocking(int file_descriptor) {
78 const bool success = dbus_watch_handle(raw_watch_, DBUS_WATCH_READABLE);
79 CHECK(success) << "Unable to allocate memory";
80 }
81
82 // Implement MessagePumpLibevent::Watcher.
83 virtual void OnFileCanWriteWithoutBlocking(int file_descriptor) {
84 const bool success = dbus_watch_handle(raw_watch_, DBUS_WATCH_WRITABLE);
85 CHECK(success) << "Unable to allocate memory";
86 }
87
88 DBusWatch* raw_watch_;
89 base::MessagePumpLibevent::FileDescriptorWatcher file_descriptor_watcher_;
90 };
91
92 // The class is used for monitoring the timeout used for D-Bus method
93 // calls.
94 //
95 // Unlike Watch, Timeout is a ref counted object, to ensure that |this| of
96 // the object is is alive when HandleTimeout() is called. It's unlikely
97 // but it may be possible that HandleTimeout() is called after
98 // Bus::OnRemoveTimeout(). That's why we don't simply delete the object in
99 // Bus::OnRemoveTimeout().
100 class Timeout : public base::RefCountedThreadSafe<Timeout> {
101 public:
102 Timeout(DBusTimeout* timeout)
103 : raw_timeout_(timeout),
104 monitoring_is_active_(false),
105 is_completed(false) {
106 dbus_timeout_set_data(raw_timeout_, this, NULL);
107 AddRef(); // Balanced on Complete().
108 }
109
110 // Returns true if the timeout is ready to be monitored.
111 bool IsReadyToBeMonitored() {
112 return dbus_timeout_get_enabled(raw_timeout_);
113 }
114
115 // Starts monitoring the timeout.
116 void StartMonitoring(dbus::Bus* bus) {
117 bus->PostDelayedTaskToDBusThread(FROM_HERE,
118 base::Bind(&Timeout::HandleTimeout,
119 this),
120 GetIntervalInMs());
121 monitoring_is_active_ = true;
122 }
123
124 // Stops monitoring the timeout.
125 void StopMonitoring() {
126 // We cannot take back the delayed task we posted in
127 // StartMonitoring(), so we just mark the monitoring is inactive now.
128 monitoring_is_active_ = false;
129 }
130
131 // Returns the interval in milliseconds.
132 int GetIntervalInMs() {
133 return dbus_timeout_get_interval(raw_timeout_);
134 }
135
136 // Cleans up the raw_timeout and marks that timeout is completed.
137 // See the class comment above for why we are doing this.
138 void Complete() {
139 dbus_timeout_set_data(raw_timeout_, NULL, NULL);
140 is_completed = true;
141 Release();
142 }
143
144 private:
145 friend class base::RefCountedThreadSafe<Timeout>;
146 ~Timeout() {
147 }
148
149 // Handles the timeout.
150 void HandleTimeout() {
151 // If the timeout is marked completed, we should do nothing. This can
152 // occur if this function is called after Bus::OnRemoveTimeout().
153 if (is_completed)
154 return;
155 // Skip if monitoring is cancled.
156 if (!monitoring_is_active_)
157 return;
158
159 const bool success = dbus_timeout_handle(raw_timeout_);
160 CHECK(success) << "Unable to allocate memory";
161 }
162
163 DBusTimeout* raw_timeout_;
164 bool monitoring_is_active_;
165 bool is_completed;
166 };
167
168 } // namespace
169
170 Bus::Options::Options()
171 : bus_type(SESSION),
172 connection_type(PRIVATE),
173 dbus_thread(NULL) {
174 }
175
176 Bus::Options::~Options() {
177 }
178
179 Bus::Bus(const Options& options)
180 : bus_type_(options.bus_type),
181 connection_type_(options.connection_type),
182 dbus_thread_(options.dbus_thread),
183 connection_(NULL),
184 origin_loop_(MessageLoop::current()),
185 origin_thread_id_(base::PlatformThread::CurrentId()),
186 dbus_thread_id_(base::kInvalidThreadId),
187 async_operations_are_set_up_(false),
188 num_pending_watches_(0),
189 num_pending_timeouts_(0) {
190 if (dbus_thread_) {
191 dbus_thread_id_ = dbus_thread_->thread_id();
192 DCHECK(dbus_thread_->IsRunning())
193 << "The D-Bus thread should be running";
194 DCHECK_EQ(MessageLoop::TYPE_IO,
195 dbus_thread_->message_loop()->type())
196 << "The D-Bus thread should have an MessageLoopForIO attached";
197 }
198
199 // This is safe to call multiple times.
200 dbus_threads_init_default();
201 }
202
203 Bus::~Bus() {
204 DCHECK(!connection_);
205 DCHECK(owned_service_names_.empty());
206 DCHECK_EQ(0, num_pending_watches_);
207 DCHECK_EQ(0, num_pending_timeouts_);
208 }
209
210 ObjectProxy* Bus::GetObjectProxy(const std::string& service_name,
211 const std::string& object_path) {
212 AssertOnOriginThread();
213
214 scoped_refptr<ObjectProxy> object_proxy =
215 new ObjectProxy(this, service_name, object_path);
216 object_proxies_.push_back(object_proxy);
217
218 return object_proxy;
219 }
220
221 ExportedObject* Bus::GetExportedObject(const std::string& service_name,
222 const std::string& object_path) {
223 AssertOnOriginThread();
224
225 scoped_refptr<ExportedObject> exported_object =
226 new ExportedObject(this, service_name, object_path);
227 exported_objects_.push_back(exported_object);
228
229 return exported_object;
230 }
231
232 bool Bus::Connect() {
233 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
234 AssertOnDBusThread();
235
236 // Check if it's already initialized.
237 if (connection_)
238 return true;
239
240 ScopedDBusError error;
241 const DBusBusType dbus_bus_type = static_cast<DBusBusType>(bus_type_);
242 if (connection_type_ == PRIVATE) {
243 connection_ = dbus_bus_get_private(dbus_bus_type, error.get());
244 } else {
245 connection_ = dbus_bus_get(dbus_bus_type, error.get());
246 }
247 if (!connection_) {
248 LOG(ERROR) << "Failed to connect to the bus: "
249 << (dbus_error_is_set(error.get()) ? error.message() : "");
250 return false;
251 }
252 // We shouldn't exit on the disconnected signal.
253 dbus_connection_set_exit_on_disconnect(connection_, false);
254
255 return true;
256 }
257
258 void Bus::ShutdownAndBlock() {
259 AssertOnDBusThread();
260
261 // Unregister the exported objects.
262 for (size_t i = 0; i < exported_objects_.size(); ++i) {
263 exported_objects_[i]->Unregister();
264 }
265
266 // Release all service names.
267 for (std::set<std::string>::iterator iter = owned_service_names_.begin();
268 iter != owned_service_names_.end();) {
269 // This is a bit tricky but we should increment the iter here as
270 // ReleaseOwnership() may remove |service_name| from the set.
271 const std::string& service_name = *iter++;
272 ReleaseOwnership(service_name);
273 }
274 if (!owned_service_names_.empty()) {
275 LOG(ERROR) << "Failed to release all service names. # of services left: "
276 << owned_service_names_.size();
277 }
278
279 // Private connection should be closed.
280 if (connection_ && connection_type_ == PRIVATE) {
281 dbus_connection_close(connection_);
282 }
283 // dbus_connection_close() won't unref.
284 dbus_connection_unref(connection_);
285
286 connection_ = NULL;
287 }
288
289 void Bus::Shutdown(OnShutdownCallback callback) {
290 AssertOnOriginThread();
291
292 PostTaskToDBusThread(FROM_HERE, base::Bind(&Bus::ShutdownInternal,
293 this,
294 callback));
295 }
296
297 bool Bus::RequestOwnership(const std::string& service_name) {
298 DCHECK(connection_);
299 // dbus_bus_request_name() is a blocking call.
300 AssertOnDBusThread();
301
302 // Check if we already own the service name.
303 if (owned_service_names_.find(service_name) != owned_service_names_.end()) {
304 return true;
305 }
306
307 ScopedDBusError error;
308 const int result = dbus_bus_request_name(connection_,
309 service_name.c_str(),
310 DBUS_NAME_FLAG_DO_NOT_QUEUE,
311 error.get());
312 if (result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
313 LOG(ERROR) << "Failed to get the onwership of " << service_name << ": "
314 << (dbus_error_is_set(error.get()) ? error.message() : "");
315 return false;
316 }
317 owned_service_names_.insert(service_name);
318 return true;
319 }
320
321 bool Bus::ReleaseOwnership(const std::string& service_name) {
322 DCHECK(connection_);
323 // dbus_bus_request_name() is a blocking call.
324 AssertOnDBusThread();
325
326 // Check if we already own the service name.
327 std::set<std::string>::iterator found =
328 owned_service_names_.find(service_name);
329 if (found == owned_service_names_.end()) {
330 LOG(ERROR) << service_name << " is not owned by the bus";
331 return false;
332 }
333
334 ScopedDBusError error;
335 const int result = dbus_bus_release_name(connection_, service_name.c_str(),
336 error.get());
337 if (result == DBUS_RELEASE_NAME_REPLY_RELEASED) {
338 owned_service_names_.erase(found);
339 return true;
340 } else {
341 LOG(ERROR) << "Failed to release the onwership of " << service_name << ": "
342 << (error.is_set() ? error.message() : "");
343 return false;
344 }
345 }
346
347 bool Bus::SetUpAsyncOperations() {
348 DCHECK(connection_);
349 AssertOnDBusThread();
350
351 if (async_operations_are_set_up_)
352 return true;
353
354 // Process all the incoming data if any, so that OnDispatchStatus() will
355 // be called when the incoming data is ready.
356 ProcessAllIncomingDataIfAny();
357
358 bool success = dbus_connection_set_watch_functions(connection_,
359 &Bus::OnAddWatchThunk,
360 &Bus::OnRemoveWatchThunk,
361 &Bus::OnToggleWatchThunk,
362 this,
363 NULL);
364 CHECK(success) << "Unable to allocate memory";
365
366 // TODO(satorux): Timeout is not yet implemented.
367 success = dbus_connection_set_timeout_functions(connection_,
368 &Bus::OnAddTimeoutThunk,
369 &Bus::OnRemoveTimeoutThunk,
370 &Bus::OnToggleTimeoutThunk,
371 this,
372 NULL);
373 CHECK(success) << "Unable to allocate memory";
374
375 dbus_connection_set_dispatch_status_function(
376 connection_,
377 &Bus::OnDispatchStatusChangedThunk,
378 this,
379 NULL);
380
381 async_operations_are_set_up_ = true;
382
383 return true;
384 }
385
386 DBusMessage* Bus::SendWithReplyAndBlock(DBusMessage* request,
387 int timeout_ms,
388 DBusError* error) {
389 DCHECK(connection_);
390 AssertOnDBusThread();
391
392 return dbus_connection_send_with_reply_and_block(
393 connection_, request, timeout_ms, error);
394 }
395
396 void Bus::SendWithReply(DBusMessage* request,
397 DBusPendingCall** pending_call,
398 int timeout_ms) {
399 DCHECK(connection_);
400 AssertOnDBusThread();
401
402 const bool success = dbus_connection_send_with_reply(
403 connection_, request, pending_call, timeout_ms);
404 CHECK(success) << "Unable to allocate memory";
405 }
406
407 bool Bus::TryRegisterObjectPath(const std::string& object_path,
408 const DBusObjectPathVTable* vtable,
409 void* user_data,
410 DBusError* error) {
411 DCHECK(connection_);
412 AssertOnDBusThread();
413
414 return dbus_connection_try_register_object_path(
415 connection_,
416 object_path.c_str(),
417 vtable,
418 user_data,
419 error);
420 }
421
422 void Bus::UnregisterObjectPath(const std::string& object_path) {
423 DCHECK(connection_);
424 AssertOnDBusThread();
425
426 const bool success = dbus_connection_unregister_object_path(
427 connection_,
428 object_path.c_str());
429 CHECK(success) << "Unable to allocate memory";
430 }
431
432 void Bus::ShutdownInternal(OnShutdownCallback callback) {
433 AssertOnDBusThread();
434
435 ShutdownAndBlock();
436 PostTaskToOriginThread(FROM_HERE, callback);
437 }
438
439 void Bus::ProcessAllIncomingDataIfAny() {
440 AssertOnDBusThread();
441
442 // As mentioned at the class comment in .h file, connection_ can be NULL.
443 if (!connection_ || !dbus_connection_get_is_connected(connection_))
444 return;
445
446 if (dbus_connection_get_dispatch_status(connection_) ==
447 DBUS_DISPATCH_DATA_REMAINS) {
448 while (dbus_connection_dispatch(connection_) ==
449 DBUS_DISPATCH_DATA_REMAINS);
450 }
451 }
452
453 void Bus::PostTaskToOriginThread(const tracked_objects::Location& from_here,
454 const base::Closure& task) {
455 origin_loop_->PostTask(from_here, task);
456 }
457
458 void Bus::PostTaskToDBusThread(const tracked_objects::Location& from_here,
459 const base::Closure& task) {
460 if (dbus_thread_)
461 dbus_thread_->message_loop()->PostTask(from_here, task);
462 else
463 origin_loop_->PostTask(from_here, task);
464 }
465
466 void Bus::PostDelayedTaskToDBusThread(
467 const tracked_objects::Location& from_here,
468 const base::Closure& task,
469 int delay_ms) {
470 if (dbus_thread_)
471 dbus_thread_->message_loop()->PostDelayedTask(from_here, task, delay_ms);
472 else
473 origin_loop_->PostDelayedTask(from_here, task, delay_ms);
474 }
475
476 bool Bus::HasDBusThread() {
477 return dbus_thread_ != NULL;
478 }
479
480 void Bus::AssertOnOriginThread() {
481 DCHECK_EQ(origin_thread_id_, base::PlatformThread::CurrentId());
482 }
483
484 void Bus::AssertOnDBusThread() {
485 base::ThreadRestrictions::AssertIOAllowed();
486
487 if (dbus_thread_) {
488 DCHECK_EQ(dbus_thread_id_, base::PlatformThread::CurrentId());
489 } else {
490 AssertOnOriginThread();
491 }
492 }
493
494 dbus_bool_t Bus::OnAddWatch(DBusWatch* raw_watch) {
495 AssertOnDBusThread();
496
497 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
498 Watch* watch = new Watch(raw_watch);
499 if (watch->IsReadyToBeWatched()) {
500 watch->StartWatching();
501 }
502 ++num_pending_watches_;
503 return true;
504 }
505
506 void Bus::OnRemoveWatch(DBusWatch* raw_watch) {
507 AssertOnDBusThread();
508
509 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
510 delete watch;
511 --num_pending_watches_;
512 }
513
514 void Bus::OnToggleWatch(DBusWatch* raw_watch) {
515 AssertOnDBusThread();
516
517 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
518 if (watch->IsReadyToBeWatched()) {
519 watch->StartWatching();
520 } else {
521 // It's safe to call this if StartWatching() wasn't called, per
522 // message_pump_libevent.h.
523 watch->StopWatching();
524 }
525 }
526
527 dbus_bool_t Bus::OnAddTimeout(DBusTimeout* raw_timeout) {
528 AssertOnDBusThread();
529
530 // timeout will be deleted when raw_timeout is removed in
531 // OnRemoveTimeoutThunk().
532 Timeout* timeout = new Timeout(raw_timeout);
533 if (timeout->IsReadyToBeMonitored()) {
534 timeout->StartMonitoring(this);
535 }
536 ++num_pending_timeouts_;
537 return true;
538 }
539
540 void Bus::OnRemoveTimeout(DBusTimeout* raw_timeout) {
541 AssertOnDBusThread();
542
543 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
544 timeout->Complete();
545 --num_pending_timeouts_;
546 }
547
548 void Bus::OnToggleTimeout(DBusTimeout* raw_timeout) {
549 AssertOnDBusThread();
550
551 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
552 if (timeout->IsReadyToBeMonitored()) {
553 timeout->StartMonitoring(this);
554 } else {
555 timeout->StopMonitoring();
556 }
557 }
558
559 void Bus::OnDispatchStatusChanged(DBusConnection* connection,
560 DBusDispatchStatus status) {
561 DCHECK_EQ(connection, connection_);
562 AssertOnDBusThread();
563
564 if (!dbus_connection_get_is_connected(connection))
565 return;
566
567 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
568 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
569 // prohibited by the D-Bus library. Hence, we post a task here instead.
570 // See comments for dbus_connection_set_dispatch_status_function().
571 PostTaskToDBusThread(FROM_HERE,
572 base::Bind(&Bus::ProcessAllIncomingDataIfAny,
573 this));
574 }
575
576 dbus_bool_t Bus::OnAddWatchThunk(DBusWatch* raw_watch, void* data) {
577 Bus* self = static_cast<Bus*>(data);
578 return self->OnAddWatch(raw_watch);
579 }
580
581 void Bus::OnRemoveWatchThunk(DBusWatch* raw_watch, void* data) {
582 Bus* self = static_cast<Bus*>(data);
583 return self->OnRemoveWatch(raw_watch);
584 }
585
586 void Bus::OnToggleWatchThunk(DBusWatch* raw_watch, void* data) {
587 Bus* self = static_cast<Bus*>(data);
588 return self->OnToggleWatch(raw_watch);
589 }
590
591 dbus_bool_t Bus::OnAddTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
592 Bus* self = static_cast<Bus*>(data);
593 return self->OnAddTimeout(raw_timeout);
594 }
595
596 void Bus::OnRemoveTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
597 Bus* self = static_cast<Bus*>(data);
598 return self->OnRemoveTimeout(raw_timeout);
599 }
600
601 void Bus::OnToggleTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
602 Bus* self = static_cast<Bus*>(data);
603 return self->OnToggleTimeout(raw_timeout);
604 }
605
606 void Bus::OnDispatchStatusChangedThunk(DBusConnection* connection,
607 DBusDispatchStatus status,
608 void* data) {
609 Bus* self = static_cast<Bus*>(data);
610 return self->OnDispatchStatusChanged(connection, status);
611 }
612
613 } // namespace dbus
OLDNEW
« no previous file with comments | « dbus/bus.h ('k') | dbus/dbus.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698