1 /* chrony plugin for collectd
2 (c) 2015 by Claudius M Zingerli, ZSeng
3 Internas roughly based on the ntpd plugin
4 Some functions copied from chronyd/web (marked)
8 * - More robust udp parsing (using offsets instead of structs?)
9 * -> Currently chrony parses its data the same way as we do (using structs)
10 * - Plausibility checks on values received
11 * -> Done at higher levels
15 #include <sys/types.h>
16 #include <sys/socket.h>
19 #include <arpa/inet.h> /* ntohs/ntohl */
22 #include "common.h" /* auxiliary functions */
23 #include "plugin.h" /* plugin_register_*, plugin_dispatch_values */
25 #define CONFIG_KEY_HOST "Host"
26 #define CONFIG_KEY_PORT "Port"
27 #define CONFIG_KEY_TIMEOUT "Timeout"
29 #define URAND_DEVICE_PATH "/dev/urandom" /* Used to initialize seq nr generator*/
30 #define RAND_DEVICE_PATH "/dev/random" /* Used to initialize seq nr generator (fall back)*/
32 static const char *g_config_keys[] =
39 static int g_config_keys_num = STATIC_ARRAY_SIZE (g_config_keys);
40 static int g_is_connected = 0;
41 static int g_chrony_socket = -1;
42 static time_t g_chrony_timeout = -1;
43 static char *g_chrony_host = NULL;
44 static char *g_chrony_port = NULL;
45 static char *g_plugin_instance = NULL;
46 static uint32_t g_chrony_rand = 1;
47 static uint32_t g_chrony_seq_is_initialized = 0;
49 #define PLUGIN_NAME_SHORT "chrony"
50 #define PLUGIN_NAME PLUGIN_NAME_SHORT " plugin"
51 #define DAEMON_NAME PLUGIN_NAME_SHORT
52 #define CHRONY_DEFAULT_HOST "localhost"
53 #define CHRONY_DEFAULT_PORT "323"
54 #define CHRONY_DEFAULT_TIMEOUT 2
56 /* Return codes (collectd expects non-zero on errors) */
57 #define CHRONY_RC_OK (int)0
58 #define CHRONY_RC_FAIL (int)1
60 /* Variables adapted from chrony/candm.h */
62 #define PROTO_VERSION_NUMBER 6
63 #define IPADDR_UNSPEC 0
64 #define IPADDR_INET4 1
65 #define IPADDR_INET6 2
66 #define IPV6_STR_MAX_SIZE (8*4+7+1)
70 PKT_TYPE_CMD_REQUEST = 1,
71 PKT_TYPE_CMD_REPLY = 2
88 RPY_MANUAL_TIMESTAMP = 4,
94 #define ATTRIB_PACKED __attribute__((packed))
95 typedef struct ATTRIB_PACKED
100 typedef struct ATTRIB_PACKED
102 uint32_t tv_sec_high;
114 STT_NOSUCHSOURCE = 4,
118 STT_ACCESSALLOWED = 8,
119 STT_ACCESSDENIED = 9,
120 STT_NOHOSTACCESS = 10,
121 STT_SOURCEALREADYKNOWN = 11,
122 STT_TOOMANYSOURCES = 12,
128 STT_BADPKTVERSION = 18,
129 STT_BADPKTLENGTH = 19
132 /* Chrony client request packets */
133 typedef struct ATTRIB_PACKED
135 uint8_t f_dummy0[80]; //Chrony expects 80bytes dummy data (Avoiding UDP Amplification)
136 } tChrony_Req_Tracking;
138 typedef struct ATTRIB_PACKED
140 uint32_t f_n_sources;
141 } tChrony_Req_N_Sources;
143 typedef struct ATTRIB_PACKED
146 uint8_t f_dummy0[44];
147 } tChrony_Req_Source_data;
149 typedef struct ATTRIB_PACKED
152 uint8_t f_dummy0[56];
153 } tChrony_Req_Source_stats;
155 typedef struct ATTRIB_PACKED
169 } header; /* Packed: 20Bytes */
172 tChrony_Req_N_Sources n_sources;
173 tChrony_Req_Source_data source_data;
174 tChrony_Req_Source_stats source_stats;
175 tChrony_Req_Tracking tracking;
177 uint8_t padding[4+16]; /* Padding to match minimal response size */
180 /* Chrony daemon response packets */
181 typedef struct ATTRIB_PACKED
183 uint32_t f_n_sources;
184 } tChrony_Resp_N_Sources;
186 typedef struct ATTRIB_PACKED
196 typedef struct ATTRIB_PACKED
199 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3/clang 3.4.1 on x86_64 */
200 int16_t f_poll; /* 2^f_poll = Time between polls (s) */
201 uint16_t f_stratum; /* Remote clock stratum */
202 uint16_t f_state; /* 0 = RPY_SD_ST_SYNC, 1 = RPY_SD_ST_UNREACH, 2 = RPY_SD_ST_FALSETICKER */
203 /* 3 = RPY_SD_ST_JITTERY, 4 = RPY_SD_ST_CANDIDATE, 5 = RPY_SD_ST_OUTLIER */
204 uint16_t f_mode; /* 0 = RPY_SD_MD_CLIENT, 1 = RPY_SD_MD_PEER, 2 = RPY_SD_MD_REF */
205 uint16_t f_flags; /* unused */
206 uint16_t f_reachability; /* Bit mask of successfull tries to reach the source */
208 uint32_t f_since_sample; /* Time since last sample (s) */
209 tFloat f_origin_latest_meas; /* */
210 tFloat f_latest_meas; /* */
211 tFloat f_latest_meas_err; /* */
212 } tChrony_Resp_Source_data;
214 typedef struct ATTRIB_PACKED
218 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3/clang 3.4.1 on x86_64 */
219 uint32_t f_n_samples; /* Number of measurements done */
220 uint32_t f_n_runs; /* How many measurements to come */
221 uint32_t f_span_seconds; /* For how long we're measuring */
222 tFloat f_rtc_seconds_fast; /* ??? */
223 tFloat f_rtc_gain_rate_ppm; /* Estimated relative frequency error */
224 tFloat f_skew_ppm; /* Clock skew (ppm) (worst case freq est error (skew: peak2peak)) */
225 tFloat f_est_offset; /* Estimated offset of source */
226 tFloat f_est_offset_err; /* Error of estimation */
227 } tChrony_Resp_Source_stats;
229 typedef struct ATTRIB_PACKED
233 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3/clang 3.4.1 on x86_64 */
235 uint16_t f_leap_status;
237 tFloat f_current_correction;
238 tFloat f_last_offset;
241 tFloat f_resid_freq_ppm;
244 tFloat f_root_dispersion;
245 tFloat f_last_update_interval;
246 } tChrony_Resp_Tracking;
248 typedef struct ATTRIB_PACKED
265 } header; /* Packed: 28 Bytes */
269 tChrony_Resp_N_Sources n_sources;
270 tChrony_Resp_Source_data source_data;
271 tChrony_Resp_Source_stats source_stats;
272 tChrony_Resp_Tracking tracking;
275 uint8_t padding[1024];
279 /*****************************************************************************/
280 /* Internal functions */
281 /*****************************************************************************/
282 /* Code adapted from: http://long.ccaba.upc.edu/long/045Guidelines/eva/ipv6.html#daytimeClient6 */
284 static int connect_client (const char *p_hostname,
285 const char *p_service,
289 struct addrinfo hints, *res=NULL, *ressave=NULL;
292 memset(&hints, 0, sizeof(struct addrinfo));
294 hints.ai_family = p_family;
295 hints.ai_socktype = p_socktype;
297 n = getaddrinfo(p_hostname, p_service, &hints, &res);
301 ERROR (PLUGIN_NAME ": getaddrinfo error:: [%s]", gai_strerror(n));
310 sockfd = socket(res->ai_family,
316 if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
328 freeaddrinfo(ressave);
332 /*Code originally from: git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
333 /*char * UTI_IPToString(IPAddr *addr)*/
334 static char * niptoha(const tChrony_IPAddr *addr,char *p_buf, size_t p_buf_size)
337 unsigned long a, b, c, d, ip;
340 switch (ntohs(addr->f_family))
343 rc=snprintf(p_buf, p_buf_size, "[UNSPEC]");
346 ip = ntohl(addr->addr.ip4);
351 rc=snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
354 ip6 = addr->addr.ip6;
357 rc=inet_ntop(AF_INET6, ip6, p_buf, p_bug_size);
359 #if defined(BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
360 rc=snprintf(p_buf, p_buf_size, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
361 ip6[15], ip6[14], ip6[13], ip6[12], ip6[11], ip6[10], ip6[9], ip6[8],
362 ip6[7], ip6[6], ip6[5], ip6[4], ip6[3], ip6[2], ip6[1], ip6[0]);
364 rc=snprintf(p_buf, p_buf_size, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
365 ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7],
366 ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15]);
371 rc=snprintf(p_buf, p_buf_size, "[UNKNOWN]");
378 static int chrony_set_timeout()
380 /*Set the socket's timeout to g_chrony_timeout; a value of 0 signals infinite timeout*/
381 /*Returns 0 on success, !0 on error (check errno)*/
384 tv.tv_sec = g_chrony_timeout;
387 assert(g_chrony_socket>=0);
388 if (setsockopt(g_chrony_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval)) < 0)
390 return CHRONY_RC_FAIL;
395 static int chrony_connect()
397 /*Connects to the chrony daemon*/
398 /*Returns 0 on success, !0 on error (check errno)*/
401 if (g_chrony_host == NULL)
403 g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
404 assert(g_chrony_host);
406 if (g_chrony_port == NULL)
408 g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
409 assert(g_chrony_port);
411 if (g_chrony_timeout < 0)
413 g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
414 assert(g_chrony_timeout>=0);
418 DEBUG(PLUGIN_NAME ": Connecting to %s:%s", g_chrony_host, g_chrony_port);
419 socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
422 ERROR (PLUGIN_NAME ": Error connecting to daemon. Errno = %d", errno);
423 return CHRONY_RC_FAIL;
425 DEBUG(PLUGIN_NAME ": Connected");
426 g_chrony_socket = socket;
428 if (chrony_set_timeout())
430 ERROR (PLUGIN_NAME ": Error setting timeout to %lds. Errno = %d", g_chrony_timeout, errno);
431 return CHRONY_RC_FAIL;
436 static int chrony_send_request(const tChrony_Request *p_req, size_t p_req_size)
438 if (send(g_chrony_socket,p_req,p_req_size,0) < 0)
440 ERROR (PLUGIN_NAME ": Error sending packet. Errno = %d", errno);
441 return CHRONY_RC_FAIL;
446 static int chrony_recv_response(tChrony_Response *p_resp, size_t p_resp_max_size, size_t *p_resp_size)
448 ssize_t rc = recv(g_chrony_socket,p_resp,p_resp_max_size,0);
451 ERROR (PLUGIN_NAME ": Error receiving packet: %s (%d)", strerror(errno), errno);
452 return CHRONY_RC_FAIL;
459 static int chrony_query(const int p_command, tChrony_Request *p_req, tChrony_Response *p_resp, size_t *p_resp_size)
461 /* Check connection. We simply perform one try as collectd already handles retries */
466 if (g_is_connected == 0)
468 if (chrony_connect() == 0)
472 ERROR (PLUGIN_NAME ": Unable to connect. Errno = %d", errno);
473 return CHRONY_RC_FAIL;
480 int valid_command = 0;
481 size_t req_size = sizeof(p_req->header) + sizeof(p_req->padding);
482 size_t resp_size = sizeof(p_resp->header);
483 uint16_t resp_code = RPY_NULL;
487 req_size += sizeof(p_req->body.tracking);
488 resp_size += sizeof(p_resp->body.tracking);
489 resp_code = RPY_TRACKING;
493 req_size += sizeof(p_req->body.n_sources);
494 resp_size += sizeof(p_resp->body.n_sources);
495 resp_code = RPY_N_SOURCES;
498 case REQ_SOURCE_DATA:
499 req_size += sizeof(p_req->body.source_data);
500 resp_size += sizeof(p_resp->body.source_data);
501 resp_code = RPY_SOURCE_DATA;
504 case REQ_SOURCE_STATS:
505 req_size += sizeof(p_req->body.source_stats);
506 resp_size += sizeof(p_resp->body.source_stats);
507 resp_code = RPY_SOURCE_STATS;
511 ERROR (PLUGIN_NAME ": Unknown request command (Was: %d)", p_command);
515 if (valid_command == 0)
520 uint32_t seq_nr = rand_r(&g_chrony_rand);
521 p_req->header.f_cmd = htons(p_command);
522 p_req->header.f_cmd_try = 0;
523 p_req->header.f_seq = seq_nr;
525 DEBUG(PLUGIN_NAME ": Sending request (.cmd = %d, .seq = %d)",p_command, seq_nr);
526 if (chrony_send_request(p_req,req_size) != 0)
531 DEBUG(PLUGIN_NAME ": Waiting for response");
532 if (chrony_recv_response(p_resp,resp_size,p_resp_size) != 0)
536 DEBUG(PLUGIN_NAME ": Received response: .version = %u, .type = %u, .cmd = %u, .reply = %u, .status = %u, .seq = %u",
537 p_resp->header.f_version, p_resp->header.f_type, ntohs(p_resp->header.f_cmd),
538 ntohs(p_resp->header.f_reply), ntohs(p_resp->header.f_status), p_resp->header.f_seq);
540 if (p_resp->header.f_version != p_req->header.f_version)
542 ERROR(PLUGIN_NAME ": Wrong protocol version (Was: %d, expected: %d)", p_resp->header.f_version, p_req->header.f_version);
543 return CHRONY_RC_FAIL;
545 if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY)
547 ERROR(PLUGIN_NAME ": Wrong packet type (Was: %d, expected: %d)", p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
548 return CHRONY_RC_FAIL;
550 if (p_resp->header.f_seq != seq_nr)
552 /* FIXME: Implement sequence number handling */
553 ERROR(PLUGIN_NAME ": Unexpected sequence number (Was: %d, expected: %d)", p_resp->header.f_seq, p_req->header.f_seq);
554 return CHRONY_RC_FAIL;
556 if (p_resp->header.f_cmd != p_req->header.f_cmd)
558 ERROR(PLUGIN_NAME ": Wrong reply command (Was: %d, expected: %d)", p_resp->header.f_cmd, p_req->header.f_cmd);
559 return CHRONY_RC_FAIL;
562 if (ntohs(p_resp->header.f_reply) != resp_code)
564 ERROR(PLUGIN_NAME ": Wrong reply code (Was: %d, expected: %d)", ntohs(p_resp->header.f_reply), resp_code);
565 return CHRONY_RC_FAIL;
568 switch (p_resp->header.f_status)
571 DEBUG(PLUGIN_NAME ": Reply packet status STT_SUCCESS");
574 ERROR(PLUGIN_NAME ": Reply packet contains error status: %d (expected: %d)", p_resp->header.f_status, STT_SUCCESS);
575 return CHRONY_RC_FAIL;
582 /* Some error occured */
583 return CHRONY_RC_FAIL;
586 static void chrony_init_req(tChrony_Request *p_req)
588 memset(p_req,0,sizeof(*p_req));
589 p_req->header.f_version = PROTO_VERSION_NUMBER;
590 p_req->header.f_type = PKT_TYPE_CMD_REQUEST;
591 p_req->header.f_dummy0 = 0;
592 p_req->header.f_dummy1 = 0;
593 p_req->header.f_dummy2 = 0;
594 p_req->header.f_dummy3 = 0;
597 /* Code from: git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c (GPLv2) */
599 #define FLOAT_EXP_BITS 7
600 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
601 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
602 #define FLOAT_COEF_BITS ((int)sizeof (int32_t) * 8 - FLOAT_EXP_BITS)
603 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
604 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
606 /* double UTI_tFloatNetworkToHost(tFloat f) */
607 static double ntohf(tFloat p_float)
609 /* Convert tFloat in Network-bit-order to double in host-bit-order */
614 uval = ntohl(p_float.value);
615 exp = (uval >> FLOAT_COEF_BITS) - FLOAT_COEF_BITS;
616 if (exp >= 1 << (FLOAT_EXP_BITS - 1))
618 exp -= 1 << FLOAT_EXP_BITS;
621 /* coef = (x << FLOAT_EXP_BITS) >> FLOAT_EXP_BITS; */
622 coef = uval % (1U << FLOAT_COEF_BITS);
623 if (coef >= 1 << (FLOAT_COEF_BITS - 1))
625 coef -= 1 << FLOAT_COEF_BITS;
627 return coef * pow(2.0, exp);
631 static void chrony_push_data(char *p_type, char *p_type_inst, double p_value)
634 value_list_t vl = VALUE_LIST_INIT;
636 values[0].gauge = p_value; /* TODO: Check type??? (counter, gauge, derive, absolute) */
641 /* XXX: Shall g_chrony_host/g_chrony_port be reflected in the plugin's output? */
642 /* hostname_g is set in daemon/collectd.c (from config, via gethostname or by resolving localhost) */
643 /* defined as: char hostname_g[DATA_MAX_NAME_LEN]; (never NULL) */
644 { sstrncpy (vl.host, hostname_g, sizeof (vl.host)); }
645 { sstrncpy (vl.plugin, PLUGIN_NAME_SHORT, sizeof (vl.plugin)); }
646 if (g_plugin_instance != NULL) { sstrncpy (vl.plugin_instance, g_plugin_instance, sizeof (vl.plugin_instance)); }
647 if (p_type != NULL) { sstrncpy (vl.type, p_type, sizeof (vl.type)); }
648 if (p_type_inst != NULL) { sstrncpy (vl.type_instance, p_type_inst, sizeof (vl.type_instance)); }
650 plugin_dispatch_values (&vl);
654 static void chrony_push_data_valid(char *p_type, char *p_type_inst, const int p_is_valid, double p_value)
656 /* Push real value if p_is_valid is true, push NAN if p_is_valid is not true (idea from ntp plugin)*/
661 chrony_push_data(p_type, p_type_inst, p_value);
665 static int chrony_init_seq()
667 /* Initialize the sequence number generator from /dev/urandom */
670 int fh = open(URAND_DEVICE_PATH, O_RDONLY);
673 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
674 if (rc != sizeof(g_chrony_rand))
676 ERROR (PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)", URAND_DEVICE_PATH, strerror(errno), errno);
678 return CHRONY_RC_FAIL;
681 DEBUG(PLUGIN_NAME ": Seeding RNG from " URAND_DEVICE_PATH);
685 /* URAND_DEVICE_PATH device not found. Try RAND_DEVICE_PATH as fall-back */
686 int fh = open(RAND_DEVICE_PATH, O_RDONLY);
689 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
690 if (rc != sizeof(g_chrony_rand))
692 ERROR (PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)", RAND_DEVICE_PATH, strerror(errno), errno);
694 return CHRONY_RC_FAIL;
697 DEBUG(PLUGIN_NAME ": Seeding RNG from " RAND_DEVICE_PATH);
699 /* Error opening RAND_DEVICE_PATH. Try time(NULL) as fall-back */
700 DEBUG(PLUGIN_NAME ": Seeding RNG from time(NULL)");
701 g_chrony_rand = time(NULL) ^ getpid();
704 ERROR (PLUGIN_NAME ": Opening random source \'%s\' failed: %s (%d)", URAND_DEVICE_PATH, strerror(errno), errno);
705 return CHRONY_RC_FAIL;
713 /*****************************************************************************/
714 /* Exported functions */
715 /*****************************************************************************/
716 static int chrony_config(const char *p_key, const char *p_value)
720 /* Parse config variables */
721 if (strcasecmp(p_key, CONFIG_KEY_HOST) == 0)
723 if (g_chrony_host != NULL)
725 free (g_chrony_host);
727 if ((g_chrony_host = strdup (p_value)) == NULL)
729 ERROR (PLUGIN_NAME ": Error duplicating host name");
730 return CHRONY_RC_FAIL;
732 } else if (strcasecmp(p_key, CONFIG_KEY_PORT) == 0)
734 if (g_chrony_port != NULL)
736 free (g_chrony_port);
738 if ((g_chrony_port = strdup (p_value)) == NULL)
740 ERROR (PLUGIN_NAME ": Error duplicating port name");
741 return CHRONY_RC_FAIL;
743 } else if (strcasecmp(p_key, CONFIG_KEY_TIMEOUT) == 0)
745 time_t tosec = strtol(p_value,NULL,0);
746 g_chrony_timeout = tosec;
748 WARNING(PLUGIN_NAME ": Unknown configuration variable: %s %s",p_key,p_value);
749 return CHRONY_RC_FAIL;
751 /* XXX: We could set g_plugin_instance here to "g_chrony_host-g_chrony_port", but as multiple instances aren't yet supported, we skip this for now */
757 static int chrony_request_daemon_stats()
759 /* Perform Tracking request */
761 size_t chrony_resp_size;
762 tChrony_Request chrony_req;
763 tChrony_Response chrony_resp;
765 chrony_init_req(&chrony_req);
766 rc = chrony_query(REQ_TRACKING, &chrony_req, &chrony_resp, &chrony_resp_size);
769 ERROR (PLUGIN_NAME ": chrony_query (REQ_TRACKING) failed with status %i", rc);
775 char src_addr[IPV6_STR_MAX_SIZE];
776 memset(src_addr, 0, sizeof(src_addr));
777 niptoha(&chrony_resp.body.tracking.addr, src_addr, sizeof(src_addr));
778 DEBUG(PLUGIN_NAME ": Daemon stat: .addr = %s, .ref_id= %u, .stratum = %u, .leap_status = %u, .ref_time = %u:%u:%u, .current_correction = %f, .last_offset = %f, .rms_offset = %f, .freq_ppm = %f, .skew_ppm = %f, .root_delay = %f, .root_dispersion = %f, .last_update_interval = %f",
780 ntohs(chrony_resp.body.tracking.f_ref_id), //FIXME: 16bit
781 ntohs(chrony_resp.body.tracking.f_stratum),
782 ntohs(chrony_resp.body.tracking.f_leap_status),
783 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high),
784 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low),
785 ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec),
786 ntohf(chrony_resp.body.tracking.f_current_correction),
787 ntohf(chrony_resp.body.tracking.f_last_offset),
788 ntohf(chrony_resp.body.tracking.f_rms_offset),
789 ntohf(chrony_resp.body.tracking.f_freq_ppm),
790 ntohf(chrony_resp.body.tracking.f_skew_ppm),
791 ntohf(chrony_resp.body.tracking.f_root_delay),
792 ntohf(chrony_resp.body.tracking.f_root_dispersion),
793 ntohf(chrony_resp.body.tracking.f_last_update_interval)
798 double time_ref = ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec);
799 time_ref /= 1000000000.0;
800 time_ref += ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low);
801 if (chrony_resp.body.tracking.f_ref_time.tv_sec_high)
803 double secs_high = ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high);
804 secs_high *= 4294967296.0;
805 time_ref += secs_high;
808 /* Forward results to collectd-daemon */
809 /* Type_instance is always 'chrony' to tag daemon-wide data */
810 /* Type Type_instance Value */
811 chrony_push_data("clock_stratum", DAEMON_NAME, ntohs(chrony_resp.body.tracking.f_stratum));
812 chrony_push_data("time_ref", DAEMON_NAME, time_ref); /* unit: s */
813 chrony_push_data("time_offset_ntp", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_current_correction)); /* Offset between system time and NTP, unit: s */
814 chrony_push_data("time_offset", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_last_offset)); /* Estimated Offset of the NTP time, unit: s */
815 chrony_push_data("time_offset_rms", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_rms_offset)); /* averaged value of the above, unit: s */
816 chrony_push_data("frequency_error", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_freq_ppm)); /* Frequency error of the local osc, unit: ppm */
817 chrony_push_data("clock_skew_ppm", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_skew_ppm));
818 chrony_push_data("root_delay", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_root_delay)); /* Network latency between local daemon and the current source */
819 chrony_push_data("root_dispersion", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_root_dispersion));
820 chrony_push_data("clock_last_update",DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_last_update_interval));
826 static int chrony_request_sources_count(unsigned int *p_count)
828 /* Requests the number of time sources from the chrony daemon */
830 size_t chrony_resp_size;
831 tChrony_Request chrony_req;
832 tChrony_Response chrony_resp;
834 DEBUG(PLUGIN_NAME ": Requesting data");
835 chrony_init_req(&chrony_req);
836 rc = chrony_query (REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
839 ERROR (PLUGIN_NAME ": chrony_query (REQ_N_SOURCES) failed with status %i", rc);
843 *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
844 DEBUG(PLUGIN_NAME ": Getting data of %d clock sources", *p_count);
850 static int chrony_request_source_data(int p_src_idx, int *p_is_reachable)
852 /* Perform Source data request for source #p_src_idx*/
854 size_t chrony_resp_size;
855 tChrony_Request chrony_req;
856 tChrony_Response chrony_resp;
858 char src_addr[IPV6_STR_MAX_SIZE];
859 memset(src_addr, 0, sizeof(src_addr));
861 chrony_init_req(&chrony_req);
862 chrony_req.body.source_data.f_index = htonl(p_src_idx);
863 rc = chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp, &chrony_resp_size);
866 ERROR (PLUGIN_NAME ": chrony_query (REQ_SOURCE_DATA) failed with status %i", rc);
870 niptoha(&chrony_resp.body.source_data.addr, src_addr, sizeof(src_addr));
871 DEBUG(PLUGIN_NAME ": Source[%d] data: .addr = %s, .poll = %u, .stratum = %u, .state = %u, .mode = %u, .flags = %u, .reach = %u, .latest_meas_ago = %u, .orig_latest_meas = %f, .latest_meas = %f, .latest_meas_err = %f",
874 ntohs(chrony_resp.body.source_data.f_poll),
875 ntohs(chrony_resp.body.source_data.f_stratum),
876 ntohs(chrony_resp.body.source_data.f_state),
877 ntohs(chrony_resp.body.source_data.f_mode),
878 ntohs(chrony_resp.body.source_data.f_flags),
879 ntohs(chrony_resp.body.source_data.f_reachability),
880 ntohl(chrony_resp.body.source_data.f_since_sample),
881 ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
882 ntohf(chrony_resp.body.source_data.f_latest_meas),
883 ntohf(chrony_resp.body.source_data.f_latest_meas_err)
886 /* Push NaN if source is currently not reachable */
887 int is_reachable = ntohs(chrony_resp.body.source_data.f_reachability) & 0x01;
888 *p_is_reachable = is_reachable;
890 /* Forward results to collectd-daemon */
891 chrony_push_data_valid("clock_stratum", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_stratum));
892 chrony_push_data_valid("clock_state", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_state));
893 chrony_push_data_valid("clock_mode", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_mode));
894 chrony_push_data_valid("clock_reachability",src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_reachability));
895 chrony_push_data_valid("clock_last_meas", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_since_sample));
901 static int chrony_request_source_stats(int p_src_idx, const int *p_is_reachable)
903 /* Perform Source stats request for source #p_src_idx */
905 size_t chrony_resp_size;
906 tChrony_Request chrony_req;
907 tChrony_Response chrony_resp;
908 double skew_ppm, frequency_error, time_offset;
910 char src_addr[IPV6_STR_MAX_SIZE];
911 memset(src_addr, 0, sizeof(src_addr));
913 if (*p_is_reachable == 0)
919 chrony_init_req(&chrony_req);
920 chrony_req.body.source_stats.f_index = htonl(p_src_idx);
921 rc = chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp, &chrony_resp_size);
924 ERROR (PLUGIN_NAME ": chrony_query (REQ_SOURCE_STATS) failed with status %i", rc);
928 skew_ppm = ntohf(chrony_resp.body.source_stats.f_skew_ppm);
929 frequency_error = ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm);
930 time_offset = ntohf(chrony_resp.body.source_stats.f_est_offset);
932 niptoha(&chrony_resp.body.source_stats.addr, src_addr, sizeof(src_addr));
933 DEBUG(PLUGIN_NAME ": Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, " \
934 ".n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, " \
935 ".rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, .est_offset_err = %f",
938 ntohl(chrony_resp.body.source_stats.f_ref_id),
939 ntohl(chrony_resp.body.source_stats.f_n_samples),
940 ntohl(chrony_resp.body.source_stats.f_n_runs),
941 ntohl(chrony_resp.body.source_stats.f_span_seconds),
942 ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
946 ntohf(chrony_resp.body.source_stats.f_est_offset_err)
949 } //if (*is_reachable)
951 /* Forward results to collectd-daemon */
952 chrony_push_data_valid("clock_skew_ppm", src_addr, *p_is_reachable, skew_ppm);
953 chrony_push_data_valid("frequency_error", src_addr, *p_is_reachable, frequency_error); /* unit: ppm */
954 chrony_push_data_valid("time_offset", src_addr, *p_is_reachable, time_offset); /* unit: s */
959 static int chrony_read()
961 /* collectd read callback: Perform data acquisition */
963 unsigned int now_src, n_sources;
965 if (g_chrony_seq_is_initialized == 0)
967 /* Seed RNG for sequence number generation */
968 rc = chrony_init_seq();
969 if (rc != CHRONY_RC_OK)
973 g_chrony_seq_is_initialized = 1;
976 /* Get daemon stats */
977 rc = chrony_request_daemon_stats();
978 if (rc != CHRONY_RC_OK)
983 /* Get number of time sources, then check every source for status */
984 rc = chrony_request_sources_count(&n_sources);
985 if (rc != CHRONY_RC_OK)
990 for (now_src = 0; now_src < n_sources; ++now_src)
993 rc = chrony_request_source_data(now_src, &is_reachable);
994 if (rc != CHRONY_RC_OK)
999 rc = chrony_request_source_stats(now_src, &is_reachable);
1000 if (rc != CHRONY_RC_OK)
1005 return CHRONY_RC_OK;
1009 static int chrony_shutdown()
1011 /* Collectd shutdown callback: Free mem */
1012 if (g_is_connected != 0)
1014 close(g_chrony_socket);
1017 if (g_chrony_host != NULL)
1019 free (g_chrony_host);
1020 g_chrony_host = NULL;
1022 if (g_chrony_port != NULL)
1024 free (g_chrony_port);
1025 g_chrony_port = NULL;
1027 if (g_plugin_instance != NULL)
1029 free (g_plugin_instance);
1030 g_plugin_instance = NULL;
1032 return CHRONY_RC_OK;
1036 void module_register (void)
1038 plugin_register_config( PLUGIN_NAME_SHORT, chrony_config, g_config_keys, g_config_keys_num);
1039 plugin_register_read( PLUGIN_NAME_SHORT, chrony_read);
1040 plugin_register_shutdown(PLUGIN_NAME_SHORT, chrony_shutdown);