Non-generated config file
[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 #define SERVICE "do-nothing"
42
43 #define BINARY "mockup-service"
44
45 #define CFGFILENAME "test_arm_api_data.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   GNUNET_SCHEDULER_TaskIdentifier 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  * @param tc context information (why was this task triggered now)
145  */
146 void
147 service_shutdown_cancel (void *cls,
148                          const struct GNUNET_SCHEDULER_TaskContext *tc)
149 {
150   struct ShutdownContext *shutdown_ctx = cls;
151
152   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "service_shutdown_cancel called!\n");
153   shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
154   GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
155   GNUNET_free (shutdown_ctx);
156 }
157
158
159 /**
160  * If possible, write a shutdown message to the target
161  * buffer and destroy the client connection.
162  *
163  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
164  * @param size number of bytes available in buf
165  * @param buf NULL on error, otherwise target buffer
166  * @return number of bytes written to buf
167  */
168 static size_t
169 write_shutdown (void *cls, size_t size, void *buf)
170 {
171   struct GNUNET_MessageHeader *msg;
172   struct ShutdownContext *shutdown_ctx = cls;
173
174   if (size < sizeof (struct GNUNET_MessageHeader))
175   {
176     LOG ("Failed to send a shutdown request\n");
177     shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
178     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
179     GNUNET_free (shutdown_ctx);
180     return 0;                   /* client disconnected */
181   }
182
183   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
184                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
185   shutdown_ctx->cancel_task = GNUNET_SCHEDULER_add_delayed (
186       GNUNET_TIME_absolute_get_remaining (shutdown_ctx->timeout),
187       &service_shutdown_cancel, shutdown_ctx);
188   msg = (struct GNUNET_MessageHeader *) buf;
189   msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_STOP);
190   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
191   strcpy ((char *) &msg[1], SERVICE);
192   LOG ("Sent a shutdown request\n");
193   return sizeof (struct GNUNET_MessageHeader) + strlen (SERVICE) + 1;
194 }
195
196
197 /**
198  * Request that the service should shutdown.
199  * Afterwards, the connection will automatically be
200  * disconnected.  Hence the "sock" should not
201  * be used by the caller after this call
202  * (calling this function frees "sock" after a while).
203  *
204  * @param sock the socket connected to the service
205  * @param timeout how long to wait before giving up on transmission
206  * @param cont continuation to call once the service is really down
207  * @param cont_cls closure for continuation
208  *
209  */
210 static void
211 do_nothing_service_shutdown (struct GNUNET_CLIENT_Connection *sock,
212                       struct GNUNET_TIME_Relative timeout,
213                       GNUNET_CLIENT_ShutdownTask cont, void *cont_cls)
214 {
215   struct ShutdownContext *shutdown_ctx;
216
217   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
218   shutdown_ctx->cont = cont;
219   shutdown_ctx->cont_cls = cont_cls;
220   shutdown_ctx->sock = sock;
221   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
222   GNUNET_CLIENT_notify_transmit_ready (sock,
223                                        sizeof (struct GNUNET_MessageHeader) + strlen (SERVICE) + 1,
224                                        timeout, GNUNET_NO, &write_shutdown,
225                                        shutdown_ctx);
226 }
227
228
229 static void
230 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc);
231
232
233 static void
234 shutdown_cont (void *cls, int reason)
235 {
236   if (GNUNET_NO != reason)
237   {
238     /* Re-try shutdown */
239     LOG ("do-nothing didn't die, trying again\n");
240     GNUNET_SCHEDULER_add_now (kill_task, NULL);
241     return;
242   }
243   startedWaitingAt = GNUNET_TIME_absolute_get ();
244   LOG ("do-nothing is dead, starting the countdown\n");
245 }
246
247
248 static void
249 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc)
250 {
251   static struct GNUNET_CLIENT_Connection *doNothingConnection = NULL;
252
253   if (NULL != cbData)
254   {
255     waitedFor = GNUNET_TIME_absolute_get_duration (startedWaitingAt);
256     LOG ("Waited for: %s\n", 
257          GNUNET_STRINGS_relative_time_to_string (waitedFor, GNUNET_YES));
258   }
259   else
260   {
261     waitedFor.rel_value_us = 0;
262   }
263   /* Connect to the doNothing task */
264   doNothingConnection = GNUNET_CLIENT_connect (SERVICE, cfg);
265   GNUNET_assert (doNothingConnection != NULL);
266   if (trialCount == 12)
267     waitedFor_prev = waitedFor;
268   else if (trialCount == 13)
269   {
270     GNUNET_CLIENT_disconnect (doNothingConnection);
271     GNUNET_ARM_request_service_stop (arm, SERVICE, TIMEOUT, NULL, NULL);
272     if (waitedFor_prev.rel_value_us >= waitedFor.rel_value_us)
273       ok = 9;
274     else
275       ok = 0;
276     trialCount += 1;
277     return;
278   }
279   trialCount += 1;
280   /* Use the created connection to kill the doNothingTask */
281   do_nothing_service_shutdown (doNothingConnection,
282       TIMEOUT, &shutdown_cont, NULL);
283 }
284
285
286 static void
287 trigger_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
288 {
289   GNUNET_ARM_disconnect_and_free (arm);
290   GNUNET_ARM_monitor_disconnect_and_free (mon);
291 }
292
293
294 static void
295 arm_stop_cb (void *cls, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
296 {
297   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
298   GNUNET_break (result == GNUNET_ARM_RESULT_STOPPED);
299   LOG ("ARM service stopped\n");
300   GNUNET_SCHEDULER_add_now (trigger_disconnect, NULL);
301 }
302
303
304 static void
305 srv_status (void *cls, const char *service, enum GNUNET_ARM_ServiceStatus status)
306 {
307   LOG ("Service %s is %u, phase %u\n", service, status, phase);
308   if (status == GNUNET_ARM_SERVICE_MONITORING_STARTED)
309   {
310     phase++;
311     GNUNET_ARM_request_service_start (arm, SERVICE,
312         GNUNET_OS_INHERIT_STD_OUT_AND_ERR, TIMEOUT, NULL, NULL);
313     return;
314   }
315   if (phase == 1)
316   {
317     GNUNET_break (status == GNUNET_ARM_SERVICE_STARTING);
318     GNUNET_break (0 == strcasecmp (service, SERVICE));
319     GNUNET_break (phase == 1);
320     LOG ("do-nothing is starting\n");
321     phase++;
322     ok = 1;
323     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &kill_task, NULL);
324   }
325   else if ((phase == 2) && (strcasecmp (SERVICE, service) == 0))
326   {
327     /* We passively monitor ARM for status updates. ARM should tell us
328      * when do-nothing dies (no need to run a service upness test ourselves).
329      */
330     if (status == GNUNET_ARM_SERVICE_STARTING)
331     {
332       LOG ("do-nothing is starting\n");
333       GNUNET_SCHEDULER_add_now (kill_task, &ok);
334     }
335     else if ((status == GNUNET_ARM_SERVICE_STOPPED) && (trialCount == 14))
336     {
337       phase++;
338       GNUNET_ARM_request_service_stop (arm, "arm", TIMEOUT, arm_stop_cb, NULL);
339     }
340   }
341 }
342
343
344 static void
345 arm_start_cb (void *cls, enum GNUNET_ARM_RequestStatus status, const char *servicename, enum GNUNET_ARM_Result result)
346 {
347   GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK);
348   GNUNET_break (result == GNUNET_ARM_RESULT_STARTING);
349   GNUNET_break (phase == 0);
350   LOG ("Sent 'START' request for arm to ARM %s\n", 
351        (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully");
352 }
353
354
355 static void
356 task (void *cls, char *const *args, const char *cfgfile,
357       const struct GNUNET_CONFIGURATION_Handle *c)
358 {
359   char *armconfig;
360   cfg = c;
361   if (NULL != cfgfile)
362   {
363     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "arm",
364         "CONFIG", &armconfig))
365     {
366       GNUNET_CONFIGURATION_set_value_string ((struct GNUNET_CONFIGURATION_Handle
367                                               *) cfg, "arm", "CONFIG",
368                                              cfgfile);
369     }
370     else
371       GNUNET_free (armconfig);
372   }
373
374   arm = GNUNET_ARM_connect (cfg, NULL, NULL);
375   if (NULL != arm)
376   {
377     mon = GNUNET_ARM_monitor (cfg, &srv_status, NULL);
378     if (NULL != mon)
379     {
380 #if START_ARM
381       GNUNET_ARM_request_service_start (arm, "arm",
382           GNUNET_OS_INHERIT_STD_OUT_AND_ERR, GNUNET_TIME_UNIT_ZERO, arm_start_cb, NULL);
383 #else
384       arm_start_cb (NULL, arm, GNUNET_ARM_REQUEST_SENT_OK, "arm", GNUNET_ARM_SERVICE_STARTING);
385 #endif
386     }
387     else
388     {
389       GNUNET_ARM_disconnect_and_free (arm);
390       arm = NULL;
391     }
392   }
393 }
394
395
396 static int
397 check ()
398 {
399   char *const argv[] = {
400     "test-exponential-backoff",
401     "-c", CFGFILENAME,
402     NULL
403   };
404   struct GNUNET_GETOPT_CommandLineOption options[] = {
405     GNUNET_GETOPT_OPTION_END
406   };
407
408   /* Running ARM  and running the do_nothing task */
409   GNUNET_assert (GNUNET_OK ==
410                  GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
411                                      argv, "test-exponential-backoff",
412                                      "nohelp", options, &task, NULL));
413
414
415   return ok;
416 }
417
418
419 static int
420 init ()
421 {
422   struct GNUNET_CONFIGURATION_Handle *cfg;
423   char pwd[PATH_MAX];
424   char *binary;
425
426   cfg = GNUNET_CONFIGURATION_create ();
427   if (GNUNET_OK != GNUNET_CONFIGURATION_parse (cfg,
428                                                "test_arm_api_data.conf"))
429     return GNUNET_SYSERR;
430   if (NULL == getcwd (pwd, PATH_MAX))
431     return GNUNET_SYSERR;
432   GNUNET_assert (0 < GNUNET_asprintf (&binary, "%s/%s", pwd, BINARY));
433   GNUNET_CONFIGURATION_set_value_string (cfg, SERVICE, "BINARY", binary);
434   GNUNET_free (binary);  
435   if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, CFGFILENAME))
436   {
437     GNUNET_CONFIGURATION_destroy (cfg);
438     return GNUNET_SYSERR;
439   }
440   GNUNET_CONFIGURATION_destroy (cfg);
441
442 #if LOG_BACKOFF
443   killLogFileName = GNUNET_DISK_mktemp ("exponential-backoff-waiting.log");
444   if (NULL == (killLogFilePtr = FOPEN (killLogFileName, "w")))
445     {
446       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fopen",
447                                 killLogFileName);
448       GNUNET_free (killLogFileName);
449       return GNUNET_SYSERR;
450     }
451 #endif
452   return GNUNET_OK;
453 }
454
455
456 static void
457 houseKeep ()
458 {
459 #if LOG_BACKOFF
460   GNUNET_assert (0 == fclose (killLogFilePtr));
461   GNUNET_free (killLogFileName);
462 #endif
463   (void) unlink (CFGFILENAME);
464 }
465
466
467 int
468 main (int argc, char *argv[])
469 {
470   int ret;
471
472   GNUNET_log_setup ("test-exponential-backoff",
473                     "WARNING",
474                     NULL);
475
476   if (GNUNET_OK != init ())
477     return 1;
478   ret = check ();
479   houseKeep ();
480   return ret;
481 }
482
483 /* end of test_exponential_backoff.c */