- fix 2699
[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  * Our configuration.
115  */
116 static struct GNUNET_CONFIGURATION_Handle *cfg;
117
118 /**
119  * Processing stage that we are in.  Simple counter.
120  */
121 static unsigned int phase;
122
123 /**
124  * User defined timestamp for completing operations.
125  */
126 static struct GNUNET_TIME_Relative timeout;
127
128 /**
129  * Do we want to give our stdout to gnunet-service-arm?
130  */
131 static unsigned int no_stdout;
132
133 /**
134  * Do we want to give our stderr to gnunet-service-arm?
135  */
136 static unsigned int no_stderr;
137
138
139 /**
140  * Main continuation-passing-style loop.  Runs the various
141  * jobs that we've been asked to do in order.
142  *
143  * @param cls closure, unused
144  * @param tc context, unused
145  */
146 static void
147 cps_loop (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
148
149
150 /**
151  * Callback invoked with the status of the last operation.  Reports to the
152  * user and then runs the next phase in the FSM.
153  *
154  * @param cls pointer to "const char*" identifying service that was manipulated
155  * @param result result of the operation
156  */
157 static void
158 confirm_cb (void *cls, 
159             enum GNUNET_ARM_ProcessStatus result)
160 {
161   const char *service = cls;
162
163   switch (result)
164   {
165   case GNUNET_ARM_PROCESS_UNKNOWN:
166     FPRINTF (stderr, _("Service `%s' is unknown to ARM.\n"), service);
167     ret = 1;
168     break;
169   case GNUNET_ARM_PROCESS_DOWN:
170     if (quiet != GNUNET_YES)
171       FPRINTF (stdout, _("Service `%s' has been stopped.\n"), service);
172     break;
173   case GNUNET_ARM_PROCESS_ALREADY_RUNNING:
174     FPRINTF (stderr, _("Service `%s' was already running.\n"), service);
175     ret = 1;
176     break;
177   case GNUNET_ARM_PROCESS_STARTING:
178     if (quiet != GNUNET_YES)
179       FPRINTF (stdout, _("Service `%s' has been started.\n"), service);
180     break;
181   case GNUNET_ARM_PROCESS_ALREADY_STOPPING:
182     FPRINTF (stderr, _("Service `%s' was already being stopped.\n"), service);
183     ret = 1;
184     break;
185   case GNUNET_ARM_PROCESS_ALREADY_DOWN:
186     FPRINTF (stderr, _("Service `%s' was already not running.\n"), service);
187     ret = 1;
188     break;
189   case GNUNET_ARM_PROCESS_SHUTDOWN:
190     FPRINTF (stderr, "%s", _("Request ignored as ARM is shutting down.\n"));
191     ret = 1;
192     break;
193   case GNUNET_ARM_PROCESS_COMMUNICATION_ERROR:
194     FPRINTF (stderr, "%s", _("Error communicating with ARM service.\n"));
195     ret = 1;
196     break;
197   case GNUNET_ARM_PROCESS_COMMUNICATION_TIMEOUT:
198     FPRINTF (stderr, "%s",  _("Timeout communicating with ARM service.\n"));
199     ret = 1;
200     break;
201   case GNUNET_ARM_PROCESS_FAILURE:
202     FPRINTF (stderr, "%s",  _("Operation failed.\n"));
203     ret = 1;
204     break;
205   default:
206     FPRINTF (stderr, "%s",  _("Unknown response code from ARM.\n"));
207     break;
208   }
209   GNUNET_SCHEDULER_add_now (&cps_loop, NULL);
210 }
211
212
213 /**
214  * Callback invoked with the list of running services.  
215  * Reports to the user and then runs the next phase in the FSM.
216  *
217  * @param cls currently not used
218  * @param result result of the operation
219  * @param count number of running services
220  * @param list copy of the list of running services
221  */
222 static void
223 list_cb (void *cls, int result, unsigned int count, const char *const*list)
224 {
225   unsigned int i;
226
227   if ( (result != GNUNET_YES) || (NULL == list) )
228   {
229     FPRINTF (stderr, "%s", _("Error communicating with ARM. ARM not running?\n"));
230     return;
231   }
232   FPRINTF (stdout, "%s", _("Running services:\n"));
233   for (i=0; i<count; i++)
234     FPRINTF (stdout, "%s\n", list[i]);
235 }
236
237
238 /**
239  * Attempts to delete configuration file and SERVICEHOME
240  * on arm shutdown provided the end and delete options
241  * were specified when gnunet-arm was run.
242  */
243 static void
244 delete_files ()
245 {
246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
247               "Will attempt to remove configuration file %s and service directory %s\n",
248               config_file, dir);
249
250   if (UNLINK (config_file) != 0)
251     {
252       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
253                   _("Failed to remove configuration file %s\n"), config_file);
254     }
255
256   if (GNUNET_DISK_directory_remove (dir) != GNUNET_OK)
257     {
258       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
259                   _("Failed to remove servicehome directory %s\n"), dir);
260
261     }
262 }
263
264
265 /**
266  * Main continuation-passing-style loop.  Runs the various
267  * jobs that we've been asked to do in order.
268  *
269  * @param cls closure, unused
270  * @param tc context, unused
271  */
272 static void
273 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
274 {
275   GNUNET_ARM_disconnect (h);
276   h = NULL;
277   if ((end == GNUNET_YES) && (delete == GNUNET_YES))
278     delete_files ();    
279   GNUNET_CONFIGURATION_destroy (cfg);
280   cfg = NULL;
281 }
282
283
284 /**
285  * Main function that will be run by the scheduler.
286  *
287  * @param cls closure
288  * @param args remaining command-line arguments
289  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
290  * @param c configuration
291  */
292 static void
293 run (void *cls, char *const *args, const char *cfgfile,
294      const struct GNUNET_CONFIGURATION_Handle *c)
295 {
296   char *armconfig;
297
298   cfg = GNUNET_CONFIGURATION_dup (c);
299   config_file = cfgfile;
300   if (GNUNET_CONFIGURATION_get_value_string
301       (cfg, "PATHS", "SERVICEHOME", &dir) != GNUNET_OK)
302   {
303     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
304                                "PATHS", "SERVICEHOME");
305     return;
306     }
307   if (NULL != cfgfile)
308   {
309     if (GNUNET_OK !=
310         GNUNET_CONFIGURATION_get_value_filename (cfg, "arm", "CONFIG",
311                                                  &armconfig))
312     {
313       GNUNET_CONFIGURATION_set_value_string (cfg, "arm", "CONFIG",
314                                              cfgfile);
315     }
316     else
317       GNUNET_free (armconfig);
318   }
319   if (NULL == (h = GNUNET_ARM_connect (cfg, NULL)))
320   {
321     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
322                 _("Fatal error initializing ARM API.\n"));
323     ret = 1;
324     GNUNET_CONFIGURATION_destroy (cfg);
325     cfg = NULL;
326     return;
327   }
328   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
329                                 &shutdown_task, NULL);
330   GNUNET_SCHEDULER_add_now (&cps_loop, NULL);
331 }
332
333
334 /**
335  * Main continuation-passing-style loop.  Runs the various
336  * jobs that we've been asked to do in order.
337  *
338  * @param cls closure, unused
339  * @param tc context, unused
340  */
341 static void
342 cps_loop (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
343 {
344   if (NULL == h)
345     return;
346   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
347     return;
348   while (1)
349   {
350     switch (phase++)
351     {
352     case 0:
353       if (NULL != term)
354       {
355         GNUNET_ARM_stop_service (h, term,
356                                  (0 ==
357                                   timeout.rel_value) ? STOP_TIMEOUT :
358                                  timeout, &confirm_cb, term);
359         return;
360       }
361       break;
362     case 1:
363       if ((end) || (restart))
364       {
365         GNUNET_ARM_stop_service (h, "arm",
366                                  (0 ==
367                                   timeout.rel_value) ? STOP_TIMEOUT_ARM
368                                  : timeout, &confirm_cb, "arm");
369         return;
370       }
371       break;
372     case 2:
373       if (start)
374       {
375         GNUNET_ARM_start_service (h, "arm",
376                                   (no_stdout ? 0 : GNUNET_OS_INHERIT_STD_OUT) |
377                                   (no_stderr ? 0 : GNUNET_OS_INHERIT_STD_ERR),
378                                   (0 ==
379                                    timeout.rel_value) ? START_TIMEOUT :
380                                   timeout, &confirm_cb, "arm");
381         return;
382       }
383       break;
384     case 3:
385       if (NULL != init)
386        {
387          GNUNET_ARM_start_service (h, init,
388                                    (no_stdout ? 0 : GNUNET_OS_INHERIT_STD_OUT) |
389                                    (no_stderr ? 0 : GNUNET_OS_INHERIT_STD_ERR),
390                                    (0 ==
391                                     timeout.rel_value) ? START_TIMEOUT :
392                                    timeout, &confirm_cb, init);
393          return;
394        }
395       break;
396     case 4:
397       if (restart)
398       {
399         GNUNET_ARM_disconnect (h);
400         phase = 0;
401         end = 0;
402         start = 1;
403         restart = 0;
404         if (NULL == (h = GNUNET_ARM_connect (cfg, NULL)))
405         {
406           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
407                       _("Fatal error initializing ARM API.\n"));
408           ret = 1;
409           return;
410         }
411         GNUNET_SCHEDULER_add_now (&cps_loop, NULL);
412         return;
413       }
414       break;
415     case 5:
416       if (list) 
417       {
418         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
419                     "Going to list all running services controlled by ARM.\n");
420         
421         if (NULL == h) 
422         {
423           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
424                       _("Fatal error initializing ARM API.\n"));
425           return;
426         }       
427         GNUNET_ARM_list_running_services (h, 
428                                           (0 == 
429                                            timeout.rel_value) ? LIST_TIMEOUT : 
430                                           timeout, &list_cb, NULL);
431         return;
432       }
433       /* Fall through */
434     default:            /* last phase */
435       GNUNET_SCHEDULER_shutdown ();
436       return;
437     }
438   }
439 }
440
441
442 /**
443  * The main function to obtain arm from gnunetd.
444  *
445  * @param argc number of arguments from the command line
446  * @param argv command line arguments
447  * @return 0 ok, 1 on error
448  */
449 int
450 main (int argc, char *const *argv)
451 {
452   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
453     {'e', "end", NULL, gettext_noop ("stop all GNUnet services"),
454      GNUNET_NO, &GNUNET_GETOPT_set_one, &end},
455     {'i', "init", "SERVICE", gettext_noop ("start a particular service"),
456      GNUNET_YES, &GNUNET_GETOPT_set_string, &init},
457     {'k', "kill", "SERVICE", gettext_noop ("stop a particular service"),
458      GNUNET_YES, &GNUNET_GETOPT_set_string, &term},
459     {'s', "start", NULL, gettext_noop ("start all GNUnet default services"),
460      GNUNET_NO, &GNUNET_GETOPT_set_one, &start},
461     {'r', "restart", NULL,
462      gettext_noop ("stop and start all GNUnet default services"),
463      GNUNET_NO, &GNUNET_GETOPT_set_one, &restart},
464     {'d', "delete", NULL,
465      gettext_noop ("delete config file and directory on exit"),
466      GNUNET_NO, &GNUNET_GETOPT_set_one, &delete},
467     {'q', "quiet", NULL, gettext_noop ("don't print status messages"),
468      GNUNET_NO, &GNUNET_GETOPT_set_one, &quiet},
469     {'T', "timeout", "MSECS",
470      gettext_noop ("timeout in MSECS milliseconds for completing current operation"),
471      GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &timeout},
472     {'I', "info", NULL, gettext_noop ("list currently running services"),
473      GNUNET_NO, &GNUNET_GETOPT_set_one, &list},
474     {'O', "no-stdout", NULL, gettext_noop ("don't let gnunet-service-arm inherit standard output"),
475      GNUNET_NO, &GNUNET_GETOPT_set_one, &no_stdout},
476     {'E', "no-stderr", NULL, gettext_noop ("don't let gnunet-service-arm inherit standard error"),
477      GNUNET_NO, &GNUNET_GETOPT_set_one, &no_stderr},
478     GNUNET_GETOPT_OPTION_END
479   };
480
481   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
482     return 2;
483
484   if (GNUNET_OK ==
485       GNUNET_PROGRAM_run (argc, argv, "gnunet-arm",
486                           gettext_noop
487                           ("Control services and the Automated Restart Manager (ARM)"),
488                           options, &run, NULL))
489     {
490       GNUNET_free ((void *) argv);
491       return ret;
492     }
493   GNUNET_free ((void*) argv);
494   return 1;
495 }
496
497 /* end of gnunet-arm.c */