]> arthur.barton.de Git - netdata.git/blob - src/health.c
preparations for saving/loading the alarm log
[netdata.git] / src / health.c
1 #include "common.h"
2
3 #define RRDVAR_MAX_LENGTH 1024
4
5 struct health_options {
6     const char *health_default_exec;
7     const char *health_default_recipient;
8     const char *log_filename;
9     FILE *log_fp;
10 };
11
12 static struct health_options health = {
13     .health_default_exec = PLUGINS_DIR "/alarm-notify.sh",
14     .health_default_recipient = "root",
15     .log_filename = VARLIB_DIR "/health/alarm_log.db",
16     .log_fp = NULL
17 };
18
19 int health_enabled = 1;
20
21 // ----------------------------------------------------------------------------
22 // health alarm log load/save
23 // no need for locking - only one thread is reading / writing the alarms log
24
25 static inline int health_alarm_log_open(void) {
26     if(health.log_fp)
27         fclose(health.log_fp);
28
29     health.log_fp = fopen(health.log_filename, "a");
30
31     if(health.log_fp) {
32         if (setvbuf(health.log_fp, NULL, _IOLBF, 0) != 0)
33             error("Cannot set line buffering on health log file.");
34         return 0;
35     }
36
37     error("Cannot open health log file '%s'. Health data will be lost in case of netdata or server crash.", health.log_filename);
38     return -1;
39 }
40
41 static inline void health_alarm_log_close(void) {
42     if(health.log_fp) {
43         fclose(health.log_fp);
44         health.log_fp = NULL;
45     }
46 }
47
48 static inline void health_log_recreate(void) {
49     if(health.log_fp != NULL) {
50         health_alarm_log_close();
51
52         // open it with truncate
53         health.log_fp = fopen(health.log_filename, "w");
54         if(health.log_fp) fclose(health.log_fp);
55         else error("Cannot truncate health log '%s'", health.log_filename);
56
57         health.log_fp = NULL;
58
59         health_alarm_log_open();
60     }
61 }
62
63 static inline void health_alarm_log_save(RRDHOST *host, ALARM_ENTRY *ae) {
64     (void)host;
65     (void)ae;
66     
67 /*    if(likely(health.log_fp)) {
68         if(unlikely(fprintf(health.log_fp, "A\t%s\t%08x\t%08x\t%08x\t%08x\t%08x\t%08x\t%s\t%s\t%s\t%s\t%s\t%08x\n",
69             host->hostname,
70             ae->unique_id,
71             ae->alarm_id,
72             ae->alarm_event_id,
73             (uint32_t)ae->when,
74             (uint32_t)ae->duration,
75             (uint32_t)ae->non_clear_duration,
76             (uint32_t)ae->exec_run_timestamp,
77             ae->name,
78             ae->chart,
79             ae->family,
80             ae->exec,
81             ae->recipient
82             ) < 0))
83             error("Health: failed to save alarm log entry. Health data may be lost in case of abnormal restart.");
84     }
85 */
86 }
87
88 static inline void health_alarm_log_load(RRDHOST *host) {
89     (void)host;
90
91 }
92
93 // ----------------------------------------------------------------------------
94 // health alarm log management
95
96 static inline void health_alarm_log(RRDHOST *host,
97                 uint32_t alarm_id, uint32_t alarm_event_id,
98                 time_t when,
99                 const char *name, const char *chart, const char *family,
100                 const char *exec, const char *recipient, time_t duration,
101                 calculated_number old_value, calculated_number new_value,
102                 int old_status, int new_status,
103                 const char *source,
104                 const char *units,
105                 const char *info,
106                 int delay
107 ) {
108     debug(D_HEALTH, "Health adding alarm log entry with id: %u", host->health_log.next_log_id);
109
110     ALARM_ENTRY *ae = callocz(1, sizeof(ALARM_ENTRY));
111     ae->name = strdupz(name);
112     ae->hash_name = simple_hash(ae->name);
113
114     if(chart) {
115         ae->chart = strdupz(chart);
116         ae->hash_chart = simple_hash(ae->chart);
117     }
118
119     if(family)
120         ae->family = strdupz(family);
121
122     if(exec) ae->exec = strdupz(exec);
123     if(recipient) ae->recipient = strdupz(recipient);
124     if(source) ae->source = strdupz(source);
125     if(units) ae->units = strdupz(units);
126     if(info) ae->info = strdupz(info);
127
128     ae->unique_id = host->health_log.next_log_id++;
129     ae->alarm_id = alarm_id;
130     ae->alarm_event_id = alarm_event_id;
131     ae->when = when;
132     ae->old_value = old_value;
133     ae->new_value = new_value;
134     ae->old_status = old_status;
135     ae->new_status = new_status;
136     ae->duration = duration;
137     ae->delay = delay;
138     ae->delay_up_to_timestamp = when + delay;
139
140     if(ae->old_status == RRDCALC_STATUS_WARNING || ae->old_status == RRDCALC_STATUS_CRITICAL)
141         ae->non_clear_duration += ae->duration;
142
143     // link it
144     pthread_rwlock_wrlock(&host->health_log.alarm_log_rwlock);
145     ae->next = host->health_log.alarms;
146     host->health_log.alarms = ae;
147     host->health_log.count++;
148     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
149
150     // match previous alarms
151     pthread_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
152     ALARM_ENTRY *t;
153     for(t = host->health_log.alarms ; t ; t = t->next) {
154         if(t != ae && t->alarm_id == ae->alarm_id) {
155             if(!(t->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED) && !t->updated_by) {
156                 t->notifications |= HEALTH_ENTRY_NOTIFICATIONS_UPDATED;
157                 t->updated_by = ae;
158
159                 if((t->new_status == RRDCALC_STATUS_WARNING || t->new_status == RRDCALC_STATUS_CRITICAL) &&
160                    (t->old_status == RRDCALC_STATUS_WARNING || t->old_status == RRDCALC_STATUS_CRITICAL))
161                     ae->non_clear_duration += t->non_clear_duration;
162
163                 health_alarm_log_save(host, t);
164             }
165             else {
166                 // no need to continue
167                 break;
168             }
169         }
170     }
171     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
172
173     health_alarm_log_save(host, ae);
174 }
175
176 // ----------------------------------------------------------------------------
177 // RRDVAR management
178
179 static inline int rrdvar_fix_name(char *variable) {
180     int fixed = 0;
181     while(*variable) {
182         if (!isalnum(*variable) && *variable != '.' && *variable != '_') {
183             *variable++ = '_';
184             fixed++;
185         }
186         else
187             variable++;
188     }
189
190     return fixed;
191 }
192
193 int rrdvar_compare(void* a, void* b) {
194     if(((RRDVAR *)a)->hash < ((RRDVAR *)b)->hash) return -1;
195     else if(((RRDVAR *)a)->hash > ((RRDVAR *)b)->hash) return 1;
196     else return strcmp(((RRDVAR *)a)->name, ((RRDVAR *)b)->name);
197 }
198
199 static inline RRDVAR *rrdvar_index_add(avl_tree_lock *tree, RRDVAR *rv) {
200     RRDVAR *ret = (RRDVAR *)avl_insert_lock(tree, (avl *)(rv));
201     if(ret != rv)
202         debug(D_VARIABLES, "Request to insert RRDVAR '%s' into index failed. Already exists.", rv->name);
203
204     return ret;
205 }
206
207 static inline RRDVAR *rrdvar_index_del(avl_tree_lock *tree, RRDVAR *rv) {
208     RRDVAR *ret = (RRDVAR *)avl_remove_lock(tree, (avl *)(rv));
209     if(!ret)
210         error("Request to remove RRDVAR '%s' from index failed. Not Found.", rv->name);
211
212     return ret;
213 }
214
215 static inline RRDVAR *rrdvar_index_find(avl_tree_lock *tree, const char *name, uint32_t hash) {
216     RRDVAR tmp;
217     tmp.name = (char *)name;
218     tmp.hash = (hash)?hash:simple_hash(tmp.name);
219
220     return (RRDVAR *)avl_search_lock(tree, (avl *)&tmp);
221 }
222
223 static inline void rrdvar_free(RRDHOST *host, avl_tree_lock *tree, RRDVAR *rv) {
224     (void)host;
225
226     if(!rv) return;
227
228     if(tree)
229         rrdvar_index_del(tree, rv);
230
231     freez(rv->name);
232     freez(rv);
233 }
234
235 static inline RRDVAR *rrdvar_create_and_index(const char *scope, avl_tree_lock *tree, const char *name, int type, calculated_number *value) {
236     char *variable = strdupz(name);
237     rrdvar_fix_name(variable);
238     uint32_t hash = simple_hash(variable);
239
240     RRDVAR *rv = rrdvar_index_find(tree, variable, hash);
241     if(unlikely(!rv)) {
242         debug(D_VARIABLES, "Variable '%s' not found in scope '%s'. Creating a new one.", variable, scope);
243
244         rv = callocz(1, sizeof(RRDVAR));
245         rv->name = variable;
246         rv->hash = hash;
247         rv->type = type;
248         rv->value = value;
249
250         RRDVAR *ret = rrdvar_index_add(tree, rv);
251         if(unlikely(ret != rv)) {
252             debug(D_VARIABLES, "Variable '%s' in scope '%s' already exists", variable, scope);
253             rrdvar_free(NULL, NULL, rv);
254             rv = NULL;
255         }
256         else
257             debug(D_VARIABLES, "Variable '%s' created in scope '%s'", variable, scope);
258     }
259     else {
260         // already exists
261         freez(variable);
262         rv = NULL;
263     }
264
265     return rv;
266 }
267
268 // ----------------------------------------------------------------------------
269 // RRDVAR lookup
270
271 calculated_number rrdvar2number(RRDVAR *rv) {
272     switch(rv->type) {
273         case RRDVAR_TYPE_CALCULATED: {
274             calculated_number *n = (calculated_number *)rv->value;
275             return *n;
276         }
277
278         case RRDVAR_TYPE_TIME_T: {
279             time_t *n = (time_t *)rv->value;
280             return *n;
281         }
282
283         case RRDVAR_TYPE_COLLECTED: {
284             collected_number *n = (collected_number *)rv->value;
285             return *n;
286         }
287
288         case RRDVAR_TYPE_TOTAL: {
289             total_number *n = (total_number *)rv->value;
290             return *n;
291         }
292
293         case RRDVAR_TYPE_INT: {
294             int *n = (int *)rv->value;
295             return *n;
296         }
297
298         default:
299             error("I don't know how to convert RRDVAR type %d to calculated_number", rv->type);
300             return NAN;
301     }
302 }
303
304 void dump_variable(void *data) {
305     RRDVAR *rv = (RRDVAR *)data;
306     debug(D_HEALTH, "%50s : %20.5Lf", rv->name, rrdvar2number(rv));
307 }
308
309 int health_variable_lookup(const char *variable, uint32_t hash, RRDCALC *rc, calculated_number *result) {
310     RRDSET *st = rc->rrdset;
311     RRDVAR *rv;
312
313     if(!st) return 0;
314
315     rv = rrdvar_index_find(&st->variables_root_index, variable, hash);
316     if(rv) {
317         *result = rrdvar2number(rv);
318         return 1;
319     }
320
321     rv = rrdvar_index_find(&st->rrdfamily->variables_root_index, variable, hash);
322     if(rv) {
323         *result = rrdvar2number(rv);
324         return 1;
325     }
326
327     rv = rrdvar_index_find(&st->rrdhost->variables_root_index, variable, hash);
328     if(rv) {
329         *result = rrdvar2number(rv);
330         return 1;
331     }
332
333     debug(D_HEALTH, "Available local chart '%s' variables:", st->id);
334     avl_traverse_lock(&st->variables_root_index, dump_variable);
335
336     debug(D_HEALTH, "Available family '%s' variables:", st->rrdfamily->family);
337     avl_traverse_lock(&st->rrdfamily->variables_root_index, dump_variable);
338
339     debug(D_HEALTH, "Available host '%s' variables:", st->rrdhost->hostname);
340     avl_traverse_lock(&st->rrdhost->variables_root_index, dump_variable);
341
342     return 0;
343 }
344
345 // ----------------------------------------------------------------------------
346 // RRDSETVAR management
347
348 RRDSETVAR *rrdsetvar_create(RRDSET *st, const char *variable, int type, void *value, uint32_t options) {
349     debug(D_VARIABLES, "RRDVARSET create for chart id '%s' name '%s' with variable name '%s'", st->id, st->name, variable);
350     RRDSETVAR *rs = (RRDSETVAR *)callocz(1, sizeof(RRDSETVAR));
351
352     char buffer[RRDVAR_MAX_LENGTH + 1];
353     snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->id, variable);
354     rs->fullid = strdupz(buffer);
355
356     snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, variable);
357     rs->fullname = strdupz(buffer);
358
359     rs->variable = strdupz(variable);
360
361     rs->type = type;
362     rs->value = value;
363     rs->options = options;
364     rs->rrdset = st;
365
366     rs->local       = rrdvar_create_and_index("local",  &st->variables_root_index, rs->variable, rs->type, rs->value);
367     rs->family      = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullid, rs->type, rs->value);
368     rs->host        = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullid, rs->type, rs->value);
369     rs->family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullname, rs->type, rs->value);
370     rs->host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullname, rs->type, rs->value);
371
372     rs->next = st->variables;
373     st->variables = rs;
374
375     return rs;
376 }
377
378 void rrdsetvar_rename_all(RRDSET *st) {
379     debug(D_VARIABLES, "RRDSETVAR rename for chart id '%s' name '%s'", st->id, st->name);
380
381     // only these 2 can change name
382     // rs->family_name
383     // rs->host_name
384
385     char buffer[RRDVAR_MAX_LENGTH + 1];
386     RRDSETVAR *rs, *next = st->variables;
387     while((rs = next)) {
388         next = rs->next;
389
390         snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rs->variable);
391
392         if (strcmp(buffer, rs->fullname)) {
393             // name changed
394             rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
395             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_name);
396
397             freez(rs->fullname);
398             rs->fullname = strdupz(st->name);
399             rs->family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullname, rs->type, rs->value);
400             rs->host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullname, rs->type, rs->value);
401         }
402     }
403
404     rrdsetcalc_link_matching(st);
405 }
406
407 void rrdsetvar_free(RRDSETVAR *rs) {
408     RRDSET *st = rs->rrdset;
409     debug(D_VARIABLES, "RRDSETVAR free for chart id '%s' name '%s', variable '%s'", st->id, st->name, rs->variable);
410
411     rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local);
412     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family);
413     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host);
414     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
415     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_name);
416
417     if(st->variables == rs) {
418         st->variables = rs->next;
419     }
420     else {
421         RRDSETVAR *t;
422         for (t = st->variables; t && t->next != rs; t = t->next);
423         if(!t) error("RRDSETVAR '%s' not found in chart '%s' variables linked list", rs->fullname, st->id);
424         else t->next = rs->next;
425     }
426
427     freez(rs->fullid);
428     freez(rs->fullname);
429     freez(rs->variable);
430     freez(rs);
431 }
432
433 // ----------------------------------------------------------------------------
434 // RRDDIMVAR management
435
436 #define RRDDIMVAR_ID_MAX 1024
437
438 RRDDIMVAR *rrddimvar_create(RRDDIM *rd, int type, const char *prefix, const char *suffix, void *value, uint32_t options) {
439     RRDSET *st = rd->rrdset;
440
441     debug(D_VARIABLES, "RRDDIMSET create for chart id '%s' name '%s', dimension id '%s', name '%s%s%s'", st->id, st->name, rd->id, (prefix)?prefix:"", rd->name, (suffix)?suffix:"");
442
443     if(!prefix) prefix = "";
444     if(!suffix) suffix = "";
445
446     char buffer[RRDDIMVAR_ID_MAX + 1];
447     RRDDIMVAR *rs = (RRDDIMVAR *)callocz(1, sizeof(RRDDIMVAR));
448
449     rs->prefix = strdupz(prefix);
450     rs->suffix = strdupz(suffix);
451
452     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->id, rs->suffix);
453     rs->id = strdupz(buffer);
454
455     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->name, rs->suffix);
456     rs->name = strdupz(buffer);
457
458     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->id, rs->id);
459     rs->fullidid = strdupz(buffer);
460
461     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->id, rs->name);
462     rs->fullidname = strdupz(buffer);
463
464     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->name, rs->id);
465     rs->fullnameid = strdupz(buffer);
466
467     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->name, rs->name);
468     rs->fullnamename = strdupz(buffer);
469
470     rs->type = type;
471     rs->value = value;
472     rs->options = options;
473     rs->rrddim = rd;
474
475     rs->local_id     = rrdvar_create_and_index("local", &st->variables_root_index, rs->id, rs->type, rs->value);
476     rs->local_name   = rrdvar_create_and_index("local", &st->variables_root_index, rs->name, rs->type, rs->value);
477
478     rs->family_id    = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->id, rs->type, rs->value);
479     rs->family_name  = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->name, rs->type, rs->value);
480
481     rs->host_fullidid     = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullidid, rs->type, rs->value);
482     rs->host_fullidname   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullidname, rs->type, rs->value);
483     rs->host_fullnameid   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullnameid, rs->type, rs->value);
484     rs->host_fullnamename = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullnamename, rs->type, rs->value);
485
486     rs->next = rd->variables;
487     rd->variables = rs;
488
489     return rs;
490 }
491
492 void rrddimvar_rename_all(RRDDIM *rd) {
493     RRDSET *st = rd->rrdset;
494     debug(D_VARIABLES, "RRDDIMSET rename for chart id '%s' name '%s', dimension id '%s', name '%s'", st->id, st->name, rd->id, rd->name);
495
496     RRDDIMVAR *rs, *next = rd->variables;
497     while((rs = next)) {
498         next = rs->next;
499
500         if (strcmp(rd->name, rs->name)) {
501             char buffer[RRDDIMVAR_ID_MAX + 1];
502             // name changed
503
504             // name
505             rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_name);
506             freez(rs->name);
507             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->name, rs->suffix);
508             rs->name = strdupz(buffer);
509             rs->local_name = rrdvar_create_and_index("local", &st->variables_root_index, rs->name, rs->type, rs->value);
510
511             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidname);
512             freez(rs->fullidname);
513             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->id, rs->name);
514             rs->fullidname = strdupz(buffer);
515             rs->host_fullidname = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
516                                                              rs->fullidname, rs->type, rs->value);
517
518             // fullnameid
519             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnameid);
520             freez(rs->fullnameid);
521             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->id);
522             rs->fullnameid = strdupz(buffer);
523             rs->host_fullnameid = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
524                                                           rs->fullnameid, rs->type, rs->value);
525
526             // fullnamename
527             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnamename);
528             freez(rs->fullnamename);
529             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->name);
530             rs->fullnamename = strdupz(buffer);
531             rs->host_fullnamename = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
532                                                           rs->fullnamename, rs->type, rs->value);
533         }
534     }
535 }
536
537 void rrddimvar_free(RRDDIMVAR *rs) {
538     RRDDIM *rd = rs->rrddim;
539     RRDSET *st = rd->rrdset;
540     debug(D_VARIABLES, "RRDDIMSET free for chart id '%s' name '%s', dimension id '%s', name '%s', prefix='%s', suffix='%s'", st->id, st->name, rd->id, rd->name, rs->prefix, rs->suffix);
541
542     rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_id);
543     rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_name);
544
545     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_id);
546     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
547
548     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidid);
549     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidname);
550     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnameid);
551     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnamename);
552
553     if(rd->variables == rs) {
554         debug(D_VARIABLES, "RRDDIMSET removing first entry for chart id '%s' name '%s', dimension id '%s', name '%s'", st->id, st->name, rd->id, rd->name);
555         rd->variables = rs->next;
556     }
557     else {
558         debug(D_VARIABLES, "RRDDIMSET removing non-first entry for chart id '%s' name '%s', dimension id '%s', name '%s'", st->id, st->name, rd->id, rd->name);
559         RRDDIMVAR *t;
560         for (t = rd->variables; t && t->next != rs; t = t->next) ;
561         if(!t) error("RRDDIMVAR '%s' not found in dimension '%s/%s' variables linked list", rs->name, st->id, rd->id);
562         else t->next = rs->next;
563     }
564
565     freez(rs->prefix);
566     freez(rs->suffix);
567     freez(rs->id);
568     freez(rs->name);
569     freez(rs->fullidid);
570     freez(rs->fullidname);
571     freez(rs->fullnameid);
572     freez(rs->fullnamename);
573     freez(rs);
574 }
575
576 // ----------------------------------------------------------------------------
577 // RRDCALC management
578
579 static inline const char *rrdcalc_status2string(int status) {
580     switch(status) {
581         case RRDCALC_STATUS_REMOVED:
582             return "REMOVED";
583
584         case RRDCALC_STATUS_UNDEFINED:
585             return "UNDEFINED";
586
587         case RRDCALC_STATUS_UNINITIALIZED:
588             return "UNINITIALIZED";
589
590         case RRDCALC_STATUS_CLEAR:
591             return "CLEAR";
592
593         case RRDCALC_STATUS_RAISED:
594             return "RAISED";
595
596         case RRDCALC_STATUS_WARNING:
597             return "WARNING";
598
599         case RRDCALC_STATUS_CRITICAL:
600             return "CRITICAL";
601
602         default:
603             error("Unknown alarm status %d", status);
604             return "UNKNOWN";
605     }
606 }
607
608 static void rrdsetcalc_link(RRDSET *st, RRDCALC *rc) {
609     debug(D_HEALTH, "Health linking alarm '%s.%s' to chart '%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, st->id, st->rrdhost->hostname);
610
611     rc->last_status_change = time(NULL);
612     rc->rrdset = st;
613
614     rc->rrdset_next = st->alarms;
615     rc->rrdset_prev = NULL;
616     
617     if(rc->rrdset_next)
618         rc->rrdset_next->rrdset_prev = rc;
619
620     st->alarms = rc;
621
622     if(rc->update_every < rc->rrdset->update_every) {
623         error("Health alarm '%s.%s' has update every %d, less than chart update every %d. Setting alarm update frequency to %d.", rc->rrdset->id, rc->name, rc->update_every, rc->rrdset->update_every, rc->rrdset->update_every);
624         rc->update_every = rc->rrdset->update_every;
625     }
626
627     if(!isnan(rc->green) && isnan(st->green)) {
628         debug(D_HEALTH, "Health alarm '%s.%s' green threshold set from %Lf to %Lf.", rc->rrdset->id, rc->name, rc->rrdset->green, rc->green);
629         st->green = rc->green;
630     }
631
632     if(!isnan(rc->red) && isnan(st->red)) {
633         debug(D_HEALTH, "Health alarm '%s.%s' red threshold set from %Lf to %Lf.", rc->rrdset->id, rc->name, rc->rrdset->red, rc->red);
634         st->red = rc->red;
635     }
636
637     rc->local  = rrdvar_create_and_index("local",  &st->variables_root_index, rc->name, RRDVAR_TYPE_CALCULATED, &rc->value);
638     rc->family = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rc->name, RRDVAR_TYPE_CALCULATED, &rc->value);
639
640     char fullname[RRDVAR_MAX_LENGTH + 1];
641     snprintfz(fullname, RRDVAR_MAX_LENGTH, "%s.%s", st->id, rc->name);
642     rc->hostid   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, fullname, RRDVAR_TYPE_CALCULATED, &rc->value);
643
644     snprintfz(fullname, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rc->name);
645     rc->hostname = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, fullname, RRDVAR_TYPE_CALCULATED, &rc->value);
646
647         if(!rc->units) rc->units = strdupz(st->units);
648
649     {
650         time_t now = time(NULL);
651         health_alarm_log(st->rrdhost, rc->id, rc->next_event_id++, now, rc->name, rc->rrdset->id, rc->rrdset->family, rc->exec, rc->recipient, now - rc->last_status_change, rc->old_value, rc->value, rc->status, RRDCALC_STATUS_UNINITIALIZED, rc->source, rc->units, rc->info, 0);
652     }
653 }
654
655 static inline int rrdcalc_is_matching_this_rrdset(RRDCALC *rc, RRDSET *st) {
656     if(     (rc->hash_chart == st->hash      && !strcmp(rc->chart, st->id)) ||
657             (rc->hash_chart == st->hash_name && !strcmp(rc->chart, st->name)))
658         return 1;
659
660     return 0;
661 }
662
663 // this has to be called while the RRDHOST is locked
664 inline void rrdsetcalc_link_matching(RRDSET *st) {
665     // debug(D_HEALTH, "find matching alarms for chart '%s'", st->id);
666
667     RRDCALC *rc;
668     for(rc = st->rrdhost->alarms; rc ; rc = rc->next) {
669         if(unlikely(rc->rrdset))
670             continue;
671
672         if(unlikely(rrdcalc_is_matching_this_rrdset(rc, st)))
673             rrdsetcalc_link(st, rc);
674     }
675 }
676
677 // this has to be called while the RRDHOST is locked
678 inline void rrdsetcalc_unlink(RRDCALC *rc) {
679     RRDSET *st = rc->rrdset;
680
681     if(!st) {
682         debug(D_HEALTH, "Requested to unlink RRDCALC '%s.%s' which is not linked to any RRDSET", rc->chart?rc->chart:"NOCHART", rc->name);
683         error("Requested to unlink RRDCALC '%s.%s' which is not linked to any RRDSET", rc->chart?rc->chart:"NOCHART", rc->name);
684         return;
685     }
686
687     {
688         time_t now = time(NULL);
689         health_alarm_log(st->rrdhost, rc->id, rc->next_event_id++, now, rc->name, rc->rrdset->id, rc->rrdset->family, rc->exec, rc->recipient, now - rc->last_status_change, rc->old_value, rc->value, rc->status, RRDCALC_STATUS_REMOVED, rc->source, rc->units, rc->info, 0);
690     }
691
692     RRDHOST *host = st->rrdhost;
693
694     debug(D_HEALTH, "Health unlinking alarm '%s.%s' from chart '%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, st->id, host->hostname);
695
696     // unlink it
697     if(rc->rrdset_prev)
698         rc->rrdset_prev->rrdset_next = rc->rrdset_next;
699
700     if(rc->rrdset_next)
701         rc->rrdset_next->rrdset_prev = rc->rrdset_prev;
702
703     if(st->alarms == rc)
704         st->alarms = rc->rrdset_next;
705
706     rc->rrdset_prev = rc->rrdset_next = NULL;
707
708     rrdvar_free(st->rrdhost, &st->variables_root_index, rc->local);
709     rc->local = NULL;
710
711     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rc->family);
712     rc->family = NULL;
713
714     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rc->hostid);
715     rc->hostid = NULL;
716
717     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rc->hostname);
718     rc->hostname = NULL;
719
720     rc->rrdset = NULL;
721
722     // RRDCALC will remain in RRDHOST
723     // so that if the matching chart is found in the future
724     // it will be applied automatically
725 }
726
727 RRDCALC *rrdcalc_find(RRDSET *st, const char *name) {
728     RRDCALC *rc;
729     uint32_t hash = simple_hash(name);
730
731     for( rc = st->alarms; rc ; rc = rc->rrdset_next ) {
732         if(unlikely(rc->hash == hash && !strcmp(rc->name, name)))
733             return rc;
734     }
735
736     return NULL;
737 }
738
739 static inline int rrdcalc_exists(RRDHOST *host, const char *chart, const char *name, uint32_t hash_chart, uint32_t hash_name) {
740     RRDCALC *rc;
741
742     if(unlikely(!chart)) {
743         error("attempt to find RRDCALC '%s' without giving a chart name", name);
744         return 1;
745     }
746
747     if(unlikely(!hash_chart)) hash_chart = simple_hash(chart);
748     if(unlikely(!hash_name))  hash_name  = simple_hash(name);
749
750     // make sure it does not already exist
751     for(rc = host->alarms; rc ; rc = rc->next) {
752         if (unlikely(rc->chart && rc->hash == hash_name && rc->hash_chart == hash_chart && !strcmp(name, rc->name) && !strcmp(chart, rc->chart))) {
753             debug(D_HEALTH, "Health alarm '%s.%s' already exists in host '%s'.", chart, name, host->hostname);
754             error("Health alarm '%s.%s' already exists in host '%s'.", chart, name, host->hostname);
755             return 1;
756         }
757     }
758
759     return 0;
760 }
761
762 static inline uint32_t rrdcalc_get_unique_id(RRDHOST *host, const char *chart, const char *name, uint32_t *next_event_id) {
763     if(chart && name) {
764         uint32_t hash_chart = simple_hash(chart);
765         uint32_t hash_name = simple_hash(name);
766
767         // re-use old IDs, by looking them up in the alarm log
768         ALARM_ENTRY *ae;
769         for(ae = host->health_log.alarms; ae ;ae = ae->next) {
770             if(unlikely(ae->hash_name == hash_name && ae->hash_chart == hash_chart && !strcmp(name, ae->name) && !strcmp(chart, ae->chart))) {
771                 if(next_event_id) *next_event_id = ae->alarm_event_id + 1;
772                 return ae->alarm_id;
773             }
774         }
775     }
776
777     return host->health_log.next_alarm_id++;
778 }
779
780 static inline void rrdcalc_create_part2(RRDHOST *host, RRDCALC *rc) {
781     rrdhost_check_rdlock(host);
782
783     if(rc->calculation) {
784         rc->calculation->status = &rc->status;
785         rc->calculation->this = &rc->value;
786         rc->calculation->after = &rc->db_after;
787         rc->calculation->before = &rc->db_before;
788         rc->calculation->rrdcalc = rc;
789     }
790
791     if(rc->warning) {
792         rc->warning->status = &rc->status;
793         rc->warning->this = &rc->value;
794         rc->warning->after = &rc->db_after;
795         rc->warning->before = &rc->db_before;
796         rc->warning->rrdcalc = rc;
797     }
798
799     if(rc->critical) {
800         rc->critical->status = &rc->status;
801         rc->critical->this = &rc->value;
802         rc->critical->after = &rc->db_after;
803         rc->critical->before = &rc->db_before;
804         rc->critical->rrdcalc = rc;
805     }
806
807     // link it to the host
808     if(likely(host->alarms)) {
809         // append it
810         RRDCALC *t;
811         for(t = host->alarms; t && t->next ; t = t->next) ;
812         t->next = rc;
813     }
814     else {
815         host->alarms = rc;
816     }
817
818     // link it to its chart
819     RRDSET *st;
820     for(st = host->rrdset_root; st ; st = st->next) {
821         if(rrdcalc_is_matching_this_rrdset(rc, st)) {
822             rrdsetcalc_link(st, rc);
823             break;
824         }
825     }
826 }
827
828 static inline RRDCALC *rrdcalc_create(RRDHOST *host, RRDCALCTEMPLATE *rt, const char *chart) {
829
830     debug(D_HEALTH, "Health creating dynamic alarm (from template) '%s.%s'", chart, rt->name);
831
832     if(rrdcalc_exists(host, chart, rt->name, 0, 0))
833         return NULL;
834
835     RRDCALC *rc = callocz(1, sizeof(RRDCALC));
836     rc->next_event_id = 1;
837     rc->id = rrdcalc_get_unique_id(host, chart, rt->name, &rc->next_event_id);
838     rc->name = strdupz(rt->name);
839     rc->hash = simple_hash(rc->name);
840     rc->chart = strdupz(chart);
841     rc->hash_chart = simple_hash(rc->chart);
842
843     if(rt->dimensions) rc->dimensions = strdupz(rt->dimensions);
844
845     rc->green = rt->green;
846     rc->red = rt->red;
847     rc->value = NAN;
848     rc->old_value = NAN;
849
850     rc->delay_up_duration = rt->delay_up_duration;
851     rc->delay_down_duration = rt->delay_down_duration;
852     rc->delay_max_duration = rt->delay_max_duration;
853     rc->delay_multiplier = rt->delay_multiplier;
854
855     rc->group = rt->group;
856     rc->after = rt->after;
857     rc->before = rt->before;
858     rc->update_every = rt->update_every;
859     rc->options = rt->options;
860
861     if(rt->exec) rc->exec = strdupz(rt->exec);
862     if(rt->recipient) rc->recipient = strdupz(rt->recipient);
863     if(rt->source) rc->source = strdupz(rt->source);
864     if(rt->units) rc->units = strdupz(rt->units);
865     if(rt->info) rc->info = strdupz(rt->info);
866
867     if(rt->calculation) {
868         rc->calculation = expression_parse(rt->calculation->source, NULL, NULL);
869         if(!rc->calculation)
870             error("Health alarm '%s.%s': failed to parse calculation expression '%s'", chart, rt->name, rt->calculation->source);
871     }
872     if(rt->warning) {
873         rc->warning = expression_parse(rt->warning->source, NULL, NULL);
874         if(!rc->warning)
875             error("Health alarm '%s.%s': failed to re-parse warning expression '%s'", chart, rt->name, rt->warning->source);
876     }
877     if(rt->critical) {
878         rc->critical = expression_parse(rt->critical->source, NULL, NULL);
879         if(!rc->critical)
880             error("Health alarm '%s.%s': failed to re-parse critical expression '%s'", chart, rt->name, rt->critical->source);
881     }
882
883     debug(D_HEALTH, "Health runtime added alarm '%s.%s': exec '%s', recipient '%s', green %Lf, red %Lf, lookup: group %d, after %d, before %d, options %u, dimensions '%s', update every %d, calculation '%s', warning '%s', critical '%s', source '%s', delay up %d, delay down %d, delay max %d, delay_multiplier %f",
884           (rc->chart)?rc->chart:"NOCHART",
885           rc->name,
886           (rc->exec)?rc->exec:"DEFAULT",
887           (rc->recipient)?rc->recipient:"DEFAULT",
888           rc->green,
889           rc->red,
890           rc->group,
891           rc->after,
892           rc->before,
893           rc->options,
894           (rc->dimensions)?rc->dimensions:"NONE",
895           rc->update_every,
896           (rc->calculation)?rc->calculation->parsed_as:"NONE",
897           (rc->warning)?rc->warning->parsed_as:"NONE",
898           (rc->critical)?rc->critical->parsed_as:"NONE",
899           rc->source,
900           rc->delay_up_duration,
901           rc->delay_down_duration,
902           rc->delay_max_duration,
903           rc->delay_multiplier
904     );
905
906     rrdcalc_create_part2(host, rc);
907     return rc;
908 }
909
910 void rrdcalc_free(RRDHOST *host, RRDCALC *rc) {
911     if(!rc) return;
912
913     debug(D_HEALTH, "Health removing alarm '%s.%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
914
915     // unlink it from RRDSET
916     if(rc->rrdset) rrdsetcalc_unlink(rc);
917
918     // unlink it from RRDHOST
919     if(unlikely(rc == host->alarms))
920         host->alarms = rc->next;
921
922     else if(likely(host->alarms)) {
923         RRDCALC *t, *last = host->alarms;
924         for(t = last->next; t && t != rc; last = t, t = t->next) ;
925         if(last->next == rc)
926             last->next = rc->next;
927         else
928             error("Cannot unlink alarm '%s.%s' from host '%s': not found", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
929     }
930     else
931         error("Cannot unlink unlink '%s.%s' from host '%s': This host does not have any calculations", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
932
933     expression_free(rc->calculation);
934     expression_free(rc->warning);
935     expression_free(rc->critical);
936
937     freez(rc->name);
938     freez(rc->chart);
939     freez(rc->family);
940     freez(rc->dimensions);
941     freez(rc->exec);
942     freez(rc->recipient);
943     freez(rc->source);
944     freez(rc->units);
945     freez(rc->info);
946     freez(rc);
947 }
948
949 // ----------------------------------------------------------------------------
950 // RRDCALCTEMPLATE management
951
952 void rrdcalctemplate_link_matching(RRDSET *st) {
953     RRDCALCTEMPLATE *rt;
954
955     for(rt = st->rrdhost->templates; rt ; rt = rt->next) {
956         if(rt->hash_context == st->hash_context && !strcmp(rt->context, st->context)) {
957             RRDCALC *rc = rrdcalc_create(st->rrdhost, rt, st->id);
958             if(unlikely(!rc))
959                 error("Health tried to create alarm from template '%s', but it failed", rt->name);
960
961 #ifdef NETDATA_INTERNAL_CHECKS
962             else if(rc->rrdset != st)
963                 error("Health alarm '%s.%s' should be linked to chart '%s', but it is not", rc->chart?rc->chart:"NOCHART", rc->name, st->id);
964 #endif
965         }
966     }
967 }
968
969 static inline void rrdcalctemplate_free(RRDHOST *host, RRDCALCTEMPLATE *rt) {
970     debug(D_HEALTH, "Health removing template '%s' of host '%s'", rt->name, host->hostname);
971
972     if(host->templates) {
973         if(host->templates == rt) {
974             host->templates = rt->next;
975         }
976         else {
977             RRDCALCTEMPLATE *t, *last = host->templates;
978             for (t = last->next; t && t != rt; last = t, t = t->next ) ;
979             if(last && last->next == rt) {
980                 last->next = rt->next;
981                 rt->next = NULL;
982             }
983             else
984                 error("Cannot find RRDCALCTEMPLATE '%s' linked in host '%s'", rt->name, host->hostname);
985         }
986     }
987
988     expression_free(rt->calculation);
989     expression_free(rt->warning);
990     expression_free(rt->critical);
991
992     freez(rt->name);
993     freez(rt->exec);
994     freez(rt->recipient);
995     freez(rt->context);
996     freez(rt->source);
997     freez(rt->units);
998     freez(rt->info);
999     freez(rt->dimensions);
1000     freez(rt);
1001 }
1002
1003 // ----------------------------------------------------------------------------
1004 // load health configuration
1005
1006 #define HEALTH_CONF_MAX_LINE 4096
1007
1008 #define HEALTH_ALARM_KEY "alarm"
1009 #define HEALTH_TEMPLATE_KEY "template"
1010 #define HEALTH_ON_KEY "on"
1011 #define HEALTH_LOOKUP_KEY "lookup"
1012 #define HEALTH_CALC_KEY "calc"
1013 #define HEALTH_EVERY_KEY "every"
1014 #define HEALTH_GREEN_KEY "green"
1015 #define HEALTH_RED_KEY "red"
1016 #define HEALTH_WARN_KEY "warn"
1017 #define HEALTH_CRIT_KEY "crit"
1018 #define HEALTH_EXEC_KEY "exec"
1019 #define HEALTH_RECIPIENT_KEY "to"
1020 #define HEALTH_UNITS_KEY "units"
1021 #define HEALTH_INFO_KEY "info"
1022 #define HEALTH_DELAY_KEY "delay"
1023
1024 static inline int rrdcalc_add_alarm_from_config(RRDHOST *host, RRDCALC *rc) {
1025     if(!rc->chart) {
1026         error("Health configuration for alarm '%s' does not have a chart", rc->name);
1027         return 0;
1028     }
1029
1030     if(!rc->update_every) {
1031         error("Health configuration for alarm '%s.%s' has no frequency (parameter 'every'). Ignoring it.", rc->chart?rc->chart:"NOCHART", rc->name);
1032         return 0;
1033     }
1034
1035     if(!RRDCALC_HAS_DB_LOOKUP(rc) && !rc->warning && !rc->critical) {
1036         error("Health configuration for alarm '%s.%s' is useless (no calculation, no warning and no critical evaluation)", rc->chart?rc->chart:"NOCHART", rc->name);
1037         return 0;
1038     }
1039
1040     if (rrdcalc_exists(host, rc->chart, rc->name, rc->hash_chart, rc->hash))
1041         return 0;
1042
1043     rc->id = rrdcalc_get_unique_id(&localhost, rc->chart, rc->name, &rc->next_event_id);
1044
1045     debug(D_HEALTH, "Health configuration adding alarm '%s.%s' (%u): exec '%s', recipient '%s', green %Lf, red %Lf, lookup: group %d, after %d, before %d, options %u, dimensions '%s', update every %d, calculation '%s', warning '%s', critical '%s', source '%s', delay up %d, delay down %d, delay max %d, delay_multiplier %f",
1046           rc->chart?rc->chart:"NOCHART",
1047           rc->name,
1048           rc->id,
1049           (rc->exec)?rc->exec:"DEFAULT",
1050           (rc->recipient)?rc->recipient:"DEFAULT",
1051           rc->green,
1052           rc->red,
1053           rc->group,
1054           rc->after,
1055           rc->before,
1056           rc->options,
1057           (rc->dimensions)?rc->dimensions:"NONE",
1058           rc->update_every,
1059           (rc->calculation)?rc->calculation->parsed_as:"NONE",
1060           (rc->warning)?rc->warning->parsed_as:"NONE",
1061           (rc->critical)?rc->critical->parsed_as:"NONE",
1062           rc->source,
1063           rc->delay_up_duration,
1064           rc->delay_down_duration,
1065           rc->delay_max_duration,
1066           rc->delay_multiplier
1067     );
1068
1069     rrdcalc_create_part2(host, rc);
1070     return 1;
1071 }
1072
1073 static inline int rrdcalctemplate_add_template_from_config(RRDHOST *host, RRDCALCTEMPLATE *rt) {
1074     if(unlikely(!rt->context)) {
1075         error("Health configuration for template '%s' does not have a context", rt->name);
1076         return 0;
1077     }
1078
1079     if(unlikely(!rt->update_every)) {
1080         error("Health configuration for template '%s' has no frequency (parameter 'every'). Ignoring it.", rt->name);
1081         return 0;
1082     }
1083
1084     if(unlikely(!RRDCALCTEMPLATE_HAS_CALCULATION(rt) && !rt->warning && !rt->critical)) {
1085         error("Health configuration for template '%s' is useless (no calculation, no warning and no critical evaluation)", rt->name);
1086         return 0;
1087     }
1088
1089     RRDCALCTEMPLATE *t, *last = NULL;
1090     for (t = host->templates; t ; last = t, t = t->next) {
1091         if(unlikely(t->hash_name == rt->hash_name && !strcmp(t->name, rt->name))) {
1092             error("Health configuration template '%s' already exists for host '%s'.", rt->name, host->hostname);
1093             return 0;
1094         }
1095     }
1096
1097     debug(D_HEALTH, "Health configuration adding template '%s': context '%s', exec '%s', recipient '%s', green %Lf, red %Lf, lookup: group %d, after %d, before %d, options %u, dimensions '%s', update every %d, calculation '%s', warning '%s', critical '%s', source '%s', delay up %d, delay down %d, delay max %d, delay_multiplier %f",
1098           rt->name,
1099           (rt->context)?rt->context:"NONE",
1100           (rt->exec)?rt->exec:"DEFAULT",
1101           (rt->recipient)?rt->recipient:"DEFAULT",
1102           rt->green,
1103           rt->red,
1104           rt->group,
1105           rt->after,
1106           rt->before,
1107           rt->options,
1108           (rt->dimensions)?rt->dimensions:"NONE",
1109           rt->update_every,
1110           (rt->calculation)?rt->calculation->parsed_as:"NONE",
1111           (rt->warning)?rt->warning->parsed_as:"NONE",
1112           (rt->critical)?rt->critical->parsed_as:"NONE",
1113           rt->source,
1114           rt->delay_up_duration,
1115           rt->delay_down_duration,
1116           rt->delay_max_duration,
1117           rt->delay_multiplier
1118     );
1119
1120     if(likely(last)) {
1121         last->next = rt;
1122     }
1123     else {
1124         rt->next = host->templates;
1125         host->templates = rt;
1126     }
1127
1128     return 1;
1129 }
1130
1131 static inline int health_parse_duration(char *string, int *result) {
1132     // make sure it is a number
1133     if(!*string || !(isdigit(*string) || *string == '+' || *string == '-')) {
1134         *result = 0;
1135         return 0;
1136     }
1137
1138     char *e = NULL;
1139     calculated_number n = strtold(string, &e);
1140     if(e && *e) {
1141         switch (*e) {
1142             case 'Y':
1143                 *result = (int) (n * 86400 * 365);
1144                 break;
1145             case 'M':
1146                 *result = (int) (n * 86400 * 30);
1147                 break;
1148             case 'w':
1149                 *result = (int) (n * 86400 * 7);
1150                 break;
1151             case 'd':
1152                 *result = (int) (n * 86400);
1153                 break;
1154             case 'h':
1155                 *result = (int) (n * 3600);
1156                 break;
1157             case 'm':
1158                 *result = (int) (n * 60);
1159                 break;
1160
1161             default:
1162             case 's':
1163                 *result = (int) (n);
1164                 break;
1165         }
1166     }
1167     else
1168        *result = (int)(n);
1169
1170     return 1;
1171 }
1172
1173 static inline int health_parse_delay(
1174         size_t line, const char *path, const char *file, char *string,
1175         int *delay_up_duration,
1176         int *delay_down_duration,
1177         int *delay_max_duration,
1178         float *delay_multiplier) {
1179
1180     char given_up = 0;
1181     char given_down = 0;
1182     char given_max = 0;
1183     char given_multiplier = 0;
1184
1185     char *s = string;
1186     while(*s) {
1187         char *key = s;
1188
1189         while(*s && !isspace(*s)) s++;
1190         while(*s && isspace(*s)) *s++ = '\0';
1191
1192         if(!*key) break;
1193
1194         char *value = s;
1195         while(*s && !isspace(*s)) s++;
1196         while(*s && isspace(*s)) *s++ = '\0';
1197
1198         if(!strcasecmp(key, "up")) {
1199             if (!health_parse_duration(value, delay_up_duration)) {
1200                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1201                       line, path, file, value, key);
1202             }
1203             else given_up = 1;
1204         }
1205         else if(!strcasecmp(key, "down")) {
1206             if (!health_parse_duration(value, delay_down_duration)) {
1207                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1208                       line, path, file, value, key);
1209             }
1210             else given_down = 1;
1211         }
1212         else if(!strcasecmp(key, "multiplier")) {
1213             *delay_multiplier = strtof(value, NULL);
1214             if(isnan(*delay_multiplier) || isinf(*delay_multiplier) || islessequal(*delay_multiplier, 0)) {
1215                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1216                       line, path, file, value, key);
1217             }
1218             else given_multiplier = 1;
1219         }
1220         else if(!strcasecmp(key, "max")) {
1221             if (!health_parse_duration(value, delay_max_duration)) {
1222                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1223                       line, path, file, value, key);
1224             }
1225             else given_max = 1;
1226         }
1227         else {
1228             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
1229                   line, path, file, key);
1230         }
1231     }
1232
1233     if(!given_up)
1234         *delay_up_duration = 0;
1235
1236     if(!given_down)
1237         *delay_down_duration = 0;
1238
1239     if(!given_multiplier)
1240         *delay_multiplier = 1.0;
1241
1242     if(!given_max) {
1243         if((*delay_max_duration) < (*delay_up_duration) * (*delay_multiplier))
1244             *delay_max_duration = (*delay_up_duration) * (*delay_multiplier);
1245
1246         if((*delay_max_duration) < (*delay_down_duration) * (*delay_multiplier))
1247             *delay_max_duration = (*delay_down_duration) * (*delay_multiplier);
1248     }
1249
1250     return 1;
1251 }
1252
1253 static inline int health_parse_db_lookup(
1254         size_t line, const char *path, const char *file, char *string,
1255         int *group_method, int *after, int *before, int *every,
1256         uint32_t *options, char **dimensions
1257 ) {
1258     debug(D_HEALTH, "Health configuration parsing database lookup %zu@%s/%s: %s", line, path, file, string);
1259
1260     if(*dimensions) freez(*dimensions);
1261     *dimensions = NULL;
1262     *after = 0;
1263     *before = 0;
1264     *every = 0;
1265     *options = 0;
1266
1267     char *s = string, *key;
1268
1269     // first is the group method
1270     key = s;
1271     while(*s && !isspace(*s)) s++;
1272     while(*s && isspace(*s)) *s++ = '\0';
1273     if(!*s) {
1274         error("Health configuration invalid chart calculation at line %zu of file '%s/%s': expected group method followed by the 'after' time, but got '%s'",
1275               line, path, file, key);
1276         return 0;
1277     }
1278
1279     if((*group_method = web_client_api_request_v1_data_group(key, -1)) == -1) {
1280         error("Health configuration at line %zu of file '%s/%s': invalid group method '%s'",
1281               line, path, file, key);
1282         return 0;
1283     }
1284
1285     // then is the 'after' time
1286     key = s;
1287     while(*s && !isspace(*s)) s++;
1288     while(*s && isspace(*s)) *s++ = '\0';
1289
1290     if(!health_parse_duration(key, after)) {
1291         error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' after group method",
1292               line, path, file, key);
1293         return 0;
1294     }
1295
1296     // sane defaults
1297     *every = abs(*after);
1298
1299     // now we may have optional parameters
1300     while(*s) {
1301         key = s;
1302         while(*s && !isspace(*s)) s++;
1303         while(*s && isspace(*s)) *s++ = '\0';
1304         if(!*key) break;
1305
1306         if(!strcasecmp(key, "at")) {
1307             char *value = s;
1308             while(*s && !isspace(*s)) s++;
1309             while(*s && isspace(*s)) *s++ = '\0';
1310
1311             if (!health_parse_duration(value, before)) {
1312                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
1313                       line, path, file, value, key);
1314             }
1315         }
1316         else if(!strcasecmp(key, HEALTH_EVERY_KEY)) {
1317             char *value = s;
1318             while(*s && !isspace(*s)) s++;
1319             while(*s && isspace(*s)) *s++ = '\0';
1320
1321             if (!health_parse_duration(value, every)) {
1322                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
1323                       line, path, file, value, key);
1324             }
1325         }
1326         else if(!strcasecmp(key, "absolute") || !strcasecmp(key, "abs") || !strcasecmp(key, "absolute_sum")) {
1327             *options |= RRDR_OPTION_ABSOLUTE;
1328         }
1329         else if(!strcasecmp(key, "min2max")) {
1330             *options |= RRDR_OPTION_MIN2MAX;
1331         }
1332         else if(!strcasecmp(key, "null2zero")) {
1333             *options |= RRDR_OPTION_NULL2ZERO;
1334         }
1335         else if(!strcasecmp(key, "percentage")) {
1336             *options |= RRDR_OPTION_PERCENTAGE;
1337         }
1338         else if(!strcasecmp(key, "unaligned")) {
1339             *options |= RRDR_OPTION_NOT_ALIGNED;
1340         }
1341         else if(!strcasecmp(key, "of")) {
1342             if(*s && strcasecmp(s, "all"))
1343                *dimensions = strdupz(s);
1344             break;
1345         }
1346         else {
1347             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
1348                   line, path, file, key);
1349         }
1350     }
1351
1352     return 1;
1353 }
1354
1355 static inline char *health_source_file(size_t line, const char *path, const char *filename) {
1356     char buffer[FILENAME_MAX + 1];
1357     snprintfz(buffer, FILENAME_MAX, "%zu@%s/%s", line, path, filename);
1358     return strdupz(buffer);
1359 }
1360
1361 static inline void strip_quotes(char *s) {
1362     while(*s) {
1363         if(*s == '\'' || *s == '"') *s = ' ';
1364         s++;
1365     }
1366 }
1367
1368 int health_readfile(const char *path, const char *filename) {
1369     debug(D_HEALTH, "Health configuration reading file '%s/%s'", path, filename);
1370
1371     static uint32_t hash_alarm = 0, hash_template = 0, hash_on = 0, hash_calc = 0, hash_green = 0, hash_red = 0, hash_warn = 0, hash_crit = 0, hash_exec = 0, hash_every = 0, hash_lookup = 0, hash_units = 0, hash_info = 0, hash_recipient = 0, hash_delay = 0;
1372     char buffer[HEALTH_CONF_MAX_LINE + 1];
1373
1374     if(unlikely(!hash_alarm)) {
1375         hash_alarm = simple_uhash(HEALTH_ALARM_KEY);
1376         hash_template = simple_uhash(HEALTH_TEMPLATE_KEY);
1377         hash_on = simple_uhash(HEALTH_ON_KEY);
1378         hash_calc = simple_uhash(HEALTH_CALC_KEY);
1379         hash_lookup = simple_uhash(HEALTH_LOOKUP_KEY);
1380         hash_green = simple_uhash(HEALTH_GREEN_KEY);
1381         hash_red = simple_uhash(HEALTH_RED_KEY);
1382         hash_warn = simple_uhash(HEALTH_WARN_KEY);
1383         hash_crit = simple_uhash(HEALTH_CRIT_KEY);
1384         hash_exec = simple_uhash(HEALTH_EXEC_KEY);
1385         hash_every = simple_uhash(HEALTH_EVERY_KEY);
1386         hash_units = simple_hash(HEALTH_UNITS_KEY);
1387         hash_info = simple_hash(HEALTH_INFO_KEY);
1388         hash_recipient = simple_hash(HEALTH_RECIPIENT_KEY);
1389         hash_delay = simple_uhash(HEALTH_DELAY_KEY);
1390     }
1391
1392     snprintfz(buffer, HEALTH_CONF_MAX_LINE, "%s/%s", path, filename);
1393     FILE *fp = fopen(buffer, "r");
1394     if(!fp) {
1395         error("Health configuration cannot read file '%s'.", buffer);
1396         return 0;
1397     }
1398
1399     RRDCALC *rc = NULL;
1400     RRDCALCTEMPLATE *rt = NULL;
1401
1402     size_t line = 0, append = 0;
1403     char *s;
1404     while((s = fgets(&buffer[append], (int)(HEALTH_CONF_MAX_LINE - append), fp)) || append) {
1405         int stop_appending = !s;
1406         line++;
1407         // info("Line %zu of file '%s/%s': '%s'", line, path, filename, s);
1408         s = trim(buffer);
1409         if(!s) continue;
1410         // info("Trimmed line %zu of file '%s/%s': '%s'", line, path, filename, s);
1411
1412         append = strlen(s);
1413         if(!stop_appending && s[append - 1] == '\\') {
1414             s[append - 1] = ' ';
1415             append = &s[append] - buffer;
1416             if(append < HEALTH_CONF_MAX_LINE)
1417                 continue;
1418             else {
1419                 error("Health configuration has too long muli-line at line %zu of file '%s/%s'.", line, path, filename);
1420             }
1421         }
1422         append = 0;
1423
1424         char *key = s;
1425         while(*s && *s != ':') s++;
1426         if(!*s) {
1427             error("Health configuration has invalid line %zu of file '%s/%s'. It does not contain a ':'. Ignoring it.", line, path, filename);
1428             continue;
1429         }
1430         *s = '\0';
1431         s++;
1432
1433         char *value = s;
1434         key = trim(key);
1435         value = trim(value);
1436
1437         if(!key) {
1438             error("Health configuration has invalid line %zu of file '%s/%s'. Keyword is empty. Ignoring it.", line, path, filename);
1439             continue;
1440         }
1441
1442         if(!value) {
1443             error("Health configuration has invalid line %zu of file '%s/%s'. value is empty. Ignoring it.", line, path, filename);
1444             continue;
1445         }
1446
1447         // info("Health file '%s/%s', key '%s', value '%s'", path, filename, key, value);
1448         uint32_t hash = simple_uhash(key);
1449
1450         if(hash == hash_alarm && !strcasecmp(key, HEALTH_ALARM_KEY)) {
1451             if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1452                 rrdcalc_free(&localhost, rc);
1453
1454             if(rt) {
1455                 if (!rrdcalctemplate_add_template_from_config(&localhost, rt))
1456                     rrdcalctemplate_free(&localhost, rt);
1457                 rt = NULL;
1458             }
1459
1460             rc = callocz(1, sizeof(RRDCALC));
1461             rc->next_event_id = 1;
1462             rc->name = strdupz(value);
1463             rc->hash = simple_hash(rc->name);
1464             rc->source = health_source_file(line, path, filename);
1465             rc->green = NAN;
1466             rc->red = NAN;
1467             rc->value = NAN;
1468             rc->old_value = NAN;
1469             rc->delay_multiplier = 1.0;
1470
1471             if(rrdvar_fix_name(rc->name))
1472                 error("Health configuration renamed alarm '%s' to '%s'", value, rc->name);
1473         }
1474         else if(hash == hash_template && !strcasecmp(key, HEALTH_TEMPLATE_KEY)) {
1475             if(rc) {
1476                 if(!rrdcalc_add_alarm_from_config(&localhost, rc))
1477                     rrdcalc_free(&localhost, rc);
1478                 rc = NULL;
1479             }
1480
1481             if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1482                 rrdcalctemplate_free(&localhost, rt);
1483
1484             rt = callocz(1, sizeof(RRDCALCTEMPLATE));
1485             rt->name = strdupz(value);
1486             rt->hash_name = simple_hash(rt->name);
1487             rt->source = health_source_file(line, path, filename);
1488             rt->green = NAN;
1489             rt->red = NAN;
1490             rt->delay_multiplier = 1.0;
1491
1492             if(rrdvar_fix_name(rt->name))
1493                 error("Health configuration renamed template '%s' to '%s'", value, rt->name);
1494         }
1495         else if(rc) {
1496             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1497                 if(rc->chart) {
1498                     if(strcmp(rc->chart, value))
1499                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1500                              line, path, filename, rc->name, key, rc->chart, value, value);
1501
1502                     freez(rc->chart);
1503                 }
1504                 rc->chart = strdupz(value);
1505                 rc->hash_chart = simple_hash(rc->chart);
1506             }
1507             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1508                 health_parse_db_lookup(line, path, filename, value, &rc->group, &rc->after, &rc->before,
1509                                        &rc->update_every,
1510                                        &rc->options, &rc->dimensions);
1511             }
1512             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1513                 if(!health_parse_duration(value, &rc->update_every))
1514                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
1515                          line, path, filename, rc->name, key, value);
1516             }
1517             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1518                 char *e;
1519                 rc->green = strtold(value, &e);
1520                 if(e && *e) {
1521                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1522                          line, path, filename, rc->name, key, e);
1523                 }
1524             }
1525             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1526                 char *e;
1527                 rc->red = strtold(value, &e);
1528                 if(e && *e) {
1529                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1530                          line, path, filename, rc->name, key, e);
1531                 }
1532             }
1533             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1534                 const char *failed_at = NULL;
1535                 int error = 0;
1536                 rc->calculation = expression_parse(value, &failed_at, &error);
1537                 if(!rc->calculation) {
1538                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1539                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1540                 }
1541             }
1542             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1543                 const char *failed_at = NULL;
1544                 int error = 0;
1545                 rc->warning = expression_parse(value, &failed_at, &error);
1546                 if(!rc->warning) {
1547                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1548                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1549                 }
1550             }
1551             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1552                 const char *failed_at = NULL;
1553                 int error = 0;
1554                 rc->critical = expression_parse(value, &failed_at, &error);
1555                 if(!rc->critical) {
1556                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1557                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1558                 }
1559             }
1560             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1561                 if(rc->exec) {
1562                     if(strcmp(rc->exec, value))
1563                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1564                              line, path, filename, rc->name, key, rc->exec, value, value);
1565
1566                     freez(rc->exec);
1567                 }
1568                 rc->exec = strdupz(value);
1569             }
1570             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
1571                 if(rc->recipient) {
1572                     if(strcmp(rc->recipient, value))
1573                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1574                              line, path, filename, rc->name, key, rc->recipient, value, value);
1575
1576                     freez(rc->recipient);
1577                 }
1578                 rc->recipient = strdupz(value);
1579             }
1580             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
1581                 if(rc->units) {
1582                     if(strcmp(rc->units, value))
1583                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1584                              line, path, filename, rc->name, key, rc->units, value, value);
1585
1586                     freez(rc->units);
1587                 }
1588                 rc->units = strdupz(value);
1589                 strip_quotes(rc->units);
1590             }
1591             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
1592                 if(rc->info) {
1593                     if(strcmp(rc->info, value))
1594                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1595                              line, path, filename, rc->name, key, rc->info, value, value);
1596
1597                     freez(rc->info);
1598                 }
1599                 rc->info = strdupz(value);
1600                 strip_quotes(rc->info);
1601             }
1602             else if(hash == hash_delay && !strcasecmp(key, HEALTH_DELAY_KEY)) {
1603                 health_parse_delay(line, path, filename, value, &rc->delay_up_duration, &rc->delay_down_duration, &rc->delay_max_duration, &rc->delay_multiplier);
1604             }
1605             else {
1606                 error("Health configuration at line %zu of file '%s/%s' for alarm '%s' has unknown key '%s'.",
1607                      line, path, filename, rc->name, key);
1608             }
1609         }
1610         else if(rt) {
1611             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1612                 if(rt->context) {
1613                     if(strcmp(rt->context, value))
1614                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1615                              line, path, filename, rt->name, key, rt->context, value, value);
1616
1617                     freez(rt->context);
1618                 }
1619                 rt->context = strdupz(value);
1620                 rt->hash_context = simple_hash(rt->context);
1621             }
1622             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1623                 health_parse_db_lookup(line, path, filename, value, &rt->group, &rt->after, &rt->before,
1624                                        &rt->update_every,
1625                                        &rt->options, &rt->dimensions);
1626             }
1627             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1628                 if(!health_parse_duration(value, &rt->update_every))
1629                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
1630                          line, path, filename, rt->name, key, value);
1631             }
1632             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1633                 char *e;
1634                 rt->green = strtold(value, &e);
1635                 if(e && *e) {
1636                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1637                          line, path, filename, rt->name, key, e);
1638                 }
1639             }
1640             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1641                 char *e;
1642                 rt->red = strtold(value, &e);
1643                 if(e && *e) {
1644                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1645                          line, path, filename, rt->name, key, e);
1646                 }
1647             }
1648             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1649                 const char *failed_at = NULL;
1650                 int error = 0;
1651                 rt->calculation = expression_parse(value, &failed_at, &error);
1652                 if(!rt->calculation) {
1653                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1654                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1655                 }
1656             }
1657             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1658                 const char *failed_at = NULL;
1659                 int error = 0;
1660                 rt->warning = expression_parse(value, &failed_at, &error);
1661                 if(!rt->warning) {
1662                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1663                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1664                 }
1665             }
1666             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1667                 const char *failed_at = NULL;
1668                 int error = 0;
1669                 rt->critical = expression_parse(value, &failed_at, &error);
1670                 if(!rt->critical) {
1671                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1672                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1673                 }
1674             }
1675             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1676                 if(rt->exec) {
1677                     if(strcmp(rt->exec, value))
1678                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1679                              line, path, filename, rt->name, key, rt->exec, value, value);
1680
1681                     freez(rt->exec);
1682                 }
1683                 rt->exec = strdupz(value);
1684             }
1685             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
1686                 if(rt->recipient) {
1687                     if(strcmp(rt->recipient, value))
1688                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1689                              line, path, filename, rt->name, key, rt->recipient, value, value);
1690
1691                     freez(rt->recipient);
1692                 }
1693                 rt->recipient = strdupz(value);
1694             }
1695             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
1696                 if(rt->units) {
1697                     if(strcmp(rt->units, value))
1698                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1699                              line, path, filename, rt->name, key, rt->units, value, value);
1700
1701                     freez(rt->units);
1702                 }
1703                 rt->units = strdupz(value);
1704                 strip_quotes(rt->units);
1705             }
1706             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
1707                 if(rt->info) {
1708                     if(strcmp(rt->info, value))
1709                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1710                              line, path, filename, rt->name, key, rt->info, value, value);
1711
1712                     freez(rt->info);
1713                 }
1714                 rt->info = strdupz(value);
1715                 strip_quotes(rt->info);
1716             }
1717             else if(hash == hash_delay && !strcasecmp(key, HEALTH_DELAY_KEY)) {
1718                 health_parse_delay(line, path, filename, value, &rt->delay_up_duration, &rt->delay_down_duration, &rt->delay_max_duration, &rt->delay_multiplier);
1719             }
1720             else {
1721                 error("Health configuration at line %zu of file '%s/%s' for template '%s' has unknown key '%s'.",
1722                       line, path, filename, rt->name, key);
1723             }
1724         }
1725         else {
1726             error("Health configuration at line %zu of file '%s/%s' has unknown key '%s'. Expected either '" HEALTH_ALARM_KEY "' or '" HEALTH_TEMPLATE_KEY "'.",
1727                   line, path, filename, key);
1728         }
1729     }
1730
1731     if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1732         rrdcalc_free(&localhost, rc);
1733
1734     if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1735         rrdcalctemplate_free(&localhost, rt);
1736
1737     fclose(fp);
1738     return 1;
1739 }
1740
1741 void health_readdir(const char *path) {
1742     size_t pathlen = strlen(path);
1743
1744     debug(D_HEALTH, "Health configuration reading directory '%s'", path);
1745
1746     DIR *dir = opendir(path);
1747     if (!dir) {
1748         error("Health configuration cannot open directory '%s'.", path);
1749         return;
1750     }
1751
1752     struct dirent *de = NULL;
1753     while ((de = readdir(dir))) {
1754         size_t len = strlen(de->d_name);
1755
1756         if(de->d_type == DT_DIR
1757            && (
1758                    (de->d_name[0] == '.' && de->d_name[1] == '\0')
1759                    || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')
1760            )) {
1761             debug(D_HEALTH, "Ignoring directory '%s'", de->d_name);
1762             continue;
1763         }
1764
1765         else if(de->d_type == DT_DIR) {
1766             char *s = mallocz(pathlen + strlen(de->d_name) + 2);
1767             strcpy(s, path);
1768             strcat(s, "/");
1769             strcat(s, de->d_name);
1770             health_readdir(s);
1771             freez(s);
1772             continue;
1773         }
1774
1775         else if((de->d_type == DT_LNK || de->d_type == DT_REG || de->d_type == DT_UNKNOWN) &&
1776                 len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) {
1777             health_readfile(path, de->d_name);
1778         }
1779
1780         else debug(D_HEALTH, "Ignoring file '%s'", de->d_name);
1781     }
1782
1783     closedir(dir);
1784 }
1785
1786 static inline char *health_config_dir(void) {
1787     char buffer[FILENAME_MAX + 1];
1788     snprintfz(buffer, FILENAME_MAX, "%s/health.d", config_get("global", "config directory", CONFIG_DIR));
1789     return config_get("health", "health configuration directory", buffer);
1790 }
1791
1792 void health_init(void) {
1793     debug(D_HEALTH, "Health configuration initializing");
1794
1795     if(!(health_enabled = config_get_boolean("health", "enabled", 1))) {
1796         debug(D_HEALTH, "Health is disabled.");
1797         return;
1798     }
1799
1800     health_alarm_log_load(&localhost);
1801
1802     char *path = health_config_dir();
1803
1804     {
1805         char buffer[FILENAME_MAX + 1];
1806         snprintfz(buffer, FILENAME_MAX, "%s/alarm-notify.sh", config_get("global", "plugins directory", PLUGINS_DIR));
1807         health.health_default_exec = config_get("health", "script to execute on alarm", buffer);
1808     }
1809
1810     long n = config_get_number("health", "in memory max health log entries", (long)localhost.health_log.max);
1811     if(n < 10) {
1812         error("Health configuration has invalid max log entries %ld. Using default %u", n, localhost.health_log.max);
1813         config_set_number("health", "in memory max health log entries", (long)localhost.health_log.max);
1814     }
1815     else localhost.health_log.max = (unsigned int)n;
1816
1817     rrdhost_rwlock(&localhost);
1818     health_readdir(path);
1819     rrdhost_unlock(&localhost);
1820 }
1821
1822 // ----------------------------------------------------------------------------
1823 // JSON generation
1824
1825 static inline void health_string2json(BUFFER *wb, const char *prefix, const char *label, const char *value, const char *suffix) {
1826     if(value && *value)
1827         buffer_sprintf(wb, "%s\"%s\":\"%s\"%s", prefix, label, value, suffix);
1828     else
1829         buffer_sprintf(wb, "%s\"%s\":null%s", prefix, label, suffix);
1830 }
1831
1832 static inline void health_alarm_entry2json_nolock(BUFFER *wb, ALARM_ENTRY *ae, RRDHOST *host) {
1833     buffer_sprintf(wb, "\n\t{\n"
1834                            "\t\t\"hostname\": \"%s\",\n"
1835                            "\t\t\"unique_id\": %u,\n"
1836                            "\t\t\"alarm_id\": %u,\n"
1837                            "\t\t\"alarm_event_id\": %u,\n"
1838                            "\t\t\"name\": \"%s\",\n"
1839                            "\t\t\"chart\": \"%s\",\n"
1840                            "\t\t\"family\": \"%s\",\n"
1841                            "\t\t\"processed\": %s,\n"
1842                            "\t\t\"updated\": %s,\n"
1843                            "\t\t\"exec_run\": %lu,\n"
1844                            "\t\t\"exec_failed\": %s,\n"
1845                            "\t\t\"exec\": \"%s\",\n"
1846                            "\t\t\"recipient\": \"%s\",\n"
1847                            "\t\t\"exec_code\": %d,\n"
1848                            "\t\t\"source\": \"%s\",\n"
1849                            "\t\t\"units\": \"%s\",\n"
1850                            "\t\t\"info\": \"%s\",\n"
1851                            "\t\t\"when\": %lu,\n"
1852                            "\t\t\"duration\": %lu,\n"
1853                            "\t\t\"non_clear_duration\": %lu,\n"
1854                            "\t\t\"status\": \"%s\",\n"
1855                            "\t\t\"old_status\": \"%s\",\n"
1856                            "\t\t\"delay\": %d,\n"
1857                            "\t\t\"delay_up_to_timestamp\": %lu,\n",
1858                    host->hostname,
1859                    ae->unique_id,
1860                    ae->alarm_id,
1861                    ae->alarm_event_id,
1862                    ae->name,
1863                    ae->chart,
1864                    ae->family,
1865                    (ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_PROCESSED)?"true":"false",
1866                    (ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED)?"true":"false",
1867                    (unsigned long)ae->exec_run_timestamp,
1868                    (ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_EXEC_FAILED)?"true":"false",
1869                    ae->exec?ae->exec:health.health_default_exec,
1870                    ae->recipient?ae->recipient:health.health_default_recipient,
1871                    ae->exec_code,
1872                    ae->source,
1873                    ae->units?ae->units:"",
1874                    ae->info?ae->info:"",
1875                    (unsigned long)ae->when,
1876                    (unsigned long)ae->duration,
1877                    (unsigned long)ae->non_clear_duration,
1878                    rrdcalc_status2string(ae->new_status),
1879                    rrdcalc_status2string(ae->old_status),
1880                    ae->delay,
1881                    (unsigned long)ae->delay_up_to_timestamp
1882     );
1883
1884     buffer_strcat(wb, "\t\t\"value\":");
1885     buffer_rrd_value(wb, ae->new_value);
1886     buffer_strcat(wb, ",\n");
1887
1888     buffer_strcat(wb, "\t\t\"old_value\":");
1889     buffer_rrd_value(wb, ae->old_value);
1890     buffer_strcat(wb, "\n");
1891
1892     buffer_strcat(wb, "\t}");
1893 }
1894
1895 void health_alarm_log2json(RRDHOST *host, BUFFER *wb, uint32_t after) {
1896     pthread_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
1897
1898     buffer_strcat(wb, "[");
1899
1900     unsigned int max = host->health_log.max;
1901     unsigned int count = 0;
1902     ALARM_ENTRY *ae;
1903     for(ae = host->health_log.alarms; ae && count < max ; count++, ae = ae->next) {
1904         if(ae->unique_id > after) {
1905             if(likely(count)) buffer_strcat(wb, ",");
1906             health_alarm_entry2json_nolock(wb, ae, host);
1907         }
1908     }
1909
1910     buffer_strcat(wb, "\n]\n");
1911
1912     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
1913 }
1914
1915 static inline void health_rrdcalc2json_nolock(BUFFER *wb, RRDCALC *rc) {
1916     buffer_sprintf(wb,
1917            "\t\t\"%s.%s\": {\n"
1918                    "\t\t\t\"id\": %lu,\n"
1919                    "\t\t\t\"name\": \"%s\",\n"
1920                    "\t\t\t\"chart\": \"%s\",\n"
1921                    "\t\t\t\"family\": \"%s\",\n"
1922                    "\t\t\t\"active\": %s,\n"
1923                    "\t\t\t\"exec\": \"%s\",\n"
1924                    "\t\t\t\"recipient\": \"%s\",\n"
1925                    "\t\t\t\"source\": \"%s\",\n"
1926                    "\t\t\t\"units\": \"%s\",\n"
1927                    "\t\t\t\"info\": \"%s\",\n"
1928                                    "\t\t\t\"status\": \"%s\",\n"
1929                    "\t\t\t\"last_status_change\": %lu,\n"
1930                    "\t\t\t\"last_updated\": %lu,\n"
1931                    "\t\t\t\"next_update\": %lu,\n"
1932                    "\t\t\t\"update_every\": %d,\n"
1933                    "\t\t\t\"delay_up_duration\": %d,\n"
1934                    "\t\t\t\"delay_down_duration\": %d,\n"
1935                    "\t\t\t\"delay_max_duration\": %d,\n"
1936                    "\t\t\t\"delay_multiplier\": %f,\n"
1937                    "\t\t\t\"delay\": %d,\n"
1938                    "\t\t\t\"delay_up_to_timestamp\": %lu,\n"
1939             , rc->chart, rc->name
1940             , (unsigned long)rc->id
1941             , rc->name
1942             , rc->chart
1943             , (rc->rrdset && rc->rrdset->family)?rc->rrdset->family:""
1944             , (rc->rrdset)?"true":"false"
1945             , rc->exec?rc->exec:health.health_default_exec
1946             , rc->recipient?rc->recipient:health.health_default_recipient
1947             , rc->source
1948             , rc->units?rc->units:""
1949             , rc->info?rc->info:""
1950             , rrdcalc_status2string(rc->status)
1951             , (unsigned long)rc->last_status_change
1952             , (unsigned long)rc->last_updated
1953             , (unsigned long)rc->next_update
1954             , rc->update_every
1955             , rc->delay_up_duration
1956             , rc->delay_down_duration
1957             , rc->delay_max_duration
1958             , rc->delay_multiplier
1959             , rc->delay_last
1960             , (unsigned long)rc->delay_up_to_timestamp
1961     );
1962
1963     if(RRDCALC_HAS_DB_LOOKUP(rc)) {
1964         if(rc->dimensions && *rc->dimensions)
1965             health_string2json(wb, "\t\t\t", "lookup_dimensions", rc->dimensions, ",\n");
1966
1967         buffer_sprintf(wb,
1968                        "\t\t\t\"db_after\": %lu,\n"
1969                        "\t\t\t\"db_before\": %lu,\n"
1970                        "\t\t\t\"lookup_method\": \"%s\",\n"
1971                        "\t\t\t\"lookup_after\": %d,\n"
1972                        "\t\t\t\"lookup_before\": %d,\n"
1973                        "\t\t\t\"lookup_options\": \"",
1974                        (unsigned long) rc->db_after,
1975                        (unsigned long) rc->db_before,
1976                        group_method2string(rc->group),
1977                        rc->after,
1978                        rc->before
1979         );
1980         buffer_data_options2string(wb, rc->options);
1981         buffer_strcat(wb, "\",\n");
1982     }
1983
1984     if(rc->calculation) {
1985         health_string2json(wb, "\t\t\t", "calc", rc->calculation->source, ",\n");
1986         health_string2json(wb, "\t\t\t", "calc_parsed", rc->calculation->parsed_as, ",\n");
1987     }
1988
1989     if(rc->warning) {
1990         health_string2json(wb, "\t\t\t", "warn", rc->warning->source, ",\n");
1991         health_string2json(wb, "\t\t\t", "warn_parsed", rc->warning->parsed_as, ",\n");
1992     }
1993
1994     if(rc->critical) {
1995         health_string2json(wb, "\t\t\t", "crit", rc->critical->source, ",\n");
1996         health_string2json(wb, "\t\t\t", "crit_parsed", rc->critical->parsed_as, ",\n");
1997     }
1998
1999     buffer_strcat(wb, "\t\t\t\"green\":");
2000     buffer_rrd_value(wb, rc->green);
2001     buffer_strcat(wb, ",\n");
2002
2003     buffer_strcat(wb, "\t\t\t\"red\":");
2004     buffer_rrd_value(wb, rc->red);
2005     buffer_strcat(wb, ",\n");
2006
2007     buffer_strcat(wb, "\t\t\t\"value\":");
2008     buffer_rrd_value(wb, rc->value);
2009     buffer_strcat(wb, "\n");
2010
2011     buffer_strcat(wb, "\t\t}");
2012 }
2013
2014 //void health_rrdcalctemplate2json_nolock(BUFFER *wb, RRDCALCTEMPLATE *rt) {
2015 //
2016 //}
2017
2018 void health_alarms2json(RRDHOST *host, BUFFER *wb, int all) {
2019     int i;
2020
2021     rrdhost_rdlock(&localhost);
2022     buffer_sprintf(wb, "{\n\t\"hostname\": \"%s\","
2023                         "\n\t\"latest_alarm_log_unique_id\": %u,"
2024                         "\n\t\"status\": %s,"
2025                         "\n\t\"now\": %lu,"
2026                         "\n\t\"alarms\": {\n",
2027                         host->hostname,
2028                         (host->health_log.next_log_id > 0)?(host->health_log.next_log_id - 1):0,
2029                         health_enabled?"true":"false",
2030                         (unsigned long)time(NULL));
2031
2032     RRDCALC *rc;
2033     for(i = 0, rc = host->alarms; rc ; rc = rc->next) {
2034         if(unlikely(!rc->rrdset || !rc->rrdset->last_collected_time.tv_sec))
2035             continue;
2036
2037         if(likely(!all && !(rc->status == RRDCALC_STATUS_WARNING || rc->status == RRDCALC_STATUS_CRITICAL)))
2038             continue;
2039
2040         if(likely(i)) buffer_strcat(wb, ",\n");
2041         health_rrdcalc2json_nolock(wb, rc);
2042         i++;
2043     }
2044
2045 //    buffer_strcat(wb, "\n\t},\n\t\"templates\": {");
2046 //    RRDCALCTEMPLATE *rt;
2047 //    for(rt = host->templates; rt ; rt = rt->next)
2048 //        health_rrdcalctemplate2json_nolock(wb, rt);
2049
2050     buffer_strcat(wb, "\n\t}\n}\n");
2051     rrdhost_unlock(&localhost);
2052 }
2053
2054
2055 // ----------------------------------------------------------------------------
2056 // re-load health configuration
2057
2058 static inline void health_free_all_nolock(RRDHOST *host) {
2059     while(host->templates)
2060         rrdcalctemplate_free(host, host->templates);
2061
2062     while(host->alarms)
2063         rrdcalc_free(host, host->alarms);
2064 }
2065
2066 void health_reload(void) {
2067     if(!health_enabled) {
2068         error("Health reload is requested, but health is not enabled.");
2069         return;
2070     }
2071
2072     char *path = health_config_dir();
2073
2074     // free all running alarms
2075     rrdhost_rwlock(&localhost);
2076     health_free_all_nolock(&localhost);
2077     rrdhost_unlock(&localhost);
2078
2079     // invalidate all previous entries in the alarm log
2080     ALARM_ENTRY *t;
2081     for(t = localhost.health_log.alarms ; t ; t = t->next) {
2082         if(t->new_status != RRDCALC_STATUS_REMOVED)
2083             t->notifications |= HEALTH_ENTRY_NOTIFICATIONS_UPDATED;
2084     }
2085
2086     // reset all thresholds to all charts
2087     RRDSET *st;
2088     for(st = localhost.rrdset_root; st ; st = st->next) {
2089         st->green = NAN;
2090         st->red = NAN;
2091     }
2092
2093     // load the new alarms
2094     rrdhost_rwlock(&localhost);
2095     health_readdir(path);
2096     rrdhost_unlock(&localhost);
2097
2098     // link the loaded alarms to their charts
2099     for(st = localhost.rrdset_root; st ; st = st->next) {
2100         rrdhost_rwlock(&localhost);
2101
2102         rrdsetcalc_link_matching(st);
2103         rrdcalctemplate_link_matching(st);
2104
2105         rrdhost_unlock(&localhost);
2106     }
2107 }
2108
2109 // ----------------------------------------------------------------------------
2110 // health main thread and friends
2111
2112 static inline int rrdcalc_value2status(calculated_number n) {
2113     if(isnan(n)) return RRDCALC_STATUS_UNDEFINED;
2114     if(n) return RRDCALC_STATUS_RAISED;
2115     return RRDCALC_STATUS_CLEAR;
2116 }
2117
2118 static inline void health_alarm_execute(RRDHOST *host, ALARM_ENTRY *ae) {
2119     ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_PROCESSED;
2120
2121     // find the previous notification for the same alarm
2122     ALARM_ENTRY *t;
2123     for(t = ae->next; t ;t = t->next) {
2124         if(t->alarm_id == ae->alarm_id && t->notifications & HEALTH_ENTRY_NOTIFICATIONS_EXEC_RUN)
2125             break;
2126     }
2127
2128     if(t && t->new_status == ae->new_status) {
2129         // don't send the same notification again
2130         info("Health not sending again notification for alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
2131         goto done;
2132     }
2133
2134     if((ae->old_status == RRDCALC_STATUS_UNDEFINED && ae->new_status == RRDCALC_STATUS_UNINITIALIZED)
2135         || (ae->old_status == RRDCALC_STATUS_UNINITIALIZED && ae->new_status == RRDCALC_STATUS_CLEAR)) {
2136         info("Health not sending notification for first initialization of alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
2137         goto done;
2138     }
2139
2140     char buffer[FILENAME_MAX + 1];
2141     pid_t command_pid;
2142
2143     const char *exec = ae->exec;
2144     if(!exec) exec = health.health_default_exec;
2145
2146     const char *recipient = ae->recipient;
2147     if(!recipient) recipient = health.health_default_recipient;
2148
2149     snprintfz(buffer, FILENAME_MAX, "exec %s '%s' '%s' '%u' '%u' '%u' '%lu' '%s' '%s' '%s' '%s' '%s' '%0.0Lf' '%0.0Lf' '%s' '%u' '%u' '%s' '%s'",
2150               exec,
2151               recipient,
2152               host->hostname,
2153               ae->unique_id,
2154               ae->alarm_id,
2155               ae->alarm_event_id,
2156               (unsigned long)ae->when,
2157               ae->name,
2158               ae->chart?ae->chart:"NOCAHRT",
2159               ae->family?ae->family:"NOFAMILY",
2160               rrdcalc_status2string(ae->new_status),
2161               rrdcalc_status2string(ae->old_status),
2162               ae->new_value,
2163               ae->old_value,
2164               ae->source?ae->source:"UNKNOWN",
2165               (uint32_t)ae->duration,
2166               (uint32_t)ae->non_clear_duration,
2167               ae->units?ae->units:"",
2168               ae->info?ae->info:""
2169     );
2170
2171     ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_EXEC_RUN;
2172     ae->exec_run_timestamp = time(NULL);
2173
2174     debug(D_HEALTH, "executing command '%s'", buffer);
2175     FILE *fp = mypopen(buffer, &command_pid);
2176     if(!fp) {
2177         error("HEALTH: Cannot popen(\"%s\", \"r\").", buffer);
2178         goto done;
2179     }
2180     debug(D_HEALTH, "HEALTH reading from command");
2181     char *s = fgets(buffer, FILENAME_MAX, fp);
2182     (void)s;
2183     ae->exec_code = mypclose(fp, command_pid);
2184     debug(D_HEALTH, "done executing command - returned with code %d", ae->exec_code);
2185
2186     if(ae->exec_code != 0)
2187         ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_EXEC_FAILED;
2188
2189 done:
2190     health_alarm_log_save(host, ae);
2191     return;
2192 }
2193
2194 static inline void health_process_notifications(RRDHOST *host, ALARM_ENTRY *ae) {
2195     info("Health alarm '%s.%s' = %0.2Lf - changed status from %s to %s",
2196          ae->chart?ae->chart:"NOCHART", ae->name,
2197          ae->new_value,
2198          rrdcalc_status2string(ae->old_status),
2199          rrdcalc_status2string(ae->new_status)
2200     );
2201
2202     health_alarm_execute(host, ae);
2203 }
2204
2205 static inline void health_alarm_log_process(RRDHOST *host) {
2206     static uint32_t stop_at_id = 0;
2207     uint32_t first_waiting = (host->health_log.alarms)?host->health_log.alarms->unique_id:0;
2208     time_t now = time(NULL);
2209
2210     pthread_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
2211
2212     ALARM_ENTRY *ae;
2213     for(ae = host->health_log.alarms; ae && ae->unique_id >= stop_at_id ; ae = ae->next) {
2214         if(unlikely(
2215             !(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_PROCESSED) &&
2216             !(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED)
2217             )) {
2218
2219             if(unlikely(ae->unique_id < first_waiting))
2220                 first_waiting = ae->unique_id;
2221
2222             if(likely(now >= ae->delay_up_to_timestamp))
2223                 health_process_notifications(host, ae);
2224         }
2225     }
2226
2227     // remember this for the next iteration
2228     stop_at_id = first_waiting;
2229
2230     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
2231
2232     if(host->health_log.count <= host->health_log.max)
2233         return;
2234
2235     // cleanup excess entries in the log
2236     pthread_rwlock_wrlock(&host->health_log.alarm_log_rwlock);
2237
2238     ALARM_ENTRY *last = NULL;
2239     unsigned int count = host->health_log.max * 2 / 3;
2240     for(ae = host->health_log.alarms; ae && count ; count--, last = ae, ae = ae->next) ;
2241
2242     if(ae && last && last->next == ae)
2243         last->next = NULL;
2244     else
2245         ae = NULL;
2246
2247     while(ae) {
2248         debug(D_HEALTH, "Health removing alarm log entry with id: %u", ae->unique_id);
2249
2250         ALARM_ENTRY *t = ae->next;
2251
2252         freez(ae->name);
2253         freez(ae->chart);
2254         freez(ae->family);
2255         freez(ae->exec);
2256         freez(ae->recipient);
2257         freez(ae->source);
2258         freez(ae->units);
2259         freez(ae->info);
2260         freez(ae);
2261
2262         ae = t;
2263         host->health_log.count--;
2264     }
2265
2266     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
2267 }
2268
2269 static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
2270     if (unlikely(!rc->rrdset)) {
2271         debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rc->chart?rc->chart:"NOCHART", rc->name);
2272         return 0;
2273     }
2274
2275     if (unlikely(!rc->rrdset->last_collected_time.tv_sec)) {
2276         debug(D_HEALTH, "Health not running alarm '%s.%s'. Chart is not yet collected.", rc->chart?rc->chart:"NOCHART", rc->name);
2277         return 0;
2278     }
2279
2280     if (unlikely(!rc->update_every)) {
2281         debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rc->chart?rc->chart:"NOCHART", rc->name);
2282         return 0;
2283     }
2284
2285     if (unlikely(rc->next_update > now)) {
2286         if (unlikely(*next_run > rc->next_update))
2287             *next_run = rc->next_update;
2288
2289         debug(D_HEALTH, "Health not examining alarm '%s.%s' yet (will do in %d secs).", rc->chart?rc->chart:"NOCHART", rc->name, (int) (rc->next_update - now));
2290         return 0;
2291     }
2292
2293     // FIXME
2294     // we should check that the DB lookup is possible
2295     // i.e.
2296     // - the duration of the chart includes the required timeframe
2297     // we SHOULD NOT check the dimensions - there might be alarms that refer non-existing dimensions (e.g. cpu steal)
2298
2299     return 1;
2300 }
2301
2302 void *health_main(void *ptr) {
2303     (void)ptr;
2304
2305     info("HEALTH thread created with task id %d", gettid());
2306
2307     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2308         error("Cannot set pthread cancel type to DEFERRED.");
2309
2310     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2311         error("Cannot set pthread cancel state to ENABLE.");
2312
2313     int min_run_every = (int)config_get_number("health", "run at least every seconds", 10);
2314     if(min_run_every < 1) min_run_every = 1;
2315
2316     BUFFER *wb = buffer_create(100);
2317
2318     unsigned int loop = 0;
2319     while(health_enabled && !netdata_exit) {
2320         loop++;
2321         debug(D_HEALTH, "Health monitoring iteration no %u started", loop);
2322
2323         int oldstate, runnable = 0;
2324         time_t now = time(NULL);
2325         time_t next_run = now + min_run_every;
2326         RRDCALC *rc;
2327
2328         if (unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
2329             error("Cannot set pthread cancel state to DISABLE.");
2330
2331         rrdhost_rdlock(&localhost);
2332
2333         // the first loop is to lookup values from the db
2334         for (rc = localhost.alarms; rc; rc = rc->next) {
2335             if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
2336                 continue;
2337
2338             runnable++;
2339             rc->old_value = rc->value;
2340
2341             // 1. if there is database lookup, do it
2342             // 2. if there is calculation expression, run it
2343
2344             if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
2345                 time_t old_db_timestamp = rc->db_before;
2346                 int value_is_null = 0;
2347
2348                 int ret = rrd2value(rc->rrdset, wb, &rc->value,
2349                                     rc->dimensions, 1, rc->after, rc->before, rc->group,
2350                                     rc->options, &rc->db_after, &rc->db_before, &value_is_null);
2351
2352                 if (unlikely(ret != 200)) {
2353                     // database lookup failed
2354                     rc->value = NAN;
2355
2356                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
2357
2358                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_DB_ERROR))) {
2359                         rc->rrdcalc_flags |= RRDCALC_FLAG_DB_ERROR;
2360                         error("Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
2361                     }
2362                 }
2363                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_ERROR))
2364                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_ERROR;
2365
2366                 if (unlikely(old_db_timestamp == rc->db_before)) {
2367                     // database is stale
2368
2369                     debug(D_HEALTH, "Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
2370
2371                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_DB_STALE))) {
2372                         rc->rrdcalc_flags |= RRDCALC_FLAG_DB_STALE;
2373                         error("Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
2374                     }
2375                 }
2376                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_STALE))
2377                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_STALE;
2378
2379                 if (unlikely(value_is_null)) {
2380                     // collected value is null
2381
2382                     rc->value = NAN;
2383
2384                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
2385                           rc->chart?rc->chart:"NOCHART", rc->name);
2386
2387                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_DB_NAN))) {
2388                         rc->rrdcalc_flags |= RRDCALC_FLAG_DB_NAN;
2389                         error("Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
2390                               rc->chart?rc->chart:"NOCHART", rc->name);
2391                     }
2392                 }
2393                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_NAN))
2394                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_NAN;
2395
2396                 debug(D_HEALTH, "Health alarm '%s.%s': database lookup gave value "
2397                         CALCULATED_NUMBER_FORMAT, rc->chart?rc->chart:"NOCHART", rc->name, rc->value);
2398             }
2399
2400             if(unlikely(rc->calculation)) {
2401                 if (unlikely(!expression_evaluate(rc->calculation))) {
2402                     // calculation failed
2403
2404                     rc->value = NAN;
2405
2406                     debug(D_HEALTH, "Health alarm '%s.%s': failed to evaluate calculation with error: %s",
2407                           rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
2408
2409                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_CALC_ERROR))) {
2410                         rc->rrdcalc_flags |= RRDCALC_FLAG_CALC_ERROR;
2411                         error("Health alarm '%s.%s': failed to evaluate calculation with error: %s",
2412                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
2413                     }
2414                 }
2415                 else {
2416                     if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_CALC_ERROR))
2417                         rc->rrdcalc_flags &= ~RRDCALC_FLAG_CALC_ERROR;
2418
2419                     debug(D_HEALTH, "Health alarm '%s.%s': calculation expression gave value "
2420                             CALCULATED_NUMBER_FORMAT
2421                             ": %s (source: %s)",
2422                           rc->chart?rc->chart:"NOCHART", rc->name,
2423                           rc->calculation->result,
2424                           buffer_tostring(rc->calculation->error_msg),
2425                           rc->source
2426                     );
2427
2428                     rc->value = rc->calculation->result;
2429                 }
2430             }
2431         }
2432         rrdhost_unlock(&localhost);
2433
2434         if (unlikely(runnable && !netdata_exit)) {
2435             rrdhost_rdlock(&localhost);
2436
2437             for (rc = localhost.alarms; rc; rc = rc->next) {
2438                 if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
2439                     continue;
2440
2441                 int warning_status  = RRDCALC_STATUS_UNDEFINED;
2442                 int critical_status = RRDCALC_STATUS_UNDEFINED;
2443
2444                 if(likely(rc->warning)) {
2445                     if(unlikely(!expression_evaluate(rc->warning))) {
2446                         // calculation failed
2447
2448                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression failed with error: %s",
2449                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
2450
2451                         if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_WARN_ERROR))) {
2452                             rc->rrdcalc_flags |= RRDCALC_FLAG_WARN_ERROR;
2453                             error("Health alarm '%s.%s': warning expression failed with error: %s",
2454                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
2455                         }
2456                     }
2457                     else {
2458                         if(unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_WARN_ERROR))
2459                             rc->rrdcalc_flags &= ~RRDCALC_FLAG_WARN_ERROR;
2460
2461                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression gave value "
2462                                 CALCULATED_NUMBER_FORMAT
2463                                 ": %s (source: %s)",
2464                               rc->chart?rc->chart:"NOCHART", rc->name,
2465                               rc->warning->result,
2466                               buffer_tostring(rc->warning->error_msg),
2467                               rc->source
2468                         );
2469
2470                         warning_status = rrdcalc_value2status(rc->warning->result);
2471                     }
2472                 }
2473
2474                 if(likely(rc->critical)) {
2475                     if(unlikely(!expression_evaluate(rc->critical))) {
2476                         // calculation failed
2477
2478                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression failed with error: %s",
2479                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
2480
2481                         if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_CRIT_ERROR))) {
2482                             rc->rrdcalc_flags |= RRDCALC_FLAG_CRIT_ERROR;
2483                             error("Health alarm '%s.%s': critical expression failed with error: %s",
2484                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
2485                         }
2486                     }
2487                     else {
2488                         if(unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_CRIT_ERROR))
2489                             rc->rrdcalc_flags &= ~RRDCALC_FLAG_CRIT_ERROR;
2490
2491                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression gave value "
2492                                 CALCULATED_NUMBER_FORMAT
2493                                 ": %s (source: %s)",
2494                               rc->chart?rc->chart:"NOCHART", rc->name,
2495                               rc->critical->result,
2496                               buffer_tostring(rc->critical->error_msg),
2497                               rc->source
2498                         );
2499
2500                         critical_status = rrdcalc_value2status(rc->critical->result);
2501                     }
2502                 }
2503
2504                 int status = RRDCALC_STATUS_UNDEFINED;
2505
2506                 switch(warning_status) {
2507                     case RRDCALC_STATUS_CLEAR:
2508                         status = RRDCALC_STATUS_CLEAR;
2509                         break;
2510
2511                     case RRDCALC_STATUS_RAISED:
2512                         status = RRDCALC_STATUS_WARNING;
2513                         break;
2514
2515                     default:
2516                         break;
2517                 }
2518
2519                 switch(critical_status) {
2520                     case RRDCALC_STATUS_CLEAR:
2521                         if(status == RRDCALC_STATUS_UNDEFINED)
2522                             status = RRDCALC_STATUS_CLEAR;
2523                         break;
2524
2525                     case RRDCALC_STATUS_RAISED:
2526                         status = RRDCALC_STATUS_CRITICAL;
2527                         break;
2528
2529                     default:
2530                         break;
2531                 }
2532
2533                 if(status != rc->status) {
2534                     int delay = 0;
2535
2536                     if(now > rc->delay_up_to_timestamp) {
2537                         rc->delay_up_current = rc->delay_up_duration;
2538                         rc->delay_down_current = rc->delay_down_duration;
2539                         rc->delay_last = 0;
2540                         rc->delay_up_to_timestamp = 0;
2541                     }
2542                     else {
2543                         rc->delay_up_current = (int)(rc->delay_up_current * rc->delay_multiplier);
2544                         if(rc->delay_up_current > rc->delay_max_duration) rc->delay_up_current = rc->delay_max_duration;
2545
2546                         rc->delay_down_current = (int)(rc->delay_down_current * rc->delay_multiplier);
2547                         if(rc->delay_down_current > rc->delay_max_duration) rc->delay_down_current = rc->delay_max_duration;
2548                     }
2549
2550                     if(status > rc->status)
2551                         delay = rc->delay_up_current;
2552                     else
2553                         delay = rc->delay_down_current;
2554
2555                     // COMMENTED: because we do need to send raising alarms
2556                     // if(now + delay < rc->delay_up_to_timestamp)
2557                     //    delay = (int)(rc->delay_up_to_timestamp - now);
2558
2559                     rc->delay_last = delay;
2560                     rc->delay_up_to_timestamp = now + delay;
2561                     health_alarm_log(&localhost, rc->id, rc->next_event_id++, now, rc->name, rc->rrdset->id, rc->rrdset->family, rc->exec, rc->recipient, now - rc->last_status_change, rc->old_value, rc->value, rc->status, status, rc->source, rc->units, rc->info, rc->delay_last);
2562                     rc->last_status_change = now;
2563                     rc->status = status;
2564                 }
2565
2566                 rc->last_updated = now;
2567                 rc->next_update = now + rc->update_every;
2568
2569                 if (next_run > rc->next_update)
2570                     next_run = rc->next_update;
2571             }
2572
2573             rrdhost_unlock(&localhost);
2574         }
2575
2576         if (unlikely(pthread_setcancelstate(oldstate, NULL) != 0))
2577             error("Cannot set pthread cancel state to RESTORE (%d).", oldstate);
2578
2579         if(unlikely(netdata_exit))
2580             break;
2581
2582         // execute notifications
2583         // and cleanup
2584         health_alarm_log_process(&localhost);
2585
2586         if(unlikely(netdata_exit))
2587             break;
2588         
2589         now = time(NULL);
2590         if(now < next_run) {
2591             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration in %d secs",
2592                   loop, (int) (next_run - now));
2593             sleep_usec(1000000 * (unsigned long long) (next_run - now));
2594         }
2595         else {
2596             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration now", loop);
2597         }
2598     }
2599
2600     buffer_free(wb);
2601
2602     info("HEALTH thread exiting");
2603     pthread_exit(NULL);
2604     return NULL;
2605 }