1 /******************************************************************************
3 * Nagios check_ntp plugin
6 * Copyright (c) 2006 sean finney <seanius@seanius.net>
7 * Copyright (c) 2006 nagios-plugins team
9 * Last Modified: $Date$
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.
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";
48 static char *server_address
=NULL
;
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. */
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 */
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 */
81 /* this structure holds data about results from querying offset from a peer */
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 */
91 /* this structure holds everything in an ntp control message as per rfc1305 */
93 uint8_t flags
; /* byte with leapindicator,vers,mode. see macros */
94 uint8_t op
; /* R,E,M bits and Opcode */
95 uint16_t seq
; /* Packet sequence */
96 uint16_t status
; /* Clock status */
97 uint16_t assoc
; /* Association */
98 uint16_t offset
; /* Similar to TCP sequence # */
99 uint16_t count
; /* # bytes of data */
100 char data
[MAX_CM_SIZE
]; /* ASCII data of the request */
101 /* NB: not necessarily NULL terminated! */
102 } ntp_control_message
;
104 /* this is an association/status-word pair found in control packet reponses */
108 } ntp_assoc_status_pair
;
110 /* bits 1,2 are the leap indicator */
112 #define LI(x) ((x&LI_MASK)>>6)
113 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
114 /* and these are the values of the leap indicator */
115 #define LI_NOWARNING 0x00
116 #define LI_EXTRASEC 0x01
117 #define LI_MISSINGSEC 0x02
118 #define LI_ALARM 0x03
119 /* bits 3,4,5 are the ntp version */
121 #define VN(x) ((x&VN_MASK)>>3)
122 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
123 #define VN_RESERVED 0x02
124 /* bits 6,7,8 are the ntp mode */
125 #define MODE_MASK 0x07
126 #define MODE(x) (x&MODE_MASK)
127 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
128 /* here are some values */
129 #define MODE_CLIENT 0x03
130 #define MODE_CONTROLMSG 0x06
131 /* In control message, bits 8-10 are R,E,M bits */
132 #define REM_MASK 0xe0
133 #define REM_RESP 0x80
134 #define REM_ERROR 0x40
135 #define REM_MORE 0x20
136 /* In control message, bits 11 - 15 are opcode */
138 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
139 #define OP_READSTAT 0x01
140 #define OP_READVAR 0x02
141 /* In peer status bytes, bits 6,7,8 determine clock selection status */
142 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
143 #define PEER_INCLUDED 0x04
144 #define PEER_SYNCSOURCE 0x06
147 ** a note about the 32-bit "fixed point" numbers:
149 they are divided into halves, each being a 16-bit int in network byte order:
150 - the first 16 bits are an int on the left side of a decimal point.
151 - the second 16 bits represent a fraction n/(2^16)
152 likewise for the 64-bit "fixed point" numbers with everything doubled :)
155 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
156 number. note that these can be used as lvalues too */
157 #define L16(x) (((uint16_t*)&x)[0])
158 #define R16(x) (((uint16_t*)&x)[1])
159 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
160 number. these too can be used as lvalues */
161 #define L32(x) (((uint32_t*)&x)[0])
162 #define R32(x) (((uint32_t*)&x)[1])
164 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
165 #define EPOCHDIFF 0x83aa7e80UL
167 /* extract a 32-bit ntp fixed point number into a double */
168 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
170 /* likewise for a 64-bit ntp fp number */
171 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
172 (ntohl(L32(n))-EPOCHDIFF) + \
173 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
176 /* convert a struct timeval to a double */
177 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
179 /* convert an ntp 64-bit fp number to a struct timeval */
180 #define NTP64toTV(n,t) \
181 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
183 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
184 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
188 /* convert a struct timeval to an ntp 64-bit fp number */
189 #define TVtoNTP64(t,n) \
190 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
192 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
193 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
197 /* NTP control message header is 12 bytes, plus any data in the data
198 * field, plus null padding to the nearest 32-bit boundary per rfc.
200 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
202 /* finally, a little helper or two for debugging: */
203 #define DBG(x) do{if(verbose>1){ x; }}while(0);
204 #define PRINTSOCKADDR(x) \
206 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
209 /* calculate the offset of the local clock */
210 static inline double calc_offset(const ntp_message
*m
, const struct timeval
*t
){
211 double client_tx
, peer_rx
, peer_tx
, client_rx
;
212 client_tx
= NTP64asDOUBLE(m
->origts
);
213 peer_rx
= NTP64asDOUBLE(m
->rxts
);
214 peer_tx
= NTP64asDOUBLE(m
->txts
);
215 client_rx
=TVasDOUBLE((*t
));
216 return (.5*((peer_tx
-client_rx
)+(peer_rx
-client_tx
)));
219 /* print out a ntp packet in human readable/debuggable format */
220 void print_ntp_message(const ntp_message
*p
){
221 struct timeval ref
, orig
, rx
, tx
;
223 NTP64toTV(p
->refts
,ref
);
224 NTP64toTV(p
->origts
,orig
);
225 NTP64toTV(p
->rxts
,rx
);
226 NTP64toTV(p
->txts
,tx
);
228 printf("packet contents:\n");
229 printf("\tflags: 0x%.2x\n", p
->flags
);
230 printf("\t li=%d (0x%.2x)\n", LI(p
->flags
), p
->flags
&LI_MASK
);
231 printf("\t vn=%d (0x%.2x)\n", VN(p
->flags
), p
->flags
&VN_MASK
);
232 printf("\t mode=%d (0x%.2x)\n", MODE(p
->flags
), p
->flags
&MODE_MASK
);
233 printf("\tstratum = %d\n", p
->stratum
);
234 printf("\tpoll = %g\n", pow(2, p
->poll
));
235 printf("\tprecision = %g\n", pow(2, p
->precision
));
236 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p
->rtdelay
));
237 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p
->rtdisp
));
238 printf("\trefid = %x\n", p
->refid
);
239 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p
->refts
));
240 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p
->origts
));
241 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p
->rxts
));
242 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p
->txts
));
245 void print_ntp_control_message(const ntp_control_message
*p
){
247 const ntp_assoc_status_pair
*peer
=NULL
;
249 printf("control packet contents:\n");
250 printf("\tflags: 0x%.2x , 0x%.2x\n", p
->flags
, p
->op
);
251 printf("\t li=%d (0x%.2x)\n", LI(p
->flags
), p
->flags
&LI_MASK
);
252 printf("\t vn=%d (0x%.2x)\n", VN(p
->flags
), p
->flags
&VN_MASK
);
253 printf("\t mode=%d (0x%.2x)\n", MODE(p
->flags
), p
->flags
&MODE_MASK
);
254 printf("\t response=%d (0x%.2x)\n", (p
->op
&REM_RESP
)>0, p
->op
&REM_RESP
);
255 printf("\t more=%d (0x%.2x)\n", (p
->op
&REM_MORE
)>0, p
->op
&REM_MORE
);
256 printf("\t error=%d (0x%.2x)\n", (p
->op
&REM_ERROR
)>0, p
->op
&REM_ERROR
);
257 printf("\t op=%d (0x%.2x)\n", p
->op
&OP_MASK
, p
->op
&OP_MASK
);
258 printf("\tsequence: %d (0x%.2x)\n", ntohs(p
->seq
), ntohs(p
->seq
));
259 printf("\tstatus: %d (0x%.2x)\n", ntohs(p
->status
), ntohs(p
->status
));
260 printf("\tassoc: %d (0x%.2x)\n", ntohs(p
->assoc
), ntohs(p
->assoc
));
261 printf("\toffset: %d (0x%.2x)\n", ntohs(p
->offset
), ntohs(p
->offset
));
262 printf("\tcount: %d (0x%.2x)\n", ntohs(p
->count
), ntohs(p
->count
));
263 numpeers
=ntohs(p
->count
)/(sizeof(ntp_assoc_status_pair
));
264 if(p
->op
&REM_RESP
&& p
->op
&OP_READSTAT
){
265 peer
=(ntp_assoc_status_pair
*)p
->data
;
266 for(i
=0;i
<numpeers
;i
++){
267 printf("\tpeer id %.2x status %.2x",
268 ntohs(peer
[i
].assoc
), ntohs(peer
[i
].status
));
269 if (PEER_SEL(peer
[i
].status
) >= PEER_INCLUDED
){
270 if(PEER_SEL(peer
[i
].status
) >= PEER_SYNCSOURCE
){
271 printf(" <-- current sync source");
273 printf(" <-- current sync candidate");
281 void setup_request(ntp_message
*p
){
284 memset(p
, 0, sizeof(ntp_message
));
285 LI_SET(p
->flags
, LI_ALARM
);
287 MODE_SET(p
->flags
, MODE_CLIENT
);
289 p
->precision
=(int8_t)0xfa;
290 L16(p
->rtdelay
)=htons(1);
291 L16(p
->rtdisp
)=htons(1);
293 gettimeofday(&t
, NULL
);
294 TVtoNTP64(t
,p
->txts
);
297 /* select the "best" server from a list of servers, and return its index.
298 * this is done by filtering servers based on stratum, dispersion, and
299 * finally round-trip delay. */
300 int best_offset_server(const ntp_server_results
*slist
, int nservers
){
301 int i
=0, j
=0, cserver
=0, candidates
[5], csize
=0;
303 /* for each server */
304 for(cserver
=0; cserver
<nservers
; cserver
++){
305 /* compare it to each of the servers already in the candidate list */
306 for(i
=0; i
<csize
; i
++){
307 /* does it have an equal or better stratum? */
308 if(slist
[cserver
].stratum
<= slist
[i
].stratum
){
309 /* does it have an equal or better dispersion? */
310 if(slist
[cserver
].rtdisp
<= slist
[i
].rtdisp
){
311 /* does it have a better rtdelay? */
312 if(slist
[cserver
].rtdelay
< slist
[i
].rtdelay
){
319 /* if we haven't reached the current list's end, move everyone
320 * over one to the right, and insert the new candidate */
323 candidates
[j
]=candidates
[j
-1];
326 /* regardless, if they should be on the list... */
328 candidates
[i
]=cserver
;
330 /* otherwise discard the server */
332 DBG(printf("discarding peer id %d\n", cserver
));
337 DBG(printf("best server selected: peer %d\n", candidates
[0]));
338 return candidates
[0];
340 DBG(printf("no peers meeting synchronization criteria :(\n"));
345 /* do everything we need to get the total average offset
346 * - we use a certain amount of parallelization with poll() to ensure
347 * we don't waste time sitting around waiting for single packets.
348 * - we also "manually" handle resolving host names and connecting, because
349 * we have to do it in a way that our lazy macros don't handle currently :( */
350 double offset_request(const char *host
, int *status
){
351 int i
=0, j
=0, ga_result
=0, num_hosts
=0, *socklist
=NULL
, respnum
=0;
352 int servers_completed
=0, one_written
=0, one_read
=0, servers_readable
=0, best_index
=-1;
353 time_t now_time
=0, start_ts
=0;
354 ntp_message
*req
=NULL
;
355 double avg_offset
=0.;
356 struct timeval recv_time
;
357 struct addrinfo
*ai
=NULL
, *ai_tmp
=NULL
, hints
;
358 struct pollfd
*ufds
=NULL
;
359 ntp_server_results
*servers
=NULL
;
361 /* setup hints to only return results from getaddrinfo that we'd like */
362 memset(&hints
, 0, sizeof(struct addrinfo
));
363 hints
.ai_family
= address_family
;
364 hints
.ai_protocol
= IPPROTO_UDP
;
365 hints
.ai_socktype
= SOCK_DGRAM
;
367 /* fill in ai with the list of hosts resolved by the host name */
368 ga_result
= getaddrinfo(host
, "123", &hints
, &ai
);
370 die(STATE_UNKNOWN
, "error getting address for %s: %s\n",
371 host
, gai_strerror(ga_result
));
374 /* count the number of returned hosts, and allocate stuff accordingly */
375 for(ai_tmp
=ai
; ai_tmp
!=NULL
; ai_tmp
=ai_tmp
->ai_next
){ num_hosts
++; }
376 req
=(ntp_message
*)malloc(sizeof(ntp_message
)*num_hosts
);
377 if(req
==NULL
) die(STATE_UNKNOWN
, "can not allocate ntp message array");
378 socklist
=(int*)malloc(sizeof(int)*num_hosts
);
379 if(socklist
==NULL
) die(STATE_UNKNOWN
, "can not allocate socket array");
380 ufds
=(struct pollfd
*)malloc(sizeof(struct pollfd
)*num_hosts
);
381 if(ufds
==NULL
) die(STATE_UNKNOWN
, "can not allocate socket array");
382 servers
=(ntp_server_results
*)malloc(sizeof(ntp_server_results
)*num_hosts
);
383 if(servers
==NULL
) die(STATE_UNKNOWN
, "can not allocate server array");
384 memset(servers
, 0, sizeof(ntp_server_results
)*num_hosts
);
386 /* setup each socket for writing, and the corresponding struct pollfd */
389 socklist
[i
]=socket(ai_tmp
->ai_family
, SOCK_DGRAM
, IPPROTO_UDP
);
390 if(socklist
[i
] == -1) {
392 die(STATE_UNKNOWN
, "can not create new socket");
394 if(connect(socklist
[i
], ai_tmp
->ai_addr
, ai_tmp
->ai_addrlen
)){
395 die(STATE_UNKNOWN
, "can't create socket connection");
397 ufds
[i
].fd
=socklist
[i
];
398 ufds
[i
].events
=POLLIN
;
401 ai_tmp
= ai_tmp
->ai_next
;
404 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
405 * have passed in order to ensure post-processing and jitter time. */
406 now_time
=start_ts
=time(NULL
);
407 while(servers_completed
<num_hosts
&& now_time
-start_ts
<= socket_timeout
/2){
408 /* loop through each server and find each one which hasn't
409 * been touched in the past second or so and is still lacking
410 * some responses. for each of these servers, send a new request,
411 * and update the "waiting" timestamp with the current time. */
415 for(i
=0; i
<num_hosts
; i
++){
416 if(servers
[i
].waiting
<now_time
&& servers
[i
].num_responses
<AVG_NUM
){
417 if(verbose
&& servers
[i
].waiting
!= 0) printf("re-");
418 if(verbose
) printf("sending request to peer %d\n", i
);
419 setup_request(&req
[i
]);
420 write(socklist
[i
], &req
[i
], sizeof(ntp_message
));
421 servers
[i
].waiting
=now_time
;
427 /* quickly poll for any sockets with pending data */
428 servers_readable
=poll(ufds
, num_hosts
, 100);
429 if(servers_readable
==-1){
430 perror("polling ntp sockets");
431 die(STATE_UNKNOWN
, "communication errors");
434 /* read from any sockets with pending data */
435 for(i
=0; servers_readable
&& i
<num_hosts
; i
++){
436 if(ufds
[i
].revents
&POLLIN
&& servers
[i
].num_responses
< AVG_NUM
){
438 printf("response from peer %d: ", i
);
441 read(ufds
[i
].fd
, &req
[i
], sizeof(ntp_message
));
442 gettimeofday(&recv_time
, NULL
);
443 DBG(print_ntp_message(&req
[i
]));
444 respnum
=servers
[i
].num_responses
++;
445 servers
[i
].offset
[respnum
]=calc_offset(&req
[i
], &recv_time
);
447 printf("offset %.10g\n", servers
[i
].offset
[respnum
]);
449 servers
[i
].stratum
=req
[i
].stratum
;
450 servers
[i
].rtdisp
=NTP32asDOUBLE(req
[i
].rtdisp
);
451 servers
[i
].rtdelay
=NTP32asDOUBLE(req
[i
].rtdelay
);
452 servers
[i
].waiting
=0;
455 if(servers
[i
].num_responses
==AVG_NUM
) servers_completed
++;
458 /* lather, rinse, repeat. */
462 die(STATE_CRITICAL
, "NTP CRITICAL: No response from NTP server\n");
465 /* now, pick the best server from the list */
466 best_index
=best_offset_server(servers
, num_hosts
);
468 *status
=STATE_CRITICAL
;
470 /* finally, calculate the average offset */
471 for(i
=0; i
<servers
[best_index
].num_responses
;i
++){
472 avg_offset
+=servers
[best_index
].offset
[j
];
474 avg_offset
/=servers
[best_index
].num_responses
;
478 /* FIXME: Not closing the socket to avoid re-use of the local port
479 * which can cause old NTP packets to be read instead of NTP control
480 * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
481 * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
488 if(verbose
) printf("overall average offset: %.10g\n", avg_offset
);
493 setup_control_request(ntp_control_message
*p
, uint8_t opcode
, uint16_t seq
){
494 memset(p
, 0, sizeof(ntp_control_message
));
495 LI_SET(p
->flags
, LI_NOWARNING
);
496 VN_SET(p
->flags
, VN_RESERVED
);
497 MODE_SET(p
->flags
, MODE_CONTROLMSG
);
498 OP_SET(p
->op
, opcode
);
500 /* Remaining fields are zero for requests */
503 /* XXX handle responses with the error bit set */
504 double jitter_request(const char *host
, int *status
){
505 int conn
=-1, i
, npeers
=0, num_candidates
=0, syncsource_found
=0;
506 int run
=0, min_peer_sel
=PEER_INCLUDED
, num_selected
=0, num_valid
=0;
507 int peers_size
=0, peer_offset
=0;
508 ntp_assoc_status_pair
*peers
=NULL
;
509 ntp_control_message req
;
510 const char *getvar
= "jitter";
511 double rval
= 0.0, jitter
= -1.0;
512 char *startofvalue
=NULL
, *nptr
=NULL
;
515 /* Long-winded explanation:
516 * Getting the jitter requires a number of steps:
517 * 1) Send a READSTAT request.
518 * 2) Interpret the READSTAT reply
519 * a) The data section contains a list of peer identifiers (16 bits)
520 * and associated status words (16 bits)
521 * b) We want the value of 0x06 in the SEL (peer selection) value,
522 * which means "current synchronizatin source". If that's missing,
523 * we take anything better than 0x04 (see the rfc for details) but
524 * set a minimum of warning.
525 * 3) Send a READVAR request for information on each peer identified
526 * in 2b greater than the minimum selection value.
527 * 4) Extract the jitter value from the data[] (it's ASCII)
529 my_udp_connect(server_address
, 123, &conn
);
531 /* keep sending requests until the server stops setting the
532 * REM_MORE bit, though usually this is only 1 packet. */
534 setup_control_request(&req
, OP_READSTAT
, 1);
535 DBG(printf("sending READSTAT request"));
536 write(conn
, &req
, SIZEOF_NTPCM(req
));
537 DBG(print_ntp_control_message(&req
));
538 /* Attempt to read the largest size packet possible */
539 req
.count
=htons(MAX_CM_SIZE
);
540 DBG(printf("recieving READSTAT response"))
541 read(conn
, &req
, SIZEOF_NTPCM(req
));
542 DBG(print_ntp_control_message(&req
));
543 /* Each peer identifier is 4 bytes in the data section, which
544 * we represent as a ntp_assoc_status_pair datatype.
546 peers_size
+=ntohs(req
.count
);
547 if((tmp
=realloc(peers
, peers_size
)) == NULL
)
548 free(peers
), die(STATE_UNKNOWN
, "can not (re)allocate 'peers' buffer\n");
550 memcpy((void*)((ptrdiff_t)peers
+peer_offset
), (void*)req
.data
, ntohs(req
.count
));
551 npeers
=peers_size
/sizeof(ntp_assoc_status_pair
);
552 peer_offset
+=ntohs(req
.count
);
553 } while(req
.op
&REM_MORE
);
555 /* first, let's find out if we have a sync source, or if there are
556 * at least some candidates. in the case of the latter we'll issue
557 * a warning but go ahead with the check on them. */
558 for (i
= 0; i
< npeers
; i
++){
559 if (PEER_SEL(peers
[i
].status
) >= PEER_INCLUDED
){
561 if(PEER_SEL(peers
[i
].status
) >= PEER_SYNCSOURCE
){
563 min_peer_sel
=PEER_SYNCSOURCE
;
567 if(verbose
) printf("%d candiate peers available\n", num_candidates
);
568 if(verbose
&& syncsource_found
) printf("synchronization source found\n");
569 if(! syncsource_found
){
570 *status
= STATE_WARNING
;
571 if(verbose
) printf("warning: no synchronization source found\n");
575 for (run
=0; run
<AVG_NUM
; run
++){
576 if(verbose
) printf("jitter run %d of %d\n", run
+1, AVG_NUM
);
577 for (i
= 0; i
< npeers
; i
++){
578 /* Only query this server if it is the current sync source */
579 if (PEER_SEL(peers
[i
].status
) >= min_peer_sel
){
581 setup_control_request(&req
, OP_READVAR
, 2);
582 req
.assoc
= peers
[i
].assoc
;
583 /* By spec, putting the variable name "jitter" in the request
584 * should cause the server to provide _only_ the jitter value.
585 * thus reducing net traffic, guaranteeing us only a single
586 * datagram in reply, and making intepretation much simpler
588 /* Older servers doesn't know what jitter is, so if we get an
589 * error on the first pass we redo it with "dispersion" */
590 strncpy(req
.data
, getvar
, MAX_CM_SIZE
-1);
591 req
.count
= htons(strlen(getvar
));
592 DBG(printf("sending READVAR request...\n"));
593 write(conn
, &req
, SIZEOF_NTPCM(req
));
594 DBG(print_ntp_control_message(&req
));
596 req
.count
= htons(MAX_CM_SIZE
);
597 DBG(printf("recieving READVAR response...\n"));
598 read(conn
, &req
, SIZEOF_NTPCM(req
));
599 DBG(print_ntp_control_message(&req
));
601 if(req
.op
&REM_ERROR
&& strstr(getvar
, "jitter")) {
602 if(verbose
) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n");
603 getvar
= "dispersion";
609 /* get to the float value */
611 printf("parsing jitter from peer %.2x: ", ntohs(peers
[i
].assoc
));
613 startofvalue
= strchr(req
.data
, '=');
614 if(startofvalue
!= NULL
) {
616 jitter
= strtod(startofvalue
, &nptr
);
618 if(startofvalue
== NULL
|| startofvalue
==nptr
){
619 printf("warning: unable to read server jitter response.\n");
620 *status
= STATE_WARNING
;
622 if(verbose
) printf("%g\n", jitter
);
629 printf("jitter parsed from %d/%d peers\n", num_valid
, num_selected
);
633 rval
= num_valid
? rval
/ num_valid
: -1.0;
636 if(peers
!=NULL
) free(peers
);
637 /* If we return -1.0, it means no synchronization source was found */
641 int process_arguments(int argc
, char **argv
){
644 static struct option longopts
[] = {
645 {"version", no_argument
, 0, 'V'},
646 {"help", no_argument
, 0, 'h'},
647 {"verbose", no_argument
, 0, 'v'},
648 {"use-ipv4", no_argument
, 0, '4'},
649 {"use-ipv6", no_argument
, 0, '6'},
650 {"warning", required_argument
, 0, 'w'},
651 {"critical", required_argument
, 0, 'c'},
652 {"jwarn", required_argument
, 0, 'j'},
653 {"jcrit", required_argument
, 0, 'k'},
654 {"timeout", required_argument
, 0, 't'},
655 {"hostname", required_argument
, 0, 'H'},
664 c
= getopt_long (argc
, argv
, "Vhv46w:c:j:k:t:H:", longopts
, &option
);
665 if (c
== -1 || c
== EOF
|| c
== 1)
674 print_revision(progname
, revision
);
681 owarn
= atof(optarg
);
684 ocrit
= atof(optarg
);
688 jwarn
= atof(optarg
);
692 jcrit
= atof(optarg
);
695 if(is_host(optarg
) == FALSE
)
696 usage2(_("Invalid hostname/address"), optarg
);
697 server_address
= strdup(optarg
);
700 socket_timeout
=atoi(optarg
);
703 address_family
= AF_INET
;
707 address_family
= AF_INET6
;
709 usage4 (_("IPv6 support not available"));
713 /* print short usage statement if args not parsable */
720 usage4(_("Critical offset should be larger than warning offset"));
724 usage4(_("Critical jitter should be larger than warning jitter"));
727 if(server_address
== NULL
){
728 usage4(_("Hostname was not supplied"));
734 int main(int argc
, char *argv
[]){
735 int result
, offset_result
, jitter_result
;
736 double offset
=0, jitter
=0;
738 result
=offset_result
=jitter_result
=STATE_UNKNOWN
;
740 if (process_arguments (argc
, argv
) == ERROR
)
741 usage4 (_("Could not parse arguments"));
743 /* initialize alarm signal handling */
744 signal (SIGALRM
, socket_timeout_alarm_handler
);
746 /* set socket timeout */
747 alarm (socket_timeout
);
749 offset
= offset_request(server_address
, &offset_result
);
750 if(fabs(offset
) > ocrit
){
751 result
= STATE_CRITICAL
;
752 } else if(fabs(offset
) > owarn
) {
753 result
= STATE_WARNING
;
757 result
=max_state(result
, offset_result
);
759 /* If not told to check the jitter, we don't even send packets.
760 * jitter is checked using NTP control packets, which not all
761 * servers recognize. Trying to check the jitter on OpenNTPD
762 * (for example) will result in an error
765 jitter
=jitter_request(server_address
, &jitter_result
);
767 result
= max_state(result
, STATE_CRITICAL
);
768 } else if(jitter
> jwarn
) {
769 result
= max_state(result
, STATE_WARNING
);
770 } else if(jitter
== -1.0 && result
== STATE_OK
){
771 /* -1 indicates that we couldn't calculate the jitter
772 * Only overrides STATE_OK from the offset */
773 result
= STATE_UNKNOWN
;
776 result
=max_state(result
, jitter_result
);
779 case STATE_CRITICAL
:
780 printf("NTP CRITICAL: ");
783 printf("NTP WARNING: ");
789 printf("NTP UNKNOWN: ");
792 if(offset_result
==STATE_CRITICAL
){
793 printf("Offset unknown|offset=unknown");
795 if(offset_result
==STATE_WARNING
){
796 printf("Unable to fully sample sync server. ");
798 printf("Offset %.10g secs|offset=%.10g", offset
, offset
);
800 if (do_jitter
) printf(" jitter=%f", jitter
);
803 if(server_address
!=NULL
) free(server_address
);
809 void print_help(void){
810 print_revision(progname
, revision
);
812 printf ("Copyright (c) 2006 Sean Finney\n");
813 printf (COPYRIGHT
, copyright
, email
);
815 printf ("%s\n", _("This plugin checks the selected ntp server"));
820 printf (_(UT_HELP_VRSN
));
821 printf (_(UT_HOST_PORT
), 'p', "123");
822 printf (_(UT_WARN_CRIT
));
823 printf (" %s\n", "-j, --warning=DOUBLE");
824 printf (" %s\n", _("warning value for jitter"));
825 printf (" %s\n", "-k, --critical=DOUBLE");
826 printf (" %s\n", _("critical value for jitter"));
827 printf (_(UT_TIMEOUT
), DEFAULT_SOCKET_TIMEOUT
);
828 printf (_(UT_VERBOSE
));
829 printf (_(UT_SUPPORT
));
835 printf (_("Usage:"));
836 printf("%s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname
);