- warn on missing cases
[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_util_lib.h"
27 #include "gnunet_protocols.h"
28
29 #define LOG(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
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     LOG ("Failed to send a shutdown request\n");
169     shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
170     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
171     GNUNET_free (shutdown_ctx);
172     return 0;                   /* client disconnected */
173   }
174
175   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
176                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
177   shutdown_ctx->cancel_task = GNUNET_SCHEDULER_add_delayed (
178       GNUNET_TIME_absolute_get_remaining (shutdown_ctx->timeout),
179       &service_shutdown_cancel, shutdown_ctx);
180   msg = (struct GNUNET_MessageHeader *) buf;
181   msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_STOP);
182   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
183   strcpy ((char *) &msg[1], "do-nothing");
184   LOG ("Sent a shutdown request\n");
185   return sizeof (struct GNUNET_MessageHeader) + strlen ("do-nothing") + 1;
186 }
187
188
189 /**
190  * Request that the service should shutdown.
191  * Afterwards, the connection will automatically be
192  * disconnected.  Hence the "sock" should not
193  * be used by the caller after this call
194  * (calling this function frees "sock" after a while).
195  *
196  * @param sock the socket connected to the service
197  * @param timeout how long to wait before giving up on transmission
198  * @param cont continuation to call once the service is really down
199  * @param cont_cls closure for continuation
200  *
201  */
202 static void
203 do_nothing_service_shutdown (struct GNUNET_CLIENT_Connection *sock,
204                       struct GNUNET_TIME_Relative timeout,
205                       GNUNET_CLIENT_ShutdownTask cont, void *cont_cls)
206 {
207   struct ShutdownContext *shutdown_ctx;
208
209   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
210   shutdown_ctx->cont = cont;
211   shutdown_ctx->cont_cls = cont_cls;
212   shutdown_ctx->sock = sock;
213   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
214   GNUNET_CLIENT_notify_transmit_ready (sock,
215                                        sizeof (struct GNUNET_MessageHeader) + strlen ("do-nothing") + 1,
216                                        timeout, GNUNET_NO, &write_shutdown,
217                                        shutdown_ctx);
218 }
219
220
221 static void
222 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc);
223
224
225 static void
226 shutdown_cont (void *cls, int reason)
227 {
228   if (GNUNET_NO != reason)
229   {
230     /* Re-try shutdown */
231     LOG ("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   LOG ("do-nothing is dead, starting the countdown\n");
237 }
238
239
240 static void
241 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc)
242 {
243   static struct GNUNET_CLIENT_Connection *doNothingConnection = NULL;
244
245   if (NULL != cbData)
246   {
247     waitedFor = GNUNET_TIME_absolute_get_duration (startedWaitingAt);
248     LOG ("Waited for: %s\n", 
249          GNUNET_STRINGS_relative_time_to_string (waitedFor, GNUNET_YES));
250   }
251   else
252   {
253     waitedFor.rel_value = 0;
254   }
255   /* Connect to the doNothing task */
256   doNothingConnection = GNUNET_CLIENT_connect ("do-nothing", cfg);
257   GNUNET_assert (doNothingConnection != NULL);
258   if (trialCount == 12)
259     waitedFor_prev = waitedFor;
260   else if (trialCount == 13)
261   {
262     GNUNET_CLIENT_disconnect (doNothingConnection);
263     GNUNET_ARM_request_service_stop (arm, "do-nothing", TIMEOUT, NULL, NULL);
264     if (waitedFor_prev.rel_value >= waitedFor.rel_value)
265       ok = 9;
266     else
267       ok = 0;
268     trialCount += 1;
269     return;
270   }
271   trialCount += 1;
272   /* Use the created connection to kill the doNothingTask */
273   do_nothing_service_shutdown (doNothingConnection,
274       TIMEOUT, &shutdown_cont, NULL);
275 }
276
277
278 static void
279 trigger_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
280 {
281   GNUNET_ARM_disconnect_and_free (arm);
282   GNUNET_ARM_monitor_disconnect_and_free (mon);
283 }
284
285
286 static void
287 arm_stop_cb (void *cls, struct GNUNET_ARM_Handle *h, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
288 {
289   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
290   GNUNET_break (result == GNUNET_ARM_RESULT_STOPPING);
291   LOG ("ARM service stopped\n");
292   GNUNET_SCHEDULER_add_now (trigger_disconnect, NULL);
293 }
294
295
296 static void
297 srv_status (void *cls, struct GNUNET_ARM_MonitorHandle *mon, const char *service, enum GNUNET_ARM_ServiceStatus status)
298 {
299   LOG ("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     LOG ("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       LOG ("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
336 static void
337 arm_start_cb (void *cls, struct GNUNET_ARM_Handle *h, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
338 {
339   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
340   GNUNET_break (result == GNUNET_ARM_RESULT_STARTING);
341   GNUNET_break (phase == 0);
342   LOG ("Sent 'START' request for arm to ARM %s\n", 
343        (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully");
344 }
345
346
347 static void
348 task (void *cls, char *const *args, const char *cfgfile,
349       const struct GNUNET_CONFIGURATION_Handle *c)
350 {
351   char *armconfig;
352   cfg = c;
353   if (NULL != cfgfile)
354   {
355     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "arm",
356         "CONFIG", &armconfig))
357     {
358       GNUNET_CONFIGURATION_set_value_string ((struct GNUNET_CONFIGURATION_Handle
359                                               *) cfg, "arm", "CONFIG",
360                                              cfgfile);
361     }
362     else
363       GNUNET_free (armconfig);
364   }
365
366   arm = GNUNET_ARM_connect (cfg, NULL, NULL);
367   if (NULL != arm)
368   {
369     mon = GNUNET_ARM_monitor (cfg, srv_status, NULL);
370     if (NULL != mon)
371     {
372 #if START_ARM
373       GNUNET_ARM_request_service_start (arm, "arm",
374           GNUNET_OS_INHERIT_STD_OUT_AND_ERR, GNUNET_TIME_UNIT_ZERO, arm_start_cb, NULL);
375 #else
376       arm_start_cb (NULL, arm, GNUNET_ARM_REQUEST_SENT_OK, "arm", GNUNET_ARM_SERVICE_STARTING);
377 #endif
378     }
379     else
380     {
381       GNUNET_ARM_disconnect_and_free (arm);
382       arm = NULL;
383     }
384   }
385 }
386
387
388 static int
389 check ()
390 {
391   char *const argv[] = {
392     "test-exponential-backoff",
393     "-c", "test_arm_api_data.conf",
394     NULL
395   };
396   struct GNUNET_GETOPT_CommandLineOption options[] = {
397     GNUNET_GETOPT_OPTION_END
398   };
399
400   /* Running ARM  and running the do_nothing task */
401   GNUNET_assert (GNUNET_OK ==
402                  GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
403                                      argv, "test-exponential-backoff",
404                                      "nohelp", options, &task, NULL));
405
406
407   return ok;
408 }
409
410
411 static int
412 init ()
413 {
414 #if LOG_BACKOFF
415   killLogFileName = GNUNET_DISK_mktemp ("exponential-backoff-waiting.log");
416   if (NULL == (killLogFilePtr = FOPEN (killLogFileName, "w")))
417     {
418       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fopen",
419                                 killLogFileName);
420       GNUNET_free (killLogFileName);
421       return GNUNET_SYSERR;
422     }
423 #endif
424   return GNUNET_OK;
425 }
426
427
428 static void
429 houseKeep ()
430 {
431 #if LOG_BACKOFF
432   GNUNET_assert (0 == fclose (killLogFilePtr));
433   GNUNET_free (killLogFileName);
434 #endif
435 }
436
437
438 int
439 main (int argc, char *argv[])
440 {
441   int ret;
442
443   GNUNET_log_setup ("test-exponential-backoff",
444                     "WARNING",
445                     NULL);
446
447   init ();
448   ret = check ();
449   houseKeep ();
450   return ret;
451 }
452
453 /* end of test_exponential_backoff.c */