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