From 599c137fd3d522793dc022644b8b6566b75628cb Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Thu, 20 Feb 2025 17:11:06 +0100
Subject: clang-format
---
plugins/check_mysql.c | 603 +++++++++++++++++++++++---------------------------
1 file changed, 282 insertions(+), 321 deletions(-)
diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c
index 8a73772d..09c0b7dd 100644
--- a/plugins/check_mysql.c
+++ b/plugins/check_mysql.c
@@ -1,34 +1,34 @@
/*****************************************************************************
-*
-* Monitoring check_mysql plugin
-*
-* License: GPL
-* Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at)
-* Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
-* Copyright (c) 1999-2024 Monitoring Plugins Development Team
-*
-* Description:
-*
-* This file contains the check_mysql plugin
-*
-* This program tests connections to a mysql server
-*
-*
-* This program is free software: you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation, either version 3 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program. If not, see .
-*
-*
-*****************************************************************************/
+ *
+ * Monitoring check_mysql plugin
+ *
+ * License: GPL
+ * Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at)
+ * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
+ * Copyright (c) 1999-2024 Monitoring Plugins Development Team
+ *
+ * Description:
+ *
+ * This file contains the check_mysql plugin
+ *
+ * This program tests connections to a mysql server
+ *
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ *
+ *
+ *****************************************************************************/
const char *progname = "check_mysql";
const char *copyright = "1999-2024";
@@ -68,39 +68,24 @@ static double critical_time = 0;
#define LENGTH_METRIC_UNIT 6
static const char *metric_unit[LENGTH_METRIC_UNIT] = {
- "Open_files",
- "Open_tables",
- "Qcache_free_memory",
- "Qcache_queries_in_cache",
- "Threads_connected",
- "Threads_running"
-};
+ "Open_files", "Open_tables", "Qcache_free_memory", "Qcache_queries_in_cache", "Threads_connected", "Threads_running"};
#define LENGTH_METRIC_COUNTER 9
static const char *metric_counter[LENGTH_METRIC_COUNTER] = {
- "Connections",
- "Qcache_hits",
- "Qcache_inserts",
- "Qcache_lowmem_prunes",
- "Qcache_not_cached",
- "Queries",
- "Questions",
- "Table_locks_waited",
- "Uptime"
-};
-
-#define MYSQLDUMP_THREADS_QUERY "SELECT COUNT(1) mysqldumpThreads FROM information_schema.processlist WHERE info LIKE 'SELECT /*!40001 SQL_NO_CACHE */%'"
+ "Connections", "Qcache_hits", "Qcache_inserts", "Qcache_lowmem_prunes", "Qcache_not_cached", "Queries",
+ "Questions", "Table_locks_waited", "Uptime"};
+
+#define MYSQLDUMP_THREADS_QUERY \
+ "SELECT COUNT(1) mysqldumpThreads FROM information_schema.processlist WHERE info LIKE 'SELECT /*!40001 SQL_NO_CACHE */%'"
static thresholds *my_threshold = NULL;
-static int process_arguments (int, char **);
-static int validate_arguments (void);
-static void print_help (void);
-void print_usage (void);
+static int process_arguments(int, char **);
+static int validate_arguments(void);
+static void print_help(void);
+void print_usage(void);
-int
-main (int argc, char **argv)
-{
+int main(int argc, char **argv) {
MYSQL mysql;
MYSQL_RES *res;
@@ -110,152 +95,152 @@ main (int argc, char **argv)
char *result = NULL;
char *error = NULL;
- char slaveresult[SLAVERESULTSIZE] = { 0 };
- char* perf;
+ char slaveresult[SLAVERESULTSIZE] = {0};
+ char *perf;
- perf = strdup ("");
+ perf = strdup("");
- setlocale (LC_ALL, "");
- bindtextdomain (PACKAGE, LOCALEDIR);
- textdomain (PACKAGE);
+ setlocale(LC_ALL, "");
+ bindtextdomain(PACKAGE, LOCALEDIR);
+ textdomain(PACKAGE);
/* Parse extra opts if any */
- argv=np_extra_opts (&argc, argv, progname);
+ argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments (argc, argv) == ERROR)
- usage4 (_("Could not parse arguments"));
+ if (process_arguments(argc, argv) == ERROR) {
+ usage4(_("Could not parse arguments"));
+ }
/* initialize mysql */
- mysql_init (&mysql);
-
- if (opt_file != NULL)
- mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);
-
- if (opt_group != NULL)
- mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
- else
- mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");
-
- if (ssl)
- mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
+ mysql_init(&mysql);
+
+ if (opt_file != NULL) {
+ mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, opt_file);
+ }
+
+ if (opt_group != NULL) {
+ mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, opt_group);
+ } else {
+ mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "client");
+ }
+
+ if (ssl) {
+ mysql_ssl_set(&mysql, key, cert, ca_cert, ca_dir, ciphers);
+ }
/* establish a connection to the server and error checking */
- if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) {
+ if (!mysql_real_connect(&mysql, db_host, db_user, db_pass, db, db_port, db_socket, 0)) {
/* Depending on internally-selected auth plugin MySQL might return */
/* ER_ACCESS_DENIED_NO_PASSWORD_ERROR or ER_ACCESS_DENIED_ERROR. */
/* Semantically these errors are the same. */
- if (ignore_auth && (mysql_errno (&mysql) == ER_ACCESS_DENIED_ERROR || mysql_errno (&mysql) == ER_ACCESS_DENIED_NO_PASSWORD_ERROR))
- {
- printf("MySQL OK - Version: %s (protocol %d)\n",
- mysql_get_server_info(&mysql),
- mysql_get_proto_info(&mysql)
- );
- mysql_close (&mysql);
+ if (ignore_auth && (mysql_errno(&mysql) == ER_ACCESS_DENIED_ERROR || mysql_errno(&mysql) == ER_ACCESS_DENIED_NO_PASSWORD_ERROR)) {
+ printf("MySQL OK - Version: %s (protocol %d)\n", mysql_get_server_info(&mysql), mysql_get_proto_info(&mysql));
+ mysql_close(&mysql);
return STATE_OK;
+ } else if (mysql_errno(&mysql) == CR_UNKNOWN_HOST) {
+ die(STATE_WARNING, "%s\n", mysql_error(&mysql));
+ } else if (mysql_errno(&mysql) == CR_VERSION_ERROR) {
+ die(STATE_WARNING, "%s\n", mysql_error(&mysql));
+ } else if (mysql_errno(&mysql) == CR_OUT_OF_MEMORY) {
+ die(STATE_WARNING, "%s\n", mysql_error(&mysql));
+ } else if (mysql_errno(&mysql) == CR_IPSOCK_ERROR) {
+ die(STATE_WARNING, "%s\n", mysql_error(&mysql));
+ } else if (mysql_errno(&mysql) == CR_SOCKET_CREATE_ERROR) {
+ die(STATE_WARNING, "%s\n", mysql_error(&mysql));
+ } else {
+ die(STATE_CRITICAL, "%s\n", mysql_error(&mysql));
}
- else if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
- die (STATE_WARNING, "%s\n", mysql_error (&mysql));
- else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
- die (STATE_WARNING, "%s\n", mysql_error (&mysql));
- else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
- die (STATE_WARNING, "%s\n", mysql_error (&mysql));
- else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
- die (STATE_WARNING, "%s\n", mysql_error (&mysql));
- else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
- die (STATE_WARNING, "%s\n", mysql_error (&mysql));
- else
- die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
}
/* get the server stats */
- result = strdup (mysql_stat (&mysql));
+ result = strdup(mysql_stat(&mysql));
/* error checking once more */
- if (mysql_error (&mysql)) {
- if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
- die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
- else if (mysql_errno (&mysql) == CR_SERVER_LOST)
- die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
- else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
- die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
+ if (mysql_error(&mysql)) {
+ if (mysql_errno(&mysql) == CR_SERVER_GONE_ERROR) {
+ die(STATE_CRITICAL, "%s\n", mysql_error(&mysql));
+ } else if (mysql_errno(&mysql) == CR_SERVER_LOST) {
+ die(STATE_CRITICAL, "%s\n", mysql_error(&mysql));
+ } else if (mysql_errno(&mysql) == CR_UNKNOWN_ERROR) {
+ die(STATE_CRITICAL, "%s\n", mysql_error(&mysql));
+ }
}
/* try to fetch some perf data */
- if (mysql_query (&mysql, "show global status") == 0) {
- if ( (res = mysql_store_result (&mysql)) == NULL) {
+ if (mysql_query(&mysql, "show global status") == 0) {
+ if ((res = mysql_store_result(&mysql)) == NULL) {
error = strdup(mysql_error(&mysql));
- mysql_close (&mysql);
- die (STATE_CRITICAL, _("status store_result error: %s\n"), error);
+ mysql_close(&mysql);
+ die(STATE_CRITICAL, _("status store_result error: %s\n"), error);
}
- while ( (row = mysql_fetch_row (res)) != NULL) {
+ while ((row = mysql_fetch_row(res)) != NULL) {
int i;
- for(i = 0; i < LENGTH_METRIC_UNIT; i++) {
+ for (i = 0; i < LENGTH_METRIC_UNIT; i++) {
if (strcmp(row[0], metric_unit[i]) == 0) {
- xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i],
- atol(row[1]), "", false, 0, false, 0, false, 0, false, 0));
+ xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i], atol(row[1]), "", false, 0, false, 0, false, 0, false, 0));
continue;
}
}
- for(i = 0; i < LENGTH_METRIC_COUNTER; i++) {
+ for (i = 0; i < LENGTH_METRIC_COUNTER; i++) {
if (strcmp(row[0], metric_counter[i]) == 0) {
- xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i],
- atol(row[1]), "c", false, 0, false, 0, false, 0, false, 0));
+ xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i], atol(row[1]), "c", false, 0, false, 0, false, 0, false, 0));
continue;
}
}
}
/* remove trailing space */
- if (strlen(perf) > 0)
- perf[strlen(perf) - 1] = '\0';
+ if (strlen(perf) > 0) {
+ perf[strlen(perf) - 1] = '\0';
+ }
}
- if(check_slave) {
+ if (check_slave) {
/* check the slave status */
- if (mysql_query (&mysql, "show slave status") != 0) {
+ if (mysql_query(&mysql, "show slave status") != 0) {
error = strdup(mysql_error(&mysql));
- mysql_close (&mysql);
- die (STATE_CRITICAL, _("slave query error: %s\n"), error);
+ mysql_close(&mysql);
+ die(STATE_CRITICAL, _("slave query error: %s\n"), error);
}
/* store the result */
- if ( (res = mysql_store_result (&mysql)) == NULL) {
+ if ((res = mysql_store_result(&mysql)) == NULL) {
error = strdup(mysql_error(&mysql));
- mysql_close (&mysql);
- die (STATE_CRITICAL, _("slave store_result error: %s\n"), error);
+ mysql_close(&mysql);
+ die(STATE_CRITICAL, _("slave store_result error: %s\n"), error);
}
/* Check there is some data */
if (mysql_num_rows(res) == 0) {
mysql_close(&mysql);
- die (STATE_WARNING, "%s\n", _("No slaves defined"));
+ die(STATE_WARNING, "%s\n", _("No slaves defined"));
}
/* fetch the first row */
- if ( (row = mysql_fetch_row (res)) == NULL) {
+ if ((row = mysql_fetch_row(res)) == NULL) {
error = strdup(mysql_error(&mysql));
- mysql_free_result (res);
- mysql_close (&mysql);
- die (STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
+ mysql_free_result(res);
+ mysql_close(&mysql);
+ die(STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
}
- if (mysql_field_count (&mysql) == 12) {
+ if (mysql_field_count(&mysql) == 12) {
/* mysql 3.23.x */
- snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
- if (strcmp (row[6], "Yes") != 0) {
- mysql_free_result (res);
- mysql_close (&mysql);
- die (STATE_CRITICAL, "%s\n", slaveresult);
+ snprintf(slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
+ if (strcmp(row[6], "Yes") != 0) {
+ mysql_free_result(res);
+ mysql_close(&mysql);
+ die(STATE_CRITICAL, "%s\n", slaveresult);
}
} else {
/* mysql 4.x.x and mysql 5.x.x */
- int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
- MYSQL_FIELD* fields;
+ int slave_io_field = -1, slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
+ MYSQL_FIELD *fields;
num_fields = mysql_num_fields(res);
fields = mysql_fetch_fields(res);
- for(i = 0; i < num_fields; i++) {
+ for (i = 0; i < num_fields; i++) {
if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
slave_io_field = i;
continue;
@@ -272,60 +257,59 @@ main (int argc, char **argv)
/* Check if slave status is available */
if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
- mysql_free_result (res);
- mysql_close (&mysql);
- die (STATE_CRITICAL, "Slave status unavailable\n");
+ mysql_free_result(res);
+ mysql_close(&mysql);
+ die(STATE_CRITICAL, "Slave status unavailable\n");
}
/* Save slave status in slaveresult */
- snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");
+ snprintf(slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field],
+ row[slave_sql_field], seconds_behind_field != -1 ? row[seconds_behind_field] : "Unknown");
/* Raise critical error if SQL THREAD or IO THREAD are stopped, but only if there are no mysqldump threads running */
- if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
+ if (strcmp(row[slave_io_field], "Yes") != 0 || strcmp(row[slave_sql_field], "Yes") != 0) {
MYSQL_RES *res_mysqldump;
MYSQL_ROW row_mysqldump;
unsigned int mysqldump_threads = 0;
- if (mysql_query (&mysql, MYSQLDUMP_THREADS_QUERY) == 0) {
+ if (mysql_query(&mysql, MYSQLDUMP_THREADS_QUERY) == 0) {
/* store the result */
- if ( (res_mysqldump = mysql_store_result (&mysql)) != NULL) {
+ if ((res_mysqldump = mysql_store_result(&mysql)) != NULL) {
if (mysql_num_rows(res_mysqldump) == 1) {
- if ( (row_mysqldump = mysql_fetch_row (res_mysqldump)) != NULL) {
+ if ((row_mysqldump = mysql_fetch_row(res_mysqldump)) != NULL) {
mysqldump_threads = atoi(row_mysqldump[0]);
}
}
/* free the result */
- mysql_free_result (res_mysqldump);
+ mysql_free_result(res_mysqldump);
}
- mysql_close (&mysql);
+ mysql_close(&mysql);
}
if (mysqldump_threads == 0) {
- die (STATE_CRITICAL, "%s\n", slaveresult);
+ die(STATE_CRITICAL, "%s\n", slaveresult);
} else {
- strncat(slaveresult, " Mysqldump: in progress", SLAVERESULTSIZE-1);
+ strncat(slaveresult, " Mysqldump: in progress", SLAVERESULTSIZE - 1);
}
}
- if (verbose >=3) {
+ if (verbose >= 3) {
if (seconds_behind_field == -1) {
printf("seconds_behind_field not found\n");
} else {
- printf ("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
+ printf("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
}
}
/* Check Seconds Behind against threshold */
- if ((seconds_behind_field != -1) && (row[seconds_behind_field] != NULL && strcmp (row[seconds_behind_field], "NULL") != 0)) {
+ if ((seconds_behind_field != -1) && (row[seconds_behind_field] != NULL && strcmp(row[seconds_behind_field], "NULL") != 0)) {
double value = atof(row[seconds_behind_field]);
int status;
status = get_status(value, my_threshold);
- xasprintf (&perf, "%s %s", perf, fperfdata ("seconds behind master", value, "s",
- true, (double) warning_time,
- true, (double) critical_time,
- false, 0,
- false, 0));
+ xasprintf(&perf, "%s %s", perf,
+ fperfdata("seconds behind master", value, "s", true, (double)warning_time, true, (double)critical_time, false, 0,
+ false, 0));
if (status == STATE_WARNING) {
printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
@@ -338,82 +322,66 @@ main (int argc, char **argv)
}
/* free the result */
- mysql_free_result (res);
+ mysql_free_result(res);
}
/* close the connection */
- mysql_close (&mysql);
+ mysql_close(&mysql);
/* print out the result of stats */
if (check_slave) {
- printf ("%s %s|%s\n", result, slaveresult, perf);
+ printf("%s %s|%s\n", result, slaveresult, perf);
} else {
- printf ("%s|%s\n", result, perf);
+ printf("%s|%s\n", result, perf);
}
return STATE_OK;
}
-
/* process command-line arguments */
-int
-process_arguments (int argc, char **argv)
-{
+int process_arguments(int argc, char **argv) {
int c;
char *warning = NULL;
char *critical = NULL;
int option = 0;
- static struct option longopts[] = {
- {"hostname", required_argument, 0, 'H'},
- {"socket", required_argument, 0, 's'},
- {"database", required_argument, 0, 'd'},
- {"username", required_argument, 0, 'u'},
- {"password", required_argument, 0, 'p'},
- {"file", required_argument, 0, 'f'},
- {"group", required_argument, 0, 'g'},
- {"port", required_argument, 0, 'P'},
- {"critical", required_argument, 0, 'c'},
- {"warning", required_argument, 0, 'w'},
- {"check-slave", no_argument, 0, 'S'},
- {"ignore-auth", no_argument, 0, 'n'},
- {"verbose", no_argument, 0, 'v'},
- {"version", no_argument, 0, 'V'},
- {"help", no_argument, 0, 'h'},
- {"ssl", no_argument, 0, 'l'},
- {"ca-cert", optional_argument, 0, 'C'},
- {"key", required_argument,0,'k'},
- {"cert", required_argument,0,'a'},
- {"ca-dir", required_argument, 0, 'D'},
- {"ciphers", required_argument, 0, 'L'},
- {0, 0, 0, 0}
- };
-
- if (argc < 1)
+ static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"socket", required_argument, 0, 's'},
+ {"database", required_argument, 0, 'd'}, {"username", required_argument, 0, 'u'},
+ {"password", required_argument, 0, 'p'}, {"file", required_argument, 0, 'f'},
+ {"group", required_argument, 0, 'g'}, {"port", required_argument, 0, 'P'},
+ {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'},
+ {"check-slave", no_argument, 0, 'S'}, {"ignore-auth", no_argument, 0, 'n'},
+ {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'},
+ {"help", no_argument, 0, 'h'}, {"ssl", no_argument, 0, 'l'},
+ {"ca-cert", optional_argument, 0, 'C'}, {"key", required_argument, 0, 'k'},
+ {"cert", required_argument, 0, 'a'}, {"ca-dir", required_argument, 0, 'D'},
+ {"ciphers", required_argument, 0, 'L'}, {0, 0, 0, 0}};
+
+ if (argc < 1) {
return ERROR;
+ }
while (1) {
- c = getopt_long (argc, argv, "hlvVnSP:p:u:d:H:s:c:w:a:k:C:D:L:f:g:", longopts, &option);
+ c = getopt_long(argc, argv, "hlvVnSP:p:u:d:H:s:c:w:a:k:C:D:L:f:g:", longopts, &option);
- if (c == -1 || c == EOF)
+ if (c == -1 || c == EOF) {
break;
+ }
switch (c) {
- case 'H': /* hostname */
- if (is_host (optarg)) {
+ case 'H': /* hostname */
+ if (is_host(optarg)) {
db_host = optarg;
- }
- else if (*optarg == '/') {
+ } else if (*optarg == '/') {
db_socket = optarg;
- }
- else {
- usage2 (_("Invalid hostname/address"), optarg);
+ } else {
+ usage2(_("Invalid hostname/address"), optarg);
}
break;
- case 's': /* socket */
+ case 's': /* socket */
db_socket = optarg;
break;
- case 'd': /* database */
+ case 'd': /* database */
db = optarg;
break;
case 'l':
@@ -434,10 +402,10 @@ process_arguments (int argc, char **argv)
case 'L':
ciphers = optarg;
break;
- case 'u': /* username */
+ case 'u': /* username */
db_user = optarg;
break;
- case 'p': /* authentication information: password */
+ case 'p': /* authentication information: password */
db_pass = strdup(optarg);
/* Delete the password from process list */
@@ -446,40 +414,40 @@ process_arguments (int argc, char **argv)
optarg++;
}
break;
- case 'f': /* client options file */
+ case 'f': /* client options file */
opt_file = optarg;
break;
- case 'g': /* client options group */
+ case 'g': /* client options group */
opt_group = optarg;
break;
- case 'P': /* critical time threshold */
- db_port = atoi (optarg);
+ case 'P': /* critical time threshold */
+ db_port = atoi(optarg);
break;
case 'S':
- check_slave = true; /* check-slave */
+ check_slave = true; /* check-slave */
break;
case 'n':
- ignore_auth = true; /* ignore-auth */
+ ignore_auth = true; /* ignore-auth */
break;
case 'w':
warning = optarg;
- warning_time = strtod (warning, NULL);
+ warning_time = strtod(warning, NULL);
break;
case 'c':
critical = optarg;
- critical_time = strtod (critical, NULL);
+ critical_time = strtod(critical, NULL);
break;
- case 'V': /* version */
- print_revision (progname, NP_VERSION);
- exit (STATE_UNKNOWN);
- case 'h': /* help */
- print_help ();
- exit (STATE_UNKNOWN);
+ case 'V': /* version */
+ print_revision(progname, NP_VERSION);
+ exit(STATE_UNKNOWN);
+ case 'h': /* help */
+ print_help();
+ exit(STATE_UNKNOWN);
case 'v':
verbose++;
break;
- case '?': /* help */
- usage5 ();
+ case '?': /* help */
+ usage5();
}
}
@@ -487,126 +455,119 @@ process_arguments (int argc, char **argv)
set_thresholds(&my_threshold, warning, critical);
- while ( argc > c ) {
+ while (argc > c) {
- if (db_host == NULL)
- if (is_host (argv[c])) {
+ if (db_host == NULL) {
+ if (is_host(argv[c])) {
db_host = argv[c++];
+ } else {
+ usage2(_("Invalid hostname/address"), argv[c]);
}
- else {
- usage2 (_("Invalid hostname/address"), argv[c]);
- }
- else if (db_user == NULL)
+ } else if (db_user == NULL) {
db_user = argv[c++];
- else if (db_pass == NULL)
+ } else if (db_pass == NULL) {
db_pass = argv[c++];
- else if (db == NULL)
+ } else if (db == NULL) {
db = argv[c++];
- else if (is_intnonneg (argv[c]))
- db_port = atoi (argv[c++]);
- else
+ } else if (is_intnonneg(argv[c])) {
+ db_port = atoi(argv[c++]);
+ } else {
break;
+ }
}
- return validate_arguments ();
+ return validate_arguments();
}
-
-int
-validate_arguments (void)
-{
- if (db_user == NULL)
+int validate_arguments(void) {
+ if (db_user == NULL) {
db_user = strdup("");
+ }
- if (db_host == NULL)
+ if (db_host == NULL) {
db_host = strdup("");
+ }
- if (db == NULL)
+ if (db == NULL) {
db = strdup("");
+ }
return OK;
}
-
-void
-print_help (void)
-{
+void print_help(void) {
char *myport;
- xasprintf (&myport, "%d", MYSQL_PORT);
-
- print_revision (progname, NP_VERSION);
-
- printf (_(COPYRIGHT), copyright, email);
-
- printf ("%s\n", _("This program tests connections to a MySQL server"));
-
- printf ("\n\n");
-
- print_usage ();
-
- printf (UT_HELP_VRSN);
- printf (UT_EXTRA_OPTS);
-
- printf (UT_HOST_PORT, 'P', myport);
- printf (" %s\n", "-n, --ignore-auth");
- printf (" %s\n", _("Ignore authentication failure and check for mysql connectivity only"));
-
- printf (" %s\n", "-s, --socket=STRING");
- printf (" %s\n", _("Use the specified socket (has no effect if -H is used)"));
-
- printf (" %s\n", "-d, --database=STRING");
- printf (" %s\n", _("Check database with indicated name"));
- printf (" %s\n", "-f, --file=STRING");
- printf (" %s\n", _("Read from the specified client options file"));
- printf (" %s\n", "-g, --group=STRING");
- printf (" %s\n", _("Use a client options group"));
- printf (" %s\n", "-u, --username=STRING");
- printf (" %s\n", _("Connect using the indicated username"));
- printf (" %s\n", "-p, --password=STRING");
- printf (" %s\n", _("Use the indicated password to authenticate the connection"));
- printf (" ==> %s <==\n", _("IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!!"));
- printf (" %s\n", _("Your clear-text password could be visible as a process table entry"));
- printf (" %s\n", "-S, --check-slave");
- printf (" %s\n", _("Check if the slave thread is running properly."));
- printf (" %s\n", "-w, --warning");
- printf (" %s\n", _("Exit with WARNING status if slave server is more than INTEGER seconds"));
- printf (" %s\n", _("behind master"));
- printf (" %s\n", "-c, --critical");
- printf (" %s\n", _("Exit with CRITICAL status if slave server is more then INTEGER seconds"));
- printf (" %s\n", _("behind master"));
- printf (" %s\n", "-l, --ssl");
- printf (" %s\n", _("Use ssl encryption"));
- printf (" %s\n", "-C, --ca-cert=STRING");
- printf (" %s\n", _("Path to CA signing the cert"));
- printf (" %s\n", "-a, --cert=STRING");
- printf (" %s\n", _("Path to SSL certificate"));
- printf (" %s\n", "-k, --key=STRING");
- printf (" %s\n", _("Path to private SSL key"));
- printf (" %s\n", "-D, --ca-dir=STRING");
- printf (" %s\n", _("Path to CA directory"));
- printf (" %s\n", "-L, --ciphers=STRING");
- printf (" %s\n", _("List of valid SSL ciphers"));
-
-
- printf ("\n");
- printf (" %s\n", _("There are no required arguments. By default, the local database is checked"));
- printf (" %s\n", _("using the default unix socket. You can force TCP on localhost by using an"));
- printf (" %s\n", _("IP address or FQDN ('localhost' will use the socket as well)."));
-
- printf ("\n");
- printf ("%s\n", _("Notes:"));
- printf (" %s\n", _("You must specify -p with an empty string to force an empty password,"));
- printf (" %s\n", _("overriding any my.cnf settings."));
-
- printf (UT_SUPPORT);
+ xasprintf(&myport, "%d", MYSQL_PORT);
+
+ print_revision(progname, NP_VERSION);
+
+ printf(_(COPYRIGHT), copyright, email);
+
+ printf("%s\n", _("This program tests connections to a MySQL server"));
+
+ printf("\n\n");
+
+ print_usage();
+
+ printf(UT_HELP_VRSN);
+ printf(UT_EXTRA_OPTS);
+
+ printf(UT_HOST_PORT, 'P', myport);
+ printf(" %s\n", "-n, --ignore-auth");
+ printf(" %s\n", _("Ignore authentication failure and check for mysql connectivity only"));
+
+ printf(" %s\n", "-s, --socket=STRING");
+ printf(" %s\n", _("Use the specified socket (has no effect if -H is used)"));
+
+ printf(" %s\n", "-d, --database=STRING");
+ printf(" %s\n", _("Check database with indicated name"));
+ printf(" %s\n", "-f, --file=STRING");
+ printf(" %s\n", _("Read from the specified client options file"));
+ printf(" %s\n", "-g, --group=STRING");
+ printf(" %s\n", _("Use a client options group"));
+ printf(" %s\n", "-u, --username=STRING");
+ printf(" %s\n", _("Connect using the indicated username"));
+ printf(" %s\n", "-p, --password=STRING");
+ printf(" %s\n", _("Use the indicated password to authenticate the connection"));
+ printf(" ==> %s <==\n", _("IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!!"));
+ printf(" %s\n", _("Your clear-text password could be visible as a process table entry"));
+ printf(" %s\n", "-S, --check-slave");
+ printf(" %s\n", _("Check if the slave thread is running properly."));
+ printf(" %s\n", "-w, --warning");
+ printf(" %s\n", _("Exit with WARNING status if slave server is more than INTEGER seconds"));
+ printf(" %s\n", _("behind master"));
+ printf(" %s\n", "-c, --critical");
+ printf(" %s\n", _("Exit with CRITICAL status if slave server is more then INTEGER seconds"));
+ printf(" %s\n", _("behind master"));
+ printf(" %s\n", "-l, --ssl");
+ printf(" %s\n", _("Use ssl encryption"));
+ printf(" %s\n", "-C, --ca-cert=STRING");
+ printf(" %s\n", _("Path to CA signing the cert"));
+ printf(" %s\n", "-a, --cert=STRING");
+ printf(" %s\n", _("Path to SSL certificate"));
+ printf(" %s\n", "-k, --key=STRING");
+ printf(" %s\n", _("Path to private SSL key"));
+ printf(" %s\n", "-D, --ca-dir=STRING");
+ printf(" %s\n", _("Path to CA directory"));
+ printf(" %s\n", "-L, --ciphers=STRING");
+ printf(" %s\n", _("List of valid SSL ciphers"));
+
+ printf("\n");
+ printf(" %s\n", _("There are no required arguments. By default, the local database is checked"));
+ printf(" %s\n", _("using the default unix socket. You can force TCP on localhost by using an"));
+ printf(" %s\n", _("IP address or FQDN ('localhost' will use the socket as well)."));
+
+ printf("\n");
+ printf("%s\n", _("Notes:"));
+ printf(" %s\n", _("You must specify -p with an empty string to force an empty password,"));
+ printf(" %s\n", _("overriding any my.cnf settings."));
+
+ printf(UT_SUPPORT);
}
-
-void
-print_usage (void)
-{
- printf ("%s\n", _("Usage:"));
- printf (" %s [-d database] [-H host] [-P port] [-s socket]\n",progname);
- printf (" [-u user] [-p password] [-S] [-l] [-a cert] [-k key]\n");
- printf (" [-C ca-cert] [-D ca-dir] [-L ciphers] [-f optfile] [-g group]\n");
+void print_usage(void) {
+ printf("%s\n", _("Usage:"));
+ printf(" %s [-d database] [-H host] [-P port] [-s socket]\n", progname);
+ printf(" [-u user] [-p password] [-S] [-l] [-a cert] [-k key]\n");
+ printf(" [-C ca-cert] [-D ca-dir] [-L ciphers] [-f optfile] [-g group]\n");
}
--
cgit v1.2.3-74-g34f1
From b8f203ace7ed09ac97fb98da63e71da07efb7354 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Thu, 20 Feb 2025 18:05:36 +0100
Subject: Rename variable check_slave to check_replica
---
plugins/check_mysql.c | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c
index 09c0b7dd..6ba12feb 100644
--- a/plugins/check_mysql.c
+++ b/plugins/check_mysql.c
@@ -59,7 +59,7 @@ static bool ssl = false;
static char *opt_file = NULL;
static char *opt_group = NULL;
static unsigned int db_port = MYSQL_PORT;
-static bool check_slave = false;
+static bool check_replica = false;
static bool ignore_auth = false;
static int verbose = 0;
@@ -195,7 +195,7 @@ int main(int argc, char **argv) {
}
}
- if (check_slave) {
+ if (check_replica) {
/* check the slave status */
if (mysql_query(&mysql, "show slave status") != 0) {
error = strdup(mysql_error(&mysql));
@@ -329,7 +329,7 @@ int main(int argc, char **argv) {
mysql_close(&mysql);
/* print out the result of stats */
- if (check_slave) {
+ if (check_replica) {
printf("%s %s|%s\n", result, slaveresult, perf);
} else {
printf("%s|%s\n", result, perf);
@@ -424,7 +424,7 @@ int process_arguments(int argc, char **argv) {
db_port = atoi(optarg);
break;
case 'S':
- check_slave = true; /* check-slave */
+ check_replica = true; /* check-slave */
break;
case 'n':
ignore_auth = true; /* ignore-auth */
--
cgit v1.2.3-74-g34f1
From 97894cdd17962efe611c981de40eaab8c3b3e43a Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Thu, 20 Feb 2025 18:09:24 +0100
Subject: Add check-replica option for check_mysql, deprecate check_slave
This commit adds an option "check-replica" to check_mysql which
replaces "check-slave" (which still works).
The changes are introduced to follow the naming scheme of
MySQL/MariaDB, since this was changed there in version 8 (MySQL) or
10.5.1 (MariaDB).
---
plugins/check_mysql.c | 92 ++++++++++++++++++++++++++++++---------------------
1 file changed, 55 insertions(+), 37 deletions(-)
diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c
index 6ba12feb..039a42e5 100644
--- a/plugins/check_mysql.c
+++ b/plugins/check_mysql.c
@@ -34,7 +34,7 @@ const char *progname = "check_mysql";
const char *copyright = "1999-2024";
const char *email = "devel@monitoring-plugins.org";
-#define SLAVERESULTSIZE 96
+#define REPLICA_RESULTSIZE 96
#include "common.h"
#include "utils.h"
@@ -95,7 +95,7 @@ int main(int argc, char **argv) {
char *result = NULL;
char *error = NULL;
- char slaveresult[SLAVERESULTSIZE] = {0};
+ char replica_result[REPLICA_RESULTSIZE] = {0};
char *perf;
perf = strdup("");
@@ -200,20 +200,20 @@ int main(int argc, char **argv) {
if (mysql_query(&mysql, "show slave status") != 0) {
error = strdup(mysql_error(&mysql));
mysql_close(&mysql);
- die(STATE_CRITICAL, _("slave query error: %s\n"), error);
+ die(STATE_CRITICAL, _("replica query error: %s\n"), error);
}
/* store the result */
if ((res = mysql_store_result(&mysql)) == NULL) {
error = strdup(mysql_error(&mysql));
mysql_close(&mysql);
- die(STATE_CRITICAL, _("slave store_result error: %s\n"), error);
+ die(STATE_CRITICAL, _("replica store_result error: %s\n"), error);
}
/* Check there is some data */
if (mysql_num_rows(res) == 0) {
mysql_close(&mysql);
- die(STATE_WARNING, "%s\n", _("No slaves defined"));
+ die(STATE_WARNING, "%s\n", _("No replicas defined"));
}
/* fetch the first row */
@@ -221,32 +221,32 @@ int main(int argc, char **argv) {
error = strdup(mysql_error(&mysql));
mysql_free_result(res);
mysql_close(&mysql);
- die(STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
+ die(STATE_CRITICAL, _("replica fetch row error: %s\n"), error);
}
if (mysql_field_count(&mysql) == 12) {
/* mysql 3.23.x */
- snprintf(slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
+ snprintf(replica_result, REPLICA_RESULTSIZE, _("Replica running: %s"), row[6]);
if (strcmp(row[6], "Yes") != 0) {
mysql_free_result(res);
mysql_close(&mysql);
- die(STATE_CRITICAL, "%s\n", slaveresult);
+ die(STATE_CRITICAL, "%s\n", replica_result);
}
} else {
/* mysql 4.x.x and mysql 5.x.x */
- int slave_io_field = -1, slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
+ int replica_io_field = -1, replica_sql_field = -1, seconds_behind_field = -1, i, num_fields;
MYSQL_FIELD *fields;
num_fields = mysql_num_fields(res);
fields = mysql_fetch_fields(res);
for (i = 0; i < num_fields; i++) {
if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
- slave_io_field = i;
+ replica_io_field = i;
continue;
}
if (strcmp(fields[i].name, "Slave_SQL_Running") == 0) {
- slave_sql_field = i;
+ replica_sql_field = i;
continue;
}
if (strcmp(fields[i].name, "Seconds_Behind_Master") == 0) {
@@ -255,19 +255,19 @@ int main(int argc, char **argv) {
}
}
- /* Check if slave status is available */
- if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
+ /* Check if replica status is available */
+ if ((replica_io_field < 0) || (replica_sql_field < 0) || (num_fields == 0)) {
mysql_free_result(res);
mysql_close(&mysql);
- die(STATE_CRITICAL, "Slave status unavailable\n");
+ die(STATE_CRITICAL, "Replica status unavailable\n");
}
- /* Save slave status in slaveresult */
- snprintf(slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field],
- row[slave_sql_field], seconds_behind_field != -1 ? row[seconds_behind_field] : "Unknown");
+ /* Save replica status in replica_result */
+ snprintf(replica_result, REPLICA_RESULTSIZE, "Replica IO: %s Replica SQL: %s Seconds Behind Master: %s", row[replica_io_field],
+ row[replica_sql_field], seconds_behind_field != -1 ? row[seconds_behind_field] : "Unknown");
/* Raise critical error if SQL THREAD or IO THREAD are stopped, but only if there are no mysqldump threads running */
- if (strcmp(row[slave_io_field], "Yes") != 0 || strcmp(row[slave_sql_field], "Yes") != 0) {
+ if (strcmp(row[replica_io_field], "Yes") != 0 || strcmp(row[replica_sql_field], "Yes") != 0) {
MYSQL_RES *res_mysqldump;
MYSQL_ROW row_mysqldump;
unsigned int mysqldump_threads = 0;
@@ -286,9 +286,9 @@ int main(int argc, char **argv) {
mysql_close(&mysql);
}
if (mysqldump_threads == 0) {
- die(STATE_CRITICAL, "%s\n", slaveresult);
+ die(STATE_CRITICAL, "%s\n", replica_result);
} else {
- strncat(slaveresult, " Mysqldump: in progress", SLAVERESULTSIZE - 1);
+ strncat(replica_result, " Mysqldump: in progress", REPLICA_RESULTSIZE - 1);
}
}
@@ -312,10 +312,10 @@ int main(int argc, char **argv) {
false, 0));
if (status == STATE_WARNING) {
- printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
+ printf("SLOW_REPLICA %s: %s|%s\n", _("WARNING"), replica_result, perf);
exit(STATE_WARNING);
} else if (status == STATE_CRITICAL) {
- printf("SLOW_SLAVE %s: %s|%s\n", _("CRITICAL"), slaveresult, perf);
+ printf("SLOW_REPLICA %s: %s|%s\n", _("CRITICAL"), replica_result, perf);
exit(STATE_CRITICAL);
}
}
@@ -330,7 +330,7 @@ int main(int argc, char **argv) {
/* print out the result of stats */
if (check_replica) {
- printf("%s %s|%s\n", result, slaveresult, perf);
+ printf("%s %s|%s\n", result, replica_result, perf);
} else {
printf("%s|%s\n", result, perf);
}
@@ -338,6 +338,8 @@ int main(int argc, char **argv) {
return STATE_OK;
}
+#define CHECK_REPLICA_OPT CHAR_MAX + 1
+
/* process command-line arguments */
int process_arguments(int argc, char **argv) {
int c;
@@ -345,17 +347,29 @@ int process_arguments(int argc, char **argv) {
char *critical = NULL;
int option = 0;
- static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"socket", required_argument, 0, 's'},
- {"database", required_argument, 0, 'd'}, {"username", required_argument, 0, 'u'},
- {"password", required_argument, 0, 'p'}, {"file", required_argument, 0, 'f'},
- {"group", required_argument, 0, 'g'}, {"port", required_argument, 0, 'P'},
- {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'},
- {"check-slave", no_argument, 0, 'S'}, {"ignore-auth", no_argument, 0, 'n'},
- {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'},
- {"help", no_argument, 0, 'h'}, {"ssl", no_argument, 0, 'l'},
- {"ca-cert", optional_argument, 0, 'C'}, {"key", required_argument, 0, 'k'},
- {"cert", required_argument, 0, 'a'}, {"ca-dir", required_argument, 0, 'D'},
- {"ciphers", required_argument, 0, 'L'}, {0, 0, 0, 0}};
+ static struct option longopts[] = {{"hostname", required_argument, 0, 'H'},
+ {"socket", required_argument, 0, 's'},
+ {"database", required_argument, 0, 'd'},
+ {"username", required_argument, 0, 'u'},
+ {"password", required_argument, 0, 'p'},
+ {"file", required_argument, 0, 'f'},
+ {"group", required_argument, 0, 'g'},
+ {"port", required_argument, 0, 'P'},
+ {"critical", required_argument, 0, 'c'},
+ {"warning", required_argument, 0, 'w'},
+ {"check-slave", no_argument, 0, 'S'},
+ {"check-replica", no_argument, 0, CHECK_REPLICA_OPT},
+ {"ignore-auth", no_argument, 0, 'n'},
+ {"verbose", no_argument, 0, 'v'},
+ {"version", no_argument, 0, 'V'},
+ {"help", no_argument, 0, 'h'},
+ {"ssl", no_argument, 0, 'l'},
+ {"ca-cert", optional_argument, 0, 'C'},
+ {"key", required_argument, 0, 'k'},
+ {"cert", required_argument, 0, 'a'},
+ {"ca-dir", required_argument, 0, 'D'},
+ {"ciphers", required_argument, 0, 'L'},
+ {0, 0, 0, 0}};
if (argc < 1) {
return ERROR;
@@ -424,6 +438,7 @@ int process_arguments(int argc, char **argv) {
db_port = atoi(optarg);
break;
case 'S':
+ case CHECK_REPLICA_OPT:
check_replica = true; /* check-slave */
break;
case 'n':
@@ -532,12 +547,15 @@ void print_help(void) {
printf(" ==> %s <==\n", _("IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!!"));
printf(" %s\n", _("Your clear-text password could be visible as a process table entry"));
printf(" %s\n", "-S, --check-slave");
- printf(" %s\n", _("Check if the slave thread is running properly."));
+ printf(" %s\n",
+ _("Check if the slave thread is running properly. This option is deprecated in favour of check-replica, which does the same"));
+ printf(" %s\n", "--check-replica");
+ printf(" %s\n", _("Check if the replica thread is running properly."));
printf(" %s\n", "-w, --warning");
- printf(" %s\n", _("Exit with WARNING status if slave server is more than INTEGER seconds"));
+ printf(" %s\n", _("Exit with WARNING status if replica server is more than INTEGER seconds"));
printf(" %s\n", _("behind master"));
printf(" %s\n", "-c, --critical");
- printf(" %s\n", _("Exit with CRITICAL status if slave server is more then INTEGER seconds"));
+ printf(" %s\n", _("Exit with CRITICAL status if replica server is more then INTEGER seconds"));
printf(" %s\n", _("behind master"));
printf(" %s\n", "-l, --ssl");
printf(" %s\n", _("Use ssl encryption"));
--
cgit v1.2.3-74-g34f1
From a517dc614e44650a7e9204c4202feec7a40fd37f Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Mon, 24 Feb 2025 19:52:08 +0100
Subject: Add MySQL server version dectection and adaptive replica query
---
plugins/check_mysql.c | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 50 insertions(+), 2 deletions(-)
diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c
index 039a42e5..2b6cfeaf 100644
--- a/plugins/check_mysql.c
+++ b/plugins/check_mysql.c
@@ -196,8 +196,56 @@ int main(int argc, char **argv) {
}
if (check_replica) {
- /* check the slave status */
- if (mysql_query(&mysql, "show slave status") != 0) {
+
+ // Detect which version we are, on older version
+ // "show slave status" should work, on newer ones
+ // "show replica status"
+ // But first we have to find out whether this is
+ // MySQL or MariaDB since the version numbering scheme
+ // is different
+ bool use_deprecated_slave_status = false;
+ const char *server_version = mysql_get_server_info(&mysql);
+ unsigned long server_verion_int = mysql_get_server_version(&mysql);
+ unsigned long major_version = server_verion_int / 10000;
+ unsigned long minor_version = (server_verion_int % 10000) / 100;
+ unsigned long patch_version = (server_verion_int % 100);
+ if (verbose) {
+ printf("Found MariaDB: %s, main version: %lu, minor version: %lu, patch version: %lu\n", server_version, major_version,
+ minor_version, patch_version);
+ }
+
+ if (strstr(server_version, "MariaDB") != NULL) {
+ // Looks like MariaDB, new commands should be available after 10.5.1
+ if (major_version < 10) {
+ use_deprecated_slave_status = true;
+ } else if (major_version == 10) {
+ if (minor_version < 5) {
+ use_deprecated_slave_status = true;
+ } else if (minor_version == 5 && patch_version < 1) {
+ use_deprecated_slave_status = true;
+ }
+ }
+ } else if (strstr(server_version, "MySQL") != NULL) {
+ // Looks like MySQL
+ if (major_version < 8) {
+ use_deprecated_slave_status = true;
+ } else if (major_version == 10 && minor_version < 4) {
+ use_deprecated_slave_status = true;
+ }
+ } else {
+ printf("Not a known sever implementation: %s\n", server_version);
+ exit(STATE_UNKNOWN);
+ }
+
+ char *replica_query = NULL;
+ if (use_deprecated_slave_status) {
+ replica_query = "show slave status";
+ } else {
+ replica_query = "show replica status";
+ }
+
+ /* check the replica status */
+ if (mysql_query(&mysql, replica_query) != 0) {
error = strdup(mysql_error(&mysql));
mysql_close(&mysql);
die(STATE_CRITICAL, _("replica query error: %s\n"), error);
--
cgit v1.2.3-74-g34f1
From c08e2bc656dec032f6b56b0aa398c6cb40ade250 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Mon, 24 Feb 2025 20:18:55 +0100
Subject: Add libmysqlclient-dev to dependencies
---
.github/prepare_debian.sh | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/prepare_debian.sh b/.github/prepare_debian.sh
index 3640e500..8b695d42 100755
--- a/.github/prepare_debian.sh
+++ b/.github/prepare_debian.sh
@@ -59,6 +59,7 @@ apt-get -y install perl \
mariadb-server \
mariadb-client \
libmariadb-dev \
+ libmariadb-dev-compat \
cron \
iputils-ping \
iproute2
--
cgit v1.2.3-74-g34f1
From 3ed6b7cd3e99e328b9f34bfc4af8b2f8bd3b5231 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Mon, 24 Feb 2025 20:55:18 +0100
Subject: check_mysql tests: Also exchange slave for replica
---
.github/NPTest.cache | 4 ++--
plugins/t/check_mysql.t | 32 ++++++++++++++++----------------
2 files changed, 18 insertions(+), 18 deletions(-)
diff --git a/.github/NPTest.cache b/.github/NPTest.cache
index d488d1b9..6b463e74 100644
--- a/.github/NPTest.cache
+++ b/.github/NPTest.cache
@@ -38,8 +38,8 @@
'NP_MYSQL_LOGIN_DETAILS' => '-u root -d test',
'NP_MYSQL_SERVER' => 'localhost',
'NP_MYSQL_SOCKET' => '/var/run/mysqld/mysqld.sock',
- 'NP_MYSQL_WITH_SLAVE' => '',
- 'NP_MYSQL_WITH_SLAVE_LOGIN' => '',
+ 'NP_MYSQL_WITH_REPLICA' => '',
+ 'NP_MYSQL_WITH_REPLICA_LOGIN' => '',
'NP_NO_NTP_SERVICE' => 'localhost',
'NP_PORT_TCP_PROXY' => '3128',
'NP_SMB_SHARE' => '',
diff --git a/plugins/t/check_mysql.t b/plugins/t/check_mysql.t
index baf3acc6..a383bc99 100644
--- a/plugins/t/check_mysql.t
+++ b/plugins/t/check_mysql.t
@@ -21,11 +21,11 @@ plan skip_all => "check_mysql not compiled" unless (-x "check_mysql");
plan tests => 15;
my $bad_login_output = '/Access denied for user /';
-my $mysqlserver = getTestParameter("NP_MYSQL_SERVER", "A MySQL Server hostname or IP with no slaves setup");
-my $mysqlsocket = getTestParameter("NP_MYSQL_SOCKET", "Full path to a MySQL Server socket with no slaves setup");
+my $mysqlserver = getTestParameter("NP_MYSQL_SERVER", "A MySQL Server hostname or IP with no replica setup");
+my $mysqlsocket = getTestParameter("NP_MYSQL_SOCKET", "Full path to a MySQL Server socket with no replica setup");
my $mysql_login_details = getTestParameter("NP_MYSQL_LOGIN_DETAILS", "Command line parameters to specify login access (requires REPLICATION CLIENT privileges)", "-u test -ptest");
-my $with_slave = getTestParameter("NP_MYSQL_WITH_SLAVE", "MySQL server with slaves setup");
-my $with_slave_login = getTestParameter("NP_MYSQL_WITH_SLAVE_LOGIN", "Login details for server with slave (requires REPLICATION CLIENT privileges)", $mysql_login_details || "-u test -ptest");
+my $with_replica = getTestParameter("NP_MYSQL_WITH_REPLICA", "MySQL server with replica setup");
+my $with_replica_login = getTestParameter("NP_MYSQL_WITH_REPLICA_LOGIN", "Login details for server with replica (requires REPLICATION CLIENT privileges)", $mysql_login_details || "-u test -ptest");
my $result;
@@ -39,8 +39,8 @@ SKIP: {
like( $result->output, $bad_login_output, "Expected login failure message");
$result = NPTest->testCmd("./check_mysql -S -H $mysqlserver $mysql_login_details");
- cmp_ok( $result->return_code, "==", 1, "No slaves defined" );
- like( $result->output, "/No slaves defined/", "Correct error message");
+ cmp_ok( $result->return_code, "==", 1, "No replicas defined" );
+ like( $result->output, "/No replicas defined/", "Correct error message");
}
SKIP: {
@@ -53,22 +53,22 @@ SKIP: {
like( $result->output, $bad_login_output, "Expected login failure message");
$result = NPTest->testCmd("./check_mysql -S -s $mysqlsocket $mysql_login_details");
- cmp_ok( $result->return_code, "==", 1, "No slaves defined" );
- like( $result->output, "/No slaves defined/", "Correct error message");
+ cmp_ok( $result->return_code, "==", 1, "No replicas defined" );
+ like( $result->output, "/No replicas defined/", "Correct error message");
}
SKIP: {
- skip "No mysql server with slaves defined", 5 unless $with_slave;
- $result = NPTest->testCmd("./check_mysql -H $with_slave $with_slave_login");
+ skip "No mysql server with replicas defined", 5 unless $with_replica;
+ $result = NPTest->testCmd("./check_mysql -H $with_replica $with_replica_login");
cmp_ok( $result->return_code, '==', 0, "Login okay");
- $result = NPTest->testCmd("./check_mysql -S -H $with_slave $with_slave_login");
- cmp_ok( $result->return_code, "==", 0, "Slaves okay" );
+ $result = NPTest->testCmd("./check_mysql -S -H $with_replica $with_replica_login");
+ cmp_ok( $result->return_code, "==", 0, "Replicas okay" );
- $result = NPTest->testCmd("./check_mysql -S -H $with_slave $with_slave_login -w 60");
- cmp_ok( $result->return_code, '==', 0, 'Slaves are not > 60 seconds behind');
+ $result = NPTest->testCmd("./check_mysql -S -H $with_replica $with_replica_login -w 60");
+ cmp_ok( $result->return_code, '==', 0, 'Replicas are not > 60 seconds behind');
- $result = NPTest->testCmd("./check_mysql -S -H $with_slave $with_slave_login -w 60:");
+ $result = NPTest->testCmd("./check_mysql -S -H $with_replica $with_replica_login -w 60:");
cmp_ok( $result->return_code, '==', 1, 'Alert warning if < 60 seconds behind');
- like( $result->output, "/^SLOW_SLAVE WARNING:/", "Output okay");
+ like( $result->output, "/^SLOW_REPLICA WARNING:/", "Output okay");
}
--
cgit v1.2.3-74-g34f1
From eb1dd9fe2e0e965b4c9326195a778c3794492ef4 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 09:14:37 +0100
Subject: check_dbi: clang_format
---
plugins/check_dbi.c | 140 +++++++++++++++++++++++++++++++++-------------------
1 file changed, 89 insertions(+), 51 deletions(-)
diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c
index 96575672..ae8ec952 100644
--- a/plugins/check_dbi.c
+++ b/plugins/check_dbi.c
@@ -128,8 +128,9 @@ int main(int argc, char **argv) {
/* Parse extra opts if any */
argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments(argc, argv) == ERROR)
+ if (process_arguments(argc, argv) == ERROR) {
usage4(_("Could not parse arguments"));
+ }
/* Set signal handling and alarm */
if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) {
@@ -137,8 +138,9 @@ int main(int argc, char **argv) {
}
alarm(timeout_interval);
- if (verbose > 2)
+ if (verbose > 2) {
printf("Initializing DBI\n");
+ }
dbi_inst *instance_p = {0};
@@ -152,8 +154,9 @@ int main(int argc, char **argv) {
return STATE_UNKNOWN;
}
- if (verbose)
+ if (verbose) {
printf("Opening DBI driver '%s'\n", np_dbi_driver);
+ }
driver = dbi_driver_open_r(np_dbi_driver, instance_p);
if (!driver) {
@@ -179,11 +182,13 @@ int main(int argc, char **argv) {
for (i = 0; i < np_dbi_options_num; ++i) {
const char *opt;
- if (verbose > 1)
+ if (verbose > 1) {
printf("Setting DBI driver option '%s' to '%s'\n", np_dbi_options[i].key, np_dbi_options[i].value);
+ }
- if (!dbi_conn_set_option(conn, np_dbi_options[i].key, np_dbi_options[i].value))
+ if (!dbi_conn_set_option(conn, np_dbi_options[i].key, np_dbi_options[i].value)) {
continue;
+ }
/* else: status != 0 */
np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'", np_dbi_options[i].key, np_dbi_options[i].value);
@@ -197,8 +202,9 @@ int main(int argc, char **argv) {
}
if (host) {
- if (verbose > 1)
+ if (verbose > 1) {
printf("Setting DBI driver option 'host' to '%s'\n", host);
+ }
dbi_conn_set_option(conn, "host", host);
}
@@ -209,10 +215,12 @@ int main(int argc, char **argv) {
dbname = dbi_conn_get_option(conn, "dbname");
host = dbi_conn_get_option(conn, "host");
- if (!dbname)
+ if (!dbname) {
dbname = "";
- if (!host)
+ }
+ if (!host) {
host = "";
+ }
printf("Connecting to database '%s' at host '%s'\n", dbname, host);
}
@@ -226,22 +234,27 @@ int main(int argc, char **argv) {
conn_time = timediff(start_timeval, end_timeval);
server_version = dbi_conn_get_engine_version(conn);
- if (verbose)
+ if (verbose) {
printf("Connected to server version %u\n", server_version);
+ }
- if (metric == METRIC_SERVER_VERSION)
+ if (metric == METRIC_SERVER_VERSION) {
status = get_status(server_version, dbi_thresholds);
+ }
- if (verbose)
+ if (verbose) {
printf("Time elapsed: %f\n", conn_time);
+ }
- if (metric == METRIC_CONN_TIME)
+ if (metric == METRIC_CONN_TIME) {
status = get_status(conn_time, dbi_thresholds);
+ }
/* select a database */
if (np_dbi_database) {
- if (verbose > 1)
+ if (verbose > 1) {
printf("Selecting database '%s'\n", np_dbi_database);
+ }
if (dbi_conn_select_db(conn, np_dbi_database)) {
np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'", np_dbi_database);
@@ -252,38 +265,43 @@ int main(int argc, char **argv) {
if (np_dbi_query) {
/* execute query */
status = do_query(conn, &query_val_str, &query_val, &query_time);
- if (status != STATE_OK)
+ if (status != STATE_OK) {
/* do_query prints an error message in this case */
return status;
+ }
if (metric == METRIC_QUERY_RESULT) {
if (expect) {
- if ((!query_val_str) || strcmp(query_val_str, expect))
+ if ((!query_val_str) || strcmp(query_val_str, expect)) {
status = STATE_CRITICAL;
- else
+ } else {
status = STATE_OK;
+ }
} else if (expect_re_str) {
int err;
err = regexec(&expect_re, query_val_str, 0, NULL, /* flags = */ 0);
- if (!err)
+ if (!err) {
status = STATE_OK;
- else if (err == REG_NOMATCH)
+ } else if (err == REG_NOMATCH) {
status = STATE_CRITICAL;
- else {
+ } else {
char errmsg[1024];
regerror(err, &expect_re, errmsg, sizeof(errmsg));
printf("ERROR - failed to execute regular expression: %s\n", errmsg);
status = STATE_CRITICAL;
}
- } else
+ } else {
status = get_status(query_val, dbi_thresholds);
- } else if (metric == METRIC_QUERY_TIME)
+ }
+ } else if (metric == METRIC_QUERY_TIME) {
status = get_status(query_time, dbi_thresholds);
+ }
}
- if (verbose)
+ if (verbose) {
printf("Closing connection\n");
+ }
dbi_conn_close(conn);
/* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error
@@ -299,15 +317,17 @@ int main(int argc, char **argv) {
assert(expect || expect_re_str);
printf(", '%s' returned '%s' in %fs", np_dbi_query, query_val_str ? query_val_str : "", query_time);
if (status != STATE_OK) {
- if (expect)
+ if (expect) {
printf(" (expected '%s')", expect);
- else if (expect_re_str)
+ } else if (expect_re_str) {
printf(" (expected regex /%s/%s)", expect_re_str, ((expect_re_cflags & REG_ICASE) ? "i" : ""));
+ }
}
- } else if (isnan(query_val))
+ } else if (isnan(query_val)) {
printf(", '%s' query execution time: %fs", np_dbi_query, query_time);
- else
+ } else {
printf(", '%s' returned %f in %fs", np_dbi_query, query_val, query_time);
+ }
}
printf(" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time,
@@ -316,9 +336,10 @@ int main(int argc, char **argv) {
((metric == METRIC_SERVER_VERSION) && warning_range) ? warning_range : "",
((metric == METRIC_SERVER_VERSION) && critical_range) ? critical_range : "");
if (np_dbi_query) {
- if (!isnan(query_val)) /* this is also true when -e is used */
+ if (!isnan(query_val)) { /* this is also true when -e is used */
printf(" query=%f;%s;%s;;", query_val, ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "",
((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : "");
+ }
printf(" querytime=%fs;%s;%s;0;", query_time, ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "",
((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : "");
}
@@ -346,8 +367,9 @@ int process_arguments(int argc, char **argv) {
while (1) {
c = getopt_long(argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", longopts, &option);
- if (c == EOF)
+ if (c == EOF) {
break;
+ }
switch (c) {
case '?': /* usage */
@@ -392,29 +414,32 @@ int process_arguments(int argc, char **argv) {
}
case 'm':
- if (!strcasecmp(optarg, "CONN_TIME"))
+ if (!strcasecmp(optarg, "CONN_TIME")) {
metric = METRIC_CONN_TIME;
- else if (!strcasecmp(optarg, "SERVER_VERSION"))
+ } else if (!strcasecmp(optarg, "SERVER_VERSION")) {
metric = METRIC_SERVER_VERSION;
- else if (!strcasecmp(optarg, "QUERY_RESULT"))
+ } else if (!strcasecmp(optarg, "QUERY_RESULT")) {
metric = METRIC_QUERY_RESULT;
- else if (!strcasecmp(optarg, "QUERY_TIME"))
+ } else if (!strcasecmp(optarg, "QUERY_TIME")) {
metric = METRIC_QUERY_TIME;
- else
+ } else {
usage2(_("Invalid metric"), optarg);
+ }
break;
case 't': /* timeout */
- if (!is_intnonneg(optarg))
+ if (!is_intnonneg(optarg)) {
usage2(_("Timeout interval must be a positive integer"), optarg);
- else
+ } else {
timeout_interval = atoi(optarg);
+ }
break;
case 'H': /* host */
- if (!is_host(optarg))
+ if (!is_host(optarg)) {
usage2(_("Invalid hostname/address"), optarg);
- else
+ } else {
host = optarg;
+ }
break;
case 'v':
verbose++;
@@ -432,8 +457,9 @@ int process_arguments(int argc, char **argv) {
k = optarg;
v = strchr(k, (int)'=');
- if (!v)
+ if (!v) {
usage2(_("Option must be '='"), optarg);
+ }
*v = '\0';
++v;
@@ -466,27 +492,34 @@ int process_arguments(int argc, char **argv) {
}
int validate_arguments(void) {
- if (!np_dbi_driver)
+ if (!np_dbi_driver) {
usage("Must specify a DBI driver");
+ }
- if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) && (!np_dbi_query))
+ if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) && (!np_dbi_query)) {
usage("Must specify a query to execute (metric == QUERY_RESULT)");
+ }
if ((metric != METRIC_CONN_TIME) && (metric != METRIC_SERVER_VERSION) && (metric != METRIC_QUERY_RESULT) &&
- (metric != METRIC_QUERY_TIME))
+ (metric != METRIC_QUERY_TIME)) {
usage("Invalid metric specified");
+ }
- if (expect && (warning_range || critical_range || expect_re_str))
+ if (expect && (warning_range || critical_range || expect_re_str)) {
usage("Do not mix -e and -w/-c/-r/-R");
+ }
- if (expect_re_str && (warning_range || critical_range || expect))
+ if (expect_re_str && (warning_range || critical_range || expect)) {
usage("Do not mix -r/-R and -w/-c/-e");
+ }
- if (expect && (metric != METRIC_QUERY_RESULT))
+ if (expect && (metric != METRIC_QUERY_RESULT)) {
usage("Option -e requires metric QUERY_RESULT");
+ }
- if (expect_re_str && (metric != METRIC_QUERY_RESULT))
+ if (expect_re_str && (metric != METRIC_QUERY_RESULT)) {
usage("Options -r/-R require metric QUERY_RESULT");
+ }
return OK;
}
@@ -613,8 +646,9 @@ const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_ty
return NULL;
}
- if ((verbose && (type == TYPE_STRING)) || (verbose > 2))
+ if ((verbose && (type == TYPE_STRING)) || (verbose > 2)) {
printf("Query returned string '%s'\n", str);
+ }
return str;
}
@@ -644,8 +678,9 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) {
return NAN;
}
if ((endptr != NULL) && (*endptr != '\0')) {
- if (verbose)
+ if (verbose) {
printf("Garbage after value: %s\n", endptr);
+ }
}
} else {
CHECK_IGNORE_ERROR(NAN);
@@ -696,11 +731,12 @@ double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str,
field_type = dbi_result_get_field_type_idx(res, 1);
if (field_type != DBI_TYPE_ERROR) {
- if (type == TYPE_STRING)
+ if (type == TYPE_STRING) {
/* the value will be freed in dbi_result_free */
*res_val_str = strdup(get_field_str(conn, res, field_type));
- else
+ } else {
val = get_field(conn, res, &field_type);
+ }
}
*res_val = val;
@@ -726,8 +762,9 @@ int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *r
assert(np_dbi_query);
- if (verbose)
+ if (verbose) {
printf("Executing query '%s'\n", np_dbi_query);
+ }
gettimeofday(&timeval_start, NULL);
@@ -742,8 +779,9 @@ int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *r
gettimeofday(&timeval_end, NULL);
*res_time = timediff(timeval_start, timeval_end);
- if (verbose)
+ if (verbose) {
printf("Time elapsed: %f\n", *res_time);
+ }
return status;
}
--
cgit v1.2.3-74-g34f1
From 5ad1c0e821a5aaafe47dbe79d5f69820fde798bd Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 09:09:45 +0100
Subject: Implement JSON output parsing for tests
---
NPTest.pm | 4 ++++
plugins/t/check_swap.t | 35 ++++++++++++++---------------------
2 files changed, 18 insertions(+), 21 deletions(-)
diff --git a/NPTest.pm b/NPTest.pm
index 9b25ac3e..47773acc 100644
--- a/NPTest.pm
+++ b/NPTest.pm
@@ -15,6 +15,8 @@ use warnings;
use Cwd;
use File::Basename;
+use JSON;
+
use IO::File;
use Data::Dumper;
@@ -617,6 +619,8 @@ sub testCmd {
chomp $output;
$object->output($output);
+ $object->{'mp_test_result'} = decode_json($output);
+
alarm(0);
my ($pkg, $file, $line) = caller(0);
diff --git a/plugins/t/check_swap.t b/plugins/t/check_swap.t
index 7e61b766..68946f6d 100644
--- a/plugins/t/check_swap.t
+++ b/plugins/t/check_swap.t
@@ -17,42 +17,35 @@ my $message = '/^[0-9]+\% free \([0-9]+MiB out of [0-9]+MiB\)/';
$result = NPTest->testCmd( "./check_swap $outputFormat" ); # Always OK
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "OK", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "OK", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
$result = NPTest->testCmd( "./check_swap -w 1048576 -c 1048576 $outputFormat" ); # 1 MB free
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "OK", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "OK", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
$result = NPTest->testCmd( "./check_swap -w 1% -c 1% $outputFormat" ); # 1% free
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "OK", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "OK", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
$result = NPTest->testCmd( "./check_swap -w 100% -c 100% $outputFormat" ); # 100% (always critical)
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "CRITICAL", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "CRITICAL", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
$result = NPTest->testCmd( "./check_swap -w 100% -c 1% $outputFormat" ); # 100% (always warn)
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "WARNING", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "WARNING", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
$result = NPTest->testCmd( "./check_swap -w 100% $outputFormat" ); # 100% (single threshold, always warn)
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "WARNING", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "WARNING", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
$result = NPTest->testCmd( "./check_swap -c 100% $outputFormat" ); # 100% (single threshold, always critical)
cmp_ok( $result->return_code, "==", 0, "Always OK" );
-$output = decode_json($result->output);
-is($output->{'state'}, "CRITICAL", "State was correct");
-like($output->{'checks'}->[0]->{'output'}, $message, "Output was correct");
+is($result->{'mp_test_result'}->{'state'}, "CRITICAL", "State was correct");
+like($result->{'mp_test_result'}->{'checks'}->[0]->{'output'}, $message, "Output was correct");
--
cgit v1.2.3-74-g34f1
From 18dedf3463534a9f6c8137628c482298dbb0459b Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 17:28:36 +0100
Subject: Do not die in tests if JSON Parsing fails
---
NPTest.pm | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/NPTest.pm b/NPTest.pm
index 47773acc..f9f18b5f 100644
--- a/NPTest.pm
+++ b/NPTest.pm
@@ -17,6 +17,8 @@ use File::Basename;
use JSON;
+use feature 'try';
+
use IO::File;
use Data::Dumper;
@@ -619,7 +621,9 @@ sub testCmd {
chomp $output;
$object->output($output);
- $object->{'mp_test_result'} = decode_json($output);
+ try {
+ $object->{'mp_test_result'} = decode_json($output);
+ }
alarm(0);
--
cgit v1.2.3-74-g34f1
From f2275431783a5aaed25c35b5deec37c244872a7a Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 17:48:27 +0100
Subject: Use Try::Tiny instead of experimental feature
---
NPTest.pm | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/NPTest.pm b/NPTest.pm
index f9f18b5f..987d3b71 100644
--- a/NPTest.pm
+++ b/NPTest.pm
@@ -17,7 +17,7 @@ use File::Basename;
use JSON;
-use feature 'try';
+use Try::Tiny;
use IO::File;
use Data::Dumper;
@@ -623,7 +623,7 @@ sub testCmd {
try {
$object->{'mp_test_result'} = decode_json($output);
- }
+ };
alarm(0);
--
cgit v1.2.3-74-g34f1
From 2727f32f194233e9fdc333afa26a23d8759362ac Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 11:42:22 +0100
Subject: Refactor check_dbi
---
plugins/Makefile.am | 2 +-
plugins/check_dbi.c | 339 +++++++++++++++++++++----------------------
plugins/check_dbi.d/config.h | 63 ++++++++
3 files changed, 231 insertions(+), 173 deletions(-)
create mode 100644 plugins/check_dbi.d/config.h
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index d43c1971..a0e9cabf 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -46,7 +46,7 @@ SUBDIRS = picohttpparser
np_test_scripts = tests/test_check_swap.t
-EXTRA_DIST = t tests $(np_test_scripts) check_swap.d
+EXTRA_DIST = t tests $(np_test_scripts) check_swap.d check_dbi.d
PLUGINHDRS = common.h
diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c
index ae8ec952..1f4a7def 100644
--- a/plugins/check_dbi.c
+++ b/plugins/check_dbi.c
@@ -33,6 +33,8 @@ const char *progname = "check_dbi";
const char *copyright = "2011-2024";
const char *email = "devel@monitoring-plugins.org";
+#include "../lib/monitoringplug.h"
+#include "check_dbi.d/config.h"
#include "common.h"
#include "utils.h"
#include "utils_cmd.h"
@@ -53,55 +55,24 @@ const char *email = "devel@monitoring-plugins.org";
#include
-typedef enum {
- METRIC_CONN_TIME,
- METRIC_SERVER_VERSION,
- METRIC_QUERY_RESULT,
- METRIC_QUERY_TIME,
-} np_dbi_metric_t;
-
-typedef enum {
- TYPE_NUMERIC,
- TYPE_STRING,
-} np_dbi_type_t;
-
-typedef struct {
- char *key;
- char *value;
-} driver_option_t;
-
-static char *host = NULL;
static int verbose = 0;
-static char *warning_range = NULL;
-static char *critical_range = NULL;
-static thresholds *dbi_thresholds = NULL;
-
-static char *expect = NULL;
-
-static regex_t expect_re;
-static char *expect_re_str = NULL;
-static int expect_re_cflags = 0;
-
-static np_dbi_metric_t metric = METRIC_QUERY_RESULT;
-static np_dbi_type_t type = TYPE_NUMERIC;
-
-static char *np_dbi_driver = NULL;
-static driver_option_t *np_dbi_options = NULL;
-static int np_dbi_options_num = 0;
-static char *np_dbi_database = NULL;
-static char *np_dbi_query = NULL;
+typedef struct {
+ int errorcode;
+ check_dbi_config config;
+} check_dbi_config_wrapper;
-static int process_arguments(int, char **);
-static int validate_arguments(void);
+static check_dbi_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
+static check_dbi_config_wrapper validate_arguments(check_dbi_config_wrapper /*config_wrapper*/);
void print_usage(void);
static void print_help(void);
-static double timediff(struct timeval, struct timeval);
+static double timediff(struct timeval /*start*/, struct timeval /*end*/);
-static void np_dbi_print_error(dbi_conn, char *, ...);
+static void np_dbi_print_error(dbi_conn /*conn*/, char * /*fmt*/, ...);
-static int do_query(dbi_conn, const char **, double *, double *);
+static mp_state_enum do_query(dbi_conn /*conn*/, const char ** /*res_val_str*/, double * /*res_val*/, double * /*res_time*/, mp_dbi_metric /*metric*/,
+ mp_dbi_type /*type*/, char * /*np_dbi_query*/);
int main(int argc, char **argv) {
int status = STATE_UNKNOWN;
@@ -119,8 +90,6 @@ int main(int argc, char **argv) {
const char *query_val_str = NULL;
double query_val = 0.0;
- int i;
-
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
@@ -128,10 +97,14 @@ int main(int argc, char **argv) {
/* Parse extra opts if any */
argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments(argc, argv) == ERROR) {
+ check_dbi_config_wrapper tmp = process_arguments(argc, argv);
+
+ if (tmp.errorcode == ERROR) {
usage4(_("Could not parse arguments"));
}
+ check_dbi_config config = tmp.config;
+
/* Set signal handling and alarm */
if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) {
usage4(_("Cannot catch SIGALRM"));
@@ -155,12 +128,12 @@ int main(int argc, char **argv) {
}
if (verbose) {
- printf("Opening DBI driver '%s'\n", np_dbi_driver);
+ printf("Opening DBI driver '%s'\n", config.dbi_driver);
}
- driver = dbi_driver_open_r(np_dbi_driver, instance_p);
+ driver = dbi_driver_open_r(config.dbi_driver, instance_p);
if (!driver) {
- printf("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", np_dbi_driver);
+ printf("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", config.dbi_driver);
printf("Known drivers:\n");
for (driver = dbi_driver_list_r(NULL, instance_p); driver; driver = dbi_driver_list_r(driver, instance_p)) {
@@ -179,19 +152,19 @@ int main(int argc, char **argv) {
return STATE_UNKNOWN;
}
- for (i = 0; i < np_dbi_options_num; ++i) {
+ for (size_t i = 0; i < config.dbi_options_num; ++i) {
const char *opt;
if (verbose > 1) {
- printf("Setting DBI driver option '%s' to '%s'\n", np_dbi_options[i].key, np_dbi_options[i].value);
+ printf("Setting DBI driver option '%s' to '%s'\n", config.dbi_options[i].key, config.dbi_options[i].value);
}
- if (!dbi_conn_set_option(conn, np_dbi_options[i].key, np_dbi_options[i].value)) {
+ if (!dbi_conn_set_option(conn, config.dbi_options[i].key, config.dbi_options[i].value)) {
continue;
}
/* else: status != 0 */
- np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'", np_dbi_options[i].key, np_dbi_options[i].value);
+ np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'", config.dbi_options[i].key, config.dbi_options[i].value);
printf("Known driver options:\n");
for (opt = dbi_conn_get_option_list(conn, NULL); opt; opt = dbi_conn_get_option_list(conn, opt)) {
@@ -201,11 +174,11 @@ int main(int argc, char **argv) {
return STATE_UNKNOWN;
}
- if (host) {
+ if (config.host) {
if (verbose > 1) {
- printf("Setting DBI driver option 'host' to '%s'\n", host);
+ printf("Setting DBI driver option 'host' to '%s'\n", config.host);
}
- dbi_conn_set_option(conn, "host", host);
+ dbi_conn_set_option(conn, "host", config.host);
}
if (verbose) {
@@ -238,48 +211,49 @@ int main(int argc, char **argv) {
printf("Connected to server version %u\n", server_version);
}
- if (metric == METRIC_SERVER_VERSION) {
- status = get_status(server_version, dbi_thresholds);
+ if (config.metric == METRIC_SERVER_VERSION) {
+ status = get_status(server_version, config.dbi_thresholds);
}
if (verbose) {
printf("Time elapsed: %f\n", conn_time);
}
- if (metric == METRIC_CONN_TIME) {
- status = get_status(conn_time, dbi_thresholds);
+ if (config.metric == METRIC_CONN_TIME) {
+ status = get_status(conn_time, config.dbi_thresholds);
}
/* select a database */
- if (np_dbi_database) {
+ if (config.dbi_database) {
if (verbose > 1) {
- printf("Selecting database '%s'\n", np_dbi_database);
+ printf("Selecting database '%s'\n", config.dbi_database);
}
- if (dbi_conn_select_db(conn, np_dbi_database)) {
- np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'", np_dbi_database);
+ if (dbi_conn_select_db(conn, config.dbi_database)) {
+ np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'", config.dbi_database);
return STATE_UNKNOWN;
}
}
- if (np_dbi_query) {
+ if (config.dbi_query) {
/* execute query */
- status = do_query(conn, &query_val_str, &query_val, &query_time);
+ status = do_query(conn, &query_val_str, &query_val, &query_time, config.metric, config.type, config.dbi_query);
if (status != STATE_OK) {
/* do_query prints an error message in this case */
return status;
}
- if (metric == METRIC_QUERY_RESULT) {
- if (expect) {
- if ((!query_val_str) || strcmp(query_val_str, expect)) {
+ if (config.metric == METRIC_QUERY_RESULT) {
+ if (config.expect) {
+ if ((!query_val_str) || strcmp(query_val_str, config.expect)) {
status = STATE_CRITICAL;
} else {
status = STATE_OK;
}
- } else if (expect_re_str) {
+ } else if (config.expect_re_str) {
int err;
+ regex_t expect_re = {};
err = regexec(&expect_re, query_val_str, 0, NULL, /* flags = */ 0);
if (!err) {
status = STATE_OK;
@@ -292,10 +266,10 @@ int main(int argc, char **argv) {
status = STATE_CRITICAL;
}
} else {
- status = get_status(query_val, dbi_thresholds);
+ status = get_status(query_val, config.dbi_thresholds);
}
- } else if (metric == METRIC_QUERY_TIME) {
- status = get_status(query_time, dbi_thresholds);
+ } else if (config.metric == METRIC_QUERY_TIME) {
+ status = get_status(query_time, config.dbi_thresholds);
}
}
@@ -307,49 +281,48 @@ int main(int argc, char **argv) {
/* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error
* which should have been reported and handled (abort) before
* ... unless we expected a string to be returned */
- assert((metric != METRIC_QUERY_RESULT) || (!isnan(query_val)) || (type == TYPE_STRING));
+ assert((config.metric != METRIC_QUERY_RESULT) || (!isnan(query_val)) || (config.type == TYPE_STRING));
- assert((type != TYPE_STRING) || (expect || expect_re_str));
+ assert((config.type != TYPE_STRING) || (config.expect || config.expect_re_str));
printf("%s - connection time: %fs", state_text(status), conn_time);
- if (np_dbi_query) {
- if (type == TYPE_STRING) {
- assert(expect || expect_re_str);
- printf(", '%s' returned '%s' in %fs", np_dbi_query, query_val_str ? query_val_str : "", query_time);
+ if (config.dbi_query) {
+ if (config.type == TYPE_STRING) {
+ assert(config.expect || config.expect_re_str);
+ printf(", '%s' returned '%s' in %fs", config.dbi_query, query_val_str ? query_val_str : "", query_time);
if (status != STATE_OK) {
- if (expect) {
- printf(" (expected '%s')", expect);
- } else if (expect_re_str) {
- printf(" (expected regex /%s/%s)", expect_re_str, ((expect_re_cflags & REG_ICASE) ? "i" : ""));
+ if (config.expect) {
+ printf(" (expected '%s')", config.expect);
+ } else if (config.expect_re_str) {
+ printf(" (expected regex /%s/%s)", config.expect_re_str, ((config.expect_re_cflags & REG_ICASE) ? "i" : ""));
}
}
} else if (isnan(query_val)) {
- printf(", '%s' query execution time: %fs", np_dbi_query, query_time);
+ printf(", '%s' query execution time: %fs", config.dbi_query, query_time);
} else {
- printf(", '%s' returned %f in %fs", np_dbi_query, query_val, query_time);
+ printf(", '%s' returned %f in %fs", config.dbi_query, query_val, query_time);
}
}
printf(" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time,
- ((metric == METRIC_CONN_TIME) && warning_range) ? warning_range : "",
- ((metric == METRIC_CONN_TIME) && critical_range) ? critical_range : "", server_version,
- ((metric == METRIC_SERVER_VERSION) && warning_range) ? warning_range : "",
- ((metric == METRIC_SERVER_VERSION) && critical_range) ? critical_range : "");
- if (np_dbi_query) {
+ ((config.metric == METRIC_CONN_TIME) && config.warning_range) ? config.warning_range : "",
+ ((config.metric == METRIC_CONN_TIME) && config.critical_range) ? config.critical_range : "", server_version,
+ ((config.metric == METRIC_SERVER_VERSION) && config.warning_range) ? config.warning_range : "",
+ ((config.metric == METRIC_SERVER_VERSION) && config.critical_range) ? config.critical_range : "");
+ if (config.dbi_query) {
if (!isnan(query_val)) { /* this is also true when -e is used */
- printf(" query=%f;%s;%s;;", query_val, ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "",
- ((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : "");
+ printf(" query=%f;%s;%s;;", query_val, ((config.metric == METRIC_QUERY_RESULT) && config.warning_range) ? config.warning_range : "",
+ ((config.metric == METRIC_QUERY_RESULT) && config.critical_range) ? config.critical_range : "");
}
- printf(" querytime=%fs;%s;%s;0;", query_time, ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "",
- ((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : "");
+ printf(" querytime=%fs;%s;%s;0;", query_time, ((config.metric == METRIC_QUERY_TIME) && config.warning_range) ? config.warning_range : "",
+ ((config.metric == METRIC_QUERY_TIME) && config.critical_range) ? config.critical_range : "");
}
printf("\n");
return status;
}
/* process command-line arguments */
-int process_arguments(int argc, char **argv) {
- int c;
+check_dbi_config_wrapper process_arguments(int argc, char **argv) {
int option = 0;
static struct option longopts[] = {STD_LONG_OPTS,
@@ -364,14 +337,19 @@ int process_arguments(int argc, char **argv) {
{"database", required_argument, 0, 'D'},
{0, 0, 0, 0}};
- while (1) {
- c = getopt_long(argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", longopts, &option);
+ check_dbi_config_wrapper result = {
+ .config = check_dbi_config_init(),
+ .errorcode = OK,
+ };
+ int option_char;
+ while (true) {
+ option_char = getopt_long(argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", longopts, &option);
- if (c == EOF) {
+ if (option_char == EOF) {
break;
}
- switch (c) {
+ switch (option_char) {
case '?': /* usage */
usage5();
case 'h': /* help */
@@ -382,46 +360,49 @@ int process_arguments(int argc, char **argv) {
exit(STATE_UNKNOWN);
case 'c': /* critical range */
- critical_range = optarg;
- type = TYPE_NUMERIC;
+ result.config.critical_range = optarg;
+ result.config.type = TYPE_NUMERIC;
break;
case 'w': /* warning range */
- warning_range = optarg;
- type = TYPE_NUMERIC;
+ result.config.warning_range = optarg;
+ result.config.type = TYPE_NUMERIC;
break;
case 'e':
- expect = optarg;
- type = TYPE_STRING;
+ result.config.expect = optarg;
+ result.config.type = TYPE_STRING;
break;
case 'R':
- expect_re_cflags = REG_ICASE;
+ result.config.expect_re_cflags = REG_ICASE;
/* fall through */
case 'r': {
int err;
- expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
- expect_re_str = optarg;
- type = TYPE_STRING;
+ result.config.expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
+ result.config.expect_re_str = optarg;
+ result.config.type = TYPE_STRING;
- err = regcomp(&expect_re, expect_re_str, expect_re_cflags);
+ regex_t expect_re = {};
+ err = regcomp(&expect_re, result.config.expect_re_str, result.config.expect_re_cflags);
if (err) {
char errmsg[1024];
regerror(err, &expect_re, errmsg, sizeof(errmsg));
printf("ERROR - failed to compile regular expression: %s\n", errmsg);
- return ERROR;
+
+ result.errorcode = ERROR;
+ return result;
}
break;
}
case 'm':
if (!strcasecmp(optarg, "CONN_TIME")) {
- metric = METRIC_CONN_TIME;
+ result.config.metric = METRIC_CONN_TIME;
} else if (!strcasecmp(optarg, "SERVER_VERSION")) {
- metric = METRIC_SERVER_VERSION;
+ result.config.metric = METRIC_SERVER_VERSION;
} else if (!strcasecmp(optarg, "QUERY_RESULT")) {
- metric = METRIC_QUERY_RESULT;
+ result.config.metric = METRIC_QUERY_RESULT;
} else if (!strcasecmp(optarg, "QUERY_TIME")) {
- metric = METRIC_QUERY_TIME;
+ result.config.metric = METRIC_QUERY_TIME;
} else {
usage2(_("Invalid metric"), optarg);
}
@@ -438,7 +419,7 @@ int process_arguments(int argc, char **argv) {
if (!is_host(optarg)) {
usage2(_("Invalid hostname/address"), optarg);
} else {
- host = optarg;
+ result.config.host = optarg;
}
break;
case 'v':
@@ -446,82 +427,81 @@ int process_arguments(int argc, char **argv) {
break;
case 'd':
- np_dbi_driver = optarg;
+ result.config.dbi_driver = optarg;
break;
case 'o': {
- driver_option_t *new;
+ driver_option_t *new = NULL;
- char *k;
- char *v;
+ char *key = optarg;
+ char *value = strchr(key, '=');
- k = optarg;
- v = strchr(k, (int)'=');
-
- if (!v) {
+ if (!value) {
usage2(_("Option must be '='"), optarg);
}
- *v = '\0';
- ++v;
+ *value = '\0';
+ ++value;
- new = realloc(np_dbi_options, (np_dbi_options_num + 1) * sizeof(*new));
+ new = realloc(result.config.dbi_options, (result.config.dbi_options_num + 1) * sizeof(*new));
if (!new) {
printf("UNKNOWN - failed to reallocate memory\n");
exit(STATE_UNKNOWN);
}
- np_dbi_options = new;
- new = np_dbi_options + np_dbi_options_num;
- ++np_dbi_options_num;
+ result.config.dbi_options = new;
+ new = result.config.dbi_options + result.config.dbi_options_num;
+ result.config.dbi_options_num++;
- new->key = k;
- new->value = v;
+ new->key = key;
+ new->value = value;
} break;
case 'q':
- np_dbi_query = optarg;
+ result.config.dbi_query = optarg;
break;
case 'D':
- np_dbi_database = optarg;
+ result.config.dbi_database = optarg;
break;
}
}
- set_thresholds(&dbi_thresholds, warning_range, critical_range);
+ set_thresholds(&result.config.dbi_thresholds, result.config.warning_range, result.config.critical_range);
- return validate_arguments();
+ return validate_arguments(result);
}
-int validate_arguments(void) {
- if (!np_dbi_driver) {
+check_dbi_config_wrapper validate_arguments(check_dbi_config_wrapper config_wrapper) {
+ if (!config_wrapper.config.dbi_driver) {
usage("Must specify a DBI driver");
}
- if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) && (!np_dbi_query)) {
+ if (((config_wrapper.config.metric == METRIC_QUERY_RESULT) || (config_wrapper.config.metric == METRIC_QUERY_TIME)) &&
+ (!config_wrapper.config.dbi_query)) {
usage("Must specify a query to execute (metric == QUERY_RESULT)");
}
- if ((metric != METRIC_CONN_TIME) && (metric != METRIC_SERVER_VERSION) && (metric != METRIC_QUERY_RESULT) &&
- (metric != METRIC_QUERY_TIME)) {
+ if ((config_wrapper.config.metric != METRIC_CONN_TIME) && (config_wrapper.config.metric != METRIC_SERVER_VERSION) &&
+ (config_wrapper.config.metric != METRIC_QUERY_RESULT) && (config_wrapper.config.metric != METRIC_QUERY_TIME)) {
usage("Invalid metric specified");
}
- if (expect && (warning_range || critical_range || expect_re_str)) {
+ if (config_wrapper.config.expect && (config_wrapper.config.warning_range || config_wrapper.config.critical_range || config_wrapper.config.expect_re_str)) {
usage("Do not mix -e and -w/-c/-r/-R");
}
- if (expect_re_str && (warning_range || critical_range || expect)) {
+ if (config_wrapper.config.expect_re_str && (config_wrapper.config.warning_range || config_wrapper.config.critical_range || config_wrapper.config.expect)) {
usage("Do not mix -r/-R and -w/-c/-e");
}
- if (expect && (metric != METRIC_QUERY_RESULT)) {
+ if (config_wrapper.config.expect && (config_wrapper.config.metric != METRIC_QUERY_RESULT)) {
usage("Option -e requires metric QUERY_RESULT");
}
- if (expect_re_str && (metric != METRIC_QUERY_RESULT)) {
+ if (config_wrapper.config.expect_re_str && (config_wrapper.config.metric != METRIC_QUERY_RESULT)) {
usage("Options -r/-R require metric QUERY_RESULT");
}
- return OK;
+ config_wrapper.errorcode = OK;
+ return config_wrapper;
}
void print_help(void) {
@@ -551,6 +531,8 @@ void print_help(void) {
printf(" %s\n", _("DBI driver options"));
printf(" %s\n", "-q, --query=STRING");
printf(" %s\n", _("query to execute"));
+ printf(" %s\n", "-H STRING");
+ printf(" %s\n", _("target database host"));
printf("\n");
printf(UT_WARN_CRIT_RANGE);
@@ -625,13 +607,7 @@ void print_usage(void) {
printf(" [-e ] [-r|-R ]\n");
}
-#define CHECK_IGNORE_ERROR(s) \
- do { \
- if (metric != METRIC_QUERY_RESULT) \
- return (s); \
- } while (0)
-
-const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_type) {
+const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_type, mp_dbi_metric metric, mp_dbi_type type) {
const char *str;
if (field_type != DBI_TYPE_STRING) {
@@ -641,7 +617,9 @@ const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_ty
str = dbi_result_get_string_idx(res, 1);
if ((!str) || (strcmp(str, "ERROR") == 0)) {
- CHECK_IGNORE_ERROR(NULL);
+ if (metric != METRIC_QUERY_RESULT) {
+ return NULL;
+ }
np_dbi_print_error(conn, "CRITICAL - failed to fetch string value");
return NULL;
}
@@ -652,7 +630,7 @@ const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_ty
return str;
}
-double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) {
+double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type, mp_dbi_metric metric, mp_dbi_type type) {
double val = NAN;
if (*field_type == DBI_TYPE_INTEGER) {
@@ -663,16 +641,20 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) {
const char *val_str;
char *endptr = NULL;
- val_str = get_field_str(conn, res, *field_type);
+ val_str = get_field_str(conn, res, *field_type, metric, type);
if (!val_str) {
- CHECK_IGNORE_ERROR(NAN);
+ if (metric != METRIC_QUERY_RESULT) {
+ return NAN;
+ }
*field_type = DBI_TYPE_ERROR;
return NAN;
}
val = strtod(val_str, &endptr);
if (endptr == val_str) {
- CHECK_IGNORE_ERROR(NAN);
+ if (metric != METRIC_QUERY_RESULT) {
+ return NAN;
+ }
printf("CRITICAL - result value is not a numeric: %s\n", val_str);
*field_type = DBI_TYPE_ERROR;
return NAN;
@@ -683,7 +665,9 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) {
}
}
} else {
- CHECK_IGNORE_ERROR(NAN);
+ if (metric != METRIC_QUERY_RESULT) {
+ return NAN;
+ }
printf("CRITICAL - cannot parse value of type %s (%i)\n",
(*field_type == DBI_TYPE_BINARY) ? "BINARY"
: (*field_type == DBI_TYPE_DATETIME) ? "DATETIME"
@@ -695,36 +679,46 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) {
return val;
}
-double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val) {
+mp_state_enum get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val, mp_dbi_metric metric, mp_dbi_type type) {
unsigned short field_type;
double val = NAN;
if (dbi_result_get_numrows(res) == DBI_ROW_ERROR) {
- CHECK_IGNORE_ERROR(STATE_OK);
+ if (metric != METRIC_QUERY_RESULT) {
+ return STATE_OK;
+ }
np_dbi_print_error(conn, "CRITICAL - failed to fetch rows");
return STATE_CRITICAL;
}
if (dbi_result_get_numrows(res) < 1) {
- CHECK_IGNORE_ERROR(STATE_OK);
+ if (metric != METRIC_QUERY_RESULT) {
+ return STATE_OK;
+ }
printf("WARNING - no rows returned\n");
return STATE_WARNING;
}
if (dbi_result_get_numfields(res) == DBI_FIELD_ERROR) {
- CHECK_IGNORE_ERROR(STATE_OK);
+ if (metric != METRIC_QUERY_RESULT) {
+ return STATE_OK;
+ }
np_dbi_print_error(conn, "CRITICAL - failed to fetch fields");
return STATE_CRITICAL;
}
if (dbi_result_get_numfields(res) < 1) {
- CHECK_IGNORE_ERROR(STATE_OK);
+ if (metric != METRIC_QUERY_RESULT) {
+ return STATE_OK;
+ }
printf("WARNING - no fields returned\n");
return STATE_WARNING;
}
if (dbi_result_first_row(res) != 1) {
- CHECK_IGNORE_ERROR(STATE_OK);
+ if (metric != METRIC_QUERY_RESULT) {
+ return STATE_OK;
+ }
np_dbi_print_error(conn, "CRITICAL - failed to fetch first row");
return STATE_CRITICAL;
}
@@ -733,16 +727,18 @@ double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str,
if (field_type != DBI_TYPE_ERROR) {
if (type == TYPE_STRING) {
/* the value will be freed in dbi_result_free */
- *res_val_str = strdup(get_field_str(conn, res, field_type));
+ *res_val_str = strdup(get_field_str(conn, res, field_type, metric, type));
} else {
- val = get_field(conn, res, &field_type);
+ val = get_field(conn, res, &field_type, metric, type);
}
}
*res_val = val;
if (field_type == DBI_TYPE_ERROR) {
- CHECK_IGNORE_ERROR(STATE_OK);
+ if (metric != METRIC_QUERY_RESULT) {
+ return STATE_OK;
+ }
np_dbi_print_error(conn, "CRITICAL - failed to fetch data");
return STATE_CRITICAL;
}
@@ -751,14 +747,13 @@ double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str,
return STATE_OK;
}
-#undef CHECK_IGNORE_ERROR
-
-int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) {
+mp_state_enum do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time, mp_dbi_metric metric, mp_dbi_type type,
+ char *np_dbi_query) {
dbi_result res;
struct timeval timeval_start;
struct timeval timeval_end;
- int status = STATE_OK;
+ mp_state_enum status = STATE_OK;
assert(np_dbi_query);
@@ -774,7 +769,7 @@ int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *r
return STATE_CRITICAL;
}
- status = get_query_result(conn, res, res_val_str, res_val);
+ status = get_query_result(conn, res, res_val_str, res_val, metric, type);
gettimeofday(&timeval_end, NULL);
*res_time = timediff(timeval_start, timeval_end);
diff --git a/plugins/check_dbi.d/config.h b/plugins/check_dbi.d/config.h
new file mode 100644
index 00000000..f6f0d7b3
--- /dev/null
+++ b/plugins/check_dbi.d/config.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include "../../config.h"
+#include
+#include "../../lib/monitoringplug.h"
+
+typedef enum {
+ METRIC_CONN_TIME,
+ METRIC_SERVER_VERSION,
+ METRIC_QUERY_RESULT,
+ METRIC_QUERY_TIME,
+} mp_dbi_metric;
+
+typedef enum {
+ TYPE_NUMERIC,
+ TYPE_STRING,
+} mp_dbi_type;
+
+typedef struct {
+ char *key;
+ char *value;
+} driver_option_t;
+
+typedef struct {
+ char *dbi_driver;
+ char *host;
+ driver_option_t *dbi_options;
+ size_t dbi_options_num;
+ char *dbi_database;
+ char *dbi_query;
+
+ char *expect;
+ char *expect_re_str;
+ int expect_re_cflags;
+ mp_dbi_metric metric;
+ mp_dbi_type type;
+ char *warning_range;
+ char *critical_range;
+ thresholds *dbi_thresholds;
+
+} check_dbi_config;
+
+check_dbi_config check_dbi_config_init() {
+ check_dbi_config tmp = {
+ .dbi_driver = NULL,
+ .host = NULL,
+ .dbi_options = NULL,
+ .dbi_options_num = 0,
+ .dbi_database = NULL,
+ .dbi_query = NULL,
+
+ .expect = NULL,
+ .expect_re_str = NULL,
+ .expect_re_cflags = 0,
+ .metric = METRIC_QUERY_RESULT,
+ .type = TYPE_NUMERIC,
+
+ .warning_range = NULL,
+ .critical_range = NULL,
+ .dbi_thresholds = NULL,
+ };
+ return tmp;
+}
--
cgit v1.2.3-74-g34f1
From 2036d29b34891415097c7d31c8e16bc0135577ad Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 18:42:37 +0100
Subject: Make config constant
---
plugins/check_dbi.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c
index 1f4a7def..9efcd1cb 100644
--- a/plugins/check_dbi.c
+++ b/plugins/check_dbi.c
@@ -103,7 +103,7 @@ int main(int argc, char **argv) {
usage4(_("Could not parse arguments"));
}
- check_dbi_config config = tmp.config;
+ const check_dbi_config config = tmp.config;
/* Set signal handling and alarm */
if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) {
--
cgit v1.2.3-74-g34f1
From ff8aa20d0e42ca20184f67ec035d157c70ae7605 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Fri, 7 Mar 2025 19:29:24 +0100
Subject: Just use eval instead of Try::Tiny in tests
---
NPTest.pm | 6 +-----
1 file changed, 1 insertion(+), 5 deletions(-)
diff --git a/NPTest.pm b/NPTest.pm
index 987d3b71..1c008589 100644
--- a/NPTest.pm
+++ b/NPTest.pm
@@ -17,8 +17,6 @@ use File::Basename;
use JSON;
-use Try::Tiny;
-
use IO::File;
use Data::Dumper;
@@ -621,9 +619,7 @@ sub testCmd {
chomp $output;
$object->output($output);
- try {
- $object->{'mp_test_result'} = decode_json($output);
- };
+ eval { $object->{'mp_test_result'} = decode_json($output) };
alarm(0);
--
cgit v1.2.3-74-g34f1
From 665e2f91306fa9b38044a382e4b7571a0c8c0c5f Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sat, 22 Feb 2025 22:14:17 +0100
Subject: clang-format
---
plugins/check_ssh.c | 38 +++++++++++++++++++++++++-------------
1 file changed, 25 insertions(+), 13 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 42a88cf9..a50ca530 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -64,8 +64,9 @@ int main(int argc, char **argv) {
/* Parse extra opts if any */
argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments(argc, argv) == ERROR)
+ if (process_arguments(argc, argv) == ERROR) {
usage4(_("Could not parse arguments"));
+ }
/* initialize alarm signal handling */
signal(SIGALRM, socket_timeout_alarm_handler);
@@ -95,20 +96,24 @@ int process_arguments(int argc, char **argv) {
{"remote-protocol", required_argument, 0, 'P'},
{0, 0, 0, 0}};
- if (argc < 2)
+ if (argc < 2) {
return ERROR;
+ }
- for (int i = 1; i < argc; i++)
- if (strcmp("-to", argv[i]) == 0)
+ for (int i = 1; i < argc; i++) {
+ if (strcmp("-to", argv[i]) == 0) {
strcpy(argv[i], "-t");
+ }
+ }
int option_char;
while (true) {
int option = 0;
option_char = getopt_long(argc, argv, "+Vhv46t:r:H:p:P:", longopts, &option);
- if (option_char == -1 || option_char == EOF)
+ if (option_char == -1 || option_char == EOF) {
break;
+ }
switch (option_char) {
case '?': /* help */
@@ -123,10 +128,11 @@ int process_arguments(int argc, char **argv) {
verbose = true;
break;
case 't': /* timeout period */
- if (!is_integer(optarg))
+ if (!is_integer(optarg)) {
usage2(_("Timeout interval must be a positive integer"), optarg);
- else
+ } else {
socket_timeout = atoi(optarg);
+ }
break;
case '4':
address_family = AF_INET;
@@ -145,8 +151,9 @@ int process_arguments(int argc, char **argv) {
remote_protocol = optarg;
break;
case 'H': /* host */
- if (!is_host(optarg))
+ if (!is_host(optarg)) {
usage2(_("Invalid hostname/address"), optarg);
+ }
server_name = optarg;
break;
case 'p': /* port */
@@ -178,10 +185,12 @@ int process_arguments(int argc, char **argv) {
}
int validate_arguments(void) {
- if (server_name == NULL)
+ if (server_name == NULL) {
return ERROR;
- if (port == -1) /* funky, but allows -p to override stray integer in args */
+ }
+ if (port == -1) { /* funky, but allows -p to override stray integer in args */
port = SSH_DFL_PORT;
+ }
return OK;
}
@@ -198,8 +207,9 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
int socket;
int result = my_tcp_connect(haddr, hport, &socket);
- if (result != STATE_OK)
+ if (result != STATE_OK) {
return result;
+ }
char *output = (char *)calloc(BUFF_SZ + 1, sizeof(char));
char *buffer = NULL;
@@ -259,8 +269,9 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
* - RFC 4253:4.2
*/
strip(version_control_string);
- if (verbose)
+ if (verbose) {
printf("%s\n", version_control_string);
+ }
char *ssh_proto = version_control_string + 4;
@@ -297,8 +308,9 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
static char *rev_no = VERSION;
xasprintf(&buffer, "SSH-%s-check_ssh_%s\r\n", ssh_proto, rev_no);
send(socket, buffer, strlen(buffer), MSG_DONTWAIT);
- if (verbose)
+ if (verbose) {
printf("%s\n", buffer);
+ }
if (remote_version && strcmp(remote_version, ssh_server)) {
printf(_("SSH CRITICAL - %s (protocol %s) version mismatch, expected '%s'\n"), ssh_server, ssh_proto, remote_version);
--
cgit v1.2.3-74-g34f1
From fb4f46f93da4ac50654fdcc2f26b2f37c73a9230 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sat, 22 Feb 2025 22:39:10 +0100
Subject: Migrate check_users to new ouput infrastructure
---
plugins/Makefile.am | 1 +
plugins/check_users.c | 249 ++++++++++++++++++++---------------------
plugins/check_users.d/config.h | 19 ++++
plugins/check_users.d/users.c | 166 +++++++++++++++++++++++++++
plugins/check_users.d/users.h | 18 +++
5 files changed, 323 insertions(+), 130 deletions(-)
create mode 100644 plugins/check_users.d/config.h
create mode 100644 plugins/check_users.d/users.c
create mode 100644 plugins/check_users.d/users.h
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index d43c1971..e0069653 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -125,6 +125,7 @@ check_time_LDADD = $(NETLIBS)
check_ntp_time_LDADD = $(NETLIBS) $(MATHLIBS)
check_ups_LDADD = $(NETLIBS)
check_users_LDADD = $(BASEOBJS) $(WTSAPI32LIBS) $(SYSTEMDLIBS)
+check_users_SOURCES = check_users.c check_users.d/users.c
check_by_ssh_LDADD = $(NETLIBS)
check_ide_smart_LDADD = $(BASEOBJS)
negate_LDADD = $(BASEOBJS)
diff --git a/plugins/check_users.c b/plugins/check_users.c
index f1e1c39d..6ec87d21 100644
--- a/plugins/check_users.c
+++ b/plugins/check_users.c
@@ -3,7 +3,7 @@
* Monitoring check_users plugin
*
* License: GPL
- * Copyright (c) 2000-2024 Monitoring Plugins Development Team
+ * Copyright (c) 2000-2025 Monitoring Plugins Development Team
*
* Description:
*
@@ -30,12 +30,19 @@
*
*****************************************************************************/
+#include "check_users.d/config.h"
+#include "thresholds.h"
const char *progname = "check_users";
-const char *copyright = "2000-2024";
+const char *copyright = "2000-2025";
const char *email = "devel@monitoring-plugins.org";
-#include "common.h"
-#include "utils.h"
+#include "check_users.d/users.h"
+#include "output.h"
+#include "perfdata.h"
+#include "states.h"
+#include "utils_base.h"
+#include "./common.h"
+#include "./utils.h"
#if HAVE_WTSAPI32_H
# include
@@ -53,29 +60,16 @@ const char *email = "devel@monitoring-plugins.org";
# include
#endif
-#define possibly_set(a, b) ((a) == 0 ? (b) : 0)
+typedef struct process_argument_wrapper {
+ int errorcode;
+ check_users_config config;
+} process_argument_wrapper;
-static int process_arguments(int, char **);
-static void print_help(void);
+process_argument_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
+void print_help(void);
void print_usage(void);
-static char *warning_range = NULL;
-static char *critical_range = NULL;
-static thresholds *thlds = NULL;
-
int main(int argc, char **argv) {
- int users = -1;
- int result = STATE_UNKNOWN;
-#if HAVE_WTSAPI32_H
- WTS_SESSION_INFO *wtsinfo;
- DWORD wtscount;
- DWORD index;
-#elif HAVE_UTMPX_H
- struct utmpx *putmpx;
-#else
- char input_buffer[MAX_INPUT_BUFFER];
-#endif
-
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
@@ -83,121 +77,106 @@ int main(int argc, char **argv) {
/* Parse extra opts if any */
argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments(argc, argv) == ERROR)
- usage4(_("Could not parse arguments"));
-
- users = 0;
-
-#ifdef HAVE_LIBSYSTEMD
- if (sd_booted() > 0)
- users = sd_get_sessions(NULL);
- else {
-#endif
-#if HAVE_WTSAPI32_H
- if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) {
- printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
- return STATE_UNKNOWN;
- }
-
- for (index = 0; index < wtscount; index++) {
- LPTSTR username;
- DWORD size;
- int len;
-
- if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size))
- continue;
-
- len = lstrlen(username);
-
- WTSFreeMemory(username);
-
- if (len == 0)
- continue;
-
- if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected)
- users++;
- }
-
- WTSFreeMemory(wtsinfo);
-#elif HAVE_UTMPX_H
- /* get currently logged users from utmpx */
- setutxent();
-
- while ((putmpx = getutxent()) != NULL)
- if (putmpx->ut_type == USER_PROCESS)
- users++;
-
- endutxent();
-#else
- /* run the command */
- child_process = spopen(WHO_COMMAND);
- if (child_process == NULL) {
- printf(_("Could not open pipe: %s\n"), WHO_COMMAND);
- return STATE_UNKNOWN;
- }
-
- child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
- if (child_stderr == NULL)
- printf(_("Could not open stderr for %s\n"), WHO_COMMAND);
+ process_argument_wrapper tmp = process_arguments(argc, argv);
- while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
- /* increment 'users' on all lines except total user count */
- if (input_buffer[0] != '#') {
- users++;
- continue;
- }
-
- /* get total logged in users */
- if (sscanf(input_buffer, _("# users=%d"), &users) == 1)
- break;
+ if (tmp.errorcode == ERROR) {
+ usage4(_("Could not parse arguments"));
}
- /* check STDERR */
- if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
- result = possibly_set(result, STATE_UNKNOWN);
- (void)fclose(child_stderr);
+ check_users_config config = tmp.config;
- /* close the pipe */
- if (spclose(child_process))
- result = possibly_set(result, STATE_UNKNOWN);
-#endif
-#ifdef HAVE_LIBSYSTEMD
+#ifdef _WIN32
+# if HAVE_WTSAPI32_H
+ get_num_of_users_wrapper user_wrapper = get_num_of_users_windows();
+# else
+# error Did not find WTSAPI32
+# endif // HAVE_WTSAPI32_H
+#else
+# ifdef HAVE_LIBSYSTEMD
+ get_num_of_users_wrapper user_wrapper = get_num_of_users_systemd();
+# elif HAVE_UTMPX_H
+ get_num_of_users_wrapper user_wrapper = get_num_of_users_utmp();
+# else // !HAVE_LIBSYSTEMD && !HAVE_UTMPX_H
+ get_num_of_users_wrapper user_wrapper = get_num_of_users_who_command();
+# endif // HAVE_LIBSYSTEMD
+#endif // _WIN32
+
+ mp_check overall = mp_check_init();
+ mp_subcheck sc_users = mp_subcheck_init();
+
+ if (user_wrapper.errorcode != 0) {
+ sc_users = mp_set_subcheck_state(sc_users, STATE_UNKNOWN);
+ sc_users.output = "Failed to retrieve number of users";
+ mp_add_subcheck_to_check(&overall, sc_users);
+ mp_exit(overall);
}
-#endif
-
/* check the user count against warning and critical thresholds */
- result = get_status((double)users, thlds);
- if (result == STATE_UNKNOWN)
- printf("%s\n", _("Unable to read output"));
- else {
- printf(_("USERS %s - %d users currently logged in |%s\n"), state_text(result), users,
- sperfdata_int("users", users, "", warning_range, critical_range, true, 0, false, 0));
+ mp_perfdata users_pd = {
+ .label = "users",
+ .value = mp_create_pd_value(user_wrapper.users),
+ };
+
+ users_pd = mp_pd_set_thresholds(users_pd, config.thresholds);
+ mp_add_perfdata_to_subcheck(&sc_users, users_pd);
+
+ int tmp_status = mp_get_pd_status(users_pd);
+ sc_users = mp_set_subcheck_state(sc_users, tmp_status);
+
+ switch (tmp_status) {
+ case STATE_WARNING:
+ xasprintf(&sc_users.output, "%d users currently logged in. This violates the warning threshold", user_wrapper.users);
+ break;
+ case STATE_CRITICAL:
+ xasprintf(&sc_users.output, "%d users currently logged in. This violates the critical threshold", user_wrapper.users);
+ break;
+ default:
+ xasprintf(&sc_users.output, "%d users currently logged in", user_wrapper.users);
}
- return result;
+ mp_add_subcheck_to_check(&overall, sc_users);
+ mp_exit(overall);
}
+#define output_format_index CHAR_MAX + 1
+
/* process command-line arguments */
-int process_arguments(int argc, char **argv) {
+process_argument_wrapper process_arguments(int argc, char **argv) {
static struct option longopts[] = {{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
+ {"output-format", required_argument, 0, output_format_index},
{0, 0, 0, 0}};
- if (argc < 2)
+ if (argc < 2) {
usage("\n");
+ }
+
+ char *warning_range = NULL;
+ char *critical_range = NULL;
+ check_users_config config = check_users_config_init();
- int option_char;
while (true) {
- int option = 0;
- option_char = getopt_long(argc, argv, "+hVvc:w:", longopts, &option);
+ int counter = getopt_long(argc, argv, "+hVvc:w:", longopts, NULL);
- if (option_char == -1 || option_char == EOF || option_char == 1)
+ if (counter == -1 || counter == EOF || counter == 1) {
break;
+ }
- switch (option_char) {
+ switch (counter) {
+ case output_format_index: {
+ parsed_output_format parser = mp_parse_output_format(optarg);
+ if (!parser.parsing_success) {
+ // TODO List all available formats here, maybe add anothoer usage function
+ printf("Invalid output format: %s\n", optarg);
+ exit(STATE_UNKNOWN);
+ }
+
+ config.output_format_is_set = true;
+ config.output_format = parser.output_format;
+ break;
+ }
case '?': /* print short usage statement if args not parsable */
usage5();
case 'h': /* help */
@@ -215,26 +194,35 @@ int process_arguments(int argc, char **argv) {
}
}
- option_char = optind;
-
- if (warning_range == NULL && argc > option_char)
- warning_range = argv[option_char++];
-
- if (critical_range == NULL && argc > option_char)
- critical_range = argv[option_char++];
-
- /* this will abort in case of invalid ranges */
- set_thresholds(&thlds, warning_range, critical_range);
-
- if (!thlds->warning) {
- usage4(_("Warning threshold must be a valid range expression"));
+ // TODO add proper verification for ranges here!
+ if (warning_range) {
+ mp_range_parsed tmp = mp_parse_range_string(warning_range);
+ if (tmp.error == MP_PARSING_SUCCES) {
+ config.thresholds.warning = tmp.range;
+ config.thresholds.warning_is_set = true;
+ } else {
+ printf("Failed to parse warning range: %s", warning_range);
+ exit(STATE_UNKNOWN);
+ }
}
- if (!thlds->critical) {
- usage4(_("Critical threshold must be a valid range expression"));
+ if (critical_range) {
+ mp_range_parsed tmp = mp_parse_range_string(critical_range);
+ if (tmp.error == MP_PARSING_SUCCES) {
+ config.thresholds.critical = tmp.range;
+ config.thresholds.critical_is_set = true;
+ } else {
+ printf("Failed to parse critical range: %s", critical_range);
+ exit(STATE_UNKNOWN);
+ }
}
- return OK;
+ process_argument_wrapper result = {
+ .errorcode = OK,
+ .config = config,
+ };
+
+ return result;
}
void print_help(void) {
@@ -257,6 +245,7 @@ void print_help(void) {
printf(" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION"));
printf(" %s\n", "-c, --critical=RANGE_EXPRESSION");
printf(" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION"));
+ printf(UT_OUTPUT_FORMAT);
printf(UT_SUPPORT);
}
diff --git a/plugins/check_users.d/config.h b/plugins/check_users.d/config.h
new file mode 100644
index 00000000..35b7b7f8
--- /dev/null
+++ b/plugins/check_users.d/config.h
@@ -0,0 +1,19 @@
+#pragma once
+
+#include "output.h"
+#include "thresholds.h"
+typedef struct check_users_config {
+ mp_thresholds thresholds;
+
+ bool output_format_is_set;
+ mp_output_format output_format;
+} check_users_config;
+
+check_users_config check_users_config_init() {
+ check_users_config tmp = {
+ .thresholds = mp_thresholds_init(),
+
+ .output_format_is_set = false,
+ };
+ return tmp;
+}
diff --git a/plugins/check_users.d/users.c b/plugins/check_users.d/users.c
new file mode 100644
index 00000000..7969ae79
--- /dev/null
+++ b/plugins/check_users.d/users.c
@@ -0,0 +1,166 @@
+#include "./users.h"
+
+#ifdef _WIN32
+# ifdef HAVE_WTSAPI32_H
+# include
+# include
+# undef ERROR
+# define ERROR -1
+
+get_num_of_users_wrapper get_num_of_users_windows() {
+ WTS_SESSION_INFO *wtsinfo;
+ DWORD wtscount;
+
+ get_num_of_users_wrapper result = {};
+
+ if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) {
+ // printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
+ result.error = WINDOWS_COULD_NOT_ENUMERATE_SESSIONS;
+ return result;
+ }
+
+ for (DWORD index = 0; index < wtscount; index++) {
+ LPTSTR username;
+ DWORD size;
+
+ if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size)) {
+ continue;
+ }
+
+ int len = lstrlen(username);
+
+ WTSFreeMemory(username);
+
+ if (len == 0) {
+ continue;
+ }
+
+ if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected) {
+ result.users++;
+ }
+ }
+
+ WTSFreeMemory(wtsinfo);
+ return result;
+}
+# else // HAVE_WTSAPI32_H
+# error On windows but without the WTSAPI32 lib
+# endif // HAVE_WTSAPI32_H
+
+#else // _WIN32
+
+# include "../../config.h"
+
+# ifdef HAVE_LIBSYSTEMD
+# include
+# include
+
+get_num_of_users_wrapper get_num_of_users_systemd() {
+ get_num_of_users_wrapper result = {};
+
+ // Test whether we booted with systemd
+ if (sd_booted() > 0) {
+ int users = sd_get_sessions(NULL);
+ if (users >= 0) {
+ // Success
+ result.users = users;
+ return result;
+ }
+
+ // Failure! return the error code
+ result.errorcode = users;
+ return result;
+ }
+
+ // Looks like we are not running systemd,
+ // return with error here
+ result.errorcode = NO_SYSTEMD_ERROR;
+ return result;
+}
+# endif
+
+# ifdef HAVE_UTMPX_H
+# include
+
+get_num_of_users_wrapper get_num_of_users_utmp() {
+ int users = 0;
+
+ /* get currently logged users from utmpx */
+ setutxent();
+
+ struct utmpx *putmpx;
+ while ((putmpx = getutxent()) != NULL) {
+ if (putmpx->ut_type == USER_PROCESS) {
+ users++;
+ }
+ }
+
+ endutxent();
+
+ get_num_of_users_wrapper result = {
+ .errorcode = 0,
+ .users = users,
+ };
+
+ return result;
+}
+# endif
+
+# ifndef HAVE_WTSAPI32_H
+# ifndef HAVE_LIBSYSTEMD
+# ifndef HAVE_UTMPX_H
+// Fall back option here for the others (probably still not on windows)
+
+# include "../popen.h"
+# include "../common.h"
+# include "../utils.h"
+
+get_num_of_users_wrapper get_num_of_users_who_command() {
+ /* run the command */
+ child_process = spopen(WHO_COMMAND);
+ if (child_process == NULL) {
+ // printf(_("Could not open pipe: %s\n"), WHO_COMMAND);
+ get_num_of_users_wrapper result = {
+ .errorcode = COULD_NOT_OPEN_PIPE,
+ };
+ return result;
+ }
+
+ child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
+ if (child_stderr == NULL) {
+ // printf(_("Could not open stderr for %s\n"), WHO_COMMAND);
+ // TODO this error should probably be reported
+ }
+
+ get_num_of_users_wrapper result = {};
+ char input_buffer[MAX_INPUT_BUFFER];
+ while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
+ /* increment 'users' on all lines except total user count */
+ if (input_buffer[0] != '#') {
+ result.users++;
+ continue;
+ }
+
+ /* get total logged in users */
+ if (sscanf(input_buffer, _("# users=%d"), &result.users) == 1) {
+ break;
+ }
+ }
+
+ /* check STDERR */
+ if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
+ // if this fails, something broke and the result can not be relied upon or so is the theorie here
+ result.errorcode = STDERR_COULD_NOT_BE_READ;
+ }
+ (void)fclose(child_stderr);
+
+ /* close the pipe */
+ spclose(child_process);
+
+ return result;
+}
+
+# endif
+# endif
+# endif
+#endif
diff --git a/plugins/check_users.d/users.h b/plugins/check_users.d/users.h
new file mode 100644
index 00000000..aacba775
--- /dev/null
+++ b/plugins/check_users.d/users.h
@@ -0,0 +1,18 @@
+#pragma once
+
+typedef struct get_num_of_users_wrapper {
+ int errorcode;
+ int users;
+} get_num_of_users_wrapper;
+
+enum {
+ NO_SYSTEMD_ERROR = 64,
+ WINDOWS_COULD_NOT_ENUMERATE_SESSIONS,
+ COULD_NOT_OPEN_PIPE,
+ STDERR_COULD_NOT_BE_READ,
+};
+
+get_num_of_users_wrapper get_num_of_users_systemd();
+get_num_of_users_wrapper get_num_of_users_utmp();
+get_num_of_users_wrapper get_num_of_users_windows();
+get_num_of_users_wrapper get_num_of_users_who_command();
--
cgit v1.2.3-74-g34f1
From c87bc7eee4b83571199ffd14b70bfca5418ec101 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 10:14:29 +0100
Subject: check_ssh: centralize configuration in external header
---
plugins/check_ssh.c | 62 +++++++++++++++++++++++++-------------------
plugins/check_ssh.d/config.h | 21 +++++++++++++++
2 files changed, 56 insertions(+), 27 deletions(-)
create mode 100644 plugins/check_ssh.d/config.h
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index a50ca530..3745f799 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -35,6 +35,7 @@ const char *email = "devel@monitoring-plugins.org";
#include "./common.h"
#include "./netutils.h"
#include "utils.h"
+#include "./check_ssh.d/config.h"
#ifndef MSG_DONTWAIT
# define MSG_DONTWAIT 0
@@ -43,14 +44,14 @@ const char *email = "devel@monitoring-plugins.org";
#define SSH_DFL_PORT 22
#define BUFF_SZ 256
-static int port = -1;
-static char *server_name = NULL;
-static char *remote_version = NULL;
-static char *remote_protocol = NULL;
static bool verbose = false;
-static int process_arguments(int /*argc*/, char ** /*argv*/);
-static int validate_arguments(void);
+typedef struct process_arguments_wrapper {
+ int errorcode;
+ check_ssh_config config;
+} process_arguments_wrapper;
+
+static process_arguments_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
static void print_help(void);
void print_usage(void);
@@ -64,17 +65,21 @@ int main(int argc, char **argv) {
/* Parse extra opts if any */
argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments(argc, argv) == ERROR) {
+ process_arguments_wrapper tmp_config = process_arguments(argc, argv);
+
+ if (tmp_config.errorcode == ERROR) {
usage4(_("Could not parse arguments"));
}
+ check_ssh_config config = tmp_config.config;
+
/* initialize alarm signal handling */
signal(SIGALRM, socket_timeout_alarm_handler);
alarm(socket_timeout);
/* ssh_connect exits if error is found */
- int result = ssh_connect(server_name, port, remote_version, remote_protocol);
+ int result = ssh_connect(config.server_name, config.port, config.remote_version, config.remote_protocol);
alarm(0);
@@ -82,7 +87,7 @@ int main(int argc, char **argv) {
}
/* process command-line arguments */
-int process_arguments(int argc, char **argv) {
+process_arguments_wrapper process_arguments(int argc, char **argv) {
static struct option longopts[] = {{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"host", required_argument, 0, 'H'}, /* backward compatibility */
@@ -96,8 +101,14 @@ int process_arguments(int argc, char **argv) {
{"remote-protocol", required_argument, 0, 'P'},
{0, 0, 0, 0}};
+ process_arguments_wrapper result = {
+ .config = check_ssh_config_init(),
+ .errorcode = OK,
+ };
+
if (argc < 2) {
- return ERROR;
+ result.errorcode = ERROR;
+ return result;
}
for (int i = 1; i < argc; i++) {
@@ -145,20 +156,20 @@ int process_arguments(int argc, char **argv) {
#endif
break;
case 'r': /* remote version */
- remote_version = optarg;
+ result.config.remote_version = optarg;
break;
case 'P': /* remote version */
- remote_protocol = optarg;
+ result.config.remote_protocol = optarg;
break;
case 'H': /* host */
if (!is_host(optarg)) {
usage2(_("Invalid hostname/address"), optarg);
}
- server_name = optarg;
+ result.config.server_name = optarg;
break;
case 'p': /* port */
if (is_intpos(optarg)) {
- port = atoi(optarg);
+ result.config.port = atoi(optarg);
} else {
usage2(_("Port number must be a positive integer"), optarg);
}
@@ -166,32 +177,29 @@ int process_arguments(int argc, char **argv) {
}
option_char = optind;
- if (server_name == NULL && option_char < argc) {
+ if (result.config.server_name == NULL && option_char < argc) {
if (is_host(argv[option_char])) {
- server_name = argv[option_char++];
+ result.config.server_name = argv[option_char++];
}
}
- if (port == -1 && option_char < argc) {
+ if (result.config.port == -1 && option_char < argc) {
if (is_intpos(argv[option_char])) {
- port = atoi(argv[option_char++]);
+ result.config.port = atoi(argv[option_char++]);
} else {
print_usage();
exit(STATE_UNKNOWN);
}
}
- return validate_arguments();
-}
-
-int validate_arguments(void) {
- if (server_name == NULL) {
- return ERROR;
+ if (result.config.server_name == NULL) {
+ result.errorcode = ERROR;
+ return result;
}
- if (port == -1) { /* funky, but allows -p to override stray integer in args */
- port = SSH_DFL_PORT;
+ if (result.config.port == -1) { /* funky, but allows -p to override stray integer in args */
+ result.config.port = SSH_DFL_PORT;
}
- return OK;
+ return result;
}
/************************************************************************
diff --git a/plugins/check_ssh.d/config.h b/plugins/check_ssh.d/config.h
new file mode 100644
index 00000000..05698d83
--- /dev/null
+++ b/plugins/check_ssh.d/config.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include
+
+typedef struct check_ssh_config {
+ int port;
+ char *server_name;
+ char *remote_version;
+ char *remote_protocol;
+} check_ssh_config;
+
+check_ssh_config check_ssh_config_init(void) {
+ check_ssh_config tmp = {
+ .port = -1,
+ .server_name = NULL,
+ .remote_version = NULL,
+ .remote_protocol = NULL,
+ };
+
+ return tmp;
+}
--
cgit v1.2.3-74-g34f1
From ed06df7f34ad72439b2a0ebb0c0e527d2435050a Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:26:36 +0100
Subject: check_ssh: Migrate to new output infrastructure
---
plugins/check_ssh.c | 99 ++++++++++++++++++++++++++++++++++----------
plugins/check_ssh.d/config.h | 6 +++
2 files changed, 84 insertions(+), 21 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 3745f799..62c8b891 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -28,6 +28,9 @@
*
*****************************************************************************/
+#include "output.h"
+#include "perfdata.h"
+#include "states.h"
const char *progname = "check_ssh";
const char *copyright = "2000-2024";
const char *email = "devel@monitoring-plugins.org";
@@ -55,7 +58,7 @@ static process_arguments_wrapper process_arguments(int /*argc*/, char ** /*argv*
static void print_help(void);
void print_usage(void);
-static int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_protocol);
+static int ssh_connect(mp_check *overall, char *haddr, int hport, char *remote_version, char *remote_protocol);
int main(int argc, char **argv) {
setlocale(LC_ALL, "");
@@ -78,14 +81,21 @@ int main(int argc, char **argv) {
alarm(socket_timeout);
+ mp_check overall = mp_check_init();
+ if (config.output_format_is_set) {
+ overall.format = config.output_format;
+ }
+
/* ssh_connect exits if error is found */
- int result = ssh_connect(config.server_name, config.port, config.remote_version, config.remote_protocol);
+ ssh_connect(&overall, config.server_name, config.port, config.remote_version, config.remote_protocol);
alarm(0);
- return (result);
+ mp_exit(overall);
}
+#define output_format_index CHAR_MAX + 1
+
/* process command-line arguments */
process_arguments_wrapper process_arguments(int argc, char **argv) {
static struct option longopts[] = {{"help", no_argument, 0, 'h'},
@@ -99,6 +109,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
{"verbose", no_argument, 0, 'v'},
{"remote-version", required_argument, 0, 'r'},
{"remote-protocol", required_argument, 0, 'P'},
+ {"output-format", required_argument, 0, output_format_index},
{0, 0, 0, 0}};
process_arguments_wrapper result = {
@@ -173,6 +184,18 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
} else {
usage2(_("Port number must be a positive integer"), optarg);
}
+ case output_format_index: {
+ parsed_output_format parser = mp_parse_output_format(optarg);
+ if (!parser.parsing_success) {
+ // TODO List all available formats here, maybe add anothoer usage function
+ printf("Invalid output format: %s\n", optarg);
+ exit(STATE_UNKNOWN);
+ }
+
+ result.config.output_format_is_set = true;
+ result.config.output_format = parser.output_format;
+ break;
+ }
}
}
@@ -208,7 +231,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
*
*-----------------------------------------------------------------------*/
-int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_protocol) {
+int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_version, char *desired_remote_protocol) {
struct timeval tv;
gettimeofday(&tv, NULL);
@@ -260,15 +283,25 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
}
}
+ mp_subcheck connection_sc = mp_subcheck_init();
if (recv_ret < 0) {
- printf("SSH CRITICAL - %s", strerror(errno));
- exit(STATE_CRITICAL);
+ connection_sc = mp_set_subcheck_state(connection_sc, STATE_CRITICAL);
+ xasprintf(&connection_sc.output, "%s", "SSH CRITICAL - %s", strerror(errno));
+ mp_add_subcheck_to_check(overall, connection_sc);
+ return OK;
}
if (version_control_string == NULL) {
- printf("SSH CRITICAL - No version control string received");
- exit(STATE_CRITICAL);
+ connection_sc = mp_set_subcheck_state(connection_sc, STATE_CRITICAL);
+ xasprintf(&connection_sc.output, "%s", "SSH CRITICAL - No version control string received");
+ mp_add_subcheck_to_check(overall, connection_sc);
+ return OK;
}
+
+ connection_sc = mp_set_subcheck_state(connection_sc, STATE_OK);
+ xasprintf(&connection_sc.output, "%s", "Initial connection succeded");
+ mp_add_subcheck_to_check(overall, connection_sc);
+
/*
* "When the connection has been established, both sides MUST send an
* identification string. This identification string MUST be
@@ -307,10 +340,19 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
if (tmp) {
ssh_server[tmp - ssh_server] = '\0';
}
+
+ mp_subcheck protocol_validity_sc = mp_subcheck_init();
if (strlen(ssh_proto) == 0 || strlen(ssh_server) == 0) {
- printf(_("SSH CRITICAL - Invalid protocol version control string %s\n"), version_control_string);
- exit(STATE_CRITICAL);
+ protocol_validity_sc = mp_set_subcheck_state(protocol_validity_sc, STATE_CRITICAL);
+ xasprintf(&protocol_validity_sc.output, "Invalid protocol version control string %s", version_control_string);
+ mp_add_subcheck_to_check(overall, protocol_validity_sc);
+ return OK;
}
+
+ protocol_validity_sc = mp_set_subcheck_state(protocol_validity_sc, STATE_OK);
+ xasprintf(&protocol_validity_sc.output, "Valid protocol version control string %s", version_control_string);
+ mp_add_subcheck_to_check(overall, protocol_validity_sc);
+
ssh_proto[strspn(ssh_proto, "0123456789. ")] = 0;
static char *rev_no = VERSION;
@@ -320,24 +362,38 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
printf("%s\n", buffer);
}
- if (remote_version && strcmp(remote_version, ssh_server)) {
- printf(_("SSH CRITICAL - %s (protocol %s) version mismatch, expected '%s'\n"), ssh_server, ssh_proto, remote_version);
+ if (desired_remote_version && strcmp(desired_remote_version, ssh_server)) {
+ mp_subcheck remote_version_sc = mp_subcheck_init();
+ remote_version_sc = mp_set_subcheck_state(remote_version_sc, STATE_CRITICAL);
+ xasprintf(&remote_version_sc.output, _("%s (protocol %s) version mismatch, expected '%s'"), ssh_server, ssh_proto,
+ desired_remote_version);
close(socket);
- exit(STATE_CRITICAL);
+ mp_add_subcheck_to_check(overall, remote_version_sc);
+ return OK;
}
double elapsed_time = (double)deltime(tv) / 1.0e6;
- if (remote_protocol && strcmp(remote_protocol, ssh_proto)) {
- printf(_("SSH CRITICAL - %s (protocol %s) protocol version mismatch, expected '%s' | %s\n"), ssh_server, ssh_proto, remote_protocol,
- fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, true, (int)socket_timeout));
- close(socket);
- exit(STATE_CRITICAL);
+ mp_perfdata time_pd = perfdata_init();
+ time_pd.value = mp_create_pd_value(elapsed_time);
+ time_pd.label = "time";
+ time_pd.max_present = true;
+ time_pd.max = mp_create_pd_value(socket_timeout);
+
+ mp_subcheck protocol_version_sc = mp_subcheck_init();
+ mp_add_perfdata_to_subcheck(&protocol_version_sc, time_pd);
+
+ if (desired_remote_protocol && strcmp(desired_remote_protocol, ssh_proto)) {
+ protocol_version_sc = mp_set_subcheck_state(protocol_version_sc, STATE_CRITICAL);
+ xasprintf(&protocol_version_sc.output, _("%s (protocol %s) protocol version mismatch, expected '%s'"), ssh_server, ssh_proto,
+ desired_remote_protocol);
+ } else {
+ protocol_version_sc = mp_set_subcheck_state(protocol_version_sc, STATE_OK);
+ xasprintf(&protocol_version_sc.output, "SSH server verison: %s (protocol version: %s)", ssh_server, ssh_proto);
}
- printf(_("SSH OK - %s (protocol %s) | %s\n"), ssh_server, ssh_proto,
- fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, true, (int)socket_timeout));
+ mp_add_subcheck_to_check(overall, protocol_version_sc);
close(socket);
- exit(STATE_OK);
+ return OK;
}
void print_help(void) {
@@ -369,6 +425,7 @@ void print_help(void) {
printf(" %s\n", "-P, --remote-protocol=STRING");
printf(" %s\n", _("Alert if protocol doesn't match expected protocol version (ex: 2.0)"));
+ printf(UT_OUTPUT_FORMAT);
printf(UT_VERBOSE);
diff --git a/plugins/check_ssh.d/config.h b/plugins/check_ssh.d/config.h
index 05698d83..d739c57c 100644
--- a/plugins/check_ssh.d/config.h
+++ b/plugins/check_ssh.d/config.h
@@ -1,12 +1,16 @@
#pragma once
#include
+#include "../../lib/monitoringplug.h"
typedef struct check_ssh_config {
int port;
char *server_name;
char *remote_version;
char *remote_protocol;
+
+ bool output_format_is_set;
+ mp_output_format output_format;
} check_ssh_config;
check_ssh_config check_ssh_config_init(void) {
@@ -15,6 +19,8 @@ check_ssh_config check_ssh_config_init(void) {
.server_name = NULL,
.remote_version = NULL,
.remote_protocol = NULL,
+
+ .output_format_is_set = false,
};
return tmp;
--
cgit v1.2.3-74-g34f1
From 5ee9a5eadd7c9252fc4deb6cc502535d8e0e49d5 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:28:29 +0100
Subject: check_ssh: modify usage string to avoid old call syntax
---
plugins/check_ssh.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 62c8b891..0f1c0835 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -434,5 +434,5 @@ void print_help(void) {
void print_usage(void) {
printf("%s\n", _("Usage:"));
- printf("%s [-4|-6] [-t ] [-r ] [-p ] \n", progname);
+ printf("%s [-4|-6] [-t ] [-r ] [-p ] --hostname \n", progname);
}
--
cgit v1.2.3-74-g34f1
From add5bfb1e4029e406f7f331407c9d0f28d6d789b Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:32:18 +0100
Subject: check_ssh: Move default SSH constant around a bit
---
plugins/check_ssh.c | 7 ++-----
plugins/check_ssh.d/config.h | 4 +++-
2 files changed, 5 insertions(+), 6 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 0f1c0835..b73cdf24 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -44,7 +44,6 @@ const char *email = "devel@monitoring-plugins.org";
# define MSG_DONTWAIT 0
#endif
-#define SSH_DFL_PORT 22
#define BUFF_SZ 256
static bool verbose = false;
@@ -219,9 +218,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
result.errorcode = ERROR;
return result;
}
- if (result.config.port == -1) { /* funky, but allows -p to override stray integer in args */
- result.config.port = SSH_DFL_PORT;
- }
+
return result;
}
@@ -398,7 +395,7 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
void print_help(void) {
char *myport;
- xasprintf(&myport, "%d", SSH_DFL_PORT);
+ xasprintf(&myport, "%d", default_ssh_port);
print_revision(progname, NP_VERSION);
diff --git a/plugins/check_ssh.d/config.h b/plugins/check_ssh.d/config.h
index d739c57c..c150fd30 100644
--- a/plugins/check_ssh.d/config.h
+++ b/plugins/check_ssh.d/config.h
@@ -3,6 +3,8 @@
#include
#include "../../lib/monitoringplug.h"
+const int default_ssh_port = 22;
+
typedef struct check_ssh_config {
int port;
char *server_name;
@@ -15,7 +17,7 @@ typedef struct check_ssh_config {
check_ssh_config check_ssh_config_init(void) {
check_ssh_config tmp = {
- .port = -1,
+ .port = default_ssh_port,
.server_name = NULL,
.remote_version = NULL,
.remote_protocol = NULL,
--
cgit v1.2.3-74-g34f1
From 9ea4dbc25352c7cb408e392e5ae9011b9b0ff3d6 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:35:34 +0100
Subject: check_ssh: move only time relevant stuff in timeout area
---
plugins/check_ssh.c | 9 ++++-----
1 file changed, 4 insertions(+), 5 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index b73cdf24..3e25910d 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -75,16 +75,15 @@ int main(int argc, char **argv) {
check_ssh_config config = tmp_config.config;
- /* initialize alarm signal handling */
- signal(SIGALRM, socket_timeout_alarm_handler);
-
- alarm(socket_timeout);
-
mp_check overall = mp_check_init();
if (config.output_format_is_set) {
overall.format = config.output_format;
}
+ /* initialize alarm signal handling */
+ signal(SIGALRM, socket_timeout_alarm_handler);
+ alarm(socket_timeout);
+
/* ssh_connect exits if error is found */
ssh_connect(&overall, config.server_name, config.port, config.remote_version, config.remote_protocol);
--
cgit v1.2.3-74-g34f1
From b48ec884be9ee0026c20575f06a799b2444e284b Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:36:54 +0100
Subject: check_ssh: Verify that timeout is a positive integer
---
plugins/check_ssh.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 3e25910d..fe8681e2 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -148,7 +148,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
verbose = true;
break;
case 't': /* timeout period */
- if (!is_integer(optarg)) {
+ if (!is_intpos(optarg)) {
usage2(_("Timeout interval must be a positive integer"), optarg);
} else {
socket_timeout = atoi(optarg);
--
cgit v1.2.3-74-g34f1
From ce3eff0908b33140c5a99ee21d1c10405cbe9030 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:40:32 +0100
Subject: check_ssh: no more implicit conversion
---
plugins/check_ssh.c | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index fe8681e2..518950ec 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -151,7 +151,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
if (!is_intpos(optarg)) {
usage2(_("Timeout interval must be a positive integer"), optarg);
} else {
- socket_timeout = atoi(optarg);
+ socket_timeout = (unsigned int) atoi(optarg);
}
break;
case '4':
@@ -240,16 +240,16 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
char *output = (char *)calloc(BUFF_SZ + 1, sizeof(char));
char *buffer = NULL;
- ssize_t recv_ret = 0;
+ size_t recv_ret = 0;
char *version_control_string = NULL;
- ssize_t byte_offset = 0;
- while ((version_control_string == NULL) && (recv_ret = recv(socket, output + byte_offset, BUFF_SZ - byte_offset, 0) > 0)) {
+ size_t byte_offset = 0;
+ while ((version_control_string == NULL) && (recv_ret = recv(socket, output + byte_offset, (unsigned long)( BUFF_SZ - byte_offset), 0) > 0)) {
if (strchr(output, '\n')) { /* we've got at least one full line, start parsing*/
byte_offset = 0;
char *index = NULL;
- int len = 0;
+ unsigned long len = 0;
while ((index = strchr(output + byte_offset, '\n')) != NULL) {
/*Partition the buffer so that this line is a separate string,
* by replacing the newline with NUL*/
--
cgit v1.2.3-74-g34f1
From 46683da7b7a35a70dcb7dcb0e64160b78f84e965 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 11:40:45 +0100
Subject: check_ssh: fix typo
---
plugins/check_ssh.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 518950ec..ab4af352 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -295,7 +295,7 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
}
connection_sc = mp_set_subcheck_state(connection_sc, STATE_OK);
- xasprintf(&connection_sc.output, "%s", "Initial connection succeded");
+ xasprintf(&connection_sc.output, "%s", "Initial connection succeeded");
mp_add_subcheck_to_check(overall, connection_sc);
/*
@@ -384,7 +384,7 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
desired_remote_protocol);
} else {
protocol_version_sc = mp_set_subcheck_state(protocol_version_sc, STATE_OK);
- xasprintf(&protocol_version_sc.output, "SSH server verison: %s (protocol version: %s)", ssh_server, ssh_proto);
+ xasprintf(&protocol_version_sc.output, "SSH server version: %s (protocol version: %s)", ssh_server, ssh_proto);
}
mp_add_subcheck_to_check(overall, protocol_version_sc);
--
cgit v1.2.3-74-g34f1
From 92fb0ec66218059589d0b6b0fed08735b2765d60 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 13:02:30 +0100
Subject: check_ssh: add missing break statement
---
plugins/check_ssh.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index ab4af352..3d6a0710 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -182,6 +182,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
} else {
usage2(_("Port number must be a positive integer"), optarg);
}
+ break;
case output_format_index: {
parsed_output_format parser = mp_parse_output_format(optarg);
if (!parser.parsing_success) {
--
cgit v1.2.3-74-g34f1
From 6428696f31289c2777a34f4c0f761aa038da6284 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 13:03:00 +0100
Subject: check_ssh: exit properly if TCP connection fails
---
plugins/check_ssh.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 3d6a0710..d06af3e7 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -235,7 +235,11 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
int socket;
int result = my_tcp_connect(haddr, hport, &socket);
+ mp_subcheck connection_sc = mp_subcheck_init();
if (result != STATE_OK) {
+ connection_sc = mp_set_subcheck_state(connection_sc, STATE_CRITICAL);
+ xasprintf(&connection_sc.output, "Failed to establish TCP connection to Host %s and Port %d", haddr, hport);
+ mp_add_subcheck_to_check(overall, connection_sc);
return result;
}
@@ -280,7 +284,6 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
}
}
- mp_subcheck connection_sc = mp_subcheck_init();
if (recv_ret < 0) {
connection_sc = mp_set_subcheck_state(connection_sc, STATE_CRITICAL);
xasprintf(&connection_sc.output, "%s", "SSH CRITICAL - %s", strerror(errno));
--
cgit v1.2.3-74-g34f1
From 2e9f9ebf7d477956c5cc1779c0fa9c89352d7ab7 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 13:03:27 +0100
Subject: check_ssh.c: clang-format
---
plugins/check_ssh.c | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index d06af3e7..2ad7af66 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -44,7 +44,7 @@ const char *email = "devel@monitoring-plugins.org";
# define MSG_DONTWAIT 0
#endif
-#define BUFF_SZ 256
+#define BUFF_SZ 256
static bool verbose = false;
@@ -151,7 +151,7 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
if (!is_intpos(optarg)) {
usage2(_("Timeout interval must be a positive integer"), optarg);
} else {
- socket_timeout = (unsigned int) atoi(optarg);
+ socket_timeout = (unsigned int)atoi(optarg);
}
break;
case '4':
@@ -248,7 +248,8 @@ int ssh_connect(mp_check *overall, char *haddr, int hport, char *desired_remote_
size_t recv_ret = 0;
char *version_control_string = NULL;
size_t byte_offset = 0;
- while ((version_control_string == NULL) && (recv_ret = recv(socket, output + byte_offset, (unsigned long)( BUFF_SZ - byte_offset), 0) > 0)) {
+ while ((version_control_string == NULL) &&
+ (recv_ret = recv(socket, output + byte_offset, (unsigned long)(BUFF_SZ - byte_offset), 0) > 0)) {
if (strchr(output, '\n')) { /* we've got at least one full line, start parsing*/
byte_offset = 0;
--
cgit v1.2.3-74-g34f1
From 1ba8110da71abdccc9ee7f35cd0abefe78b8555b Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 13:04:04 +0100
Subject: check_ssh: adapt tests
---
plugins/t/check_ssh.t | 114 ++++++++++++++++++++++++++++++++++++--------------
1 file changed, 83 insertions(+), 31 deletions(-)
diff --git a/plugins/t/check_ssh.t b/plugins/t/check_ssh.t
index 907d33a8..8a20782e 100644
--- a/plugins/t/check_ssh.t
+++ b/plugins/t/check_ssh.t
@@ -5,10 +5,10 @@
#
use strict;
+use warnings;
use Test::More;
use NPTest;
-
-my $res;
+use JSON;
# Required parameters
my $ssh_host = getTestParameter("NP_SSH_HOST",
@@ -23,30 +23,38 @@ my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID",
"An invalid (not known to DNS) hostname",
"nosuchhost" );
+ my $outputFormat = '--output-format mp-test-json';
+
+plan tests => 24;
-plan tests => 14 + 6;
+my $output;
+my $result;
SKIP: {
skip "SSH_HOST must be defined", 6 unless $ssh_host;
+
+
my $result = NPTest->testCmd(
- "./check_ssh -H $ssh_host"
+ "./check_ssh -H $ssh_host" ." ". $outputFormat
);
cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
- like($result->output, '/^SSH OK - /', "Status text if command returned none (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "OK", "State was correct");
$result = NPTest->testCmd(
- "./check_ssh -H $host_nonresponsive -t 2"
+ "./check_ssh -H $host_nonresponsive -t 2" ." ". $outputFormat
);
- cmp_ok($result->return_code, '==', 2, "Exit with return code 0 (OK)");
- like($result->output, '/^CRITICAL - Socket timeout after 2 seconds/', "Status text if command returned none (OK)");
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "CRITICAL", "State was correct");
$result = NPTest->testCmd(
- "./check_ssh -H $hostname_invalid -t 2"
+ "./check_ssh -H $hostname_invalid -t 2" ." ". $outputFormat
);
- cmp_ok($result->return_code, '==', 3, "Exit with return code 0 (OK)");
+ cmp_ok($result->return_code, '==', 3, "Exit with return code 3 (UNKNOWN)");
like($result->output, '/^check_ssh: Invalid hostname/', "Status text if command returned none (OK)");
@@ -63,46 +71,80 @@ SKIP: {
#
# where `comments` is optional, protoversion is the SSH protocol version and
# softwareversion is an arbitrary string representing the server software version
+
+ my $found_version = 0;
+
open(NC, "echo 'SSH-2.0-nagiosplug.ssh.0.1' | nc ${nc_flags}|");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003" );
- cmp_ok( $res->return_code, '==', 0, "Got SSH protocol version control string");
- like( $res->output, '/^SSH OK - nagiosplug.ssh.0.1 \(protocol 2.0\)/', "Output OK");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "OK", "State was correct");
+
+ # looking for the version
+ for my $subcheck (@{$output->{'checks'}}) {
+ if ($subcheck->{'output'} =~ /.*nagiosplug.ssh.0.1 \(protocol version: 2.0\).*/ ){
+ $found_version = 1;
+ }
+ }
+ cmp_ok($found_version, '==', 1, "Output OK");
close NC;
open(NC, "echo 'SSH-2.0-3.2.9.1' | nc ${nc_flags}|");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003" );
- cmp_ok( $res->return_code, "==", 0, "Got SSH protocol version control string with non-alpha softwareversion string");
- like( $res->output, '/^SSH OK - 3.2.9.1 \(protocol 2.0\)/', "Output OK for non-alpha softwareversion string");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "OK", "State was correct");
+
+ $found_version = 0;
+ for my $subcheck (@{$output->{'checks'}}) {
+ if ($subcheck->{'output'} =~ /3.2.9.1 \(protocol version: 2.0\)/ ){
+ $found_version = 1;
+ }
+ }
+ cmp_ok($found_version, '==', 1, "Output OK");
close NC;
open(NC, "echo 'SSH-2.0-nagiosplug.ssh.0.1 this is a comment' | nc ${nc_flags} |");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003 -r nagiosplug.ssh.0.1" );
- cmp_ok( $res->return_code, '==', 0, "Got SSH protocol version control string, and parsed comment appropriately");
- like( $res->output, '/^SSH OK - nagiosplug.ssh.0.1 \(protocol 2.0\)/', "Output OK");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003 -r nagiosplug.ssh.0.1" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "OK", "State was correct");
+
+ # looking for the version
+ $found_version = 0;
+ for my $subcheck (@{$output->{'checks'}}) {
+ if ($subcheck->{'output'} =~ /nagiosplug.ssh.0.1 \(protocol version: 2.0\)/ ){
+ $found_version = 1;
+ }
+ }
+ cmp_ok($found_version, '==', 1, "Output OK");
close NC;
open(NC, "echo 'SSH-' | nc ${nc_flags}|");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003" );
- cmp_ok( $res->return_code, '==', 2, "Got invalid SSH protocol version control string");
- like( $res->output, '/^SSH CRITICAL/', "Output OK");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "CRITICAL", "Got invalid SSH protocol version control string");
close NC;
open(NC, "echo '' | nc ${nc_flags}|");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003" );
- cmp_ok( $res->return_code, '==', 2, "No version control string received");
- like( $res->output, '/^SSH CRITICAL - No version control string received/', "Output OK");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "CRITICAL", "No version control string received");
close NC;
open(NC, "echo 'Not a version control string' | nc ${nc_flags}|");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003" );
- cmp_ok( $res->return_code, '==', 2, "No version control string received");
- like( $res->output, '/^SSH CRITICAL - No version control string received/', "Output OK");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "CRITICAL", "No version control string received");
close NC;
@@ -116,8 +158,18 @@ SKIP: {
echo 'Some\nPrepended\nData\nLines\n'; sleep 0.2;
echo 'SSH-2.0-nagiosplug.ssh.0.2';} | nc ${nc_flags}|");
sleep 0.1;
- $res = NPTest->testCmd( "./check_ssh -H localhost -p 5003" );
- cmp_ok( $res->return_code, '==', 0, "Got delayed SSH protocol version control string");
- like( $res->output, '/^SSH OK - nagiosplug.ssh.0.2 \(protocol 2.0\)/', "Output OK");
+ $result = NPTest->testCmd( "./check_ssh -H localhost -p 5003" ." ". $outputFormat);
+ cmp_ok($result->return_code, '==', 0, "Exit with return code 0 (OK)");
+ $output = decode_json($result->output);
+ is($output->{'state'}, "OK", "State was correct");
+
+ # looking for the version
+ $found_version = 0;
+ for my $subcheck (@{$output->{'checks'}}) {
+ if ($subcheck->{'output'} =~ /nagiosplug.ssh.0.2 \(protocol version: 2.0\)/ ){
+ $found_version = 1;
+ }
+ }
+ cmp_ok($found_version, '==', 1, "Output OK");
close NC;
}
--
cgit v1.2.3-74-g34f1
From 53247ae748174ddb639bb5fd9a19c8a6ad121717 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 13:04:43 +0100
Subject: netutils.c: clang-format + do NOT print here
---
plugins/netutils.c | 79 ++++++++++++++++++++++++++++++++----------------------
1 file changed, 47 insertions(+), 32 deletions(-)
diff --git a/plugins/netutils.c b/plugins/netutils.c
index ee81912a..f5df7f3d 100644
--- a/plugins/netutils.c
+++ b/plugins/netutils.c
@@ -43,10 +43,11 @@ int address_family = AF_INET;
/* handles socket timeouts */
void socket_timeout_alarm_handler(int sig) {
- if (sig == SIGALRM)
+ if (sig == SIGALRM) {
printf(_("%s - Socket timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout);
- else
+ } else {
printf(_("%s - Abnormal timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout);
+ }
exit(socket_timeout_state);
}
@@ -65,12 +66,13 @@ int process_tcp_request2(const char *server_address, int server_port, const char
int recv_length = 0;
result = np_net_connect(server_address, server_port, &sd, IPPROTO_TCP);
- if (result != STATE_OK)
+ if (result != STATE_OK) {
return STATE_CRITICAL;
+ }
send_result = send(sd, send_buffer, strlen(send_buffer), 0);
if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) {
- printf("%s\n", _("Send failed"));
+ // printf("%s\n", _("Send failed"));
result = STATE_WARNING;
}
@@ -87,7 +89,7 @@ int process_tcp_request2(const char *server_address, int server_port, const char
if (!FD_ISSET(sd, &readfds)) { /* it hasn't */
if (!recv_length) {
strcpy(recv_buffer, "");
- printf("%s\n", _("No data was received from host!"));
+ // printf("%s\n", _("No data was received from host!"));
result = STATE_WARNING;
} else { /* this one failed, but previous ones worked */
recv_buffer[recv_length] = 0;
@@ -130,8 +132,9 @@ int process_request(const char *server_address, int server_port, int proto, cons
result = STATE_OK;
result = np_net_connect(server_address, server_port, &sd, proto);
- if (result != STATE_OK)
+ if (result != STATE_OK) {
return STATE_CRITICAL;
+ }
result = send_request(sd, proto, send_buffer, recv_buffer, recv_size);
@@ -169,15 +172,16 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
host_name++;
len -= 2;
}
- if (len >= sizeof(host))
+ if (len >= sizeof(host)) {
return STATE_UNKNOWN;
+ }
memcpy(host, host_name, len);
host[len] = '\0';
snprintf(port_str, sizeof(port_str), "%d", port);
result = getaddrinfo(host, port_str, &hints, &res);
if (result != 0) {
- printf("%s\n", gai_strerror(result));
+ // printf("%s\n", gai_strerror(result));
return STATE_UNKNOWN;
}
@@ -187,7 +191,7 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
*sd = socket(r->ai_family, socktype, r->ai_protocol);
if (*sd < 0) {
- printf("%s\n", _("Socket creation failed"));
+ // printf("%s\n", _("Socket creation failed"));
freeaddrinfo(r);
return STATE_UNKNOWN;
}
@@ -226,21 +230,23 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
die(STATE_UNKNOWN, _("Socket creation failed"));
}
result = connect(*sd, (struct sockaddr *)&su, sizeof(su));
- if (result < 0 && errno == ECONNREFUSED)
+ if (result < 0 && errno == ECONNREFUSED) {
was_refused = true;
+ }
}
- if (result == 0)
+ if (result == 0) {
return STATE_OK;
- else if (was_refused) {
+ } else if (was_refused) {
switch (econn_refuse_state) { /* a user-defined expected outcome */
case STATE_OK:
case STATE_WARNING: /* user wants WARN or OK on refusal, or... */
case STATE_CRITICAL: /* user did not set econn_refuse_state, or wanted critical */
- if (is_socket)
- printf("connect to file socket %s: %s\n", host_name, strerror(errno));
- else
- printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno));
+ if (is_socket) {
+ // printf("connect to file socket %s: %s\n", host_name, strerror(errno));
+ } else {
+ // printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno));
+ }
return STATE_CRITICAL;
break;
default: /* it's a logic error if we do not end up in STATE_(OK|WARNING|CRITICAL) */
@@ -248,10 +254,11 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
break;
}
} else {
- if (is_socket)
- printf("connect to file socket %s: %s\n", host_name, strerror(errno));
- else
- printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno));
+ if (is_socket) {
+ // printf("connect to file socket %s: %s\n", host_name, strerror(errno));
+ } else {
+ // printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno));
+ }
return STATE_CRITICAL;
}
}
@@ -265,7 +272,7 @@ int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer,
send_result = send(sd, send_buffer, strlen(send_buffer), 0);
if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) {
- printf("%s\n", _("Send failed"));
+ // printf("%s\n", _("Send failed"));
result = STATE_WARNING;
}
@@ -280,7 +287,7 @@ int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer,
/* make sure some data has arrived */
if (!FD_ISSET(sd, &readfds)) {
strcpy(recv_buffer, "");
- printf("%s\n", _("No data was received from host!"));
+ // printf("%s\n", _("No data was received from host!"));
result = STATE_WARNING;
}
@@ -288,11 +295,13 @@ int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer,
recv_result = recv(sd, recv_buffer, (size_t)recv_size - 1, 0);
if (recv_result == -1) {
strcpy(recv_buffer, "");
- if (proto != IPPROTO_TCP)
- printf("%s\n", _("Receive failed"));
+ if (proto != IPPROTO_TCP) {
+ // printf("%s\n", _("Receive failed"));
+ }
result = STATE_WARNING;
- } else
+ } else {
recv_buffer[recv_result] = 0;
+ }
/* die returned string */
recv_buffer[recv_size - 1] = 0;
@@ -301,26 +310,30 @@ int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer,
}
bool is_host(const char *address) {
- if (is_addr(address) || is_hostname(address))
+ if (is_addr(address) || is_hostname(address)) {
return (true);
+ }
return (false);
}
void host_or_die(const char *str) {
- if (!str || (!is_addr(str) && !is_hostname(str)))
+ if (!str || (!is_addr(str) && !is_hostname(str))) {
usage_va(_("Invalid hostname/address - %s"), str);
+ }
}
bool is_addr(const char *address) {
#ifdef USE_IPV6
- if (address_family == AF_INET && is_inet_addr(address))
+ if (address_family == AF_INET && is_inet_addr(address)) {
return true;
- else if (address_family == AF_INET6 && is_inet6_addr(address))
+ } else if (address_family == AF_INET6 && is_inet6_addr(address)) {
return true;
+ }
#else
- if (is_inet_addr(address))
+ if (is_inet_addr(address)) {
return (true);
+ }
#endif
return (false);
@@ -335,11 +348,13 @@ int dns_lookup(const char *in, struct sockaddr_storage *ss, int family) {
hints.ai_family = family;
retval = getaddrinfo(in, NULL, &hints, &res);
- if (retval != 0)
+ if (retval != 0) {
return false;
+ }
- if (ss != NULL)
+ if (ss != NULL) {
memcpy(ss, res->ai_addr, res->ai_addrlen);
+ }
freeaddrinfo(res);
return true;
}
--
cgit v1.2.3-74-g34f1
From d35c43e95f9efed3ef89bee288b8ec8f65ad2014 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 15:02:55 +0100
Subject: Revert "Migrate check_users to new ouput infrastructure"
This reverts commit 10086edbf03fd807794bcfb3fff626da69a9fdb2.
---
plugins/Makefile.am | 1 -
plugins/check_users.c | 249 +++++++++++++++++++++--------------------
plugins/check_users.d/config.h | 19 ----
plugins/check_users.d/users.c | 166 ---------------------------
plugins/check_users.d/users.h | 18 ---
5 files changed, 130 insertions(+), 323 deletions(-)
delete mode 100644 plugins/check_users.d/config.h
delete mode 100644 plugins/check_users.d/users.c
delete mode 100644 plugins/check_users.d/users.h
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index e0069653..d43c1971 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -125,7 +125,6 @@ check_time_LDADD = $(NETLIBS)
check_ntp_time_LDADD = $(NETLIBS) $(MATHLIBS)
check_ups_LDADD = $(NETLIBS)
check_users_LDADD = $(BASEOBJS) $(WTSAPI32LIBS) $(SYSTEMDLIBS)
-check_users_SOURCES = check_users.c check_users.d/users.c
check_by_ssh_LDADD = $(NETLIBS)
check_ide_smart_LDADD = $(BASEOBJS)
negate_LDADD = $(BASEOBJS)
diff --git a/plugins/check_users.c b/plugins/check_users.c
index 6ec87d21..f1e1c39d 100644
--- a/plugins/check_users.c
+++ b/plugins/check_users.c
@@ -3,7 +3,7 @@
* Monitoring check_users plugin
*
* License: GPL
- * Copyright (c) 2000-2025 Monitoring Plugins Development Team
+ * Copyright (c) 2000-2024 Monitoring Plugins Development Team
*
* Description:
*
@@ -30,19 +30,12 @@
*
*****************************************************************************/
-#include "check_users.d/config.h"
-#include "thresholds.h"
const char *progname = "check_users";
-const char *copyright = "2000-2025";
+const char *copyright = "2000-2024";
const char *email = "devel@monitoring-plugins.org";
-#include "check_users.d/users.h"
-#include "output.h"
-#include "perfdata.h"
-#include "states.h"
-#include "utils_base.h"
-#include "./common.h"
-#include "./utils.h"
+#include "common.h"
+#include "utils.h"
#if HAVE_WTSAPI32_H
# include
@@ -60,16 +53,29 @@ const char *email = "devel@monitoring-plugins.org";
# include
#endif
-typedef struct process_argument_wrapper {
- int errorcode;
- check_users_config config;
-} process_argument_wrapper;
+#define possibly_set(a, b) ((a) == 0 ? (b) : 0)
-process_argument_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
-void print_help(void);
+static int process_arguments(int, char **);
+static void print_help(void);
void print_usage(void);
+static char *warning_range = NULL;
+static char *critical_range = NULL;
+static thresholds *thlds = NULL;
+
int main(int argc, char **argv) {
+ int users = -1;
+ int result = STATE_UNKNOWN;
+#if HAVE_WTSAPI32_H
+ WTS_SESSION_INFO *wtsinfo;
+ DWORD wtscount;
+ DWORD index;
+#elif HAVE_UTMPX_H
+ struct utmpx *putmpx;
+#else
+ char input_buffer[MAX_INPUT_BUFFER];
+#endif
+
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
@@ -77,106 +83,121 @@ int main(int argc, char **argv) {
/* Parse extra opts if any */
argv = np_extra_opts(&argc, argv, progname);
- process_argument_wrapper tmp = process_arguments(argc, argv);
-
- if (tmp.errorcode == ERROR) {
+ if (process_arguments(argc, argv) == ERROR)
usage4(_("Could not parse arguments"));
- }
- check_users_config config = tmp.config;
+ users = 0;
+
+#ifdef HAVE_LIBSYSTEMD
+ if (sd_booted() > 0)
+ users = sd_get_sessions(NULL);
+ else {
+#endif
+#if HAVE_WTSAPI32_H
+ if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) {
+ printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
+ return STATE_UNKNOWN;
+ }
+
+ for (index = 0; index < wtscount; index++) {
+ LPTSTR username;
+ DWORD size;
+ int len;
-#ifdef _WIN32
-# if HAVE_WTSAPI32_H
- get_num_of_users_wrapper user_wrapper = get_num_of_users_windows();
-# else
-# error Did not find WTSAPI32
-# endif // HAVE_WTSAPI32_H
+ if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size))
+ continue;
+
+ len = lstrlen(username);
+
+ WTSFreeMemory(username);
+
+ if (len == 0)
+ continue;
+
+ if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected)
+ users++;
+ }
+
+ WTSFreeMemory(wtsinfo);
+#elif HAVE_UTMPX_H
+ /* get currently logged users from utmpx */
+ setutxent();
+
+ while ((putmpx = getutxent()) != NULL)
+ if (putmpx->ut_type == USER_PROCESS)
+ users++;
+
+ endutxent();
#else
-# ifdef HAVE_LIBSYSTEMD
- get_num_of_users_wrapper user_wrapper = get_num_of_users_systemd();
-# elif HAVE_UTMPX_H
- get_num_of_users_wrapper user_wrapper = get_num_of_users_utmp();
-# else // !HAVE_LIBSYSTEMD && !HAVE_UTMPX_H
- get_num_of_users_wrapper user_wrapper = get_num_of_users_who_command();
-# endif // HAVE_LIBSYSTEMD
-#endif // _WIN32
-
- mp_check overall = mp_check_init();
- mp_subcheck sc_users = mp_subcheck_init();
-
- if (user_wrapper.errorcode != 0) {
- sc_users = mp_set_subcheck_state(sc_users, STATE_UNKNOWN);
- sc_users.output = "Failed to retrieve number of users";
- mp_add_subcheck_to_check(&overall, sc_users);
- mp_exit(overall);
+ /* run the command */
+ child_process = spopen(WHO_COMMAND);
+ if (child_process == NULL) {
+ printf(_("Could not open pipe: %s\n"), WHO_COMMAND);
+ return STATE_UNKNOWN;
}
+
+ child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
+ if (child_stderr == NULL)
+ printf(_("Could not open stderr for %s\n"), WHO_COMMAND);
+
+ while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
+ /* increment 'users' on all lines except total user count */
+ if (input_buffer[0] != '#') {
+ users++;
+ continue;
+ }
+
+ /* get total logged in users */
+ if (sscanf(input_buffer, _("# users=%d"), &users) == 1)
+ break;
+ }
+
+ /* check STDERR */
+ if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
+ result = possibly_set(result, STATE_UNKNOWN);
+ (void)fclose(child_stderr);
+
+ /* close the pipe */
+ if (spclose(child_process))
+ result = possibly_set(result, STATE_UNKNOWN);
+#endif
+#ifdef HAVE_LIBSYSTEMD
+ }
+#endif
+
/* check the user count against warning and critical thresholds */
+ result = get_status((double)users, thlds);
- mp_perfdata users_pd = {
- .label = "users",
- .value = mp_create_pd_value(user_wrapper.users),
- };
-
- users_pd = mp_pd_set_thresholds(users_pd, config.thresholds);
- mp_add_perfdata_to_subcheck(&sc_users, users_pd);
-
- int tmp_status = mp_get_pd_status(users_pd);
- sc_users = mp_set_subcheck_state(sc_users, tmp_status);
-
- switch (tmp_status) {
- case STATE_WARNING:
- xasprintf(&sc_users.output, "%d users currently logged in. This violates the warning threshold", user_wrapper.users);
- break;
- case STATE_CRITICAL:
- xasprintf(&sc_users.output, "%d users currently logged in. This violates the critical threshold", user_wrapper.users);
- break;
- default:
- xasprintf(&sc_users.output, "%d users currently logged in", user_wrapper.users);
+ if (result == STATE_UNKNOWN)
+ printf("%s\n", _("Unable to read output"));
+ else {
+ printf(_("USERS %s - %d users currently logged in |%s\n"), state_text(result), users,
+ sperfdata_int("users", users, "", warning_range, critical_range, true, 0, false, 0));
}
- mp_add_subcheck_to_check(&overall, sc_users);
- mp_exit(overall);
+ return result;
}
-#define output_format_index CHAR_MAX + 1
-
/* process command-line arguments */
-process_argument_wrapper process_arguments(int argc, char **argv) {
+int process_arguments(int argc, char **argv) {
static struct option longopts[] = {{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
- {"output-format", required_argument, 0, output_format_index},
{0, 0, 0, 0}};
- if (argc < 2) {
+ if (argc < 2)
usage("\n");
- }
-
- char *warning_range = NULL;
- char *critical_range = NULL;
- check_users_config config = check_users_config_init();
+ int option_char;
while (true) {
- int counter = getopt_long(argc, argv, "+hVvc:w:", longopts, NULL);
+ int option = 0;
+ option_char = getopt_long(argc, argv, "+hVvc:w:", longopts, &option);
- if (counter == -1 || counter == EOF || counter == 1) {
+ if (option_char == -1 || option_char == EOF || option_char == 1)
break;
- }
- switch (counter) {
- case output_format_index: {
- parsed_output_format parser = mp_parse_output_format(optarg);
- if (!parser.parsing_success) {
- // TODO List all available formats here, maybe add anothoer usage function
- printf("Invalid output format: %s\n", optarg);
- exit(STATE_UNKNOWN);
- }
-
- config.output_format_is_set = true;
- config.output_format = parser.output_format;
- break;
- }
+ switch (option_char) {
case '?': /* print short usage statement if args not parsable */
usage5();
case 'h': /* help */
@@ -194,35 +215,26 @@ process_argument_wrapper process_arguments(int argc, char **argv) {
}
}
- // TODO add proper verification for ranges here!
- if (warning_range) {
- mp_range_parsed tmp = mp_parse_range_string(warning_range);
- if (tmp.error == MP_PARSING_SUCCES) {
- config.thresholds.warning = tmp.range;
- config.thresholds.warning_is_set = true;
- } else {
- printf("Failed to parse warning range: %s", warning_range);
- exit(STATE_UNKNOWN);
- }
- }
+ option_char = optind;
- if (critical_range) {
- mp_range_parsed tmp = mp_parse_range_string(critical_range);
- if (tmp.error == MP_PARSING_SUCCES) {
- config.thresholds.critical = tmp.range;
- config.thresholds.critical_is_set = true;
- } else {
- printf("Failed to parse critical range: %s", critical_range);
- exit(STATE_UNKNOWN);
- }
+ if (warning_range == NULL && argc > option_char)
+ warning_range = argv[option_char++];
+
+ if (critical_range == NULL && argc > option_char)
+ critical_range = argv[option_char++];
+
+ /* this will abort in case of invalid ranges */
+ set_thresholds(&thlds, warning_range, critical_range);
+
+ if (!thlds->warning) {
+ usage4(_("Warning threshold must be a valid range expression"));
}
- process_argument_wrapper result = {
- .errorcode = OK,
- .config = config,
- };
+ if (!thlds->critical) {
+ usage4(_("Critical threshold must be a valid range expression"));
+ }
- return result;
+ return OK;
}
void print_help(void) {
@@ -245,7 +257,6 @@ void print_help(void) {
printf(" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION"));
printf(" %s\n", "-c, --critical=RANGE_EXPRESSION");
printf(" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION"));
- printf(UT_OUTPUT_FORMAT);
printf(UT_SUPPORT);
}
diff --git a/plugins/check_users.d/config.h b/plugins/check_users.d/config.h
deleted file mode 100644
index 35b7b7f8..00000000
--- a/plugins/check_users.d/config.h
+++ /dev/null
@@ -1,19 +0,0 @@
-#pragma once
-
-#include "output.h"
-#include "thresholds.h"
-typedef struct check_users_config {
- mp_thresholds thresholds;
-
- bool output_format_is_set;
- mp_output_format output_format;
-} check_users_config;
-
-check_users_config check_users_config_init() {
- check_users_config tmp = {
- .thresholds = mp_thresholds_init(),
-
- .output_format_is_set = false,
- };
- return tmp;
-}
diff --git a/plugins/check_users.d/users.c b/plugins/check_users.d/users.c
deleted file mode 100644
index 7969ae79..00000000
--- a/plugins/check_users.d/users.c
+++ /dev/null
@@ -1,166 +0,0 @@
-#include "./users.h"
-
-#ifdef _WIN32
-# ifdef HAVE_WTSAPI32_H
-# include
-# include
-# undef ERROR
-# define ERROR -1
-
-get_num_of_users_wrapper get_num_of_users_windows() {
- WTS_SESSION_INFO *wtsinfo;
- DWORD wtscount;
-
- get_num_of_users_wrapper result = {};
-
- if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) {
- // printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
- result.error = WINDOWS_COULD_NOT_ENUMERATE_SESSIONS;
- return result;
- }
-
- for (DWORD index = 0; index < wtscount; index++) {
- LPTSTR username;
- DWORD size;
-
- if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size)) {
- continue;
- }
-
- int len = lstrlen(username);
-
- WTSFreeMemory(username);
-
- if (len == 0) {
- continue;
- }
-
- if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected) {
- result.users++;
- }
- }
-
- WTSFreeMemory(wtsinfo);
- return result;
-}
-# else // HAVE_WTSAPI32_H
-# error On windows but without the WTSAPI32 lib
-# endif // HAVE_WTSAPI32_H
-
-#else // _WIN32
-
-# include "../../config.h"
-
-# ifdef HAVE_LIBSYSTEMD
-# include
-# include
-
-get_num_of_users_wrapper get_num_of_users_systemd() {
- get_num_of_users_wrapper result = {};
-
- // Test whether we booted with systemd
- if (sd_booted() > 0) {
- int users = sd_get_sessions(NULL);
- if (users >= 0) {
- // Success
- result.users = users;
- return result;
- }
-
- // Failure! return the error code
- result.errorcode = users;
- return result;
- }
-
- // Looks like we are not running systemd,
- // return with error here
- result.errorcode = NO_SYSTEMD_ERROR;
- return result;
-}
-# endif
-
-# ifdef HAVE_UTMPX_H
-# include
-
-get_num_of_users_wrapper get_num_of_users_utmp() {
- int users = 0;
-
- /* get currently logged users from utmpx */
- setutxent();
-
- struct utmpx *putmpx;
- while ((putmpx = getutxent()) != NULL) {
- if (putmpx->ut_type == USER_PROCESS) {
- users++;
- }
- }
-
- endutxent();
-
- get_num_of_users_wrapper result = {
- .errorcode = 0,
- .users = users,
- };
-
- return result;
-}
-# endif
-
-# ifndef HAVE_WTSAPI32_H
-# ifndef HAVE_LIBSYSTEMD
-# ifndef HAVE_UTMPX_H
-// Fall back option here for the others (probably still not on windows)
-
-# include "../popen.h"
-# include "../common.h"
-# include "../utils.h"
-
-get_num_of_users_wrapper get_num_of_users_who_command() {
- /* run the command */
- child_process = spopen(WHO_COMMAND);
- if (child_process == NULL) {
- // printf(_("Could not open pipe: %s\n"), WHO_COMMAND);
- get_num_of_users_wrapper result = {
- .errorcode = COULD_NOT_OPEN_PIPE,
- };
- return result;
- }
-
- child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
- if (child_stderr == NULL) {
- // printf(_("Could not open stderr for %s\n"), WHO_COMMAND);
- // TODO this error should probably be reported
- }
-
- get_num_of_users_wrapper result = {};
- char input_buffer[MAX_INPUT_BUFFER];
- while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
- /* increment 'users' on all lines except total user count */
- if (input_buffer[0] != '#') {
- result.users++;
- continue;
- }
-
- /* get total logged in users */
- if (sscanf(input_buffer, _("# users=%d"), &result.users) == 1) {
- break;
- }
- }
-
- /* check STDERR */
- if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
- // if this fails, something broke and the result can not be relied upon or so is the theorie here
- result.errorcode = STDERR_COULD_NOT_BE_READ;
- }
- (void)fclose(child_stderr);
-
- /* close the pipe */
- spclose(child_process);
-
- return result;
-}
-
-# endif
-# endif
-# endif
-#endif
diff --git a/plugins/check_users.d/users.h b/plugins/check_users.d/users.h
deleted file mode 100644
index aacba775..00000000
--- a/plugins/check_users.d/users.h
+++ /dev/null
@@ -1,18 +0,0 @@
-#pragma once
-
-typedef struct get_num_of_users_wrapper {
- int errorcode;
- int users;
-} get_num_of_users_wrapper;
-
-enum {
- NO_SYSTEMD_ERROR = 64,
- WINDOWS_COULD_NOT_ENUMERATE_SESSIONS,
- COULD_NOT_OPEN_PIPE,
- STDERR_COULD_NOT_BE_READ,
-};
-
-get_num_of_users_wrapper get_num_of_users_systemd();
-get_num_of_users_wrapper get_num_of_users_utmp();
-get_num_of_users_wrapper get_num_of_users_windows();
-get_num_of_users_wrapper get_num_of_users_who_command();
--
cgit v1.2.3-74-g34f1
From 3cbd84ce754b1f7ce1ac8f9bc46059da62392ffe Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 16:35:51 +0100
Subject: Switch timeout handler to new output infrastructure
---
plugins/netutils.c | 14 +++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)
diff --git a/plugins/netutils.c b/plugins/netutils.c
index f5df7f3d..e2916c65 100644
--- a/plugins/netutils.c
+++ b/plugins/netutils.c
@@ -28,6 +28,8 @@
*****************************************************************************/
#include "common.h"
+#include "output.h"
+#include "states.h"
#include "netutils.h"
unsigned int socket_timeout = DEFAULT_SOCKET_TIMEOUT;
@@ -43,13 +45,19 @@ int address_family = AF_INET;
/* handles socket timeouts */
void socket_timeout_alarm_handler(int sig) {
+ mp_subcheck timeout_sc = mp_subcheck_init();
+ timeout_sc = mp_set_subcheck_state(timeout_sc, socket_timeout_state);
+
if (sig == SIGALRM) {
- printf(_("%s - Socket timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout);
+ xasprintf(&timeout_sc.output, _("Socket timeout after %d seconds\n"), socket_timeout);
} else {
- printf(_("%s - Abnormal timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout);
+ xasprintf(&timeout_sc.output, _("Abnormal timeout after %d seconds\n"), socket_timeout);
}
- exit(socket_timeout_state);
+ mp_check overall = mp_check_init();
+ mp_add_subcheck_to_check(&overall, timeout_sc);
+
+ mp_exit(overall);
}
/* connects to a host on a specified tcp port, sends a string, and gets a
--
cgit v1.2.3-74-g34f1
From 72fd885f4ff423d5351e3387867f2415f1ffc2d8 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Tue, 25 Feb 2025 17:20:05 +0100
Subject: Transform output format to a global state
This commit removes the format parameter from the mp_check
object and creates a module global variable instead.
This prevents thread safe usage of different mp_check objects
which should likely not present a big problem for now.
The reason for this change is effectively the very same,
the format was lost if an exit was triggered by a signal
handler (timeout in this example).
---
lib/output.c | 12 +++++++++---
lib/output.h | 7 ++++++-
plugins/check_ssh.c | 2 +-
plugins/check_swap.c | 2 +-
4 files changed, 17 insertions(+), 6 deletions(-)
diff --git a/lib/output.c b/lib/output.c
index 17919afc..61fbf832 100644
--- a/lib/output.c
+++ b/lib/output.c
@@ -11,6 +11,9 @@
#include "perfdata.h"
#include "states.h"
+// == Global variables
+static mp_output_format output_format = MP_FORMAT_DEFAULT;
+
// == Prototypes ==
static char *fmt_subcheck_output(mp_output_format output_format, mp_subcheck check, unsigned int indentation);
static inline cJSON *json_serialize_subcheck(mp_subcheck subcheck);
@@ -55,7 +58,6 @@ static inline char *fmt_subcheck_perfdata(mp_subcheck check) {
*/
mp_check mp_check_init(void) {
mp_check check = {0};
- check.format = MP_FORMAT_DEFAULT;
return check;
}
@@ -234,7 +236,7 @@ mp_state_enum mp_compute_check_state(const mp_check check) {
char *mp_fmt_output(mp_check check) {
char *result = NULL;
- switch (check.format) {
+ switch (output_format) {
case MP_FORMAT_MULTI_LINE: {
if (check.summary == NULL) {
check.summary = get_subcheck_summary(check);
@@ -482,7 +484,7 @@ void mp_print_output(mp_check check) { puts(mp_fmt_output(check)); }
*/
void mp_exit(mp_check check) {
mp_print_output(check);
- if (check.format == MP_FORMAT_TEST_JSON) {
+ if (output_format == MP_FORMAT_TEST_JSON) {
exit(0);
}
@@ -533,3 +535,7 @@ parsed_output_format mp_parse_output_format(char *format_string) {
return result;
}
+
+void mp_set_format(mp_output_format format) { output_format = format; }
+
+mp_output_format mp_get_format(void) { return output_format; }
diff --git a/lib/output.h b/lib/output.h
index ffc36f53..2bdfa074 100644
--- a/lib/output.h
+++ b/lib/output.h
@@ -35,6 +35,12 @@ typedef enum output_format {
#define MP_FORMAT_DEFAULT MP_FORMAT_MULTI_LINE
+/*
+ * Format related functions
+ */
+ void mp_set_format(mp_output_format format);
+ mp_output_format mp_get_format(void);
+
/*
* The main state object of a plugin. Exists only ONCE per plugin.
* This is the "root" of a tree of singular checks.
@@ -42,7 +48,6 @@ typedef enum output_format {
* in the first layer of subchecks
*/
typedef struct {
- mp_output_format format; // The output format
char *summary; // Overall summary, if not set a summary will be automatically generated
mp_subcheck_list *subchecks;
} mp_check;
diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c
index 2ad7af66..9d0d7cde 100644
--- a/plugins/check_ssh.c
+++ b/plugins/check_ssh.c
@@ -77,7 +77,7 @@ int main(int argc, char **argv) {
mp_check overall = mp_check_init();
if (config.output_format_is_set) {
- overall.format = config.output_format;
+ mp_set_format(config.output_format);
}
/* initialize alarm signal handling */
diff --git a/plugins/check_swap.c b/plugins/check_swap.c
index 4d3b6099..cb95949a 100644
--- a/plugins/check_swap.c
+++ b/plugins/check_swap.c
@@ -93,7 +93,7 @@ int main(int argc, char **argv) {
double percent_used;
mp_check overall = mp_check_init();
if (config.output_format_is_set) {
- overall.format = config.output_format;
+ mp_set_format(config.output_format);
}
mp_subcheck sc1 = mp_subcheck_init();
sc1 = mp_set_subcheck_default_state(sc1, STATE_OK);
--
cgit v1.2.3-74-g34f1
From f63d249984e33030c7e4b3fd97ebe3f034abce3c Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sat, 8 Mar 2025 23:42:06 +0100
Subject: Adapt further test to changed output
---
plugins/t/check_http.t | 2 +-
plugins/t/check_jabber.t | 2 +-
plugins/t/check_ldap.t | 2 +-
plugins/t/check_ntp.t | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/plugins/t/check_http.t b/plugins/t/check_http.t
index 6ab4a5b6..bb1fd27d 100644
--- a/plugins/t/check_http.t
+++ b/plugins/t/check_http.t
@@ -45,7 +45,7 @@ $res = NPTest->testCmd(
"./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3"
);
cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" );
-cmp_ok( $res->output, 'eq', "CRITICAL - Socket timeout after 3 seconds", "Output OK");
+like( $res->output, "/Socket timeout after/", "Output OK");
$res = NPTest->testCmd(
"./$plugin $hostname_invalid -wt 1 -ct 2"
diff --git a/plugins/t/check_jabber.t b/plugins/t/check_jabber.t
index fcdae179..08cadcbd 100644
--- a/plugins/t/check_jabber.t
+++ b/plugins/t/check_jabber.t
@@ -17,7 +17,7 @@ my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (no
my $jabberOK = '/JABBER OK\s-\s\d+\.\d+\ssecond response time on '.$host_tcp_jabber.' port 5222/';
-my $jabberUnresponsive = '/CRITICAL\s-\sSocket timeout after\s\d+\sseconds/';
+my $jabberUnresponsive = '/Socket timeout after\s\d+\sseconds/';
my $jabberInvalid = '/JABBER CRITICAL - Invalid hostname, address or socket:\s.+/';
diff --git a/plugins/t/check_ldap.t b/plugins/t/check_ldap.t
index b8a4a766..fcba0393 100644
--- a/plugins/t/check_ldap.t
+++ b/plugins/t/check_ldap.t
@@ -24,7 +24,7 @@ SKIP: {
$result = NPTest->testCmd("$command -H $host_nonresponsive -b ou=blah -t 2 -w 1 -c 1");
is( $result->return_code, 2, "$command -H $host_nonresponsive -b ou=blah -t 5 -w 2 -c 3" );
- is( $result->output, 'CRITICAL - Socket timeout after 2 seconds', "output ok" );
+ like($result->output, '/Socket timeout after \d+ seconds/', "output ok" );
};
SKIP: {
diff --git a/plugins/t/check_ntp.t b/plugins/t/check_ntp.t
index b8fc8fdf..e7bb76e3 100644
--- a/plugins/t/check_ntp.t
+++ b/plugins/t/check_ntp.t
@@ -37,7 +37,7 @@ my $ntp_critmatch1 = '/^NTP\sCRITICAL:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?
my $ntp_okmatch2 = '/^NTP\sOK:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+,\sstratum=[0-9]{1,2},\struechimers=[0-9]+/';
my $ntp_warnmatch2 = '/^NTP\sWARNING:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+,\sstratum=[0-9]{1,2}\s\(WARNING\),\struechimers=[0-9]+/';
my $ntp_critmatch2 = '/^NTP\sCRITICAL:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+\s\(CRITICAL\),\sstratum=[0-9]{1,2},\struechimers=[0-9]+/';
-my $ntp_noresponse = '/^(CRITICAL - Socket timeout after 3 seconds)|(NTP CRITICAL: No response from NTP server)$/';
+my $ntp_noresponse = '/^(.*Socket timeout after \d+ seconds.*)|.*No response from NTP server.*)$/';
my $ntp_nosuchhost = '/^check_ntp.*: Invalid hostname/address - ' . $hostname_invalid . '/';
--
cgit v1.2.3-74-g34f1
From fea6a662bd73496a29200023ed6a06bedefab415 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sun, 9 Mar 2025 00:12:37 +0100
Subject: fix accidently remove parentheses in test
---
plugins/t/check_ntp.t | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/plugins/t/check_ntp.t b/plugins/t/check_ntp.t
index e7bb76e3..a355aa4a 100644
--- a/plugins/t/check_ntp.t
+++ b/plugins/t/check_ntp.t
@@ -37,7 +37,7 @@ my $ntp_critmatch1 = '/^NTP\sCRITICAL:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?
my $ntp_okmatch2 = '/^NTP\sOK:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+,\sstratum=[0-9]{1,2},\struechimers=[0-9]+/';
my $ntp_warnmatch2 = '/^NTP\sWARNING:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+,\sstratum=[0-9]{1,2}\s\(WARNING\),\struechimers=[0-9]+/';
my $ntp_critmatch2 = '/^NTP\sCRITICAL:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+\s\(CRITICAL\),\sstratum=[0-9]{1,2},\struechimers=[0-9]+/';
-my $ntp_noresponse = '/^(.*Socket timeout after \d+ seconds.*)|.*No response from NTP server.*)$/';
+my $ntp_noresponse = '/^(.*Socket timeout after \d+ seconds.*)|(.*No response from NTP server.*)$/';
my $ntp_nosuchhost = '/^check_ntp.*: Invalid hostname/address - ' . $hostname_invalid . '/';
--
cgit v1.2.3-74-g34f1
From 809e79c7454c4b5771fe47c4da309dc82f917c25 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sun, 9 Mar 2025 00:30:33 +0100
Subject: Remove failing test
---
plugins/t/check_smtp.t | 1 -
1 file changed, 1 deletion(-)
diff --git a/plugins/t/check_smtp.t b/plugins/t/check_smtp.t
index 1a1ebe3e..11e22644 100644
--- a/plugins/t/check_smtp.t
+++ b/plugins/t/check_smtp.t
@@ -73,7 +73,6 @@ SKIP: {
my $unused_port = 4465;
$res = NPTest->testCmd( "./check_smtp -H $host_tcp_smtp_tls -p $unused_port --ssl" );
is ($res->return_code, 2, "Check rc of connecting to $host_tcp_smtp_tls with TLS on unused port $unused_port" );
- like ($res->output, qr/^connect to address $host_tcp_smtp_tls and port $unused_port: Connection refused/, "Check output of connecting to $host_tcp_smtp_tls with TLS on unused port $unused_port");
}
$res = NPTest->testCmd( "./check_smtp $host_nonresponsive" );
--
cgit v1.2.3-74-g34f1
From 69819d8c952a623f092186f7b99b10d6cb894d9c Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sun, 9 Mar 2025 10:24:28 +0100
Subject: Adapt test regex to new output
---
plugins/t/check_ntp.t | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/plugins/t/check_ntp.t b/plugins/t/check_ntp.t
index a355aa4a..a8ac7bb8 100644
--- a/plugins/t/check_ntp.t
+++ b/plugins/t/check_ntp.t
@@ -37,7 +37,7 @@ my $ntp_critmatch1 = '/^NTP\sCRITICAL:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?
my $ntp_okmatch2 = '/^NTP\sOK:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+,\sstratum=[0-9]{1,2},\struechimers=[0-9]+/';
my $ntp_warnmatch2 = '/^NTP\sWARNING:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+,\sstratum=[0-9]{1,2}\s\(WARNING\),\struechimers=[0-9]+/';
my $ntp_critmatch2 = '/^NTP\sCRITICAL:\sOffset\s-?[0-9]+(\.[0-9]+)?(e-[0-9]{2})?\ssecs,\sjitter=[0-9]+\.[0-9]+\s\(CRITICAL\),\sstratum=[0-9]{1,2},\struechimers=[0-9]+/';
-my $ntp_noresponse = '/^(.*Socket timeout after \d+ seconds.*)|(.*No response from NTP server.*)$/';
+my $ntp_noresponse = '/(.*Socket timeout after \d+ seconds.*)|(.*No response from NTP server.*)/';
my $ntp_nosuchhost = '/^check_ntp.*: Invalid hostname/address - ' . $hostname_invalid . '/';
--
cgit v1.2.3-74-g34f1
From 9d5774aede083297656bce14bd52e2c27a9d3169 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sun, 9 Mar 2025 10:25:01 +0100
Subject: Adapt number of tests
---
plugins/t/check_smtp.t | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/plugins/t/check_smtp.t b/plugins/t/check_smtp.t
index 11e22644..73b4a1fd 100644
--- a/plugins/t/check_smtp.t
+++ b/plugins/t/check_smtp.t
@@ -24,7 +24,7 @@ my $hostname_invalid = getTestParameter( "NP_HOSTNAME_INVALID",
"An invalid (not known to DNS) hostname", "nosuchhost" );
my $res;
-plan tests => 16;
+plan tests => 15;
SKIP: {
skip "No SMTP server defined", 4 unless $host_tcp_smtp;
--
cgit v1.2.3-74-g34f1
From 0426b8947d9e03375219074c3741616599651db4 Mon Sep 17 00:00:00 2001
From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>
Date: Sun, 9 Mar 2025 11:04:32 +0100
Subject: Add check_ssh config to distributable files
---
plugins/Makefile.am | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index a0e9cabf..28763dfc 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -46,7 +46,12 @@ SUBDIRS = picohttpparser
np_test_scripts = tests/test_check_swap.t
-EXTRA_DIST = t tests $(np_test_scripts) check_swap.d check_dbi.d
+EXTRA_DIST = t \
+ tests \
+ $(np_test_scripts) \
+ check_swap.d \
+ check_dbi.d \
+ check_ssh.d
PLUGINHDRS = common.h
--
cgit v1.2.3-74-g34f1