GDBus: Use call() instead of invoke_method()
[platform/upstream/glib.git] / gio / tests / gdbus-threading.c
1 /* GLib testing framework examples and tests
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include <gio/gio.h>
24 #include <unistd.h>
25 #include <string.h>
26
27 #include "gdbus-tests.h"
28
29 /* all tests rely on a global connection */
30 static GDBusConnection *c = NULL;
31
32 /* all tests rely on a shared mainloop */
33 static GMainLoop *loop = NULL;
34
35 /* ---------------------------------------------------------------------------------------------------- */
36 /* Ensure that signal and method replies are delivered in the right thread */
37 /* ---------------------------------------------------------------------------------------------------- */
38
39 typedef struct {
40   GThread *thread;
41   GMainLoop *thread_loop;
42   guint signal_count;
43 } DeliveryData;
44
45 static void
46 msg_cb_expect_success (GDBusConnection *connection,
47                        GAsyncResult    *res,
48                        gpointer         user_data)
49 {
50   DeliveryData *data = user_data;
51   GError *error;
52   GVariant *result;
53
54   error = NULL;
55   result = g_dbus_connection_call_finish (connection,
56                                           res,
57                                           &error);
58   g_assert_no_error (error);
59   g_assert (result != NULL);
60   g_variant_unref (result);
61
62   g_assert (g_thread_self () == data->thread);
63
64   g_main_loop_quit (data->thread_loop);
65 }
66
67 static void
68 msg_cb_expect_error_cancelled (GDBusConnection *connection,
69                                GAsyncResult    *res,
70                                gpointer         user_data)
71 {
72   DeliveryData *data = user_data;
73   GError *error;
74   GVariant *result;
75
76   error = NULL;
77   result = g_dbus_connection_call_finish (connection,
78                                           res,
79                                           &error);
80   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
81   g_assert (!g_dbus_error_is_remote_error (error));
82   g_error_free (error);
83   g_assert (result == NULL);
84
85   g_assert (g_thread_self () == data->thread);
86
87   g_main_loop_quit (data->thread_loop);
88 }
89
90 static void
91 signal_handler (GDBusConnection *connection,
92                 const gchar      *sender_name,
93                 const gchar      *object_path,
94                 const gchar      *interface_name,
95                 const gchar      *signal_name,
96                 GVariant         *parameters,
97                 gpointer         user_data)
98 {
99   DeliveryData *data = user_data;
100
101   g_assert (g_thread_self () == data->thread);
102
103   data->signal_count++;
104
105   g_main_loop_quit (data->thread_loop);
106 }
107
108 static gpointer
109 test_delivery_in_thread_func (gpointer _data)
110 {
111   GMainLoop *thread_loop;
112   GMainContext *thread_context;
113   DeliveryData data;
114   GCancellable *ca;
115   guint subscription_id;
116   GDBusConnection *priv_c;
117   GError *error;
118
119   error = NULL;
120
121   thread_context = g_main_context_new ();
122   thread_loop = g_main_loop_new (thread_context, FALSE);
123   g_main_context_push_thread_default (thread_context);
124
125   data.thread = g_thread_self ();
126   data.thread_loop = thread_loop;
127   data.signal_count = 0;
128
129   /* ---------------------------------------------------------------------------------------------------- */
130
131   /*
132    * Check that we get a reply to the GetId() method call.
133    */
134   g_dbus_connection_call (c,
135                           "org.freedesktop.DBus",  /* bus_name */
136                           "/org/freedesktop/DBus", /* object path */
137                           "org.freedesktop.DBus",  /* interface name */
138                           "GetId",                 /* method name */
139                           NULL,
140                           G_DBUS_CALL_FLAGS_NONE,
141                           -1,
142                           NULL,
143                           (GAsyncReadyCallback) msg_cb_expect_success,
144                           &data);
145   g_main_loop_run (thread_loop);
146
147   /*
148    * Check that we never actually send a message if the GCancellable
149    * is already cancelled - i.e.  we should get #G_IO_ERROR_CANCELLED
150    * when the actual connection is not up.
151    */
152   ca = g_cancellable_new ();
153   g_cancellable_cancel (ca);
154   g_dbus_connection_call (c,
155                           "org.freedesktop.DBus",  /* bus_name */
156                           "/org/freedesktop/DBus", /* object path */
157                           "org.freedesktop.DBus",  /* interface name */
158                           "GetId",                 /* method name */
159                           NULL,
160                           G_DBUS_CALL_FLAGS_NONE,
161                           -1,
162                           ca,
163                           (GAsyncReadyCallback) msg_cb_expect_error_cancelled,
164                           &data);
165   g_main_loop_run (thread_loop);
166   g_object_unref (ca);
167
168   /*
169    * Check that cancellation works when the message is already in flight.
170    */
171   ca = g_cancellable_new ();
172   g_dbus_connection_call (c,
173                           "org.freedesktop.DBus",  /* bus_name */
174                           "/org/freedesktop/DBus", /* object path */
175                           "org.freedesktop.DBus",  /* interface name */
176                           "GetId",                 /* method name */
177                           NULL,
178                           G_DBUS_CALL_FLAGS_NONE,
179                           -1,
180                           ca,
181                           (GAsyncReadyCallback) msg_cb_expect_error_cancelled,
182                           &data);
183   g_cancellable_cancel (ca);
184   g_main_loop_run (thread_loop);
185   g_object_unref (ca);
186
187   /*
188    * Check that signals are delivered to the correct thread.
189    *
190    * First we subscribe to the signal, then we create a a private
191    * connection. This should cause a NameOwnerChanged message from
192    * the message bus.
193    */
194   subscription_id = g_dbus_connection_signal_subscribe (c,
195                                                         "org.freedesktop.DBus",  /* sender */
196                                                         "org.freedesktop.DBus",  /* interface */
197                                                         "NameOwnerChanged",      /* member */
198                                                         "/org/freedesktop/DBus", /* path */
199                                                         NULL,
200                                                         signal_handler,
201                                                         &data,
202                                                         NULL);
203   g_assert (subscription_id != 0);
204   g_assert (data.signal_count == 0);
205
206   priv_c = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, &error);
207   g_assert_no_error (error);
208   g_assert (priv_c != NULL);
209
210   g_main_loop_run (thread_loop);
211   g_assert (data.signal_count == 1);
212
213   g_object_unref (priv_c);
214
215   g_dbus_connection_signal_unsubscribe (c, subscription_id);
216
217   /* ---------------------------------------------------------------------------------------------------- */
218
219   g_main_context_pop_thread_default (thread_context);
220   g_main_loop_unref (thread_loop);
221   g_main_context_unref (thread_context);
222
223   g_main_loop_quit (loop);
224
225   return NULL;
226 }
227
228 static void
229 test_delivery_in_thread (void)
230 {
231   GError *error;
232   GThread *thread;
233
234   error = NULL;
235   thread = g_thread_create (test_delivery_in_thread_func,
236                             NULL,
237                             TRUE,
238                             &error);
239   g_assert_no_error (error);
240   g_assert (thread != NULL);
241
242   /* run the event loop - it is needed to dispatch D-Bus messages */
243   g_main_loop_run (loop);
244
245   g_thread_join (thread);
246 }
247
248 /* ---------------------------------------------------------------------------------------------------- */
249
250 typedef struct {
251   GDBusProxy *proxy;
252   gint msec;
253   guint num;
254   gboolean async;
255
256   GMainLoop *thread_loop;
257   GThread *thread;
258
259   gboolean done;
260 } SyncThreadData;
261
262 static void
263 sleep_cb (GDBusProxy   *proxy,
264           GAsyncResult *res,
265           gpointer      user_data)
266 {
267   SyncThreadData *data = user_data;
268   GError *error;
269   GVariant *result;
270
271   error = NULL;
272   result = g_dbus_proxy_call_finish (proxy,
273                                      res,
274                                      &error);
275   g_assert_no_error (error);
276   g_assert (result != NULL);
277   g_assert_cmpstr (g_variant_get_type_string (result), ==, "()");
278   g_variant_unref (result);
279
280   g_assert (data->thread == g_thread_self ());
281
282   g_main_loop_quit (data->thread_loop);
283
284   //g_debug ("async cb (%p)", g_thread_self ());
285 }
286
287 static gpointer
288 test_sleep_in_thread_func (gpointer _data)
289 {
290   SyncThreadData *data = _data;
291   GMainContext *thread_context;
292   guint n;
293
294   thread_context = g_main_context_new ();
295   data->thread_loop = g_main_loop_new (thread_context, FALSE);
296   g_main_context_push_thread_default (thread_context);
297
298   data->thread = g_thread_self ();
299
300   for (n = 0; n < data->num; n++)
301     {
302       if (data->async)
303         {
304           //g_debug ("invoking async (%p)", g_thread_self ());
305           g_dbus_proxy_call (data->proxy,
306                              "Sleep",
307                              g_variant_new ("(i)", data->msec),
308                              G_DBUS_CALL_FLAGS_NONE,
309                              -1,
310                              NULL,
311                              (GAsyncReadyCallback) sleep_cb,
312                              data);
313           g_main_loop_run (data->thread_loop);
314           g_print ("A");
315           //g_debug ("done invoking async (%p)", g_thread_self ());
316         }
317       else
318         {
319           GError *error;
320           GVariant *result;
321
322           error = NULL;
323           //g_debug ("invoking sync (%p)", g_thread_self ());
324           result = g_dbus_proxy_call_sync (data->proxy,
325                                            "Sleep",
326                                            g_variant_new ("(i)", data->msec),
327                                            G_DBUS_CALL_FLAGS_NONE,
328                                            -1,
329                                            NULL,
330                                            &error);
331           g_print ("S");
332           //g_debug ("done invoking sync (%p)", g_thread_self ());
333           g_assert_no_error (error);
334           g_assert (result != NULL);
335           g_assert_cmpstr (g_variant_get_type_string (result), ==, "()");
336           g_variant_unref (result);
337         }
338     }
339
340   g_main_context_pop_thread_default (thread_context);
341   g_main_loop_unref (data->thread_loop);
342   g_main_context_unref (thread_context);
343
344   data->done = TRUE;
345   g_main_loop_quit (loop);
346
347   return NULL;
348 }
349
350 static void
351 on_proxy_appeared (GDBusConnection *connection,
352                    const gchar     *name,
353                    const gchar     *name_owner,
354                    GDBusProxy      *proxy,
355                    gpointer         user_data)
356 {
357   guint n;
358
359   /*
360    * Check that multiple threads can do calls without interferring with
361    * each other. We do this by creating three threads that call the
362    * Sleep() method on the server (which handles it asynchronously, e.g.
363    * it won't block other requests) with different sleep durations and
364    * a number of times. We do this so each set of calls add up to 4000
365    * milliseconds.
366    *
367    * We run this test twice - first with async calls in each thread, then
368    * again with sync calls
369    */
370
371   for (n = 0; n < 2; n++)
372     {
373       gboolean do_async;
374       GThread *thread1;
375       GThread *thread2;
376       GThread *thread3;
377       SyncThreadData data1;
378       SyncThreadData data2;
379       SyncThreadData data3;
380       GError *error;
381       GTimeVal start_time;
382       GTimeVal end_time;
383       guint elapsed_msec;
384
385       error = NULL;
386       do_async = (n == 0);
387
388       g_get_current_time (&start_time);
389
390       data1.proxy = proxy;
391       data1.msec = 40;
392       data1.num = 100;
393       data1.async = do_async;
394       data1.done = FALSE;
395       thread1 = g_thread_create (test_sleep_in_thread_func,
396                                  &data1,
397                                  TRUE,
398                                  &error);
399       g_assert_no_error (error);
400       g_assert (thread1 != NULL);
401
402       data2.proxy = proxy;
403       data2.msec = 20;
404       data2.num = 200;
405       data2.async = do_async;
406       data2.done = FALSE;
407       thread2 = g_thread_create (test_sleep_in_thread_func,
408                                  &data2,
409                                  TRUE,
410                                  &error);
411       g_assert_no_error (error);
412       g_assert (thread2 != NULL);
413
414       data3.proxy = proxy;
415       data3.msec = 100;
416       data3.num = 40;
417       data3.async = do_async;
418       data3.done = FALSE;
419       thread3 = g_thread_create (test_sleep_in_thread_func,
420                                  &data3,
421                                  TRUE,
422                                  &error);
423       g_assert_no_error (error);
424       g_assert (thread3 != NULL);
425
426       /* we handle messages in the main loop - threads will quit it when they are done */
427       while (!(data1.done && data2.done && data3.done))
428         g_main_loop_run (loop);
429
430       g_thread_join (thread1);
431       g_thread_join (thread2);
432       g_thread_join (thread3);
433
434       g_get_current_time (&end_time);
435
436       elapsed_msec = ((end_time.tv_sec * G_USEC_PER_SEC + end_time.tv_usec) -
437                       (start_time.tv_sec * G_USEC_PER_SEC + start_time.tv_usec)) / 1000;
438
439       //g_debug ("Elapsed time for %s = %d msec", n == 0 ? "async" : "sync", elapsed_msec);
440
441       /* elapsed_msec should be 4000 msec + change for overhead */
442       g_assert_cmpint (elapsed_msec, >=, 4000);
443       g_assert_cmpint (elapsed_msec,  <, 5000);
444
445       g_print (" ");
446     }
447
448   g_main_loop_quit (loop);
449 }
450
451 static void
452 on_proxy_vanished (GDBusConnection *connection,
453                    const gchar     *name,
454                    gpointer         user_data)
455 {
456 }
457
458 static void
459 test_method_calls_in_thread (void)
460 {
461   guint watcher_id;
462
463   watcher_id = g_bus_watch_proxy (G_BUS_TYPE_SESSION,
464                                   "com.example.TestService",
465                                   G_BUS_NAME_WATCHER_FLAGS_NONE,
466                                   "/com/example/TestObject",
467                                   "com.example.Frob",
468                                   G_TYPE_DBUS_PROXY,
469                                   G_DBUS_PROXY_FLAGS_NONE,
470                                   on_proxy_appeared,
471                                   on_proxy_vanished,
472                                   NULL,
473                                   NULL);
474
475   g_main_loop_run (loop);
476
477   g_bus_unwatch_proxy (watcher_id);
478 }
479
480 /* ---------------------------------------------------------------------------------------------------- */
481
482 int
483 main (int   argc,
484       char *argv[])
485 {
486   GError *error;
487   gint ret;
488
489   g_type_init ();
490   g_thread_init (NULL);
491   g_test_init (&argc, &argv, NULL);
492
493   /* all the tests rely on a shared main loop */
494   loop = g_main_loop_new (NULL, FALSE);
495
496   /* all the tests use a session bus with a well-known address that we can bring up and down
497    * using session_bus_up() and session_bus_down().
498    */
499   g_unsetenv ("DISPLAY");
500   g_setenv ("DBUS_SESSION_BUS_ADDRESS", session_bus_get_temporary_address (), TRUE);
501
502   session_bus_up ();
503
504   /* TODO: wait a bit for the bus to come up.. ideally session_bus_up() won't return
505    * until one can connect to the bus but that's not how things work right now
506    */
507   usleep (500 * 1000);
508
509   /* this is safe; testserver will exit once the bus goes away */
510   g_assert (g_spawn_command_line_async ("./gdbus-testserver.py", NULL));
511
512   /* wait for the service to come up */
513   usleep (500 * 1000);
514
515   /* Create the connection in the main thread */
516   error = NULL;
517   c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
518   g_assert_no_error (error);
519   g_assert (c != NULL);
520
521   g_test_add_func ("/gdbus/delivery-in-thread", test_delivery_in_thread);
522   g_test_add_func ("/gdbus/method-calls-in-thread", test_method_calls_in_thread);
523
524   ret = g_test_run();
525
526   g_object_unref (c);
527
528   /* tear down bus */
529   session_bus_down ();
530
531   return ret;
532 }