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 "plugin.h" /* plugin_register_*, plugin_dispatch_values */
32 #include "utils/common/common.h" /* auxiliary functions */
35 #include <netdb.h> /* struct addrinfo */
38 #include <arpa/inet.h> /* ntohs/ntohl */
41 /* AIX doesn't have MSG_DONTWAIT */
43 #define MSG_DONTWAIT MSG_NONBLOCK
46 #define CONFIG_KEY_HOST "Host"
47 #define CONFIG_KEY_PORT "Port"
48 #define CONFIG_KEY_TIMEOUT "Timeout"
50 #define URAND_DEVICE_PATH \
51 "/dev/urandom" /* Used to initialize seq nr generator */
52 #define RAND_DEVICE_PATH \
53 "/dev/random" /* Used to initialize seq nr generator (fall back) */
55 static const char *g_config_keys[] = {CONFIG_KEY_HOST, CONFIG_KEY_PORT,
58 static int g_config_keys_num = STATIC_ARRAY_SIZE(g_config_keys);
59 static int g_chrony_is_connected;
60 static int g_chrony_socket = -1;
61 static time_t g_chrony_timeout = -1;
62 static char *g_chrony_plugin_instance;
63 static char *g_chrony_host;
64 static char *g_chrony_port;
65 static uint32_t g_chrony_rand = 1;
66 static uint32_t g_chrony_seq_is_initialized;
68 #define PLUGIN_NAME_SHORT "chrony"
69 #define PLUGIN_NAME PLUGIN_NAME_SHORT " plugin"
70 #define DAEMON_NAME PLUGIN_NAME_SHORT
71 #define CHRONY_DEFAULT_HOST "localhost"
72 #define CHRONY_DEFAULT_PORT "323"
73 #define CHRONY_DEFAULT_TIMEOUT 2
75 /* Return codes (collectd expects non-zero on errors) */
76 #define CHRONY_RC_OK 0
77 #define CHRONY_RC_FAIL 1
79 /* Chronyd command packet variables adapted from chrony/candm.h (GPL2) */
80 #define PROTO_VERSION_NUMBER 6
81 #define IPADDR_UNSPEC 0
82 #define IPADDR_INET4 1
83 #define IPADDR_INET6 2
84 #define IPV6_STR_MAX_SIZE (8 * 4 + 7 + 1)
85 #define MODE_REFCLOCK 2
87 typedef enum { PKT_TYPE_CMD_REQUEST = 1, PKT_TYPE_CMD_REPLY = 2 } ePacketType;
100 RPY_MANUAL_TIMESTAMP = 4,
102 RPY_SOURCE_STATS = 6,
106 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(lint)
107 #/* extension to enforce struct packing. */
108 #define ATTRIB_PACKED __attribute__((packed))
110 #error Not defining packed attribute (unknown compiler)
111 #define ATTRIB_PACKED
114 typedef struct ATTRIB_PACKED {
118 typedef struct ATTRIB_PACKED {
119 uint32_t tv_sec_high;
129 STT_NOSUCHSOURCE = 4,
133 STT_ACCESSALLOWED = 8,
134 STT_ACCESSDENIED = 9,
135 STT_NOHOSTACCESS = 10,
136 STT_SOURCEALREADYKNOWN = 11,
137 STT_TOOMANYSOURCES = 12,
143 STT_BADPKTVERSION = 18,
144 STT_BADPKTLENGTH = 19
147 /* Chrony client request packets */
148 typedef struct ATTRIB_PACKED {
149 uint8_t f_dummy0[80]; /* Chrony expects 80bytes dummy data (Avoiding UDP
151 } tChrony_Req_Tracking;
153 typedef struct ATTRIB_PACKED {
154 uint32_t f_n_sources;
155 } tChrony_Req_N_Sources;
157 typedef struct ATTRIB_PACKED {
159 uint8_t f_dummy0[44];
160 } tChrony_Req_Source_data;
162 typedef struct ATTRIB_PACKED {
164 uint8_t f_dummy0[56];
165 } tChrony_Req_Source_stats;
167 typedef struct ATTRIB_PACKED {
179 } header; /* Packed: 20Bytes */
181 tChrony_Req_N_Sources n_sources;
182 tChrony_Req_Source_data source_data;
183 tChrony_Req_Source_stats source_stats;
184 tChrony_Req_Tracking tracking;
186 uint8_t padding[4 + 16]; /* Padding to match minimal response size */
189 /* Chrony daemon response packets */
190 typedef struct ATTRIB_PACKED {
191 uint32_t f_n_sources;
192 } tChrony_Resp_N_Sources;
194 typedef struct ATTRIB_PACKED {
203 typedef struct ATTRIB_PACKED {
205 int16_t f_poll; /* 2^f_poll = Time between polls (s) */
206 uint16_t f_stratum; /* Remote clock stratum */
207 uint16_t f_state; /* 0 = RPY_SD_ST_SYNC, 1 = RPY_SD_ST_UNREACH, 2 =
208 RPY_SD_ST_FALSETICKER */
209 /* 3 = RPY_SD_ST_JITTERY, 4 = RPY_SD_ST_CANDIDATE, 5 = RPY_SD_ST_OUTLIER */
210 uint16_t f_mode; /* 0 = RPY_SD_MD_CLIENT, 1 = RPY_SD_MD_PEER, 2 =
212 uint16_t f_flags; /* unused */
214 f_reachability; /* Bit mask of successfull tries to reach the source */
216 uint32_t f_since_sample; /* Time since last sample (s) */
217 tFloat f_origin_latest_meas; /* */
218 tFloat f_latest_meas; /* */
219 tFloat f_latest_meas_err; /* */
220 } tChrony_Resp_Source_data;
222 typedef struct ATTRIB_PACKED {
225 uint32_t f_n_samples; /* Number of measurements done */
226 uint32_t f_n_runs; /* How many measurements to come */
227 uint32_t f_span_seconds; /* For how long we're measuring */
228 tFloat f_rtc_seconds_fast; /* ??? */
229 tFloat f_rtc_gain_rate_ppm; /* Estimated relative frequency error */
230 tFloat f_skew_ppm; /* Clock skew (ppm) (worst case freq est error (skew:
232 tFloat f_est_offset; /* Estimated offset of source */
233 tFloat f_est_offset_err; /* Error of estimation */
234 } tChrony_Resp_Source_stats;
236 typedef struct ATTRIB_PACKED {
240 uint16_t f_leap_status;
242 tFloat f_current_correction;
243 tFloat f_last_offset;
246 tFloat f_resid_freq_ppm;
249 tFloat f_root_dispersion;
250 tFloat f_last_update_interval;
251 } tChrony_Resp_Tracking;
253 typedef struct ATTRIB_PACKED {
268 } header; /* Packed: 28 Bytes */
271 tChrony_Resp_N_Sources n_sources;
272 tChrony_Resp_Source_data source_data;
273 tChrony_Resp_Source_stats source_stats;
274 tChrony_Resp_Tracking tracking;
277 uint8_t padding[1024];
280 /*****************************************************************************/
281 /* Internal functions */
282 /*****************************************************************************/
284 /* connect_client code adapted from:
285 * http://long.ccaba.upc.edu/long/045Guidelines/eva/ipv6.html#daytimeClient6 */
286 /* License granted by Eva M Castro via e-mail on 2016-02-18 under the terms of
288 static int connect_client(const char *p_hostname, const char *p_service,
289 int p_family, int p_socktype) {
290 struct addrinfo *res, *ressave;
293 struct addrinfo ai_hints = {.ai_family = p_family, .ai_socktype = p_socktype};
295 n = getaddrinfo(p_hostname, p_service, &ai_hints, &res);
298 ERROR(PLUGIN_NAME ": getaddrinfo error:: [%s]", gai_strerror(n));
306 sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
309 if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0) {
320 freeaddrinfo(ressave);
324 /* niptoha code originally from:
325 * git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
326 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
327 /* Original name: char * UTI_IPToString(IPAddr *addr)*/
328 static char *niptoha(const tChrony_IPAddr *addr, char *p_buf,
331 unsigned long a, b, c, d, ip;
333 switch (ntohs(addr->f_family)) {
335 rc = snprintf(p_buf, p_buf_size, "[UNSPEC]");
338 ip = ntohl(addr->addr.ip4);
339 a = (ip >> 24) & 0xff;
340 b = (ip >> 16) & 0xff;
341 c = (ip >> 8) & 0xff;
342 d = (ip >> 0) & 0xff;
343 rc = snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
346 const char *rp = inet_ntop(AF_INET6, addr->addr.ip6, p_buf, p_buf_size);
348 ERROR(PLUGIN_NAME ": Error converting ipv6 address to string. Errno = %d",
350 rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
355 rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
361 static void nreftostr(uint32_t nrefid, char *p_buf, size_t p_buf_size) {
364 for (int i = 0; i < 4; i++) {
365 int c = ntohl(nrefid) << i * 8 >> 24;
366 if (!isalnum(c) || j + 1 >= p_buf_size)
374 static int chrony_set_timeout(void) {
375 /* Set the socket's timeout to g_chrony_timeout; a value of 0 signals
376 * infinite timeout */
377 /* Returns 0 on success, !0 on error (check errno) */
380 tv.tv_sec = g_chrony_timeout;
383 assert(g_chrony_socket >= 0);
384 if (setsockopt(g_chrony_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,
385 sizeof(struct timeval)) < 0) {
386 return CHRONY_RC_FAIL;
391 static int chrony_connect(void) {
392 /* Connects to the chrony daemon */
393 /* Returns 0 on success, !0 on error (check errno) */
396 if (g_chrony_host == NULL) {
397 g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
398 if (g_chrony_host == NULL) {
399 ERROR(PLUGIN_NAME ": Error duplicating chrony host name");
400 return CHRONY_RC_FAIL;
403 if (g_chrony_port == NULL) {
404 g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
405 if (g_chrony_port == NULL) {
406 ERROR(PLUGIN_NAME ": Error duplicating chrony port string");
407 return CHRONY_RC_FAIL;
410 if (g_chrony_timeout < 0) {
411 g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
412 assert(g_chrony_timeout >= 0);
415 DEBUG(PLUGIN_NAME ": Connecting to %s:%s", g_chrony_host, g_chrony_port);
416 socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
418 ERROR(PLUGIN_NAME ": Error connecting to daemon. Errno = %d", errno);
419 return CHRONY_RC_FAIL;
421 DEBUG(PLUGIN_NAME ": Connected");
422 g_chrony_socket = socket;
424 if (chrony_set_timeout()) {
425 ERROR(PLUGIN_NAME ": Error setting timeout to %llds. Errno = %d",
426 (long long)g_chrony_timeout, errno);
427 return CHRONY_RC_FAIL;
432 static int chrony_send_request(const tChrony_Request *p_req,
434 if (send(g_chrony_socket, p_req, p_req_size, 0) < 0) {
435 ERROR(PLUGIN_NAME ": Error sending packet. Errno = %d", errno);
436 return CHRONY_RC_FAIL;
441 static int chrony_recv_response(tChrony_Response *p_resp,
442 size_t p_resp_max_size, size_t *p_resp_size) {
443 ssize_t rc = recv(g_chrony_socket, p_resp, p_resp_max_size, 0);
445 ERROR(PLUGIN_NAME ": Error receiving packet: %s (%d)", strerror(errno),
447 return CHRONY_RC_FAIL;
454 static void chrony_flush_recv_queue(void) {
457 if (g_chrony_is_connected) {
458 while (recv(g_chrony_socket, buf, sizeof(buf), MSG_DONTWAIT) > 0)
463 static int chrony_query(const int p_command, tChrony_Request *p_req,
464 tChrony_Response *p_resp, size_t *p_resp_size) {
465 /* Check connection. We simply perform one try as collectd already handles
471 if (g_chrony_is_connected == 0) {
472 if (chrony_connect() == CHRONY_RC_OK) {
473 g_chrony_is_connected = 1;
475 ERROR(PLUGIN_NAME ": Unable to connect. Errno = %d", errno);
476 return CHRONY_RC_FAIL;
481 int valid_command = 0;
482 size_t req_size = sizeof(p_req->header) + sizeof(p_req->padding);
483 size_t resp_size = sizeof(p_resp->header);
484 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)
518 uint32_t seq_nr = rand_r(&g_chrony_rand);
519 p_req->header.f_cmd = htons(p_command);
520 p_req->header.f_cmd_try = 0;
521 p_req->header.f_seq = seq_nr;
523 DEBUG(PLUGIN_NAME ": Sending request (.cmd = %d, .seq = %d)", p_command,
525 if (chrony_send_request(p_req, req_size) != 0)
528 DEBUG(PLUGIN_NAME ": Waiting for response");
529 if (chrony_recv_response(p_resp, resp_size, p_resp_size) != 0)
532 DEBUG(PLUGIN_NAME ": Received response: .version = %u, .type = %u, .cmd = "
533 "%u, .reply = %u, .status = %u, .seq = %u",
534 p_resp->header.f_version, p_resp->header.f_type,
535 ntohs(p_resp->header.f_cmd), ntohs(p_resp->header.f_reply),
536 ntohs(p_resp->header.f_status), p_resp->header.f_seq);
538 if (p_resp->header.f_version != p_req->header.f_version) {
539 ERROR(PLUGIN_NAME ": Wrong protocol version (Was: %d, expected: %d)",
540 p_resp->header.f_version, p_req->header.f_version);
541 return CHRONY_RC_FAIL;
543 if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY) {
544 ERROR(PLUGIN_NAME ": Wrong packet type (Was: %d, expected: %d)",
545 p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
546 return CHRONY_RC_FAIL;
548 if (p_resp->header.f_seq != seq_nr) {
549 /* FIXME: Implement sequence number handling */
550 ERROR(PLUGIN_NAME ": Unexpected sequence number (Was: %d, expected: %d)",
551 p_resp->header.f_seq, p_req->header.f_seq);
552 return CHRONY_RC_FAIL;
554 if (p_resp->header.f_cmd != p_req->header.f_cmd) {
555 ERROR(PLUGIN_NAME ": Wrong reply command (Was: %d, expected: %d)",
556 p_resp->header.f_cmd, p_req->header.f_cmd);
557 return CHRONY_RC_FAIL;
560 if (ntohs(p_resp->header.f_reply) != resp_code) {
561 ERROR(PLUGIN_NAME ": Wrong reply code (Was: %d, expected: %d)",
562 ntohs(p_resp->header.f_reply), resp_code);
563 return CHRONY_RC_FAIL;
566 switch (p_resp->header.f_status) {
568 DEBUG(PLUGIN_NAME ": Reply packet status STT_SUCCESS");
572 ": Reply packet contains error status: %d (expected: %d)",
573 p_resp->header.f_status, STT_SUCCESS);
574 return CHRONY_RC_FAIL;
581 /* Some error occured */
582 return CHRONY_RC_FAIL;
585 static void chrony_init_req(tChrony_Request *p_req) {
586 memset(p_req, 0, sizeof(*p_req));
587 p_req->header.f_version = PROTO_VERSION_NUMBER;
588 p_req->header.f_type = PKT_TYPE_CMD_REQUEST;
589 p_req->header.f_dummy0 = 0;
590 p_req->header.f_dummy1 = 0;
591 p_req->header.f_dummy2 = 0;
592 p_req->header.f_dummy3 = 0;
595 /* ntohf code originally from:
596 * git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
597 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
598 /* Original name: double UTI_tFloatNetworkToHost(tFloat f) */
599 static double ntohf(tFloat p_float) {
600 /* Convert tFloat in Network-bit-order to double in host-bit-order */
602 #define FLOAT_EXP_BITS 7
603 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
604 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
605 #define FLOAT_COEF_BITS ((int)sizeof(int32_t) * 8 - FLOAT_EXP_BITS)
606 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
607 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
612 uval = ntohl(p_float.value);
613 exp = (uval >> FLOAT_COEF_BITS);
614 if (exp >= 1 << (FLOAT_EXP_BITS - 1))
615 exp -= 1 << FLOAT_EXP_BITS;
616 exp -= FLOAT_COEF_BITS;
618 /* coef = (x << FLOAT_EXP_BITS) >> FLOAT_EXP_BITS; */
619 coef = uval % (1U << FLOAT_COEF_BITS);
620 if (coef >= 1 << (FLOAT_COEF_BITS - 1))
621 coef -= 1 << FLOAT_COEF_BITS;
623 return coef * pow(2.0, exp);
626 static void chrony_push_data(const char *p_type, const char *p_type_inst,
628 value_list_t vl = VALUE_LIST_INIT;
630 vl.values = &(value_t){.gauge = p_value};
633 /* XXX: Shall g_chrony_host/g_chrony_port be reflected in the plugin's output?
635 sstrncpy(vl.plugin, PLUGIN_NAME_SHORT, sizeof(vl.plugin));
636 if (g_chrony_plugin_instance != NULL) {
637 sstrncpy(vl.plugin_instance, g_chrony_plugin_instance,
638 sizeof(vl.plugin_instance));
641 sstrncpy(vl.type, p_type, sizeof(vl.type));
643 if (p_type_inst != NULL)
644 sstrncpy(vl.type_instance, p_type_inst, sizeof(vl.type_instance));
646 plugin_dispatch_values(&vl);
649 static void chrony_push_data_valid(const char *p_type, const char *p_type_inst,
650 const int p_is_valid, double p_value) {
651 /* Push real value if p_is_valid is true, push NAN if p_is_valid is not true
652 * (idea from ntp plugin) */
656 chrony_push_data(p_type, p_type_inst, p_value);
659 static int chrony_init_seq(void) {
660 /* Initialize the sequence number generator from /dev/urandom */
661 /* Fallbacks: /dev/random and time(NULL) */
666 fh = open(URAND_DEVICE_PATH, O_RDONLY);
668 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
669 if (rc != sizeof(g_chrony_rand)) {
670 ERROR(PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)",
671 URAND_DEVICE_PATH, strerror(errno), errno);
673 return CHRONY_RC_FAIL;
676 DEBUG(PLUGIN_NAME ": Seeding RNG from " URAND_DEVICE_PATH);
678 if (errno == ENOENT) {
679 /* URAND_DEVICE_PATH device not found. Try RAND_DEVICE_PATH as fall-back
681 fh = open(RAND_DEVICE_PATH, O_RDONLY);
683 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
684 if (rc != sizeof(g_chrony_rand)) {
686 ": Reading from random source \'%s\'failed: %s (%d)",
687 RAND_DEVICE_PATH, strerror(errno), errno);
689 return CHRONY_RC_FAIL;
692 DEBUG(PLUGIN_NAME ": Seeding RNG from " RAND_DEVICE_PATH);
694 /* Error opening RAND_DEVICE_PATH. Try time(NULL) as fall-back */
695 DEBUG(PLUGIN_NAME ": Seeding RNG from time(NULL)");
696 g_chrony_rand = time(NULL) ^ getpid();
699 ERROR(PLUGIN_NAME ": Opening random source \'%s\' failed: %s (%d)",
700 URAND_DEVICE_PATH, strerror(errno), errno);
701 return CHRONY_RC_FAIL;
708 /*****************************************************************************/
709 /* Exported functions */
710 /*****************************************************************************/
711 static int chrony_config(const char *p_key, const char *p_value) {
715 /* Parse config variables */
716 if (strcasecmp(p_key, CONFIG_KEY_HOST) == 0) {
717 if (g_chrony_host != NULL)
720 if ((g_chrony_host = strdup(p_value)) == NULL) {
721 ERROR(PLUGIN_NAME ": Error duplicating host name");
722 return CHRONY_RC_FAIL;
725 if (strcasecmp(p_key, CONFIG_KEY_PORT) == 0) {
726 if (g_chrony_port != NULL)
729 if ((g_chrony_port = strdup(p_value)) == NULL) {
730 ERROR(PLUGIN_NAME ": Error duplicating port name");
731 return CHRONY_RC_FAIL;
734 if (strcasecmp(p_key, CONFIG_KEY_TIMEOUT) == 0) {
735 time_t tosec = strtol(p_value, NULL, 0);
736 g_chrony_timeout = tosec;
738 WARNING(PLUGIN_NAME ": Unknown configuration variable: %s %s", p_key,
740 return CHRONY_RC_FAIL;
744 /* XXX: We could set g_chrony_plugin_instance here to
745 * "g_chrony_host-g_chrony_port", but as multiple instances aren't yet
746 * supported, we skip this for now */
751 static int chrony_request_daemon_stats(void) {
752 /* Perform Tracking request */
754 size_t chrony_resp_size;
755 tChrony_Request chrony_req;
756 tChrony_Response chrony_resp;
758 chrony_init_req(&chrony_req);
759 rc = chrony_query(REQ_TRACKING, &chrony_req, &chrony_resp, &chrony_resp_size);
761 ERROR(PLUGIN_NAME ": chrony_query (REQ_TRACKING) failed with status %i",
767 char src_addr[IPV6_STR_MAX_SIZE] = {0};
768 niptoha(&chrony_resp.body.tracking.addr, src_addr, sizeof(src_addr));
770 ": Daemon stat: .addr = %s, .ref_id= %u, .stratum = %u, .leap_status "
771 "= %u, .ref_time = %u:%u:%u, .current_correction = %f, .last_offset "
772 "= %f, .rms_offset = %f, .freq_ppm = %f, .skew_ppm = %f, .root_delay "
773 "= %f, .root_dispersion = %f, .last_update_interval = %f",
774 src_addr, ntohs(chrony_resp.body.tracking.f_ref_id),
775 ntohs(chrony_resp.body.tracking.f_stratum),
776 ntohs(chrony_resp.body.tracking.f_leap_status),
777 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high),
778 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low),
779 ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec),
780 ntohf(chrony_resp.body.tracking.f_current_correction),
781 ntohf(chrony_resp.body.tracking.f_last_offset),
782 ntohf(chrony_resp.body.tracking.f_rms_offset),
783 ntohf(chrony_resp.body.tracking.f_freq_ppm),
784 ntohf(chrony_resp.body.tracking.f_skew_ppm),
785 ntohf(chrony_resp.body.tracking.f_root_delay),
786 ntohf(chrony_resp.body.tracking.f_root_dispersion),
787 ntohf(chrony_resp.body.tracking.f_last_update_interval));
791 double time_ref = ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec);
792 time_ref /= 1000000000.0;
793 time_ref += ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low);
794 if (chrony_resp.body.tracking.f_ref_time.tv_sec_high) {
795 double secs_high = ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high);
796 secs_high *= 4294967296.0;
797 time_ref += secs_high;
800 /* Forward results to collectd-daemon */
801 /* Type_instance is always 'chrony' to tag daemon-wide data */
802 /* Type Type_instan Value */
803 chrony_push_data("clock_stratum", DAEMON_NAME,
804 ntohs(chrony_resp.body.tracking.f_stratum));
805 chrony_push_data("time_ref", DAEMON_NAME, time_ref); /* unit: s */
807 "time_offset_ntp", DAEMON_NAME,
808 ntohf(chrony_resp.body.tracking.f_current_correction)); /* Offset between
812 "time_offset", DAEMON_NAME,
814 chrony_resp.body.tracking
815 .f_last_offset)); /* Estimated Offset of the NTP time, unit: s */
817 "time_offset_rms", DAEMON_NAME,
818 ntohf(chrony_resp.body.tracking
819 .f_rms_offset)); /* averaged value of the above, unit: s */
821 "frequency_error", DAEMON_NAME,
822 ntohf(chrony_resp.body.tracking
823 .f_freq_ppm)); /* Frequency error of the local osc, unit: ppm */
824 chrony_push_data("clock_skew_ppm", DAEMON_NAME,
825 ntohf(chrony_resp.body.tracking.f_skew_ppm));
827 "root_delay", DAEMON_NAME,
828 ntohf(chrony_resp.body.tracking.f_root_delay)); /* Network latency between
831 chrony_push_data("root_dispersion", DAEMON_NAME,
832 ntohf(chrony_resp.body.tracking.f_root_dispersion));
833 chrony_push_data("clock_last_update", DAEMON_NAME,
834 ntohf(chrony_resp.body.tracking.f_last_update_interval));
839 static int chrony_request_sources_count(unsigned int *p_count) {
840 /* Requests the number of time sources from the chrony daemon */
842 size_t chrony_resp_size;
843 tChrony_Request chrony_req;
844 tChrony_Response chrony_resp;
846 DEBUG(PLUGIN_NAME ": Requesting data");
847 chrony_init_req(&chrony_req);
849 chrony_query(REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
851 ERROR(PLUGIN_NAME ": chrony_query (REQ_N_SOURCES) failed with status %i",
856 *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
857 DEBUG(PLUGIN_NAME ": Getting data of %d clock sources", *p_count);
862 static int chrony_request_source_data(int p_src_idx, char *src_addr,
863 size_t addr_size, int *p_is_reachable) {
864 /* Perform Source data request for source #p_src_idx */
866 size_t chrony_resp_size;
867 tChrony_Request chrony_req;
868 tChrony_Response chrony_resp;
870 chrony_init_req(&chrony_req);
871 chrony_req.body.source_data.f_index = htonl(p_src_idx);
872 rc = chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp,
875 ERROR(PLUGIN_NAME ": chrony_query (REQ_SOURCE_DATA) failed with status %i",
880 if (ntohs(chrony_resp.body.source_data.f_mode) == MODE_REFCLOCK)
881 nreftostr(chrony_resp.body.source_data.addr.addr.ip4, src_addr, addr_size);
883 niptoha(&chrony_resp.body.source_data.addr, src_addr, addr_size);
885 DEBUG(PLUGIN_NAME ": Source[%d] data: .addr = %s, .poll = %u, .stratum = %u, "
886 ".state = %u, .mode = %u, .flags = %u, .reach = %u, "
887 ".latest_meas_ago = %u, .orig_latest_meas = %f, "
888 ".latest_meas = %f, .latest_meas_err = %f",
889 p_src_idx, src_addr, ntohs(chrony_resp.body.source_data.f_poll),
890 ntohs(chrony_resp.body.source_data.f_stratum),
891 ntohs(chrony_resp.body.source_data.f_state),
892 ntohs(chrony_resp.body.source_data.f_mode),
893 ntohs(chrony_resp.body.source_data.f_flags),
894 ntohs(chrony_resp.body.source_data.f_reachability),
895 ntohl(chrony_resp.body.source_data.f_since_sample),
896 ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
897 ntohf(chrony_resp.body.source_data.f_latest_meas),
898 ntohf(chrony_resp.body.source_data.f_latest_meas_err));
900 /* Push NaN if source is currently not reachable */
901 int is_reachable = ntohs(chrony_resp.body.source_data.f_reachability) & 0x01;
902 *p_is_reachable = is_reachable;
904 /* Forward results to collectd-daemon */
905 chrony_push_data_valid("clock_stratum", src_addr, is_reachable,
906 ntohs(chrony_resp.body.source_data.f_stratum));
907 chrony_push_data_valid("clock_state", src_addr, is_reachable,
908 ntohs(chrony_resp.body.source_data.f_state));
909 chrony_push_data_valid("clock_mode", src_addr, is_reachable,
910 ntohs(chrony_resp.body.source_data.f_mode));
911 chrony_push_data_valid("clock_reachability", src_addr, is_reachable,
912 ntohs(chrony_resp.body.source_data.f_reachability));
913 chrony_push_data_valid("clock_last_meas", src_addr, is_reachable,
914 ntohl(chrony_resp.body.source_data.f_since_sample));
915 chrony_push_data_valid(
916 "time_offset", src_addr, is_reachable,
917 ntohf(chrony_resp.body.source_data.f_origin_latest_meas));
922 static int chrony_request_source_stats(int p_src_idx, const char *src_addr,
923 const int *p_is_reachable) {
924 /* Perform Source stats request for source #p_src_idx */
926 size_t chrony_resp_size;
927 tChrony_Request chrony_req;
928 tChrony_Response chrony_resp;
929 double skew_ppm, frequency_error;
931 if (*p_is_reachable == 0) {
935 chrony_init_req(&chrony_req);
936 chrony_req.body.source_stats.f_index = htonl(p_src_idx);
937 rc = chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp,
941 ": chrony_query (REQ_SOURCE_STATS) failed with status %i",
946 skew_ppm = ntohf(chrony_resp.body.source_stats.f_skew_ppm);
947 frequency_error = ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm);
950 ": Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, "
951 ".n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, "
952 ".rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, "
953 ".est_offset_err = %f",
954 p_src_idx, src_addr, ntohl(chrony_resp.body.source_stats.f_ref_id),
955 ntohl(chrony_resp.body.source_stats.f_n_samples),
956 ntohl(chrony_resp.body.source_stats.f_n_runs),
957 ntohl(chrony_resp.body.source_stats.f_span_seconds),
958 ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
959 frequency_error, skew_ppm,
960 ntohf(chrony_resp.body.source_stats.f_est_offset),
961 ntohf(chrony_resp.body.source_stats.f_est_offset_err));
963 } /* if (*is_reachable) */
965 /* Forward results to collectd-daemon */
966 chrony_push_data_valid("clock_skew_ppm", src_addr, *p_is_reachable, skew_ppm);
967 chrony_push_data_valid("frequency_error", src_addr, *p_is_reachable,
968 frequency_error); /* unit: ppm */
973 static int chrony_read(void) {
974 /* collectd read callback: Perform data acquisition */
976 unsigned int n_sources;
978 if (g_chrony_seq_is_initialized == 0) {
979 /* Seed RNG for sequence number generation */
980 rc = chrony_init_seq();
981 if (rc != CHRONY_RC_OK)
984 g_chrony_seq_is_initialized = 1;
987 /* Ignore late responses that may have been received */
988 chrony_flush_recv_queue();
990 /* Get daemon stats */
991 rc = chrony_request_daemon_stats();
992 if (rc != CHRONY_RC_OK)
995 /* Get number of time sources, then check every source for status */
996 rc = chrony_request_sources_count(&n_sources);
997 if (rc != CHRONY_RC_OK)
1000 for (unsigned int now_src = 0; now_src < n_sources; ++now_src) {
1001 char src_addr[IPV6_STR_MAX_SIZE] = {0};
1003 rc = chrony_request_source_data(now_src, src_addr, sizeof(src_addr),
1005 if (rc != CHRONY_RC_OK)
1008 rc = chrony_request_source_stats(now_src, src_addr, &is_reachable);
1009 if (rc != CHRONY_RC_OK)
1012 return CHRONY_RC_OK;
1015 static int chrony_shutdown(void) {
1016 /* Collectd shutdown callback: Free mem */
1017 if (g_chrony_is_connected != 0) {
1018 close(g_chrony_socket);
1019 g_chrony_is_connected = 0;
1021 if (g_chrony_host != NULL)
1022 sfree(g_chrony_host);
1024 if (g_chrony_port != NULL)
1025 sfree(g_chrony_port);
1027 if (g_chrony_plugin_instance != NULL)
1028 sfree(g_chrony_plugin_instance);
1030 return CHRONY_RC_OK;
1033 void module_register(void) {
1034 plugin_register_config(PLUGIN_NAME_SHORT, chrony_config, g_config_keys,
1036 plugin_register_read(PLUGIN_NAME_SHORT, chrony_read);
1037 plugin_register_shutdown(PLUGIN_NAME_SHORT, chrony_shutdown);