summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore6
-rw-r--r--configure.ac9
-rw-r--r--plugins/Makefile.am21
-rw-r--r--plugins/check_swap.c777
-rw-r--r--plugins/check_swap.d/check_swap.h45
-rw-r--r--plugins/check_swap.d/swap.c415
-rw-r--r--plugins/tests/test_check_swap.c24
-rw-r--r--plugins/tests/test_check_swap.t6
-rw-r--r--plugins/tests/var/proc_meminfo55
9 files changed, 824 insertions, 534 deletions
diff --git a/.gitignore b/.gitignore
index 6f903d61..bbd7d844 100644
--- a/.gitignore
+++ b/.gitignore
@@ -221,7 +221,13 @@ NP-VERSION-FILE
221/plugins/tests/Makefile.in 221/plugins/tests/Makefile.in
222/plugins/tests/test_utils 222/plugins/tests/test_utils
223/plugins/tests/test_disk 223/plugins/tests/test_disk
224/plugins/tests/test_check_swap
224/plugins/tests/.deps 225/plugins/tests/.deps
226/plugins/tests/.dirstamp
227
228# /plugins/check_swap.d
229/plugins/check_swap.d/.deps
230/plugins/check_swap.d/.dirstamp
225 231
226# /plugins-root/ 232# /plugins-root/
227/plugins-root/.deps 233/plugins-root/.deps
diff --git a/configure.ac b/configure.ac
index 17272e45..e4408a41 100644
--- a/configure.ac
+++ b/configure.ac
@@ -4,7 +4,7 @@ AC_INIT(monitoring-plugins,2.3git)
4AC_CONFIG_SRCDIR(NPTest.pm) 4AC_CONFIG_SRCDIR(NPTest.pm)
5AC_CONFIG_FILES([gl/Makefile]) 5AC_CONFIG_FILES([gl/Makefile])
6AC_CONFIG_AUX_DIR(build-aux) 6AC_CONFIG_AUX_DIR(build-aux)
7AM_INIT_AUTOMAKE([1.8.3]) 7AM_INIT_AUTOMAKE([1.8.3 subdir-objects])
8AM_SILENT_RULES([yes]) 8AM_SILENT_RULES([yes])
9AM_MAINTAINER_MODE([enable]) 9AM_MAINTAINER_MODE([enable])
10AC_CONFIG_HEADERS([config.h]) 10AC_CONFIG_HEADERS([config.h])
@@ -185,6 +185,9 @@ fi
185if test "$enable_libtap" = "yes" ; then 185if test "$enable_libtap" = "yes" ; then
186 EXTRA_TEST="test_utils test_disk test_tcp test_cmd test_base64" 186 EXTRA_TEST="test_utils test_disk test_tcp test_cmd test_base64"
187 AC_SUBST(EXTRA_TEST) 187 AC_SUBST(EXTRA_TEST)
188
189 EXTRA_PLUGIN_TESTS="tests/test_check_swap"
190 AC_SUBST(EXTRA_PLUGIN_TESTS)
188fi 191fi
189 192
190dnl INI Parsing 193dnl INI Parsing
@@ -1850,8 +1853,8 @@ AC_SUBST(EXTRAS_ROOT)
1850AC_SUBST(EXTRA_NETOBJS) 1853AC_SUBST(EXTRA_NETOBJS)
1851AC_SUBST(DEPLIBS) 1854AC_SUBST(DEPLIBS)
1852 1855
1853AM_GNU_GETTEXT([external], [need-ngettext]) 1856dnl AM_GNU_GETTEXT([external], [need-ngettext])
1854AM_GNU_GETTEXT_VERSION(0.15) 1857dnl AM_GNU_GETTEXT_VERSION(0.15)
1855 1858
1856dnl Check for Redhat spopen problem 1859dnl Check for Redhat spopen problem
1857dnl Weird problem where ECHILD is returned from a wait call in error 1860dnl Weird problem where ECHILD is returned from a wait call in error
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index 49086b7a..2310f107 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -38,19 +38,27 @@ check_tcp_programs = check_ftp check_imap check_nntp check_pop \
38EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \ 38EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \
39 check_swap check_fping check_ldap check_game check_dig \ 39 check_swap check_fping check_ldap check_game check_dig \
40 check_nagios check_by_ssh check_dns check_nt check_ide_smart \ 40 check_nagios check_by_ssh check_dns check_nt check_ide_smart \
41 check_procs check_mysql_query check_apt check_dbi check_curl 41 check_procs check_mysql_query check_apt check_dbi check_curl \
42 \
43 tests/test_check_swap
42 44
43SUBDIRS = picohttpparser 45SUBDIRS = picohttpparser
44 46
45EXTRA_DIST = t tests 47np_test_scripts = tests/test_check_swap.t
48
49EXTRA_DIST = t tests $(np_test_scripts) check_swap.d
46 50
47PLUGINHDRS = common.h 51PLUGINHDRS = common.h
48 52
49noinst_LIBRARIES = libnpcommon.a 53noinst_LIBRARIES = libnpcommon.a
54noinst_PROGRAMS = @EXTRA_PLUGIN_TESTS@
55# These two lines support "make check", but we use "make test"
56check_PROGRAMS = @EXTRA_PLUGIN_TESTS@
50 57
51libnpcommon_a_SOURCES = utils.c netutils.c sslutils.c runcmd.c \ 58libnpcommon_a_SOURCES = utils.c netutils.c sslutils.c runcmd.c \
52 popen.c utils.h netutils.h popen.h common.h runcmd.c runcmd.h 59 popen.c utils.h netutils.h popen.h common.h runcmd.c runcmd.h
53 60
61
54BASEOBJS = libnpcommon.a ../lib/libmonitoringplug.a ../gl/libgnu.a $(LIB_CRYPTO) 62BASEOBJS = libnpcommon.a ../lib/libmonitoringplug.a ../gl/libgnu.a $(LIB_CRYPTO)
55NETOBJS = $(BASEOBJS) $(EXTRA_NETOBLS) 63NETOBJS = $(BASEOBJS) $(EXTRA_NETOBLS)
56NETLIBS = $(NETOBJS) $(SOCKETLIBS) 64NETLIBS = $(NETOBJS) $(SOCKETLIBS)
@@ -58,7 +66,10 @@ SSLOBJS = $(BASEOBJS) $(NETLIBS) $(SSLLIBS) $(LIB_CRYPTO)
58 66
59TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir) 67TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir)
60 68
61TESTS = @PLUGIN_TEST@ 69tap_ldflags = -L$(top_srcdir)/tap
70
71TESTS = @PLUGIN_TEST@ @EXTRA_PLUGIN_TESTS@
72
62 73
63test: 74test:
64 perl -I $(top_builddir) -I $(top_srcdir) ../test.pl 75 perl -I $(top_builddir) -I $(top_srcdir) ../test.pl
@@ -107,6 +118,7 @@ check_real_LDADD = $(NETLIBS)
107check_snmp_LDADD = $(BASEOBJS) 118check_snmp_LDADD = $(BASEOBJS)
108check_smtp_LDADD = $(SSLOBJS) 119check_smtp_LDADD = $(SSLOBJS)
109check_ssh_LDADD = $(NETLIBS) 120check_ssh_LDADD = $(NETLIBS)
121check_swap_SOURCES = check_swap.c check_swap.d/swap.c
110check_swap_LDADD = $(MATHLIBS) $(BASEOBJS) 122check_swap_LDADD = $(MATHLIBS) $(BASEOBJS)
111check_tcp_LDADD = $(SSLOBJS) 123check_tcp_LDADD = $(SSLOBJS)
112check_time_LDADD = $(NETLIBS) 124check_time_LDADD = $(NETLIBS)
@@ -122,6 +134,9 @@ if !HAVE_UTMPX
122check_users_LDADD += popen.o 134check_users_LDADD += popen.o
123endif 135endif
124 136
137tests_test_check_swap_LDADD = $(BASEOBJS) $(tap_ldflags) -ltap
138tests_test_check_swap_SOURCES = check_swap.c check_swap.d/swap.c
139
125############################################################################## 140##############################################################################
126# secondary dependencies 141# secondary dependencies
127 142
diff --git a/plugins/check_swap.c b/plugins/check_swap.c
index fddd93fa..f34b0514 100644
--- a/plugins/check_swap.c
+++ b/plugins/check_swap.c
@@ -1,610 +1,331 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* Monitoring check_swap plugin 3 * Monitoring check_swap plugin
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net) 6 * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
7* Copyright (c) 2000-2007 Monitoring Plugins Development Team 7 * Copyright (c) 2000-2023 Monitoring Plugins Development Team
8* 8 *
9* Description: 9 * Description:
10* 10 *
11* This file contains the check_swap plugin 11 * This file contains the check_swap plugin
12* 12 *
13* 13 *
14* This program is free software: you can redistribute it and/or modify 14 * This program is free software: you can redistribute it and/or modify
15* it under the terms of the GNU General Public License as published by 15 * it under the terms of the GNU General Public License as published by
16* the Free Software Foundation, either version 3 of the License, or 16 * the Free Software Foundation, either version 3 of the License, or
17* (at your option) any later version. 17 * (at your option) any later version.
18* 18 *
19* This program is distributed in the hope that it will be useful, 19 * This program is distributed in the hope that it will be useful,
20* but WITHOUT ANY WARRANTY; without even the implied warranty of 20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22* GNU General Public License for more details. 22 * GNU General Public License for more details.
23* 23 *
24* You should have received a copy of the GNU General Public License 24 * You should have received a copy of the GNU General Public License
25* along with this program. If not, see <http://www.gnu.org/licenses/>. 25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26* 26 *
27* 27 *
28*****************************************************************************/ 28 *****************************************************************************/
29 29
30const char *progname = "check_swap"; 30const char *progname = "check_swap";
31const char *copyright = "2000-2007"; 31const char *copyright = "2000-2023";
32const char *email = "devel@monitoring-plugins.org"; 32const char *email = "devel@monitoring-plugins.org";
33 33
34#include "common.h"
35#include "popen.h"
36#include "utils.h"
37 34
38#ifdef HAVE_DECL_SWAPCTL 35#ifdef HAVE_DECL_SWAPCTL
39# ifdef HAVE_SYS_PARAM_H 36#ifdef HAVE_SYS_PARAM_H
40# include <sys/param.h> 37#include <sys/param.h>
41# endif
42# ifdef HAVE_SYS_SWAP_H
43# include <sys/swap.h>
44# endif
45# ifdef HAVE_SYS_STAT_H
46# include <sys/stat.h>
47# endif
48#endif 38#endif
49 39#ifdef HAVE_SYS_SWAP_H
50#ifndef SWAP_CONVERSION 40#include <sys/swap.h>
51# define SWAP_CONVERSION 1 41#endif
42#ifdef HAVE_SYS_STAT_H
43#include <sys/stat.h>
52#endif 44#endif
53
54typedef struct {
55 int is_percentage;
56 uint64_t value;
57} threshold_t;
58
59int check_swap (float free_swap_mb, float total_swap_mb);
60int process_arguments (int argc, char **argv);
61int validate_arguments (void);
62void print_usage (void);
63void print_help (void);
64
65threshold_t warn;
66threshold_t crit;
67int verbose;
68bool allswaps = false;
69int no_swap_state = STATE_CRITICAL;
70
71int
72main (int argc, char **argv)
73{
74 unsigned int percent_used, percent;
75 uint64_t total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0;
76 uint64_t dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0;
77 uint64_t tmp_KB = 0;
78 int result = STATE_UNKNOWN;
79 char input_buffer[MAX_INPUT_BUFFER];
80#ifdef HAVE_PROC_MEMINFO
81 FILE *fp;
82#else
83 int conv_factor = SWAP_CONVERSION;
84# ifdef HAVE_SWAP
85 char *temp_buffer;
86 char *swap_command;
87 char *swap_format;
88# else
89# ifdef HAVE_DECL_SWAPCTL
90 int i=0, nswaps=0, swapctl_res=0;
91# ifdef CHECK_SWAP_SWAPCTL_SVR4
92 swaptbl_t *tbl=NULL;
93 swapent_t *ent=NULL;
94# else
95# ifdef CHECK_SWAP_SWAPCTL_BSD
96 struct swapent *ent;
97# endif /* CHECK_SWAP_SWAPCTL_BSD */
98# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
99# endif /* HAVE_DECL_SWAPCTL */
100# endif
101#endif 45#endif
102 char str[32];
103 char *status;
104
105 setlocale (LC_ALL, "");
106 bindtextdomain (PACKAGE, LOCALEDIR);
107 textdomain (PACKAGE);
108
109 status = strdup ("");
110
111 /* Parse extra opts if any */
112 argv=np_extra_opts (&argc, argv, progname);
113 46
114 if (process_arguments (argc, argv) == ERROR) 47#include "./check_swap.d/check_swap.h"
115 usage4 (_("Could not parse arguments")); 48#include "./utils.h"
116 49
117#ifdef HAVE_PROC_MEMINFO 50typedef struct {
118 if (verbose >= 3) { 51 int errorcode;
119 printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO); 52 swap_config config;
120 } 53} swap_config_wrapper;
121 fp = fopen (PROC_MEMINFO, "r");
122 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
123 /*
124 * The following sscanf call looks for a line looking like: "Swap: 123 123 123"
125 * On which kind of system this format exists, I can not say, but I wanted to
126 * document this for people who are not adapt with sscanf anymore, like me
127 */
128 if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) {
129 dsktotal_mb = dsktotal_mb / (1024 * 1024); /* Apply conversion */
130 dskused_mb = dskused_mb / (1024 * 1024);
131 dskfree_mb = dskfree_mb / (1024 * 1024);
132 total_swap_mb += dsktotal_mb;
133 used_swap_mb += dskused_mb;
134 free_swap_mb += dskfree_mb;
135 if (allswaps) {
136 if (dsktotal_mb == 0)
137 percent=100.0;
138 else
139 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
140 result = max_state (result, check_swap (dskfree_mb, dsktotal_mb));
141 if (verbose)
142 xasprintf (&status, "%s [%lu (%d%%)]", status, dskfree_mb, 100 - percent);
143 }
144 }
145 54
146 /* 55swap_config_wrapper process_arguments(swap_config_wrapper config, int argc,
147 * The following sscanf call looks for lines looking like: "SwapTotal: 123" and "SwapFree: 123" 56 char **argv);
148 * This format exists at least on Debian Linux with a 5.* kernel 57void print_usage();
149 */ 58void print_help(swap_config);
150 else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %lu %*[k]%*[B]", str, &tmp_KB)) {
151 if (verbose >= 3) {
152 printf("Got %s with %lu\n", str, tmp_KB);
153 }
154 /* I think this part is always in Kb, so convert to mb */
155 if (strcmp ("Total", str) == 0) {
156 dsktotal_mb = tmp_KB / 1024;
157 }
158 else if (strcmp ("Free", str) == 0) {
159 dskfree_mb = dskfree_mb + tmp_KB / 1024;
160 }
161 else if (strcmp ("Cached", str) == 0) {
162 dskfree_mb = dskfree_mb + tmp_KB / 1024;
163 }
164 }
165 }
166 fclose(fp);
167 dskused_mb = dsktotal_mb - dskfree_mb;
168 total_swap_mb = dsktotal_mb;
169 used_swap_mb = dskused_mb;
170 free_swap_mb = dskfree_mb;
171#else
172# ifdef HAVE_SWAP
173 xasprintf(&swap_command, "%s", SWAP_COMMAND);
174 xasprintf(&swap_format, "%s", SWAP_FORMAT);
175
176/* These override the command used if a summary (and thus ! allswaps) is required */
177/* The summary flag returns more accurate information about swap usage on these OSes */
178# ifdef _AIX
179 if (!allswaps) {
180 xasprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
181 xasprintf(&swap_format, "%s", "%lu%*s %lu");
182 conv_factor = 1;
183 }
184# endif
185 59
186 if (verbose >= 2)
187 printf (_("Command: %s\n"), swap_command);
188 if (verbose >= 3)
189 printf (_("Format: %s\n"), swap_format);
190 60
191 child_process = spopen (swap_command); 61int main(int argc, char **argv) {
192 if (child_process == NULL) { 62 setlocale(LC_ALL, "");
193 printf (_("Could not open pipe: %s\n"), swap_command); 63 bindtextdomain(PACKAGE, LOCALEDIR);
194 return STATE_UNKNOWN; 64 textdomain(PACKAGE);
195 }
196 65
197 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); 66 char *status;
198 if (child_stderr == NULL) 67 status = strdup("");
199 printf (_("Could not open stderr for %s\n"), swap_command);
200
201 sprintf (str, "%s", "");
202 /* read 1st line */
203 fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
204 if (strcmp (swap_format, "") == 0) {
205 temp_buffer = strtok (input_buffer, " \n");
206 while (temp_buffer) {
207 if (strstr (temp_buffer, "blocks"))
208 sprintf (str, "%s %s", str, "%lu");
209 else if (strstr (temp_buffer, "dskfree"))
210 sprintf (str, "%s %s", str, "%lu");
211 else
212 sprintf (str, "%s %s", str, "%*s");
213 temp_buffer = strtok (NULL, " \n");
214 }
215 }
216
217/* If different swap command is used for summary switch, need to read format differently */
218# ifdef _AIX
219 if (!allswaps) {
220 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process); /* Ignore first line */
221 sscanf (input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
222 free_swap_mb = total_swap_mb * (100 - used_swap_mb) /100;
223 used_swap_mb = total_swap_mb - free_swap_mb;
224 if (verbose >= 3)
225 printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
226 } else {
227# endif
228 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
229 sscanf (input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
230
231 dsktotal_mb = dsktotal_mb / conv_factor;
232 /* AIX lists percent used, so this converts to dskfree in MBs */
233# ifdef _AIX
234 dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
235# else
236 dskfree_mb = dskfree_mb / conv_factor;
237# endif
238 if (verbose >= 3)
239 printf (_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
240
241 dskused_mb = dsktotal_mb - dskfree_mb;
242 total_swap_mb += dsktotal_mb;
243 used_swap_mb += dskused_mb;
244 free_swap_mb += dskfree_mb;
245 if (allswaps) {
246 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
247 result = max_state (result, check_swap (dskfree_mb, dsktotal_mb));
248 if (verbose)
249 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
250 }
251 }
252# ifdef _AIX
253 }
254# endif
255 68
256 /* If we get anything on STDERR, at least set warning */ 69 /* Parse extra opts if any */
257 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) 70 argv = np_extra_opts(&argc, argv, progname);
258 result = max_state (result, STATE_WARNING);
259 71
260 /* close stderr */ 72 swap_config_wrapper tmp = {.errorcode = OK};
261 (void) fclose (child_stderr);
262 73
263 /* close the pipe */ 74 tmp.config = swap_config_init();
264 if (spclose (child_process))
265 result = max_state (result, STATE_WARNING);
266# else
267# ifdef CHECK_SWAP_SWAPCTL_SVR4
268 75
269 /* get the number of active swap devices */ 76 tmp = process_arguments(tmp, argc, argv);
270 if((nswaps=swapctl(SC_GETNSWP, NULL))== -1)
271 die(STATE_UNKNOWN, _("Error getting swap devices\n") );
272 77
273 if(nswaps == 0) 78 if (tmp.errorcode != OK) {
274 die(STATE_OK, _("SWAP OK: No swap devices defined\n")); 79 usage4(_("Could not parse arguments"));
80 }
275 81
276 if(verbose >= 3) 82 swap_config config = tmp.config;
277 printf("Found %d swap device(s)\n", nswaps);
278 83
279 /* initialize swap table + entries */ 84 swap_result data = get_swap_data(config);
280 tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
281 85
282 if(tbl==NULL) 86 double percent_used;
283 die(STATE_UNKNOWN, _("malloc() failed!\n"));
284 87
285 memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps)); 88 /* if total_swap_mb == 0, let's not divide by 0 */
286 tbl->swt_n=nswaps; 89 if (data.metrics.total != 0) {
287 for(i=0;i<nswaps;i++){ 90 percent_used =
288 if((tbl->swt_ent[i].ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN)) == NULL) 91 100 * ((double)data.metrics.used) / ((double)data.metrics.total);
289 die(STATE_UNKNOWN, _("malloc() failed!\n")); 92 } else {
93 printf(_("SWAP %s - Swap is either disabled, not present, or of zero "
94 "size."),
95 state_text(data.statusCode));
96 exit(config.no_swap_state);
290 } 97 }
291 98
292 /* and now, tally 'em up */ 99 if (config.verbose) {
293 swapctl_res=swapctl(SC_LIST, tbl); 100 printf("Computed usage percentage: %g\n", percent_used);
294 if(swapctl_res < 0){
295 perror(_("swapctl failed: "));
296 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
297 } 101 }
298 102
299 for(i=0;i<nswaps;i++){ 103 uint64_t warn_print = config.warn.value;
300 dsktotal_mb = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION; 104 if (config.warn.is_percentage) {
301 dskfree_mb = (float) tbl->swt_ent[i].ste_free / SWAP_CONVERSION; 105 warn_print = config.warn.value * (data.metrics.total / 100);
302 dskused_mb = ( dsktotal_mb - dskfree_mb );
303
304 if (verbose >= 3)
305 printf ("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb);
306
307 if(allswaps && dsktotal_mb > 0){
308 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
309 result = max_state (result, check_swap (dskfree_mb, dsktotal_mb));
310 if (verbose) {
311 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
312 }
313 }
314
315 total_swap_mb += dsktotal_mb;
316 free_swap_mb += dskfree_mb;
317 used_swap_mb += dskused_mb;
318 } 106 }
319 107
320 /* and clean up after ourselves */ 108 uint64_t crit_print = config.crit.value;
321 for(i=0;i<nswaps;i++){ 109 if (config.crit.is_percentage) {
322 free(tbl->swt_ent[i].ste_path); 110 crit_print = config.crit.value * (data.metrics.total / 100);
323 } 111 }
324 free(tbl);
325# else
326# ifdef CHECK_SWAP_SWAPCTL_BSD
327 112
328 /* get the number of active swap devices */ 113 char *perfdata =
329 nswaps=swapctl(SWAP_NSWAP, NULL, 0); 114 perfdata_uint64("swap", data.metrics.free, "B", true, warn_print, true,
115 crit_print, true, 0, true, (long)data.metrics.total);
330 116
331 /* initialize swap table + entries */ 117 if (config.verbose > 1) {
332 ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps); 118 printf("Warn threshold value: %" PRIu64 "\n", config.warn.value);
333
334 /* and now, tally 'em up */
335 swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
336 if(swapctl_res < 0){
337 perror(_("swapctl failed: "));
338 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
339 } 119 }
340 120
341 for(i=0;i<nswaps;i++){ 121 if ((config.warn.is_percentage &&
342 dsktotal_mb = (float) ent[i].se_nblks / conv_factor; 122 (percent_used >= (100 - config.warn.value))) ||
343 dskused_mb = (float) ent[i].se_inuse / conv_factor; 123 config.warn.value >= data.metrics.free) {
344 dskfree_mb = ( dsktotal_mb - dskused_mb ); 124 data.statusCode = max_state(data.statusCode, STATE_WARNING);
345
346 if(allswaps && dsktotal_mb > 0){
347 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
348 result = max_state (result, check_swap(dskfree_mb, dsktotal_mb));
349 if (verbose) {
350 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
351 }
352 }
353
354 total_swap_mb += dsktotal_mb;
355 free_swap_mb += dskfree_mb;
356 used_swap_mb += dskused_mb;
357 } 125 }
358 126
359 /* and clean up after ourselves */ 127 if (config.verbose > 1) {
360 free(ent); 128 printf("Crit threshold value: %" PRIu64 "\n", config.crit.value);
361
362# endif /* CHECK_SWAP_SWAPCTL_BSD */
363# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
364# endif /* HAVE_SWAP */
365#endif /* HAVE_PROC_MEMINFO */
366
367 /* if total_swap_mb == 0, let's not divide by 0 */
368 if(total_swap_mb) {
369 percent_used = 100 * ((double) used_swap_mb) / ((double) total_swap_mb);
370 } else {
371 percent_used = 100;
372 status = "- Swap is either disabled, not present, or of zero size. ";
373 } 129 }
374 130
375 result = max_state (result, check_swap(free_swap_mb, total_swap_mb)); 131 if ((config.crit.is_percentage &&
376 printf (_("SWAP %s - %d%% free (%dMB out of %dMB) %s|"), 132 (percent_used >= (100 - config.crit.value))) ||
377 state_text (result), 133 config.crit.value >= data.metrics.free) {
378 (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status); 134 data.statusCode = max_state(data.statusCode, STATE_CRITICAL);
379
380 uint64_t warn_print = warn.value;
381 if (warn.is_percentage) warn_print = warn.value * (total_swap_mb *1024 *1024/100);
382 uint64_t crit_print = crit.value;
383 if (crit.is_percentage) crit_print = crit.value * (total_swap_mb *1024 *1024/100);
384
385 puts (perfdata_uint64 ("swap", free_swap_mb *1024 *1024, "B",
386 true, warn_print,
387 true, crit_print,
388 true, 0,
389 true, (long) total_swap_mb * 1024 * 1024));
390
391 return result;
392}
393
394
395int
396check_swap(float free_swap_mb, float total_swap_mb)
397{
398
399 if (!total_swap_mb) return no_swap_state;
400
401 uint64_t free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */
402
403 if (!crit.is_percentage && crit.value >= free_swap) return STATE_CRITICAL;
404 if (!warn.is_percentage && warn.value >= free_swap) return STATE_WARNING;
405
406
407 uint64_t usage_percentage = ((total_swap_mb - free_swap_mb) / total_swap_mb) * 100;
408
409 if (crit.is_percentage &&
410 crit.value != 0 &&
411 usage_percentage >= (100 - crit.value))
412 {
413 return STATE_CRITICAL;
414 } 135 }
415 136
416 if (warn.is_percentage && 137 printf(_("SWAP %s - %g%% free (%lluMB out of %lluMB) %s|%s\n"),
417 warn.value != 0 && 138 state_text(data.statusCode), (100 - percent_used), data.metrics.free,
418 usage_percentage >= (100 - warn.value)) 139 data.metrics.total, status, perfdata);
419 {
420 return STATE_WARNING;
421 }
422 140
423 return STATE_OK; 141 exit(data.statusCode);
424} 142}
425 143
426
427
428/* process command-line arguments */ 144/* process command-line arguments */
429int 145swap_config_wrapper process_arguments(swap_config_wrapper conf_wrapper,
430process_arguments (int argc, char **argv) 146 int argc, char **argv) {
431{ 147 if (argc < 2) {
432 int c = 0; /* option character */ 148 conf_wrapper.errorcode = ERROR;
149 return conf_wrapper;
150 }
433 151
434 int option = 0; 152 int option = 0;
435 static struct option longopts[] = { 153 static struct option longopts[] = {{"warning", required_argument, 0, 'w'},
436 {"warning", required_argument, 0, 'w'}, 154 {"critical", required_argument, 0, 'c'},
437 {"critical", required_argument, 0, 'c'}, 155 {"allswaps", no_argument, 0, 'a'},
438 {"allswaps", no_argument, 0, 'a'}, 156 {"no-swap", required_argument, 0, 'n'},
439 {"no-swap", required_argument, 0, 'n'}, 157 {"verbose", no_argument, 0, 'v'},
440 {"verbose", no_argument, 0, 'v'}, 158 {"version", no_argument, 0, 'V'},
441 {"version", no_argument, 0, 'V'}, 159 {"help", no_argument, 0, 'h'},
442 {"help", no_argument, 0, 'h'}, 160 {0, 0, 0, 0}};
443 {0, 0, 0, 0} 161
444 }; 162 int c = 0; /* option character */
445 163 while (true) {
446 if (argc < 2) 164 c = getopt_long(argc, argv, "+?Vvhac:w:n:", longopts, &option);
447 return ERROR;
448
449 while (1) {
450 c = getopt_long (argc, argv, "+?Vvhac:w:n:", longopts, &option);
451 165
452 if (c == -1 || c == EOF) 166 if (c == -1 || c == EOF)
453 break; 167 break;
454 168
455 switch (c) { 169 switch (c) {
456 case 'w': /* warning size threshold */ 170 case 'w': /* warning size threshold */
457 { 171 {
458 /* 172 /*
459 * We expect either a positive integer value without a unit, which means 173 * We expect either a positive integer value without a unit, which
460 * the unit is Bytes or a positive integer value and a percentage sign (%), 174 * means the unit is Bytes or a positive integer value and a
461 * which means the value must be with 0 and 100 and is relative to the total swap 175 * percentage sign (%), which means the value must be with 0 and 100
462 */ 176 * and is relative to the total swap
463 size_t length; 177 */
464 length = strlen(optarg); 178 size_t length;
465 179 length = strlen(optarg);
466 if (optarg[length - 1] == '%') { 180
467 /* It's percentage */ 181 if (optarg[length - 1] == '%') {
468 warn.is_percentage = 1; 182 /* It's percentage */
469 optarg[length - 1] = '\0'; 183 conf_wrapper.config.warn.is_percentage = true;
470 if (is_uint64(optarg, &warn.value)) { 184 optarg[length - 1] = '\0';
471 if (warn.value > 100) { 185 if (is_uint64(optarg, &conf_wrapper.config.warn.value)) {
472 usage4 (_("Warning threshold percentage must be <= 100!")); 186 if (conf_wrapper.config.warn.value > 100) {
473 } 187 usage4(
188 _("Warning threshold percentage must be <= 100!"));
474 } 189 }
190 }
191 break;
192 } else {
193 /* It's Bytes */
194 conf_wrapper.config.warn.is_percentage = false;
195 if (is_uint64(optarg, &conf_wrapper.config.warn.value)) {
475 break; 196 break;
476 } else { 197 } else {
477 /* It's Bytes */ 198 usage4(_("Warning threshold be positive integer or "
478 warn.is_percentage = 0; 199 "percentage!"));
479 if (is_uint64(optarg, &warn.value)) {
480 break;
481 } else {
482 usage4 (_("Warning threshold be positive integer or percentage!"));
483 }
484 } 200 }
485 } 201 }
202 }
486 case 'c': /* critical size threshold */ 203 case 'c': /* critical size threshold */
487 { 204 {
488 /* 205 /*
489 * We expect either a positive integer value without a unit, which means 206 * We expect either a positive integer value without a unit, which
490 * the unit is Bytes or a positive integer value and a percentage sign (%), 207 * means the unit is Bytes or a positive integer value and a
491 * which means the value must be with 0 and 100 and is relative to the total swap 208 * percentage sign (%), which means the value must be with 0 and 100
492 */ 209 * and is relative to the total swap
493 size_t length; 210 */
494 length = strlen(optarg); 211 size_t length;
495 212 length = strlen(optarg);
496 if (optarg[length - 1] == '%') { 213
497 /* It's percentage */ 214 if (optarg[length - 1] == '%') {
498 crit.is_percentage = 1; 215 /* It's percentage */
499 optarg[length - 1] = '\0'; 216 conf_wrapper.config.crit.is_percentage = true;
500 if (is_uint64(optarg, &crit.value)) { 217 optarg[length - 1] = '\0';
501 if (crit.value> 100) { 218 if (is_uint64(optarg, &conf_wrapper.config.crit.value)) {
502 usage4 (_("Critical threshold percentage must be <= 100!")); 219 if (conf_wrapper.config.crit.value > 100) {
503 } 220 usage4(
221 _("Critical threshold percentage must be <= 100!"));
504 } 222 }
223 }
224 break;
225 } else {
226 /* It's Bytes */
227 conf_wrapper.config.crit.is_percentage = false;
228 if (is_uint64(optarg, &conf_wrapper.config.crit.value)) {
505 break; 229 break;
506 } else { 230 } else {
507 /* It's Bytes */ 231 usage4(_("Critical threshold be positive integer or "
508 crit.is_percentage = 0; 232 "percentage!"));
509 if (is_uint64(optarg, &crit.value)) {
510 break;
511 } else {
512 usage4 (_("Critical threshold be positive integer or percentage!"));
513 }
514 } 233 }
515 } 234 }
516 case 'a': /* all swap */ 235 }
517 allswaps = true; 236 case 'a': /* all swap */
237 conf_wrapper.config.allswaps = true;
518 break; 238 break;
519 case 'n': 239 case 'n':
520 if ((no_swap_state = mp_translate_state(optarg)) == ERROR) { 240 if ((conf_wrapper.config.no_swap_state =
521 usage4 (_("no-swap result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 241 mp_translate_state(optarg)) == ERROR) {
242 usage4(_("no-swap result must be a valid state name (OK, "
243 "WARNING, CRITICAL, UNKNOWN) or integer (0-3)."));
522 } 244 }
523 break; 245 break;
524 case 'v': /* verbose */ 246 case 'v': /* verbose */
525 verbose++; 247 conf_wrapper.config.verbose++;
526 break; 248 break;
527 case 'V': /* version */ 249 case 'V': /* version */
528 print_revision (progname, NP_VERSION); 250 print_revision(progname, NP_VERSION);
529 exit (STATE_UNKNOWN); 251 exit(STATE_UNKNOWN);
530 case 'h': /* help */ 252 case 'h': /* help */
531 print_help (); 253 print_help(conf_wrapper.config);
532 exit (STATE_UNKNOWN); 254 exit(STATE_UNKNOWN);
533 case '?': /* error */ 255 case '?': /* error */
534 usage5 (); 256 usage5();
535 } 257 }
536 } 258 }
537 259
538 c = optind; 260 c = optind;
539 if (c == argc)
540 return validate_arguments ();
541 261
542 return validate_arguments (); 262 if (conf_wrapper.config.warn.value == 0 &&
543} 263 conf_wrapper.config.crit.value == 0) {
544 264 conf_wrapper.errorcode = ERROR;
545 265 return conf_wrapper;
546 266 } else if ((conf_wrapper.config.warn.is_percentage ==
547int 267 conf_wrapper.config.crit.is_percentage) &&
548validate_arguments (void) 268 (conf_wrapper.config.warn.value <
549{ 269 conf_wrapper.config.crit.value)) {
550 if (warn.value == 0 && crit.value == 0) { 270 /* This is NOT triggered if warn and crit are different units, e.g warn
551 return ERROR; 271 * is percentage and crit is absolute. We cannot determine the condition
552 } 272 * at this point since we dont know the value of total swap yet
553 else if ((warn.is_percentage == crit.is_percentage) && (warn.value < crit.value)) {
554 /* This is NOT triggered if warn and crit are different units, e.g warn is percentage
555 * and crit is absolute. We cannot determine the condition at this point since we
556 * dont know the value of total swap yet
557 */ 273 */
558 usage4(_("Warning should be more than critical")); 274 usage4(_("Warning should be more than critical"));
559 } 275 }
560 return OK;
561}
562 276
563 277 return conf_wrapper;
564
565void
566print_help (void)
567{
568 print_revision (progname, NP_VERSION);
569
570 printf (_(COPYRIGHT), copyright, email);
571
572 printf ("%s\n", _("Check swap space on local machine."));
573
574 printf ("\n\n");
575
576 print_usage ();
577
578 printf (UT_HELP_VRSN);
579 printf (UT_EXTRA_OPTS);
580
581 printf (" %s\n", "-w, --warning=INTEGER");
582 printf (" %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free"));
583 printf (" %s\n", "-w, --warning=PERCENT%");
584 printf (" %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free"));
585 printf (" %s\n", "-c, --critical=INTEGER");
586 printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free"));
587 printf (" %s\n", "-c, --critical=PERCENT%");
588 printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of swap space is free"));
589 printf (" %s\n", "-a, --allswaps");
590 printf (" %s\n", _("Conduct comparisons for all swap partitions, one by one"));
591 printf (" %s\n", "-n, --no-swap=<ok|warning|critical|unknown>");
592 printf (" %s %s\n", _("Resulting state when there is no swap regardless of thresholds. Default:"), state_text(no_swap_state));
593 printf (UT_VERBOSE);
594
595 printf ("\n");
596 printf ("%s\n", _("Notes:"));
597 printf (" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, they are all checked."));
598 printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s."));
599
600 printf (UT_SUPPORT);
601} 278}
602 279
280void print_help(swap_config config) {
281 print_revision(progname, NP_VERSION);
282
283 printf(_(COPYRIGHT), copyright, email);
284
285 printf("%s\n", _("Check swap space on local machine."));
286
287 printf("\n\n");
288
289 print_usage();
290
291 printf(UT_HELP_VRSN);
292 printf(UT_EXTRA_OPTS);
293
294 printf(" %s\n", "-w, --warning=INTEGER");
295 printf(" %s\n", _("Exit with WARNING status if less than INTEGER bytes "
296 "of swap space are free"));
297 printf(" %s\n", "-w, --warning=PERCENT%");
298 printf(" %s\n", _("Exit with WARNING status if less than PERCENT of "
299 "swap space is free"));
300 printf(" %s\n", "-c, --critical=INTEGER");
301 printf(" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes "
302 "of swap space are free"));
303 printf(" %s\n", "-c, --critical=PERCENT%");
304 printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of "
305 "swap space is free"));
306 printf(" %s\n", "-a, --allswaps");
307 printf(" %s\n",
308 _("Conduct comparisons for all swap partitions, one by one"));
309 printf(" %s\n", "-n, --no-swap=<ok|warning|critical|unknown>");
310 printf(" %s %s\n",
311 _("Resulting state when there is no swap regardless of thresholds. "
312 "Default:"),
313 state_text(config.no_swap_state));
314 printf(UT_VERBOSE);
315
316 printf("\n");
317 printf("%s\n", _("Notes:"));
318 printf(" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, "
319 "they are all checked."));
320 printf(
321 " %s\n",
322 _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s."));
323
324 printf(UT_SUPPORT);
325}
603 326
604void 327void print_usage() {
605print_usage (void) 328 printf("%s\n", _("Usage:"));
606{ 329 printf(" %s [-av] -w <percent_free>%% -c <percent_free>%%\n", progname);
607 printf ("%s\n", _("Usage:")); 330 printf(" -w <bytes_free> -c <bytes_free> [-n <state>]\n");
608 printf (" %s [-av] -w <percent_free>%% -c <percent_free>%%\n",progname);
609 printf (" -w <bytes_free> -c <bytes_free> [-n <state>]\n");
610} 331}
diff --git a/plugins/check_swap.d/check_swap.h b/plugins/check_swap.d/check_swap.h
new file mode 100644
index 00000000..bad52917
--- /dev/null
+++ b/plugins/check_swap.d/check_swap.h
@@ -0,0 +1,45 @@
1#ifndef CHECK_SWAP_H
2#define CHECK_SWAP_H
3
4#include "../common.h"
5
6#ifndef SWAP_CONVERSION
7#define SWAP_CONVERSION 1
8#endif
9
10typedef struct {
11 bool is_percentage;
12 uint64_t value;
13} threshold;
14
15typedef struct {
16 unsigned long long free; // Free swap in Bytes!
17 unsigned long long used; // Used swap in Bytes!
18 unsigned long long total; // Total swap size, you guessed it, in Bytes!
19} swap_metrics;
20
21typedef struct {
22 int errorcode;
23 int statusCode;
24 swap_metrics metrics;
25} swap_result;
26
27typedef struct {
28 int verbose;
29 bool allswaps;
30 int no_swap_state;
31 threshold warn;
32 threshold crit;
33 bool on_aix;
34 int conversion_factor;
35} swap_config;
36
37swap_config swap_config_init();
38
39swap_result get_swap_data(swap_config config);
40swap_result getSwapFromProcMeminfo(swap_config config, char path_to_proc_meminfo[]);
41swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[], const char swap_format[]);
42swap_result getSwapFromSwapctl_BSD(swap_config config);
43swap_result getSwapFromSwap_SRV4(swap_config config);
44
45#endif
diff --git a/plugins/check_swap.d/swap.c b/plugins/check_swap.d/swap.c
new file mode 100644
index 00000000..50920fa3
--- /dev/null
+++ b/plugins/check_swap.d/swap.c
@@ -0,0 +1,415 @@
1#include "./check_swap.d/check_swap.h"
2#include "../popen.h"
3#include "../utils.h"
4
5swap_config swap_config_init() {
6 swap_config tmp = {0};
7 tmp.allswaps = false;
8 tmp.no_swap_state = STATE_CRITICAL;
9 tmp.verbose = 0;
10 tmp.conversion_factor = SWAP_CONVERSION;
11
12#ifdef _AIX
13 tmp.on_aix = true;
14#else
15 tmp.on_aix = false;
16#endif
17
18 return tmp;
19}
20
21swap_result get_swap_data(swap_config config) {
22#ifdef HAVE_PROC_MEMINFO
23 if (config.verbose >= 3) {
24 printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
25 }
26
27 return getSwapFromProcMeminfo(config, PROC_MEMINFO);
28#else
29#ifdef HAVE_SWAP
30 if (config.verbose >= 3) {
31 printf("Using swap command %s with format: %s\n", SWAP_COMMAND, SWAP_FORMAT);
32 }
33
34 /* These override the command used if a summary (and thus ! allswaps) is
35 * required
36 * The summary flag returns more accurate information about swap usage on these
37 * OSes */
38 if (config.on_aix && !config.allswaps) {
39
40 config.conversion_factor = 1;
41
42 return getSwapFromSwapCommand(config, "/usr/sbin/lsps -s", "%lu%*s %lu");
43 } else {
44 return getSwapFromSwapCommand(config, SWAP_COMMAND, SWAP_FORMAT);
45 }
46#else
47#ifdef CHECK_SWAP_SWAPCTL_SVR4
48 return getSwapFromSwapctl_SRV4();
49#else
50#ifdef CHECK_SWAP_SWAPCTL_BSD
51 return getSwapFromSwapctl_BSD();
52#else
53#error No way found to retrieve swap
54#endif /* CHECK_SWAP_SWAPCTL_BSD */
55#endif /* CHECK_SWAP_SWAPCTL_SVR4 */
56#endif /* HAVE_SWAP */
57#endif /* HAVE_PROC_MEMINFO */
58}
59
60swap_result getSwapFromProcMeminfo(swap_config config, char proc_meminfo[]) {
61 FILE *fp;
62 fp = fopen(proc_meminfo, "r");
63
64 swap_result result = {0};
65 result.statusCode = STATE_OK;
66
67 uint64_t swap_total = 0, swap_used = 0, swap_free = 0;
68
69 char input_buffer[MAX_INPUT_BUFFER];
70 char str[32];
71
72 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
73 uint64_t tmp_KB = 0;
74
75 /*
76 * The following sscanf call looks for a line looking like: "Swap: 123
77 * 123 123" On which kind of system this format exists, I can not say,
78 * but I wanted to document this for people who are not adapt with
79 * sscanf anymore, like me
80 * Also the units used here are unclear and probably wrong
81 */
82 if (sscanf(input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu",
83 &swap_total, &swap_used, &swap_free) == 3) {
84
85 result.metrics.total += swap_total;
86 result.metrics.used += swap_used;
87 result.metrics.free += swap_free;
88
89 /*
90 * The following sscanf call looks for lines looking like:
91 * "SwapTotal: 123" and "SwapFree: 123" This format exists at least
92 * on Debian Linux with a 5.* kernel
93 */
94 } else if (sscanf(input_buffer,
95 "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %lu "
96 "%*[k]%*[B]",
97 str, &tmp_KB)) {
98
99 if (config.verbose >= 3) {
100 printf("Got %s with %lu\n", str, tmp_KB);
101 }
102
103 /* I think this part is always in Kb, so convert to bytes */
104 if (strcmp("Total", str) == 0) {
105 swap_total = tmp_KB * 1024;
106 } else if (strcmp("Free", str) == 0) {
107 swap_free = swap_free + tmp_KB * 1024;
108 } else if (strcmp("Cached", str) == 0) {
109 swap_free = swap_free + tmp_KB * 1024;
110 }
111 }
112 }
113
114 fclose(fp);
115
116 result.metrics.total = swap_total;
117 result.metrics.used = swap_total - swap_free;
118 result.metrics.free = swap_free;
119
120 return result;
121}
122
123swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[], const char swap_format[]) {
124 swap_result result = {0};
125
126 char *temp_buffer;
127
128 if (config.verbose >= 2)
129 printf(_("Command: %s\n"), swap_command);
130 if (config.verbose >= 3)
131 printf(_("Format: %s\n"), swap_format);
132
133 child_process = spopen(swap_command);
134 if (child_process == NULL) {
135 printf(_("Could not open pipe: %s\n"), swap_command);
136 swap_result tmp = {
137 .errorcode = STATE_UNKNOWN,
138 };
139 return tmp;
140 }
141
142 child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
143 if (child_stderr == NULL) {
144 printf(_("Could not open stderr for %s\n"), swap_command);
145 }
146
147 char str[32] = {0};
148 char input_buffer[MAX_INPUT_BUFFER];
149
150 /* read 1st line */
151 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process);
152 if (strcmp(swap_format, "") == 0) {
153 temp_buffer = strtok(input_buffer, " \n");
154 while (temp_buffer) {
155 if (strstr(temp_buffer, "blocks"))
156 sprintf(str, "%s %s", str, "%lu");
157 else if (strstr(temp_buffer, "dskfree"))
158 sprintf(str, "%s %s", str, "%lu");
159 else
160 sprintf(str, "%s %s", str, "%*s");
161 temp_buffer = strtok(NULL, " \n");
162 }
163 }
164
165 double total_swap_mb = 0, free_swap_mb = 0, used_swap_mb = 0;
166 double dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0;
167
168 /*
169 * If different swap command is used for summary switch, need to read format
170 * differently
171 */
172 if (config.on_aix && !config.allswaps) {
173 fgets(input_buffer, MAX_INPUT_BUFFER - 1,
174 child_process); /* Ignore first line */
175 sscanf(input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
176 free_swap_mb = total_swap_mb * (100 - used_swap_mb) / 100;
177 used_swap_mb = total_swap_mb - free_swap_mb;
178
179 if (config.verbose >= 3) {
180 printf(_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb,
181 used_swap_mb, free_swap_mb);
182 }
183 } else {
184 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
185 sscanf(input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
186
187 dsktotal_mb = dsktotal_mb / config.conversion_factor;
188 /* AIX lists percent used, so this converts to dskfree in MBs */
189
190 if (config.on_aix) {
191 dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
192 } else {
193 dskfree_mb = dskfree_mb / config.conversion_factor;
194 }
195
196 if (config.verbose >= 3)
197 printf(_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
198
199 dskused_mb = dsktotal_mb - dskfree_mb;
200 total_swap_mb += dsktotal_mb;
201 used_swap_mb += dskused_mb;
202 free_swap_mb += dskfree_mb;
203 }
204 }
205
206 result.metrics.free = free_swap_mb * 1024 * 1024;
207 result.metrics.used = used_swap_mb * 1024 * 1024;
208 result.metrics.total = free_swap_mb * 1024 * 1024;
209
210 /* If we get anything on STDERR, at least set warning */
211 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
212 result.statusCode = max_state(result.statusCode, STATE_WARNING);
213 // TODO Set error here
214 }
215
216 /* close stderr */
217 (void)fclose(child_stderr);
218
219 /* close the pipe */
220 if (spclose(child_process)) {
221 result.statusCode = max_state(result.statusCode, STATE_WARNING);
222 // TODO set error here
223 }
224
225 return result;
226}
227
228#ifndef CHECK_SWAP_SWAPCTL_BSD
229#define CHECK_SWAP_SWAPCTL_BSD
230
231// Stub functionality for BSD stuff, so the compiler always sees the following BSD code
232
233#define SWAP_NSWAP 0
234#define SWAP_STATS 1
235
236int bsd_swapctl(int cmd, const void *arg, int misc) {
237 (void) cmd;
238 (void) arg;
239 (void) misc;
240 return 512;
241}
242
243struct swapent {
244 dev_t se_dev; /* device id */
245 int se_flags; /* entry flags */
246 int se_nblks; /* total blocks */
247 int se_inuse; /* blocks in use */
248 int se_priority; /* priority */
249 char se_path[PATH_MAX]; /* path to entry */
250};
251
252#else
253#define bsd_swapctl swapctl
254#endif
255
256swap_result getSwapFromSwapctl_BSD(swap_config config) {
257 /* get the number of active swap devices */
258 int nswaps = bsd_swapctl(SWAP_NSWAP, NULL, 0);
259
260 /* initialize swap table + entries */
261 struct swapent *ent = (struct swapent *)malloc(sizeof(struct swapent) * nswaps);
262
263 /* and now, tally 'em up */
264 int swapctl_res = bsd_swapctl(SWAP_STATS, ent, nswaps);
265 if (swapctl_res < 0) {
266 perror(_("swapctl failed: "));
267 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
268 }
269
270
271 double dsktotal_mb = 0.0, dskfree_mb = 0.0, dskused_mb = 0.0;
272 unsigned long long total_swap_mb = 0, free_swap_mb = 0, used_swap_mb = 0;
273
274 for (int i = 0; i < nswaps; i++) {
275 dsktotal_mb = (float)ent[i].se_nblks / config.conversion_factor;
276 dskused_mb = (float)ent[i].se_inuse / config.conversion_factor;
277 dskfree_mb = (dsktotal_mb - dskused_mb);
278
279 if (config.allswaps && dsktotal_mb > 0) {
280 double percent = 100 * (((double)dskused_mb) / ((double)dsktotal_mb));
281
282 if (config.verbose) {
283 printf("[%.0f (%g%%)]", dskfree_mb, 100 - percent);
284 }
285 }
286
287 total_swap_mb += dsktotal_mb;
288 free_swap_mb += dskfree_mb;
289 used_swap_mb += dskused_mb;
290 }
291
292 /* and clean up after ourselves */
293 free(ent);
294
295 swap_result result = {0};
296
297 result.statusCode = OK;
298 result.errorcode = OK;
299
300 result.metrics.total = total_swap_mb * 1024 * 1024;
301 result.metrics.free = free_swap_mb * 1024 * 1024;
302 result.metrics.used = used_swap_mb * 1024 * 1024;
303
304 return result;
305}
306
307
308
309#ifndef CHECK_SWAP_SWAPCTL_SVR4
310int srv4_swapctl(int cmd, void *arg) {
311 (void) cmd;
312 (void) arg;
313 return 512;
314}
315
316typedef struct srv4_swapent {
317 char *ste_path; /* name of the swap file */
318 off_t ste_start; /* starting block for swapping */
319 off_t ste_length; /* length of swap area */
320 long ste_pages; /* number of pages for swapping */
321 long ste_free; /* number of ste_pages free */
322 long ste_flags; /* ST_INDEL bit set if swap file */
323 /* is now being deleted */
324} swapent_t;
325
326typedef struct swaptbl {
327 int swt_n; /* number of swapents following */
328 struct srv4_swapent swt_ent[]; /* array of swt_n swapents */
329} swaptbl_t;
330
331#define SC_LIST 2
332#define SC_GETNSWP 3
333
334#ifndef MAXPATHLEN
335#define MAXPATHLEN 2048
336#endif
337
338#else
339#define srv4_swapctl swapctl
340#endif
341
342swap_result getSwapFromSwap_SRV4(swap_config config) {
343 int nswaps = 0;
344
345 /* get the number of active swap devices */
346 if ((nswaps = srv4_swapctl(SC_GETNSWP, NULL)) == -1)
347 die(STATE_UNKNOWN, _("Error getting swap devices\n"));
348
349 if (nswaps == 0)
350 die(STATE_OK, _("SWAP OK: No swap devices defined\n"));
351
352 if (config.verbose >= 3)
353 printf("Found %d swap device(s)\n", nswaps);
354
355 /* initialize swap table + entries */
356 swaptbl_t *tbl = (swaptbl_t *)malloc(sizeof(swaptbl_t) + (sizeof(swapent_t) * nswaps));
357
358 if (tbl == NULL)
359 die(STATE_UNKNOWN, _("malloc() failed!\n"));
360
361 memset(tbl, 0, sizeof(swaptbl_t) + (sizeof(swapent_t) * nswaps));
362 tbl->swt_n = nswaps;
363
364 for (int i = 0; i < nswaps; i++) {
365 if ((tbl->swt_ent[i].ste_path =
366 (char *)malloc(sizeof(char) * MAXPATHLEN)) == NULL)
367 die(STATE_UNKNOWN, _("malloc() failed!\n"));
368 }
369
370 /* and now, tally 'em up */
371 int swapctl_res = srv4_swapctl(SC_LIST, tbl);
372 if (swapctl_res < 0) {
373 perror(_("swapctl failed: "));
374 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
375 }
376
377 double dsktotal_mb = 0.0, dskfree_mb = 0.0, dskused_mb = 0.0;
378 unsigned long long total_swap_mb = 0, free_swap_mb = 0, used_swap_mb = 0;
379
380 for (int i = 0; i < nswaps; i++) {
381 dsktotal_mb = (float)tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
382 dskfree_mb = (float)tbl->swt_ent[i].ste_free / SWAP_CONVERSION;
383 dskused_mb = (dsktotal_mb - dskfree_mb);
384
385 if (config.verbose >= 3)
386 printf("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n",
387 dsktotal_mb, dskfree_mb, dskused_mb);
388
389 if (config.allswaps && dsktotal_mb > 0) {
390 double percent = 100 * (((double)dskused_mb) / ((double)dsktotal_mb));
391
392 if (config.verbose) {
393 printf("[%.0f (%g%%)]", dskfree_mb, 100 - percent);
394 }
395 }
396
397 total_swap_mb += dsktotal_mb;
398 free_swap_mb += dskfree_mb;
399 used_swap_mb += dskused_mb;
400 }
401
402 /* and clean up after ourselves */
403 for (int i = 0; i < nswaps; i++) {
404 free(tbl->swt_ent[i].ste_path);
405 }
406 free(tbl);
407
408 swap_result result = {0};
409 result.errorcode = OK;
410 result.metrics.total = total_swap_mb * 1024 * 1024;
411 result.metrics.free = free_swap_mb * 1024 * 1024;
412 result.metrics.used = used_swap_mb * 1024 * 1024;
413
414 return result;
415}
diff --git a/plugins/tests/test_check_swap.c b/plugins/tests/test_check_swap.c
new file mode 100644
index 00000000..86ab188f
--- /dev/null
+++ b/plugins/tests/test_check_swap.c
@@ -0,0 +1,24 @@
1
2#include "../check_swap.d/check_swap.h"
3#include "../../tap/tap.h"
4
5void print_usage() {};
6void print_help(swap_config config) {
7 (void) config;
8};
9
10const char *progname = "test_check_swap";
11
12int main() {
13
14 swap_config config = swap_config_init();
15
16 swap_result test_data = getSwapFromProcMeminfo(config, "./var/proc_meminfo");
17
18 plan_tests(4);
19
20 ok(test_data.errorcode == 0, "Test whether we manage to retrieve swap data");
21 ok(test_data.metrics.total == 34233905152, "Is the total Swap correct");
22 ok(test_data.metrics.free == 34231021568, "Is the free Swap correct");
23 ok(test_data.metrics.used == 0, "Is the used Swap correct");
24}
diff --git a/plugins/tests/test_check_swap.t b/plugins/tests/test_check_swap.t
new file mode 100644
index 00000000..97c651a8
--- /dev/null
+++ b/plugins/tests/test_check_swap.t
@@ -0,0 +1,6 @@
1#!/usr/bin/perl
2use Test::More;
3if (! -e "./test_check_swap") {
4 plan skip_all => "./test_swap not compiled - please enable libtap library to test";
5}
6exec "./test_check_swap";
diff --git a/plugins/tests/var/proc_meminfo b/plugins/tests/var/proc_meminfo
new file mode 100644
index 00000000..8c94c4e5
--- /dev/null
+++ b/plugins/tests/var/proc_meminfo
@@ -0,0 +1,55 @@
1MemTotal: 32767776 kB
2MemFree: 1693508 kB
3MemAvailable: 23807480 kB
4Buffers: 438456 kB
5Cached: 19124976 kB
6SwapCached: 136 kB
7Active: 7860680 kB
8Inactive: 18886776 kB
9Active(anon): 6108756 kB
10Inactive(anon): 1364500 kB
11Active(file): 1751924 kB
12Inactive(file): 17522276 kB
13Unevictable: 8548 kB
14Mlocked: 8548 kB
15SwapTotal: 33431548 kB
16SwapFree: 33428732 kB
17Zswap: 0 kB
18Zswapped: 0 kB
19Dirty: 784 kB
20Writeback: 0 kB
21AnonPages: 7139968 kB
22Mapped: 1094916 kB
23Shmem: 284160 kB
24KReclaimable: 3303788 kB
25Slab: 3801908 kB
26SReclaimable: 3303788 kB
27SUnreclaim: 498120 kB
28KernelStack: 32992 kB
29PageTables: 68160 kB
30SecPageTables: 0 kB
31NFS_Unstable: 0 kB
32Bounce: 0 kB
33WritebackTmp: 0 kB
34CommitLimit: 49815436 kB
35Committed_AS: 16888536 kB
36VmallocTotal: 34359738367 kB
37VmallocUsed: 91200 kB
38VmallocChunk: 0 kB
39Percpu: 41472 kB
40HardwareCorrupted: 0 kB
41AnonHugePages: 1708032 kB
42ShmemHugePages: 0 kB
43ShmemPmdMapped: 0 kB
44FileHugePages: 0 kB
45FilePmdMapped: 0 kB
46Unaccepted: 0 kB
47HugePages_Total: 0
48HugePages_Free: 0
49HugePages_Rsvd: 0
50HugePages_Surp: 0
51Hugepagesize: 2048 kB
52Hugetlb: 0 kB
53DirectMap4k: 860468 kB
54DirectMap2M: 20023296 kB
55DirectMap1G: 12582912 kB