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