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