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