Back to index

nagios-plugins  1.4.16
check_swap.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios check_disk plugin
00004 * 
00005 * License: GPL
00006 * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
00007 * Copyright (c) 2000-2007 Nagios Plugins Development Team
00008 * 
00009 * Description:
00010 * 
00011 * This file contains the check_disk plugin
00012 * 
00013 * 
00014 * This program is free software: you can redistribute it and/or modify
00015 * it under the terms of the GNU General Public License as published by
00016 * the Free Software Foundation, either version 3 of the License, or
00017 * (at your option) any later version.
00018 * 
00019 * This program is distributed in the hope that it will be useful,
00020 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00021 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00022 * GNU General Public License for more details.
00023 * 
00024 * You should have received a copy of the GNU General Public License
00025 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00026 * 
00027 * 
00028 *****************************************************************************/
00029 
00030 const char *progname = "check_swap";
00031 const char *copyright = "2000-2007";
00032 const char *email = "nagiosplug-devel@lists.sourceforge.net";
00033 
00034 #include "common.h"
00035 #include "popen.h"
00036 #include "utils.h"
00037 
00038 #ifdef HAVE_DECL_SWAPCTL
00039 # ifdef HAVE_SYS_PARAM_H
00040 #  include <sys/param.h>
00041 # endif
00042 # ifdef HAVE_SYS_SWAP_H
00043 #  include <sys/swap.h>
00044 # endif
00045 # ifdef HAVE_SYS_STAT_H
00046 #  include <sys/stat.h>
00047 # endif
00048 #endif
00049 
00050 #ifndef SWAP_CONVERSION
00051 # define SWAP_CONVERSION 1
00052 #endif
00053 
00054 int check_swap (int usp, float free_swap_mb);
00055 int process_arguments (int argc, char **argv);
00056 int validate_arguments (void);
00057 void print_usage (void);
00058 void print_help (void);
00059 
00060 int warn_percent = 0;
00061 int crit_percent = 0;
00062 float warn_size_bytes = 0;
00063 float crit_size_bytes= 0;
00064 int verbose;
00065 int allswaps;
00066 
00067 int
00068 main (int argc, char **argv)
00069 {
00070        int percent_used, percent;
00071        float total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0;
00072        float dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0, tmp_mb = 0;
00073        int result = STATE_UNKNOWN;
00074        char input_buffer[MAX_INPUT_BUFFER];
00075 #ifdef HAVE_PROC_MEMINFO
00076        FILE *fp;
00077 #else
00078        int conv_factor = SWAP_CONVERSION;
00079 # ifdef HAVE_SWAP
00080        char *temp_buffer;
00081        char *swap_command;
00082        char *swap_format;
00083 # else
00084 #  ifdef HAVE_DECL_SWAPCTL
00085        int i=0, nswaps=0, swapctl_res=0;
00086 #   ifdef CHECK_SWAP_SWAPCTL_SVR4
00087        swaptbl_t *tbl=NULL;
00088        swapent_t *ent=NULL;
00089 #   else
00090 #    ifdef CHECK_SWAP_SWAPCTL_BSD
00091        struct swapent *ent;
00092 #    endif /* CHECK_SWAP_SWAPCTL_BSD */
00093 #   endif /* CHECK_SWAP_SWAPCTL_SVR4 */
00094 #  endif /* HAVE_DECL_SWAPCTL */
00095 # endif
00096 #endif
00097        char str[32];
00098        char *status;
00099 
00100        setlocale (LC_ALL, "");
00101        bindtextdomain (PACKAGE, LOCALEDIR);
00102        textdomain (PACKAGE);
00103 
00104        status = strdup ("");
00105 
00106        /* Parse extra opts if any */
00107        argv=np_extra_opts (&argc, argv, progname);
00108 
00109        if (process_arguments (argc, argv) == ERROR)
00110               usage4 (_("Could not parse arguments"));
00111 
00112 #ifdef HAVE_PROC_MEMINFO
00113        if (verbose >= 3) {
00114               printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
00115        }
00116        fp = fopen (PROC_MEMINFO, "r");
00117        while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
00118               if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) {
00119                      dsktotal_mb = dsktotal_mb / 1048576;      /* Apply conversion */
00120                      dskused_mb = dskused_mb / 1048576;
00121                      dskfree_mb = dskfree_mb / 1048576;
00122                      total_swap_mb += dsktotal_mb;
00123                      used_swap_mb += dskused_mb;
00124                      free_swap_mb += dskfree_mb;
00125                      if (allswaps) {
00126                             if (dsktotal_mb == 0)
00127                                    percent=100.0;
00128                             else
00129                                    percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
00130                             result = max_state (result, check_swap (percent, dskfree_mb));
00131                             if (verbose)
00132                                    asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
00133                      }
00134               }
00135               else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) {
00136                      if (verbose >= 3) {
00137                             printf("Got %s with %f\n", str, tmp_mb);
00138                      }
00139                      /* I think this part is always in Kb, so convert to mb */
00140                      if (strcmp ("Total", str) == 0) {
00141                             dsktotal_mb = tmp_mb / 1024;
00142                      }
00143                      else if (strcmp ("Free", str) == 0) {
00144                             dskfree_mb = tmp_mb / 1024;
00145                      }
00146               }
00147        }
00148        fclose(fp);
00149        dskused_mb = dsktotal_mb - dskfree_mb;
00150        total_swap_mb = dsktotal_mb;
00151        used_swap_mb = dskused_mb;
00152        free_swap_mb = dskfree_mb;
00153 #else
00154 # ifdef HAVE_SWAP
00155        asprintf(&swap_command, "%s", SWAP_COMMAND);
00156        asprintf(&swap_format, "%s", SWAP_FORMAT);
00157 
00158 /* These override the command used if a summary (and thus ! allswaps) is required */
00159 /* The summary flag returns more accurate information about swap usage on these OSes */
00160 #  ifdef _AIX
00161        if (!allswaps) {
00162               asprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
00163               asprintf(&swap_format, "%s", "%f%*s %f");
00164               conv_factor = 1;
00165        }
00166 #  endif
00167 
00168        if (verbose >= 2)
00169               printf (_("Command: %s\n"), swap_command);
00170        if (verbose >= 3)
00171               printf (_("Format: %s\n"), swap_format);
00172 
00173        child_process = spopen (swap_command);
00174        if (child_process == NULL) {
00175               printf (_("Could not open pipe: %s\n"), swap_command);
00176               return STATE_UNKNOWN;
00177        }
00178 
00179        child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
00180        if (child_stderr == NULL)
00181               printf (_("Could not open stderr for %s\n"), swap_command);
00182 
00183        sprintf (str, "%s", "");
00184        /* read 1st line */
00185        fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
00186        if (strcmp (swap_format, "") == 0) {
00187               temp_buffer = strtok (input_buffer, " \n");
00188               while (temp_buffer) {
00189                      if (strstr (temp_buffer, "blocks"))
00190                             sprintf (str, "%s %s", str, "%f");
00191                      else if (strstr (temp_buffer, "dskfree"))
00192                             sprintf (str, "%s %s", str, "%f");
00193                      else
00194                             sprintf (str, "%s %s", str, "%*s");
00195                      temp_buffer = strtok (NULL, " \n");
00196               }
00197        }
00198 
00199 /* If different swap command is used for summary switch, need to read format differently */
00200 #  ifdef _AIX
00201        if (!allswaps) {
00202               fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process);      /* Ignore first line */
00203               sscanf (input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
00204               free_swap_mb = total_swap_mb * (100 - used_swap_mb) /100;
00205               used_swap_mb = total_swap_mb - free_swap_mb;
00206               if (verbose >= 3)
00207                      printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
00208        } else {
00209 #  endif
00210               while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
00211                      sscanf (input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
00212 
00213                      dsktotal_mb = dsktotal_mb / conv_factor;
00214                      /* AIX lists percent used, so this converts to dskfree in MBs */
00215 #  ifdef _AIX
00216                      dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
00217 #  else
00218                      dskfree_mb = dskfree_mb / conv_factor;
00219 #  endif
00220                      if (verbose >= 3)
00221                             printf (_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
00222 
00223                      dskused_mb = dsktotal_mb - dskfree_mb;
00224                      total_swap_mb += dsktotal_mb;
00225                      used_swap_mb += dskused_mb;
00226                      free_swap_mb += dskfree_mb;
00227                      if (allswaps) {
00228                             percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
00229                             result = max_state (result, check_swap (percent, dskfree_mb));
00230                             if (verbose)
00231                                    asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
00232                      }
00233               }
00234 #  ifdef _AIX
00235        }
00236 #  endif
00237 
00238        /* If we get anything on STDERR, at least set warning */
00239        while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
00240               result = max_state (result, STATE_WARNING);
00241 
00242        /* close stderr */
00243        (void) fclose (child_stderr);
00244 
00245        /* close the pipe */
00246        if (spclose (child_process))
00247               result = max_state (result, STATE_WARNING);
00248 # else
00249 #  ifdef CHECK_SWAP_SWAPCTL_SVR4
00250 
00251        /* get the number of active swap devices */
00252        if((nswaps=swapctl(SC_GETNSWP, NULL))== -1)
00253               die(STATE_UNKNOWN, _("Error getting swap devices\n") );
00254 
00255        if(nswaps == 0)
00256               die(STATE_OK, _("SWAP OK: No swap devices defined\n"));
00257 
00258        if(verbose >= 3)
00259               printf("Found %d swap device(s)\n", nswaps);
00260 
00261        /* initialize swap table + entries */
00262        tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
00263 
00264        if(tbl==NULL)
00265               die(STATE_UNKNOWN, _("malloc() failed!\n"));
00266 
00267        memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
00268        tbl->swt_n=nswaps;
00269        for(i=0;i<nswaps;i++){
00270               if((tbl->swt_ent[i].ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN)) == NULL)
00271                      die(STATE_UNKNOWN, _("malloc() failed!\n"));
00272        }
00273 
00274        /* and now, tally 'em up */
00275        swapctl_res=swapctl(SC_LIST, tbl);
00276        if(swapctl_res < 0){
00277               perror(_("swapctl failed: "));
00278               die(STATE_UNKNOWN, _("Error in swapctl call\n"));
00279        }
00280 
00281        for(i=0;i<nswaps;i++){
00282               dsktotal_mb = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
00283               dskfree_mb = (float) tbl->swt_ent[i].ste_free /  SWAP_CONVERSION;
00284               dskused_mb = ( dsktotal_mb - dskfree_mb );
00285 
00286               if (verbose >= 3)
00287                      printf ("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb);
00288 
00289               if(allswaps && dsktotal_mb > 0){
00290                      percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
00291                      result = max_state (result, check_swap (percent, dskfree_mb));
00292                      if (verbose) {
00293                             asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
00294                      }
00295               }
00296 
00297               total_swap_mb += dsktotal_mb;
00298               free_swap_mb += dskfree_mb;
00299               used_swap_mb += dskused_mb;
00300        }
00301 
00302        /* and clean up after ourselves */
00303        for(i=0;i<nswaps;i++){
00304               free(tbl->swt_ent[i].ste_path);
00305        }
00306        free(tbl);
00307 #  else
00308 #   ifdef CHECK_SWAP_SWAPCTL_BSD
00309 
00310        /* get the number of active swap devices */
00311        nswaps=swapctl(SWAP_NSWAP, NULL, 0);
00312 
00313        /* initialize swap table + entries */
00314        ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps);
00315 
00316        /* and now, tally 'em up */
00317        swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
00318        if(swapctl_res < 0){
00319               perror(_("swapctl failed: "));
00320               die(STATE_UNKNOWN, _("Error in swapctl call\n"));
00321        }
00322 
00323        for(i=0;i<nswaps;i++){
00324               dsktotal_mb = (float) ent[i].se_nblks / conv_factor;
00325               dskused_mb = (float) ent[i].se_inuse / conv_factor;
00326               dskfree_mb = ( dsktotal_mb - dskused_mb );
00327 
00328               if(allswaps && dsktotal_mb > 0){
00329                      percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
00330                      result = max_state (result, check_swap (percent, dskfree_mb));
00331                      if (verbose) {
00332                             asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
00333                      }
00334               }
00335 
00336               total_swap_mb += dsktotal_mb;
00337               free_swap_mb += dskfree_mb;
00338               used_swap_mb += dskused_mb;
00339        }
00340 
00341        /* and clean up after ourselves */
00342        free(ent);
00343 
00344 #   endif /* CHECK_SWAP_SWAPCTL_BSD */
00345 #  endif /* CHECK_SWAP_SWAPCTL_SVR4 */
00346 # endif /* HAVE_SWAP */
00347 #endif /* HAVE_PROC_MEMINFO */
00348 
00349        /* if total_swap_mb == 0, let's not divide by 0 */
00350        if(total_swap_mb) {
00351               percent_used = 100 * ((double) used_swap_mb) / ((double) total_swap_mb);
00352        } else {
00353               percent_used = 0;
00354        }
00355 
00356        result = max_state (result, check_swap (percent_used, free_swap_mb));
00357        printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"),
00358                      state_text (result),
00359                      (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status);
00360 
00361        puts (perfdata ("swap", (long) free_swap_mb, "MB",
00362                        TRUE, (long) max (warn_size_bytes/(1024 * 1024), warn_percent/100.0*total_swap_mb),
00363                        TRUE, (long) max (crit_size_bytes/(1024 * 1024), crit_percent/100.0*total_swap_mb),
00364                        TRUE, 0,
00365                        TRUE, (long) total_swap_mb));
00366 
00367        return result;
00368 }
00369 
00370 
00371 
00372 int
00373 check_swap (int usp, float free_swap_mb)
00374 {
00375        int result = STATE_UNKNOWN;
00376        float free_swap = free_swap_mb * (1024 * 1024);         /* Convert back to bytes as warn and crit specified in bytes */
00377        if (usp >= 0 && crit_percent != 0 && usp >= (100.0 - crit_percent))
00378               result = STATE_CRITICAL;
00379        else if (crit_size_bytes > 0 && free_swap <= crit_size_bytes)
00380               result = STATE_CRITICAL;
00381        else if (usp >= 0 && warn_percent != 0 && usp >= (100.0 - warn_percent))
00382               result = STATE_WARNING;
00383        else if (warn_size_bytes > 0 && free_swap <= warn_size_bytes)
00384               result = STATE_WARNING;
00385        else if (usp >= 0.0)
00386               result = STATE_OK;
00387        return result;
00388 }
00389 
00390 
00391 
00392 /* process command-line arguments */
00393 int
00394 process_arguments (int argc, char **argv)
00395 {
00396        int c = 0;  /* option character */
00397 
00398        int option = 0;
00399        static struct option longopts[] = {
00400               {"warning", required_argument, 0, 'w'},
00401               {"critical", required_argument, 0, 'c'},
00402               {"allswaps", no_argument, 0, 'a'},
00403               {"verbose", no_argument, 0, 'v'},
00404               {"version", no_argument, 0, 'V'},
00405               {"help", no_argument, 0, 'h'},
00406               {0, 0, 0, 0}
00407        };
00408 
00409        if (argc < 2)
00410               return ERROR;
00411 
00412        while (1) {
00413               c = getopt_long (argc, argv, "+?Vvhac:w:", longopts, &option);
00414 
00415               if (c == -1 || c == EOF)
00416                      break;
00417 
00418               switch (c) {
00419               case 'w':                                                             /* warning size threshold */
00420                      if (is_intnonneg (optarg)) {
00421                             warn_size_bytes = (float) atoi (optarg);
00422                             break;
00423                      }
00424                      else if (strstr (optarg, ",") &&
00425                                                   strstr (optarg, "%") &&
00426                                                   sscanf (optarg, "%f,%d%%", &warn_size_bytes, &warn_percent) == 2) {
00427                             warn_size_bytes = floorf(warn_size_bytes);
00428                             break;
00429                      }
00430                      else if (strstr (optarg, "%") &&
00431                                                   sscanf (optarg, "%d%%", &warn_percent) == 1) {
00432                             break;
00433                      }
00434                      else {
00435                             usage4 (_("Warning threshold must be integer or percentage!"));
00436                      }
00437               case 'c':                                                             /* critical size threshold */
00438                      if (is_intnonneg (optarg)) {
00439                             crit_size_bytes = (float) atoi (optarg);
00440                             break;
00441                      }
00442                      else if (strstr (optarg, ",") &&
00443                                                   strstr (optarg, "%") &&
00444                                                   sscanf (optarg, "%f,%d%%", &crit_size_bytes, &crit_percent) == 2) {
00445                             crit_size_bytes = floorf(crit_size_bytes);
00446                             break;
00447                      }
00448                      else if (strstr (optarg, "%") &&
00449                                                   sscanf (optarg, "%d%%", &crit_percent) == 1) {
00450                             break;
00451                      }
00452                      else {
00453                             usage4 (_("Critical threshold must be integer or percentage!"));
00454                      }
00455               case 'a':                                                             /* all swap */
00456                      allswaps = TRUE;
00457                      break;
00458               case 'v':                                                             /* verbose */
00459                      verbose++;
00460                      break;
00461               case 'V':                                                             /* version */
00462                      print_revision (progname, NP_VERSION);
00463                      exit (STATE_OK);
00464               case 'h':                                                             /* help */
00465                      print_help ();
00466                      exit (STATE_OK);
00467               case '?':                                                             /* error */
00468                      usage5 ();
00469               }
00470        }
00471 
00472        c = optind;
00473        if (c == argc)
00474               return validate_arguments ();
00475        if (warn_percent == 0 && is_intnonneg (argv[c]))
00476               warn_percent = atoi (argv[c++]);
00477 
00478        if (c == argc)
00479               return validate_arguments ();
00480        if (crit_percent == 0 && is_intnonneg (argv[c]))
00481               crit_percent = atoi (argv[c++]);
00482 
00483        if (c == argc)
00484               return validate_arguments ();
00485        if (warn_size_bytes == 0 && is_intnonneg (argv[c]))
00486               warn_size_bytes = (float) atoi (argv[c++]);
00487 
00488        if (c == argc)
00489               return validate_arguments ();
00490        if (crit_size_bytes == 0 && is_intnonneg (argv[c]))
00491               crit_size_bytes = (float) atoi (argv[c++]);
00492 
00493        return validate_arguments ();
00494 }
00495 
00496 
00497 
00498 int
00499 validate_arguments (void)
00500 {
00501        if (warn_percent == 0 && crit_percent == 0 && warn_size_bytes == 0
00502                      && crit_size_bytes == 0) {
00503               return ERROR;
00504        }
00505        else if (warn_percent < crit_percent) {
00506               usage4
00507                      (_("Warning percentage should be more than critical percentage"));
00508        }
00509        else if (warn_size_bytes < crit_size_bytes) {
00510               usage4
00511                      (_("Warning free space should be more than critical free space"));
00512        }
00513        return OK;
00514 }
00515 
00516 
00517 
00518 void
00519 print_help (void)
00520 {
00521        print_revision (progname, NP_VERSION);
00522 
00523        printf (_(COPYRIGHT), copyright, email);
00524 
00525        printf ("%s\n", _("Check swap space on local machine."));
00526 
00527   printf ("\n\n");
00528 
00529        print_usage ();
00530 
00531        printf (UT_HELP_VRSN);
00532        printf (UT_EXTRA_OPTS);
00533 
00534        printf (" %s\n", "-w, --warning=INTEGER");
00535   printf ("    %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free"));
00536   printf (" %s\n", "-w, --warning=PERCENT%%");
00537   printf ("    %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free"));
00538   printf (" %s\n", "-c, --critical=INTEGER");
00539   printf ("    %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free"));
00540   printf (" %s\n", "-c, --critical=PERCENT%%");
00541   printf ("    %s\n", _("Exit with CRITCAL status if less than PERCENT of swap space is free"));
00542   printf (" %s\n", "-a, --allswaps");
00543   printf ("    %s\n", _("Conduct comparisons for all swap partitions, one by one"));
00544        printf (UT_VERBOSE);
00545 
00546        printf ("\n");
00547   printf ("%s\n", _("Notes:"));
00548   printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s."));
00549 
00550        printf (UT_SUPPORT);
00551 }
00552 
00553 
00554 
00555 void
00556 print_usage (void)
00557 {
00558        printf ("%s\n", _("Usage:"));
00559   printf ("%s [-av] -w <percent_free>%% -c <percent_free>%%\n",progname);
00560   printf ("%s [-av] -w <bytes_free> -c <bytes_free>\n", progname);
00561 }