minor fix and better debug/error messages
[oweals/gnunet.git] / src / arm / arm_api.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 2, 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 /**
22  * @file arm/arm_api.c
23  * @brief API for accessing the ARM service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_arm_service.h"
28 #include "gnunet_client_lib.h"
29 #include "gnunet_getopt_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_server_lib.h"
33 #include "arm.h"
34
35
36 /**
37  * How long are we willing to wait for a service operation during the multi-operation
38  * request processing?
39  */
40 #define MULTI_TIMEOUT  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
41
42
43 /**
44  * Handle for interacting with ARM.
45  */ 
46 struct GNUNET_ARM_Handle
47 {
48
49   /**
50    * Our connection to the ARM service.
51    */
52   struct GNUNET_CLIENT_Connection *client;
53
54   /**
55    * The configuration that we are using.
56    */
57   struct GNUNET_CONFIGURATION_Handle *cfg;
58
59   /**
60    * Scheduler to use.
61    */
62   struct GNUNET_SCHEDULER_Handle *sched;
63
64 };
65
66
67 /**
68  * Setup a context for communicating with ARM.  Note that this
69  * can be done even if the ARM service is not yet running.
70  *
71  * @param cfg configuration to use (needed to contact ARM;
72  *        the ARM service may internally use a different
73  *        configuration to determine how to start the service).
74  * @param sched scheduler to use
75  * @param service service that *this* process is implementing/providing, can be NULL
76  * @return context to use for further ARM operations, NULL on error
77  */
78 struct GNUNET_ARM_Handle *
79 GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
80                     struct GNUNET_SCHEDULER_Handle *sched,
81                     const char *service)
82 {
83   struct GNUNET_ARM_Handle *ret;
84   struct GNUNET_CLIENT_Connection *client;
85
86   client = GNUNET_CLIENT_connect (sched, "arm", cfg);
87   if (client == NULL)
88     return NULL;
89   GNUNET_CLIENT_ignore_shutdown (client, GNUNET_YES);
90   ret = GNUNET_malloc (sizeof (struct GNUNET_ARM_Handle));
91   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
92   ret->sched = sched;
93   ret->client = client;
94   return ret;
95 }
96
97
98 /**
99  * Disconnect from the ARM service.
100  *
101  * @param h the handle that was being used
102  */
103 void
104 GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h)
105 {
106   if (h->client != NULL)
107     GNUNET_CLIENT_disconnect (h->client);
108   GNUNET_CONFIGURATION_destroy (h->cfg);
109   GNUNET_free (h);
110 }
111
112
113 /**
114  * Internal state for a request with ARM.
115  */
116 struct RequestContext
117 {
118
119   /**
120    * Pointer to our handle with ARM.
121    */
122   struct GNUNET_ARM_Handle *h;
123
124   /**
125    * Function to call with a status code for the requested operation.
126    */
127   GNUNET_ARM_Callback callback;
128
129   /**
130    * Closure for "callback".
131    */
132   void *cls;
133
134   /**
135    * Timeout for the operation.
136    */
137   struct GNUNET_TIME_Absolute timeout;
138
139   /**
140    * Type of the request expressed as a message type (start or stop).
141    */
142   uint16_t type;
143
144 };
145
146
147 /**
148  * A client specifically requested starting of ARM itself.
149  * This function is called with information about whether
150  * or not ARM is running; if it is, report success.  If
151  * it is not, start the ARM process.
152  *
153  * @param cls the context for the request that we will report on (struct RequestContext*)
154  * @param tc why were we called (reason says if ARM is running)
155  */
156 static void
157 arm_service_report (void *cls,
158                     const struct GNUNET_SCHEDULER_TaskContext *tc)
159 {
160   struct RequestContext *pos = cls;
161   pid_t pid;
162   char *binary;
163   char *config;
164
165   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_PREREQ_DONE))
166     {
167 #if DEBUG_ARM
168       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
169                   "Looks like `%s' is already running.\n",
170                   "gnunet-service-arm");
171 #endif
172       /* arm is running! */
173       if (pos->callback != NULL)
174         pos->callback (pos->cls, GNUNET_YES);
175       GNUNET_free (pos);
176       return;
177     }
178 #if DEBUG_ARM
179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
180               "Looks like `%s' is not running, will start it.\n",
181               "gnunet-service-arm");
182 #endif
183   /* FIXME: should we check that HOSTNAME for 'arm' is localhost? */
184   /* start service */
185   if (GNUNET_OK !=
186       GNUNET_CONFIGURATION_get_value_string (pos->h->cfg,
187                                              "arm",
188                                              "BINARY",
189                                              &binary))
190     {
191       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
192                   _("Configuration failes to specify option `%s' in section `%s'!\n"),
193                   "BINARY",
194                   "arm");
195       if (pos->callback != NULL)
196         pos->callback (pos->cls, GNUNET_SYSERR);
197       GNUNET_free (pos);
198       return;
199     }
200   if (GNUNET_OK !=
201       GNUNET_CONFIGURATION_get_value_filename (pos->h->cfg,
202                                                "arm", "CONFIG", &config))
203     {
204       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
205                   _("Configuration fails to specify option `%s' in section `%s'!\n"),
206                   "CONFIG",
207                   "arm");
208       if (pos->callback != NULL)
209         pos->callback (pos->cls, GNUNET_SYSERR);
210       GNUNET_free (binary);
211       GNUNET_free (pos);
212       return;
213     }
214   pid = GNUNET_OS_start_process (binary, binary, "-d", "-c", config,
215 #if DEBUG_ARM
216                                  "-L", "DEBUG",
217 #endif
218                                  NULL);
219   GNUNET_free (binary);
220   GNUNET_free (config);
221   if (pid == -1)
222     {
223       if (pos->callback != NULL)
224         pos->callback (pos->cls, GNUNET_SYSERR);
225       GNUNET_free (pos);
226       return;
227     }
228   if (pos->callback != NULL)
229     pos->callback (pos->cls, GNUNET_YES);
230   GNUNET_free (pos);
231 }
232
233
234 /**
235  * Process a response from ARM to a request for a change in service
236  * status.
237  *
238  * @param cls the request context 
239  * @param msg the response
240  */
241 static void
242 handle_response (void *cls, const struct GNUNET_MessageHeader *msg)
243 {
244   struct RequestContext *sc = cls;
245   int ret;
246
247   if (msg == NULL)
248     {
249       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
250                   _("Error receiving response to `%s' request from ARM for service `%s'\n"),
251                   (sc->type == GNUNET_MESSAGE_TYPE_ARM_START) 
252                   ? "START"
253                   : "STOP",
254                   (const char*) &sc[1]);
255       GNUNET_CLIENT_disconnect (sc->h->client);
256       sc->h->client = GNUNET_CLIENT_connect (sc->h->sched, 
257                                              "arm", 
258                                              sc->h->cfg);
259       GNUNET_assert (NULL != sc->h->client);
260       GNUNET_CLIENT_ignore_shutdown (sc->h->client, GNUNET_YES);
261       if (sc->callback != NULL)
262         sc->callback (sc->cls, GNUNET_SYSERR);
263       GNUNET_free (sc);
264       return;
265     }
266 #if DEBUG_ARM
267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
268               "Received response from ARM for  service `%s': %u\n",
269               (const char*) &sc[1],
270               ntohs(msg->type));
271 #endif
272   switch (ntohs (msg->type))
273     {
274     case GNUNET_MESSAGE_TYPE_ARM_IS_UP:
275       ret = GNUNET_YES;
276       break;
277     case GNUNET_MESSAGE_TYPE_ARM_IS_DOWN:
278       ret = GNUNET_NO;
279       break;
280     case GNUNET_MESSAGE_TYPE_ARM_IS_UNKNOWN:
281       ret = GNUNET_SYSERR;
282       break;
283     default:
284       GNUNET_break (0);
285       ret = GNUNET_SYSERR;
286     }
287   if (sc->callback != NULL)
288     sc->callback (sc->cls, ret);
289   GNUNET_free (sc);
290 }
291
292
293 /**
294  * Start or stop a service.
295  *
296  * @param h handle to ARM
297  * @param service_name name of the service
298  * @param timeout how long to wait before failing for good
299  * @param cb callback to invoke when service is ready
300  * @param cb_cls closure for callback
301  * @param type type of the request 
302  */
303 static void
304 change_service (struct GNUNET_ARM_Handle *h,
305                 const char *service_name,
306                 struct GNUNET_TIME_Relative timeout,
307                 GNUNET_ARM_Callback cb, void *cb_cls, uint16_t type)
308 {
309   struct RequestContext *sctx;
310   size_t slen;
311   struct GNUNET_MessageHeader *msg;
312
313   slen = strlen (service_name) + 1;
314   if (slen + sizeof (struct GNUNET_MessageHeader) >
315       GNUNET_SERVER_MAX_MESSAGE_SIZE)
316     {
317       GNUNET_break (0);
318       if (cb != NULL)
319         cb (cb_cls, GNUNET_NO);
320       return;
321     }
322 #if DEBUG_ARM
323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
324               (type == GNUNET_MESSAGE_TYPE_ARM_START) 
325               ? _("Requesting start of service `%s'.\n") 
326               : _("Requesting termination of service `%s'.\n"),
327               service_name);
328 #endif
329   sctx = GNUNET_malloc (sizeof (struct RequestContext) + slen);
330   sctx->h = h;
331   sctx->callback = cb;
332   sctx->cls = cb_cls;
333   sctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
334   sctx->type = type;
335   memcpy (&sctx[1], service_name, slen);
336   msg = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader) + slen);
337   msg->size = htons (sizeof (struct GNUNET_MessageHeader) + slen);
338   msg->type = htons (sctx->type);
339   memcpy (&msg[1], service_name, slen);
340   if (GNUNET_OK !=
341       GNUNET_CLIENT_transmit_and_get_response (sctx->h->client,
342                                                msg,
343                                                GNUNET_TIME_absolute_get_remaining (sctx->timeout),
344                                                GNUNET_YES,
345                                                &handle_response,
346                                                sctx))
347     {       
348       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
349                   (type == GNUNET_MESSAGE_TYPE_ARM_START)
350                   ? _("Error while trying to transmit request to start `%s' to ARM\n")
351                   : _("Error while trying to transmit request to stop `%s' to ARM\n"),
352                   (const char*) &service_name);
353       if (cb != NULL)
354         cb (cb_cls, GNUNET_SYSERR);
355       GNUNET_free (sctx);
356       GNUNET_free (msg);
357       return;
358     }
359   GNUNET_free (msg);
360 }
361
362
363 /**
364  * Start a service.
365  *
366  * @param h handle to ARM
367  * @param service_name name of the service
368  * @param timeout how long to wait before failing for good
369  * @param cb callback to invoke when service is ready
370  * @param cb_cls closure for callback
371  */
372 void
373 GNUNET_ARM_start_service (struct GNUNET_ARM_Handle *h,
374                           const char *service_name,
375                           struct GNUNET_TIME_Relative timeout,
376                           GNUNET_ARM_Callback cb, void *cb_cls)
377 {
378   struct RequestContext *sctx;
379   size_t slen;
380
381   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
382               _("Asked to starting service `%s' within %llu ms\n"), service_name,
383               (unsigned long long) timeout.value);
384   if (0 == strcasecmp ("arm", service_name))
385     {
386       slen = strlen ("arm") + 1;
387       sctx = GNUNET_malloc (sizeof (struct RequestContext) + slen);
388       sctx->h = h;
389       sctx->callback = cb;
390       sctx->cls = cb_cls;
391       sctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
392       memcpy (&sctx[1], service_name, slen);
393       GNUNET_CLIENT_service_test (h->sched,
394                                   "arm",
395                                   h->cfg, timeout, &arm_service_report, sctx);
396       return;
397     }
398   change_service (h, service_name, timeout, cb, cb_cls, GNUNET_MESSAGE_TYPE_ARM_START);
399 }
400
401
402 /**
403  * Stop a service.
404  *
405  * @param h handle to ARM
406  * @param service_name name of the service
407  * @param timeout how long to wait before failing for good
408  * @param cb callback to invoke when service is ready
409  * @param cb_cls closure for callback
410  */
411 void
412 GNUNET_ARM_stop_service (struct GNUNET_ARM_Handle *h,
413                          const char *service_name,
414                          struct GNUNET_TIME_Relative timeout,
415                          GNUNET_ARM_Callback cb, void *cb_cls)
416 {
417   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
418               _("Stopping service `%s' within %llu ms\n"), service_name,
419               (unsigned long long) timeout.value);
420   if (0 == strcasecmp ("arm", service_name))
421     {
422       GNUNET_CLIENT_service_shutdown (h->client);
423       h->client = NULL;
424       if (cb != NULL)
425         cb (cb_cls, GNUNET_NO);
426       return;
427     }
428   change_service (h, service_name, timeout, cb, cb_cls, GNUNET_MESSAGE_TYPE_ARM_STOP);
429 }
430
431
432 /**
433  * Function to call for each service.
434  *
435  * @param h handle to ARM
436  * @param service_name name of the service
437  * @param timeout how long to wait before failing for good
438  * @param cb callback to invoke when service is ready
439  * @param cb_cls closure for callback
440  */
441 typedef void (*ServiceOperation) (struct GNUNET_ARM_Handle *h,
442                                   const char *service_name,
443                                   struct GNUNET_TIME_Relative timeout,
444                                   GNUNET_ARM_Callback cb, void *cb_cls);
445
446
447 /**
448  * Context for starting or stopping multiple services.
449  */
450 struct MultiContext
451 {
452   /**
453    * NULL-terminated array of services to start or stop.
454    */
455   char **services;
456
457   /**
458    * Our handle to ARM.
459    */
460   struct GNUNET_ARM_Handle *h;
461
462   /**
463    * Identifies the operation (start or stop).
464    */
465   ServiceOperation op;
466
467   /**
468    * Current position in "services".
469    */
470   unsigned int pos;
471 };
472
473
474 /**
475  * Run the operation for the next service in the multi-service
476  * request.
477  *
478  * @param cls the "struct MultiContext" that is being processed
479  * @param success status of the previous operation (ignored)
480  */
481 static void
482 next_operation (void *cls,
483                 int success)
484 {
485   struct MultiContext *mc = cls;
486   char *pos;
487   
488   if (NULL == (pos = mc->services[mc->pos]))
489     {
490       GNUNET_free (mc->services);
491       GNUNET_ARM_disconnect (mc->h);
492       GNUNET_free (mc);
493       return;
494     }
495   mc->pos++;
496   mc->op (mc->h, pos, MULTI_TIMEOUT, &next_operation, mc);
497   GNUNET_free (pos);
498 }
499
500
501 /**
502  * Run a multi-service request.
503  *
504  * @param cfg configuration to use (needed to contact ARM;
505  *        the ARM service may internally use a different
506  *        configuration to determine how to start the service).
507  * @param sched scheduler to use
508  * @param op the operation to perform for each service
509  * @param va NULL-terminated list of services
510  */
511 static void
512 run_multi_request (const struct GNUNET_CONFIGURATION_Handle *cfg,
513                    struct GNUNET_SCHEDULER_Handle *sched,                   
514                    ServiceOperation op,
515                    va_list va)
516 {
517   va_list cp;
518   unsigned int total;
519   struct MultiContext *mc;
520   struct GNUNET_ARM_Handle *h;
521   const char *c;
522   
523   h = GNUNET_ARM_connect (cfg, sched, NULL);
524   if (NULL == h)
525     {
526       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
527                   _("Error while trying to transmit to ARM service\n"));
528       return; 
529     }
530   total = 1;
531   va_copy (cp, va);
532   while (NULL != (va_arg (cp, const char*))) total++;
533   va_end (cp);
534   mc = GNUNET_malloc (sizeof(struct MultiContext));
535   mc->services = GNUNET_malloc (total * sizeof (char*));
536   mc->h = h;
537   mc->op = op;
538   total = 0;
539   va_copy (cp, va);
540   while (NULL != (c = va_arg (cp, const char*))) 
541     mc->services[total++] = GNUNET_strdup (c);
542   va_end (cp);
543   next_operation (mc, GNUNET_YES);
544 }
545
546
547 /**
548  * Start multiple services in the specified order.  Convenience
549  * function.  Works asynchronously, failures are not reported.
550  *
551  * @param cfg configuration to use (needed to contact ARM;
552  *        the ARM service may internally use a different
553  *        configuration to determine how to start the service).
554  * @param sched scheduler to use
555  * @param ... NULL-terminated list of service names (const char*)
556  */
557 void
558 GNUNET_ARM_start_services (const struct GNUNET_CONFIGURATION_Handle *cfg,
559                            struct GNUNET_SCHEDULER_Handle *sched,
560                            ...)
561 {
562   va_list ap;
563
564   va_start (ap, sched);
565   run_multi_request (cfg, sched, &GNUNET_ARM_start_service, ap);
566   va_end (ap);
567 }
568
569
570 /**
571  * Stop multiple services in the specified order.  Convenience
572  * function.  Works asynchronously, failures are not reported.
573  *
574  * @param cfg configuration to use (needed to contact ARM;
575  *        the ARM service may internally use a different
576  *        configuration to determine how to start the service).
577  * @param sched scheduler to use
578  * @param ... NULL-terminated list of service names (const char*)
579  */
580 void
581 GNUNET_ARM_stop_services (const struct GNUNET_CONFIGURATION_Handle *cfg,
582                           struct GNUNET_SCHEDULER_Handle *sched,
583                           ...)
584 {
585   va_list ap;
586
587   va_start (ap, sched);
588   run_multi_request (cfg, sched, &GNUNET_ARM_stop_service, ap);
589   va_end (ap);
590 }
591
592
593 /* end of arm_api.c */