Merge branch 'collectd-4.7'
[collectd.git] / src / utils_cache.c
1 /**
2  * collectd - src/utils_cache.c
3  * Copyright (C) 2007,2008  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Author:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "utils_avltree.h"
26 #include "utils_cache.h"
27 #include "utils_threshold.h"
28
29 #include <assert.h>
30 #include <pthread.h>
31
32 typedef struct cache_entry_s
33 {
34         char name[6 * DATA_MAX_NAME_LEN];
35         int        values_num;
36         gauge_t   *values_gauge;
37         value_t   *values_raw;
38         /* Time contained in the package
39          * (for calculating rates) */
40         time_t last_time;
41         /* Time according to the local clock
42          * (for purging old entries) */
43         time_t last_update;
44         /* Interval in which the data is collected
45          * (for purding old entries) */
46         int interval;
47         int state;
48 } cache_entry_t;
49
50 static c_avl_tree_t   *cache_tree = NULL;
51 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
52
53 static int cache_compare (const cache_entry_t *a, const cache_entry_t *b)
54 {
55   assert ((a != NULL) && (b != NULL));
56   return (strcmp (a->name, b->name));
57 } /* int cache_compare */
58
59 static cache_entry_t *cache_alloc (int values_num)
60 {
61   cache_entry_t *ce;
62
63   ce = (cache_entry_t *) malloc (sizeof (cache_entry_t));
64   if (ce == NULL)
65   {
66     ERROR ("utils_cache: cache_alloc: malloc failed.");
67     return (NULL);
68   }
69   memset (ce, '\0', sizeof (cache_entry_t));
70   ce->values_num = values_num;
71
72   ce->values_gauge = calloc (values_num, sizeof (*ce->values_gauge));
73   ce->values_raw   = calloc (values_num, sizeof (*ce->values_raw));
74   if ((ce->values_gauge == NULL) || (ce->values_raw == NULL))
75   {
76     sfree (ce->values_gauge);
77     sfree (ce->values_raw);
78     sfree (ce);
79     ERROR ("utils_cache: cache_alloc: calloc failed.");
80     return (NULL);
81   }
82
83   return (ce);
84 } /* cache_entry_t *cache_alloc */
85
86 static void cache_free (cache_entry_t *ce)
87 {
88   if (ce == NULL)
89     return;
90
91   sfree (ce->values_gauge);
92   sfree (ce->values_raw);
93   sfree (ce);
94 } /* void cache_free */
95
96 static int uc_send_notification (const char *name)
97 {
98   cache_entry_t *ce = NULL;
99   int status;
100
101   char *name_copy;
102   char *host;
103   char *plugin;
104   char *plugin_instance;
105   char *type;
106   char *type_instance;
107
108   notification_t n;
109
110   name_copy = strdup (name);
111   if (name_copy == NULL)
112   {
113     ERROR ("uc_send_notification: strdup failed.");
114     return (-1);
115   }
116
117   status = parse_identifier (name_copy, &host,
118       &plugin, &plugin_instance,
119       &type, &type_instance);
120   if (status != 0)
121   {
122     ERROR ("uc_send_notification: Cannot parse name `%s'", name);
123     return (-1);
124   }
125
126   /* Copy the associative members */
127   notification_init (&n, NOTIF_FAILURE, /* host = */ NULL,
128       host, plugin, plugin_instance, type, type_instance);
129
130   sfree (name_copy);
131   name_copy = host = plugin = plugin_instance = type = type_instance = NULL;
132
133   pthread_mutex_lock (&cache_lock);
134
135   /*
136    * Set the time _after_ getting the lock because we don't know how long
137    * acquiring the lock takes and we will use this time later to decide
138    * whether or not the state is OKAY.
139    */
140   n.time = time (NULL);
141
142   status = c_avl_get (cache_tree, name, (void *) &ce);
143   if (status != 0)
144   {
145     pthread_mutex_unlock (&cache_lock);
146     sfree (name_copy);
147     return (-1);
148   }
149     
150   /* Check if the entry has been updated in the meantime */
151   if ((n.time - ce->last_update) < (2 * ce->interval))
152   {
153     ce->state = STATE_OKAY;
154     pthread_mutex_unlock (&cache_lock);
155     sfree (name_copy);
156     return (-1);
157   }
158
159   ssnprintf (n.message, sizeof (n.message),
160       "%s has not been updated for %i seconds.", name,
161       (int) (n.time - ce->last_update));
162
163   pthread_mutex_unlock (&cache_lock);
164
165   plugin_dispatch_notification (&n);
166
167   return (0);
168 } /* int uc_send_notification */
169
170 static void uc_check_range (const data_set_t *ds, cache_entry_t *ce)
171 {
172   int i;
173
174   for (i = 0; i < ds->ds_num; i++)
175   {
176     if (isnan (ce->values_gauge[i]))
177       continue;
178     else if (ce->values_gauge[i] < ds->ds[i].min)
179       ce->values_gauge[i] = NAN;
180     else if (ce->values_gauge[i] > ds->ds[i].max)
181       ce->values_gauge[i] = NAN;
182   }
183 } /* void uc_check_range */
184
185 static int uc_insert (const data_set_t *ds, const value_list_t *vl,
186     const char *key)
187 {
188   int i;
189   char *key_copy;
190   cache_entry_t *ce;
191
192   /* `cache_lock' has been locked by `uc_update' */
193
194   key_copy = strdup (key);
195   if (key_copy == NULL)
196   {
197     ERROR ("uc_insert: strdup failed.");
198     return (-1);
199   }
200
201   ce = cache_alloc (ds->ds_num);
202   if (ce == NULL)
203   {
204     sfree (key_copy);
205     ERROR ("uc_insert: cache_alloc (%i) failed.", ds->ds_num);
206     return (-1);
207   }
208
209   sstrncpy (ce->name, key, sizeof (ce->name));
210
211   for (i = 0; i < ds->ds_num; i++)
212   {
213     switch (ds->ds[i].type)
214     {
215       case DS_TYPE_COUNTER:
216         ce->values_gauge[i] = NAN;
217         ce->values_raw[i].counter = vl->values[i].counter;
218         break;
219
220       case DS_TYPE_GAUGE:
221         ce->values_gauge[i] = vl->values[i].gauge;
222         ce->values_raw[i].gauge = vl->values[i].gauge;
223         break;
224
225       case DS_TYPE_DERIVE:
226         ce->values_gauge[i] = NAN;
227         ce->values_raw[i].derive = vl->values[i].derive;
228         break;
229
230       case DS_TYPE_ABSOLUTE:
231         ce->values_gauge[i] = NAN;
232         if (vl->interval > 0)
233           ce->values_gauge[i] = ((double) vl->values[i].absolute)
234             / ((double) vl->interval);
235         ce->values_raw[i].absolute = vl->values[i].absolute;
236         break;
237         
238       default:
239         /* This shouldn't happen. */
240         ERROR ("uc_insert: Don't know how to handle data source type %i.",
241             ds->ds[i].type);
242         return (-1);
243     } /* switch (ds->ds[i].type) */
244   } /* for (i) */
245
246   /* Prune invalid gauge data */
247   uc_check_range (ds, ce);
248
249   ce->last_time = vl->time;
250   ce->last_update = time (NULL);
251   ce->interval = vl->interval;
252   ce->state = STATE_OKAY;
253
254   if (c_avl_insert (cache_tree, key_copy, ce) != 0)
255   {
256     sfree (key_copy);
257     ERROR ("uc_insert: c_avl_insert failed.");
258     return (-1);
259   }
260
261   DEBUG ("uc_insert: Added %s to the cache.", key);
262   return (0);
263 } /* int uc_insert */
264
265 int uc_init (void)
266 {
267   if (cache_tree == NULL)
268     cache_tree = c_avl_create ((int (*) (const void *, const void *))
269         cache_compare);
270
271   return (0);
272 } /* int uc_init */
273
274 int uc_check_timeout (void)
275 {
276   time_t now;
277   cache_entry_t *ce;
278
279   char **keys = NULL;
280   int keys_len = 0;
281
282   char *key;
283   c_avl_iterator_t *iter;
284   int i;
285   
286   pthread_mutex_lock (&cache_lock);
287
288   now = time (NULL);
289
290   /* Build a list of entries to be flushed */
291   iter = c_avl_get_iterator (cache_tree);
292   while (c_avl_iterator_next (iter, (void *) &key, (void *) &ce) == 0)
293   {
294     /* If entry has not been updated, add to `keys' array */
295     if ((now - ce->last_update) >= (2 * ce->interval))
296     {
297       char **tmp;
298
299       tmp = (char **) realloc ((void *) keys,
300           (keys_len + 1) * sizeof (char *));
301       if (tmp == NULL)
302       {
303         ERROR ("uc_check_timeout: realloc failed.");
304         c_avl_iterator_destroy (iter);
305         sfree (keys);
306         pthread_mutex_unlock (&cache_lock);
307         return (-1);
308       }
309
310       keys = tmp;
311       keys[keys_len] = strdup (key);
312       if (keys[keys_len] == NULL)
313       {
314         ERROR ("uc_check_timeout: strdup failed.");
315         continue;
316       }
317       keys_len++;
318     }
319   } /* while (c_avl_iterator_next) */
320
321   ce = NULL;
322
323   for (i = 0; i < keys_len; i++)
324   {
325     int status;
326
327     status = ut_check_interesting (keys[i]);
328
329     if (status < 0)
330     {
331       ERROR ("uc_check_timeout: ut_check_interesting failed.");
332       sfree (keys[i]);
333       continue;
334     }
335     else if (status == 0) /* ``service'' is uninteresting */
336     {
337       DEBUG ("uc_check_timeout: %s is missing but ``uninteresting''",
338           keys[i]);
339       status = c_avl_remove (cache_tree, keys[i],
340           (void *) &key, (void *) &ce);
341       if (status != 0)
342       {
343         ERROR ("uc_check_timeout: c_avl_remove (%s) failed.", keys[i]);
344       }
345       sfree (keys[i]);
346       sfree (key);
347       cache_free (ce);
348       continue;
349     }
350
351     /* If we get here, the value is ``interesting''. Query the record from the
352      * cache and update the state field. */
353     if (c_avl_get (cache_tree, keys[i], (void *) &ce) != 0)
354     {
355       ERROR ("uc_check_timeout: cannot get data for %s from cache", keys[i]);
356       /* Do not free `keys[i]' so a notification is sent further down. */
357       continue;
358     }
359     assert (ce != NULL);
360
361     if (status == 2) /* persist */
362     {
363       DEBUG ("uc_check_timeout: %s is missing, sending notification.",
364           keys[i]);
365       ce->state = STATE_MISSING;
366       /* Do not free `keys[i]' so a notification is sent further down. */
367     }
368     else if (status == 1) /* do not persist */
369     {
370       if (ce->state == STATE_MISSING)
371       {
372         DEBUG ("uc_check_timeout: %s is missing but "
373             "notification has already been sent.",
374             keys[i]);
375         /* Set `keys[i]' to NULL to no notification is sent. */
376         sfree (keys[i]);
377       }
378       else /* (ce->state != STATE_MISSING) */
379       {
380         DEBUG ("uc_check_timeout: %s is missing, sending one notification.",
381             keys[i]);
382         ce->state = STATE_MISSING;
383         /* Do not free `keys[i]' so a notification is sent further down. */
384       }
385     }
386     else
387     {
388       WARNING ("uc_check_timeout: ut_check_interesting (%s) returned "
389           "invalid status %i.",
390           keys[i], status);
391       sfree (keys[i]);
392     }
393
394     /* Make really sure the next iteration doesn't work with this pointer.
395      * There have been too many bugs in the past.. :/  -- octo */
396     ce = NULL;
397   } /* for (keys[i]) */
398
399   c_avl_iterator_destroy (iter);
400
401   pthread_mutex_unlock (&cache_lock);
402
403   for (i = 0; i < keys_len; i++)
404   {
405     if (keys[i] == NULL)
406       continue;
407
408     uc_send_notification (keys[i]);
409     sfree (keys[i]);
410   }
411
412   sfree (keys);
413
414   return (0);
415 } /* int uc_check_timeout */
416
417 int uc_update (const data_set_t *ds, const value_list_t *vl)
418 {
419   char name[6 * DATA_MAX_NAME_LEN];
420   cache_entry_t *ce = NULL;
421   int send_okay_notification = 0;
422   time_t update_delay = 0;
423   notification_t n;
424   int status;
425   int i;
426
427   if (FORMAT_VL (name, sizeof (name), vl, ds) != 0)
428   {
429     ERROR ("uc_update: FORMAT_VL failed.");
430     return (-1);
431   }
432
433   pthread_mutex_lock (&cache_lock);
434
435   status = c_avl_get (cache_tree, name, (void *) &ce);
436   if (status != 0) /* entry does not yet exist */
437   {
438     status = uc_insert (ds, vl, name);
439     pthread_mutex_unlock (&cache_lock);
440     return (status);
441   }
442
443   assert (ce != NULL);
444   assert (ce->values_num == ds->ds_num);
445
446   if (ce->last_time >= vl->time)
447   {
448     pthread_mutex_unlock (&cache_lock);
449     NOTICE ("uc_update: Value too old: name = %s; value time = %u; "
450         "last cache update = %u;",
451         name, (unsigned int) vl->time, (unsigned int) ce->last_time);
452     return (-1);
453   }
454
455   /* Send a notification (after the lock has been released) if we switch the
456    * state from something else to `okay'. */
457   if (ce->state == STATE_MISSING)
458   {
459     send_okay_notification = 1;
460     ce->state = STATE_OKAY;
461     update_delay = time (NULL) - ce->last_update;
462   }
463
464   for (i = 0; i < ds->ds_num; i++)
465   {
466     switch (ds->ds[i].type)
467     {
468       case DS_TYPE_COUNTER:
469         {
470           counter_t diff;
471
472           /* check if the counter has wrapped around */
473           if (vl->values[i].counter < ce->values_raw[i].counter)
474           {
475             if (ce->values_raw[i].counter <= 4294967295U)
476               diff = (4294967295U - ce->values_raw[i].counter)
477                 + vl->values[i].counter;
478             else
479               diff = (18446744073709551615ULL - ce->values_raw[i].counter)
480                 + vl->values[i].counter;
481           }
482           else /* counter has NOT wrapped around */
483           {
484             diff = vl->values[i].counter - ce->values_raw[i].counter;
485           }
486
487           ce->values_gauge[i] = ((double) diff)
488             / ((double) (vl->time - ce->last_time));
489           ce->values_raw[i].counter = vl->values[i].counter;
490         }
491         break;
492
493       case DS_TYPE_GAUGE:
494         ce->values_raw[i].gauge = vl->values[i].gauge;
495         ce->values_gauge[i] = vl->values[i].gauge;
496         break;
497
498       case DS_TYPE_DERIVE:
499         {
500           derive_t diff;
501
502           diff = vl->values[i].derive - ce->values_raw[i].derive;
503
504           ce->values_gauge[i] = ((double) diff)
505             / ((double) (vl->time - ce->last_time));
506           ce->values_raw[i].derive = vl->values[i].derive;
507         }
508         break;
509
510       case DS_TYPE_ABSOLUTE:
511         ce->values_gauge[i] = ((double) vl->values[i].absolute)
512           / ((double) (vl->time - ce->last_time));
513         ce->values_raw[i].absolute = vl->values[i].absolute;
514         break;
515
516       default:
517         /* This shouldn't happen. */
518         pthread_mutex_unlock (&cache_lock);
519         ERROR ("uc_update: Don't know how to handle data source type %i.",
520             ds->ds[i].type);
521         return (-1);
522     } /* switch (ds->ds[i].type) */
523
524     DEBUG ("uc_update: %s: ds[%i] = %lf", name, i, ce->values_gauge[i]);
525   } /* for (i) */
526
527   /* Prune invalid gauge data */
528   uc_check_range (ds, ce);
529
530   ce->last_time = vl->time;
531   ce->last_update = time (NULL);
532   ce->interval = vl->interval;
533
534   pthread_mutex_unlock (&cache_lock);
535
536   if (send_okay_notification == 0)
537     return (0);
538
539   /* Do not send okay notifications for uninteresting values, i. e. values for
540    * which no threshold is configured. */
541   status = ut_check_interesting (name);
542   if (status <= 0)
543     return (0);
544
545   /* Initialize the notification */
546   memset (&n, '\0', sizeof (n));
547   NOTIFICATION_INIT_VL (&n, vl, ds);
548
549   n.severity = NOTIF_OKAY;
550   n.time = vl->time;
551
552   ssnprintf (n.message, sizeof (n.message),
553       "Received a value for %s. It was missing for %u seconds.",
554       name, (unsigned int) update_delay);
555
556   plugin_dispatch_notification (&n);
557
558   return (0);
559 } /* int uc_update */
560
561 int uc_get_rate_by_name (const char *name, gauge_t **ret_values, size_t *ret_values_num)
562 {
563   gauge_t *ret = NULL;
564   size_t ret_num = 0;
565   cache_entry_t *ce = NULL;
566   int status = 0;
567
568   pthread_mutex_lock (&cache_lock);
569
570   if (c_avl_get (cache_tree, name, (void *) &ce) == 0)
571   {
572     assert (ce != NULL);
573
574     ret_num = ce->values_num;
575     ret = (gauge_t *) malloc (ret_num * sizeof (gauge_t));
576     if (ret == NULL)
577     {
578       ERROR ("utils_cache: uc_get_rate_by_name: malloc failed.");
579       status = -1;
580     }
581     else
582     {
583       memcpy (ret, ce->values_gauge, ret_num * sizeof (gauge_t));
584     }
585   }
586   else
587   {
588     DEBUG ("utils_cache: uc_get_rate_by_name: No such value: %s", name);
589     status = -1;
590   }
591
592   pthread_mutex_unlock (&cache_lock);
593
594   if (status == 0)
595   {
596     *ret_values = ret;
597     *ret_values_num = ret_num;
598   }
599
600   return (status);
601 } /* gauge_t *uc_get_rate_by_name */
602
603 gauge_t *uc_get_rate (const data_set_t *ds, const value_list_t *vl)
604 {
605   char name[6 * DATA_MAX_NAME_LEN];
606   gauge_t *ret = NULL;
607   size_t ret_num = 0;
608   int status;
609
610   if (FORMAT_VL (name, sizeof (name), vl, ds) != 0)
611   {
612     ERROR ("utils_cache: uc_get_rate: FORMAT_VL failed.");
613     return (NULL);
614   }
615
616   status = uc_get_rate_by_name (name, &ret, &ret_num);
617   if (status != 0)
618     return (NULL);
619
620   /* This is important - the caller has no other way of knowing how many
621    * values are returned. */
622   if (ret_num != (size_t) ds->ds_num)
623   {
624     ERROR ("utils_cache: uc_get_rate: ds[%s] has %i values, "
625         "but uc_get_rate_by_name returned %zu.",
626         ds->type, ds->ds_num, ret_num);
627     sfree (ret);
628     return (NULL);
629   }
630
631   return (ret);
632 } /* gauge_t *uc_get_rate */
633
634 int uc_get_names (char ***ret_names, time_t **ret_times, size_t *ret_number)
635 {
636   c_avl_iterator_t *iter;
637   char *key;
638   cache_entry_t *value;
639
640   char **names = NULL;
641   time_t *times = NULL;
642   size_t number = 0;
643
644   int status = 0;
645
646   if ((ret_names == NULL) || (ret_number == NULL))
647     return (-1);
648
649   pthread_mutex_lock (&cache_lock);
650
651   iter = c_avl_get_iterator (cache_tree);
652   while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
653   {
654     char **temp;
655
656     if (ret_times != NULL)
657     {
658       time_t *tmp_times;
659
660       tmp_times = (time_t *) realloc (times, sizeof (time_t) * (number + 1));
661       if (tmp_times == NULL)
662       {
663         status = -1;
664         break;
665       }
666       times = tmp_times;
667       times[number] = value->last_time;
668     }
669
670     temp = (char **) realloc (names, sizeof (char *) * (number + 1));
671     if (temp == NULL)
672     {
673       status = -1;
674       break;
675     }
676     names = temp;
677     names[number] = strdup (key);
678     if (names[number] == NULL)
679     {
680       status = -1;
681       break;
682     }
683     number++;
684   } /* while (c_avl_iterator_next) */
685
686   c_avl_iterator_destroy (iter);
687   pthread_mutex_unlock (&cache_lock);
688
689   if (status != 0)
690   {
691     size_t i;
692     
693     for (i = 0; i < number; i++)
694     {
695       sfree (names[i]);
696     }
697     sfree (names);
698
699     return (-1);
700   }
701
702   *ret_names = names;
703   if (ret_times != NULL)
704     *ret_times = times;
705   *ret_number = number;
706
707   return (0);
708 } /* int uc_get_names */
709
710 int uc_get_state (const data_set_t *ds, const value_list_t *vl)
711 {
712   char name[6 * DATA_MAX_NAME_LEN];
713   cache_entry_t *ce = NULL;
714   int ret = STATE_ERROR;
715
716   if (FORMAT_VL (name, sizeof (name), vl, ds) != 0)
717   {
718     ERROR ("uc_get_state: FORMAT_VL failed.");
719     return (STATE_ERROR);
720   }
721
722   pthread_mutex_lock (&cache_lock);
723
724   if (c_avl_get (cache_tree, name, (void *) &ce) == 0)
725   {
726     assert (ce != NULL);
727     ret = ce->state;
728   }
729
730   pthread_mutex_unlock (&cache_lock);
731
732   return (ret);
733 } /* int uc_get_state */
734
735 int uc_set_state (const data_set_t *ds, const value_list_t *vl, int state)
736 {
737   char name[6 * DATA_MAX_NAME_LEN];
738   cache_entry_t *ce = NULL;
739   int ret = -1;
740
741   if (FORMAT_VL (name, sizeof (name), vl, ds) != 0)
742   {
743     ERROR ("uc_get_state: FORMAT_VL failed.");
744     return (STATE_ERROR);
745   }
746
747   pthread_mutex_lock (&cache_lock);
748
749   if (c_avl_get (cache_tree, name, (void *) &ce) == 0)
750   {
751     assert (ce != NULL);
752     ret = ce->state;
753     ce->state = state;
754   }
755
756   pthread_mutex_unlock (&cache_lock);
757
758   return (ret);
759 } /* int uc_set_state */
760 /* vim: set sw=2 ts=8 sts=2 tw=78 : */