3f33c91e69b28760ae73b9ede6027fc28ec011da
[oweals/gnunet.git] / src / arm / test_exponential_backoff.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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 #define SERVICE "do-nothing"
42
43 #define BINARY "mockup-service"
44
45 #define CFGFILENAME "test_arm_api_data2.conf"
46
47
48 static const struct GNUNET_CONFIGURATION_Handle *cfg;
49
50 static struct GNUNET_ARM_Handle *arm;
51
52 static struct GNUNET_ARM_MonitorHandle *mon;
53
54 static int ok = 1;
55
56 static int phase = 0;
57
58 static int trialCount;
59
60 static struct GNUNET_TIME_Absolute startedWaitingAt;
61
62 struct GNUNET_TIME_Relative waitedFor;
63
64 struct GNUNET_TIME_Relative waitedFor_prev;
65
66 #if LOG_BACKOFF
67 static FILE *killLogFilePtr;
68
69 static char *killLogFileName;
70 #endif
71
72
73 typedef void (*GNUNET_CLIENT_ShutdownTask) (void *cls, int reason);
74
75 /**
76  * Context for handling the shutdown of a service.
77  */
78 struct ShutdownContext
79 {
80   /**
81    * Connection to the service that is being shutdown.
82    */
83   struct GNUNET_CLIENT_Connection *sock;
84
85   /**
86    * Time allowed for shutdown to happen.
87    */
88   struct GNUNET_TIME_Absolute timeout;
89
90   /**
91    * Task set up to cancel the shutdown request on timeout.
92    */
93   struct GNUNET_SCHEDULER_Task *cancel_task;
94
95   /**
96    * Task to call once shutdown complete
97    */
98   GNUNET_CLIENT_ShutdownTask cont;
99
100   /**
101    * Closure for shutdown continuation
102    */
103   void *cont_cls;
104
105   /**
106    * We received a confirmation that the service will shut down.
107    */
108   int confirmed;
109
110 };
111
112 /**
113  * Handler receiving response to service shutdown requests.
114  * We expect it to be called with NULL, since the service that
115  * we are shutting down will just die without replying.
116  *
117  * @param cls closure
118  * @param msg NULL, indicating socket closure.
119  */
120 static void
121 service_shutdown_handler (void *cls, const struct GNUNET_MessageHeader *msg)
122 {
123   struct ShutdownContext *shutdown_ctx = cls;
124
125   if (NULL == msg)
126   {
127     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service shutdown complete.\n");
128     if (shutdown_ctx->cont != NULL)
129       shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_NO);
130
131     GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task);
132     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
133     GNUNET_free (shutdown_ctx);
134     return;
135   }
136   GNUNET_assert (0);
137 }
138
139
140 /**
141  * Shutting down took too long, cancel receive and return error.
142  *
143  * @param cls closure
144  */
145 static void
146 service_shutdown_cancel (void *cls)
147 {
148   struct ShutdownContext *shutdown_ctx = cls;
149
150   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "service_shutdown_cancel called!\n");
151   shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
152   GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
153   GNUNET_free (shutdown_ctx);
154 }
155
156
157 /**
158  * If possible, write a shutdown message to the target
159  * buffer and destroy the client connection.
160  *
161  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
162  * @param size number of bytes available in buf
163  * @param buf NULL on error, otherwise target buffer
164  * @return number of bytes written to buf
165  */
166 static size_t
167 write_shutdown (void *cls, size_t size, void *buf)
168 {
169   struct GNUNET_MessageHeader *msg;
170   struct ShutdownContext *shutdown_ctx = cls;
171
172   if (size < sizeof (struct GNUNET_MessageHeader))
173   {
174     LOG ("Failed to send a shutdown request\n");
175     shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
176     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
177     GNUNET_free (shutdown_ctx);
178     return 0;                   /* client disconnected */
179   }
180
181   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
182                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
183   shutdown_ctx->cancel_task = GNUNET_SCHEDULER_add_delayed (
184       GNUNET_TIME_absolute_get_remaining (shutdown_ctx->timeout),
185       &service_shutdown_cancel, shutdown_ctx);
186   msg = (struct GNUNET_MessageHeader *) buf;
187   msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_STOP);
188   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
189   strcpy ((char *) &msg[1], SERVICE);
190   LOG ("Sent a shutdown request\n");
191   return sizeof (struct GNUNET_MessageHeader) + strlen (SERVICE) + 1;
192 }
193
194
195 /**
196  * Request that the service should shutdown.
197  * Afterwards, the connection will automatically be
198  * disconnected.  Hence the "sock" should not
199  * be used by the caller after this call
200  * (calling this function frees "sock" after a while).
201  *
202  * @param sock the socket connected to the service
203  * @param timeout how long to wait before giving up on transmission
204  * @param cont continuation to call once the service is really down
205  * @param cont_cls closure for continuation
206  *
207  */
208 static void
209 do_nothing_service_shutdown (struct GNUNET_CLIENT_Connection *sock,
210                       struct GNUNET_TIME_Relative timeout,
211                       GNUNET_CLIENT_ShutdownTask cont, void *cont_cls)
212 {
213   struct ShutdownContext *shutdown_ctx;
214
215   shutdown_ctx = GNUNET_new (struct ShutdownContext);
216   shutdown_ctx->cont = cont;
217   shutdown_ctx->cont_cls = cont_cls;
218   shutdown_ctx->sock = sock;
219   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
220   GNUNET_CLIENT_notify_transmit_ready (sock,
221                                        sizeof (struct GNUNET_MessageHeader) + strlen (SERVICE) + 1,
222                                        timeout, GNUNET_NO, &write_shutdown,
223                                        shutdown_ctx);
224 }
225
226
227 static void
228 kill_task (void *cbData);
229
230
231 static void
232 shutdown_cont (void *cls, int reason)
233 {
234   if (GNUNET_NO != reason)
235   {
236     /* Re-try shutdown */
237     LOG ("do-nothing didn't die, trying again\n");
238     GNUNET_SCHEDULER_add_now (&kill_task, NULL);
239     return;
240   }
241   startedWaitingAt = GNUNET_TIME_absolute_get ();
242   LOG ("do-nothing is dead, starting the countdown\n");
243 }
244
245
246 static void
247 kill_task (void *cbData)
248 {
249   static struct GNUNET_CLIENT_Connection *doNothingConnection = NULL;
250
251   if (NULL != cbData)
252   {
253     waitedFor = GNUNET_TIME_absolute_get_duration (startedWaitingAt);
254     LOG ("Waited for: %s\n",
255          GNUNET_STRINGS_relative_time_to_string (waitedFor, GNUNET_YES));
256   }
257   else
258   {
259     waitedFor.rel_value_us = 0;
260   }
261   /* Connect to the doNothing task */
262   doNothingConnection = GNUNET_CLIENT_connect (SERVICE, cfg);
263   GNUNET_assert (doNothingConnection != NULL);
264   if (trialCount == 12)
265     waitedFor_prev = waitedFor;
266   else if (trialCount == 13)
267   {
268     GNUNET_CLIENT_disconnect (doNothingConnection);
269     GNUNET_ARM_request_service_stop (arm, SERVICE, TIMEOUT, NULL, NULL);
270     if (waitedFor_prev.rel_value_us >= waitedFor.rel_value_us)
271       ok = 9;
272     else
273       ok = 0;
274     trialCount += 1;
275     return;
276   }
277   trialCount += 1;
278   /* Use the created connection to kill the doNothingTask */
279   do_nothing_service_shutdown (doNothingConnection,
280       TIMEOUT, &shutdown_cont, NULL);
281 }
282
283
284 static void
285 trigger_disconnect (void *cls)
286 {
287   GNUNET_ARM_disconnect_and_free (arm);
288   GNUNET_ARM_monitor_disconnect_and_free (mon);
289 }
290
291
292 static void
293 arm_stop_cb (void *cls,
294              enum GNUNET_ARM_RequestStatus status,
295              const char *servicename,
296              enum GNUNET_ARM_Result result)
297 {
298   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
299   GNUNET_break (result == GNUNET_ARM_RESULT_STOPPED);
300   LOG ("ARM service stopped\n");
301   GNUNET_SCHEDULER_add_now (&trigger_disconnect, NULL);
302 }
303
304
305 static void
306 srv_status (void *cls, const char *service, enum GNUNET_ARM_ServiceStatus status)
307 {
308   LOG ("Service %s is %u, phase %u\n", service, status, phase);
309   if (status == GNUNET_ARM_SERVICE_MONITORING_STARTED)
310   {
311     phase++;
312     GNUNET_ARM_request_service_start (arm, SERVICE,
313         GNUNET_OS_INHERIT_STD_OUT_AND_ERR, TIMEOUT, NULL, NULL);
314     return;
315   }
316   if (phase == 1)
317   {
318     GNUNET_break (status == GNUNET_ARM_SERVICE_STARTING);
319     GNUNET_break (0 == strcasecmp (service, SERVICE));
320     GNUNET_break (phase == 1);
321     LOG ("do-nothing is starting\n");
322     phase++;
323     ok = 1;
324     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
325                                   &kill_task, NULL);
326   }
327   else if ((phase == 2) && (strcasecmp (SERVICE, service) == 0))
328   {
329     /* We passively monitor ARM for status updates. ARM should tell us
330      * when do-nothing dies (no need to run a service upness test ourselves).
331      */
332     if (status == GNUNET_ARM_SERVICE_STARTING)
333     {
334       LOG ("do-nothing is starting\n");
335       GNUNET_SCHEDULER_add_now (&kill_task, &ok);
336     }
337     else if ((status == GNUNET_ARM_SERVICE_STOPPED) && (trialCount == 14))
338     {
339       phase++;
340       GNUNET_ARM_request_service_stop (arm, "arm", TIMEOUT, arm_stop_cb, NULL);
341     }
342   }
343 }
344
345
346 static void
347 arm_start_cb (void *cls, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
348 {
349   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
350   GNUNET_break (result == GNUNET_ARM_RESULT_STARTING);
351   GNUNET_break (phase == 0);
352   LOG ("Sent 'START' request for arm to ARM %s\n",
353        (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully");
354 }
355
356
357 static void
358 task (void *cls, char *const *args, const char *cfgfile,
359       const struct GNUNET_CONFIGURATION_Handle *c)
360 {
361   cfg = c;
362   arm = GNUNET_ARM_connect (cfg, NULL, NULL);
363   if (NULL != arm)
364   {
365     mon = GNUNET_ARM_monitor (cfg, &srv_status, NULL);
366     if (NULL != mon)
367     {
368 #if START_ARM
369       GNUNET_ARM_request_service_start (arm, "arm",
370           GNUNET_OS_INHERIT_STD_OUT_AND_ERR, GNUNET_TIME_UNIT_ZERO, arm_start_cb, NULL);
371 #else
372       arm_start_cb (NULL, arm, GNUNET_ARM_REQUEST_SENT_OK, "arm", GNUNET_ARM_SERVICE_STARTING);
373 #endif
374     }
375     else
376     {
377       GNUNET_ARM_disconnect_and_free (arm);
378       arm = NULL;
379     }
380   }
381 }
382
383
384 static int
385 check ()
386 {
387   char *const argv[] = {
388     "test-exponential-backoff",
389     "-c", CFGFILENAME,
390     NULL
391   };
392   struct GNUNET_GETOPT_CommandLineOption options[] = {
393     GNUNET_GETOPT_OPTION_END
394   };
395
396   /* Running ARM  and running the do_nothing task */
397   GNUNET_assert (GNUNET_OK ==
398                  GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
399                                      argv, "test-exponential-backoff",
400                                      "nohelp", options, &task, NULL));
401
402
403   return ok;
404 }
405
406
407 #ifndef PATH_MAX
408 /**
409  * Assumed maximum path length (for the log file name).
410  */
411 #define PATH_MAX 4096
412 #endif
413
414
415 static int
416 init ()
417 {
418   struct GNUNET_CONFIGURATION_Handle *cfg;
419   char pwd[PATH_MAX];
420   char *binary;
421
422   cfg = GNUNET_CONFIGURATION_create ();
423   if (GNUNET_OK != GNUNET_CONFIGURATION_parse (cfg,
424                                                "test_arm_api_data.conf"))
425     return GNUNET_SYSERR;
426   if (NULL == getcwd (pwd, PATH_MAX))
427     return GNUNET_SYSERR;
428   GNUNET_assert (0 < GNUNET_asprintf (&binary, "%s/%s", pwd, BINARY));
429   GNUNET_CONFIGURATION_set_value_string (cfg, SERVICE, "BINARY", binary);
430   GNUNET_free (binary);
431   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, CFGFILENAME))
432   {
433     GNUNET_CONFIGURATION_destroy (cfg);
434     return GNUNET_SYSERR;
435   }
436   GNUNET_CONFIGURATION_destroy (cfg);
437
438 #if LOG_BACKOFF
439   killLogFileName = GNUNET_DISK_mktemp ("exponential-backoff-waiting.log");
440   if (NULL == (killLogFilePtr = FOPEN (killLogFileName, "w")))
441     {
442       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fopen",
443                                 killLogFileName);
444       GNUNET_free (killLogFileName);
445       return GNUNET_SYSERR;
446     }
447 #endif
448   return GNUNET_OK;
449 }
450
451
452 static void
453 houseKeep ()
454 {
455 #if LOG_BACKOFF
456   GNUNET_assert (0 == fclose (killLogFilePtr));
457   GNUNET_free (killLogFileName);
458 #endif
459   (void) unlink (CFGFILENAME);
460 }
461
462
463 int
464 main (int argc, char *argv[])
465 {
466   int ret;
467
468   GNUNET_log_setup ("test-exponential-backoff",
469                     "WARNING",
470                     NULL);
471
472   if (GNUNET_OK != init ())
473     return 1;
474   ret = check ();
475   houseKeep ();
476   return ret;
477 }
478
479 /* end of test_exponential_backoff.c */