1 /* chrony plugin for collectd (monitoring of chrony time server daemon)
2 **********************************************************************
3 * Copyright (C) Claudius M Zingerli, ZSeng, 2015-2016
5 * Internals roughly based on the ntpd plugin
6 * Some functions copied from chronyd/web (as marked)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of version 2 of the GNU General Public License as
10 * published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * - More robust udp parsing (using offsets instead of structs?)
23 * -> Currently chrony parses its data the same way as we do (using
25 * - Plausibility checks on values received
26 * -> Done at higher levels
31 #include "common.h" /* auxiliary functions */
32 #include "plugin.h" /* plugin_register_*, plugin_dispatch_values */
35 #include <netdb.h> /* struct addrinfo */
38 #include <arpa/inet.h> /* ntohs/ntohl */
41 #define CONFIG_KEY_HOST "Host"
42 #define CONFIG_KEY_PORT "Port"
43 #define CONFIG_KEY_TIMEOUT "Timeout"
45 #define URAND_DEVICE_PATH \
46 "/dev/urandom" /* Used to initialize seq nr generator */
47 #define RAND_DEVICE_PATH \
48 "/dev/random" /* Used to initialize seq nr generator (fall back) */
50 static const char *g_config_keys[] = {CONFIG_KEY_HOST, CONFIG_KEY_PORT,
53 static int g_config_keys_num = STATIC_ARRAY_SIZE(g_config_keys);
54 static int g_chrony_is_connected;
55 static int g_chrony_socket = -1;
56 static time_t g_chrony_timeout = -1;
57 static char *g_chrony_plugin_instance;
58 static char *g_chrony_host;
59 static char *g_chrony_port;
60 static uint32_t g_chrony_rand = 1;
61 static uint32_t g_chrony_seq_is_initialized;
63 #define PLUGIN_NAME_SHORT "chrony"
64 #define PLUGIN_NAME PLUGIN_NAME_SHORT " plugin"
65 #define DAEMON_NAME PLUGIN_NAME_SHORT
66 #define CHRONY_DEFAULT_HOST "localhost"
67 #define CHRONY_DEFAULT_PORT "323"
68 #define CHRONY_DEFAULT_TIMEOUT 2
70 /* Return codes (collectd expects non-zero on errors) */
71 #define CHRONY_RC_OK 0
72 #define CHRONY_RC_FAIL 1
74 /* Chronyd command packet variables adapted from chrony/candm.h (GPL2) */
75 #define PROTO_VERSION_NUMBER 6
76 #define IPADDR_UNSPEC 0
77 #define IPADDR_INET4 1
78 #define IPADDR_INET6 2
79 #define IPV6_STR_MAX_SIZE (8 * 4 + 7 + 1)
80 #define MODE_REFCLOCK 2
82 typedef enum { PKT_TYPE_CMD_REQUEST = 1, PKT_TYPE_CMD_REPLY = 2 } ePacketType;
95 RPY_MANUAL_TIMESTAMP = 4,
101 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(lint)
102 #/* extension to enforce struct packing. */
103 #define ATTRIB_PACKED __attribute__((packed))
105 #error Not defining packed attribute (unknown compiler)
106 #define ATTRIB_PACKED
109 typedef struct ATTRIB_PACKED { int32_t value; } tFloat;
111 typedef struct ATTRIB_PACKED {
112 uint32_t tv_sec_high;
122 STT_NOSUCHSOURCE = 4,
126 STT_ACCESSALLOWED = 8,
127 STT_ACCESSDENIED = 9,
128 STT_NOHOSTACCESS = 10,
129 STT_SOURCEALREADYKNOWN = 11,
130 STT_TOOMANYSOURCES = 12,
136 STT_BADPKTVERSION = 18,
137 STT_BADPKTLENGTH = 19
140 /* Chrony client request packets */
141 typedef struct ATTRIB_PACKED {
142 uint8_t f_dummy0[80]; /* Chrony expects 80bytes dummy data (Avoiding UDP
144 } tChrony_Req_Tracking;
146 typedef struct ATTRIB_PACKED { uint32_t f_n_sources; } tChrony_Req_N_Sources;
148 typedef struct ATTRIB_PACKED {
150 uint8_t f_dummy0[44];
151 } tChrony_Req_Source_data;
153 typedef struct ATTRIB_PACKED {
155 uint8_t f_dummy0[56];
156 } tChrony_Req_Source_stats;
158 typedef struct ATTRIB_PACKED {
170 } 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 { uint32_t f_n_sources; } tChrony_Resp_N_Sources;
183 typedef struct ATTRIB_PACKED {
192 typedef struct ATTRIB_PACKED {
194 int16_t f_poll; /* 2^f_poll = Time between polls (s) */
195 uint16_t f_stratum; /* Remote clock stratum */
196 uint16_t f_state; /* 0 = RPY_SD_ST_SYNC, 1 = RPY_SD_ST_UNREACH, 2 =
197 RPY_SD_ST_FALSETICKER */
198 /* 3 = RPY_SD_ST_JITTERY, 4 = RPY_SD_ST_CANDIDATE, 5 = RPY_SD_ST_OUTLIER */
199 uint16_t f_mode; /* 0 = RPY_SD_MD_CLIENT, 1 = RPY_SD_MD_PEER, 2 =
201 uint16_t f_flags; /* unused */
203 f_reachability; /* Bit mask of successfull tries to reach the source */
205 uint32_t f_since_sample; /* Time since last sample (s) */
206 tFloat f_origin_latest_meas; /* */
207 tFloat f_latest_meas; /* */
208 tFloat f_latest_meas_err; /* */
209 } tChrony_Resp_Source_data;
211 typedef struct ATTRIB_PACKED {
214 uint32_t f_n_samples; /* Number of measurements done */
215 uint32_t f_n_runs; /* How many measurements to come */
216 uint32_t f_span_seconds; /* For how long we're measuring */
217 tFloat f_rtc_seconds_fast; /* ??? */
218 tFloat f_rtc_gain_rate_ppm; /* Estimated relative frequency error */
219 tFloat f_skew_ppm; /* Clock skew (ppm) (worst case freq est error (skew:
221 tFloat f_est_offset; /* Estimated offset of source */
222 tFloat f_est_offset_err; /* Error of estimation */
223 } tChrony_Resp_Source_stats;
225 typedef struct ATTRIB_PACKED {
229 uint16_t f_leap_status;
231 tFloat f_current_correction;
232 tFloat f_last_offset;
235 tFloat f_resid_freq_ppm;
238 tFloat f_root_dispersion;
239 tFloat f_last_update_interval;
240 } tChrony_Resp_Tracking;
242 typedef struct ATTRIB_PACKED {
257 } header; /* Packed: 28 Bytes */
260 tChrony_Resp_N_Sources n_sources;
261 tChrony_Resp_Source_data source_data;
262 tChrony_Resp_Source_stats source_stats;
263 tChrony_Resp_Tracking tracking;
266 uint8_t padding[1024];
269 /*****************************************************************************/
270 /* Internal functions */
271 /*****************************************************************************/
273 /* connect_client code adapted from:
274 * http://long.ccaba.upc.edu/long/045Guidelines/eva/ipv6.html#daytimeClient6 */
275 /* License granted by Eva M Castro via e-mail on 2016-02-18 under the terms of
277 static int connect_client(const char *p_hostname, const char *p_service,
278 int p_family, int p_socktype) {
279 struct addrinfo *res, *ressave;
282 struct addrinfo ai_hints = {.ai_family = p_family, .ai_socktype = p_socktype};
284 n = getaddrinfo(p_hostname, p_service, &ai_hints, &res);
287 ERROR(PLUGIN_NAME ": getaddrinfo error:: [%s]", gai_strerror(n));
295 sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
298 if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0) {
309 freeaddrinfo(ressave);
313 /* niptoha code originally from:
314 * git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
315 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
316 /* Original name: char * UTI_IPToString(IPAddr *addr)*/
317 static char *niptoha(const tChrony_IPAddr *addr, char *p_buf,
320 unsigned long a, b, c, d, ip;
322 switch (ntohs(addr->f_family)) {
324 rc = snprintf(p_buf, p_buf_size, "[UNSPEC]");
327 ip = ntohl(addr->addr.ip4);
328 a = (ip >> 24) & 0xff;
329 b = (ip >> 16) & 0xff;
330 c = (ip >> 8) & 0xff;
331 d = (ip >> 0) & 0xff;
332 rc = snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
335 const char *rp = inet_ntop(AF_INET6, addr->addr.ip6, p_buf, p_buf_size);
337 ERROR(PLUGIN_NAME ": Error converting ipv6 address to string. Errno = %d",
339 rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
344 rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
350 static void nreftostr(uint32_t nrefid, char *p_buf, size_t p_buf_size) {
354 for (i = 0; i < 4; i++) {
355 c = ntohl(nrefid) << i * 8 >> 24;
356 if (!isalnum(c) || j + 1 >= p_buf_size)
364 static int chrony_set_timeout(void) {
365 /* Set the socket's timeout to g_chrony_timeout; a value of 0 signals
366 * infinite timeout */
367 /* Returns 0 on success, !0 on error (check errno) */
370 tv.tv_sec = g_chrony_timeout;
373 assert(g_chrony_socket >= 0);
374 if (setsockopt(g_chrony_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,
375 sizeof(struct timeval)) < 0) {
376 return CHRONY_RC_FAIL;
381 static int chrony_connect(void) {
382 /* Connects to the chrony daemon */
383 /* Returns 0 on success, !0 on error (check errno) */
386 if (g_chrony_host == NULL) {
387 g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
388 if (g_chrony_host == NULL) {
389 ERROR(PLUGIN_NAME ": Error duplicating chrony host name");
390 return CHRONY_RC_FAIL;
393 if (g_chrony_port == NULL) {
394 g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
395 if (g_chrony_port == NULL) {
396 ERROR(PLUGIN_NAME ": Error duplicating chrony port string");
397 return CHRONY_RC_FAIL;
400 if (g_chrony_timeout < 0) {
401 g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
402 assert(g_chrony_timeout >= 0);
405 DEBUG(PLUGIN_NAME ": Connecting to %s:%s", g_chrony_host, g_chrony_port);
406 socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
408 ERROR(PLUGIN_NAME ": Error connecting to daemon. Errno = %d", errno);
409 return CHRONY_RC_FAIL;
411 DEBUG(PLUGIN_NAME ": Connected");
412 g_chrony_socket = socket;
414 if (chrony_set_timeout()) {
415 ERROR(PLUGIN_NAME ": Error setting timeout to %llds. Errno = %d",
416 (long long)g_chrony_timeout, errno);
417 return CHRONY_RC_FAIL;
422 static int chrony_send_request(const tChrony_Request *p_req,
424 if (send(g_chrony_socket, p_req, p_req_size, 0) < 0) {
425 ERROR(PLUGIN_NAME ": Error sending packet. Errno = %d", errno);
426 return CHRONY_RC_FAIL;
431 static int chrony_recv_response(tChrony_Response *p_resp,
432 size_t p_resp_max_size, size_t *p_resp_size) {
433 ssize_t rc = recv(g_chrony_socket, p_resp, p_resp_max_size, 0);
435 ERROR(PLUGIN_NAME ": Error receiving packet: %s (%d)", strerror(errno),
437 return CHRONY_RC_FAIL;
444 static int chrony_query(const int p_command, tChrony_Request *p_req,
445 tChrony_Response *p_resp, size_t *p_resp_size) {
446 /* Check connection. We simply perform one try as collectd already handles
452 if (g_chrony_is_connected == 0) {
453 if (chrony_connect() == CHRONY_RC_OK) {
454 g_chrony_is_connected = 1;
456 ERROR(PLUGIN_NAME ": Unable to connect. Errno = %d", errno);
457 return CHRONY_RC_FAIL;
462 int valid_command = 0;
463 size_t req_size = sizeof(p_req->header) + sizeof(p_req->padding);
464 size_t resp_size = sizeof(p_resp->header);
465 uint16_t resp_code = RPY_NULL;
468 req_size += sizeof(p_req->body.tracking);
469 resp_size += sizeof(p_resp->body.tracking);
470 resp_code = RPY_TRACKING;
474 req_size += sizeof(p_req->body.n_sources);
475 resp_size += sizeof(p_resp->body.n_sources);
476 resp_code = RPY_N_SOURCES;
479 case REQ_SOURCE_DATA:
480 req_size += sizeof(p_req->body.source_data);
481 resp_size += sizeof(p_resp->body.source_data);
482 resp_code = RPY_SOURCE_DATA;
485 case REQ_SOURCE_STATS:
486 req_size += sizeof(p_req->body.source_stats);
487 resp_size += sizeof(p_resp->body.source_stats);
488 resp_code = RPY_SOURCE_STATS;
492 ERROR(PLUGIN_NAME ": Unknown request command (Was: %d)", p_command);
496 if (valid_command == 0)
499 uint32_t seq_nr = rand_r(&g_chrony_rand);
500 p_req->header.f_cmd = htons(p_command);
501 p_req->header.f_cmd_try = 0;
502 p_req->header.f_seq = seq_nr;
504 DEBUG(PLUGIN_NAME ": Sending request (.cmd = %d, .seq = %d)", p_command,
506 if (chrony_send_request(p_req, req_size) != 0)
509 DEBUG(PLUGIN_NAME ": Waiting for response");
510 if (chrony_recv_response(p_resp, resp_size, p_resp_size) != 0)
513 DEBUG(PLUGIN_NAME ": Received response: .version = %u, .type = %u, .cmd = "
514 "%u, .reply = %u, .status = %u, .seq = %u",
515 p_resp->header.f_version, p_resp->header.f_type,
516 ntohs(p_resp->header.f_cmd), ntohs(p_resp->header.f_reply),
517 ntohs(p_resp->header.f_status), p_resp->header.f_seq);
519 if (p_resp->header.f_version != p_req->header.f_version) {
520 ERROR(PLUGIN_NAME ": Wrong protocol version (Was: %d, expected: %d)",
521 p_resp->header.f_version, p_req->header.f_version);
522 return CHRONY_RC_FAIL;
524 if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY) {
525 ERROR(PLUGIN_NAME ": Wrong packet type (Was: %d, expected: %d)",
526 p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
527 return CHRONY_RC_FAIL;
529 if (p_resp->header.f_seq != seq_nr) {
530 /* FIXME: Implement sequence number handling */
531 ERROR(PLUGIN_NAME ": Unexpected sequence number (Was: %d, expected: %d)",
532 p_resp->header.f_seq, p_req->header.f_seq);
533 return CHRONY_RC_FAIL;
535 if (p_resp->header.f_cmd != p_req->header.f_cmd) {
536 ERROR(PLUGIN_NAME ": Wrong reply command (Was: %d, expected: %d)",
537 p_resp->header.f_cmd, p_req->header.f_cmd);
538 return CHRONY_RC_FAIL;
541 if (ntohs(p_resp->header.f_reply) != resp_code) {
542 ERROR(PLUGIN_NAME ": Wrong reply code (Was: %d, expected: %d)",
543 ntohs(p_resp->header.f_reply), resp_code);
544 return CHRONY_RC_FAIL;
547 switch (p_resp->header.f_status) {
549 DEBUG(PLUGIN_NAME ": Reply packet status STT_SUCCESS");
553 ": Reply packet contains error status: %d (expected: %d)",
554 p_resp->header.f_status, STT_SUCCESS);
555 return CHRONY_RC_FAIL;
562 /* Some error occured */
563 return CHRONY_RC_FAIL;
566 static void chrony_init_req(tChrony_Request *p_req) {
567 memset(p_req, 0, sizeof(*p_req));
568 p_req->header.f_version = PROTO_VERSION_NUMBER;
569 p_req->header.f_type = PKT_TYPE_CMD_REQUEST;
570 p_req->header.f_dummy0 = 0;
571 p_req->header.f_dummy1 = 0;
572 p_req->header.f_dummy2 = 0;
573 p_req->header.f_dummy3 = 0;
576 /* ntohf code originally from:
577 * git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
578 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
579 /* Original name: double UTI_tFloatNetworkToHost(tFloat f) */
580 static double ntohf(tFloat p_float) {
581 /* Convert tFloat in Network-bit-order to double in host-bit-order */
583 #define FLOAT_EXP_BITS 7
584 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
585 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
586 #define FLOAT_COEF_BITS ((int)sizeof(int32_t) * 8 - FLOAT_EXP_BITS)
587 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
588 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
593 uval = ntohl(p_float.value);
594 exp = (uval >> FLOAT_COEF_BITS);
595 if (exp >= 1 << (FLOAT_EXP_BITS - 1))
596 exp -= 1 << FLOAT_EXP_BITS;
597 exp -= FLOAT_COEF_BITS;
599 /* coef = (x << FLOAT_EXP_BITS) >> FLOAT_EXP_BITS; */
600 coef = uval % (1U << FLOAT_COEF_BITS);
601 if (coef >= 1 << (FLOAT_COEF_BITS - 1))
602 coef -= 1 << FLOAT_COEF_BITS;
604 return coef * pow(2.0, exp);
607 static void chrony_push_data(const char *p_type, const char *p_type_inst,
609 value_list_t vl = VALUE_LIST_INIT;
611 vl.values = &(value_t){.gauge = p_value};
614 /* XXX: Shall g_chrony_host/g_chrony_port be reflected in the plugin's output?
616 sstrncpy(vl.plugin, PLUGIN_NAME_SHORT, sizeof(vl.plugin));
617 if (g_chrony_plugin_instance != NULL) {
618 sstrncpy(vl.plugin_instance, g_chrony_plugin_instance,
619 sizeof(vl.plugin_instance));
622 sstrncpy(vl.type, p_type, sizeof(vl.type));
624 if (p_type_inst != NULL)
625 sstrncpy(vl.type_instance, p_type_inst, sizeof(vl.type_instance));
627 plugin_dispatch_values(&vl);
630 static void chrony_push_data_valid(const char *p_type, const char *p_type_inst,
631 const int p_is_valid, double p_value) {
632 /* Push real value if p_is_valid is true, push NAN if p_is_valid is not true
633 * (idea from ntp plugin) */
637 chrony_push_data(p_type, p_type_inst, p_value);
640 static int chrony_init_seq(void) {
641 /* Initialize the sequence number generator from /dev/urandom */
642 /* Fallbacks: /dev/random and time(NULL) */
647 fh = open(URAND_DEVICE_PATH, O_RDONLY);
649 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
650 if (rc != sizeof(g_chrony_rand)) {
651 ERROR(PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)",
652 URAND_DEVICE_PATH, strerror(errno), errno);
654 return CHRONY_RC_FAIL;
657 DEBUG(PLUGIN_NAME ": Seeding RNG from " URAND_DEVICE_PATH);
659 if (errno == ENOENT) {
660 /* URAND_DEVICE_PATH device not found. Try RAND_DEVICE_PATH as fall-back
662 fh = open(RAND_DEVICE_PATH, O_RDONLY);
664 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
665 if (rc != sizeof(g_chrony_rand)) {
667 ": Reading from random source \'%s\'failed: %s (%d)",
668 RAND_DEVICE_PATH, strerror(errno), errno);
670 return CHRONY_RC_FAIL;
673 DEBUG(PLUGIN_NAME ": Seeding RNG from " RAND_DEVICE_PATH);
675 /* Error opening RAND_DEVICE_PATH. Try time(NULL) as fall-back */
676 DEBUG(PLUGIN_NAME ": Seeding RNG from time(NULL)");
677 g_chrony_rand = time(NULL) ^ getpid();
680 ERROR(PLUGIN_NAME ": Opening random source \'%s\' failed: %s (%d)",
681 URAND_DEVICE_PATH, strerror(errno), errno);
682 return CHRONY_RC_FAIL;
689 /*****************************************************************************/
690 /* Exported functions */
691 /*****************************************************************************/
692 static int chrony_config(const char *p_key, const char *p_value) {
696 /* Parse config variables */
697 if (strcasecmp(p_key, CONFIG_KEY_HOST) == 0) {
698 if (g_chrony_host != NULL)
701 if ((g_chrony_host = strdup(p_value)) == NULL) {
702 ERROR(PLUGIN_NAME ": Error duplicating host name");
703 return CHRONY_RC_FAIL;
706 if (strcasecmp(p_key, CONFIG_KEY_PORT) == 0) {
707 if (g_chrony_port != NULL)
710 if ((g_chrony_port = strdup(p_value)) == NULL) {
711 ERROR(PLUGIN_NAME ": Error duplicating port name");
712 return CHRONY_RC_FAIL;
715 if (strcasecmp(p_key, CONFIG_KEY_TIMEOUT) == 0) {
716 time_t tosec = strtol(p_value, NULL, 0);
717 g_chrony_timeout = tosec;
719 WARNING(PLUGIN_NAME ": Unknown configuration variable: %s %s", p_key,
721 return CHRONY_RC_FAIL;
725 /* XXX: We could set g_chrony_plugin_instance here to
726 * "g_chrony_host-g_chrony_port", but as multiple instances aren't yet
727 * supported, we skip this for now */
732 static int chrony_request_daemon_stats(void) {
733 /* Perform Tracking request */
735 size_t chrony_resp_size;
736 tChrony_Request chrony_req;
737 tChrony_Response chrony_resp;
739 chrony_init_req(&chrony_req);
740 rc = chrony_query(REQ_TRACKING, &chrony_req, &chrony_resp, &chrony_resp_size);
742 ERROR(PLUGIN_NAME ": chrony_query (REQ_TRACKING) failed with status %i",
748 char src_addr[IPV6_STR_MAX_SIZE] = {0};
749 niptoha(&chrony_resp.body.tracking.addr, src_addr, sizeof(src_addr));
751 ": Daemon stat: .addr = %s, .ref_id= %u, .stratum = %u, .leap_status "
752 "= %u, .ref_time = %u:%u:%u, .current_correction = %f, .last_offset "
753 "= %f, .rms_offset = %f, .freq_ppm = %f, .skew_ppm = %f, .root_delay "
754 "= %f, .root_dispersion = %f, .last_update_interval = %f",
755 src_addr, ntohs(chrony_resp.body.tracking.f_ref_id),
756 ntohs(chrony_resp.body.tracking.f_stratum),
757 ntohs(chrony_resp.body.tracking.f_leap_status),
758 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high),
759 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low),
760 ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec),
761 ntohf(chrony_resp.body.tracking.f_current_correction),
762 ntohf(chrony_resp.body.tracking.f_last_offset),
763 ntohf(chrony_resp.body.tracking.f_rms_offset),
764 ntohf(chrony_resp.body.tracking.f_freq_ppm),
765 ntohf(chrony_resp.body.tracking.f_skew_ppm),
766 ntohf(chrony_resp.body.tracking.f_root_delay),
767 ntohf(chrony_resp.body.tracking.f_root_dispersion),
768 ntohf(chrony_resp.body.tracking.f_last_update_interval));
772 double time_ref = ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec);
773 time_ref /= 1000000000.0;
774 time_ref += ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low);
775 if (chrony_resp.body.tracking.f_ref_time.tv_sec_high) {
776 double secs_high = ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high);
777 secs_high *= 4294967296.0;
778 time_ref += secs_high;
781 /* Forward results to collectd-daemon */
782 /* Type_instance is always 'chrony' to tag daemon-wide data */
783 /* Type Type_instan Value */
784 chrony_push_data("clock_stratum", DAEMON_NAME,
785 ntohs(chrony_resp.body.tracking.f_stratum));
786 chrony_push_data("time_ref", DAEMON_NAME, time_ref); /* unit: s */
788 "time_offset_ntp", DAEMON_NAME,
789 ntohf(chrony_resp.body.tracking.f_current_correction)); /* Offset between
793 "time_offset", DAEMON_NAME,
795 chrony_resp.body.tracking
796 .f_last_offset)); /* Estimated Offset of the NTP time, unit: s */
798 "time_offset_rms", DAEMON_NAME,
799 ntohf(chrony_resp.body.tracking
800 .f_rms_offset)); /* averaged value of the above, unit: s */
802 "frequency_error", DAEMON_NAME,
803 ntohf(chrony_resp.body.tracking
804 .f_freq_ppm)); /* Frequency error of the local osc, unit: ppm */
805 chrony_push_data("clock_skew_ppm", DAEMON_NAME,
806 ntohf(chrony_resp.body.tracking.f_skew_ppm));
808 "root_delay", DAEMON_NAME,
809 ntohf(chrony_resp.body.tracking.f_root_delay)); /* Network latency between
812 chrony_push_data("root_dispersion", DAEMON_NAME,
813 ntohf(chrony_resp.body.tracking.f_root_dispersion));
814 chrony_push_data("clock_last_update", DAEMON_NAME,
815 ntohf(chrony_resp.body.tracking.f_last_update_interval));
820 static int chrony_request_sources_count(unsigned int *p_count) {
821 /* Requests the number of time sources from the chrony daemon */
823 size_t chrony_resp_size;
824 tChrony_Request chrony_req;
825 tChrony_Response chrony_resp;
827 DEBUG(PLUGIN_NAME ": Requesting data");
828 chrony_init_req(&chrony_req);
830 chrony_query(REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
832 ERROR(PLUGIN_NAME ": chrony_query (REQ_N_SOURCES) failed with status %i",
837 *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
838 DEBUG(PLUGIN_NAME ": Getting data of %d clock sources", *p_count);
843 static int chrony_request_source_data(int p_src_idx, char *src_addr,
844 size_t addr_size, int *p_is_reachable) {
845 /* Perform Source data request for source #p_src_idx */
847 size_t chrony_resp_size;
848 tChrony_Request chrony_req;
849 tChrony_Response chrony_resp;
851 chrony_init_req(&chrony_req);
852 chrony_req.body.source_data.f_index = htonl(p_src_idx);
853 rc = chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp,
856 ERROR(PLUGIN_NAME ": chrony_query (REQ_SOURCE_DATA) failed with status %i",
861 if (ntohs(chrony_resp.body.source_data.f_mode) == MODE_REFCLOCK)
862 nreftostr(chrony_resp.body.source_data.addr.addr.ip4, src_addr, addr_size);
864 niptoha(&chrony_resp.body.source_data.addr, src_addr, addr_size);
866 DEBUG(PLUGIN_NAME ": Source[%d] data: .addr = %s, .poll = %u, .stratum = %u, "
867 ".state = %u, .mode = %u, .flags = %u, .reach = %u, "
868 ".latest_meas_ago = %u, .orig_latest_meas = %f, "
869 ".latest_meas = %f, .latest_meas_err = %f",
870 p_src_idx, src_addr, ntohs(chrony_resp.body.source_data.f_poll),
871 ntohs(chrony_resp.body.source_data.f_stratum),
872 ntohs(chrony_resp.body.source_data.f_state),
873 ntohs(chrony_resp.body.source_data.f_mode),
874 ntohs(chrony_resp.body.source_data.f_flags),
875 ntohs(chrony_resp.body.source_data.f_reachability),
876 ntohl(chrony_resp.body.source_data.f_since_sample),
877 ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
878 ntohf(chrony_resp.body.source_data.f_latest_meas),
879 ntohf(chrony_resp.body.source_data.f_latest_meas_err));
881 /* Push NaN if source is currently not reachable */
882 int is_reachable = ntohs(chrony_resp.body.source_data.f_reachability) & 0x01;
883 *p_is_reachable = is_reachable;
885 /* Forward results to collectd-daemon */
886 chrony_push_data_valid("clock_stratum", src_addr, is_reachable,
887 ntohs(chrony_resp.body.source_data.f_stratum));
888 chrony_push_data_valid("clock_state", src_addr, is_reachable,
889 ntohs(chrony_resp.body.source_data.f_state));
890 chrony_push_data_valid("clock_mode", src_addr, is_reachable,
891 ntohs(chrony_resp.body.source_data.f_mode));
892 chrony_push_data_valid("clock_reachability", src_addr, is_reachable,
893 ntohs(chrony_resp.body.source_data.f_reachability));
894 chrony_push_data_valid("clock_last_meas", src_addr, is_reachable,
895 ntohl(chrony_resp.body.source_data.f_since_sample));
896 chrony_push_data_valid(
897 "time_offset", src_addr, is_reachable,
898 ntohf(chrony_resp.body.source_data.f_origin_latest_meas));
903 static int chrony_request_source_stats(int p_src_idx, const char *src_addr,
904 const int *p_is_reachable) {
905 /* Perform Source stats request for source #p_src_idx */
907 size_t chrony_resp_size;
908 tChrony_Request chrony_req;
909 tChrony_Response chrony_resp;
910 double skew_ppm, frequency_error;
912 if (*p_is_reachable == 0) {
916 chrony_init_req(&chrony_req);
917 chrony_req.body.source_stats.f_index = htonl(p_src_idx);
918 rc = chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp,
922 ": chrony_query (REQ_SOURCE_STATS) failed with status %i",
927 skew_ppm = ntohf(chrony_resp.body.source_stats.f_skew_ppm);
928 frequency_error = ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm);
931 ": Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, "
932 ".n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, "
933 ".rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, "
934 ".est_offset_err = %f",
935 p_src_idx, src_addr, ntohl(chrony_resp.body.source_stats.f_ref_id),
936 ntohl(chrony_resp.body.source_stats.f_n_samples),
937 ntohl(chrony_resp.body.source_stats.f_n_runs),
938 ntohl(chrony_resp.body.source_stats.f_span_seconds),
939 ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
940 frequency_error, skew_ppm,
941 ntohf(chrony_resp.body.source_stats.f_est_offset),
942 ntohf(chrony_resp.body.source_stats.f_est_offset_err));
944 } /* if (*is_reachable) */
946 /* Forward results to collectd-daemon */
947 chrony_push_data_valid("clock_skew_ppm", src_addr, *p_is_reachable, skew_ppm);
948 chrony_push_data_valid("frequency_error", src_addr, *p_is_reachable,
949 frequency_error); /* unit: ppm */
954 static int chrony_read(void) {
955 /* collectd read callback: Perform data acquisition */
957 unsigned int n_sources;
959 if (g_chrony_seq_is_initialized == 0) {
960 /* Seed RNG for sequence number generation */
961 rc = chrony_init_seq();
962 if (rc != CHRONY_RC_OK)
965 g_chrony_seq_is_initialized = 1;
968 /* Get daemon stats */
969 rc = chrony_request_daemon_stats();
970 if (rc != CHRONY_RC_OK)
973 /* Get number of time sources, then check every source for status */
974 rc = chrony_request_sources_count(&n_sources);
975 if (rc != CHRONY_RC_OK)
978 for (unsigned int now_src = 0; now_src < n_sources; ++now_src) {
979 char src_addr[IPV6_STR_MAX_SIZE] = {0};
981 rc = chrony_request_source_data(now_src, src_addr, sizeof(src_addr),
983 if (rc != CHRONY_RC_OK)
986 rc = chrony_request_source_stats(now_src, src_addr, &is_reachable);
987 if (rc != CHRONY_RC_OK)
993 static int chrony_shutdown(void) {
994 /* Collectd shutdown callback: Free mem */
995 if (g_chrony_is_connected != 0) {
996 close(g_chrony_socket);
997 g_chrony_is_connected = 0;
999 if (g_chrony_host != NULL)
1000 sfree(g_chrony_host);
1002 if (g_chrony_port != NULL)
1003 sfree(g_chrony_port);
1005 if (g_chrony_plugin_instance != NULL)
1006 sfree(g_chrony_plugin_instance);
1008 return CHRONY_RC_OK;
1011 void module_register(void) {
1012 plugin_register_config(PLUGIN_NAME_SHORT, chrony_config, g_config_keys,
1014 plugin_register_read(PLUGIN_NAME_SHORT, chrony_read);
1015 plugin_register_shutdown(PLUGIN_NAME_SHORT, chrony_shutdown);