6611ae5ecb6f85cb5a8f0557cb2dca4a9c3cf88a
[oweals/gnunet.git] / src / arm / gnunet-arm.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2012, 2013 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 /**
22  * @file arm/gnunet-arm.c
23  * @brief arm for writing a tool
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_arm_service.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_util_lib.h"
30
31 /**
32  * Timeout for stopping services.  Long to give some services a real chance.
33  */
34 #define STOP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
35
36 /**
37  * Timeout for stopping ARM.  Extra-long since ARM needs to stop everyone else.
38  */
39 #define STOP_TIMEOUT_ARM GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
40
41 /**
42  * Timeout for starting services, very short because of the strange way start works
43  * (by checking if running before starting, so really this time is always waited on
44  * startup (annoying)).
45  */
46 #define START_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
47
48 /**
49  * Timeout for listing all running services.
50  */
51 #define LIST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
52
53 /**
54  * Set if we are to shutdown all services (including ARM).
55  */
56 static int end;
57
58 /**
59  * Set if we are to start default services (including ARM).
60  */
61 static int start;
62
63 /**
64  * Set if we are to stop/start default services (including ARM).
65  */
66 static int restart;
67
68 /**
69  * Set if we should delete configuration and temp directory on exit.
70  */
71 static int delete;
72
73 /**
74  * Set if we should not print status messages.
75  */
76 static int quiet;
77
78 /**
79  * Set if we should print a list of currently running services.
80  */
81 static int list;
82
83 /**
84  * Set to the name of a service to start.
85  */
86 static char *init;
87
88 /**
89  * Set to the name of a service to kill.
90  */
91 static char *term;
92
93 /**
94  * Set to the name of the config file used.
95  */
96 static const char *config_file;
97
98 /**
99  * Set to the directory where runtime files are stored.
100  */
101 static char *dir;
102
103 /**
104  * Final status code.
105  */
106 static int ret;
107
108 /**
109  * Connection with ARM.
110  */
111 static struct GNUNET_ARM_Handle *h;
112
113 /**
114  * Monitor connection with ARM.
115  */
116 static struct GNUNET_ARM_MonitorHandle *m;
117
118 /**
119  * Our configuration.
120  */
121 static struct GNUNET_CONFIGURATION_Handle *cfg;
122
123 /**
124  * Processing stage that we are in.  Simple counter.
125  */
126 static unsigned int phase;
127
128 /**
129  * User defined timestamp for completing operations.
130  */
131 static struct GNUNET_TIME_Relative timeout;
132
133 /**
134  * Do we want to give our stdout to gnunet-service-arm?
135  */
136 static unsigned int no_stdout;
137
138 /**
139  * Do we want to give our stderr to gnunet-service-arm?
140  */
141 static unsigned int no_stderr;
142
143
144 /**
145  * Attempts to delete configuration file and SERVICEHOME
146  * on arm shutdown provided the end and delete options
147  * were specified when gnunet-arm was run.
148  */
149 static void
150 delete_files ()
151 {
152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
153               "Will attempt to remove configuration file %s and service directory %s\n",
154               config_file, dir);
155
156   if (UNLINK (config_file) != 0)
157     {
158       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
159                   _("Failed to remove configuration file %s\n"), config_file);
160     }
161
162   if (GNUNET_DISK_directory_remove (dir) != GNUNET_OK)
163     {
164       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
165                   _("Failed to remove servicehome directory %s\n"), dir);
166
167     }
168 }
169
170
171 /**
172  * Main continuation-passing-style loop.  Runs the various
173  * jobs that we've been asked to do in order.
174  *
175  * @param cls closure, unused
176  * @param tc context, unused
177  */
178 static void
179 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
180 {
181   GNUNET_ARM_disconnect_and_free (h);
182   GNUNET_ARM_monitor_disconnect_and_free (m);
183   h = NULL;
184   m = NULL;
185   if ((end == GNUNET_YES) && (delete == GNUNET_YES))
186     delete_files ();    
187   GNUNET_CONFIGURATION_destroy (cfg);
188   cfg = NULL;
189 }
190
191
192 static const char *
193 req_string (enum GNUNET_ARM_RequestStatus rs)
194 {
195   switch (rs)
196   {
197   case GNUNET_ARM_REQUEST_SENT_OK:
198     return _("Message was sent successfully");
199   case GNUNET_ARM_REQUEST_CONFIGURATION_ERROR:
200     return _("Misconfiguration (can't connect to the ARM service)");
201   case GNUNET_ARM_REQUEST_DISCONNECTED:
202     return _("We disconnected from ARM before we could send a request");
203   case GNUNET_ARM_REQUEST_BUSY:
204     return _("ARM API is busy");
205   case GNUNET_ARM_REQUEST_TOO_LONG:
206     return _("Request doesn't fit into a message");
207   case GNUNET_ARM_REQUEST_TIMEOUT:
208     return _("Request timed out");
209   }
210   return _("Unknown request status");
211 }
212
213 static const char *
214 ret_string (enum GNUNET_ARM_Result result)
215 {
216   switch (result)
217   {
218   case GNUNET_ARM_RESULT_STOPPED:
219     return _("%s is stopped");
220   case GNUNET_ARM_RESULT_STARTING:
221     return _("%s is starting");
222   case GNUNET_ARM_RESULT_STOPPING:
223     return _("%s is stopping");
224   case GNUNET_ARM_RESULT_IS_STARTING_ALREADY:
225     return _("%s is starting already");
226   case GNUNET_ARM_RESULT_IS_STOPPING_ALREADY:
227     return _("%s is stopping already");
228   case GNUNET_ARM_RESULT_IS_STARTED_ALREADY:
229     return _("%s is started already");
230   case GNUNET_ARM_RESULT_IS_STOPPED_ALREADY:
231     return _("%s is stopped already");
232   case GNUNET_ARM_RESULT_IS_NOT_KNOWN:
233     return _("%s service is not known to ARM");
234   case GNUNET_ARM_RESULT_START_FAILED:
235     return _("%s service failed to start");
236   case GNUNET_ARM_RESULT_IN_SHUTDOWN:
237     return _("%s service can't be started because ARM is shutting down");
238   }
239   return _("%.s Unknown result code.");
240 }
241
242 static void action_loop (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
243
244 /**
245  * Function called whenever we connect to or disconnect from ARM.
246  *
247  * @param cls closure
248  * @param arm handle to the ARM connection
249  * @param connected GNUNET_YES if connected, GNUNET_NO if disconnected,
250  *                  GNUNET_SYSERR on error.
251  */
252 static void
253 conn_status (void *cls, struct GNUNET_ARM_Handle *arm, 
254              int connected)
255 {
256   if (GNUNET_SYSERR == connected)
257   {
258     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
259                 _("Fatal error initializing ARM API.\n"));
260     GNUNET_SCHEDULER_shutdown ();
261     return;
262   }
263 /*
264   if (connected)
265     GNUNET_SCHEDULER_add_now (action_loop, NULL);
266 */
267 }
268
269
270 static void
271 term_callback (void *cls, struct GNUNET_ARM_Handle *arm,
272     enum GNUNET_ARM_RequestStatus rs, const char *service,
273     enum GNUNET_ARM_Result result)
274 {
275   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
276   {
277     char *msg;
278     GNUNET_asprintf (&msg, _("Failed to send a request to kill the `%s' service: %%s\n"), term);
279     FPRINTF (stdout, msg, req_string (rs));
280     GNUNET_free (msg);
281     GNUNET_SCHEDULER_shutdown ();
282   }
283   if ((GNUNET_ARM_RESULT_STOPPED == result) ||
284       (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY == result))
285   {
286     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service %s shutdown successful\n", term);
287     term = NULL;
288     GNUNET_SCHEDULER_add_now (action_loop, NULL);
289   }
290   else
291   {
292     char *msg;
293     GNUNET_asprintf (&msg, _("Failed to kill the `%s' service: %%s\n"), term);
294     FPRINTF (stdout, msg, ret_string (result));
295     GNUNET_free (msg);
296     GNUNET_SCHEDULER_shutdown ();
297   }
298 }
299
300 static void
301 end_callback (void *cls, struct GNUNET_ARM_Handle *arm,
302     enum GNUNET_ARM_RequestStatus rs, const char *service,
303     enum GNUNET_ARM_Result result)
304 {
305   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
306   {
307     char *msg;
308     GNUNET_asprintf (&msg, "%s", _("Failed to send a stop request to the ARM service: %s\n"));
309     FPRINTF (stdout, msg, req_string (rs));
310     GNUNET_free (msg);
311     GNUNET_SCHEDULER_shutdown ();
312   }
313   if ((GNUNET_ARM_RESULT_STOPPING == result) ||
314       (GNUNET_ARM_RESULT_STOPPED == result) ||
315       (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY == result))
316   {
317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ARM service shutdown successful\n");
318     end = 0;
319     if (restart)
320     {
321       restart = 0;
322       start = 1;
323       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating an ARM restart\n");
324     }
325     GNUNET_SCHEDULER_add_now (action_loop, NULL);
326   }
327   else
328   {
329     char *msg;
330     GNUNET_asprintf (&msg, "%s", _("Failed to stop the ARM service: %s\n"));
331     FPRINTF (stdout, msg, ret_string (result));
332     GNUNET_free (msg);
333     GNUNET_SCHEDULER_shutdown ();
334   }
335 }
336
337 static void
338 start_callback (void *cls, struct GNUNET_ARM_Handle *arm,
339     enum GNUNET_ARM_RequestStatus rs, const char *service,
340     enum GNUNET_ARM_Result result)
341 {
342   char *msg;
343
344   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
345   {
346     GNUNET_asprintf (&msg, "%s", _("Failed to start the ARM service: %s\n"));
347     FPRINTF (stdout, msg, req_string (rs));
348     GNUNET_free (msg);
349     GNUNET_SCHEDULER_shutdown ();
350     return;
351   }
352   if (! ((GNUNET_ARM_RESULT_STARTING == result) ||
353          (GNUNET_ARM_RESULT_IS_STARTED_ALREADY == result)) )
354   {
355     GNUNET_asprintf (&msg, "%s", _("Failed to start the ARM service: %s\n"));
356     FPRINTF (stdout, msg, ret_string (result));
357     GNUNET_free (msg);
358     GNUNET_SCHEDULER_shutdown ();
359   }  
360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ARM service [re]start successful\n");
361   start = 0;
362   GNUNET_SCHEDULER_add_now (action_loop, NULL);
363   return;
364 }
365
366
367 static void
368 init_callback (void *cls, struct GNUNET_ARM_Handle *arm,
369     enum GNUNET_ARM_RequestStatus rs, const char *service,
370     enum GNUNET_ARM_Result result)
371 {
372   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
373   {
374     char *msg;
375     GNUNET_asprintf (&msg, _("Failed to send a request to start the `%s' service: %%s\n"), init);
376     FPRINTF (stdout, msg, req_string (rs));
377     GNUNET_free (msg);
378     GNUNET_SCHEDULER_shutdown ();
379   }
380   if ((GNUNET_ARM_RESULT_STARTING == result) ||
381       (GNUNET_ARM_RESULT_IS_STARTED_ALREADY == result))
382   {
383     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service %s [re]start successful\n", init);
384     init = NULL;
385     GNUNET_SCHEDULER_add_now (action_loop, NULL);
386   }
387   else
388   {
389     char *msg;
390     GNUNET_asprintf (&msg, _("Failed to start the `%s' service: %%s\n"), init);
391     FPRINTF (stdout, msg, ret_string (result));
392     GNUNET_free (msg);
393     GNUNET_SCHEDULER_shutdown ();
394   }
395 }
396
397
398 static void
399 list_callback (void *cls, struct GNUNET_ARM_Handle *arm,
400     enum GNUNET_ARM_RequestStatus rs, unsigned int count,
401     const char *const*list)
402 {
403   unsigned int i;
404   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
405   {
406     char *msg;
407     GNUNET_asprintf (&msg, "%s", _("Failed to request a list of services: %s\n"));
408     FPRINTF (stdout, msg, req_string (rs));
409     GNUNET_free (msg);
410     GNUNET_SCHEDULER_shutdown ();
411   }
412   if (NULL == list)
413   {
414     FPRINTF (stderr, "%s", _("Error communicating with ARM. ARM not running?\n"));
415     return;
416   }
417   FPRINTF (stdout, "%s", _("Running services:\n"));
418   for (i = 0; i < count; i++)
419     FPRINTF (stdout, "%s\n", list[i]);
420   GNUNET_SCHEDULER_add_now (action_loop, NULL);
421 }
422
423
424 /**
425  * Main action loop.  Runs the various
426  * jobs that we've been asked to do in order.
427  *
428  * @param cls closure, unused
429  * @param tc context, unused
430  */
431 static void
432 action_loop (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
433 {
434   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
435     return;
436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Running requested actions\n");
437   while (1)
438   {
439     switch (phase++)
440     {
441     case 0:
442       if (NULL != term)
443       {
444         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Termination action\n");
445         GNUNET_ARM_request_service_stop (h, term, (0 ==
446             timeout.rel_value) ? STOP_TIMEOUT : timeout,
447             term_callback, NULL);
448         return;
449       }
450       break;
451     case 1:
452       if (end || restart)
453       {
454         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "End action\n");
455         GNUNET_ARM_request_service_stop (h, "arm", (0 ==
456             timeout.rel_value) ? STOP_TIMEOUT_ARM : timeout,
457             end_callback, NULL);
458         return;
459       }
460       break;
461     case 2:
462       if (start)
463       {
464         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start action\n");
465         GNUNET_ARM_request_service_start (h, "arm",
466             (no_stdout ? 0 : GNUNET_OS_INHERIT_STD_OUT) |
467             (no_stderr ? 0 : GNUNET_OS_INHERIT_STD_ERR),
468             (0 == timeout.rel_value) ? START_TIMEOUT: timeout,
469             start_callback, NULL);
470         return;
471       }
472       break;
473     case 3:
474       if (NULL != init)
475       {
476         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initialization action\n");
477         GNUNET_ARM_request_service_start (h, init, GNUNET_OS_INHERIT_STD_NONE,
478             (0 == timeout.rel_value) ? STOP_TIMEOUT : timeout,
479             init_callback, NULL);
480         return;
481       }
482       break;
483     case 4:
484       if (list) 
485       {
486         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
487                     "Going to list all running services controlled by ARM.\n");
488         
489         GNUNET_ARM_request_service_list (h,
490             (0 == timeout.rel_value) ? LIST_TIMEOUT : timeout,
491             list_callback, &list);
492         return;
493       }
494       /* Fall through */
495     default:            /* last phase */
496       GNUNET_SCHEDULER_shutdown ();
497       return;
498     }
499   }
500 }
501
502
503 /**
504  * Function called when a service starts or stops.
505  *
506  * @param cls closure
507  * @param arm handle to the ARM connection
508  * @param service service name
509  * @param status status of the service
510  */
511 static void
512 srv_status (void *cls, struct GNUNET_ARM_MonitorHandle *arm,
513     const char *service, enum GNUNET_ARM_ServiceStatus status)
514 {
515   const char *msg;
516   switch (status)
517   {
518   case GNUNET_ARM_SERVICE_MONITORING_STARTED:
519     msg = _("Began monitoring ARM for service status changes\n");
520     break;
521   case GNUNET_ARM_SERVICE_STOPPED:
522     msg = _("Stopped %s.\n");
523     break;
524   case GNUNET_ARM_SERVICE_STARTING:
525     msg = _("Starting %s...\n");
526     break;
527   case GNUNET_ARM_SERVICE_STOPPING:
528     msg = _("Stopping %s...\n");
529     break;
530   default:
531     msg = NULL;
532     break;
533   }
534   if (NULL != msg)
535     FPRINTF (stderr, msg, service);
536   else
537     FPRINTF (stderr, _("Unknown status %u for service %s.\n"), status, service);
538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got service %s status %u\n", service, status);
539 }
540
541
542 /**
543  * Main function that will be run by the scheduler.
544  *
545  * @param cls closure
546  * @param args remaining command-line arguments
547  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
548  * @param c configuration
549  */
550 static void
551 run (void *cls, char *const *args, const char *cfgfile,
552      const struct GNUNET_CONFIGURATION_Handle *c)
553 {
554   char *armconfig;
555
556   cfg = GNUNET_CONFIGURATION_dup (c);
557   config_file = cfgfile;
558   if (GNUNET_CONFIGURATION_get_value_string
559       (cfg, "PATHS", "SERVICEHOME", &dir) != GNUNET_OK)
560   {
561     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
562                                "PATHS", "SERVICEHOME");
563     return;
564     }
565   if (NULL != cfgfile)
566   {
567     if (GNUNET_OK !=
568         GNUNET_CONFIGURATION_get_value_filename (cfg, "arm", "CONFIG",
569                                                  &armconfig))
570     {
571       GNUNET_CONFIGURATION_set_value_string (cfg, "arm", "CONFIG",
572                                              cfgfile);
573     }
574     else
575       GNUNET_free (armconfig);
576   }
577   h = GNUNET_ARM_connect (cfg, &conn_status, NULL);
578   if (NULL != h)
579   {
580     m = GNUNET_ARM_monitor (cfg, &srv_status, NULL);
581     if (NULL != m)
582     {
583       GNUNET_SCHEDULER_add_now (&action_loop, NULL);
584       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
585           shutdown_task, NULL);
586     }
587     else
588     {
589       GNUNET_ARM_disconnect_and_free (h);
590       h = NULL;
591     }
592   }
593 }
594
595
596 /**
597  * The main function to obtain arm from gnunetd.
598  *
599  * @param argc number of arguments from the command line
600  * @param argv command line arguments
601  * @return 0 ok, 1 on error
602  */
603 int
604 main (int argc, char *const *argv)
605 {
606   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
607     {'e', "end", NULL, gettext_noop ("stop all GNUnet services"),
608      GNUNET_NO, &GNUNET_GETOPT_set_one, &end},
609     {'i', "init", "SERVICE", gettext_noop ("start a particular service"),
610      GNUNET_YES, &GNUNET_GETOPT_set_string, &init},
611     {'k', "kill", "SERVICE", gettext_noop ("stop a particular service"),
612      GNUNET_YES, &GNUNET_GETOPT_set_string, &term},
613     {'s', "start", NULL, gettext_noop ("start all GNUnet default services"),
614      GNUNET_NO, &GNUNET_GETOPT_set_one, &start},
615     {'r', "restart", NULL,
616      gettext_noop ("stop and start all GNUnet default services"),
617      GNUNET_NO, &GNUNET_GETOPT_set_one, &restart},
618     {'d', "delete", NULL,
619      gettext_noop ("delete config file and directory on exit"),
620      GNUNET_NO, &GNUNET_GETOPT_set_one, &delete},
621     {'q', "quiet", NULL, gettext_noop ("don't print status messages"),
622      GNUNET_NO, &GNUNET_GETOPT_set_one, &quiet},
623     {'T', "timeout", "MSECS",
624      gettext_noop ("timeout in MSECS milliseconds for completing current operation"),
625      GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &timeout},
626     {'I', "info", NULL, gettext_noop ("list currently running services"),
627      GNUNET_NO, &GNUNET_GETOPT_set_one, &list},
628     {'O', "no-stdout", NULL, gettext_noop ("don't let gnunet-service-arm inherit standard output"),
629      GNUNET_NO, &GNUNET_GETOPT_set_one, &no_stdout},
630     {'E', "no-stderr", NULL, gettext_noop ("don't let gnunet-service-arm inherit standard error"),
631      GNUNET_NO, &GNUNET_GETOPT_set_one, &no_stderr},
632     GNUNET_GETOPT_OPTION_END
633   };
634
635   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
636     return 2;
637
638   if (GNUNET_OK ==
639       GNUNET_PROGRAM_run (argc, argv, "gnunet-arm",
640                           gettext_noop
641                           ("Control services and the Automated Restart Manager (ARM)"),
642                           options, &run, NULL))
643     {
644       GNUNET_free ((void *) argv);
645       return ret;
646     }
647   GNUNET_free ((void*) argv);
648   return 1;
649 }
650
651 /* end of gnunet-arm.c */