Merge branch 'collectd-5.7' into collectd-5.8
[collectd.git] / src / cpusleep.c
1 /**
2  * collectd - src/cpusleep.c
3  * Copyright (C) 2016 rinigus
4  *
5  * The MIT License (MIT)
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * Authors:
26  *       rinigus <http://github.com/rinigus>
27  *
28  * CPU sleep is reported in milliseconds of sleep per second of wall
29  * time. For that, the time difference between BOOT and MONOTONIC clocks
30  * is reported using derive type.
31 **/
32
33 #include "collectd.h"
34
35 #include <time.h>
36 #include "common.h"
37 #include "plugin.h"
38
39 static void cpusleep_submit(derive_t cpu_sleep) {
40   value_list_t vl = VALUE_LIST_INIT;
41
42   vl.values = &(value_t){.derive = cpu_sleep};
43   vl.values_len = 1;
44   sstrncpy(vl.plugin, "cpusleep", sizeof(vl.plugin));
45   sstrncpy(vl.type, "total_time_in_ms", sizeof(vl.type));
46
47   plugin_dispatch_values(&vl);
48 }
49
50 static int cpusleep_read(void) {
51   struct timespec b, m;
52   if (clock_gettime(CLOCK_BOOTTIME, &b) < 0) {
53     ERROR("cpusleep plugin: clock_boottime failed");
54     return -1;
55   }
56
57   if (clock_gettime(CLOCK_MONOTONIC, &m) < 0) {
58     ERROR("cpusleep plugin: clock_monotonic failed");
59     return -1;
60   }
61
62   // to avoid false positives in counter overflow due to reboot,
63   // derive is used. Sleep is calculated in milliseconds
64   derive_t diffsec = b.tv_sec - m.tv_sec;
65   derive_t diffnsec = b.tv_nsec - m.tv_nsec;
66   derive_t sleep = diffsec * 1000 + diffnsec / 1000000;
67
68   cpusleep_submit(sleep);
69
70   return 0;
71 }
72
73 void module_register(void) {
74   plugin_register_read("cpusleep", cpusleep_read);
75 } /* void module_register */