doxy
[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 VERBOSE GNUNET_NO
32
33 #define START_ARM GNUNET_YES
34
35 #define LOG_BACKOFF GNUNET_NO
36
37 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
38
39 #define SERVICE_TEST_TIMEOUT GNUNET_TIME_UNIT_FOREVER_REL
40
41 #define FIVE_MILLISECONDS GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 5)
42
43
44 static const struct GNUNET_CONFIGURATION_Handle *cfg;
45
46 static struct GNUNET_ARM_Handle *arm;
47
48 static int ok = 1;
49
50 static int trialCount;
51
52 static struct GNUNET_TIME_Absolute startedWaitingAt;
53
54 struct GNUNET_TIME_Relative waitedFor;
55
56 #if LOG_BACKOFF
57 static FILE *killLogFilePtr;
58
59 static char *killLogFileName;
60 #endif
61
62
63 /**
64  * Context for handling the shutdown of a service.
65  */
66 struct ShutdownContext
67 {
68   /**
69    * Connection to the service that is being shutdown.
70    */
71   struct GNUNET_CLIENT_Connection *sock;
72
73   /**
74    * Time allowed for shutdown to happen.
75    */
76   struct GNUNET_TIME_Absolute timeout;
77
78   /**
79    * Task set up to cancel the shutdown request on timeout.
80    */
81   GNUNET_SCHEDULER_TaskIdentifier cancel_task;
82
83   /**
84    * Task to call once shutdown complete
85    */
86   GNUNET_CLIENT_ShutdownTask cont;
87
88   /**
89    * Closure for shutdown continuation
90    */
91   void *cont_cls;
92
93   /**
94    * We received a confirmation that the service will shut down.
95    */
96   int confirmed;
97
98 };
99
100 /**
101  * Handler receiving response to service shutdown requests.
102  * First call with NULL: service misbehaving, or something.
103  * First call with GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN:
104  *   - service will shutdown
105  * Second call with NULL:
106  *   - service has now really shut down.
107  *
108  * @param cls closure
109  * @param msg NULL, indicating socket closure.
110  */
111 static void
112 service_shutdown_handler (void *cls, const struct GNUNET_MessageHeader *msg)
113 {
114   struct ShutdownContext *shutdown_ctx = cls;
115
116   if (msg == NULL) 
117   {
118 #if VERBOSE
119     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service shutdown complete.\n");
120 #endif
121     if (shutdown_ctx->cont != NULL)
122       shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_NO);
123     
124     GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task);
125     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
126     GNUNET_free (shutdown_ctx);
127     return;
128   }
129   GNUNET_assert (ntohs (msg->size) ==
130                  sizeof (struct GNUNET_MessageHeader));
131   switch (ntohs (msg->type))
132   {
133   case GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN:
134 #if VERBOSE
135     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
136                 "Received confirmation for service shutdown.\n");
137 #endif
138     shutdown_ctx->confirmed = GNUNET_YES;
139     GNUNET_CLIENT_receive (shutdown_ctx->sock,
140                            &service_shutdown_handler, shutdown_ctx,
141                            GNUNET_TIME_UNIT_FOREVER_REL);
142     break;
143   default:              /* Fall through */
144     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
145                 "Service shutdown refused!\n");
146     if (shutdown_ctx->cont != NULL)
147       shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_YES);
148     
149     GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task);
150     GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
151     GNUNET_free (shutdown_ctx);
152     break;
153   }
154 }
155
156
157 /**
158  * Shutting down took too long, cancel receive and return error.
159  *
160  * @param cls closure
161  * @param tc context information (why was this task triggered now)
162  */
163 void
164 service_shutdown_cancel (void *cls,
165                          const struct GNUNET_SCHEDULER_TaskContext *tc)
166 {
167   struct ShutdownContext *shutdown_ctx = cls;
168
169   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "service_shutdown_cancel called!\n");
170   shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
171   GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
172   GNUNET_free (shutdown_ctx);
173 }
174
175
176 /**
177  * If possible, write a shutdown message to the target
178  * buffer and destroy the client connection.
179  *
180  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
181  * @param size number of bytes available in buf
182  * @param buf NULL on error, otherwise target buffer
183  * @return number of bytes written to buf
184  */
185 static size_t
186 write_shutdown (void *cls, size_t size, void *buf)
187 {
188   struct GNUNET_MessageHeader *msg;
189   struct ShutdownContext *shutdown_ctx = cls;
190
191   if (size < sizeof (struct GNUNET_MessageHeader))
192     {
193       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
194                   _("Failed to transmit shutdown request to client.\n"));
195       shutdown_ctx->cont (shutdown_ctx->cont_cls, GNUNET_SYSERR);
196       GNUNET_CLIENT_disconnect (shutdown_ctx->sock);
197       GNUNET_free (shutdown_ctx);
198       return 0;                 /* client disconnected */
199     }
200
201   GNUNET_CLIENT_receive (shutdown_ctx->sock, &service_shutdown_handler,
202                          shutdown_ctx, GNUNET_TIME_UNIT_FOREVER_REL);
203   shutdown_ctx->cancel_task =
204     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
205                                   (shutdown_ctx->timeout),
206                                   &service_shutdown_cancel, shutdown_ctx);
207   msg = (struct GNUNET_MessageHeader *) buf;
208   msg->type = htons (GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN);
209   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
210   return sizeof (struct GNUNET_MessageHeader);
211 }
212
213
214 /**
215  * Request that the service should shutdown.
216  * Afterwards, the connection will automatically be
217  * disconnected.  Hence the "sock" should not
218  * be used by the caller after this call
219  * (calling this function frees "sock" after a while).
220  *
221  * @param sock the socket connected to the service
222  * @param timeout how long to wait before giving up on transmission
223  * @param cont continuation to call once the service is really down
224  * @param cont_cls closure for continuation
225  *
226  */
227 static void
228 arm_service_shutdown (struct GNUNET_CLIENT_Connection *sock,
229                       struct GNUNET_TIME_Relative timeout,
230                       GNUNET_CLIENT_ShutdownTask cont, void *cont_cls)
231 {
232   struct ShutdownContext *shutdown_ctx;
233
234   shutdown_ctx = GNUNET_malloc (sizeof (struct ShutdownContext));
235   shutdown_ctx->cont = cont;
236   shutdown_ctx->cont_cls = cont_cls;
237   shutdown_ctx->sock = sock;
238   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
239   GNUNET_CLIENT_notify_transmit_ready (sock,
240                                        sizeof (struct GNUNET_MessageHeader),
241                                        timeout, GNUNET_NO, &write_shutdown,
242                                        shutdown_ctx);
243 }
244
245
246 static void
247 arm_notify_stop (void *cls, enum GNUNET_ARM_ProcessStatus status)
248 {
249   GNUNET_assert ( (status == GNUNET_ARM_PROCESS_DOWN) ||
250                   (status == GNUNET_ARM_PROCESS_ALREADY_DOWN) );
251 #if START_ARM
252   GNUNET_ARM_stop_service (arm, "arm", TIMEOUT, NULL, NULL);
253 #endif
254 }
255
256
257 static void
258 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc);
259
260
261 static void
262 do_nothing_notify (void *cls, enum GNUNET_ARM_ProcessStatus status)
263 {
264   GNUNET_assert (status == GNUNET_ARM_PROCESS_STARTING);
265   ok = 1;
266   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &kill_task, NULL);
267 }
268
269 static void
270 arm_notify (void *cls, enum GNUNET_ARM_ProcessStatus status)
271 {
272   GNUNET_assert (status == GNUNET_ARM_PROCESS_STARTING);
273   GNUNET_ARM_start_service (arm, "do-nothing", GNUNET_OS_INHERIT_STD_OUT_AND_ERR, TIMEOUT, &do_nothing_notify,
274                             NULL);
275 }
276
277
278 static void
279 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc);
280
281
282 static void
283 do_nothing_restarted_notify_task (void *cls,
284                                   const struct GNUNET_SCHEDULER_TaskContext
285                                   *tc)
286 {
287   static char a;
288
289   trialCount++;
290
291 #if LOG_BACKOFF
292   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
293     {
294       FPRINTF (killLogFilePtr, "%d.Reason is shutdown!\n", trialCount);
295     }
296   else if ((tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT) != 0)
297     {
298       FPRINTF (killLogFilePtr, "%d.Reason is timeout!\n", trialCount);
299     }
300   else if ((tc->reason & GNUNET_SCHEDULER_REASON_PREREQ_DONE) != 0)
301     {
302       FPRINTF (killLogFilePtr, "%d.Service is running!\n", trialCount);
303     }
304 #endif
305   GNUNET_SCHEDULER_add_now (&kill_task, &a);
306 }
307
308
309 static void
310 do_test (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc)
311 {
312   GNUNET_CLIENT_service_test ("do-nothing", cfg, TIMEOUT,
313                               &do_nothing_restarted_notify_task, NULL);
314 }
315
316
317 static void
318 shutdown_cont (void *cls, int reason)
319 {
320   trialCount++;
321   startedWaitingAt = GNUNET_TIME_absolute_get ();
322   GNUNET_SCHEDULER_add_delayed (waitedFor, &do_test, NULL);
323 }
324
325
326 static void
327 kill_task (void *cbData, const struct GNUNET_SCHEDULER_TaskContext *tc)
328 {
329   static struct GNUNET_CLIENT_Connection *doNothingConnection = NULL;
330
331   if (NULL != cbData)
332     {
333       waitedFor = GNUNET_TIME_absolute_get_duration (startedWaitingAt);
334
335 #if LOG_BACKOFF
336       FPRINTF (killLogFilePtr, "Waited for: %llu ms\n",
337                (unsigned long long) waitedFor.rel_value);
338 #endif
339     }
340   else
341     {
342       waitedFor.rel_value = 0;
343     }
344   /* Connect to the doNothing task */
345   doNothingConnection = GNUNET_CLIENT_connect ("do-nothing", cfg);
346   GNUNET_assert (doNothingConnection != NULL);
347   if (trialCount == 12)
348     {
349       GNUNET_CLIENT_disconnect (doNothingConnection);
350       GNUNET_ARM_stop_service (arm, "do-nothing", TIMEOUT, &arm_notify_stop,
351                                NULL);
352       ok = 0;
353       return;
354     }
355   /* Use the created connection to kill the doNothingTask */
356   arm_service_shutdown (doNothingConnection, TIMEOUT, &shutdown_cont, NULL);
357 }
358
359
360 static void
361 task (void *cls, char *const *args, const char *cfgfile,
362       const struct GNUNET_CONFIGURATION_Handle *c)
363 {
364   cfg = c;
365
366   arm = GNUNET_ARM_connect (cfg, NULL);
367 #if START_ARM
368   GNUNET_ARM_start_service (arm, "arm", GNUNET_OS_INHERIT_STD_OUT_AND_ERR, GNUNET_TIME_UNIT_ZERO, &arm_notify,
369                             NULL);
370 #else
371   arm_do_nothing (NULL, GNUNET_YES);
372 #endif
373 }
374
375
376 static int
377 check ()
378 {
379   char *const argv[] = {
380     "test-exponential-backoff",
381     "-c", "test_arm_api_data.conf",
382 #if VERBOSE
383     "-L", "DEBUG",
384 #endif
385     NULL
386   };
387   struct GNUNET_GETOPT_CommandLineOption options[] = {
388     GNUNET_GETOPT_OPTION_END
389   };
390
391   /* Running ARM  and running the do_nothing task */
392   GNUNET_assert (GNUNET_OK ==
393                  GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
394                                      argv, "test-exponential-backoff",
395                                      "nohelp", options, &task, NULL));
396
397
398   return ok;
399 }
400
401 static int
402 init ()
403 {
404 #if LOG_BACKOFF
405   killLogFileName = GNUNET_DISK_mktemp ("exponential-backoff-waiting.log");
406   if (NULL == (killLogFilePtr = FOPEN (killLogFileName, "w")))
407     {
408       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fopen",
409                                 killLogFileName);
410       GNUNET_free (killLogFileName);
411       return GNUNET_SYSERR;
412     }
413 #endif
414   return GNUNET_OK;
415 }
416
417
418 static void
419 houseKeep ()
420 {
421 #if LOG_BACKOFF
422   GNUNET_assert (0 == fclose (killLogFilePtr));
423   GNUNET_free (killLogFileName);
424 #endif
425 }
426
427
428 int
429 main (int argc, char *argv[])
430 {
431   int ret;
432
433   GNUNET_log_setup ("test-exponential-backoff",
434 #if VERBOSE
435                     "DEBUG",
436 #else
437                     "WARNING",
438 #endif
439                     NULL);
440
441   init ();
442   ret = check ();
443   houseKeep ();
444   return ret;
445 }
446
447 /* end of test_exponential_backoff.c */