1 /* chrony plugin for collectd
2 (c) 2015 by Claudius M Zingerli, ZSeng
3 Internas roughly based on the ntpd plugin
7 * - More robust udp parsing (using offsets instead of structs?)
8 * - Plausibility checks on values received
14 #include <sys/types.h>
15 #include <sys/socket.h>
19 #include "common.h" /* auxiliary functions */
20 #include "plugin.h" /* plugin_register_*, plugin_dispatch_values */
22 static const char *g_config_keys[] =
29 static int g_config_keys_num = STATIC_ARRAY_SIZE (g_config_keys);
31 # define CHRONY_DEFAULT_HOST "localhost"
32 # define CHRONY_DEFAULT_PORT "323"
33 # define CHRONY_DEFAULT_TIMEOUT 2
35 /* Copied from chrony/candm.h */
37 #define PROTO_VERSION_NUMBER 6
39 #define REQ_N_SOURCES 14
40 #define REQ_SOURCE_DATA 15
41 #define REQ_SOURCE_STATS 34
43 #define PKT_TYPE_CMD_REQUEST 1
44 #define PKT_TYPE_CMD_REPLY 2
47 #define RPY_N_SOURCES 2
48 #define RPY_SOURCE_DATA 3
49 #define RPY_MANUAL_TIMESTAMP 4
50 #define RPY_TRACKING 5
51 #define RPY_SOURCE_STATS 6
54 #define IPADDR_UNSPEC 0
55 #define IPADDR_INET4 1
56 #define IPADDR_INET6 2
58 #define ATTRIB_PACKED __attribute__((packed))
59 typedef struct ATTRIB_PACKED
75 STT_ACCESSALLOWED = 8,
77 STT_NOHOSTACCESS = 10,
78 STT_SOURCEALREADYKNOWN = 11,
79 STT_TOOMANYSOURCES = 12,
85 STT_BADPKTVERSION = 18,
86 STT_BADPKTLENGTH = 19,
89 typedef struct ATTRIB_PACKED
94 typedef struct ATTRIB_PACKED
98 } tChrony_Req_Source_data;
100 typedef struct ATTRIB_PACKED
103 uint8_t f_dummy0[56];
104 } tChrony_Req_Source_stats;
106 #define IPV6_STR_MAX_SIZE 40
107 typedef struct ATTRIB_PACKED
117 typedef struct ATTRIB_PACKED
120 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3 on x86_64 */
126 uint16_t f_reachability;
128 uint32_t f_since_sample;
129 Float f_origin_latest_meas;
131 Float f_latest_meas_err;
132 } tChrony_Resp_Source_data;
134 typedef struct ATTRIB_PACKED
138 uint16_t dummy; /* FIXME: Strange dummy space. Needed on gcc 4.8.3 on x86_64 */
139 uint32_t f_n_samples; //Number of measurements done
140 uint32_t f_n_runs; //How many measurements to come
141 uint32_t f_span_seconds; //For how long we're measuring
142 Float f_rtc_seconds_fast;
143 Float f_rtc_gain_rate_ppm; //Estimated relative frequency error
144 Float f_skew_ppm; //Clock skew
145 Float f_est_offset; //Estimated offset of source
146 Float f_est_offset_err; //Error of estimation
147 } tChrony_Resp_Source_stats;
150 typedef struct ATTRIB_PACKED
164 } header; /* Packed: 20Bytes */
167 tChrony_N_Sources n_sources; /* Packed: 4 Bytes */
168 tChrony_Req_Source_data source_data;
169 tChrony_Req_Source_stats source_stats;
171 uint8_t padding[4+16]; /* Padding to match minimal response size */
174 typedef struct ATTRIB_PACKED
191 } header; /* Packed: 28 Bytes */
197 tChrony_N_Sources n_sources;
198 tChrony_Resp_Source_data source_data;
199 tChrony_Resp_Source_stats source_stats;
202 uint8_t padding[1024];
205 static int g_is_connected = 0;
206 static int g_chrony_socket = -1;
207 static time_t g_chrony_timeout = 0;
208 static char *g_chrony_host = NULL;
209 static char *g_chrony_port = NULL;
210 static uint32_t g_chrony_seq = 0;
212 /*****************************************************************************/
213 /* Internal functions */
214 /*****************************************************************************/
215 /* Code from: http://long.ccaba.upc.edu/long/045Guidelines/eva/ipv6.html#daytimeClient6 */
218 connect_client (const char *hostname,
223 struct addrinfo hints, *res, *ressave;
226 memset(&hints, 0, sizeof(struct addrinfo));
228 hints.ai_family = family;
229 hints.ai_socktype = socktype;
231 n = getaddrinfo(hostname, service, &hints, &res);
235 ERROR ("chrony plugin: getaddrinfo error:: [%s]", gai_strerror(n));
244 sockfd = socket(res->ai_family,
250 if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
261 freeaddrinfo(ressave);
264 /*Code originally from: https://github.com/mlichvar/chrony/blob/master/util.c */
265 /*char * UTI_IPToString(IPAddr *addr)*/
266 char * niptoha(const tChrony_IPAddr *addr,char *p_buf, size_t p_buf_size)
268 unsigned long a, b, c, d, ip;
271 switch (ntohs(addr->f_family))
274 snprintf(p_buf, p_buf_size, "[UNSPEC]");
277 ip = ntohl(addr->addr.ip4);
282 snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
285 ip6 = addr->addr.ip6;
287 /* FIXME: Detect little endian systems */
288 snprintf(p_buf, p_buf_size, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
289 ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7],
290 ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15]);
292 snprintf(p_buf, p_buf_size, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
293 ip6[5], ip6[4], ip6[3], ip6[2], ip6[1], ip6[0], ip6[9], ip6[8],
294 ip6[7], ip6[6], ip6[5], ip6[4], ip6[3], ip6[2], ip6[1], ip6[0]);
298 snprintf(p_buf, p_buf_size, "[UNKNOWN]");
304 static int chrony_set_timeout()
307 tv.tv_sec = g_chrony_timeout;
310 assert(g_chrony_socket>=0);
311 if (setsockopt(g_chrony_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval)) < 0)
318 static int chrony_connect()
320 if (g_chrony_host == NULL)
322 g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
324 if (g_chrony_port == NULL)
326 g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
328 if (g_chrony_timeout <= 0)
330 g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
334 DEBUG("chrony plugin: Connecting to %s:%s", g_chrony_host, g_chrony_port);
335 int socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
338 ERROR ("chrony plugin: Error connecting to daemon. Errno = %d", errno);
341 DEBUG("chrony plugin: Connected");
342 g_chrony_socket = socket;
344 if (chrony_set_timeout())
346 ERROR ("chrony plugin: Error setting timeout to %lds. Errno = %d", g_chrony_timeout, errno);
352 static int chrony_send_request(const tChrony_Request *p_req, size_t p_req_size)
354 if (send(g_chrony_socket,p_req,p_req_size,0) < 0)
356 ERROR ("chrony plugin: Error sending packet. Errno = %d", errno);
363 static int chrony_recv_response(tChrony_Response *p_resp, size_t p_resp_max_size, size_t *p_resp_size)
365 ssize_t rc = recv(g_chrony_socket,p_resp,p_resp_max_size,0);
368 ERROR ("chrony plugin: Error receiving packet. Errno = %d", errno);
376 static int chrony_query(const int p_command, tChrony_Request *p_req, tChrony_Response *p_resp, size_t *p_resp_size)
378 /* Check connection. We simply perform one try as collectd already handles retries */
383 if (g_is_connected == 0)
385 if (chrony_connect() == 0)
389 ERROR ("chrony plugin: Unable to connect. Errno = %d", errno);
397 int valid_command = 0;
398 size_t req_size = sizeof(p_req->header) + sizeof(p_req->padding);
399 size_t resp_size = sizeof(p_resp->header);
400 uint16_t resp_code = RPY_NULL;
404 req_size += sizeof(p_req->body.n_sources);
405 resp_size += sizeof(p_resp->body.n_sources);
406 resp_code = RPY_N_SOURCES;
409 case REQ_SOURCE_DATA:
410 req_size += sizeof(p_req->body.source_data);
411 resp_size += sizeof(p_resp->body.source_data);
412 resp_code = RPY_SOURCE_DATA;
415 case REQ_SOURCE_STATS:
416 req_size += sizeof(p_req->body.source_stats);
417 resp_size += sizeof(p_resp->body.source_stats);
418 resp_code = RPY_SOURCE_STATS;
422 ERROR ("chrony plugin: Unknown request command (Was: %d)", p_command);
426 if (valid_command == 0)
431 p_req->header.f_cmd = htons(p_command);
432 p_req->header.f_cmd_try = 0;
433 p_req->header.f_seq = htonl(g_chrony_seq++);
435 DEBUG("chrony plugin: Sending request");
436 if (chrony_send_request(p_req,req_size) != 0)
441 DEBUG("chrony plugin: Waiting for response");
442 if (chrony_recv_response(p_resp,resp_size,p_resp_size) != 0)
446 DEBUG("chrony plugin: Received response: .version = %u, .type = %u, .cmd = %u, .reply = %u, .status = %u, .seq = %u",p_resp->header.f_version,p_resp->header.f_type,ntohs(p_resp->header.f_cmd),ntohs(p_resp->header.f_reply),ntohs(p_resp->header.f_status),ntohl(p_resp->header.f_seq));
448 if (p_resp->header.f_version != p_req->header.f_version)
450 ERROR("chrony plugin: Wrong protocol version (Was: %d, expected: %d)", p_resp->header.f_version, p_req->header.f_version);
453 if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY)
455 ERROR("chrony plugin: Wrong packet type (Was: %d, expected: %d)", p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
458 if (p_resp->header.f_seq != p_req->header.f_seq)
460 /* FIXME: Implement sequence number handling */
461 ERROR("chrony plugin: Unexpected sequence number (Was: %d, expected: %d)", p_resp->header.f_seq, p_req->header.f_seq);
464 if (p_resp->header.f_cmd != p_req->header.f_cmd)
466 ERROR("chrony plugin: Wrong reply command (Was: %d, expected: %d)", p_resp->header.f_cmd, p_req->header.f_cmd);
470 if (ntohs(p_resp->header.f_reply) != resp_code)
472 ERROR("chrony plugin: Wrong reply code (Was: %d, expected: %d)", ntohs(p_resp->header.f_reply), p_command);
476 switch (p_resp->header.f_status)
479 DEBUG("chrony plugin: Reply packet status STT_SUCCESS");
482 ERROR("chrony plugin: Reply packet contains error status: %d (expected: %d)", p_resp->header.f_status, STT_SUCCESS);
494 static void chrony_init_req(tChrony_Request *p_req)
496 DEBUG("chrony plugin: Clearing %ld bytes",sizeof(*p_req));
497 memset(p_req,0,sizeof(*p_req));
498 p_req->header.f_version = PROTO_VERSION_NUMBER;
499 p_req->header.f_type = PKT_TYPE_CMD_REQUEST;
500 p_req->header.f_dummy0 = 0;
501 p_req->header.f_dummy1 = 0;
502 p_req->header.f_dummy2 = 0;
503 p_req->header.f_dummy3 = 0;
506 /* Code from: https://github.com/mlichvar/chrony/blob/master/util.c (GPLv2) */
508 #define FLOAT_EXP_BITS 7
509 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
510 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
511 #define FLOAT_COEF_BITS ((int)sizeof (int32_t) * 8 - FLOAT_EXP_BITS)
512 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
513 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
515 /* double UTI_FloatNetworkToHost(Float f) */
516 double ntohf(Float f)
518 int32_t exp, coef, x;
521 exp = (x >> FLOAT_COEF_BITS) - FLOAT_COEF_BITS;
522 coef = x << FLOAT_EXP_BITS >> FLOAT_EXP_BITS;
523 return coef * pow(2.0, exp);
527 /* Code from: collectd/src/ntpd.c (MIT) */
529 static void chrony_push_data(char *type, char *type_inst, double value)
532 value_list_t vl = VALUE_LIST_INIT;
534 values[0].gauge = value;
538 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
539 sstrncpy (vl.plugin, "chrony", sizeof (vl.plugin));
540 sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
541 sstrncpy (vl.type, type, sizeof (vl.type));
542 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
544 plugin_dispatch_values (&vl);
548 /*****************************************************************************/
549 /* Exported functions */
550 /*****************************************************************************/
551 static int chrony_config(const char *p_key, const char *p_value)
555 /* Parse config variables */
556 if (strcasecmp(p_key, "Host") == 0)
558 if (g_chrony_host != NULL)
560 free (g_chrony_host);
562 if ((g_chrony_host = strdup (p_value)) == NULL)
564 ERROR ("chrony plugin: Error duplicating host name");
567 } else if (strcasecmp(p_key, "Port") == 0)
569 if (g_chrony_port != NULL)
571 free (g_chrony_port);
573 if ((g_chrony_port = strdup (p_value)) == NULL)
575 ERROR ("chrony plugin: Error duplicating port name");
578 } else if (strcasecmp(p_key, "Timeout") == 0)
580 time_t tosec = strtol(p_value,NULL,0);
581 g_chrony_timeout = tosec;
583 WARNING("chrony plugin: Unknown configuration variable: %s %s",p_key,p_value);
589 static int chrony_request_sources_count(unsigned int *p_count)
592 size_t chrony_resp_size;
593 tChrony_Request chrony_req;
594 tChrony_Response chrony_resp;
596 DEBUG("chrony plugin: Requesting data");
597 chrony_init_req(&chrony_req);
598 rc = chrony_query (REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
601 ERROR ("chrony plugin: chrony_query (REQ_N_SOURCES) failed with status %i", rc);
605 *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
606 DEBUG("chrony plugin: Getting data of %d clock sources", *p_count);
610 static int chrony_request_source_data(int p_src_idx)
612 //Source data request
613 size_t chrony_resp_size;
614 tChrony_Request chrony_req;
615 tChrony_Response chrony_resp;
616 char src_addr[IPV6_STR_MAX_SIZE];
618 chrony_init_req(&chrony_req);
619 chrony_req.body.source_data.f_index = htonl(p_src_idx);
620 int rc = chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp, &chrony_resp_size);
623 ERROR ("chrony plugin: chrony_query (REQ_SOURCE_DATA) failed with status %i", rc);
626 memset(src_addr, 0, sizeof(src_addr));
627 niptoha(&chrony_resp.body.source_data.addr, src_addr, sizeof(src_addr));
628 DEBUG("chrony plugin: 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",
631 ntohs(chrony_resp.body.source_data.f_poll),
632 ntohs(chrony_resp.body.source_data.f_stratum),
633 ntohs(chrony_resp.body.source_data.f_state),
634 ntohs(chrony_resp.body.source_data.f_mode),
635 ntohs(chrony_resp.body.source_data.f_flags),
636 ntohs(chrony_resp.body.source_data.f_reachability),
637 ntohl(chrony_resp.body.source_data.f_since_sample),
638 ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
639 ntohf(chrony_resp.body.source_data.f_latest_meas),
640 ntohf(chrony_resp.body.source_data.f_latest_meas_err)
642 chrony_push_data("clock_stratum", src_addr,ntohs(chrony_resp.body.source_data.f_stratum));
643 chrony_push_data("clock_state", src_addr,ntohs(chrony_resp.body.source_data.f_state));
644 chrony_push_data("clock_mode", src_addr,ntohs(chrony_resp.body.source_data.f_mode));
645 chrony_push_data("clock_reachability",src_addr,ntohs(chrony_resp.body.source_data.f_reachability));
646 chrony_push_data("clock_last_meas", src_addr,ntohs(chrony_resp.body.source_data.f_since_sample));
651 static int chrony_request_source_stats(int p_src_idx)
653 //Source stats request
654 size_t chrony_resp_size;
655 tChrony_Request chrony_req;
656 tChrony_Response chrony_resp;
657 char src_addr[IPV6_STR_MAX_SIZE];
659 chrony_init_req(&chrony_req);
660 chrony_req.body.source_stats.f_index = htonl(p_src_idx);
661 int rc = chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp, &chrony_resp_size);
664 ERROR ("chrony plugin: chrony_query (REQ_SOURCE_STATS) failed with status %i", rc);
668 memset(src_addr, 0, sizeof(src_addr));
669 niptoha(&chrony_resp.body.source_stats.addr, src_addr, sizeof(src_addr));
670 DEBUG("chrony plugin: Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, .n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, .rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, .est_offset_err = %f",
673 ntohl(chrony_resp.body.source_stats.f_ref_id),
674 ntohl(chrony_resp.body.source_stats.f_n_samples),
675 ntohl(chrony_resp.body.source_stats.f_n_runs),
676 ntohl(chrony_resp.body.source_stats.f_span_seconds),
677 ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
678 ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm),
679 ntohf(chrony_resp.body.source_stats.f_skew_ppm),
680 ntohf(chrony_resp.body.source_stats.f_est_offset),
681 ntohf(chrony_resp.body.source_stats.f_est_offset_err)
683 chrony_push_data("clock_skew_ppm", src_addr,ntohf(chrony_resp.body.source_stats.f_skew_ppm));
684 chrony_push_data("frequency_error", src_addr,ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm)); /* unit: ppm */
685 chrony_push_data("time_offset", src_addr,ntohf(chrony_resp.body.source_stats.f_est_offset)); /* unit: s */
689 static int chrony_read (void)
691 //Get number of time sources, then check every source for status
694 unsigned int now_src, n_sources;
695 rc = chrony_request_sources_count(&n_sources);
701 for (now_src = 0; now_src < n_sources; ++now_src)
703 rc = chrony_request_source_data(now_src);
709 rc = chrony_request_source_stats(now_src);
718 static int chrony_shutdown()
720 if (g_is_connected != 0)
722 close(g_chrony_socket);
725 if (g_chrony_host != NULL)
727 free (g_chrony_host);
728 g_chrony_host = NULL;
730 if (g_chrony_port != NULL)
732 free (g_chrony_port);
733 g_chrony_port = NULL;
738 void module_register (void)
740 plugin_register_config( "chrony", chrony_config, g_config_keys, g_config_keys_num);
741 plugin_register_read( "chrony", chrony_read);
742 plugin_register_shutdown("chrony", chrony_shutdown);