Prep for 1.4.10
[monitoring-plugins.git] / plugins / check_ntp.c
blobabd254c8670960fb0956efb6b5de081507c6429a
1 /******************************************************************************
3 * Nagios check_ntp plugin
5 * License: GPL
6 * Copyright (c) 2006 sean finney <seanius@seanius.net>
7 * Copyright (c) 2006 nagios-plugins team
9 * Last Modified: $Date$
11 * Description:
13 * This file contains the check_ntp plugin
15 * This plugin to check ntp servers independant of any commandline
16 * programs or external libraries.
19 * License Information:
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 2 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program; if not, write to the Free Software
33 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 $Id$
37 *****************************************************************************/
39 const char *progname = "check_ntp";
40 const char *revision = "$Revision$";
41 const char *copyright = "2006";
42 const char *email = "nagiosplug-devel@lists.sourceforge.net";
44 #include "common.h"
45 #include "netutils.h"
46 #include "utils.h"
48 static char *server_address=NULL;
49 static int verbose=0;
50 static double owarn=60;
51 static double ocrit=120;
52 static short do_jitter=0;
53 static double jwarn=5000;
54 static double jcrit=10000;
56 int process_arguments (int, char **);
57 void print_help (void);
58 void print_usage (void);
60 /* number of times to perform each request to get a good average. */
61 #define AVG_NUM 4
63 /* max size of control message data */
64 #define MAX_CM_SIZE 468
66 /* this structure holds everything in an ntp request/response as per rfc1305 */
67 typedef struct {
68 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
69 uint8_t stratum; /* clock stratum */
70 int8_t poll; /* polling interval */
71 int8_t precision; /* precision of the local clock */
72 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
73 uint32_t rtdisp; /* like above, but for max err to primary src */
74 uint32_t refid; /* ref clock identifier */
75 uint64_t refts; /* reference timestamp. local time local clock */
76 uint64_t origts; /* time at which request departed client */
77 uint64_t rxts; /* time at which request arrived at server */
78 uint64_t txts; /* time at which request departed server */
79 } ntp_message;
81 /* this structure holds data about results from querying offset from a peer */
82 typedef struct {
83 time_t waiting; /* ts set when we started waiting for a response */
84 int num_responses; /* number of successfully recieved responses */
85 uint8_t stratum; /* copied verbatim from the ntp_message */
86 double rtdelay; /* converted from the ntp_message */
87 double rtdisp; /* converted from the ntp_message */
88 double offset[AVG_NUM]; /* offsets from each response */
89 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
90 } ntp_server_results;
92 /* this structure holds everything in an ntp control message as per rfc1305 */
93 typedef struct {
94 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
95 uint8_t op; /* R,E,M bits and Opcode */
96 uint16_t seq; /* Packet sequence */
97 uint16_t status; /* Clock status */
98 uint16_t assoc; /* Association */
99 uint16_t offset; /* Similar to TCP sequence # */
100 uint16_t count; /* # bytes of data */
101 char data[MAX_CM_SIZE]; /* ASCII data of the request */
102 /* NB: not necessarily NULL terminated! */
103 } ntp_control_message;
105 /* this is an association/status-word pair found in control packet reponses */
106 typedef struct {
107 uint16_t assoc;
108 uint16_t status;
109 } ntp_assoc_status_pair;
111 /* bits 1,2 are the leap indicator */
112 #define LI_MASK 0xc0
113 #define LI(x) ((x&LI_MASK)>>6)
114 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
115 /* and these are the values of the leap indicator */
116 #define LI_NOWARNING 0x00
117 #define LI_EXTRASEC 0x01
118 #define LI_MISSINGSEC 0x02
119 #define LI_ALARM 0x03
120 /* bits 3,4,5 are the ntp version */
121 #define VN_MASK 0x38
122 #define VN(x) ((x&VN_MASK)>>3)
123 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
124 #define VN_RESERVED 0x02
125 /* bits 6,7,8 are the ntp mode */
126 #define MODE_MASK 0x07
127 #define MODE(x) (x&MODE_MASK)
128 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
129 /* here are some values */
130 #define MODE_CLIENT 0x03
131 #define MODE_CONTROLMSG 0x06
132 /* In control message, bits 8-10 are R,E,M bits */
133 #define REM_MASK 0xe0
134 #define REM_RESP 0x80
135 #define REM_ERROR 0x40
136 #define REM_MORE 0x20
137 /* In control message, bits 11 - 15 are opcode */
138 #define OP_MASK 0x1f
139 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
140 #define OP_READSTAT 0x01
141 #define OP_READVAR 0x02
142 /* In peer status bytes, bits 6,7,8 determine clock selection status */
143 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
144 #define PEER_INCLUDED 0x04
145 #define PEER_SYNCSOURCE 0x06
148 ** a note about the 32-bit "fixed point" numbers:
150 they are divided into halves, each being a 16-bit int in network byte order:
151 - the first 16 bits are an int on the left side of a decimal point.
152 - the second 16 bits represent a fraction n/(2^16)
153 likewise for the 64-bit "fixed point" numbers with everything doubled :)
156 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
157 number. note that these can be used as lvalues too */
158 #define L16(x) (((uint16_t*)&x)[0])
159 #define R16(x) (((uint16_t*)&x)[1])
160 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
161 number. these too can be used as lvalues */
162 #define L32(x) (((uint32_t*)&x)[0])
163 #define R32(x) (((uint32_t*)&x)[1])
165 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
166 #define EPOCHDIFF 0x83aa7e80UL
168 /* extract a 32-bit ntp fixed point number into a double */
169 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
171 /* likewise for a 64-bit ntp fp number */
172 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
173 (ntohl(L32(n))-EPOCHDIFF) + \
174 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
177 /* convert a struct timeval to a double */
178 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
180 /* convert an ntp 64-bit fp number to a struct timeval */
181 #define NTP64toTV(n,t) \
182 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
183 else { \
184 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
185 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
187 }while(0)
189 /* convert a struct timeval to an ntp 64-bit fp number */
190 #define TVtoNTP64(t,n) \
191 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
192 else { \
193 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
194 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
196 } while(0)
198 /* NTP control message header is 12 bytes, plus any data in the data
199 * field, plus null padding to the nearest 32-bit boundary per rfc.
201 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
203 /* finally, a little helper or two for debugging: */
204 #define DBG(x) do{if(verbose>1){ x; }}while(0);
205 #define PRINTSOCKADDR(x) \
206 do{ \
207 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
208 }while(0);
210 /* calculate the offset of the local clock */
211 static inline double calc_offset(const ntp_message *m, const struct timeval *t){
212 double client_tx, peer_rx, peer_tx, client_rx;
213 client_tx = NTP64asDOUBLE(m->origts);
214 peer_rx = NTP64asDOUBLE(m->rxts);
215 peer_tx = NTP64asDOUBLE(m->txts);
216 client_rx=TVasDOUBLE((*t));
217 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
220 /* print out a ntp packet in human readable/debuggable format */
221 void print_ntp_message(const ntp_message *p){
222 struct timeval ref, orig, rx, tx;
224 NTP64toTV(p->refts,ref);
225 NTP64toTV(p->origts,orig);
226 NTP64toTV(p->rxts,rx);
227 NTP64toTV(p->txts,tx);
229 printf("packet contents:\n");
230 printf("\tflags: 0x%.2x\n", p->flags);
231 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
232 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
233 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
234 printf("\tstratum = %d\n", p->stratum);
235 printf("\tpoll = %g\n", pow(2, p->poll));
236 printf("\tprecision = %g\n", pow(2, p->precision));
237 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
238 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
239 printf("\trefid = %x\n", p->refid);
240 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
241 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
242 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
243 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
246 void print_ntp_control_message(const ntp_control_message *p){
247 int i=0, numpeers=0;
248 const ntp_assoc_status_pair *peer=NULL;
250 printf("control packet contents:\n");
251 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
252 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
253 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
254 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
255 printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
256 printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
257 printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
258 printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
259 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
260 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
261 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
262 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
263 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
264 numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
265 if(p->op&REM_RESP && p->op&OP_READSTAT){
266 peer=(ntp_assoc_status_pair*)p->data;
267 for(i=0;i<numpeers;i++){
268 printf("\tpeer id %.2x status %.2x",
269 ntohs(peer[i].assoc), ntohs(peer[i].status));
270 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
271 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
272 printf(" <-- current sync source");
273 } else {
274 printf(" <-- current sync candidate");
277 printf("\n");
282 void setup_request(ntp_message *p){
283 struct timeval t;
285 memset(p, 0, sizeof(ntp_message));
286 LI_SET(p->flags, LI_ALARM);
287 VN_SET(p->flags, 4);
288 MODE_SET(p->flags, MODE_CLIENT);
289 p->poll=4;
290 p->precision=(int8_t)0xfa;
291 L16(p->rtdelay)=htons(1);
292 L16(p->rtdisp)=htons(1);
294 gettimeofday(&t, NULL);
295 TVtoNTP64(t,p->txts);
298 /* select the "best" server from a list of servers, and return its index.
299 * this is done by filtering servers based on stratum, dispersion, and
300 * finally round-trip delay. */
301 int best_offset_server(const ntp_server_results *slist, int nservers){
302 int i=0, j=0, cserver=0, candidates[5], csize=0;
304 /* for each server */
305 for(cserver=0; cserver<nservers; cserver++){
306 /* sort out servers with error flags */
307 if ( LI(slist[cserver].flags) != LI_NOWARNING ){
308 if (verbose) printf("discarding peer id %d: flags=%d\n", cserver, LI(slist[cserver].flags));
309 break;
312 /* compare it to each of the servers already in the candidate list */
313 for(i=0; i<csize; i++){
314 /* does it have an equal or better stratum? */
315 if(slist[cserver].stratum <= slist[i].stratum){
316 /* does it have an equal or better dispersion? */
317 if(slist[cserver].rtdisp <= slist[i].rtdisp){
318 /* does it have a better rtdelay? */
319 if(slist[cserver].rtdelay < slist[i].rtdelay){
320 break;
326 /* if we haven't reached the current list's end, move everyone
327 * over one to the right, and insert the new candidate */
328 if(i<csize){
329 for(j=5; j>i; j--){
330 candidates[j]=candidates[j-1];
333 /* regardless, if they should be on the list... */
334 if(i<5) {
335 candidates[i]=cserver;
336 if(csize<5) csize++;
337 /* otherwise discard the server */
338 } else {
339 DBG(printf("discarding peer id %d\n", cserver));
343 if(csize>0) {
344 DBG(printf("best server selected: peer %d\n", candidates[0]));
345 return candidates[0];
346 } else {
347 DBG(printf("no peers meeting synchronization criteria :(\n"));
348 return -1;
352 /* do everything we need to get the total average offset
353 * - we use a certain amount of parallelization with poll() to ensure
354 * we don't waste time sitting around waiting for single packets.
355 * - we also "manually" handle resolving host names and connecting, because
356 * we have to do it in a way that our lazy macros don't handle currently :( */
357 double offset_request(const char *host, int *status){
358 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
359 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1;
360 time_t now_time=0, start_ts=0;
361 ntp_message *req=NULL;
362 double avg_offset=0.;
363 struct timeval recv_time;
364 struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
365 struct pollfd *ufds=NULL;
366 ntp_server_results *servers=NULL;
368 /* setup hints to only return results from getaddrinfo that we'd like */
369 memset(&hints, 0, sizeof(struct addrinfo));
370 hints.ai_family = address_family;
371 hints.ai_protocol = IPPROTO_UDP;
372 hints.ai_socktype = SOCK_DGRAM;
374 /* fill in ai with the list of hosts resolved by the host name */
375 ga_result = getaddrinfo(host, "123", &hints, &ai);
376 if(ga_result!=0){
377 die(STATE_UNKNOWN, "error getting address for %s: %s\n",
378 host, gai_strerror(ga_result));
381 /* count the number of returned hosts, and allocate stuff accordingly */
382 for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
383 req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
384 if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
385 socklist=(int*)malloc(sizeof(int)*num_hosts);
386 if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
387 ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
388 if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
389 servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
390 if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
391 memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
393 /* setup each socket for writing, and the corresponding struct pollfd */
394 ai_tmp=ai;
395 for(i=0;ai_tmp;i++){
396 socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
397 if(socklist[i] == -1) {
398 perror(NULL);
399 die(STATE_UNKNOWN, "can not create new socket");
401 if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
402 die(STATE_UNKNOWN, "can't create socket connection");
403 } else {
404 ufds[i].fd=socklist[i];
405 ufds[i].events=POLLIN;
406 ufds[i].revents=0;
408 ai_tmp = ai_tmp->ai_next;
411 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
412 * have passed in order to ensure post-processing and jitter time. */
413 now_time=start_ts=time(NULL);
414 while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){
415 /* loop through each server and find each one which hasn't
416 * been touched in the past second or so and is still lacking
417 * some responses. for each of these servers, send a new request,
418 * and update the "waiting" timestamp with the current time. */
419 one_written=0;
420 now_time=time(NULL);
422 for(i=0; i<num_hosts; i++){
423 if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
424 if(verbose && servers[i].waiting != 0) printf("re-");
425 if(verbose) printf("sending request to peer %d\n", i);
426 setup_request(&req[i]);
427 write(socklist[i], &req[i], sizeof(ntp_message));
428 servers[i].waiting=now_time;
429 one_written=1;
430 break;
434 /* quickly poll for any sockets with pending data */
435 servers_readable=poll(ufds, num_hosts, 100);
436 if(servers_readable==-1){
437 perror("polling ntp sockets");
438 die(STATE_UNKNOWN, "communication errors");
441 /* read from any sockets with pending data */
442 for(i=0; servers_readable && i<num_hosts; i++){
443 if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
444 if(verbose) {
445 printf("response from peer %d: ", i);
448 read(ufds[i].fd, &req[i], sizeof(ntp_message));
449 gettimeofday(&recv_time, NULL);
450 DBG(print_ntp_message(&req[i]));
451 respnum=servers[i].num_responses++;
452 servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
453 if(verbose) {
454 printf("offset %.10g\n", servers[i].offset[respnum]);
456 servers[i].stratum=req[i].stratum;
457 servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
458 servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
459 servers[i].waiting=0;
460 servers[i].flags=req[i].flags;
461 servers_readable--;
462 one_read = 1;
463 if(servers[i].num_responses==AVG_NUM) servers_completed++;
466 /* lather, rinse, repeat. */
469 if (one_read == 0) {
470 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
473 /* now, pick the best server from the list */
474 best_index=best_offset_server(servers, num_hosts);
475 if(best_index < 0){
476 *status=STATE_CRITICAL;
477 } else {
478 /* finally, calculate the average offset */
479 for(i=0; i<servers[best_index].num_responses;i++){
480 avg_offset+=servers[best_index].offset[j];
482 avg_offset/=servers[best_index].num_responses;
485 /* cleanup */
486 /* FIXME: Not closing the socket to avoid re-use of the local port
487 * which can cause old NTP packets to be read instead of NTP control
488 * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
489 * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
490 free(socklist);
491 free(ufds);
492 free(servers);
493 free(req);
494 freeaddrinfo(ai);
496 if(verbose) printf("overall average offset: %.10g\n", avg_offset);
497 return avg_offset;
500 void
501 setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
502 memset(p, 0, sizeof(ntp_control_message));
503 LI_SET(p->flags, LI_NOWARNING);
504 VN_SET(p->flags, VN_RESERVED);
505 MODE_SET(p->flags, MODE_CONTROLMSG);
506 OP_SET(p->op, opcode);
507 p->seq = htons(seq);
508 /* Remaining fields are zero for requests */
511 /* XXX handle responses with the error bit set */
512 double jitter_request(const char *host, int *status){
513 int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
514 int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
515 int peers_size=0, peer_offset=0;
516 ntp_assoc_status_pair *peers=NULL;
517 ntp_control_message req;
518 const char *getvar = "jitter";
519 double rval = 0.0, jitter = -1.0;
520 char *startofvalue=NULL, *nptr=NULL;
521 void *tmp;
523 /* Long-winded explanation:
524 * Getting the jitter requires a number of steps:
525 * 1) Send a READSTAT request.
526 * 2) Interpret the READSTAT reply
527 * a) The data section contains a list of peer identifiers (16 bits)
528 * and associated status words (16 bits)
529 * b) We want the value of 0x06 in the SEL (peer selection) value,
530 * which means "current synchronizatin source". If that's missing,
531 * we take anything better than 0x04 (see the rfc for details) but
532 * set a minimum of warning.
533 * 3) Send a READVAR request for information on each peer identified
534 * in 2b greater than the minimum selection value.
535 * 4) Extract the jitter value from the data[] (it's ASCII)
537 my_udp_connect(server_address, 123, &conn);
539 /* keep sending requests until the server stops setting the
540 * REM_MORE bit, though usually this is only 1 packet. */
542 setup_control_request(&req, OP_READSTAT, 1);
543 DBG(printf("sending READSTAT request"));
544 write(conn, &req, SIZEOF_NTPCM(req));
545 DBG(print_ntp_control_message(&req));
546 /* Attempt to read the largest size packet possible */
547 req.count=htons(MAX_CM_SIZE);
548 DBG(printf("recieving READSTAT response"))
549 read(conn, &req, SIZEOF_NTPCM(req));
550 DBG(print_ntp_control_message(&req));
551 /* Each peer identifier is 4 bytes in the data section, which
552 * we represent as a ntp_assoc_status_pair datatype.
554 peers_size+=ntohs(req.count);
555 if((tmp=realloc(peers, peers_size)) == NULL)
556 free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
557 peers=tmp;
558 memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
559 npeers=peers_size/sizeof(ntp_assoc_status_pair);
560 peer_offset+=ntohs(req.count);
561 } while(req.op&REM_MORE);
563 /* first, let's find out if we have a sync source, or if there are
564 * at least some candidates. in the case of the latter we'll issue
565 * a warning but go ahead with the check on them. */
566 for (i = 0; i < npeers; i++){
567 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
568 num_candidates++;
569 if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
570 syncsource_found=1;
571 min_peer_sel=PEER_SYNCSOURCE;
575 if(verbose) printf("%d candiate peers available\n", num_candidates);
576 if(verbose && syncsource_found) printf("synchronization source found\n");
577 if(! syncsource_found){
578 *status = STATE_WARNING;
579 if(verbose) printf("warning: no synchronization source found\n");
583 for (run=0; run<AVG_NUM; run++){
584 if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
585 for (i = 0; i < npeers; i++){
586 /* Only query this server if it is the current sync source */
587 if (PEER_SEL(peers[i].status) >= min_peer_sel){
588 num_selected++;
589 setup_control_request(&req, OP_READVAR, 2);
590 req.assoc = peers[i].assoc;
591 /* By spec, putting the variable name "jitter" in the request
592 * should cause the server to provide _only_ the jitter value.
593 * thus reducing net traffic, guaranteeing us only a single
594 * datagram in reply, and making intepretation much simpler
596 /* Older servers doesn't know what jitter is, so if we get an
597 * error on the first pass we redo it with "dispersion" */
598 strncpy(req.data, getvar, MAX_CM_SIZE-1);
599 req.count = htons(strlen(getvar));
600 DBG(printf("sending READVAR request...\n"));
601 write(conn, &req, SIZEOF_NTPCM(req));
602 DBG(print_ntp_control_message(&req));
604 req.count = htons(MAX_CM_SIZE);
605 DBG(printf("recieving READVAR response...\n"));
606 read(conn, &req, SIZEOF_NTPCM(req));
607 DBG(print_ntp_control_message(&req));
609 if(req.op&REM_ERROR && strstr(getvar, "jitter")) {
610 if(verbose) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n");
611 getvar = "dispersion";
612 num_selected--;
613 i--;
614 continue;
617 /* get to the float value */
618 if(verbose) {
619 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
621 startofvalue = strchr(req.data, '=');
622 if(startofvalue != NULL) {
623 startofvalue++;
624 jitter = strtod(startofvalue, &nptr);
626 if(startofvalue == NULL || startofvalue==nptr){
627 printf("warning: unable to read server jitter response.\n");
628 *status = STATE_WARNING;
629 } else {
630 if(verbose) printf("%g\n", jitter);
631 num_valid++;
632 rval += jitter;
636 if(verbose){
637 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
641 rval = num_valid ? rval / num_valid : -1.0;
643 close(conn);
644 if(peers!=NULL) free(peers);
645 /* If we return -1.0, it means no synchronization source was found */
646 return rval;
649 int process_arguments(int argc, char **argv){
650 int c;
651 int option=0;
652 static struct option longopts[] = {
653 {"version", no_argument, 0, 'V'},
654 {"help", no_argument, 0, 'h'},
655 {"verbose", no_argument, 0, 'v'},
656 {"use-ipv4", no_argument, 0, '4'},
657 {"use-ipv6", no_argument, 0, '6'},
658 {"warning", required_argument, 0, 'w'},
659 {"critical", required_argument, 0, 'c'},
660 {"jwarn", required_argument, 0, 'j'},
661 {"jcrit", required_argument, 0, 'k'},
662 {"timeout", required_argument, 0, 't'},
663 {"hostname", required_argument, 0, 'H'},
664 {0, 0, 0, 0}
668 if (argc < 2)
669 usage ("\n");
671 while (1) {
672 c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
673 if (c == -1 || c == EOF || c == 1)
674 break;
676 switch (c) {
677 case 'h':
678 print_help();
679 exit(STATE_OK);
680 break;
681 case 'V':
682 print_revision(progname, revision);
683 exit(STATE_OK);
684 break;
685 case 'v':
686 verbose++;
687 break;
688 case 'w':
689 owarn = atof(optarg);
690 break;
691 case 'c':
692 ocrit = atof(optarg);
693 break;
694 case 'j':
695 do_jitter=1;
696 jwarn = atof(optarg);
697 break;
698 case 'k':
699 do_jitter=1;
700 jcrit = atof(optarg);
701 break;
702 case 'H':
703 if(is_host(optarg) == FALSE)
704 usage2(_("Invalid hostname/address"), optarg);
705 server_address = strdup(optarg);
706 break;
707 case 't':
708 socket_timeout=atoi(optarg);
709 break;
710 case '4':
711 address_family = AF_INET;
712 break;
713 case '6':
714 #ifdef USE_IPV6
715 address_family = AF_INET6;
716 #else
717 usage4 (_("IPv6 support not available"));
718 #endif
719 break;
720 case '?':
721 /* print short usage statement if args not parsable */
722 usage5 ();
723 break;
727 if (ocrit < owarn){
728 usage4(_("Critical offset should be larger than warning offset"));
731 if (jcrit < jwarn){
732 usage4(_("Critical jitter should be larger than warning jitter"));
735 if(server_address == NULL){
736 usage4(_("Hostname was not supplied"));
739 return 0;
742 char *perfd_offset (double offset)
744 return fperfdata ("offset", offset, "s",
745 TRUE, owarn,
746 TRUE, ocrit,
747 FALSE, 0, FALSE, 0);
750 char *perfd_jitter (double jitter)
752 return fperfdata ("jitter", jitter, "s",
753 do_jitter, jwarn,
754 do_jitter, jcrit,
755 TRUE, 0, FALSE, 0);
758 int main(int argc, char *argv[]){
759 int result, offset_result, jitter_result;
760 double offset=0, jitter=0;
761 char *result_line, *perfdata_line;
763 result=offset_result=jitter_result=STATE_UNKNOWN;
765 if (process_arguments (argc, argv) == ERROR)
766 usage4 (_("Could not parse arguments"));
768 /* initialize alarm signal handling */
769 signal (SIGALRM, socket_timeout_alarm_handler);
771 /* set socket timeout */
772 alarm (socket_timeout);
774 offset = offset_request(server_address, &offset_result);
775 if(fabs(offset) > ocrit){
776 result = STATE_CRITICAL;
777 } else if(fabs(offset) > owarn) {
778 result = STATE_WARNING;
779 } else {
780 result = STATE_OK;
782 result=max_state(result, offset_result);
784 /* If not told to check the jitter, we don't even send packets.
785 * jitter is checked using NTP control packets, which not all
786 * servers recognize. Trying to check the jitter on OpenNTPD
787 * (for example) will result in an error
789 if(do_jitter){
790 jitter=jitter_request(server_address, &jitter_result);
791 if(jitter > jcrit){
792 result = max_state(result, STATE_CRITICAL);
793 } else if(jitter > jwarn) {
794 result = max_state(result, STATE_WARNING);
795 } else if(jitter == -1.0 && result == STATE_OK){
796 /* -1 indicates that we couldn't calculate the jitter
797 * Only overrides STATE_OK from the offset */
798 result = STATE_UNKNOWN;
801 result=max_state(result, jitter_result);
803 switch (result) {
804 case STATE_CRITICAL :
805 asprintf(&result_line, "NTP CRITICAL:");
806 break;
807 case STATE_WARNING :
808 asprintf(&result_line, "NTP WARNING:");
809 break;
810 case STATE_OK :
811 asprintf(&result_line, "NTP OK:");
812 break;
813 default :
814 asprintf(&result_line, "NTP UNKNOWN:");
815 break;
817 if(offset_result==STATE_CRITICAL){
818 asprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
819 asprintf(&perfdata_line, "");
820 } else {
821 if(offset_result==STATE_WARNING){
822 asprintf(&result_line, "%s %s", result_line, _("Unable to fully sample sync server"));
824 asprintf(&result_line, "%s Offset %.10g secs", result_line, offset);
825 asprintf(&perfdata_line, "%s", perfd_offset(offset));
827 if (do_jitter) {
828 asprintf(&result_line, "%s, jitter=%f", result_line, jitter);
829 asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
831 printf("%s|%s\n", result_line, perfdata_line);
833 if(server_address!=NULL) free(server_address);
834 return result;
839 void print_help(void){
840 print_revision(progname, revision);
842 printf ("Copyright (c) 2006 Sean Finney\n");
843 printf (COPYRIGHT, copyright, email);
845 printf ("%s\n", _("This plugin checks the selected ntp server"));
847 printf ("\n\n");
849 print_usage();
850 printf (_(UT_HELP_VRSN));
851 printf (_(UT_HOST_PORT), 'p', "123");
852 printf (" %s\n", "-w, --warning=DOUBLE");
853 printf (" %s\n", _("Offset to result in warning status (seconds)"));
854 printf (" %s\n", "-c, --critical=DOUBLE");
855 printf (" %s\n", _("Offset to result in critical status (seconds)"));
856 printf (" %s\n", "-j, --warning=DOUBLE");
857 printf (" %s\n", _("Warning value for jitter"));
858 printf (" %s\n", "-k, --critical=DOUBLE");
859 printf (" %s\n", _("Critical value for jitter"));
860 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
861 printf (_(UT_VERBOSE));
862 printf (_(UT_SUPPORT));
865 void
866 print_usage(void)
868 printf (_("Usage:"));
869 printf("%s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname);