collectdctl: Improved error reporting.
[collectd.git] / src / collectdctl.c
1 /**
2  * collectd - src/collectdctl.c
3  * Copyright (C) 2010 Håkon J Dugstad Johnsen
4  * Copyright (C) 2010 Sebastian Harl
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program 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 along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Håkon J Dugstad Johnsen <hakon-dugstad.johnsen at telenor.com>
21  *   Sebastian "tokkee" Harl <sh@tokkee.org>
22  **/
23
24 #if HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include "libcollectdclient/client.h"
29
30 #include <assert.h>
31
32 #include <errno.h>
33
34 #include <getopt.h>
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include <unistd.h>
41
42 #define DEFAULT_SOCK LOCALSTATEDIR"/run/"PACKAGE_NAME"-unixsock"
43
44 extern char *optarg;
45 extern int   optind;
46
47 static void exit_usage (const char *name, int status) {
48   fprintf ((status == 0) ? stdout : stderr,
49       "Usage: %s [options] <command> [cmd options]\n\n"
50
51       "Available options:\n"
52       "  -s       Path to collectd's UNIX socket.\n"
53       "           Default: "DEFAULT_SOCK"\n"
54
55       "\n  -h       Display this help and exit.\n"
56
57       "\nAvailable commands:\n\n"
58
59       " * getval <identifier>\n"
60       " * flush [timeout=<seconds>] [plugin=<name>] [identifier=<id>]\n"
61       " * listval\n"
62       " * putval <identifier> [interval=<seconds>] <value-list(s)>\n"
63
64       "\nIdentifiers:\n\n"
65
66       "An identifier has the following format:\n\n"
67
68       "  [<hostname>/]<plugin>[-<plugin_instance>]/<type>[-<type_instance>]\n\n"
69
70       "Hostname defaults to the local hostname if omitted (e.g., uptime/uptime).\n"
71       "No error is returned if the specified identifier does not exist.\n"
72
73       "\n"PACKAGE" "VERSION", http://collectd.org/\n"
74       "by Florian octo Forster <octo@verplant.org>\n"
75       "for contributions see `AUTHORS'\n"
76       , name);
77   exit (status);
78 }
79
80 /* Count the number of occurrences of the character 'chr'
81  * in the specified string. */
82 static int count_chars (const char *str, char chr) {
83   int count = 0;
84
85   while (*str != '\0') {
86     if (*str == chr) {
87       count++;
88     }
89     str++;
90   }
91
92   return count;
93 } /* count_chars */
94
95 static int array_grow (void **array, int *array_len, size_t elem_size)
96 {
97   void *tmp;
98
99   assert ((array != NULL) && (array_len != NULL));
100
101   tmp = realloc (*array, (*array_len + 1) * elem_size);
102   if (tmp == NULL) {
103     fprintf (stderr, "ERROR: Failed to allocate memory.\n");
104     return (-1);
105   }
106
107   *array = tmp;
108   ++(*array_len);
109   return (0);
110 } /* array_grow */
111
112 static int parse_identifier (lcc_connection_t *c,
113     const char *value, lcc_identifier_t *ident)
114 {
115   char hostname[1024];
116   char ident_str[1024] = "";
117   int  n_slashes;
118
119   int status;
120
121   n_slashes = count_chars (value, '/');
122   if (n_slashes == 1) {
123     /* The user has omitted the hostname part of the identifier
124      * (there is only one '/' in the identifier)
125      * Let's add the local hostname */
126     if (gethostname (hostname, sizeof (hostname)) != 0) {
127       fprintf (stderr, "ERROR: Failed to get local hostname: %s",
128           strerror (errno));
129       return (-1);
130     }
131     hostname[sizeof (hostname) - 1] = '\0';
132
133     snprintf (ident_str, sizeof (ident_str), "%s/%s", hostname, value);
134     ident_str[sizeof(ident_str) - 1] = '\0';
135   }
136   else {
137     strncpy (ident_str, value, sizeof (ident_str));
138     ident_str[sizeof (ident_str) - 1] = '\0';
139   }
140
141   status = lcc_string_to_identifier (c, ident, ident_str);
142   if (status != 0) {
143     fprintf (stderr, "ERROR: Failed to parse identifier ``%s'': %s.\n",
144         ident_str, lcc_strerror(c));
145     return (-1);
146   }
147   return (0);
148 } /* parse_identifier */
149
150 static int getval (lcc_connection_t *c, int argc, char **argv)
151 {
152   lcc_identifier_t ident;
153
154   size_t   ret_values_num   = 0;
155   gauge_t *ret_values       = NULL;
156   char   **ret_values_names = NULL;
157
158   int status;
159   size_t i;
160
161   assert (strcasecmp (argv[0], "getval") == 0);
162
163   if (argc != 2) {
164     fprintf (stderr, "ERROR: getval: Missing identifier.\n");
165     return (-1);
166   }
167
168   memset (&ident, 0, sizeof (ident));
169   status = parse_identifier (c, argv[1], &ident);
170   if (status != 0)
171     return (status);
172
173 #define BAIL_OUT(s) \
174   do { \
175     if (ret_values != NULL) \
176       free (ret_values); \
177     if (ret_values_names != NULL) { \
178       for (i = 0; i < ret_values_num; ++i) \
179         free (ret_values_names[i]); \
180       free (ret_values_names); \
181     } \
182     ret_values_num = 0; \
183     return (s); \
184   } while (0)
185
186   status = lcc_getval (c, &ident,
187       &ret_values_num, &ret_values, &ret_values_names);
188   if (status != 0) {
189     fprintf (stderr, "ERROR: %s\n", lcc_strerror (c));
190     BAIL_OUT (-1);
191   }
192
193   for (i = 0; i < ret_values_num; ++i)
194     printf ("%s=%e\n", ret_values_names[i], ret_values[i]);
195   BAIL_OUT (0);
196 #undef BAIL_OUT
197 } /* getval */
198
199 static int flush (lcc_connection_t *c, int argc, char **argv)
200 {
201   int timeout = -1;
202
203   lcc_identifier_t *identifiers = NULL;
204   int identifiers_num = 0;
205
206   char **plugins = NULL;
207   int plugins_num = 0;
208
209   int status;
210   int i;
211
212   assert (strcasecmp (argv[0], "flush") == 0);
213
214 #define BAIL_OUT(s) \
215   do { \
216     if (identifiers != NULL) \
217       free (identifiers); \
218     identifiers_num = 0; \
219     if (plugins != NULL) \
220       free (plugins); \
221     plugins_num = 0; \
222     return (s); \
223   } while (0)
224
225   for (i = 1; i < argc; ++i) {
226     char *key, *value;
227
228     key   = argv[i];
229     value = strchr (argv[i], (int)'=');
230
231     if (! value) {
232       fprintf (stderr, "ERROR: flush: Invalid option ``%s''.\n", argv[i]);
233       BAIL_OUT (-1);
234     }
235
236     *value = '\0';
237     ++value;
238
239     if (strcasecmp (key, "timeout") == 0) {
240       char *endptr = NULL;
241
242       timeout = strtol (value, &endptr, 0);
243
244       if (endptr == value) {
245         fprintf (stderr, "ERROR: Failed to parse timeout as number: %s.\n",
246             value);
247         BAIL_OUT (-1);
248       }
249       else if ((endptr != NULL) && (*endptr != '\0')) {
250         fprintf (stderr, "WARNING: Ignoring trailing garbage after timeout: "
251             "%s.\n", endptr);
252       }
253     }
254     else if (strcasecmp (key, "plugin") == 0) {
255       status = array_grow ((void **)&plugins, &plugins_num,
256           sizeof (*plugins));
257       if (status != 0)
258         BAIL_OUT (status);
259
260       plugins[plugins_num - 1] = value;
261     }
262     else if (strcasecmp (key, "identifier") == 0) {
263       status = array_grow ((void **)&identifiers, &identifiers_num,
264           sizeof (*identifiers));
265       if (status != 0)
266         BAIL_OUT (status);
267
268       memset (identifiers + (identifiers_num - 1), 0, sizeof (*identifiers));
269       status = parse_identifier (c, value,
270           identifiers + (identifiers_num - 1));
271       if (status != 0)
272         BAIL_OUT (status);
273     }
274     else {
275       fprintf (stderr, "ERROR: flush: Unknown option `%s'.\n", key);
276       BAIL_OUT (-1);
277     }
278   }
279
280   if (plugins_num == 0) {
281     status = array_grow ((void **)&plugins, &plugins_num, sizeof (*plugins));
282     if (status != 0)
283       BAIL_OUT (status);
284
285     assert (plugins_num == 1);
286     plugins[0] = NULL;
287   }
288
289   for (i = 0; i < plugins_num; ++i) {
290     if (identifiers_num == 0) {
291       status = lcc_flush (c, plugins[i], NULL, timeout);
292       if (status != 0)
293         fprintf (stderr, "ERROR: Failed to flush plugin `%s': %s.\n",
294             (plugins[i] == NULL) ? "(all)" : plugins[i], lcc_strerror (c));
295     }
296     else {
297       int j;
298
299       for (j = 0; j < identifiers_num; ++j) {
300         status = lcc_flush (c, plugins[i], identifiers + j, timeout);
301         if (status != 0) {
302           char id[1024];
303
304           lcc_identifier_to_string (c, id, sizeof (id), identifiers + j);
305           fprintf (stderr, "ERROR: Failed to flush plugin `%s', "
306               "identifier `%s': %s.\n",
307               (plugins[i] == NULL) ? "(all)" : plugins[i],
308               id, lcc_strerror (c));
309         }
310       }
311     }
312   }
313
314   BAIL_OUT (0);
315 #undef BAIL_OUT
316 } /* flush */
317
318 static int listval (lcc_connection_t *c, int argc, char **argv)
319 {
320   lcc_identifier_t *ret_ident     = NULL;
321   size_t            ret_ident_num = 0;
322
323   int status;
324   size_t i;
325
326   assert (strcasecmp (argv[0], "listval") == 0);
327
328   if (argc != 1) {
329     fprintf (stderr, "ERROR: listval: Does not accept any arguments.\n");
330     return (-1);
331   }
332
333 #define BAIL_OUT(s) \
334   do { \
335     if (ret_ident != NULL) \
336       free (ret_ident); \
337     ret_ident_num = 0; \
338     return (s); \
339   } while (0)
340
341   status = lcc_listval (c, &ret_ident, &ret_ident_num);
342   if (status != 0) {
343     fprintf (stderr, "ERROR: %s\n", lcc_strerror (c));
344     BAIL_OUT (status);
345   }
346
347   for (i = 0; i < ret_ident_num; ++i) {
348     char id[1024];
349
350     status = lcc_identifier_to_string (c, id, sizeof (id), ret_ident + i);
351     if (status != 0) {
352       fprintf (stderr, "ERROR: listval: Failed to convert returned "
353           "identifier to a string: %s\n", lcc_strerror (c));
354       continue;
355     }
356
357     printf ("%s\n", id);
358   }
359   BAIL_OUT (0);
360 #undef BAIL_OUT
361 } /* listval */
362
363 static int putval (lcc_connection_t *c, int argc, char **argv)
364 {
365   lcc_value_list_t vl = LCC_VALUE_LIST_INIT;
366
367   /* 64 ought to be enough for anybody ;-) */
368   value_t values[64];
369   int     values_types[64];
370   size_t  values_len = 0;
371
372   int status;
373   int i;
374
375   assert (strcasecmp (argv[0], "putval") == 0);
376
377   if (argc < 3) {
378     fprintf (stderr, "ERROR: putval: Missing identifier "
379         "and/or value list.\n");
380     return (-1);
381   }
382
383   vl.values       = values;
384   vl.values_types = values_types;
385
386   status = parse_identifier (c, argv[1], &vl.identifier);
387   if (status != 0)
388     return (status);
389
390   for (i = 2; i < argc; ++i) {
391     char *tmp;
392
393     tmp = strchr (argv[i], (int)'=');
394
395     if (tmp != NULL) { /* option */
396       char *key   = argv[i];
397       char *value = tmp;
398
399       *value = '\0';
400       ++value;
401
402       if (strcasecmp (key, "interval") == 0) {
403         char *endptr;
404
405         vl.interval = strtol (value, &endptr, 0);
406
407         if (endptr == value) {
408           fprintf (stderr, "ERROR: Failed to parse interval as number: %s.\n",
409               value);
410           return (-1);
411         }
412         else if ((endptr != NULL) && (*endptr != '\0')) {
413           fprintf (stderr, "WARNING: Ignoring trailing garbage after "
414               "interval: %s.\n", endptr);
415         }
416       }
417       else {
418         fprintf (stderr, "ERROR: putval: Unknown option `%s'.\n", key);
419         return (-1);
420       }
421     }
422     else { /* value list */
423       char *value;
424
425       tmp = strchr (argv[i], (int)':');
426
427       if (tmp == NULL) {
428         fprintf (stderr, "ERROR: putval: Invalid value list: %s.\n",
429             argv[i]);
430         return (-1);
431       }
432
433       *tmp = '\0';
434       ++tmp;
435
436       if (strcasecmp (argv[i], "N") == 0) {
437         vl.time = 0;
438       }
439       else {
440         char *endptr;
441
442         vl.time = strtol (argv[i], &endptr, 0);
443
444         if (endptr == value) {
445           fprintf (stderr, "ERROR: Failed to parse time as number: %s.\n",
446               argv[i]);
447           return (-1);
448         }
449         else if ((endptr != NULL) && (*endptr != '\0')) {
450           fprintf (stderr, "ERROR: Garbage after time: %s.\n", endptr);
451           return (-1);
452         }
453       }
454
455       values_len = 0;
456       value = tmp;
457       while (value != 0) {
458         char *dot, *endptr;
459
460         tmp = strchr (argv[i], (int)':');
461
462         if (tmp != NULL) {
463           *tmp = '\0';
464           ++tmp;
465         }
466
467         /* This is a bit of a hack, but parsing types.db just does not make
468          * much sense imho -- the server might have different types defined
469          * anyway. Also, lcc uses the type information for formatting the
470          * number only, so the real meaning does not matter. -tokkee */
471         dot = strchr (value, (int)'.');
472         if (dot) { /* floating point value */
473           values[values_len].gauge = strtod (value, &endptr);
474           values_types[values_len] = LCC_TYPE_GAUGE;
475         }
476         else { /* integer */
477           values[values_len].counter = strtol (value, &endptr, 0);
478           values_types[values_len] = LCC_TYPE_COUNTER;
479         }
480         ++values_len;
481
482         if (endptr == value) {
483           fprintf (stderr, "ERROR: Failed to parse value as number: %s.\n",
484               argv[i]);
485           return (-1);
486         }
487         else if ((endptr != NULL) && (*endptr != '\0')) {
488           fprintf (stderr, "ERROR: Garbage after value: %s.\n", endptr);
489           return (-1);
490         }
491
492         value = tmp;
493       }
494
495       assert (values_len >= 1);
496       vl.values_len = values_len;
497
498       status = lcc_putval (c, &vl);
499       if (status != 0) {
500         fprintf (stderr, "ERROR: %s\n", lcc_strerror (c));
501         return (-1);
502       }
503     }
504   }
505
506   if (values_len == 0) {
507     fprintf (stderr, "ERROR: putval: Missing value list(s).\n");
508     return (-1);
509   }
510   return (0);
511 } /* putval */
512
513 int main (int argc, char **argv) {
514   char address[1024] = "unix:"DEFAULT_SOCK;
515
516   lcc_connection_t *c;
517
518   int status;
519
520   while (42) {
521     int c;
522
523     c = getopt (argc, argv, "s:h");
524
525     if (c == -1)
526       break;
527
528     switch (c) {
529       case 's':
530         snprintf (address, sizeof (address), "unix:%s", optarg);
531         address[sizeof (address) - 1] = '\0';
532         break;
533       case 'h':
534         exit_usage (argv[0], 0);
535         break;
536       default:
537         exit_usage (argv[0], 1);
538     }
539   }
540
541   if (optind >= argc) {
542     fprintf (stderr, "%s: missing command\n", argv[0]);
543     exit_usage (argv[0], 1);
544   }
545
546   c = NULL;
547   status = lcc_connect (address, &c);
548   if (status != 0) {
549     fprintf (stderr, "ERROR: Failed to connect to daemon at %s: %s.\n",
550         address, strerror (errno));
551     return (1);
552   }
553
554   if (strcasecmp (argv[optind], "getval") == 0)
555     status = getval (c, argc - optind, argv + optind);
556   else if (strcasecmp (argv[optind], "flush") == 0)
557     status = flush (c, argc - optind, argv + optind);
558   else if (strcasecmp (argv[optind], "listval") == 0)
559     status = listval (c, argc - optind, argv + optind);
560   else if (strcasecmp (argv[optind], "putval") == 0)
561     status = putval (c, argc - optind, argv + optind);
562   else {
563     fprintf (stderr, "%s: invalid command: %s\n", argv[0], argv[optind]);
564     return (1);
565   }
566
567   LCC_DESTROY (c);
568
569   if (status != 0)
570     return (status);
571   return (0);
572 } /* main */
573
574 /* vim: set sw=2 ts=2 tw=78 expandtab : */
575