Code

Perfdata added (Gary Cook)
[nagiosplug.git] / plugins / check_nt.c
1 /******************************************************************************
2  *
3  * CHECK_NT.C
4  *
5  * Program: Windows NT plugin for Nagios
6  * License: GPL
7  * Copyright (c) 2000-2002 Yves Rubin (rubiyz@yahoo.com)
8  *
9  * Description:
10  * 
11  * This requires NSClient software to run on NT (http://nsclient.ready2run.nl/)
12  *
13  * License Information:
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28  *
29  *****************************************************************************/
31 #include "common.h"
32 #include "netutils.h"
33 #include "utils.h"
35 enum checkvars {
36         CHECK_NONE,
37         CHECK_CLIENTVERSION,
38         CHECK_CPULOAD,
39         CHECK_UPTIME,
40         CHECK_USEDDISKSPACE,
41         CHECK_SERVICESTATE,
42         CHECK_PROCSTATE,
43         CHECK_MEMUSE,
44         CHECK_COUNTER,
45         CHECK_FILEAGE
46 };
48 enum {
49         MAX_VALUE_LIST = 30,
50         PORT = 1248
51 };
53 char *server_address=NULL;
54 char *volume_name=NULL;
55 int server_port=PORT;
56 char *value_list=NULL;
57 char *req_password=NULL;
58 unsigned long lvalue_list[MAX_VALUE_LIST];
59 unsigned long warning_value=0L;
60 unsigned long critical_value=0L;
61 int check_warning_value=FALSE;
62 int check_critical_value=FALSE;
63 enum checkvars vars_to_check = CHECK_NONE;
64 int show_all=FALSE;
66 const char *progname = "check_nt";
68 char recv_buffer[MAX_INPUT_BUFFER];
70 void fetch_data (const char* address, int port, const char* sendb);
71 int process_arguments(int, char **);
72 void preparelist(char *string);
73 int strtoularray(unsigned long *array, char *string, const char *delim);
74 void print_help(void);
75 void print_usage(void);
77 int main(int argc, char **argv){
78         int return_code = STATE_UNKNOWN;
79         char *send_buffer=NULL;
80         char *output_message=NULL;
81         char *perfdata=NULL;
82         char *temp_string=NULL;
83         char *temp_string_perf=NULL;
84         char *description=NULL;
86         double total_disk_space=0;
87         double free_disk_space=0;
88         double percent_used_space=0;
89         double warning_used_space=0;
90         double critical_used_space=0;
91         double mem_commitLimit=0;
92         double mem_commitByte=0;
93         unsigned long utilization;
94         unsigned long uptime;
95         unsigned long age_in_minutes;
96         double counter_value;
97         int offset=0;
98         int updays=0;
99         int uphours=0;
100         int upminutes=0;
102         setlocale (LC_ALL, "");
103         bindtextdomain (PACKAGE, LOCALEDIR);
104         textdomain (PACKAGE);
106         if(process_arguments(argc,argv)==ERROR)
107                 usage(_("Could not parse arguments\n"));
109         /* initialize alarm signal handling */
110         signal(SIGALRM,socket_timeout_alarm_handler);
112         /* set socket timeout */
113         alarm(socket_timeout);
115         switch (vars_to_check) {
117         case CHECK_CLIENTVERSION:
119                 asprintf(&send_buffer, "%s&1", req_password);
120                 fetch_data (server_address, server_port, send_buffer);
121                 if (value_list != NULL && strcmp(recv_buffer, value_list) != 0) {
122                         asprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list);
123                         return_code = STATE_WARNING;
124                 } else {
125                         asprintf (&output_message, "%s", recv_buffer);
126                         return_code = STATE_OK;
127                 }
128                 break;
130         case CHECK_CPULOAD:
132                 if (value_list==NULL)
133                         output_message = strdup (_("missing -l parameters"));
134                 else if (strtoularray(lvalue_list,value_list,",")==FALSE)
135                         output_message = strdup (_("wrong -l parameter."));
136                 else {
137                         /* -l parameters is present with only integers */
138                         return_code=STATE_OK;
139                         temp_string = strdup (_("CPU Load"));
140                         temp_string_perf = strdup (_(" "));
141       
142                         /* loop until one of the parameters is wrong or not present */
143                         while (lvalue_list[0+offset]> (unsigned long)0 &&
144                                                  lvalue_list[0+offset]<=(unsigned long)17280 && 
145                                                  lvalue_list[1+offset]> (unsigned long)0 &&
146                                                  lvalue_list[1+offset]<=(unsigned long)100 && 
147                                                  lvalue_list[2+offset]> (unsigned long)0 &&
148                                                  lvalue_list[2+offset]<=(unsigned long)100) {
150                                 /* Send request and retrieve data */
151                                 asprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);
152                                 fetch_data (server_address, server_port, send_buffer);
154                                 utilization=strtoul(recv_buffer,NULL,10);
155                                 
156                                 /* Check if any of the request is in a warning or critical state */
157                                 if(utilization >= lvalue_list[2+offset])
158                                         return_code=STATE_CRITICAL;
159                                 else if(utilization >= lvalue_list[1+offset] && return_code<STATE_WARNING)
160                                         return_code=STATE_WARNING;
162                                 asprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);
163                                 asprintf(&temp_string,"%s%s",temp_string,output_message);
164                                 asprintf(&perfdata,_(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0+offset], utilization,
165                                   lvalue_list[1+offset], lvalue_list[2+offset]);
166                                 asprintf(&temp_string_perf,"%s%s",temp_string_perf,perfdata);
167                                 offset+=3;      /* move across the array */
168                         }
169       
170                         if (strlen(temp_string)>10) {  /* we had at least one loop */
171                                 output_message = strdup (temp_string);
172                                 perfdata = temp_string_perf;
173                         } else
174                                 output_message = strdup (_("not enough values for -l parameters"));
175                 }       
176                 break;
178         case CHECK_UPTIME:
180                 asprintf(&send_buffer, "%s&3", req_password);
181                 fetch_data (server_address, server_port, send_buffer);
182                 uptime=strtoul(recv_buffer,NULL,10);
183                 updays = uptime / 86400;                        
184                 uphours = (uptime % 86400) / 3600;
185                 upminutes = ((uptime % 86400) % 3600) / 60;
186                 asprintf(&output_message,_("System Uptime : %u day(s) %u hour(s) %u minute(s)"),updays,uphours, upminutes);
187                 return_code=STATE_OK;
188                 break;
190         case CHECK_USEDDISKSPACE:
192                 if (value_list==NULL)
193                         output_message = strdup (_("missing -l parameters"));
194                 else if (strlen(value_list)!=1)
195                         output_message = strdup (_("wrong -l argument"));
196                 else {
197                         asprintf(&send_buffer,"%s&4&%s", req_password, value_list);
198                         fetch_data (server_address, server_port, send_buffer);
199                         free_disk_space=atof(strtok(recv_buffer,"&"));
200                         total_disk_space=atof(strtok(NULL,"&"));
201                         percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100;
202                         warning_used_space = ((float)warning_value / 100) * total_disk_space;
203                         critical_used_space = ((float)critical_value / 100) * total_disk_space;
205                         if (free_disk_space>=0) {
206                                 asprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
207                                   value_list, total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824,
208                                   percent_used_space, free_disk_space / 1073741824, (free_disk_space / total_disk_space)*100);
209                                 asprintf(&temp_string_perf,_("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), value_list,
210                                   (total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824,
211                                   critical_used_space / 1073741824, total_disk_space / 1073741824);
213                                 if(check_critical_value==TRUE && percent_used_space >= critical_value)
214                                         return_code=STATE_CRITICAL;
215                                 else if (check_warning_value==TRUE && percent_used_space >= warning_value)
216                                         return_code=STATE_WARNING;      
217                                 else
218                                         return_code=STATE_OK;   
220                                 output_message = strdup (temp_string);
221                                 perfdata = temp_string_perf;
222                         } else {
223                                 output_message = strdup (_("Free disk space : Invalid drive "));
224                                 return_code=STATE_UNKNOWN;
225                         }
226                 }
227                 break;
229         case CHECK_SERVICESTATE:
230         case CHECK_PROCSTATE:
232                 if (value_list==NULL)
233                         output_message = strdup (_("No service/process specified"));
234                 else {
235                         preparelist(value_list);                /* replace , between services with & to send the request */
236                         asprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6,
237                                                          (show_all==TRUE)?_("ShowAll"):_("ShowFail"),value_list);
238                         fetch_data (server_address, server_port, send_buffer);
239                         return_code=atoi(strtok(recv_buffer,"&"));
240                         temp_string=strtok(NULL,"&");
241                         output_message = strdup (temp_string);
242                 }
243                 break;
245         case CHECK_MEMUSE:
246                 
247                 asprintf(&send_buffer,"%s&7", req_password);
248                 fetch_data (server_address, server_port, send_buffer);
249                 mem_commitLimit=atof(strtok(recv_buffer,"&"));
250                 mem_commitByte=atof(strtok(NULL,"&"));
251                 percent_used_space = (mem_commitByte / mem_commitLimit) * 100;
252                 warning_used_space = ((float)warning_value / 100) * mem_commitLimit;
253                 critical_used_space = ((float)critical_value / 100) * mem_commitLimit;
255                 // Changed divisor in following line from 1048567 to 3044515 to accurately reflect memory size
256                 asprintf(&output_message,_("Memory usage: total:%.2f Mb - used: %.2f Mb (%.0f%%) - free: %.2f Mb (%.0f%%)"), 
257                   mem_commitLimit / 3044515, mem_commitByte / 3044515, percent_used_space,  
258                   (mem_commitLimit - mem_commitByte) / 3044515, (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100);
259                 asprintf(&perfdata,_("'Memory usage'=%.2fMb;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 3044515,
260                   warning_used_space / 3044515, critical_used_space / 3044515, mem_commitLimit / 3044515);
261         
262                 return_code=STATE_OK;
263                 if(check_critical_value==TRUE && percent_used_space >= critical_value)
264                         return_code=STATE_CRITICAL;
265                 else if (check_warning_value==TRUE && percent_used_space >= warning_value)
266                         return_code=STATE_WARNING;      
268                 break;
270         case CHECK_COUNTER:
272                 if (value_list==NULL)
273                         output_message = strdup (_("No counter specified"));
274                 else {
275                         preparelist(value_list);                /* replace , between services with & to send the request */
276                         asprintf(&send_buffer,"%s&8&%s", req_password,value_list);
277                         fetch_data (server_address, server_port, send_buffer);
278                         strtok(value_list,"&");                 /* burn the first parameters */
279                         description = strtok(NULL,"&");
280                         counter_value = atof(recv_buffer);
282                         if (description == NULL) 
283                                 asprintf(&output_message, "%.f", counter_value);
284                         else
285                                 asprintf(&output_message,"%s = %.f",  description, counter_value);
286                         asprintf(&perfdata,"'%s'=%.f",  description, counter_value);
287         
288                         if (critical_value > warning_value) {        /* Normal thresholds */
289                                 if(check_critical_value==TRUE && counter_value >= critical_value)
290                                         return_code=STATE_CRITICAL;
291                                 else if (check_warning_value==TRUE && counter_value >= warning_value)
292                                         return_code=STATE_WARNING;      
293                                 else
294                                         return_code=STATE_OK;   
295                         } 
296                         else {                                       /* inverse thresholds */
297                                 return_code=STATE_OK;
298                                 if(check_critical_value==TRUE && counter_value <= critical_value)
299                                         return_code=STATE_CRITICAL;
300                                 else if (check_warning_value==TRUE && counter_value <= warning_value)
301                                         return_code=STATE_WARNING;      
302                         }
303                 }
304                 break;
306         case CHECK_FILEAGE:
308                 if (value_list==NULL)
309                         output_message = strdup (_("No counter specified"));
310                 else {
311                         preparelist(value_list);                /* replace , between services with & to send the request */
312                         asprintf(&send_buffer,"%s&9&%s", req_password,value_list);
313                         fetch_data (server_address, server_port, send_buffer);
314                         age_in_minutes = atoi(strtok(recv_buffer,"&"));
315                         description = strtok(NULL,"&");
316                         output_message = strdup (description);
317         
318                         if (critical_value > warning_value) {        /* Normal thresholds */
319                                 if(check_critical_value==TRUE && age_in_minutes >= critical_value)
320                                         return_code=STATE_CRITICAL;
321                                 else if (check_warning_value==TRUE && age_in_minutes >= warning_value)
322                                         return_code=STATE_WARNING;      
323                                 else
324                                         return_code=STATE_OK;   
325                         } 
326                         else {                                       /* inverse thresholds */
327                                 if(check_critical_value==TRUE && age_in_minutes <= critical_value)
328                                         return_code=STATE_CRITICAL;
329                                 else if (check_warning_value==TRUE && age_in_minutes <= warning_value)
330                                         return_code=STATE_WARNING;      
331                                 else
332                                         return_code=STATE_OK;   
333                         }
334                 }
335                 break;
337         case CHECK_NONE:
338         default:
339                 usage (_("Please specify a variable to check"));
340                 break;
342         }
344         /* reset timeout */
345         alarm(0);
347         if (perfdata==NULL)
348                 printf("%s\n",output_message);
349         else
350                 printf("%s | %s\n",output_message,perfdata);
351         return return_code;
358 \f
359 /* process command-line arguments */
360 int process_arguments(int argc, char **argv){
361         int c;
363         int option = 0;
364         static struct option longopts[] =
365         { 
366                 {"port",     required_argument,0,'p'},
367                 {"timeout",  required_argument,0,'t'},
368                 {"critical", required_argument,0,'c'},
369                 {"warning",  required_argument,0,'w'},
370                 {"variable", required_argument,0,'v'},
371                 {"hostname", required_argument,0,'H'},
372                 {"version",  no_argument,      0,'V'},
373                 {"help",     no_argument,      0,'h'},
374                 {0,0,0,0}
375         };
377         /* no options were supplied */
378         if(argc<2) return ERROR;
380         /* backwards compatibility */
381         if (! is_option(argv[1])) {
382                 server_address = strdup(argv[1]);
383                 argv[1]=argv[0];
384                 argv=&argv[1];
385                 argc--;
386         }
388   for (c=1;c<argc;c++) {
389     if(strcmp("-to",argv[c])==0)
390       strcpy(argv[c],"-t");
391     else if (strcmp("-wv",argv[c])==0)
392       strcpy(argv[c],"-w");
393     else if (strcmp("-cv",argv[c])==0)
394       strcpy(argv[c],"-c");
395         }
397         while (1){
398                 c = getopt_long(argc,argv,"+hVH:t:c:w:p:v:l:s:d:",longopts,&option);
400                 if (c==-1||c==EOF||c==1)
401                         break;
403                 switch (c)
404                         {
405                         case '?': /* print short usage statement if args not parsable */
406                                 printf("%s: Unknown argument: %s\n\n",progname,optarg);
407                                 print_usage();
408                                 exit(STATE_UNKNOWN);
409                         case 'h': /* help */
410                                 print_help();
411                                 exit(STATE_OK);
412                         case 'V': /* version */
413                                 print_revision(progname,"$Revision$");
414                                 exit(STATE_OK);
415                         case 'H': /* hostname */
416                                 if (server_address)     free(server_address);
417                                 server_address = optarg;
418                                 break;
419                         case 's': /* password */
420                                 req_password = optarg;
421                                 break;
422                         case 'p': /* port */
423                                 if (is_intnonneg(optarg))
424                                         server_port=atoi(optarg);
425                                 else
426                                         die(STATE_UNKNOWN,_("Server port an integer (seconds)\nType '%s -h' for additional help\n"),progname);
427                                 break;
428                         case 'v':
429                                 if(strlen(optarg)<4)
430                                         return ERROR;
431                                 if(!strcmp(optarg,"CLIENTVERSION"))
432                                         vars_to_check=CHECK_CLIENTVERSION;
433                                 else if(!strcmp(optarg,"CPULOAD"))
434                                         vars_to_check=CHECK_CPULOAD;
435                                 else if(!strcmp(optarg,"UPTIME"))
436                                         vars_to_check=CHECK_UPTIME;
437                                 else if(!strcmp(optarg,"USEDDISKSPACE"))
438                                         vars_to_check=CHECK_USEDDISKSPACE;
439                                 else if(!strcmp(optarg,"SERVICESTATE"))
440                                         vars_to_check=CHECK_SERVICESTATE;
441                                 else if(!strcmp(optarg,"PROCSTATE"))
442                                         vars_to_check=CHECK_PROCSTATE;
443                                 else if(!strcmp(optarg,"MEMUSE"))
444                                         vars_to_check=CHECK_MEMUSE;
445                                 else if(!strcmp(optarg,"COUNTER"))
446                                         vars_to_check=CHECK_COUNTER;
447                                 else if(!strcmp(optarg,"FILEAGE"))
448                                         vars_to_check=CHECK_FILEAGE;
449                                 else
450                                         return ERROR;
451                                 break;
452                         case 'l': /* value list */
453                                 value_list = optarg;
454                                 break;
455                         case 'w': /* warning threshold */
456                                 warning_value=strtoul(optarg,NULL,10);
457                                 check_warning_value=TRUE;
458                                 break;
459                         case 'c': /* critical threshold */
460                                 critical_value=strtoul(optarg,NULL,10);
461                                 check_critical_value=TRUE;
462                                 break;
463                         case 'd': /* Display select for services */
464                                 if (!strcmp(optarg,"SHOWALL"))
465                                         show_all = TRUE;
466                                 break;
467                         case 't': /* timeout */
468                                 socket_timeout=atoi(optarg);
469                                 if(socket_timeout<=0)
470                                         return ERROR;
471                         }
473         }
475         if (vars_to_check==CHECK_NONE)
476                 return ERROR;
478         if (req_password == NULL)
479                 req_password = strdup (_("None"));
481         return OK;
488 \f
489 void fetch_data (const char *address, int port, const char *sendb) {
490         int result;
492         result=process_tcp_request(address, port, sendb, recv_buffer,sizeof(recv_buffer));
494         if(result!=STATE_OK)
495                 die (result, "could not fetch information from server\n");
496                 
497         if (!strncmp(recv_buffer,"ERROR",5))
498                 die (STATE_UNKNOWN, "NSClient - %s\n",recv_buffer);
501 int strtoularray(unsigned long *array, char *string, const char *delim) {
502         /* split a <delim> delimited string into a long array */
503         int idx=0;
504         char *t1;
506         for (idx=0;idx<MAX_VALUE_LIST;idx++)
507                 array[idx]=0;
508         
509         idx=0;
510         for(t1 = strtok(string,delim);t1 != NULL; t1 = strtok(NULL, delim)) {
511                 if (is_numeric(t1) && idx<MAX_VALUE_LIST) {
512                         array[idx]=strtoul(t1,NULL,10);
513                         idx++;
514                 } else  
515                         return FALSE;
516         }               
517         return TRUE;
520 void preparelist(char *string) {
521         /* Replace all , with & which is the delimiter for the request */
522         int i;
524         for (i = 0; (size_t)i < strlen(string); i++)
525                 if (string[i] == ',') {
526                         string[i]='&';
527                 }
534 \f
535 void print_help(void)
537         print_revision(progname,"$Revision$");
538         printf (_("\
539 Copyright (c) 2000 Yves Rubin (rubiyz@yahoo.com)\n\n\
540 This plugin collects data from the NSClient service running on a\n\
541 Windows NT/2000/XP server.\n\n"));
542         print_usage();
543   printf (_("\nOptions:\n\
544 -H, --hostname=HOST\n\
545   Name of the host to check\n\
546 -p, --port=INTEGER\n\
547   Optional port number (default: %d)\n\
548 -s <password>\n\
549   Password needed for the request\n\
550 -w, --warning=INTEGER\n\
551   Threshold which will result in a warning status\n\
552 -c, --critical=INTEGER\n\
553   Threshold which will result in a critical status\n\
554 -t, --timeout=INTEGER\n\
555   Seconds before connection attempt times out (default: %d)\n\
556 -h, --help\n\
557   Print this help screen\n\
558 -V, --version\n\
559   Print version information\n"),
560                 PORT, DEFAULT_SOCKET_TIMEOUT);
561   printf (_("\
562 -v, --variable=STRING\n\
563   Variable to check.  Valid variables are:\n"));
564   printf (_("\
565    CLIENTVERSION = Get the NSClient version\n\
566      If -l <version> is specified, will return warning if versions differ.\n"));
567   printf (_("\
568    CPULOAD = Average CPU load on last x minutes.\n\
569      Request a -l parameter with the following syntax:\n\
570      -l <minutes range>,<warning threshold>,<critical threshold>.\n\
571      <minute range> should be less than 24*60.\n\
572      Thresholds are percentage and up to 10 requests can be done in one shot.\n\
573      ie: -l 60,90,95,120,90,95\n"));
574   printf (_("\
575    UPTIME = Get the uptime of the machine.\n\
576      No specific parameters. No warning or critical threshold\n"));
577   printf (_("\
578    USEDDISKSPACE = Size and percentage of disk use.\n\
579      Request a -l parameter containing the drive letter only.\n\
580      Warning and critical thresholds can be specified with -w and -c.\n"));
581   printf (_("\
582    MEMUSE = Memory use.\n\
583      Warning and critical thresholds can be specified with -w and -c.\n"));
584   printf (_("\
585    SERVICESTATE = Check the state of one or several services.\n\
586      Request a -l parameters with the following syntax:\n\
587      -l <service1>,<service2>,<service3>,...\n\
588      You can specify -d SHOWALL in case you want to see working services\n\
589                  in the returned string.\n"));
590   printf (_("\
591    PROCSTATE = Check if one or several process are running.\n\
592      Same syntax as SERVICESTATE.\n"));
593   printf (_("\
594    COUNTER = Check any performance counter of Windows NT/2000.\n\
595      Request a -l parameters with the following syntax:\n\
596                  -l \"\\\\<performance object>\\\\counter\",\"<description>\n\
597      The <description> parameter is optional and \n\
598      is given to a printf output command which require a float parameters.\n\
599      Some examples:\n\
600        \"Paging file usage is %%.2f %%%%\"\n\
601        \"%%.f %%%% paging file used.\"\n"));
602   printf (_("Notes:\n\
603  - The NSClient service should be running on the server to get any information\n\
604    (http://nsclient.ready2run.nl).\n\
605  - Critical thresholds should be lower than warning thresholds\n"));
611 void print_usage(void)
613         printf(_("\
614 Usage: %s -H host -v variable [-p port] [-w warning] [-c critical]\n\
615   [-l params] [-d SHOWALL] [-t timeout]\n"), progname);
616         printf (_(UT_HLP_VRS), progname, progname);