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