root/src/noit_check.c

Revision e7f28f1601f3a810d9d3ef616ec777be5b0d5d0d, 34.0 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 4 years ago)

fixes #289

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <assert.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42
43 #include "utils/noit_log.h"
44 #include "utils/noit_hash.h"
45 #include "utils/noit_skiplist.h"
46 #include "noit_conf.h"
47 #include "noit_check.h"
48 #include "noit_module.h"
49 #include "noit_console.h"
50 #include "noit_check_tools.h"
51 #include "eventer/eventer.h"
52
53 /* 60 seconds of possible stutter */
54 #define MAX_INITIAL_STUTTER 60000
55
56 static u_int64_t check_completion_count = 0;
57 static noit_hash_table polls = NOIT_HASH_EMPTY;
58 static noit_skiplist watchlist = { 0 };
59 static noit_skiplist polls_by_name = { 0 };
60 static u_int32_t __config_load_generation = 0;
61
62 u_int64_t noit_check_completion_count() {
63   return check_completion_count;
64 }
65 static void register_console_check_commands();
66 static int check_recycle_bin_processor(eventer_t, int, void *,
67                                        struct timeval *);
68
69 const char *
70 noit_check_available_string(int16_t available) {
71   switch(available) {
72     case NP_AVAILABLE:    return "available";
73     case NP_UNAVAILABLE:  return "unavailable";
74     case NP_UNKNOWN:      return "unknown";
75   }
76   return NULL;
77 }
78 const char *
79 noit_check_state_string(int16_t state) {
80   switch(state) {
81     case NP_GOOD:         return "good";
82     case NP_BAD:          return "bad";
83     case NP_UNKNOWN:      return "unknown";
84   }
85   return NULL;
86 }
87 static int __check_name_compare(const void *a, const void *b) {
88   const noit_check_t *ac = a;
89   const noit_check_t *bc = b;
90   int rv;
91   if((rv = strcmp(ac->target, bc->target)) != 0) return rv;
92   if((rv = strcmp(ac->name, bc->name)) != 0) return rv;
93   return 0;
94 }
95 static int __watchlist_compare(const void *a, const void *b) {
96   const noit_check_t *ac = a;
97   const noit_check_t *bc = b;
98   int rv;
99   if((rv = memcmp(ac->checkid, bc->checkid, sizeof(ac->checkid))) != 0) return rv;
100   if(ac->period < bc->period) return -1;
101   if(ac->period == bc->period) return 0;
102   return 1;
103 }
104 int
105 noit_check_max_initial_stutter() {
106   int stutter;
107   if(!noit_conf_get_int(NULL, "/noit/checks/@max_initial_stutter", &stutter))
108     stutter = MAX_INITIAL_STUTTER;
109   return stutter;
110 }
111 void
112 noit_check_fake_last_check(noit_check_t *check,
113                            struct timeval *lc, struct timeval *_now) {
114   struct timeval now, period;
115   double r;
116   int offset = 0, max;
117
118   if(!(check->flags & NP_TRANSIENT)) {
119     r = drand48();
120     max = noit_check_max_initial_stutter();
121     offset = r * (MIN(max, check->period));
122   }
123   period.tv_sec = (check->period - offset) / 1000;
124   period.tv_usec = ((check->period - offset) % 1000) * 1000;
125   if(!_now) {
126     gettimeofday(&now, NULL);
127     _now = &now;
128   }
129   sub_timeval(*_now, period, lc);
130 }
131 void
132 noit_poller_process_checks(const char *xpath) {
133   int i, flags, cnt = 0;
134   noit_conf_section_t *sec;
135   __config_load_generation++;
136   sec = noit_conf_get_sections(NULL, xpath, &cnt);
137   for(i=0; i<cnt; i++) {
138     void *vcheck;
139     char uuid_str[37];
140     char target[256] = "";
141     char module[256] = "";
142     char name[256] = "";
143     char filterset[256] = "";
144     char oncheck[1024] = "";
145     int no_period = 0;
146     int no_oncheck = 0;
147     int period = 0, timeout = 0;
148     noit_boolean disabled = noit_false, busted = noit_false;
149     uuid_t uuid, out_uuid;
150     noit_hash_table *options;
151
152 #define NEXT(...) noitL(noit_stderr, __VA_ARGS__); continue
153 #define MYATTR(type,a,...) noit_conf_get_##type(sec[i], "@" #a, __VA_ARGS__)
154 #define INHERIT(type,a,...) \
155   noit_conf_get_##type(sec[i], "ancestor-or-self::node()/@" #a, __VA_ARGS__)
156
157     if(!MYATTR(stringbuf, uuid, uuid_str, sizeof(uuid_str))) {
158       noitL(noit_stderr, "check %d has no uuid\n", i+1);
159       continue;
160     }
161
162     if(uuid_parse(uuid_str, uuid)) {
163       noitL(noit_stderr, "check uuid: '%s' is invalid\n", uuid_str);
164       continue;
165     }
166
167     if(!INHERIT(stringbuf, target, target, sizeof(target))) {
168       noitL(noit_stderr, "check uuid: '%s' has no target\n", uuid_str);
169       busted = noit_true;
170     }
171     if(!INHERIT(stringbuf, module, module, sizeof(module))) {
172       noitL(noit_stderr, "check uuid: '%s' has no module\n", uuid_str);
173       busted = noit_true;
174     }
175
176     if(!INHERIT(stringbuf, filterset, filterset, sizeof(filterset)))
177       filterset[0] = '\0';
178
179     if(!MYATTR(stringbuf, name, name, sizeof(name)))
180       strlcpy(name, module, sizeof(name));
181
182     if(!INHERIT(int, period, &period) || period == 0)
183       no_period = 1;
184
185     if(!INHERIT(stringbuf, oncheck, oncheck, sizeof(oncheck)) || !oncheck[0])
186       no_oncheck = 1;
187
188     if(no_period && no_oncheck) {
189       noitL(noit_stderr, "check uuid: '%s' has neither period nor oncheck\n",
190             uuid_str);
191       busted = noit_true;
192     }
193     if(!(no_period || no_oncheck)) {
194       noitL(noit_stderr, "check uuid: '%s' has oncheck and period.\n",
195             uuid_str);
196       busted = noit_true;
197     }
198     if(!INHERIT(int, timeout, &timeout)) {
199       noitL(noit_stderr, "check uuid: '%s' has no timeout\n", uuid_str);
200       busted = noit_true;
201     }
202     if(!no_period && timeout >= period) {
203       noitL(noit_stderr, "check uuid: '%s' timeout > period\n", uuid_str);
204       timeout = period/2;
205     }
206     options = noit_conf_get_hash(sec[i], "config");
207
208     INHERIT(boolean, disable, &disabled);
209     flags = 0;
210     if(busted) flags |= NP_UNCONFIG;
211     if(disabled) flags |= NP_DISABLED;
212
213     if(noit_hash_retrieve(&polls, (char *)uuid, UUID_SIZE,
214                           &vcheck)) {
215       noit_check_t *existing_check = (noit_check_t *)vcheck;
216       /* Once set, we can never change it. */
217       assert(!existing_check->module || !existing_check->module[0] ||
218              !strcmp(existing_check->module, module));
219       /* Only set it if it is not yet set */
220       if(!existing_check->module || !existing_check->module[0]) {
221         if(existing_check->module) free(existing_check->module);
222         existing_check->module = strdup(module);
223       }
224       noit_check_update(existing_check, target, name, filterset, options,
225                            period, timeout, oncheck[0] ? oncheck : NULL,
226                            flags);
227       noitL(noit_debug, "reloaded uuid: %s\n", uuid_str);
228     }
229     else {
230       noit_poller_schedule(target, module, name, filterset, options,
231                            period, timeout, oncheck[0] ? oncheck : NULL,
232                            flags, uuid, out_uuid);
233       noitL(noit_debug, "loaded uuid: %s\n", uuid_str);
234     }
235
236     noit_hash_destroy(options, free, free);
237     free(options);
238   }
239   if(sec) free(sec);
240 }
241
242 int
243 noit_check_activate(noit_check_t *check) {
244   noit_module_t *mod;
245   if(NOIT_CHECK_LIVE(check)) return 0;
246   mod = noit_module_lookup(check->module);
247   if(mod && mod->initiate_check) {
248     if((check->flags & NP_DISABLED) == 0) {
249       mod->initiate_check(mod, check, 0, NULL);
250       return 1;
251     }
252     else
253       noitL(noit_debug, "Skipping %s`%s, disabled.\n",
254             check->target, check->name);
255   }
256   else {
257     if(!mod) {
258       noitL(noit_stderr, "Cannot find module '%s'\n", check->module);
259       check->flags |= NP_DISABLED;
260     }
261   }
262   return 0;
263 }
264
265 void
266 noit_poller_initiate() {
267   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
268   uuid_t key_id;
269   int klen;
270   void *vcheck;
271   while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
272                        &vcheck)) {
273     noit_check_activate((noit_check_t *)vcheck);
274   }
275 }
276
277 void
278 noit_poller_flush_epoch(int oldest_allowed) {
279   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
280   uuid_t key_id;
281   int klen;
282   noit_check_t *tofree = NULL;
283   void *vcheck;
284
285   /* Cleanup any previous causal map */
286   while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
287                        &vcheck)) {
288     noit_check_t *check = (noit_check_t *)vcheck;
289     /* We don't free the one we're looking at... we free it on the next
290      * pass.  This leaves out iterator in good shape.  We just need to
291      * remember to free it one last time outside the while loop, down...
292      */
293     if(tofree) {
294       noit_poller_deschedule(tofree->checkid);
295       tofree = NULL;
296     }
297     if(check->generation < oldest_allowed) {
298       tofree = check;
299     }
300   }
301   /* ... here */
302   if(tofree) noit_poller_deschedule(tofree->checkid);
303 }
304
305 void
306 noit_poller_make_causal_map() {
307   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
308   uuid_t key_id;
309   int klen;
310   void *vcheck;
311
312   /* Cleanup any previous causal map */
313   while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
314                        &vcheck)) {
315     noit_check_t *check = (noit_check_t *)vcheck;
316     dep_list_t *dep;
317     while((dep = check->causal_checks) != NULL) {
318       check->causal_checks = dep->next;
319       free(dep);
320     }
321   }
322
323   memset(&iter, 0, sizeof(iter));
324   /* Walk all checks and add check dependencies to their parents */
325   while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
326                        &vcheck)) {
327     noit_check_t *check = (noit_check_t *)vcheck, *parent;
328     if(check->oncheck) {
329       /* This service is causally triggered by another service */
330       char fullcheck[1024];
331       char *name = check->oncheck;
332       char *target = NULL;
333
334       noitL(noit_debug, "Searching for upstream trigger on %s\n", name);
335       if((target = strchr(check->oncheck, '`')) != NULL) {
336         strlcpy(fullcheck, check->oncheck, target - check->oncheck);
337         name = target + 1;
338         target = fullcheck;
339       }
340       else
341        target = check->target;
342
343       parent = noit_poller_lookup_by_name(target, name);
344       if(!parent) {
345         check->flags |= NP_DISABLED;
346         noitL(noit_stderr, "Disabling check %s`%s, can't find oncheck %s`%s\n",
347               check->target, check->name, target, name);
348       }
349       else {
350         dep_list_t *dep;
351         dep = malloc(sizeof(*dep));
352         dep->check = check;
353         dep->next = parent->causal_checks;
354         parent->causal_checks = dep;
355         noitL(noit_debug, "Causal map %s`%s --> %s`%s\n",
356               parent->target, parent->name, check->target, check->name);
357       }
358     }
359   }
360 }
361 void
362 noit_poller_reload(const char *xpath)
363 {
364   noit_poller_process_checks(xpath ? xpath : "/noit/checks//check");
365   if(!xpath) {
366     /* Full reload, we need to wipe old checks */
367     noit_poller_flush_epoch(__config_load_generation);
368   }
369   noit_poller_make_causal_map();
370   noit_poller_initiate();
371 }
372 void
373 noit_poller_init() {
374   noit_check_tools_init();
375   noit_skiplist_init(&polls_by_name);
376   noit_skiplist_set_compare(&polls_by_name, __check_name_compare,
377                             __check_name_compare);
378   noit_skiplist_init(&watchlist);
379   noit_skiplist_set_compare(&watchlist, __watchlist_compare,
380                             __watchlist_compare);
381   register_console_check_commands();
382   eventer_name_callback("check_recycle_bin_processor",
383                         check_recycle_bin_processor);
384   eventer_add_in_s_us(check_recycle_bin_processor, NULL, 60, 0);
385   noit_poller_reload(NULL);
386 }
387
388 int
389 noit_poller_check_count() {
390   return polls_by_name.size;
391 }
392
393 int
394 noit_poller_transient_check_count() {
395   return watchlist.size;
396 }
397
398 noit_check_t *
399 noit_check_clone(uuid_t in) {
400   noit_check_t *checker, *new_check;
401   void *vcheck;
402   if(noit_hash_retrieve(&polls,
403                         (char *)in, UUID_SIZE,
404                         &vcheck) == 0) {
405     return NULL;
406   }
407   checker = (noit_check_t *)vcheck;
408   if(checker->oncheck) {
409     return NULL;
410   }
411   new_check = calloc(1, sizeof(*new_check));
412   memcpy(new_check, checker, sizeof(*new_check));
413   new_check->target = strdup(new_check->target);
414   new_check->module = strdup(new_check->module);
415   new_check->name = strdup(new_check->name);
416   new_check->filterset = strdup(new_check->filterset);
417   new_check->flags = 0;
418   new_check->fire_event = NULL;
419   memset(&new_check->last_fire_time, 0, sizeof(new_check->last_fire_time));
420   memset(&new_check->stats, 0, sizeof(new_check->stats));
421   new_check->closure = NULL;
422   new_check->config = calloc(1, sizeof(*new_check->config));
423   noit_hash_merge_as_dict(new_check->config, checker->config);
424   return new_check;
425 }
426
427 noit_check_t *
428 noit_check_watch(uuid_t in, int period) {
429   /* First look for a copy that is being watched */
430   int minimum_pi = 1000, granularity_pi = 500;
431   noit_conf_section_t check_node;
432   char uuid_str[UUID_STR_LEN + 1];
433   char xpath[1024];
434   noit_check_t n, *f;
435
436   uuid_unparse_lower(in, uuid_str);
437   /* Find the check */
438   snprintf(xpath, sizeof(xpath), "//checks//check[@uuid=\"%s\"]", uuid_str);
439   check_node = noit_conf_get_section(NULL, xpath);
440   noit_conf_get_int(NULL, "//checks/@transient_min_period", &minimum_pi);
441   noit_conf_get_int(NULL, "//checks/@transient_period_granularity", &granularity_pi);
442   if(check_node) {
443     noit_conf_get_int(check_node,
444                       "ancestor-or-self::node()/@transient_min_period",
445                       &minimum_pi);
446     noit_conf_get_int(check_node,
447                       "ancestor-or-self::node()/@transient_period_granularity",
448                       &granularity_pi);
449   }
450
451   /* apply the bounds */
452   period /= granularity_pi;
453   period *= granularity_pi;
454   period = MAX(period, minimum_pi);
455
456   uuid_copy(n.checkid, in);
457   n.period = period;
458
459   f = noit_skiplist_find(&watchlist, &n, NULL);
460   if(f) return f;
461   f = noit_check_clone(in);
462   if(!f) return NULL;
463   f->period = period;
464   f->timeout = period - 10;
465   f->flags |= NP_TRANSIENT;
466   noitL(noit_debug, "Watching %s@%d\n", uuid_str, period);
467   noit_skiplist_insert(&watchlist, f);
468   return f;
469 }
470
471 noit_check_t *
472 noit_check_get_watch(uuid_t in, int period) {
473   noit_check_t n, *f;
474
475   uuid_copy(n.checkid, in);
476   n.period = period;
477
478   f = noit_skiplist_find(&watchlist, &n, NULL);
479   return f;
480 }
481
482 void
483 noit_check_transient_add_feed(noit_check_t *check, const char *feed) {
484   char *feedcopy;
485   if(!check->feeds) {
486     check->feeds = calloc(1, sizeof(*check->feeds));
487     noit_skiplist_init(check->feeds);
488     noit_skiplist_set_compare(check->feeds,
489                               (noit_skiplist_comparator_t)strcmp,
490                               (noit_skiplist_comparator_t)strcmp);
491   }
492   feedcopy = strdup(feed);
493   /* No error on failure -- it's already there */
494   if(noit_skiplist_insert(check->feeds, feedcopy) == NULL) free(feedcopy);
495   noitL(noit_debug, "check %s`%s @ %dms has %d feed(s): %s.\n",
496         check->target, check->name, check->period, check->feeds->size, feed);
497 }
498 void
499 noit_check_transient_remove_feed(noit_check_t *check, const char *feed) {
500   if(!check->feeds) return;
501   if(feed) {
502     noitL(noit_debug, "check %s`%s @ %dms removing 1 of %d feeds: %s.\n",
503           check->target, check->name, check->period, check->feeds->size, feed);
504     noit_skiplist_remove(check->feeds, feed, free);
505   }
506   if(check->feeds->size == 0) {
507     char uuid_str[UUID_STR_LEN + 1];
508     uuid_unparse_lower(check->checkid, uuid_str);
509     noitL(noit_debug, "Unwatching %s@%d\n", uuid_str, check->period);
510     noit_skiplist_remove(&watchlist, check, NULL);
511     noit_skiplist_destroy(check->feeds, free);
512     free(check->feeds);
513     check->feeds = NULL;
514     if(check->flags & NP_TRANSIENT) {
515       noitL(noit_debug, "check %s`%s @ %dms has no more listeners.\n",
516             check->target, check->name, check->period);
517       check->flags |= NP_KILLED;
518     }
519   }
520 }
521
522 noit_boolean
523 noit_check_is_valid_target(const char *target) {
524   int8_t family;
525   int rv;
526   union {
527     struct in_addr addr4;
528     struct in6_addr addr6;
529   } a;
530
531   family = AF_INET;
532   rv = inet_pton(family, target, &a);
533   if(rv != 1) {
534     family = AF_INET6;
535     rv = inet_pton(family, target, &a);
536     if(rv != 1) {
537       return noit_false;
538     }
539   }
540   return noit_true;
541 }
542 int
543 noit_check_update(noit_check_t *new_check,
544                   const char *target,
545                   const char *name,
546                   const char *filterset,
547                   noit_hash_table *config,
548                   u_int32_t period,
549                   u_int32_t timeout,
550                   const char *oncheck,
551                   int flags) {
552   int8_t family;
553   int rv;
554   int mask = NP_DISABLED | NP_UNCONFIG;
555   union {
556     struct in_addr addr4;
557     struct in6_addr addr6;
558   } a;
559
560
561   family = AF_INET;
562   rv = inet_pton(family, target, &a);
563   if(rv != 1) {
564     family = AF_INET6;
565     rv = inet_pton(family, target, &a);
566     if(rv != 1) {
567       noitL(noit_stderr, "Cannot translate '%s' to IP\n", target);
568       memset(&a, 0, sizeof(a));
569       flags |= (NP_UNCONFIG | NP_DISABLED);
570     }
571   }
572
573   new_check->generation = __config_load_generation;
574   new_check->target_family = family;
575   memcpy(&new_check->target_addr, &a, sizeof(a));
576   if(new_check->target) free(new_check->target);
577   new_check->target = strdup(target);
578   if(new_check->name) free(new_check->name);
579   new_check->name = name ? strdup(name): NULL;
580   if(new_check->filterset) free(new_check->filterset);
581   new_check->filterset = filterset ? strdup(filterset): NULL;
582
583   if(config != NULL) {
584     noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
585     const char *k;
586     int klen;
587     void *data;
588     if(new_check->config) noit_hash_delete_all(new_check->config, free, free);
589     else new_check->config = calloc(1, sizeof(*new_check->config));
590     while(noit_hash_next(config, &iter, &k, &klen, &data)) {
591       noit_hash_store(new_check->config, strdup(k), klen, strdup((char *)data));
592     }
593   }
594   if(new_check->oncheck) free(new_check->oncheck);
595   new_check->oncheck = oncheck ? strdup(oncheck) : NULL;
596   new_check->period = period;
597   new_check->timeout = timeout;
598
599   /* Unset what could be set.. then set what should be set */
600   new_check->flags = (new_check->flags & ~mask) | flags;
601
602   if(!(new_check->flags & NP_TRANSIENT)) {
603     /* This remove could fail -- no big deal */
604     noit_skiplist_remove(&polls_by_name, new_check, NULL);
605
606     /* This insert could fail.. which means we have a conflict on
607      * target`name.  That should result in the check being disabled. */
608     if(!noit_skiplist_insert(&polls_by_name, new_check)) {
609       noitL(noit_stderr, "Check %s`%s disabled due to naming conflict\n",
610             new_check->target, new_check->name);
611       new_check->flags |= NP_DISABLED;
612     }
613   }
614   noit_check_log_check(new_check);
615   return 0;
616 }
617 int
618 noit_poller_schedule(const char *target,
619                      const char *module,
620                      const char *name,
621                      const char *filterset,
622                      noit_hash_table *config,
623                      u_int32_t period,
624                      u_int32_t timeout,
625                      const char *oncheck,
626                      int flags,
627                      uuid_t in,
628                      uuid_t out) {
629   noit_check_t *new_check;
630   new_check = calloc(1, sizeof(*new_check));
631   if(!new_check) return -1;
632
633   /* The module and the UUID can never be changed */
634   new_check->module = strdup(module);
635   if(uuid_is_null(in))
636     uuid_generate(new_check->checkid);
637   else
638     uuid_copy(new_check->checkid, in);
639
640   noit_check_update(new_check, target, name, filterset, config,
641                     period, timeout, oncheck, flags);
642   assert(noit_hash_store(&polls,
643                          (char *)new_check->checkid, UUID_SIZE,
644                          new_check));
645   uuid_copy(out, new_check->checkid);
646
647   return 0;
648 }
649
650 /* A quick little list of recycleable checks.  This list never really
651  * grows large, so no sense in thinking too hard about the algorithmic
652  * complexity.
653  */
654 struct _checker_rcb {
655   noit_check_t *checker;
656   struct _checker_rcb *next;
657 };
658 static struct _checker_rcb *checker_rcb = NULL;
659 static void recycle_check(noit_check_t *checker) {
660   struct _checker_rcb *n = malloc(sizeof(*n));
661   n->checker = checker;
662   n->next = checker_rcb;
663   checker_rcb = n;
664 }
665 void
666 noit_poller_free_check(noit_check_t *checker) {
667   noit_module_t *mod;
668
669   if(checker->flags & NP_RUNNING) {
670     recycle_check(checker);
671     return;
672   }
673
674   mod = noit_module_lookup(checker->module);
675   if(mod->cleanup) mod->cleanup(mod, checker);
676   if(checker->fire_event) {
677      eventer_remove(checker->fire_event);
678      free(checker->fire_event->closure);
679      eventer_free(checker->fire_event);
680      checker->fire_event = NULL;
681   }
682   if(checker->closure) free(checker->closure);
683   if(checker->target) free(checker->target);
684   if(checker->module) free(checker->module);
685   if(checker->name) free(checker->name);
686   if(checker->config) {
687     noit_hash_destroy(checker->config, free, free);
688     free(checker->config);
689     checker->config = NULL;
690   }
691   free(checker);
692 }
693 static int
694 check_recycle_bin_processor(eventer_t e, int mask, void *closure,
695                             struct timeval *now) {
696   static struct timeval one_minute = { 60L, 0L };
697   struct _checker_rcb *prev = NULL, *curr = checker_rcb;
698   noitL(noit_debug, "Scanning check recycle bin\n");
699   while(curr) {
700     if(!(curr->checker->flags & NP_RUNNING)) {
701       noitL(noit_debug, "Check is ready to free.\n");
702       noit_poller_free_check(curr->checker);
703       if(prev) prev->next = curr->next;
704       else checker_rcb = curr->next;
705       free(curr);
706       curr = prev ? prev->next : checker_rcb;
707     }
708     else {
709       prev = curr;
710       curr = curr->next;
711     }
712   }
713   add_timeval(*now, one_minute, &e->whence);
714   return EVENTER_TIMER;
715 }
716
717 int
718 noit_poller_deschedule(uuid_t in) {
719   void *vcheck;
720   noit_check_t *checker;
721   if(noit_hash_retrieve(&polls,
722                         (char *)in, UUID_SIZE,
723                         &vcheck) == 0) {
724     return -1;
725   }
726   checker = (noit_check_t *)vcheck;
727   checker->flags |= (NP_DISABLED|NP_KILLED);
728
729   noit_skiplist_remove(&polls_by_name, checker, NULL);
730   noit_hash_delete(&polls, (char *)in, UUID_SIZE, NULL, NULL);
731
732   noit_poller_free_check(checker);
733   return 0;
734 }
735
736 noit_check_t *
737 noit_poller_lookup(uuid_t in) {
738   void *vcheck;
739   if(noit_hash_retrieve(&polls, (char *)in, UUID_SIZE, &vcheck))
740     return (noit_check_t *)vcheck;
741   return NULL;
742 }
743 noit_check_t *
744 noit_poller_lookup_by_name(char *target, char *name) {
745   noit_check_t *check, *tmp_check;
746   tmp_check = calloc(1, sizeof(*tmp_check));
747   tmp_check->target = target;
748   tmp_check->name = name;
749   check = noit_skiplist_find(&polls_by_name, tmp_check, NULL);
750   free(tmp_check);
751   return check;
752 }
753
754 void
755 noit_check_stats_clear(stats_t *s) {
756   memset(s, 0, sizeof(*s));
757   s->state = NP_UNKNOWN;
758   s->available = NP_UNKNOWN;
759 }
760 static void
761 __free_metric(void *vm) {
762   metric_t *m = vm;
763   free(m->metric_name);
764   if(m->metric_value.i) free(m->metric_value.i);
765   free(m);
766 }
767
768 void
769 __stats_add_metric(stats_t *newstate, metric_t *m) {
770   noit_hash_replace(&newstate->metrics, m->metric_name, strlen(m->metric_name),
771                     m, NULL, __free_metric);
772 }
773
774 static size_t
775 noit_metric_sizes(metric_type_t type, void *value) {
776   switch(type) {
777     case METRIC_INT32:
778     case METRIC_UINT32:
779       return sizeof(int32_t);
780     case METRIC_INT64:
781     case METRIC_UINT64:
782       return sizeof(int64_t);
783     case METRIC_DOUBLE:
784       return sizeof(double);
785     case METRIC_STRING:
786       return strlen((char *)value) + 1;
787     case METRIC_GUESS:
788       break;
789   }
790   assert(type != type);
791   return 0;
792 }
793 static metric_type_t
794 noit_metric_guess_type(const char *s, void **replacement) {
795   char *copy, *cp, *trailer, *rpl;
796   int negative = 0;
797   metric_type_t type = METRIC_STRING;
798
799   if(!s) return METRIC_GUESS;
800   copy = cp = strdup(s);
801
802   /* TRIM the string */
803   while(*cp && isspace(*cp)) cp++; /* ltrim */
804   s = cp; /* found a good starting point */
805   while(*cp) cp++; /* advance to \0 */
806   cp--; /* back up one */
807   while(cp > s && isspace(*cp)) *cp-- = '\0'; /* rtrim */
808
809   /* Find the first space */
810   cp = (char *)s;
811   while(*cp && !isspace(*cp)) cp++;
812   trailer = cp;
813   cp--; /* backup one */
814   if(cp > s && *cp == '%') *cp-- = '\0'; /* chop a last % is there is one */
815
816   while(*trailer && isspace(*trailer)) *trailer++ = '\0'; /* rtrim */
817
818   /* string was       '  -1.23e-01%  inodes used  ' */
819   /* copy is (~ = \0) '  -1.23e-01~  inodes used~~' */
820   /*                     ^           ^              */
821   /*                     s           trailer        */
822
823   /* So, the trailer must not contain numbers */
824   while(*trailer) { if(isdigit(*trailer)) goto notanumber; trailer++; }
825
826   /* And the 's' must be of the form:
827    *  0) may start with a sign [-+]?
828    *  1) [1-9][0-9]*
829    *  2) [0]?.[0-9]+
830    *  3) 0
831    *  4) [1-9][0-9]*.[0-9]+
832    *  5) all of the above ending with e[+-][0-9]+
833    */
834    rpl = (char *)s;
835    /* CASE 0 */
836    if(s[0] == '-' || s[0] == '+') {
837      if(s[0] == '-') negative = 1;
838      s++;
839    }
840
841    if(s[0] == '.') goto decimal; /* CASE 2 */
842    if(s[0] == '0') { /* CASE 2 & 3 */
843      s++;
844      if(!s[0]) goto scanint; /* CASE 3 */
845      if(s[0] == '.') goto decimal; /* CASE 2 */
846      goto notanumber;
847    }
848    if(s[0] >= '1' && s[0] <= '9') { /* CASE 1 & 4 */
849      s++;
850      while(isdigit(s[0])) s++; /* CASE 1 & 4 */
851      if(!s[0]) goto scanint; /* CASE 1 */
852      if(s[0] == '.') goto decimal; /* CASE 4 */
853      goto notanumber;
854    }
855    /* Not case 1,2,3,4 */
856    goto notanumber;
857
858   decimal:
859    s++;
860    if(!isdigit(s[0])) goto notanumber;
861    s++;
862    while(isdigit(s[0])) s++;
863    if(!s[0]) goto scandouble;
864    if(s[0] == 'e' || s[0] == 'E') goto exponent; /* CASE 5 */
865    goto notanumber;
866
867   exponent:
868    s++;
869    if(s[0] != '-' && s[0] != '+') goto notanumber;
870    s++;
871    if(!isdigit(s[0])) goto notanumber;
872    s++;
873    while(isdigit(s[0])) s++;
874    if(!s[0]) goto scandouble;
875    goto notanumber;
876
877  scanint:
878    if(negative) {
879      int64_t *v;
880      v = calloc(1, sizeof(*v));
881      *v = strtoll(rpl, NULL, 10);
882      *replacement = v;
883      type = METRIC_INT64;
884      goto alldone;
885    }
886    else {
887      u_int64_t *v;
888      v = calloc(1, sizeof(*v));
889      *v = strtoull(rpl, NULL, 10);
890      *replacement = v;
891      type = METRIC_UINT64;
892      goto alldone;
893    }
894  scandouble:
895    {
896      double *v;
897      v = calloc(1, sizeof(*v));
898      *v = strtod(rpl, NULL);
899      *replacement = v;
900      type = METRIC_DOUBLE;
901      goto alldone;
902    }
903
904  alldone:
905  notanumber:
906   free(copy);
907   return type;
908 }
909 void
910 noit_stats_set_metric(stats_t *newstate, const char *name, metric_type_t type,
911                       void *value) {
912   metric_t *m;
913   void *replacement = NULL;
914   if(type == METRIC_GUESS)
915     type = noit_metric_guess_type((char *)value, &replacement);
916   if(type == METRIC_GUESS) return;
917
918   m = calloc(1, sizeof(*m));
919   m->metric_name = strdup(name);
920   m->metric_type = type;
921   if(replacement)
922     m->metric_value.vp = replacement;
923   else if(value) {
924     size_t len;
925     len = noit_metric_sizes(type, value);
926     m->metric_value.vp = calloc(1, len);
927     memcpy(m->metric_value.vp, value, len);
928   }
929   __stats_add_metric(newstate, m);
930 }
931
932 void
933 noit_check_set_stats(struct _noit_module *module,
934                      noit_check_t *check, stats_t *newstate) {
935   int report_change = 0;
936   dep_list_t *dep;
937   if(check->stats.previous.status)
938     free(check->stats.previous.status);
939   noit_hash_destroy(&check->stats.previous.metrics, NULL, __free_metric);
940   memcpy(&check->stats.previous, &check->stats.current, sizeof(stats_t));
941   memcpy(&check->stats.current, newstate, sizeof(stats_t));
942   if(check->stats.current.status)
943     check->stats.current.status = strdup(check->stats.current.status);
944
945   /* check for state changes */
946   if(check->stats.current.available != NP_UNKNOWN &&
947      check->stats.previous.available != NP_UNKNOWN &&
948      check->stats.current.available != check->stats.previous.available)
949     report_change = 1;
950   if(check->stats.current.state != NP_UNKNOWN &&
951      check->stats.previous.state != NP_UNKNOWN &&
952      check->stats.current.state != check->stats.previous.state)
953     report_change = 1;
954
955   noitL(noit_debug, "%s`%s <- [%s]\n", check->target, check->name,
956         check->stats.current.status);
957   if(report_change) {
958     noitL(noit_debug, "%s`%s -> [%s:%s]\n",
959           check->target, check->name,
960           noit_check_available_string(check->stats.current.available),
961           noit_check_state_string(check->stats.current.state));
962   }
963
964   /* Write out our status */
965   noit_check_log_status(check);
966   /* Write out all metrics */
967   noit_check_log_metrics(check);
968   /* count the check as complete */
969   check_completion_count++;
970
971   for(dep = check->causal_checks; dep; dep = dep->next) {
972     noit_module_t *mod;
973     mod = noit_module_lookup(dep->check->module);
974     assert(mod);
975     noitL(noit_debug, "Firing %s`%s in response to %s`%s\n",
976           dep->check->target, dep->check->name,
977           check->target, check->name);
978     if((dep->check->flags & NP_DISABLED) == 0)
979       if(mod->initiate_check)
980         mod->initiate_check(mod, dep->check, 1, check);
981   }
982 }
983
984 static int
985 noit_console_show_watchlist(noit_console_closure_t ncct,
986                             int argc, char **argv,
987                             noit_console_state_t *dstate,
988                             void *closure) {
989   noit_skiplist_node *iter, *fiter;
990   nc_printf(ncct, "%d active watches.\n", watchlist.size);
991   for(iter = noit_skiplist_getlist(&watchlist); iter;
992       noit_skiplist_next(&watchlist, &iter)) {
993     char uuid_str[UUID_STR_LEN + 1];
994     noit_check_t *check = iter->data;
995
996     uuid_unparse_lower(check->checkid, uuid_str);
997     nc_printf(ncct, "%s:\n\t[%s`%s`%s]\n\tPeriod: %dms\n\tFeeds[%d]:\n",
998               uuid_str, check->target, check->module, check->name,
999               check->period, check->feeds ? check->feeds->size : 0);
1000     if(check->feeds && check->feeds->size) {
1001       for(fiter = noit_skiplist_getlist(check->feeds); fiter;
1002           noit_skiplist_next(check->feeds, &fiter)) {
1003         nc_printf(ncct, "\t\t%s\n", (const char *)fiter->data);
1004       }
1005     }
1006   }
1007   return 0;
1008 }
1009
1010 static void
1011 nc_printf_check_brief(noit_console_closure_t ncct,
1012                       noit_check_t *check) {
1013   char out[512];
1014   char uuid_str[37];
1015   snprintf(out, sizeof(out), "%s`%s", check->target, check->name);
1016   uuid_unparse_lower(check->checkid, uuid_str);
1017   nc_printf(ncct, "%s %s\n", uuid_str, out);
1018   if(check->stats.current.status)
1019     nc_printf(ncct, "\t%s\n", check->stats.current.status);
1020 }
1021
1022 char *
1023 noit_console_conf_check_opts(noit_console_closure_t ncct,
1024                              noit_console_state_stack_t *stack,
1025                              noit_console_state_t *dstate,
1026                              int argc, char **argv, int idx) {
1027   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
1028   uuid_t key_id;
1029   int klen, i = 0;
1030   void *vcheck;
1031
1032   if(argc == 1) {
1033     if(!strncmp("new", argv[0], strlen(argv[0]))) {
1034       if(idx == i) return strdup("new");
1035       i++;
1036     }
1037     while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
1038                          &vcheck)) {
1039       noit_check_t *check = (noit_check_t *)vcheck;
1040       char out[512];
1041       char uuid_str[37];
1042       snprintf(out, sizeof(out), "%s`%s", check->target, check->name);
1043       uuid_unparse_lower(check->checkid, uuid_str);
1044       if(!strncmp(out, argv[0], strlen(argv[0]))) {
1045         if(idx == i) return strdup(out);
1046         i++;
1047       }
1048       if(!strncmp(uuid_str, argv[0], strlen(argv[0]))) {
1049         if(idx == i) return strdup(uuid_str);
1050         i++;
1051       }
1052     }
1053   }
1054   if(argc == 2) {
1055     cmd_info_t *cmd;
1056     if(!strcmp("new", argv[0])) return NULL;
1057     cmd = noit_skiplist_find(&dstate->cmds, "attribute", NULL);
1058     if(!cmd) return NULL;
1059     return noit_console_opt_delegate(ncct, stack, cmd->dstate, argc-1, argv+1, idx);
1060   }
1061   return NULL;
1062 }
1063
1064 char *
1065 noit_console_check_opts(noit_console_closure_t ncct,
1066                         noit_console_state_stack_t *stack,
1067                         noit_console_state_t *dstate,
1068                         int argc, char **argv, int idx) {
1069   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
1070   uuid_t key_id;
1071   int klen, i = 0;
1072
1073   if(argc == 1) {
1074     void *vcheck;
1075     while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
1076                          &vcheck)) {
1077       char out[512];
1078       char uuid_str[37];
1079       noit_check_t *check = (noit_check_t *)vcheck;
1080       snprintf(out, sizeof(out), "%s`%s", check->target, check->name);
1081       uuid_unparse_lower(check->checkid, uuid_str);
1082       if(!strncmp(out, argv[0], strlen(argv[0]))) {
1083         if(idx == i) return strdup(out);
1084         i++;
1085       }
1086       if(!strncmp(uuid_str, argv[0], strlen(argv[0]))) {
1087         if(idx == i) return strdup(uuid_str);
1088         i++;
1089       }
1090     }
1091   }
1092   if(argc == 2) {
1093     return noit_console_opt_delegate(ncct, stack, dstate, argc-1, argv+1, idx);
1094   }
1095   return NULL;
1096 }
1097
1098 static int
1099 noit_console_show_checks(noit_console_closure_t ncct,
1100                          int argc, char **argv,
1101                          noit_console_state_t *dstate,
1102                          void *closure) {
1103   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
1104   uuid_t key_id;
1105   int klen;
1106   void *vcheck;
1107
1108   while(noit_hash_next(&polls, &iter, (const char **)key_id, &klen,
1109                        &vcheck)) {
1110     nc_printf_check_brief(ncct, (noit_check_t *)vcheck);
1111   }
1112   return 0;
1113 }
1114
1115 static void
1116 register_console_check_commands() {
1117   noit_console_state_t *tl;
1118   cmd_info_t *showcmd;
1119
1120   tl = noit_console_state_initial();
1121   showcmd = noit_console_state_get_cmd(tl, "show");
1122   assert(showcmd && showcmd->dstate);
1123
1124   noit_console_state_add_cmd(showcmd->dstate,
1125     NCSCMD("checks", noit_console_show_checks, NULL, NULL, NULL));
1126
1127   noit_console_state_add_cmd(showcmd->dstate,
1128     NCSCMD("watches", noit_console_show_watchlist, NULL, NULL, NULL));
1129 }
1130
Note: See TracBrowser for help on using the browser.