8a0dba1171e33e762e90b1331a283b2f62c78441
[oweals/gnunet.git] / src / arm / test_exponential_backoff.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file arm/test_exponential_backoff.c
22  * @brief testcase for gnunet-service-arm.c
23  */
24 #include "platform.h"
25 #include "gnunet_arm_service.h"
26 #include "gnunet_client_lib.h"
27 #include "gnunet_configuration_lib.h"
28 #include "gnunet_program_lib.h"
29 #include "gnunet_protocols.h"
30
31 #define START_ARM GNUNET_YES
32
33 #define LOG_BACKOFF GNUNET_NO
34
35 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
36
37 #define SERVICE_TEST_TIMEOUT GNUNET_TIME_UNIT_FOREVER_REL
38
39 #define FIVE_MILLISECONDS GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 5)
40
41
42 static const struct GNUNET_CONFIGURATION_Handle *cfg;
43
44 static struct GNUNET_ARM_Handle *arm;
45
46 static struct GNUNET_ARM_MonitorHandle *mon;
47
48 static int ok = 1;
49
50 static int phase = 0;
51
52 static int trialCount;
53
54 static struct GNUNET_TIME_Absolute startedWaitingAt;
55
56 struct GNUNET_TIME_Relative waitedFor;
57
58 struct GNUNET_TIME_Relative waitedFor_prev;
59
60 #if LOG_BACKOFF
61 static FILE *killLogFilePtr;
62
63 static char *killLogFileName;
64 #endif
65
66
67 /**
68  * Context for handling the shutdown of a service.
69  */
70 struct ShutdownContext
71 {
72   /**
73    * Connection to the service that is being shutdown.
74    */
75   struct GNUNET_CLIENT_Connection *sock;
76
77   /**
78    * Time allowed for shutdown to happen.
79    */
80   struct GNUNET_TIME_Absolute timeout;
81
82   /**
83    * Task set up to cancel the shutdown request on timeout.
84    */
85   GNUNET_SCHEDULER_TaskIdentifier cancel_task;
86
87   /**
88    * Task to call once shutdown complete
89    */
90   GNUNET_CLIENT_ShutdownTask cont;
91
92   /**
93    * Closure for shutdown continuation
94    */
95   void *cont_cls;
96
97   /**
98    * We received a confirmation that the service will shut down.
99    */
100   int confirmed;
101
102 };
103
104 /**
105  * Handler receiving response to service shutdown requests.
106  * We expect it to be called with NULL, since the service that
107  * we are shutting down will just die without replying.
108  *
109  * @param cls closure
110  * @param msg NULL, indicating socket closure.
111  */
112 static void
113 service_shutdown_handler (void *cls, const struct GNUNET_MessageHeader *msg)
114 {
115   struct ShutdownContext *shutdown_ctx = cls;
116
117   if (NULL == msg) 
118   {
119     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service shutdown complete.\n");
120     if (shutdown_ctx->cont != NULL)
121       shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_NO);
122     
123     GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task);
124     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
125     GNUNET_free (shutdown_ctx);
126     return;
127   }
128   GNUNET_assert (0);
129 }
130
131
132 /**
133  * Shutting down took too long, cancel receive and return error.
134  *
135  * @param cls closure
136  * @param tc context information (why was this task triggered now)
137  */
138 void
139 service_shutdown_cancel (void *cls,
140                          const struct GNUNET_SCHEDULER_TaskContext *tc)
141 {
142   struct ShutdownContext *shutdown_ctx = cls;
143
144   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "service_shutdown_cancel called!\n");
145   shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
146   GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
147   GNUNET_free (shutdown_ctx);
148 }
149
150
151 /**
152  * If possible, write a shutdown message to the target
153  * buffer and destroy the client connection.
154  *
155  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
156  * @param size number of bytes available in buf
157  * @param buf NULL on error, otherwise target buffer
158  * @return number of bytes written to buf
159  */
160 static size_t
161 write_shutdown (void *cls, size_t size, void *buf)
162 {
163   struct GNUNET_MessageHeader *msg;
164   struct ShutdownContext *shutdown_ctx = cls;
165
166   if (size < sizeof (struct GNUNET_MessageHeader))
167   {
168     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
169         _("Failed to transmit shutdown request to client.\n"));
170     FPRINTF (stderr, "%s", "Failed to send a shutdown request\n");
171     shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
172     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
173     GNUNET_free (shutdown_ctx);
174     return 0;                   /* client disconnected */
175   }
176
177   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
178                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
179   shutdown_ctx->cancel_task = GNUNET_SCHEDULER_add_delayed (
180       GNUNET_TIME_absolute_get_remaining (shutdown_ctx->timeout),
181       &service_shutdown_cancel, shutdown_ctx);
182   msg = (struct GNUNET_MessageHeader *) buf;
183   msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_STOP);
184   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
185   strcpy ((char *) &msg[1], "do-nothing");
186   FPRINTF (stderr, "%s", "Sent a shutdown request\n");
187   return sizeof (struct GNUNET_MessageHeader) + strlen ("do-nothing") + 1;
188 }
189
190
191 /**
192  * Request that the service should shutdown.
193  * Afterwards, the connection will automatically be
194  * disconnected.  Hence the "sock" should not
195  * be used by the caller after this call
196  * (calling this function frees "sock" after a while).
197  *
198  * @param sock the socket connected to the service
199  * @param timeout how long to wait before giving up on transmission
200  * @param cont continuation to call once the service is really down
201  * @param cont_cls closure for continuation
202  *
203  */
204 static void
205 do_nothing_service_shutdown (struct GNUNET_CLIENT_Connection *sock,
206                       struct GNUNET_TIME_Relative timeout,
207                       GNUNET_CLIENT_ShutdownTask cont, void *cont_cls)
208 {
209   struct ShutdownContext *shutdown_ctx;
210
211   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
212   shutdown_ctx->cont = cont;
213   shutdown_ctx->cont_cls = cont_cls;
214   shutdown_ctx->sock = sock;
215   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
216   GNUNET_CLIENT_notify_transmit_ready (sock,
217                                        sizeof (struct GNUNET_MessageHeader) + strlen ("do-nothing") + 1,
218                                        timeout, GNUNET_NO, &write_shutdown,
219                                        shutdown_ctx);
220 }
221
222 static void
223 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc);
224
225 static void
226 shutdown_cont (void *cls, int reason)
227 {
228   if (GNUNET_NO != reason)
229   {
230     /* Re-try shutdown */
231     FPRINTF (stderr, "%s", "do-nothing didn't die, trying again\n");
232     GNUNET_SCHEDULER_add_now (kill_task, NULL);
233     return;
234   }
235   startedWaitingAt = GNUNET_TIME_absolute_get ();
236   FPRINTF (stderr, "%s", "do-nothing is dead, starting the countdown\n");
237 }
238
239 static void
240 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc)
241 {
242   static struct GNUNET_CLIENT_Connection *doNothingConnection = NULL;
243
244   if (NULL != cbData)
245   {
246     waitedFor = GNUNET_TIME_absolute_get_duration (startedWaitingAt);
247     FPRINTF (stderr, "Waited for: %llu ms\n", waitedFor.rel_value);
248 #if LOG_BACKOFF
249     FPRINTF (killLogFilePtr, "Waited for: %llu ms\n",
250       (unsigned long long) waitedFor.rel_value);
251 #endif
252   }
253   else
254   {
255     waitedFor.rel_value = 0;
256   }
257   /* Connect to the doNothing task */
258   doNothingConnection = GNUNET_CLIENT_connect ("do-nothing", cfg);
259   GNUNET_assert (doNothingConnection != NULL);
260   if (trialCount == 12)
261     waitedFor_prev = waitedFor;
262   else if (trialCount == 13)
263   {
264     GNUNET_CLIENT_disconnect (doNothingConnection);
265     GNUNET_ARM_request_service_stop (arm, "do-nothing", TIMEOUT, NULL, NULL);
266     if (waitedFor_prev.rel_value >= waitedFor.rel_value)
267       ok = 9;
268     else
269       ok = 0;
270     trialCount += 1;
271     return;
272   }
273   trialCount += 1;
274   /* Use the created connection to kill the doNothingTask */
275   do_nothing_service_shutdown (doNothingConnection,
276       TIMEOUT, &shutdown_cont, NULL);
277 }
278
279 static void
280 trigger_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
281 {
282   GNUNET_ARM_disconnect (arm);
283   GNUNET_ARM_monitor_disconnect (mon);
284 }
285
286
287 static void
288 arm_stop_cb (void *cls, struct GNUNET_ARM_Handle *h, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
289 {
290   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
291   GNUNET_break (result == GNUNET_ARM_RESULT_STOPPING);
292   FPRINTF (stderr, "%s", "ARM service stopped\n");
293   GNUNET_SCHEDULER_add_now (trigger_disconnect, NULL);
294 }
295
296 void
297 srv_status (void *cls, struct GNUNET_ARM_MonitorHandle *mon, const char *service, enum GNUNET_ARM_ServiceStatus status)
298 {
299   FPRINTF (stderr, "Service %s is %u, phase %u\n", service, status, phase);
300   if (status == GNUNET_ARM_SERVICE_MONITORING_STARTED)
301   {
302     phase++;
303     GNUNET_ARM_request_service_start (arm, "do-nothing",
304         GNUNET_OS_INHERIT_STD_OUT_AND_ERR, TIMEOUT, NULL, NULL);
305     return;
306   }
307   if (phase == 1)
308   {
309     GNUNET_break (status == GNUNET_ARM_SERVICE_STARTING);
310     GNUNET_break (0 == strcasecmp (service, "do-nothing"));
311     GNUNET_break (phase == 1);
312     FPRINTF (stderr, "%s", "do-nothing is starting\n");
313     phase++;
314     ok = 1;
315     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &kill_task, NULL);
316   }
317   else if ((phase == 2) && (strcasecmp ("do-nothing", service) == 0))
318   {
319     /* We passively monitor ARM for status updates. ARM should tell us
320      * when do-nothing dies (no need to run a service upness test ourselves).
321      */
322     if (status == GNUNET_ARM_SERVICE_STARTING)
323     {
324       FPRINTF (stderr, "%s", "do-nothing is starting\n");
325       GNUNET_SCHEDULER_add_now (kill_task, &ok);
326     }
327     else if ((status == GNUNET_ARM_SERVICE_STOPPED) && (trialCount == 14))
328     {
329       phase++;
330       GNUNET_ARM_request_service_stop (arm, "arm", TIMEOUT, arm_stop_cb, NULL);
331     }
332   }
333 }
334
335 static void
336 arm_start_cb (void *cls, struct GNUNET_ARM_Handle *h, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
337 {
338   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
339   GNUNET_break (result == GNUNET_ARM_RESULT_STARTING);
340   GNUNET_break (phase == 0);
341   FPRINTF (stderr, "Sent 'START' request for arm to ARM %s\n", (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully");
342 }
343
344 static void
345 task (void *cls, char *const *args, const char *cfgfile,
346       const struct GNUNET_CONFIGURATION_Handle *c)
347 {
348   char *armconfig;
349   cfg = c;
350   if (NULL != cfgfile)
351   {
352     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "arm",
353         "CONFIG", &armconfig))
354     {
355       GNUNET_CONFIGURATION_set_value_string ((struct GNUNET_CONFIGURATION_Handle
356                                               *) cfg, "arm", "CONFIG",
357                                              cfgfile);
358     }
359     else
360       GNUNET_free (armconfig);
361   }
362
363   arm = GNUNET_ARM_alloc (cfg);
364   GNUNET_ARM_connect (arm, NULL, NULL);
365   mon = GNUNET_ARM_monitor_alloc (cfg);
366   GNUNET_ARM_monitor (mon, srv_status, NULL);
367 #if START_ARM
368   GNUNET_ARM_request_service_start (arm, "arm",
369       GNUNET_OS_INHERIT_STD_OUT_AND_ERR, GNUNET_TIME_UNIT_ZERO, arm_start_cb, NULL);
370 #else
371   arm_start_cb (NULL, arm, GNUNET_ARM_REQUEST_SENT_OK, "arm", GNUNET_ARM_SERVICE_STARTING);
372 #endif
373 }
374
375 static int
376 check ()
377 {
378   char *const argv[] = {
379     "test-exponential-backoff",
380     "-c", "test_arm_api_data.conf",
381     NULL
382   };
383   struct GNUNET_GETOPT_CommandLineOption options[] = {
384     GNUNET_GETOPT_OPTION_END
385   };
386
387   /* Running ARM  and running the do_nothing task */
388   GNUNET_assert (GNUNET_OK ==
389                  GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
390                                      argv, "test-exponential-backoff",
391                                      "nohelp", options, &task, NULL));
392
393
394   return ok;
395 }
396
397 static int
398 init ()
399 {
400 #if LOG_BACKOFF
401   killLogFileName = GNUNET_DISK_mktemp ("exponential-backoff-waiting.log");
402   if (NULL == (killLogFilePtr = FOPEN (killLogFileName, "w")))
403     {
404       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fopen",
405                                 killLogFileName);
406       GNUNET_free (killLogFileName);
407       return GNUNET_SYSERR;
408     }
409 #endif
410   return GNUNET_OK;
411 }
412
413
414 static void
415 houseKeep ()
416 {
417 #if LOG_BACKOFF
418   GNUNET_assert (0 == fclose (killLogFilePtr));
419   GNUNET_free (killLogFileName);
420 #endif
421 }
422
423
424 int
425 main (int argc, char *argv[])
426 {
427   int ret;
428
429   GNUNET_log_setup ("test-exponential-backoff",
430                     "WARNING",
431                     NULL);
432
433   init ();
434   ret = check ();
435   houseKeep ();
436   return ret;
437 }
438
439 /* end of test_exponential_backoff.c */