Various plugins: Use the global GAUGE_FORMAT.
[collectd.git] / src / rrdtool.c
1 /**
2  * collectd - src/rrdtool.c
3  * Copyright (C) 2006-2013  Florian octo Forster
4  * Copyright (C) 2008-2008  Sebastian Harl
5  * Copyright (C) 2009       Mariusz Gronczewski
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Sebastian Harl <sh at tokkee.org>
23  *   Mariusz Gronczewski <xani666 at gmail.com>
24  **/
25
26 #include "collectd.h"
27 #include "plugin.h"
28 #include "common.h"
29 #include "utils_avltree.h"
30 #include "utils_random.h"
31 #include "utils_rrdcreate.h"
32
33 #include <rrd.h>
34
35 #if HAVE_PTHREAD_H
36 # include <pthread.h>
37 #endif
38
39 /*
40  * Private types
41  */
42 struct rrd_cache_s
43 {
44         int      values_num;
45         char   **values;
46         cdtime_t first_value;
47         cdtime_t last_value;
48         int64_t  random_variation;
49         enum
50         {
51                 FLAG_NONE   = 0x00,
52                 FLAG_QUEUED = 0x01,
53                 FLAG_FLUSHQ = 0x02
54         } flags;
55 };
56 typedef struct rrd_cache_s rrd_cache_t;
57
58 enum rrd_queue_dir_e
59 {
60   QUEUE_INSERT_FRONT,
61   QUEUE_INSERT_BACK
62 };
63 typedef enum rrd_queue_dir_e rrd_queue_dir_t;
64
65 struct rrd_queue_s
66 {
67         char *filename;
68         struct rrd_queue_s *next;
69 };
70 typedef struct rrd_queue_s rrd_queue_t;
71
72 /*
73  * Private variables
74  */
75 static const char *config_keys[] =
76 {
77         "CacheTimeout",
78         "CacheFlush",
79         "CreateFilesAsync",
80         "DataDir",
81         "StepSize",
82         "HeartBeat",
83         "RRARows",
84         "RRATimespan",
85         "XFF",
86         "WritesPerSecond",
87         "RandomTimeout"
88 };
89 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
90
91 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
92  * is zero a default, depending on the `interval' member of the value list is
93  * being used. */
94 static char *datadir   = NULL;
95 static double write_rate = 0.0;
96 static rrdcreate_config_t rrdcreate_config =
97 {
98         /* stepsize = */ 0,
99         /* heartbeat = */ 0,
100         /* rrarows = */ 1200,
101         /* xff = */ 0.1,
102
103         /* timespans = */ NULL,
104         /* timespans_num = */ 0,
105
106         /* consolidation_functions = */ NULL,
107         /* consolidation_functions_num = */ 0,
108
109         /* async = */ 0
110 };
111
112 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
113  * ALWAYS lock `cache_lock' first! */
114 static cdtime_t    cache_timeout = 0;
115 static cdtime_t    cache_flush_timeout = 0;
116 static cdtime_t    random_timeout = TIME_T_TO_CDTIME_T (1);
117 static cdtime_t    cache_flush_last;
118 static c_avl_tree_t *cache = NULL;
119 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
120
121 static rrd_queue_t    *queue_head = NULL;
122 static rrd_queue_t    *queue_tail = NULL;
123 static rrd_queue_t    *flushq_head = NULL;
124 static rrd_queue_t    *flushq_tail = NULL;
125 static pthread_t       queue_thread;
126 static int             queue_thread_running = 1;
127 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
128 static pthread_cond_t  queue_cond = PTHREAD_COND_INITIALIZER;
129
130 #if !HAVE_THREADSAFE_LIBRRD
131 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
132 #endif
133
134 static int do_shutdown = 0;
135
136 #if HAVE_THREADSAFE_LIBRRD
137 static int srrd_update (char *filename, char *template,
138                 int argc, const char **argv)
139 {
140         int status;
141
142         optind = 0; /* bug in librrd? */
143         rrd_clear_error ();
144
145         status = rrd_update_r (filename, template, argc, (void *) argv);
146
147         if (status != 0)
148         {
149                 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
150                                 filename, rrd_get_error ());
151         }
152
153         return (status);
154 } /* int srrd_update */
155 /* #endif HAVE_THREADSAFE_LIBRRD */
156
157 #else /* !HAVE_THREADSAFE_LIBRRD */
158 static int srrd_update (char *filename, char *template,
159                 int argc, const char **argv)
160 {
161         int status;
162
163         int new_argc;
164         char **new_argv;
165
166         assert (template == NULL);
167
168         new_argc = 2 + argc;
169         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
170         if (new_argv == NULL)
171         {
172                 ERROR ("rrdtool plugin: malloc failed.");
173                 return (-1);
174         }
175
176         new_argv[0] = "update";
177         new_argv[1] = filename;
178
179         memcpy (new_argv + 2, argv, argc * sizeof (char *));
180         new_argv[new_argc] = NULL;
181
182         pthread_mutex_lock (&librrd_lock);
183         optind = 0; /* bug in librrd? */
184         rrd_clear_error ();
185
186         status = rrd_update (new_argc, new_argv);
187         pthread_mutex_unlock (&librrd_lock);
188
189         if (status != 0)
190         {
191                 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
192                                 filename, rrd_get_error ());
193         }
194
195         sfree (new_argv);
196
197         return (status);
198 } /* int srrd_update */
199 #endif /* !HAVE_THREADSAFE_LIBRRD */
200
201 static int value_list_to_string_multiple (char *buffer, int buffer_len,
202                 const data_set_t *ds, const value_list_t *vl)
203 {
204         int offset;
205         int status;
206         time_t tt;
207         int i;
208
209         memset (buffer, '\0', buffer_len);
210
211         tt = CDTIME_T_TO_TIME_T (vl->time);
212         status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) tt);
213         if ((status < 1) || (status >= buffer_len))
214                 return (-1);
215         offset = status;
216
217         for (i = 0; i < ds->ds_num; i++)
218         {
219                 if ((ds->ds[i].type != DS_TYPE_COUNTER)
220                                 && (ds->ds[i].type != DS_TYPE_GAUGE)
221                                 && (ds->ds[i].type != DS_TYPE_DERIVE)
222                                 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
223                         return (-1);
224
225                 if (ds->ds[i].type == DS_TYPE_COUNTER)
226                         status = ssnprintf (buffer + offset, buffer_len - offset,
227                                         ":%llu", vl->values[i].counter);
228                 else if (ds->ds[i].type == DS_TYPE_GAUGE)
229                         status = ssnprintf (buffer + offset, buffer_len - offset,
230                                         ":"GAUGE_FORMAT, vl->values[i].gauge);
231                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
232                         status = ssnprintf (buffer + offset, buffer_len - offset,
233                                         ":%"PRIi64, vl->values[i].derive);
234                 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
235                         status = ssnprintf (buffer + offset, buffer_len - offset,
236                                         ":%"PRIu64, vl->values[i].absolute);
237
238                 if ((status < 1) || (status >= (buffer_len - offset)))
239                         return (-1);
240
241                 offset += status;
242         } /* for ds->ds_num */
243
244         return (0);
245 } /* int value_list_to_string_multiple */
246
247 static int value_list_to_string (char *buffer, int buffer_len,
248                 const data_set_t *ds, const value_list_t *vl)
249 {
250         int status;
251         time_t tt;
252
253         if (ds->ds_num != 1)
254                 return (value_list_to_string_multiple (buffer, buffer_len,
255                                         ds, vl));
256
257         tt = CDTIME_T_TO_TIME_T (vl->time);
258         switch (ds->ds[0].type)
259         {
260                 case DS_TYPE_DERIVE:
261                         status = ssnprintf (buffer, buffer_len, "%u:%"PRIi64,
262                                 (unsigned) tt, vl->values[0].derive);
263                         break;
264                 case DS_TYPE_GAUGE:
265                         status = ssnprintf (buffer, buffer_len, "%u:"GAUGE_FORMAT,
266                                 (unsigned) tt, vl->values[0].gauge);
267                         break;
268                 case DS_TYPE_COUNTER:
269                         status = ssnprintf (buffer, buffer_len, "%u:%llu",
270                                 (unsigned) tt, vl->values[0].counter);
271                         break;
272                 case DS_TYPE_ABSOLUTE:
273                         status = ssnprintf (buffer, buffer_len, "%u:%"PRIu64,
274                                 (unsigned) tt, vl->values[0].absolute);
275                         break;
276                 default:
277                         return (EINVAL);
278         }
279
280         if ((status < 1) || (status >= buffer_len))
281                 return (ENOMEM);
282
283         return (0);
284 } /* int value_list_to_string */
285
286 static int value_list_to_filename (char *buffer, size_t buffer_size,
287                 value_list_t const *vl)
288 {
289         char const suffix[] = ".rrd";
290         int status;
291         size_t len;
292
293         if (datadir != NULL)
294         {
295                 size_t datadir_len = strlen (datadir) + 1;
296
297                 if (datadir_len >= buffer_size)
298                         return (ENOMEM);
299
300                 sstrncpy (buffer, datadir, buffer_size);
301                 buffer[datadir_len - 1] = '/';
302                 buffer[datadir_len] = 0;
303
304                 buffer += datadir_len;
305                 buffer_size -= datadir_len;
306         }
307
308         status = FORMAT_VL (buffer, buffer_size, vl);
309         if (status != 0)
310                 return (status);
311
312         len = strlen (buffer);
313         assert (len < buffer_size);
314         buffer += len;
315         buffer_size -= len;
316
317         if (buffer_size <= sizeof (suffix))
318                 return (ENOMEM);
319
320         memcpy (buffer, suffix, sizeof (suffix));
321         return (0);
322 } /* int value_list_to_filename */
323
324 static void *rrd_queue_thread (void __attribute__((unused)) *data)
325 {
326         struct timeval tv_next_update;
327         struct timeval tv_now;
328
329         gettimeofday (&tv_next_update, /* timezone = */ NULL);
330
331         while (42)
332         {
333                 rrd_queue_t *queue_entry;
334                 rrd_cache_t *cache_entry;
335                 char **values;
336                 int    values_num;
337                 int    status;
338                 int    i;
339
340                 values = NULL;
341                 values_num = 0;
342
343                 pthread_mutex_lock (&queue_lock);
344                 /* Wait for values to arrive */
345                 while (42)
346                 {
347                   struct timespec ts_wait;
348
349                   while ((flushq_head == NULL) && (queue_head == NULL)
350                       && (do_shutdown == 0))
351                     pthread_cond_wait (&queue_cond, &queue_lock);
352
353                   if ((flushq_head == NULL) && (queue_head == NULL))
354                     break;
355
356                   /* Don't delay if there's something to flush */
357                   if (flushq_head != NULL)
358                     break;
359
360                   /* Don't delay if we're shutting down */
361                   if (do_shutdown != 0)
362                     break;
363
364                   /* Don't delay if no delay was configured. */
365                   if (write_rate <= 0.0)
366                     break;
367
368                   gettimeofday (&tv_now, /* timezone = */ NULL);
369                   status = timeval_cmp (tv_next_update, tv_now, NULL);
370                   /* We're good to go */
371                   if (status <= 0)
372                     break;
373
374                   /* We're supposed to wait a bit with this update, so we'll
375                    * wait for the next addition to the queue or to the end of
376                    * the wait period - whichever comes first. */
377                   ts_wait.tv_sec = tv_next_update.tv_sec;
378                   ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
379
380                   status = pthread_cond_timedwait (&queue_cond, &queue_lock,
381                       &ts_wait);
382                   if (status == ETIMEDOUT)
383                     break;
384                 } /* while (42) */
385
386                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
387                  * the same time, ALWAYS lock `cache_lock' first! */
388
389                 /* We're in the shutdown phase */
390                 if ((flushq_head == NULL) && (queue_head == NULL))
391                 {
392                   pthread_mutex_unlock (&queue_lock);
393                   break;
394                 }
395
396                 if (flushq_head != NULL)
397                 {
398                   /* Dequeue the first flush entry */
399                   queue_entry = flushq_head;
400                   if (flushq_head == flushq_tail)
401                     flushq_head = flushq_tail = NULL;
402                   else
403                     flushq_head = flushq_head->next;
404                 }
405                 else /* if (queue_head != NULL) */
406                 {
407                   /* Dequeue the first regular entry */
408                   queue_entry = queue_head;
409                   if (queue_head == queue_tail)
410                     queue_head = queue_tail = NULL;
411                   else
412                     queue_head = queue_head->next;
413                 }
414
415                 /* Unlock the queue again */
416                 pthread_mutex_unlock (&queue_lock);
417
418                 /* We now need the cache lock so the entry isn't updated while
419                  * we make a copy of it's values */
420                 pthread_mutex_lock (&cache_lock);
421
422                 status = c_avl_get (cache, queue_entry->filename,
423                                 (void *) &cache_entry);
424
425                 if (status == 0)
426                 {
427                         values = cache_entry->values;
428                         values_num = cache_entry->values_num;
429
430                         cache_entry->values = NULL;
431                         cache_entry->values_num = 0;
432                         cache_entry->flags = FLAG_NONE;
433                 }
434
435                 pthread_mutex_unlock (&cache_lock);
436
437                 if (status != 0)
438                 {
439                         sfree (queue_entry->filename);
440                         sfree (queue_entry);
441                         continue;
442                 }
443
444                 /* Update `tv_next_update' */
445                 if (write_rate > 0.0) 
446                 {
447                   gettimeofday (&tv_now, /* timezone = */ NULL);
448                   tv_next_update.tv_sec = tv_now.tv_sec;
449                   tv_next_update.tv_usec = tv_now.tv_usec
450                     + ((suseconds_t) (1000000 * write_rate));
451                   while (tv_next_update.tv_usec > 1000000)
452                   {
453                     tv_next_update.tv_sec++;
454                     tv_next_update.tv_usec -= 1000000;
455                   }
456                 }
457
458                 /* Write the values to the RRD-file */
459                 srrd_update (queue_entry->filename, NULL,
460                                 values_num, (const char **)values);
461                 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
462                                 values_num, (values_num == 1) ? "" : "s",
463                                 queue_entry->filename);
464
465                 for (i = 0; i < values_num; i++)
466                 {
467                         sfree (values[i]);
468                 }
469                 sfree (values);
470                 sfree (queue_entry->filename);
471                 sfree (queue_entry);
472         } /* while (42) */
473
474         pthread_exit ((void *) 0);
475         return ((void *) 0);
476 } /* void *rrd_queue_thread */
477
478 static int rrd_queue_enqueue (const char *filename,
479     rrd_queue_t **head, rrd_queue_t **tail)
480 {
481   rrd_queue_t *queue_entry;
482
483   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
484   if (queue_entry == NULL)
485     return (-1);
486
487   queue_entry->filename = strdup (filename);
488   if (queue_entry->filename == NULL)
489   {
490     free (queue_entry);
491     return (-1);
492   }
493
494   queue_entry->next = NULL;
495
496   pthread_mutex_lock (&queue_lock);
497
498   if (*tail == NULL)
499     *head = queue_entry;
500   else
501     (*tail)->next = queue_entry;
502   *tail = queue_entry;
503
504   pthread_cond_signal (&queue_cond);
505   pthread_mutex_unlock (&queue_lock);
506
507   return (0);
508 } /* int rrd_queue_enqueue */
509
510 static int rrd_queue_dequeue (const char *filename,
511     rrd_queue_t **head, rrd_queue_t **tail)
512 {
513   rrd_queue_t *this;
514   rrd_queue_t *prev;
515
516   pthread_mutex_lock (&queue_lock);
517
518   prev = NULL;
519   this = *head;
520
521   while (this != NULL)
522   {
523     if (strcmp (this->filename, filename) == 0)
524       break;
525     
526     prev = this;
527     this = this->next;
528   }
529
530   if (this == NULL)
531   {
532     pthread_mutex_unlock (&queue_lock);
533     return (-1);
534   }
535
536   if (prev == NULL)
537     *head = this->next;
538   else
539     prev->next = this->next;
540
541   if (this->next == NULL)
542     *tail = prev;
543
544   pthread_mutex_unlock (&queue_lock);
545
546   sfree (this->filename);
547   sfree (this);
548
549   return (0);
550 } /* int rrd_queue_dequeue */
551
552 /* XXX: You must hold "cache_lock" when calling this function! */
553 static void rrd_cache_flush (cdtime_t timeout)
554 {
555         rrd_cache_t *rc;
556         cdtime_t     now;
557
558         char **keys = NULL;
559         int    keys_num = 0;
560
561         char *key;
562         c_avl_iterator_t *iter;
563         int i;
564
565         DEBUG ("rrdtool plugin: Flushing cache, timeout = %.3f",
566                         CDTIME_T_TO_DOUBLE (timeout));
567
568         now = cdtime ();
569         timeout = TIME_T_TO_CDTIME_T (timeout);
570
571         /* Build a list of entries to be flushed */
572         iter = c_avl_get_iterator (cache);
573         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
574         {
575                 if (rc->flags != FLAG_NONE)
576                         continue;
577                 /* timeout == 0  =>  flush everything */
578                 else if ((timeout != 0)
579                                 && ((now - rc->first_value) < timeout))
580                         continue;
581                 else if (rc->values_num > 0)
582                 {
583                         int status;
584
585                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
586                         if (status == 0)
587                                 rc->flags = FLAG_QUEUED;
588                 }
589                 else /* ancient and no values -> waste of memory */
590                 {
591                         char **tmp = (char **) realloc ((void *) keys,
592                                         (keys_num + 1) * sizeof (char *));
593                         if (tmp == NULL)
594                         {
595                                 char errbuf[1024];
596                                 ERROR ("rrdtool plugin: "
597                                                 "realloc failed: %s",
598                                                 sstrerror (errno, errbuf,
599                                                         sizeof (errbuf)));
600                                 c_avl_iterator_destroy (iter);
601                                 sfree (keys);
602                                 return;
603                         }
604                         keys = tmp;
605                         keys[keys_num] = key;
606                         keys_num++;
607                 }
608         } /* while (c_avl_iterator_next) */
609         c_avl_iterator_destroy (iter);
610         
611         for (i = 0; i < keys_num; i++)
612         {
613                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
614                 {
615                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
616                         continue;
617                 }
618
619                 assert (rc->values == NULL);
620                 assert (rc->values_num == 0);
621
622                 sfree (rc);
623                 sfree (key);
624                 keys[i] = NULL;
625         } /* for (i = 0..keys_num) */
626
627         sfree (keys);
628
629         cache_flush_last = now;
630 } /* void rrd_cache_flush */
631
632 static int rrd_cache_flush_identifier (cdtime_t timeout,
633     const char *identifier)
634 {
635   rrd_cache_t *rc;
636   cdtime_t now;
637   int status;
638   char key[2048];
639
640   if (identifier == NULL)
641   {
642     rrd_cache_flush (timeout);
643     return (0);
644   }
645
646   now = cdtime ();
647
648   if (datadir == NULL)
649     snprintf (key, sizeof (key), "%s.rrd",
650         identifier);
651   else
652     snprintf (key, sizeof (key), "%s/%s.rrd",
653         datadir, identifier);
654   key[sizeof (key) - 1] = 0;
655
656   status = c_avl_get (cache, key, (void *) &rc);
657   if (status != 0)
658   {
659     INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
660         "c_avl_get (%s) failed. Does that file really exist?",
661         key);
662     return (status);
663   }
664
665   if (rc->flags == FLAG_FLUSHQ)
666   {
667     status = 0;
668   }
669   else if (rc->flags == FLAG_QUEUED)
670   {
671     rrd_queue_dequeue (key, &queue_head, &queue_tail);
672     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
673     if (status == 0)
674       rc->flags = FLAG_FLUSHQ;
675   }
676   else if ((now - rc->first_value) < timeout)
677   {
678     status = 0;
679   }
680   else if (rc->values_num > 0)
681   {
682     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
683     if (status == 0)
684       rc->flags = FLAG_FLUSHQ;
685   }
686
687   return (status);
688 } /* int rrd_cache_flush_identifier */
689
690 static int64_t rrd_get_random_variation (void)
691 {
692   long min;
693   long max;
694
695   if (random_timeout <= 0)
696     return (0);
697
698   /* Assure that "cache_timeout + random_variation" is never negative. */
699   if (random_timeout > cache_timeout)
700   {
701           INFO ("rrdtool plugin: Adjusting \"RandomTimeout\" to %.3f seconds.",
702                           CDTIME_T_TO_DOUBLE (cache_timeout));
703           random_timeout = cache_timeout;
704   }
705
706   max = (long) (random_timeout / 2);
707   min = max - ((long) random_timeout);
708
709   return ((int64_t) cdrand_range (min, max));
710 } /* int64_t rrd_get_random_variation */
711
712 static int rrd_cache_insert (const char *filename,
713                 const char *value, cdtime_t value_time)
714 {
715         rrd_cache_t *rc = NULL;
716         int new_rc = 0;
717         char **values_new;
718
719         pthread_mutex_lock (&cache_lock);
720
721         /* This shouldn't happen, but it did happen at least once, so we'll be
722          * careful. */
723         if (cache == NULL)
724         {
725                 pthread_mutex_unlock (&cache_lock);
726                 WARNING ("rrdtool plugin: cache == NULL.");
727                 return (-1);
728         }
729
730         c_avl_get (cache, filename, (void *) &rc);
731
732         if (rc == NULL)
733         {
734                 rc = malloc (sizeof (*rc));
735                 if (rc == NULL)
736                         return (-1);
737                 rc->values_num = 0;
738                 rc->values = NULL;
739                 rc->first_value = 0;
740                 rc->last_value = 0;
741                 rc->random_variation = rrd_get_random_variation ();
742                 rc->flags = FLAG_NONE;
743                 new_rc = 1;
744         }
745
746         if (rc->last_value >= value_time)
747         {
748                 pthread_mutex_unlock (&cache_lock);
749                 DEBUG ("rrdtool plugin: (rc->last_value = %"PRIu64") "
750                                 ">= (value_time = %"PRIu64")",
751                                 rc->last_value, value_time);
752                 return (-1);
753         }
754
755         values_new = (char **) realloc ((void *) rc->values,
756                         (rc->values_num + 1) * sizeof (char *));
757         if (values_new == NULL)
758         {
759                 char errbuf[1024];
760                 void *cache_key = NULL;
761
762                 sstrerror (errno, errbuf, sizeof (errbuf));
763
764                 c_avl_remove (cache, filename, &cache_key, NULL);
765                 pthread_mutex_unlock (&cache_lock);
766
767                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
768
769                 sfree (cache_key);
770                 sfree (rc->values);
771                 sfree (rc);
772                 return (-1);
773         }
774         rc->values = values_new;
775
776         rc->values[rc->values_num] = strdup (value);
777         if (rc->values[rc->values_num] != NULL)
778                 rc->values_num++;
779
780         if (rc->values_num == 1)
781                 rc->first_value = value_time;
782         rc->last_value = value_time;
783
784         /* Insert if this is the first value */
785         if (new_rc == 1)
786         {
787                 void *cache_key = strdup (filename);
788
789                 if (cache_key == NULL)
790                 {
791                         char errbuf[1024];
792                         sstrerror (errno, errbuf, sizeof (errbuf));
793
794                         pthread_mutex_unlock (&cache_lock);
795
796                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
797
798                         sfree (rc->values[0]);
799                         sfree (rc->values);
800                         sfree (rc);
801                         return (-1);
802                 }
803
804                 c_avl_insert (cache, cache_key, rc);
805         }
806
807         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
808                         "values_num = %i; age = %.3f;",
809                         filename, rc->values_num,
810                         CDTIME_T_TO_DOUBLE (rc->last_value - rc->first_value));
811
812         if ((rc->last_value - rc->first_value) >= (cache_timeout + rc->random_variation))
813         {
814                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
815                  * the same time, ALWAYS lock `cache_lock' first! */
816                 if (rc->flags == FLAG_NONE)
817                 {
818                         int status;
819
820                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
821                         if (status == 0)
822                                 rc->flags = FLAG_QUEUED;
823
824                         rc->random_variation = rrd_get_random_variation ();
825                 }
826                 else
827                 {
828                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
829                 }
830         }
831
832         if ((cache_timeout > 0) &&
833                         ((cdtime () - cache_flush_last) > cache_flush_timeout))
834                 rrd_cache_flush (cache_flush_timeout);
835
836         pthread_mutex_unlock (&cache_lock);
837
838         return (0);
839 } /* int rrd_cache_insert */
840
841 static int rrd_cache_destroy (void) /* {{{ */
842 {
843   void *key = NULL;
844   void *value = NULL;
845
846   int non_empty = 0;
847
848   pthread_mutex_lock (&cache_lock);
849
850   if (cache == NULL)
851   {
852     pthread_mutex_unlock (&cache_lock);
853     return (0);
854   }
855
856   while (c_avl_pick (cache, &key, &value) == 0)
857   {
858     rrd_cache_t *rc;
859     int i;
860
861     sfree (key);
862     key = NULL;
863
864     rc = value;
865     value = NULL;
866
867     if (rc->values_num > 0)
868       non_empty++;
869
870     for (i = 0; i < rc->values_num; i++)
871       sfree (rc->values[i]);
872     sfree (rc->values);
873     sfree (rc);
874   }
875
876   c_avl_destroy (cache);
877   cache = NULL;
878
879   if (non_empty > 0)
880   {
881     INFO ("rrdtool plugin: %i cache %s had values when destroying the cache.",
882         non_empty, (non_empty == 1) ? "entry" : "entries");
883   }
884   else
885   {
886     DEBUG ("rrdtool plugin: No values have been lost "
887         "when destroying the cache.");
888   }
889
890   pthread_mutex_unlock (&cache_lock);
891   return (0);
892 } /* }}} int rrd_cache_destroy */
893
894 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
895 {
896         int a = *((int *) a_ptr);
897         int b = *((int *) b_ptr);
898
899         if (a < b)
900                 return (-1);
901         else if (a > b)
902                 return (1);
903         else
904                 return (0);
905 } /* int rrd_compare_numeric */
906
907 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
908                 user_data_t __attribute__((unused)) *user_data)
909 {
910         struct stat  statbuf;
911         char         filename[512];
912         char         values[512];
913         int          status;
914
915         if (do_shutdown)
916                 return (0);
917
918         if (0 != strcmp (ds->type, vl->type)) {
919                 ERROR ("rrdtool plugin: DS type does not match value list type");
920                 return -1;
921         }
922
923         if (value_list_to_filename (filename, sizeof (filename), vl) != 0)
924                 return (-1);
925
926         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
927                 return (-1);
928
929         if (stat (filename, &statbuf) == -1)
930         {
931                 if (errno == ENOENT)
932                 {
933                         status = cu_rrd_create_file (filename,
934                                         ds, vl, &rrdcreate_config);
935                         if (status != 0)
936                                 return (-1);
937                         else if (rrdcreate_config.async)
938                                 return (0);
939                 }
940                 else
941                 {
942                         char errbuf[1024];
943                         ERROR ("stat(%s) failed: %s", filename,
944                                         sstrerror (errno, errbuf,
945                                                 sizeof (errbuf)));
946                         return (-1);
947                 }
948         }
949         else if (!S_ISREG (statbuf.st_mode))
950         {
951                 ERROR ("stat(%s): Not a regular file!",
952                                 filename);
953                 return (-1);
954         }
955
956         status = rrd_cache_insert (filename, values, vl->time);
957
958         return (status);
959 } /* int rrd_write */
960
961 static int rrd_flush (cdtime_t timeout, const char *identifier,
962                 __attribute__((unused)) user_data_t *user_data)
963 {
964         pthread_mutex_lock (&cache_lock);
965
966         if (cache == NULL) {
967                 pthread_mutex_unlock (&cache_lock);
968                 return (0);
969         }
970
971         rrd_cache_flush_identifier (timeout, identifier);
972
973         pthread_mutex_unlock (&cache_lock);
974         return (0);
975 } /* int rrd_flush */
976
977 static int rrd_config (const char *key, const char *value)
978 {
979         if (strcasecmp ("CacheTimeout", key) == 0)
980         {
981                 double tmp = atof (value);
982                 if (tmp < 0)
983                 {
984                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
985                                         "be greater than 0.\n");
986                         ERROR ("rrdtool: `CacheTimeout' must "
987                                         "be greater than 0.\n");
988                         return (1);
989                 }
990                 cache_timeout = DOUBLE_TO_CDTIME_T (tmp);
991         }
992         else if (strcasecmp ("CacheFlush", key) == 0)
993         {
994                 int tmp = atoi (value);
995                 if (tmp < 0)
996                 {
997                         fprintf (stderr, "rrdtool: `CacheFlush' must "
998                                         "be greater than 0.\n");
999                         ERROR ("rrdtool: `CacheFlush' must "
1000                                         "be greater than 0.\n");
1001                         return (1);
1002                 }
1003                 cache_flush_timeout = tmp;
1004         }
1005         else if (strcasecmp ("DataDir", key) == 0)
1006         {
1007                 if (datadir != NULL)
1008                         free (datadir);
1009                 datadir = strdup (value);
1010                 if (datadir != NULL)
1011                 {
1012                         int len = strlen (datadir);
1013                         while ((len > 0) && (datadir[len - 1] == '/'))
1014                         {
1015                                 len--;
1016                                 datadir[len] = '\0';
1017                         }
1018                         if (len <= 0)
1019                         {
1020                                 free (datadir);
1021                                 datadir = NULL;
1022                         }
1023                 }
1024         }
1025         else if (strcasecmp ("StepSize", key) == 0)
1026         {
1027                 unsigned long temp = strtoul (value, NULL, 0);
1028                 if (temp > 0)
1029                         rrdcreate_config.stepsize = temp;
1030         }
1031         else if (strcasecmp ("HeartBeat", key) == 0)
1032         {
1033                 int temp = atoi (value);
1034                 if (temp > 0)
1035                         rrdcreate_config.heartbeat = temp;
1036         }
1037         else if (strcasecmp ("CreateFilesAsync", key) == 0)
1038         {
1039                 if (IS_TRUE (value))
1040                         rrdcreate_config.async = 1;
1041                 else
1042                         rrdcreate_config.async = 0;
1043         }
1044         else if (strcasecmp ("RRARows", key) == 0)
1045         {
1046                 int tmp = atoi (value);
1047                 if (tmp <= 0)
1048                 {
1049                         fprintf (stderr, "rrdtool: `RRARows' must "
1050                                         "be greater than 0.\n");
1051                         ERROR ("rrdtool: `RRARows' must "
1052                                         "be greater than 0.\n");
1053                         return (1);
1054                 }
1055                 rrdcreate_config.rrarows = tmp;
1056         }
1057         else if (strcasecmp ("RRATimespan", key) == 0)
1058         {
1059                 char *saveptr = NULL;
1060                 char *dummy;
1061                 char *ptr;
1062                 char *value_copy;
1063                 int *tmp_alloc;
1064
1065                 value_copy = strdup (value);
1066                 if (value_copy == NULL)
1067                         return (1);
1068
1069                 dummy = value_copy;
1070                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1071                 {
1072                         dummy = NULL;
1073                         
1074                         tmp_alloc = realloc (rrdcreate_config.timespans,
1075                                         sizeof (int) * (rrdcreate_config.timespans_num + 1));
1076                         if (tmp_alloc == NULL)
1077                         {
1078                                 fprintf (stderr, "rrdtool: realloc failed.\n");
1079                                 ERROR ("rrdtool: realloc failed.\n");
1080                                 free (value_copy);
1081                                 return (1);
1082                         }
1083                         rrdcreate_config.timespans = tmp_alloc;
1084                         rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
1085                         if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
1086                                 rrdcreate_config.timespans_num++;
1087                 } /* while (strtok_r) */
1088
1089                 qsort (/* base = */ rrdcreate_config.timespans,
1090                                 /* nmemb  = */ rrdcreate_config.timespans_num,
1091                                 /* size   = */ sizeof (rrdcreate_config.timespans[0]),
1092                                 /* compar = */ rrd_compare_numeric);
1093
1094                 free (value_copy);
1095         }
1096         else if (strcasecmp ("XFF", key) == 0)
1097         {
1098                 double tmp = atof (value);
1099                 if ((tmp < 0.0) || (tmp >= 1.0))
1100                 {
1101                         fprintf (stderr, "rrdtool: `XFF' must "
1102                                         "be in the range 0 to 1 (exclusive).");
1103                         ERROR ("rrdtool: `XFF' must "
1104                                         "be in the range 0 to 1 (exclusive).");
1105                         return (1);
1106                 }
1107                 rrdcreate_config.xff = tmp;
1108         }
1109         else if (strcasecmp ("WritesPerSecond", key) == 0)
1110         {
1111                 double wps = atof (value);
1112
1113                 if (wps < 0.0)
1114                 {
1115                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
1116                                         "greater than or equal to zero.");
1117                         return (1);
1118                 }
1119                 else if (wps == 0.0)
1120                 {
1121                         write_rate = 0.0;
1122                 }
1123                 else
1124                 {
1125                         write_rate = 1.0 / wps;
1126                 }
1127         }
1128         else if (strcasecmp ("RandomTimeout", key) == 0)
1129         {
1130                 double tmp;
1131
1132                 tmp = atof (value);
1133                 if (tmp < 0.0)
1134                 {
1135                         fprintf (stderr, "rrdtool: `RandomTimeout' must "
1136                                         "be greater than or equal to zero.\n");
1137                         ERROR ("rrdtool: `RandomTimeout' must "
1138                                         "be greater then or equal to zero.");
1139                 }
1140                 else
1141                 {
1142                         random_timeout = DOUBLE_TO_CDTIME_T (tmp);
1143                 }
1144         }
1145         else
1146         {
1147                 return (-1);
1148         }
1149         return (0);
1150 } /* int rrd_config */
1151
1152 static int rrd_shutdown (void)
1153 {
1154         pthread_mutex_lock (&cache_lock);
1155         rrd_cache_flush (0);
1156         pthread_mutex_unlock (&cache_lock);
1157
1158         pthread_mutex_lock (&queue_lock);
1159         do_shutdown = 1;
1160         pthread_cond_signal (&queue_cond);
1161         pthread_mutex_unlock (&queue_lock);
1162
1163         if ((queue_thread_running != 0)
1164                         && ((queue_head != NULL) || (flushq_head != NULL)))
1165         {
1166                 INFO ("rrdtool plugin: Shutting down the queue thread. "
1167                                 "This may take a while.");
1168         }
1169         else if (queue_thread_running != 0)
1170         {
1171                 INFO ("rrdtool plugin: Shutting down the queue thread.");
1172         }
1173
1174         /* Wait for all the values to be written to disk before returning. */
1175         if (queue_thread_running != 0)
1176         {
1177                 pthread_join (queue_thread, NULL);
1178                 memset (&queue_thread, 0, sizeof (queue_thread));
1179                 queue_thread_running = 0;
1180                 DEBUG ("rrdtool plugin: queue_thread exited.");
1181         }
1182
1183         rrd_cache_destroy ();
1184
1185         return (0);
1186 } /* int rrd_shutdown */
1187
1188 static int rrd_init (void)
1189 {
1190         static int init_once = 0;
1191         int status;
1192
1193         if (init_once != 0)
1194                 return (0);
1195         init_once = 1;
1196
1197         if (rrdcreate_config.heartbeat <= 0)
1198                 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1199
1200         /* Set the cache up */
1201         pthread_mutex_lock (&cache_lock);
1202
1203         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1204         if (cache == NULL)
1205         {
1206                 ERROR ("rrdtool plugin: c_avl_create failed.");
1207                 return (-1);
1208         }
1209
1210         cache_flush_last = cdtime ();
1211         if (cache_timeout == 0)
1212         {
1213                 cache_flush_timeout = 0;
1214         }
1215         else if (cache_flush_timeout < cache_timeout)
1216                 cache_flush_timeout = 10 * cache_timeout;
1217
1218         pthread_mutex_unlock (&cache_lock);
1219
1220         status = plugin_thread_create (&queue_thread, /* attr = */ NULL,
1221                         rrd_queue_thread, /* args = */ NULL);
1222         if (status != 0)
1223         {
1224                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1225                 return (-1);
1226         }
1227         queue_thread_running = 1;
1228
1229         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %lu;"
1230                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1231                         (datadir == NULL) ? "(null)" : datadir,
1232                         rrdcreate_config.stepsize,
1233                         rrdcreate_config.heartbeat,
1234                         rrdcreate_config.rrarows,
1235                         rrdcreate_config.xff);
1236
1237         return (0);
1238 } /* int rrd_init */
1239
1240 void module_register (void)
1241 {
1242         plugin_register_config ("rrdtool", rrd_config,
1243                         config_keys, config_keys_num);
1244         plugin_register_init ("rrdtool", rrd_init);
1245         plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1246         plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1247         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1248 }