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