2 * collectd - src/common.c
3 * Copyright (C) 2005,2006 Florian octo Forster
5 * This program is free software; you can redistribute it and/
6 * or modify it under the terms of the GNU General Public Li-
7 * cence as published by the Free Software Foundation; either
8 * version 2 of the Licence, or any later version.
10 * This program is distributed in the hope that it will be use-
11 * ful, but WITHOUT ANY WARRANTY; without even the implied war-
12 * ranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public Licence for more details.
15 * You should have received a copy of the GNU General Public
16 * Licence along with this program; if not, write to the Free
17 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
21 * Florian octo Forster <octo at verplant.org>
22 * Niki W. Waibel <niki.waibel@gmx.net>
26 #include "utils_debug.h"
32 extern int operating_mode;
35 extern kstat_ctl_t *kc;
40 static char *rra_def[] =
42 "RRA:AVERAGE:0.0:1:1500",
43 "RRA:AVERAGE:0.2:6:1500",
44 "RRA:AVERAGE:0.1:180:1680",
45 "RRA:AVERAGE:0.1:2160:1520",
48 "RRA:MIN:0.1:180:1680",
49 "RRA:MIN:0.1:2160:1520",
52 "RRA:MAX:0.1:180:1680",
53 "RRA:MAX:0.1:2160:1520",
56 static int rra_num = 12;
59 static int rra_timespans[] =
68 static int rra_timespans_num = 5;
70 static char *rra_types[] =
77 static int rra_types_num = 3;
78 #endif /* HAVE_LIBRRD */
80 void sstrncpy (char *d, const char *s, int len)
86 char *sstrdup (const char *s)
93 if((r = strdup (s)) == NULL)
95 DBG ("Not enough memory.");
102 void *smalloc (size_t size)
106 if ((r = malloc (size)) == NULL)
108 DBG("Not enough memory.");
116 void sfree (void **ptr)
128 int strsplit (char *string, char **fields, size_t size)
135 while ((fields[i] = strtok (ptr, " \t")) != NULL)
147 int strjoin (char *dst, size_t dst_len,
148 char **fields, size_t fields_num,
155 memset (dst, '\0', dst_len);
162 sep_len = strlen (sep);
164 for (i = 0; i < fields_num; i++)
166 if ((i > 0) && (sep_len > 0))
168 if (dst_len <= sep_len)
171 strncat (dst, sep, dst_len);
175 field_len = strlen (fields[i]);
177 if (dst_len <= field_len)
180 strncat (dst, fields[i], dst_len);
181 dst_len -= field_len;
184 return (strlen (dst));
187 int strsubstitute (char *str, char c_from, char c_to)
208 int escape_slashes (char *buf, int buf_len)
212 if (strcmp (buf, "/") == 0)
217 strncpy (buf, "root", buf_len);
221 /* Move one to the left */
222 memmove (buf, buf + 1, buf_len - 1);
224 for (i = 0; i < buf_len - 1; i++)
228 else if (buf[i] == '/')
236 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
238 if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
241 if ((tv0->tv_sec < tv1->tv_sec)
242 || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
245 ret->tv_sec = tv0->tv_sec - tv1->tv_sec;
246 ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
248 if (ret->tv_nsec < 0)
250 assert (ret->tv_sec > 0);
252 ret->tv_nsec += 1000000000;
259 static int check_create_dir (const char *file_orig)
269 int last_is_file = 1;
274 * Sanity checks first
276 if (file_orig == NULL)
279 if ((len = strlen (file_orig)) < 1)
285 * If `file_orig' ends in a slash the last component is a directory,
286 * otherwise it's a file. Act accordingly..
288 if (file_orig[len - 1] == '/')
292 * Create a copy for `strtok' to destroy
294 strncpy (file_copy, file_orig, 512);
295 file_copy[511] = '\0';
298 * Break into components. This will eat up several slashes in a row and
299 * remove leading and trailing slashes..
303 while ((fields[fields_num] = strtok (ptr, "/")) != NULL)
308 if (fields_num >= 16)
313 * For each component, do..
315 for (i = 0; i < (fields_num - last_is_file); i++)
318 * Do not create directories that start with a dot. This
319 * prevents `../../' attacks and other likely malicious
322 if (fields[i][0] == '.')
324 syslog (LOG_ERR, "Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
329 * Join the components together again
331 if (strjoin (dir, dir_len, fields, i + 1, "/") < 0)
333 syslog (LOG_ERR, "strjoin failed: `%s', component #%i", file_orig, i);
337 if (stat (dir, &statbuf) == -1)
341 if (mkdir (dir, 0755) == -1)
343 syslog (LOG_ERR, "mkdir (%s): %s", dir, strerror (errno));
349 syslog (LOG_ERR, "stat (%s): %s", dir, strerror (errno));
353 else if (!S_ISDIR (statbuf.st_mode))
355 syslog (LOG_ERR, "stat (%s): Not a directory!", dir);
367 static int rra_get (char ***ret)
369 static char **rra_def = NULL;
370 static int rra_num = 0;
372 int rra_max = rra_timespans_num * rra_types_num;
384 if ((rra_num != 0) && (rra_def != NULL))
390 if ((rra_def = (char **) malloc ((rra_max + 1) * sizeof (char *))) == NULL)
392 memset (rra_def, '\0', (rra_max + 1) * sizeof (char *));
394 step = atoi (COLLECTD_STEP);
395 rows = atoi (COLLECTD_ROWS);
397 if ((step <= 0) || (rows <= 0))
404 for (i = 0; i < rra_timespans_num; i++)
406 span = rra_timespans[i];
408 if ((span / step) < rows)
414 cdp_len = (int) floor (((double) span) / ((double) (rows * step)));
416 cdp_num = (int) ceil (((double) span) / ((double) (cdp_len * step)));
418 for (j = 0; j < rra_types_num; j++)
420 if (rra_num >= rra_max)
423 if (snprintf (buffer, sizeof(buffer), "RRA:%s:%3.1f:%u:%u",
424 rra_types[j], COLLECTD_XFF,
425 cdp_len, cdp_num) >= sizeof (buffer))
427 syslog (LOG_ERR, "rra_get: Buffer would have been truncated.");
431 rra_def[rra_num++] = sstrdup (buffer);
436 DBG ("rra_num = %i", rra_num);
437 for (i = 0; i < rra_num; i++)
438 DBG (" %s", rra_def[i]);
444 #endif /* HAVE_LIBRRD */
446 static int log_create_file (char *filename, char **ds_def, int ds_num)
451 if (check_create_dir (filename))
454 log = fopen (filename, "w");
457 syslog (LOG_WARNING, "Failed to create %s: %s", filename,
462 fprintf (log, "epoch");
463 for (i = 0; i < ds_num; i++)
468 name = strchr (ds_def[i], ':');
471 syslog (LOG_WARNING, "Invalid DS definition '%s' for %s",
472 ds_def[i], filename);
479 tmp = strchr (name, ':');
482 syslog (LOG_WARNING, "Invalid DS definition '%s' for %s",
483 ds_def[i], filename);
489 /* The `%.*s' is needed because there is no null-byte behind
491 fprintf(log, ",%.*s", (tmp - name), name);
499 static int log_update_file (char *host, char *file, char *values,
500 char **ds_def, int ds_num)
505 char full_file[1024];
507 /* Cook the values a bit: Substitute colons with commas */
508 strsubstitute (values, ':', ',');
510 /* host == NULL => local mode */
513 if (snprintf (full_file, 1024, "%s/%s", host, file) >= 1024)
518 if (snprintf (full_file, 1024, "%s", file) >= 1024)
522 strncpy (full_file, file, 1024);
524 tmp = full_file + strlen (full_file) - 4;
527 /* Change the filename for logfiles. */
528 if (strncmp (tmp, ".rrd", 4) == 0)
533 /* TODO: Find a way to minimize the calls to `localtime', since
534 * they are pretty expensive.. */
536 tm = localtime (&now);
538 strftime (tmp, 1024 - (tmp - full_file), "-%Y-%m-%d", tm);
540 /* `localtime(3)' returns a pointer to static data,
541 * therefore the pointer may not be free'd. */
544 DBG ("The filename ends with `%s' which is unexpected.", tmp);
546 if (stat (full_file, &statbuf) == -1)
550 if (log_create_file (full_file, ds_def, ds_num))
555 syslog (LOG_ERR, "stat %s: %s", full_file, strerror (errno));
559 else if (!S_ISREG (statbuf.st_mode))
561 syslog (LOG_ERR, "stat %s: Not a regular file!", full_file);
566 fp = fopen (full_file, "a");
569 syslog (LOG_WARNING, "Failed to append to %s: %s", full_file,
573 fprintf(fp, "%s\n", values);
577 } /* int log_update_file */
580 static int rrd_create_file (char *filename, char **ds_def, int ds_num)
589 if (check_create_dir (filename))
592 if ((rra_num = rra_get (&rra_def)) < 1)
594 syslog (LOG_ERR, "rra_create failed: Could not calculate RRAs");
598 argc = ds_num + rra_num + 4;
600 if ((argv = (char **) malloc (sizeof (char *) * (argc + 1))) == NULL)
602 syslog (LOG_ERR, "rrd_create failed: %s", strerror (errno));
609 argv[3] = COLLECTD_STEP;
612 for (i = 0; i < ds_num; i++)
613 argv[j++] = ds_def[i];
614 for (i = 0; i < rra_num; i++)
615 argv[j++] = rra_def[i];
618 optind = 0; /* bug in librrd? */
620 if (rrd_create (argc, argv) == -1)
622 syslog (LOG_ERR, "rrd_create failed: %s: %s", filename, rrd_get_error ());
630 #endif /* HAVE_LIBRRD */
632 int rrd_update_file (char *host, char *file, char *values,
633 char **ds_def, int ds_num)
637 char full_file[1024];
638 char *argv[4] = { "update", full_file, values, NULL };
639 #endif /* HAVE_LIBRRD */
641 /* I'd rather have a function `common_update_file' to make this
642 * decission, but for that we'd need to touch all plugins.. */
643 if (operating_mode == MODE_LOG)
644 return (log_update_file (host, file, values,
648 /* host == NULL => local mode */
651 if (snprintf (full_file, 1024, "%s/%s", host, file) >= 1024)
656 if (snprintf (full_file, 1024, "%s", file) >= 1024)
660 if (stat (full_file, &statbuf) == -1)
664 if (rrd_create_file (full_file, ds_def, ds_num))
669 syslog (LOG_ERR, "stat %s: %s", full_file, strerror (errno));
673 else if (!S_ISREG (statbuf.st_mode))
675 syslog (LOG_ERR, "stat %s: Not a regular file!", full_file);
679 optind = 0; /* bug in librrd? */
681 if (rrd_update (3, argv) == -1)
683 syslog (LOG_WARNING, "rrd_update failed: %s: %s", full_file, rrd_get_error ());
687 /* #endif HAVE_LIBRRD */
690 syslog (LOG_ERR, "`rrd_update_file' was called, but collectd isn't linked against librrd!");
696 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
703 snprintf (ident, 128, "%s,%i,%s", module, instance, name);
706 if (*ksp_ptr == NULL)
708 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
710 syslog (LOG_ERR, "Cound not find kstat %s", ident);
714 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
716 syslog (LOG_WARNING, "kstat %s has wrong type", ident);
723 assert (*ksp_ptr != NULL);
724 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
727 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
729 syslog (LOG_WARNING, "kstat %s could not be read", ident);
733 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
735 syslog (LOG_WARNING, "kstat %s has wrong type", ident);
742 long long get_kstat_value (kstat_t *ksp, char *name)
745 long long retval = -1LL;
748 assert (ksp != NULL);
749 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
753 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
756 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
758 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
763 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
766 if (kn->data_type == KSTAT_DATA_INT32)
767 retval = (long long) kn->value.i32;
768 else if (kn->data_type == KSTAT_DATA_UINT32)
769 retval = (long long) kn->value.ui32;
770 else if (kn->data_type == KSTAT_DATA_INT64)
771 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
772 else if (kn->data_type == KSTAT_DATA_UINT64)
773 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
775 syslog (LOG_WARNING, "get_kstat_value: Not a numeric value: %s", name);
779 #endif /* HAVE_LIBKSTAT */