c1928b6e74297f993f26763ab4e7d5a14913fb65
[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 /**
193  * Returns a string interpretation of 'rs'
194  *
195  * @param rs the request status from ARM
196  * @return a string interpretation of the request status
197  */
198 static const char *
199 req_string (enum GNUNET_ARM_RequestStatus rs)
200 {
201   switch (rs)
202   {
203   case GNUNET_ARM_REQUEST_SENT_OK:
204     return _("Message was sent successfully");
205   case GNUNET_ARM_REQUEST_CONFIGURATION_ERROR:
206     return _("Misconfiguration (can't connect to the ARM service)");
207   case GNUNET_ARM_REQUEST_DISCONNECTED:
208     return _("We disconnected from ARM before we could send a request");
209   case GNUNET_ARM_REQUEST_BUSY:
210     return _("ARM API is busy");
211   case GNUNET_ARM_REQUEST_TOO_LONG:
212     return _("Request doesn't fit into a message");
213   case GNUNET_ARM_REQUEST_TIMEOUT:
214     return _("Request timed out");
215   }
216   return _("Unknown request status");
217 }
218
219
220 /**
221  * Returns a string interpretation of the 'result'
222  *
223  * @param result the arm result
224  * @return a string interpretation
225  */
226 static const char *
227 ret_string (enum GNUNET_ARM_Result result)
228 {
229   switch (result)
230   {
231   case GNUNET_ARM_RESULT_STOPPED:
232     return _("%s is stopped");
233   case GNUNET_ARM_RESULT_STARTING:
234     return _("%s is starting");
235   case GNUNET_ARM_RESULT_STOPPING:
236     return _("%s is stopping");
237   case GNUNET_ARM_RESULT_IS_STARTING_ALREADY:
238     return _("%s is starting already");
239   case GNUNET_ARM_RESULT_IS_STOPPING_ALREADY:
240     return _("%s is stopping already");
241   case GNUNET_ARM_RESULT_IS_STARTED_ALREADY:
242     return _("%s is started already");
243   case GNUNET_ARM_RESULT_IS_STOPPED_ALREADY:
244     return _("%s is stopped already");
245   case GNUNET_ARM_RESULT_IS_NOT_KNOWN:
246     return _("%s service is not known to ARM");
247   case GNUNET_ARM_RESULT_START_FAILED:
248     return _("%s service failed to start");
249   case GNUNET_ARM_RESULT_IN_SHUTDOWN:
250     return _("%s service can't be started because ARM is shutting down");
251   }
252   return _("%.s Unknown result code.");
253 }
254
255
256 /**
257  * Main task that runs our various operations in order.
258  *
259  * @param cls closure
260  * @param tc scheudler context
261  */
262 static void 
263 action_loop (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
264
265
266 /**
267  * Function called whenever we connect to or disconnect from ARM.
268  *
269  * @param cls closure
270  * @param connected GNUNET_YES if connected, GNUNET_NO if disconnected,
271  *                  GNUNET_SYSERR on error.
272  */
273 static void
274 conn_status (void *cls, 
275              int connected)
276 {
277   if (GNUNET_SYSERR == connected)
278   {
279     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
280                 _("Fatal error initializing ARM API.\n"));
281     GNUNET_SCHEDULER_shutdown ();
282     return;
283   }
284 }
285
286
287 static void
288 term_callback (void *cls, 
289                enum GNUNET_ARM_RequestStatus rs, const char *service,
290                enum GNUNET_ARM_Result result)
291 {
292   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
293   {
294     char *msg;
295     GNUNET_asprintf (&msg,
296                      _("Failed to send a request to kill the `%s' service: %%s\n"),
297                      term);
298     FPRINTF (stdout, msg, req_string (rs));
299     GNUNET_free (msg);
300     GNUNET_SCHEDULER_shutdown ();
301   }
302   if ((GNUNET_ARM_RESULT_STOPPED == result) ||
303       (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY == result))
304   {
305     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service %s shutdown successful\n", term);
306     term = NULL;
307     GNUNET_SCHEDULER_add_now (action_loop, NULL);
308   }
309   else
310   {
311     char *msg;
312     GNUNET_asprintf (&msg, _("Failed to kill the `%s' service: %s\n"),
313                      term, ret_string (result));
314     FPRINTF (stdout, msg, service);
315     GNUNET_free (msg);
316     GNUNET_SCHEDULER_shutdown ();
317   }
318 }
319
320
321 static void
322 end_callback (void *cls, 
323               enum GNUNET_ARM_RequestStatus rs, const char *service,
324               enum GNUNET_ARM_Result result)
325 {
326   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
327   {
328     char *msg;
329
330     GNUNET_asprintf (&msg, "%s", 
331                      _("Failed to send a stop request to the ARM service: %s\n"));
332     FPRINTF (stdout, msg, req_string (rs));
333     GNUNET_free (msg);
334     GNUNET_SCHEDULER_shutdown ();
335   }
336   if ((GNUNET_ARM_RESULT_STOPPING == result) ||
337       (GNUNET_ARM_RESULT_STOPPED == result) ||
338       (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY == result))
339   {
340     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ARM service shutdown successful\n");
341     end = 0;
342     if (restart)
343     {
344       restart = 0;
345       start = 1;
346       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating an ARM restart\n");
347     }
348     GNUNET_SCHEDULER_add_now (action_loop, NULL);
349   }
350   else
351   {
352     char *msg;
353
354     GNUNET_asprintf (&msg, "%s", _("Failed to stop the ARM service: %s\n"));
355     FPRINTF (stdout, msg, ret_string (result));
356     GNUNET_free (msg);
357     GNUNET_SCHEDULER_shutdown ();
358   }
359 }
360
361
362 static void
363 start_callback (void *cls,
364                 enum GNUNET_ARM_RequestStatus rs, const char *service,
365                 enum GNUNET_ARM_Result result)
366 {
367   char *msg;
368
369   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
370   {
371     GNUNET_asprintf (&msg, "%s", _("Failed to start the ARM service: %s\n"));
372     FPRINTF (stdout, msg, req_string (rs));
373     GNUNET_free (msg);
374     GNUNET_SCHEDULER_shutdown ();
375     return;
376   }
377   if (! ((GNUNET_ARM_RESULT_STARTING == result) ||
378          (GNUNET_ARM_RESULT_IS_STARTED_ALREADY == result)) )
379   {
380     GNUNET_asprintf (&msg, "%s", _("Failed to start the ARM service: %s\n"));
381     FPRINTF (stdout, msg, ret_string (result));
382     GNUNET_free (msg);
383     GNUNET_SCHEDULER_shutdown ();
384   }  
385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ARM service [re]start successful\n");
386   start = 0;
387   GNUNET_SCHEDULER_add_now (action_loop, NULL);
388 }
389
390
391 static void
392 init_callback (void *cls, 
393                enum GNUNET_ARM_RequestStatus rs, const char *service,
394                enum GNUNET_ARM_Result result)
395 {
396   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
397   {
398     char *msg;
399
400     GNUNET_asprintf (&msg, _("Failed to send a request to start the `%s' service: %%s\n"), init);
401     FPRINTF (stdout, msg, req_string (rs));
402     GNUNET_free (msg);
403     GNUNET_SCHEDULER_shutdown ();
404   }
405   if ((GNUNET_ARM_RESULT_STARTING == result) ||
406       (GNUNET_ARM_RESULT_IS_STARTED_ALREADY == result))
407   {
408     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service %s [re]start successful\n", init);
409     init = NULL;
410     GNUNET_SCHEDULER_add_now (action_loop, NULL);
411   }
412   else
413   {
414     char *msg;
415     GNUNET_asprintf (&msg, _("Failed to start the `%s' service: %s\n"),
416                      init, ret_string (result));
417     FPRINTF (stdout, msg, service);
418     GNUNET_free (msg);
419     GNUNET_SCHEDULER_shutdown ();
420   }
421 }
422
423
424 static void
425 list_callback (void *cls, 
426                enum GNUNET_ARM_RequestStatus rs, unsigned int count,
427                const char *const*list)
428 {
429   unsigned int i;
430   if (GNUNET_ARM_REQUEST_SENT_OK != rs)
431   {
432     char *msg;
433     GNUNET_asprintf (&msg, "%s", _("Failed to request a list of services: %s\n"));
434     FPRINTF (stdout, msg, req_string (rs));
435     GNUNET_free (msg);
436     GNUNET_SCHEDULER_shutdown ();
437   }
438   if (NULL == list)
439   {
440     FPRINTF (stderr, "%s", _("Error communicating with ARM. ARM not running?\n"));
441     return;
442   }
443   FPRINTF (stdout, "%s", _("Running services:\n"));
444   for (i = 0; i < count; i++)
445     FPRINTF (stdout, "%s\n", list[i]);
446   GNUNET_SCHEDULER_add_now (action_loop, NULL);
447 }
448
449
450 /**
451  * Main action loop.  Runs the various
452  * jobs that we've been asked to do in order.
453  *
454  * @param cls closure, unused
455  * @param tc context, unused
456  */
457 static void
458 action_loop (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
459 {
460   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
461     return;
462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Running requested actions\n");
463   while (1)
464   {
465     switch (phase++)
466     {
467     case 0:
468       if (NULL != term)
469       {
470         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Termination action\n");
471         GNUNET_ARM_request_service_stop (h, term, (0 ==
472             timeout.rel_value) ? STOP_TIMEOUT : timeout,
473             term_callback, NULL);
474         return;
475       }
476       break;
477     case 1:
478       if (end || restart)
479       {
480         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "End action\n");
481         GNUNET_ARM_request_service_stop (h, "arm", (0 ==
482             timeout.rel_value) ? STOP_TIMEOUT_ARM : timeout,
483             end_callback, NULL);
484         return;
485       }
486       break;
487     case 2:
488       if (start)
489       {
490         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start action\n");
491         GNUNET_ARM_request_service_start (h, "arm",
492             (no_stdout ? 0 : GNUNET_OS_INHERIT_STD_OUT) |
493             (no_stderr ? 0 : GNUNET_OS_INHERIT_STD_ERR),
494             (0 == timeout.rel_value) ? START_TIMEOUT: timeout,
495             start_callback, NULL);
496         return;
497       }
498       break;
499     case 3:
500       if (NULL != init)
501       {
502         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initialization action\n");
503         GNUNET_ARM_request_service_start (h, init, GNUNET_OS_INHERIT_STD_NONE,
504             (0 == timeout.rel_value) ? STOP_TIMEOUT : timeout,
505             init_callback, NULL);
506         return;
507       }
508       break;
509     case 4:
510       if (list) 
511       {
512         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
513                     "Going to list all running services controlled by ARM.\n");
514         
515         GNUNET_ARM_request_service_list (h,
516             (0 == timeout.rel_value) ? LIST_TIMEOUT : timeout,
517             list_callback, &list);
518         return;
519       }
520       /* Fall through */
521     default:            /* last phase */
522       GNUNET_SCHEDULER_shutdown ();
523       return;
524     }
525   }
526 }
527
528
529 /**
530  * Function called when a service starts or stops.
531  *
532  * @param cls closure
533  * @param service service name
534  * @param status status of the service
535  */
536 static void
537 srv_status (void *cls, 
538             const char *service, enum GNUNET_ARM_ServiceStatus status)
539 {
540   const char *msg;
541   switch (status)
542   {
543   case GNUNET_ARM_SERVICE_MONITORING_STARTED:
544     return; /* this should be done silently */
545   case GNUNET_ARM_SERVICE_STOPPED:
546     msg = _("Stopped %s.\n");
547     break;
548   case GNUNET_ARM_SERVICE_STARTING:
549     msg = _("Starting %s...\n");
550     break;
551   case GNUNET_ARM_SERVICE_STOPPING:
552     msg = _("Stopping %s...\n");
553     break;
554   default:
555     msg = NULL;
556     break;
557   }
558   if (! quiet)
559     {
560       if (NULL != msg)
561         FPRINTF (stderr, msg, service);
562       else
563         FPRINTF (stderr, _("Unknown status %u for service %s.\n"), status, service);
564     }
565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got service %s status %u\n", service, status);
566 }
567
568
569 /**
570  * Main function that will be run by the scheduler.
571  *
572  * @param cls closure
573  * @param args remaining command-line arguments
574  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
575  * @param c configuration
576  */
577 static void
578 run (void *cls, char *const *args, const char *cfgfile,
579      const struct GNUNET_CONFIGURATION_Handle *c)
580 {
581   char *armconfig;
582
583   cfg = GNUNET_CONFIGURATION_dup (c);
584   config_file = cfgfile;
585   if (GNUNET_OK != 
586       GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", "SERVICEHOME", &dir))
587   {
588     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
589                                "PATHS", "SERVICEHOME");
590     return;
591   }
592   if (NULL != cfgfile)
593   {
594     if (GNUNET_OK !=
595         GNUNET_CONFIGURATION_get_value_filename (cfg, "arm", "CONFIG",
596                                                  &armconfig))
597     {
598       GNUNET_CONFIGURATION_set_value_string (cfg, "arm", "CONFIG",
599                                              cfgfile);
600     }
601     else
602       GNUNET_free (armconfig);
603   }
604   h = GNUNET_ARM_connect (cfg, &conn_status, NULL);
605   if (NULL != h)
606   {
607     m = GNUNET_ARM_monitor (cfg, &srv_status, NULL);
608     if (NULL != m)
609     {
610       GNUNET_SCHEDULER_add_now (&action_loop, NULL);
611       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
612                                     shutdown_task, NULL);
613     }
614     else
615     {
616       GNUNET_ARM_disconnect_and_free (h);
617       h = NULL;
618     }
619   }
620 }
621
622
623 /**
624  * The main function to obtain arm from gnunetd.
625  *
626  * @param argc number of arguments from the command line
627  * @param argv command line arguments
628  * @return 0 ok, 1 on error
629  */
630 int
631 main (int argc, char *const *argv)
632 {
633   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
634     {'e', "end", NULL, gettext_noop ("stop all GNUnet services"),
635      GNUNET_NO, &GNUNET_GETOPT_set_one, &end},
636     {'i', "init", "SERVICE", gettext_noop ("start a particular service"),
637      GNUNET_YES, &GNUNET_GETOPT_set_string, &init},
638     {'k', "kill", "SERVICE", gettext_noop ("stop a particular service"),
639      GNUNET_YES, &GNUNET_GETOPT_set_string, &term},
640     {'s', "start", NULL, gettext_noop ("start all GNUnet default services"),
641      GNUNET_NO, &GNUNET_GETOPT_set_one, &start},
642     {'r', "restart", NULL,
643      gettext_noop ("stop and start all GNUnet default services"),
644      GNUNET_NO, &GNUNET_GETOPT_set_one, &restart},
645     {'d', "delete", NULL,
646      gettext_noop ("delete config file and directory on exit"),
647      GNUNET_NO, &GNUNET_GETOPT_set_one, &delete},
648     {'q', "quiet", NULL, gettext_noop ("don't print status messages"),
649      GNUNET_NO, &GNUNET_GETOPT_set_one, &quiet},
650     {'T', "timeout", "MSECS",
651      gettext_noop ("timeout in MSECS milliseconds for completing current operation"),
652      GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &timeout},
653     {'I', "info", NULL, gettext_noop ("list currently running services"),
654      GNUNET_NO, &GNUNET_GETOPT_set_one, &list},
655     {'O', "no-stdout", NULL, gettext_noop ("don't let gnunet-service-arm inherit standard output"),
656      GNUNET_NO, &GNUNET_GETOPT_set_one, &no_stdout},
657     {'E', "no-stderr", NULL, gettext_noop ("don't let gnunet-service-arm inherit standard error"),
658      GNUNET_NO, &GNUNET_GETOPT_set_one, &no_stderr},
659     GNUNET_GETOPT_OPTION_END
660   };
661
662   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
663     return 2;
664
665   if (GNUNET_OK ==
666       GNUNET_PROGRAM_run (argc, argv, "gnunet-arm",
667                           gettext_noop
668                           ("Control services and the Automated Restart Manager (ARM)"),
669                           options, &run, NULL))
670     {
671       GNUNET_free ((void *) argv);
672       return ret;
673     }
674   GNUNET_free ((void*) argv);
675   return 1;
676 }
677
678 /* end of gnunet-arm.c */