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