forked from collectd/collectd
-
Notifications
You must be signed in to change notification settings - Fork 8
/
plugin.c
2530 lines (2039 loc) · 68.4 KB
/
plugin.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* collectd - src/daemon/plugin.c
* Copyright (C) 2005-2014 Florian octo Forster
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Florian octo Forster <octo at collectd.org>
* Sebastian Harl <sh at tokkee.org>
* Manoj Srivastava <srivasta at google.com>
**/
/* _GNU_SOURCE is needed in Linux to use pthread_setname_np */
#define _GNU_SOURCE
#include "collectd.h"
#include "configfile.h"
#include "daemon/data_set.h"
#include "filter_chain.h"
#include "plugin.h"
#include "resource.h"
#include "unit.h"
#include "utils/avltree/avltree.h"
#include "utils/common/common.h"
#include "utils/heap/heap.h"
#include "utils_cache.h"
#include "utils_complain.h"
#include "utils_llist.h"
#include "utils_random.h"
#include "utils_time.h"
#ifdef WIN32
#define EXPORT __declspec(dllexport)
#include <sys/stat.h>
#include <unistd.h>
#else
#define EXPORT
#endif
#if HAVE_PTHREAD_NP_H
#include <pthread_np.h> /* for pthread_set_name_np(3) */
#endif
#include <dlfcn.h>
/* except for plugin_log_cb, all callback types return an int */
typedef int (*placeholder_cb_t)(void);
/*
* Private structures
*/
struct callback_func_s {
placeholder_cb_t cf_callback;
user_data_t cf_udata;
plugin_ctx_t cf_ctx;
};
typedef struct callback_func_s callback_func_t;
#define RF_SIMPLE 0
#define RF_COMPLEX 1
#define RF_REMOVE 65535
struct read_func_s {
/* `read_func_t' "inherits" from `callback_func_t'.
* The `rf_super' member MUST be the first one in this structure! */
#define rf_callback rf_super.cf_callback
#define rf_udata rf_super.cf_udata
#define rf_ctx rf_super.cf_ctx
callback_func_t rf_super;
char rf_group[DATA_MAX_NAME_LEN];
char *rf_name;
int rf_type;
cdtime_t rf_interval;
cdtime_t rf_effective_interval;
cdtime_t rf_next_read;
};
typedef struct read_func_s read_func_t;
struct cache_event_func_s {
plugin_cache_event_cb callback;
char *name;
user_data_t user_data;
plugin_ctx_t plugin_ctx;
};
typedef struct cache_event_func_s cache_event_func_t;
typedef struct write_queue_elem_s {
metric_family_t *family;
plugin_ctx_t ctx;
const char *plugin;
long ref_count;
struct write_queue_elem_s *next;
} write_queue_elem_t;
typedef struct write_queue_thread_s {
bool loop;
long queue_length;
char *name;
plugin_write_cb callback;
user_data_t ud;
pthread_t thread;
write_queue_elem_t *head;
struct write_queue_thread_s *next;
} write_queue_thread_t;
struct {
pthread_mutex_t lock;
pthread_cond_t cond;
write_queue_elem_t *tail;
write_queue_thread_t *threads;
} write_queue = {
.lock = PTHREAD_MUTEX_INITIALIZER,
.cond = PTHREAD_COND_INITIALIZER,
.tail = NULL,
.threads = NULL,
};
struct flush_callback_s {
char *name;
cdtime_t timeout;
};
typedef struct flush_callback_s flush_callback_t;
/*
* Private variables
*/
static c_avl_tree_t *plugins_loaded;
static llist_t *list_init;
static llist_t *list_flush;
static llist_t *list_missing;
static llist_t *list_shutdown;
static llist_t *list_log;
static llist_t *list_notification;
static size_t list_cache_event_num;
static cache_event_func_t list_cache_event[32];
static fc_chain_t *pre_cache_chain;
static fc_chain_t *post_cache_chain;
static char *plugindir;
#ifndef DEFAULT_MAX_READ_INTERVAL
#define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
#endif
static c_heap_t *read_heap;
static llist_t *read_list;
static int read_loop = 1;
static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
static pthread_t *read_threads;
static size_t read_threads_num;
static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
static pthread_key_t plugin_ctx_key;
static bool plugin_ctx_key_initialized;
static long write_limit_high;
static long write_limit_low;
static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
static derive_t stats_values_dropped;
static bool record_statistics;
/*
* Static functions
*/
static int plugin_dispatch_metric_internal(metric_family_t const *fam);
static const char *plugin_get_dir(void) {
if (plugindir == NULL)
return PLUGINDIR;
else
return plugindir;
}
static int plugin_update_internal_statistics(void) { /* {{{ */
long write_queue_length = 0;
pthread_mutex_lock(&write_queue.lock);
for (write_queue_thread_t *thread = write_queue.threads; thread != NULL;
thread = thread->next) {
if (thread->queue_length > write_queue_length) {
write_queue_length = thread->queue_length;
}
}
pthread_mutex_unlock(&write_queue.lock);
gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
/* Initialize `vl' */
value_list_t vl = VALUE_LIST_INIT;
sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
vl.interval = plugin_get_interval();
/* Write queue */
sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
/* Write queue : queue length */
vl.values = &(value_t){.gauge = copy_write_queue_length};
vl.values_len = 1;
sstrncpy(vl.type, "queue_length", sizeof(vl.type));
vl.type_instance[0] = 0;
plugin_dispatch_values(&vl);
/* Write queue : Values dropped (queue length > low limit) */
pthread_mutex_lock(&statistics_lock);
vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
pthread_mutex_unlock(&statistics_lock);
vl.values_len = 1;
sstrncpy(vl.type, "derive", sizeof(vl.type));
sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
plugin_dispatch_values(&vl);
/* Cache */
sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
/* Cache : Nb entry in cache tree */
vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
vl.values_len = 1;
sstrncpy(vl.type, "cache_size", sizeof(vl.type));
vl.type_instance[0] = 0;
plugin_dispatch_values(&vl);
return 0;
} /* }}} int plugin_update_internal_statistics */
static void free_userdata(user_data_t const *ud) /* {{{ */
{
if (ud == NULL)
return;
if ((ud->data != NULL) && (ud->free_func != NULL)) {
ud->free_func(ud->data);
}
} /* }}} void free_userdata */
static void destroy_callback(callback_func_t *cf) /* {{{ */
{
if (cf == NULL)
return;
free_userdata(&cf->cf_udata);
sfree(cf);
} /* }}} void destroy_callback */
static void destroy_all_callbacks(llist_t **list) /* {{{ */
{
llentry_t *le;
if (*list == NULL)
return;
le = llist_head(*list);
while (le != NULL) {
llentry_t *le_next;
le_next = le->next;
sfree(le->key);
destroy_callback(le->value);
le->value = NULL;
le = le_next;
}
llist_destroy(*list);
*list = NULL;
} /* }}} void destroy_all_callbacks */
static void destroy_read_heap(void) /* {{{ */
{
if (read_heap == NULL)
return;
while (42) {
read_func_t *rf;
rf = c_heap_get_root(read_heap);
if (rf == NULL)
break;
sfree(rf->rf_name);
destroy_callback((callback_func_t *)rf);
}
c_heap_destroy(read_heap);
read_heap = NULL;
} /* }}} void destroy_read_heap */
static int register_callback(llist_t **list, /* {{{ */
const char *name, callback_func_t *cf) {
if (*list == NULL) {
*list = llist_create();
if (*list == NULL) {
ERROR("plugin: register_callback: "
"llist_create failed.");
destroy_callback(cf);
return -1;
}
}
char *key = strdup(name);
if (key == NULL) {
ERROR("plugin: register_callback: strdup failed.");
destroy_callback(cf);
return -1;
}
llentry_t *le = llist_search(*list, name);
if (le == NULL) {
le = llentry_create(key, cf);
if (le == NULL) {
ERROR("plugin: register_callback: "
"llentry_create failed.");
sfree(key);
destroy_callback(cf);
return -1;
}
llist_append(*list, le);
} else {
callback_func_t *old_cf = le->value;
le->value = cf;
P_WARNING("register_callback: "
"a callback named `%s' already exists - "
"overwriting the old entry!",
name);
destroy_callback(old_cf);
sfree(key);
}
return 0;
} /* }}} int register_callback */
static int create_register_callback(llist_t **list, /* {{{ */
const char *name, placeholder_cb_t callback,
user_data_t const *ud) {
if (name == NULL || callback == NULL)
return EINVAL;
callback_func_t *cf = calloc(1, sizeof(*cf));
if (cf == NULL) {
free_userdata(ud);
ERROR("plugin: create_register_callback: calloc failed.");
return ENOMEM;
}
cf->cf_callback = callback;
if (ud == NULL) {
cf->cf_udata = (user_data_t){
.data = NULL,
.free_func = NULL,
};
} else {
cf->cf_udata = *ud;
}
cf->cf_ctx = plugin_get_ctx();
return register_callback(list, name, cf);
} /* }}} int create_register_callback */
static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
{
llentry_t *e;
if (list == NULL)
return -1;
e = llist_search(list, name);
if (e == NULL)
return -1;
llist_remove(list, e);
sfree(e->key);
destroy_callback(e->value);
llentry_destroy(e);
return 0;
} /* }}} int plugin_unregister */
/* plugin_load_file loads the shared object "file" and calls its
* "module_register" function. Returns zero on success, non-zero otherwise. */
static int plugin_load_file(char const *file, bool global) {
int flags = RTLD_NOW;
if (global)
flags |= RTLD_GLOBAL;
void *dlh = dlopen(file, flags);
if (dlh == NULL) {
char errbuf[1024] = "";
snprintf(errbuf, sizeof(errbuf),
"dlopen(\"%s\") failed: %s. "
"The most common cause for this problem is missing dependencies. "
"Use ldd(1) to check the dependencies of the plugin / shared "
"object.",
file, dlerror());
/* This error is printed to STDERR unconditionally. If list_log is NULL,
* plugin_log() will also print to STDERR. We avoid duplicate output by
* checking that the list of log handlers, list_log, is not NULL. */
fprintf(stderr, "ERROR: %s\n", errbuf);
if (list_log != NULL) {
ERROR("%s", errbuf);
}
return ENOENT;
}
void (*reg_handle)(void) = dlsym(dlh, "module_register");
if (reg_handle == NULL) {
ERROR("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
dlerror());
dlclose(dlh);
return ENOENT;
}
(*reg_handle)();
return 0;
}
static void *plugin_read_thread(void __attribute__((unused)) * args) {
while (read_loop != 0) {
read_func_t *rf;
plugin_ctx_t old_ctx;
cdtime_t start;
cdtime_t now;
cdtime_t elapsed;
int status;
int rf_type;
int rc;
/* Get the read function that needs to be read next.
* We don't need to hold "read_lock" for the heap, but we need
* to call c_heap_get_root() and pthread_cond_wait() in the
* same protected block. */
pthread_mutex_lock(&read_lock);
rf = c_heap_get_root(read_heap);
if (rf == NULL) {
pthread_cond_wait(&read_cond, &read_lock);
pthread_mutex_unlock(&read_lock);
continue;
}
pthread_mutex_unlock(&read_lock);
if (rf->rf_interval == 0) {
/* this should not happen, because the interval is set
* for each plugin when loading it
* XXX: issue a warning? */
rf->rf_interval = plugin_get_interval();
rf->rf_effective_interval = rf->rf_interval;
rf->rf_next_read = cdtime();
}
/* sleep until this entry is due,
* using pthread_cond_timedwait */
pthread_mutex_lock(&read_lock);
/* In pthread_cond_timedwait, spurious wakeups are possible
* (and really happen, at least on NetBSD with > 1 CPU), thus
* we need to re-evaluate the condition every time
* pthread_cond_timedwait returns. */
rc = 0;
while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
rc = pthread_cond_timedwait(&read_cond, &read_lock,
&CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
}
/* Must hold `read_lock' when accessing `rf->rf_type'. */
rf_type = rf->rf_type;
pthread_mutex_unlock(&read_lock);
/* Check if we're supposed to stop.. This may have interrupted
* the sleep, too. */
if (read_loop == 0) {
/* Insert `rf' again, so it can be free'd correctly */
c_heap_insert(read_heap, rf);
break;
}
/* The entry has been marked for deletion. The linked list
* entry has already been removed by `plugin_unregister_read'.
* All we have to do here is free the `read_func_t' and
* continue. */
if (rf_type == RF_REMOVE) {
DEBUG("plugin_read_thread: Destroying the `%s' "
"callback.",
rf->rf_name);
sfree(rf->rf_name);
destroy_callback((callback_func_t *)rf);
rf = NULL;
continue;
}
DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
start = cdtime();
old_ctx = plugin_set_ctx(rf->rf_ctx);
if (rf_type == RF_SIMPLE) {
int (*callback)(void) = rf->rf_callback;
status = (*callback)();
} else {
assert(rf_type == RF_COMPLEX);
plugin_read_cb callback = (plugin_read_cb)rf->rf_callback;
status = (*callback)(&rf->rf_udata);
}
plugin_set_ctx(old_ctx);
/* If the function signals failure, we will increase the
* intervals in which it will be called. */
if (status != 0) {
rf->rf_effective_interval *= 2;
if (rf->rf_effective_interval > max_read_interval)
rf->rf_effective_interval = max_read_interval;
NOTICE("read-function of plugin `%s' failed. "
"Will suspend it for %.3f seconds.",
rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
} else {
/* Success: Restore the interval, if it was changed. */
rf->rf_effective_interval = rf->rf_interval;
}
/* update the ``next read due'' field */
now = cdtime();
/* calculate the time spent in the read function */
elapsed = (now - start);
if (elapsed > rf->rf_effective_interval)
WARNING(
"plugin_read_thread: read-function of the `%s' plugin took %.3f "
"seconds, which is above its read interval (%.3f seconds). You might "
"want to adjust the `Interval' or `ReadThreads' settings.",
rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
"%.6f seconds.",
rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
DEBUG("plugin_read_thread: Effective interval of the "
"`%s' plugin is %.3f seconds.",
rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
/* Calculate the next (absolute) time at which this function
* should be called. */
rf->rf_next_read += rf->rf_effective_interval;
/* Check, if `rf_next_read' is in the past. */
if (rf->rf_next_read < now) {
/* `rf_next_read' is in the past. Insert `now'
* so this value doesn't trail off into the
* past too much. */
rf->rf_next_read = now;
}
DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
/* Re-insert this read function into the heap again. */
c_heap_insert(read_heap, rf);
} /* while (read_loop) */
pthread_exit(NULL);
return (void *)0;
} /* void *plugin_read_thread */
#ifdef PTHREAD_MAX_NAMELEN_NP
#define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
#else
#define THREAD_NAME_MAX 16
#endif
static void set_thread_name(pthread_t tid, char const *name) {
#if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
/* glibc limits the length of the name and fails if the passed string
* is too long, so we truncate it here. */
char n[THREAD_NAME_MAX];
if (strlen(name) >= THREAD_NAME_MAX)
WARNING("set_thread_name(\"%s\"): name too long", name);
sstrncpy(n, name, sizeof(n));
#if defined(HAVE_PTHREAD_SETNAME_NP)
int status = pthread_setname_np(tid, n);
if (status != 0) {
ERROR("set_thread_name(\"%s\"): %s", n, STRERROR(status));
}
#else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
pthread_set_name_np(tid, n);
#endif
#endif
}
static void start_read_threads(size_t num) /* {{{ */
{
if (read_threads != NULL)
return;
read_threads = calloc(num, sizeof(*read_threads));
if (read_threads == NULL) {
ERROR("plugin: start_read_threads: calloc failed.");
return;
}
read_threads_num = 0;
for (size_t i = 0; i < num; i++) {
int status = pthread_create(read_threads + read_threads_num,
/* attr = */ NULL, plugin_read_thread,
/* arg = */ NULL);
if (status != 0) {
ERROR("plugin: start_read_threads: pthread_create failed with status %i "
"(%s).",
status, STRERROR(status));
return;
}
char name[THREAD_NAME_MAX];
ssnprintf(name, sizeof(name), "reader#%" PRIu64,
(uint64_t)read_threads_num);
set_thread_name(read_threads[read_threads_num], name);
read_threads_num++;
} /* for (i) */
} /* }}} void start_read_threads */
static void stop_read_threads(void) {
if (read_threads == NULL)
return;
INFO("collectd: Stopping %" PRIsz " read threads.", read_threads_num);
pthread_mutex_lock(&read_lock);
read_loop = 0;
DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
pthread_cond_broadcast(&read_cond);
pthread_mutex_unlock(&read_lock);
for (size_t i = 0; i < read_threads_num; i++) {
if (pthread_join(read_threads[i], NULL) != 0) {
ERROR("plugin: stop_read_threads: pthread_join failed.");
}
read_threads[i] = (pthread_t)0;
}
sfree(read_threads);
read_threads_num = 0;
} /* void stop_read_threads */
static void write_queue_ref_single(write_queue_elem_t *elem, long dir) {
elem->ref_count += dir;
assert(elem->ref_count >= 0);
if (elem->ref_count == 0) {
if (write_queue.tail == elem) {
write_queue.tail = NULL;
assert(elem->next == NULL);
}
metric_family_free(elem->family);
sfree(elem);
}
}
static void write_queue_ref_all(write_queue_elem_t *start, long dir) {
while (start != NULL) {
write_queue_elem_t *elem = start;
start = elem->next;
write_queue_ref_single(elem, dir);
}
}
static int write_queue_enqueue(write_queue_elem_t *ins_head) {
static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
if (ins_head == NULL) {
return EINVAL;
}
pthread_mutex_lock(&write_queue.lock);
if (write_queue.threads == NULL) {
c_complain_once(LOG_WARNING, &no_write_complaint,
"write_queue_enqueue: No write callback has been "
"registered. Please load at least one output plugin, "
"if you want the collected data to be stored.");
/* Element in the ins_head queue already have zero reference count
* but without any write threads there is noone to free them.
* make sure they are freed by de-refing them 0 times. */
write_queue_ref_all(ins_head, 0);
pthread_mutex_unlock(&write_queue.lock);
return ENOENT;
}
write_queue_elem_t *ins_tail = NULL;
long num_elems = 0;
/* More than one element may be enqueued at once. Count elements and find
* local tail. */
for (write_queue_elem_t *elem = ins_head; elem != NULL; elem = elem->next) {
ins_tail = elem;
num_elems++;
}
/* Add reference to new elements to existing queue (if there is one)
* and update the tail. */
if (write_queue.tail != NULL) {
write_queue.tail->next = ins_head;
}
write_queue.tail = ins_tail;
/* Iterate through all registered write plugins/threads to:
* a) update their head pointer if their queue is currently empty.
* b) find the thread with the longest queue to apply limits later. */
write_queue_thread_t *slowest_thread = write_queue.threads;
for (write_queue_thread_t *thread = write_queue.threads; thread != NULL;
thread = thread->next) {
if (thread->head == NULL) {
thread->head = ins_head;
}
/* Mark the new elements as to be consumed by this thread */
write_queue_ref_all(ins_head, 1);
thread->queue_length += num_elems;
if (thread->queue_length > slowest_thread->queue_length) {
slowest_thread = thread;
}
}
/* Enforce write_limit_high (unless it is infinite (e.g. == 0)) */
while (write_limit_high != 0 &&
slowest_thread->queue_length > write_limit_high) {
/* Select a random element to drop between the last position in the slowest
* thread's queue and queue positon "write_limit_low". This makes sure that
* write plugins that do not let the queue get longer than "write_limit_low"
* will never drop values, regardless of what other plugins do. */
long drop_pos =
cdrand_u() % (slowest_thread->queue_length - write_limit_low) +
write_limit_low;
/* Walk the queue and count elements until element number drop_pos is
* found. to_drop will point to the element in question and to_spare
* will point to one element before to_drop (it it exists). */
write_queue_elem_t *to_spare = NULL;
write_queue_elem_t *to_drop = slowest_thread->head;
for (long queue_pos = slowest_thread->queue_length - 1;
queue_pos > drop_pos; queue_pos--) {
to_spare = to_drop;
to_drop = to_drop->next;
}
/* Unlink to_drop from linked list if it is not the head (in which case
* to_spare is NULL and it will be unlinked below) */
if (to_spare != NULL) {
to_spare->next = to_drop->next;
}
/* Iterate through all registered write plugins/threads to:
* a) update the head if it references to_drop.
* b) update the thread's queue length if to_drop was still in it's
* queue. */
for (write_queue_thread_t *thread = write_queue.threads; thread != NULL;
thread = thread->next) {
if (thread->head == to_drop) {
thread->head = to_drop->next;
}
/* Reduce reference count and queue length for every affected queue.
* There may still be references held in write_threads if the element was
* just de-queued in any and is currently used in the callback,
* so freeing may be delayed until it is dropped there. */
if (drop_pos < thread->queue_length) {
thread->queue_length--;
write_queue_ref_single(to_drop, -1);
}
}
if (record_statistics) {
pthread_mutex_lock(&statistics_lock);
stats_values_dropped++;
pthread_mutex_unlock(&statistics_lock);
}
}
pthread_cond_broadcast(&write_queue.cond);
pthread_mutex_unlock(&write_queue.lock);
return 0;
}
static void *plugin_write_thread(void *args) /* {{{ */
{
write_queue_thread_t *this_thread = args;
DEBUG("plugin_write_thread (%s): start", this_thread->name);
pthread_mutex_lock(&write_queue.lock);
while (this_thread->loop) {
write_queue_elem_t *elem = this_thread->head;
if (elem == NULL) {
pthread_cond_wait(&write_queue.cond, &write_queue.lock);
continue;
}
/* Unlink early so that write_queue_enqueue can freely manipulate the
* head while the lock is not held in the callback. */
this_thread->head = elem->next;
this_thread->queue_length--;
DEBUG("plugin_write_thread(%s): de-queue %p (remaining queue length: %ld)",
this_thread->name, elem, this_thread->queue_length);
/* Should elem be written to all plugins or this plugin in particular? */
if (elem->plugin == NULL ||
strcasecmp(elem->plugin, this_thread->name) == 0) {
pthread_mutex_unlock(&write_queue.lock);
plugin_ctx_t ctx = elem->ctx;
ctx.name = (char *)this_thread->name;
plugin_set_ctx(ctx);
/* TODO(lgo): do something with the return value? */
this_thread->callback(elem->family, &this_thread->ud);
pthread_mutex_lock(&write_queue.lock);
}
/* Free the element if it is not referenced by another queue or thread. */
write_queue_ref_single(elem, -1);
}
DEBUG("plugin_write_thread(%s): teardown", this_thread->name);
/* Cleanup before leaving */
free_userdata(&this_thread->ud);
this_thread->ud.data = NULL;
this_thread->ud.free_func = NULL;
sfree(this_thread->name);
/* Drop references to all remaining queue elements */
if (this_thread->head != NULL) {
write_queue_ref_all(this_thread->head, -1);
this_thread->head = NULL;
this_thread->queue_length = 0;
}
pthread_mutex_unlock(&write_queue.lock);
pthread_exit(NULL);
return NULL;
} /* }}} void *plugin_write_thread */
/*
* Public functions
*/
void plugin_set_dir(const char *dir) {
sfree(plugindir);
if (dir == NULL) {
plugindir = NULL;
return;
}
plugindir = strdup(dir);
if (plugindir == NULL)
ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
}
bool plugin_is_loaded(char const *name) {
if (plugins_loaded == NULL)
plugins_loaded =
c_avl_create((int (*)(const void *, const void *))strcasecmp);
assert(plugins_loaded != NULL);
int status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
return status == 0;
}
static int plugin_mark_loaded(char const *name) {
char *name_copy;
int status;
name_copy = strdup(name);
if (name_copy == NULL)
return ENOMEM;
status = c_avl_insert(plugins_loaded,
/* key = */ name_copy, /* value = */ NULL);
return status;
}
static void plugin_free_loaded(void) {
void *key;
void *value;
if (plugins_loaded == NULL)
return;
while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
sfree(key);
assert(value == NULL);
}
c_avl_destroy(plugins_loaded);
plugins_loaded = NULL;
}
#define BUFSIZE 512
#ifdef WIN32
#define SHLIB_SUFFIX ".dll"
#else
#define SHLIB_SUFFIX ".so"
#endif
int plugin_load(char const *plugin_name, bool global) {
DIR *dh;
const char *dir;
char filename[BUFSIZE] = "";
char typename[BUFSIZE];
int ret;
struct stat statbuf;
struct dirent *de;
int status;
if (plugin_name == NULL)
return EINVAL;
/* Check if plugin is already loaded and don't do anything in this
* case. */
if (plugin_is_loaded(plugin_name))
return 0;
dir = plugin_get_dir();
ret = 1;
/*
* XXX: Magic at work:
*
* Some of the language bindings, for example the Python and Perl
* plugins, need to be able to export symbols to the scripts they run.
* For this to happen, the "Globals" flag needs to be set.
* Unfortunately, this technical detail is hard to explain to the
* average user and she shouldn't have to worry about this, ideally.
* So in order to save everyone's sanity use a different default for a
* handful of special plugins. --octo
*/
if ((strcasecmp("perl", plugin_name) == 0) ||
(strcasecmp("python", plugin_name) == 0))
global = true;
/* `cpu' should not match `cpufreq'. To solve this we add SHLIB_SUFFIX to the
* type when matching the filename */
status = snprintf(typename, sizeof(typename), "%s" SHLIB_SUFFIX, plugin_name);
if ((status < 0) || ((size_t)status >= sizeof(typename))) {
WARNING("plugin_load: Filename too long: \"%s" SHLIB_SUFFIX "\"",
plugin_name);
return -1;
}
if ((dh = opendir(dir)) == NULL) {
ERROR("plugin_load: opendir (%s) failed: %s", dir, STRERRNO);