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> /* getaddrinfo */
18 # include <sys/socket.h>
24 # include <arpa/inet.h> /* ntohs/ntohl */
28 #include "common.h" /* auxiliary functions */
29 #include "plugin.h" /* plugin_register_*, plugin_dispatch_values */
31 #define CONFIG_KEY_HOST "Host"
32 #define CONFIG_KEY_PORT "Port"
33 #define CONFIG_KEY_TIMEOUT "Timeout"
35 #define URAND_DEVICE_PATH "/dev/urandom" /* Used to initialize seq nr generator*/
36 #define RAND_DEVICE_PATH "/dev/random" /* Used to initialize seq nr generator (fall back)*/
38 static const char *g_config_keys[] =
45 static int g_config_keys_num = STATIC_ARRAY_SIZE (g_config_keys);
46 static int g_is_connected = 0;
47 static int g_chrony_socket = -1;
48 static time_t g_chrony_timeout = -1;
49 static char *g_chrony_host = NULL;
50 static char *g_chrony_port = NULL;
51 static char *g_plugin_instance = NULL;
52 static uint32_t g_chrony_rand = 1;
53 static uint32_t g_chrony_seq_is_initialized = 0;
55 #define PLUGIN_NAME_SHORT "chrony"
56 #define PLUGIN_NAME PLUGIN_NAME_SHORT " plugin"
57 #define DAEMON_NAME PLUGIN_NAME_SHORT
58 #define CHRONY_DEFAULT_HOST "localhost"
59 #define CHRONY_DEFAULT_PORT "323"
60 #define CHRONY_DEFAULT_TIMEOUT 2
62 /* Return codes (collectd expects non-zero on errors) */
63 #define CHRONY_RC_OK 0
64 #define CHRONY_RC_FAIL 1
66 /* Variables adapted from chrony/candm.h (GPL2)*/
68 #define PROTO_VERSION_NUMBER 6
69 #define IPADDR_UNSPEC 0
70 #define IPADDR_INET4 1
71 #define IPADDR_INET6 2
72 #define IPV6_STR_MAX_SIZE (8*4+7+1)
76 PKT_TYPE_CMD_REQUEST = 1,
77 PKT_TYPE_CMD_REPLY = 2
94 RPY_MANUAL_TIMESTAMP = 4,
100 #define ATTRIB_PACKED __attribute__((packed))
101 typedef struct ATTRIB_PACKED
106 typedef struct ATTRIB_PACKED
108 uint32_t tv_sec_high;
120 STT_NOSUCHSOURCE = 4,
124 STT_ACCESSALLOWED = 8,
125 STT_ACCESSDENIED = 9,
126 STT_NOHOSTACCESS = 10,
127 STT_SOURCEALREADYKNOWN = 11,
128 STT_TOOMANYSOURCES = 12,
134 STT_BADPKTVERSION = 18,
135 STT_BADPKTLENGTH = 19
138 /* Chrony client request packets */
139 typedef struct ATTRIB_PACKED
141 uint8_t f_dummy0[80]; //Chrony expects 80bytes dummy data (Avoiding UDP Amplification)
142 } tChrony_Req_Tracking;
144 typedef struct ATTRIB_PACKED
146 uint32_t f_n_sources;
147 } tChrony_Req_N_Sources;
149 typedef struct ATTRIB_PACKED
152 uint8_t f_dummy0[44];
153 } tChrony_Req_Source_data;
155 typedef struct ATTRIB_PACKED
158 uint8_t f_dummy0[56];
159 } tChrony_Req_Source_stats;
161 typedef struct ATTRIB_PACKED
175 } header; /* Packed: 20Bytes */
178 tChrony_Req_N_Sources n_sources;
179 tChrony_Req_Source_data source_data;
180 tChrony_Req_Source_stats source_stats;
181 tChrony_Req_Tracking tracking;
183 uint8_t padding[4+16]; /* Padding to match minimal response size */
186 /* Chrony daemon response packets */
187 typedef struct ATTRIB_PACKED
189 uint32_t f_n_sources;
190 } tChrony_Resp_N_Sources;
192 typedef struct ATTRIB_PACKED
202 typedef struct ATTRIB_PACKED
205 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3/clang 3.4.1 on x86_64 */
206 int16_t f_poll; /* 2^f_poll = Time between polls (s) */
207 uint16_t f_stratum; /* Remote clock stratum */
208 uint16_t f_state; /* 0 = RPY_SD_ST_SYNC, 1 = RPY_SD_ST_UNREACH, 2 = 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 = RPY_SD_MD_REF */
211 uint16_t f_flags; /* unused */
212 uint16_t f_reachability; /* Bit mask of successfull tries to reach the source */
214 uint32_t f_since_sample; /* Time since last sample (s) */
215 tFloat f_origin_latest_meas; /* */
216 tFloat f_latest_meas; /* */
217 tFloat f_latest_meas_err; /* */
218 } tChrony_Resp_Source_data;
220 typedef struct ATTRIB_PACKED
224 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3/clang 3.4.1 on x86_64 */
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: peak2peak)) */
231 tFloat f_est_offset; /* Estimated offset of source */
232 tFloat f_est_offset_err; /* Error of estimation */
233 } tChrony_Resp_Source_stats;
235 typedef struct ATTRIB_PACKED
239 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3/clang 3.4.1 on x86_64 */
241 uint16_t f_leap_status;
243 tFloat f_current_correction;
244 tFloat f_last_offset;
247 tFloat f_resid_freq_ppm;
250 tFloat f_root_dispersion;
251 tFloat f_last_update_interval;
252 } tChrony_Resp_Tracking;
254 typedef struct ATTRIB_PACKED
271 } header; /* Packed: 28 Bytes */
275 tChrony_Resp_N_Sources n_sources;
276 tChrony_Resp_Source_data source_data;
277 tChrony_Resp_Source_stats source_stats;
278 tChrony_Resp_Tracking tracking;
281 uint8_t padding[1024];
285 /*****************************************************************************/
286 /* Internal functions */
287 /*****************************************************************************/
288 /* Code adapted from: http://long.ccaba.upc.edu/long/045Guidelines/eva/ipv6.html#daytimeClient6 */
290 static int connect_client (const char *p_hostname,
291 const char *p_service,
295 struct addrinfo hints, *res=NULL, *ressave=NULL;
298 memset(&hints, 0, sizeof(struct addrinfo));
300 hints.ai_family = p_family;
301 hints.ai_socktype = p_socktype;
303 n = getaddrinfo(p_hostname, p_service, &hints, &res);
307 ERROR (PLUGIN_NAME ": getaddrinfo error:: [%s]", gai_strerror(n));
316 sockfd = socket(res->ai_family,
322 if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
334 freeaddrinfo(ressave);
338 /*Code originally from: git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
339 /*char * UTI_IPToString(IPAddr *addr)*/
340 static char * niptoha(const tChrony_IPAddr *addr,char *p_buf, size_t p_buf_size)
343 unsigned long a, b, c, d, ip;
346 switch (ntohs(addr->f_family))
349 rc=snprintf(p_buf, p_buf_size, "[UNSPEC]");
352 ip = ntohl(addr->addr.ip4);
357 rc=snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
360 ip6 = addr->addr.ip6;
363 rc=inet_ntop(AF_INET6, ip6, p_buf, p_bug_size);
365 #if defined(BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
366 rc=snprintf(p_buf, p_buf_size, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
367 ip6[15], ip6[14], ip6[13], ip6[12], ip6[11], ip6[10], ip6[9], ip6[8],
368 ip6[7], ip6[6], ip6[5], ip6[4], ip6[3], ip6[2], ip6[1], ip6[0]);
370 rc=snprintf(p_buf, p_buf_size, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
371 ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7],
372 ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15]);
377 rc=snprintf(p_buf, p_buf_size, "[UNKNOWN]");
384 static int chrony_set_timeout()
386 /*Set the socket's timeout to g_chrony_timeout; a value of 0 signals infinite timeout*/
387 /*Returns 0 on success, !0 on error (check errno)*/
390 tv.tv_sec = g_chrony_timeout;
393 assert(g_chrony_socket>=0);
394 if (setsockopt(g_chrony_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval)) < 0)
396 return CHRONY_RC_FAIL;
401 static int chrony_connect()
403 /*Connects to the chrony daemon*/
404 /*Returns 0 on success, !0 on error (check errno)*/
407 if (g_chrony_host == NULL)
409 g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
410 assert(g_chrony_host);
412 if (g_chrony_port == NULL)
414 g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
415 assert(g_chrony_port);
417 if (g_chrony_timeout < 0)
419 g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
420 assert(g_chrony_timeout>=0);
424 DEBUG(PLUGIN_NAME ": Connecting to %s:%s", g_chrony_host, g_chrony_port);
425 socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
428 ERROR (PLUGIN_NAME ": Error connecting to daemon. Errno = %d", errno);
429 return CHRONY_RC_FAIL;
431 DEBUG(PLUGIN_NAME ": Connected");
432 g_chrony_socket = socket;
434 if (chrony_set_timeout())
436 ERROR (PLUGIN_NAME ": Error setting timeout to %lds. Errno = %d", g_chrony_timeout, errno);
437 return CHRONY_RC_FAIL;
442 static int chrony_send_request(const tChrony_Request *p_req, size_t p_req_size)
444 if (send(g_chrony_socket,p_req,p_req_size,0) < 0)
446 ERROR (PLUGIN_NAME ": Error sending packet. Errno = %d", errno);
447 return CHRONY_RC_FAIL;
452 static int chrony_recv_response(tChrony_Response *p_resp, size_t p_resp_max_size, size_t *p_resp_size)
454 ssize_t rc = recv(g_chrony_socket,p_resp,p_resp_max_size,0);
457 ERROR (PLUGIN_NAME ": Error receiving packet: %s (%d)", strerror(errno), errno);
458 return CHRONY_RC_FAIL;
465 static int chrony_query(const int p_command, tChrony_Request *p_req, tChrony_Response *p_resp, size_t *p_resp_size)
467 /* Check connection. We simply perform one try as collectd already handles retries */
472 if (g_is_connected == 0)
474 if (chrony_connect() == 0)
478 ERROR (PLUGIN_NAME ": Unable to connect. Errno = %d", errno);
479 return CHRONY_RC_FAIL;
486 int valid_command = 0;
487 size_t req_size = sizeof(p_req->header) + sizeof(p_req->padding);
488 size_t resp_size = sizeof(p_resp->header);
489 uint16_t resp_code = RPY_NULL;
493 req_size += sizeof(p_req->body.tracking);
494 resp_size += sizeof(p_resp->body.tracking);
495 resp_code = RPY_TRACKING;
499 req_size += sizeof(p_req->body.n_sources);
500 resp_size += sizeof(p_resp->body.n_sources);
501 resp_code = RPY_N_SOURCES;
504 case REQ_SOURCE_DATA:
505 req_size += sizeof(p_req->body.source_data);
506 resp_size += sizeof(p_resp->body.source_data);
507 resp_code = RPY_SOURCE_DATA;
510 case REQ_SOURCE_STATS:
511 req_size += sizeof(p_req->body.source_stats);
512 resp_size += sizeof(p_resp->body.source_stats);
513 resp_code = RPY_SOURCE_STATS;
517 ERROR (PLUGIN_NAME ": Unknown request command (Was: %d)", p_command);
521 if (valid_command == 0)
526 uint32_t seq_nr = rand_r(&g_chrony_rand);
527 p_req->header.f_cmd = htons(p_command);
528 p_req->header.f_cmd_try = 0;
529 p_req->header.f_seq = seq_nr;
531 DEBUG(PLUGIN_NAME ": Sending request (.cmd = %d, .seq = %d)",p_command, seq_nr);
532 if (chrony_send_request(p_req,req_size) != 0)
537 DEBUG(PLUGIN_NAME ": Waiting for response");
538 if (chrony_recv_response(p_resp,resp_size,p_resp_size) != 0)
542 DEBUG(PLUGIN_NAME ": Received response: .version = %u, .type = %u, .cmd = %u, .reply = %u, .status = %u, .seq = %u",
543 p_resp->header.f_version, p_resp->header.f_type, ntohs(p_resp->header.f_cmd),
544 ntohs(p_resp->header.f_reply), ntohs(p_resp->header.f_status), p_resp->header.f_seq);
546 if (p_resp->header.f_version != p_req->header.f_version)
548 ERROR(PLUGIN_NAME ": Wrong protocol version (Was: %d, expected: %d)", p_resp->header.f_version, p_req->header.f_version);
549 return CHRONY_RC_FAIL;
551 if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY)
553 ERROR(PLUGIN_NAME ": Wrong packet type (Was: %d, expected: %d)", p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
554 return CHRONY_RC_FAIL;
556 if (p_resp->header.f_seq != seq_nr)
558 /* FIXME: Implement sequence number handling */
559 ERROR(PLUGIN_NAME ": Unexpected sequence number (Was: %d, expected: %d)", p_resp->header.f_seq, p_req->header.f_seq);
560 return CHRONY_RC_FAIL;
562 if (p_resp->header.f_cmd != p_req->header.f_cmd)
564 ERROR(PLUGIN_NAME ": Wrong reply command (Was: %d, expected: %d)", p_resp->header.f_cmd, p_req->header.f_cmd);
565 return CHRONY_RC_FAIL;
568 if (ntohs(p_resp->header.f_reply) != resp_code)
570 ERROR(PLUGIN_NAME ": Wrong reply code (Was: %d, expected: %d)", ntohs(p_resp->header.f_reply), resp_code);
571 return CHRONY_RC_FAIL;
574 switch (p_resp->header.f_status)
577 DEBUG(PLUGIN_NAME ": Reply packet status STT_SUCCESS");
580 ERROR(PLUGIN_NAME ": Reply packet contains error status: %d (expected: %d)", p_resp->header.f_status, STT_SUCCESS);
581 return CHRONY_RC_FAIL;
588 /* Some error occured */
589 return CHRONY_RC_FAIL;
592 static void chrony_init_req(tChrony_Request *p_req)
594 memset(p_req,0,sizeof(*p_req));
595 p_req->header.f_version = PROTO_VERSION_NUMBER;
596 p_req->header.f_type = PKT_TYPE_CMD_REQUEST;
597 p_req->header.f_dummy0 = 0;
598 p_req->header.f_dummy1 = 0;
599 p_req->header.f_dummy2 = 0;
600 p_req->header.f_dummy3 = 0;
603 /* Code from: git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c (GPLv2) */
605 #define FLOAT_EXP_BITS 7
606 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
607 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
608 #define FLOAT_COEF_BITS ((int)sizeof (int32_t) * 8 - FLOAT_EXP_BITS)
609 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
610 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
612 /* double UTI_tFloatNetworkToHost(tFloat f) */
613 static double ntohf(tFloat p_float)
615 /* Convert tFloat in Network-bit-order to double in host-bit-order */
620 uval = ntohl(p_float.value);
621 exp = (uval >> FLOAT_COEF_BITS) - FLOAT_COEF_BITS;
622 if (exp >= 1 << (FLOAT_EXP_BITS - 1))
624 exp -= 1 << FLOAT_EXP_BITS;
627 /* coef = (x << FLOAT_EXP_BITS) >> FLOAT_EXP_BITS; */
628 coef = uval % (1U << FLOAT_COEF_BITS);
629 if (coef >= 1 << (FLOAT_COEF_BITS - 1))
631 coef -= 1 << FLOAT_COEF_BITS;
633 return coef * pow(2.0, exp);
637 static void chrony_push_data(char *p_type, char *p_type_inst, double p_value)
640 value_list_t vl = VALUE_LIST_INIT;
642 values[0].gauge = p_value; /* TODO: Check type??? (counter, gauge, derive, absolute) */
647 /* XXX: Shall g_chrony_host/g_chrony_port be reflected in the plugin's output? */
648 /* hostname_g is set in daemon/collectd.c (from config, via gethostname or by resolving localhost) */
649 /* defined as: char hostname_g[DATA_MAX_NAME_LEN]; (never NULL) */
650 { sstrncpy (vl.host, hostname_g, sizeof (vl.host)); }
651 { sstrncpy (vl.plugin, PLUGIN_NAME_SHORT, sizeof (vl.plugin)); }
652 if (g_plugin_instance != NULL) { sstrncpy (vl.plugin_instance, g_plugin_instance, sizeof (vl.plugin_instance)); }
653 if (p_type != NULL) { sstrncpy (vl.type, p_type, sizeof (vl.type)); }
654 if (p_type_inst != NULL) { sstrncpy (vl.type_instance, p_type_inst, sizeof (vl.type_instance)); }
656 plugin_dispatch_values (&vl);
660 static void chrony_push_data_valid(char *p_type, char *p_type_inst, const int p_is_valid, double p_value)
662 /* Push real value if p_is_valid is true, push NAN if p_is_valid is not true (idea from ntp plugin)*/
667 chrony_push_data(p_type, p_type_inst, p_value);
671 static int chrony_init_seq()
673 /* Initialize the sequence number generator from /dev/urandom */
676 int fh = open(URAND_DEVICE_PATH, O_RDONLY);
679 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
680 if (rc != sizeof(g_chrony_rand))
682 ERROR (PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)", URAND_DEVICE_PATH, strerror(errno), errno);
684 return CHRONY_RC_FAIL;
687 DEBUG(PLUGIN_NAME ": Seeding RNG from " URAND_DEVICE_PATH);
691 /* URAND_DEVICE_PATH device not found. Try RAND_DEVICE_PATH as fall-back */
692 int fh = open(RAND_DEVICE_PATH, O_RDONLY);
695 ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
696 if (rc != sizeof(g_chrony_rand))
698 ERROR (PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)", RAND_DEVICE_PATH, strerror(errno), errno);
700 return CHRONY_RC_FAIL;
703 DEBUG(PLUGIN_NAME ": Seeding RNG from " RAND_DEVICE_PATH);
705 /* Error opening RAND_DEVICE_PATH. Try time(NULL) as fall-back */
706 DEBUG(PLUGIN_NAME ": Seeding RNG from time(NULL)");
707 g_chrony_rand = time(NULL) ^ getpid();
710 ERROR (PLUGIN_NAME ": Opening random source \'%s\' failed: %s (%d)", URAND_DEVICE_PATH, strerror(errno), errno);
711 return CHRONY_RC_FAIL;
719 /*****************************************************************************/
720 /* Exported functions */
721 /*****************************************************************************/
722 static int chrony_config(const char *p_key, const char *p_value)
726 /* Parse config variables */
727 if (strcasecmp(p_key, CONFIG_KEY_HOST) == 0)
729 if (g_chrony_host != NULL)
731 free (g_chrony_host);
733 if ((g_chrony_host = strdup (p_value)) == NULL)
735 ERROR (PLUGIN_NAME ": Error duplicating host name");
736 return CHRONY_RC_FAIL;
738 } else if (strcasecmp(p_key, CONFIG_KEY_PORT) == 0)
740 if (g_chrony_port != NULL)
742 free (g_chrony_port);
744 if ((g_chrony_port = strdup (p_value)) == NULL)
746 ERROR (PLUGIN_NAME ": Error duplicating port name");
747 return CHRONY_RC_FAIL;
749 } else if (strcasecmp(p_key, CONFIG_KEY_TIMEOUT) == 0)
751 time_t tosec = strtol(p_value,NULL,0);
752 g_chrony_timeout = tosec;
754 WARNING(PLUGIN_NAME ": Unknown configuration variable: %s %s",p_key,p_value);
755 return CHRONY_RC_FAIL;
757 /* 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 */
763 static int chrony_request_daemon_stats()
765 /* Perform Tracking request */
767 size_t chrony_resp_size;
768 tChrony_Request chrony_req;
769 tChrony_Response chrony_resp;
771 chrony_init_req(&chrony_req);
772 rc = chrony_query(REQ_TRACKING, &chrony_req, &chrony_resp, &chrony_resp_size);
775 ERROR (PLUGIN_NAME ": chrony_query (REQ_TRACKING) failed with status %i", rc);
781 char src_addr[IPV6_STR_MAX_SIZE];
782 memset(src_addr, 0, sizeof(src_addr));
783 niptoha(&chrony_resp.body.tracking.addr, src_addr, sizeof(src_addr));
784 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",
786 ntohs(chrony_resp.body.tracking.f_ref_id), //FIXME: 16bit
787 ntohs(chrony_resp.body.tracking.f_stratum),
788 ntohs(chrony_resp.body.tracking.f_leap_status),
789 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high),
790 ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low),
791 ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec),
792 ntohf(chrony_resp.body.tracking.f_current_correction),
793 ntohf(chrony_resp.body.tracking.f_last_offset),
794 ntohf(chrony_resp.body.tracking.f_rms_offset),
795 ntohf(chrony_resp.body.tracking.f_freq_ppm),
796 ntohf(chrony_resp.body.tracking.f_skew_ppm),
797 ntohf(chrony_resp.body.tracking.f_root_delay),
798 ntohf(chrony_resp.body.tracking.f_root_dispersion),
799 ntohf(chrony_resp.body.tracking.f_last_update_interval)
804 double time_ref = ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec);
805 time_ref /= 1000000000.0;
806 time_ref += ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low);
807 if (chrony_resp.body.tracking.f_ref_time.tv_sec_high)
809 double secs_high = ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high);
810 secs_high *= 4294967296.0;
811 time_ref += secs_high;
814 /* Forward results to collectd-daemon */
815 /* Type_instance is always 'chrony' to tag daemon-wide data */
816 /* Type Type_instance Value */
817 chrony_push_data("clock_stratum", DAEMON_NAME, ntohs(chrony_resp.body.tracking.f_stratum));
818 chrony_push_data("time_ref", DAEMON_NAME, time_ref); /* unit: s */
819 chrony_push_data("time_offset_ntp", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_current_correction)); /* Offset between system time and NTP, unit: s */
820 chrony_push_data("time_offset", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_last_offset)); /* Estimated Offset of the NTP time, unit: s */
821 chrony_push_data("time_offset_rms", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_rms_offset)); /* averaged value of the above, unit: s */
822 chrony_push_data("frequency_error", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_freq_ppm)); /* Frequency error of the local osc, unit: ppm */
823 chrony_push_data("clock_skew_ppm", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_skew_ppm));
824 chrony_push_data("root_delay", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_root_delay)); /* Network latency between local daemon and the current source */
825 chrony_push_data("root_dispersion", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_root_dispersion));
826 chrony_push_data("clock_last_update",DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_last_update_interval));
832 static int chrony_request_sources_count(unsigned int *p_count)
834 /* Requests the number of time sources from the chrony daemon */
836 size_t chrony_resp_size;
837 tChrony_Request chrony_req;
838 tChrony_Response chrony_resp;
840 DEBUG(PLUGIN_NAME ": Requesting data");
841 chrony_init_req(&chrony_req);
842 rc = chrony_query (REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
845 ERROR (PLUGIN_NAME ": chrony_query (REQ_N_SOURCES) failed with status %i", rc);
849 *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
850 DEBUG(PLUGIN_NAME ": Getting data of %d clock sources", *p_count);
856 static int chrony_request_source_data(int p_src_idx, int *p_is_reachable)
858 /* Perform Source data request for source #p_src_idx*/
860 size_t chrony_resp_size;
861 tChrony_Request chrony_req;
862 tChrony_Response chrony_resp;
864 char src_addr[IPV6_STR_MAX_SIZE];
865 memset(src_addr, 0, sizeof(src_addr));
867 chrony_init_req(&chrony_req);
868 chrony_req.body.source_data.f_index = htonl(p_src_idx);
869 rc = chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp, &chrony_resp_size);
872 ERROR (PLUGIN_NAME ": chrony_query (REQ_SOURCE_DATA) failed with status %i", rc);
876 niptoha(&chrony_resp.body.source_data.addr, src_addr, sizeof(src_addr));
877 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",
880 ntohs(chrony_resp.body.source_data.f_poll),
881 ntohs(chrony_resp.body.source_data.f_stratum),
882 ntohs(chrony_resp.body.source_data.f_state),
883 ntohs(chrony_resp.body.source_data.f_mode),
884 ntohs(chrony_resp.body.source_data.f_flags),
885 ntohs(chrony_resp.body.source_data.f_reachability),
886 ntohl(chrony_resp.body.source_data.f_since_sample),
887 ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
888 ntohf(chrony_resp.body.source_data.f_latest_meas),
889 ntohf(chrony_resp.body.source_data.f_latest_meas_err)
892 /* Push NaN if source is currently not reachable */
893 int is_reachable = ntohs(chrony_resp.body.source_data.f_reachability) & 0x01;
894 *p_is_reachable = is_reachable;
896 /* Forward results to collectd-daemon */
897 chrony_push_data_valid("clock_stratum", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_stratum));
898 chrony_push_data_valid("clock_state", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_state));
899 chrony_push_data_valid("clock_mode", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_mode));
900 chrony_push_data_valid("clock_reachability",src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_reachability));
901 chrony_push_data_valid("clock_last_meas", src_addr, is_reachable, ntohs(chrony_resp.body.source_data.f_since_sample));
907 static int chrony_request_source_stats(int p_src_idx, const int *p_is_reachable)
909 /* Perform Source stats request for source #p_src_idx */
911 size_t chrony_resp_size;
912 tChrony_Request chrony_req;
913 tChrony_Response chrony_resp;
914 double skew_ppm, frequency_error, time_offset;
916 char src_addr[IPV6_STR_MAX_SIZE];
917 memset(src_addr, 0, sizeof(src_addr));
919 if (*p_is_reachable == 0)
925 chrony_init_req(&chrony_req);
926 chrony_req.body.source_stats.f_index = htonl(p_src_idx);
927 rc = chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp, &chrony_resp_size);
930 ERROR (PLUGIN_NAME ": chrony_query (REQ_SOURCE_STATS) failed with status %i", rc);
934 skew_ppm = ntohf(chrony_resp.body.source_stats.f_skew_ppm);
935 frequency_error = ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm);
936 time_offset = ntohf(chrony_resp.body.source_stats.f_est_offset);
938 niptoha(&chrony_resp.body.source_stats.addr, src_addr, sizeof(src_addr));
939 DEBUG(PLUGIN_NAME ": Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, " \
940 ".n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, " \
941 ".rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, .est_offset_err = %f",
944 ntohl(chrony_resp.body.source_stats.f_ref_id),
945 ntohl(chrony_resp.body.source_stats.f_n_samples),
946 ntohl(chrony_resp.body.source_stats.f_n_runs),
947 ntohl(chrony_resp.body.source_stats.f_span_seconds),
948 ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
952 ntohf(chrony_resp.body.source_stats.f_est_offset_err)
955 } //if (*is_reachable)
957 /* Forward results to collectd-daemon */
958 chrony_push_data_valid("clock_skew_ppm", src_addr, *p_is_reachable, skew_ppm);
959 chrony_push_data_valid("frequency_error", src_addr, *p_is_reachable, frequency_error); /* unit: ppm */
960 chrony_push_data_valid("time_offset", src_addr, *p_is_reachable, time_offset); /* unit: s */
965 static int chrony_read()
967 /* collectd read callback: Perform data acquisition */
969 unsigned int now_src, n_sources;
971 if (g_chrony_seq_is_initialized == 0)
973 /* Seed RNG for sequence number generation */
974 rc = chrony_init_seq();
975 if (rc != CHRONY_RC_OK)
979 g_chrony_seq_is_initialized = 1;
982 /* Get daemon stats */
983 rc = chrony_request_daemon_stats();
984 if (rc != CHRONY_RC_OK)
989 /* Get number of time sources, then check every source for status */
990 rc = chrony_request_sources_count(&n_sources);
991 if (rc != CHRONY_RC_OK)
996 for (now_src = 0; now_src < n_sources; ++now_src)
999 rc = chrony_request_source_data(now_src, &is_reachable);
1000 if (rc != CHRONY_RC_OK)
1005 rc = chrony_request_source_stats(now_src, &is_reachable);
1006 if (rc != CHRONY_RC_OK)
1011 return CHRONY_RC_OK;
1015 static int chrony_shutdown()
1017 /* Collectd shutdown callback: Free mem */
1018 if (g_is_connected != 0)
1020 close(g_chrony_socket);
1023 if (g_chrony_host != NULL)
1025 free (g_chrony_host);
1026 g_chrony_host = NULL;
1028 if (g_chrony_port != NULL)
1030 free (g_chrony_port);
1031 g_chrony_port = NULL;
1033 if (g_plugin_instance != NULL)
1035 free (g_plugin_instance);
1036 g_plugin_instance = NULL;
1038 return CHRONY_RC_OK;
1042 void module_register (void)
1044 plugin_register_config( PLUGIN_NAME_SHORT, chrony_config, g_config_keys, g_config_keys_num);
1045 plugin_register_read( PLUGIN_NAME_SHORT, chrony_read);
1046 plugin_register_shutdown(PLUGIN_NAME_SHORT, chrony_shutdown);