Merge branch 'master' into refactor/check_game

This commit is contained in:
Lorenz Kästle 2025-03-09 11:35:03 +01:00
commit 95311d2e2c
21 changed files with 1019 additions and 704 deletions

View file

@ -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' => '',

View file

@ -59,6 +59,7 @@ apt-get -y install perl \
mariadb-server \
mariadb-client \
libmariadb-dev \
libmariadb-dev-compat \
cron \
iputils-ping \
iproute2 \

View file

@ -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);
eval { $object->{'mp_test_result'} = decode_json($output) };
alarm(0);
my ($pkg, $file, $line) = caller(0);

View file

@ -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; }

View file

@ -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;

View file

@ -50,7 +50,9 @@ EXTRA_DIST = t \
tests \
$(np_test_scripts) \
check_swap.d \
check_game.d
check_game.d \
check_dbi.d \
check_ssh.d
PLUGINHDRS = common.h

View file

@ -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 <stdarg.h>
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;
typedef struct {
int errorcode;
check_dbi_config config;
} check_dbi_config_wrapper;
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;
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,8 +97,13 @@ 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"));
}
const check_dbi_config config = tmp.config;
/* Set signal handling and alarm */
if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) {
@ -137,8 +111,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,12 +127,13 @@ int main(int argc, char **argv) {
return STATE_UNKNOWN;
}
if (verbose)
printf("Opening DBI driver '%s'\n", np_dbi_driver);
if (verbose) {
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)) {
@ -176,17 +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);
if (verbose > 1) {
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)) {
@ -196,10 +174,11 @@ int main(int argc, char **argv) {
return STATE_UNKNOWN;
}
if (host) {
if (verbose > 1)
printf("Setting DBI driver option 'host' to '%s'\n", host);
dbi_conn_set_option(conn, "host", host);
if (config.host) {
if (verbose > 1) {
printf("Setting DBI driver option 'host' to '%s'\n", config.host);
}
dbi_conn_set_option(conn, "host", config.host);
}
if (verbose) {
@ -209,10 +188,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 = "<unspecified>";
if (!host)
}
if (!host) {
host = "<unspecified>";
}
printf("Connecting to database '%s' at host '%s'\n", dbname, host);
}
@ -226,109 +207,122 @@ 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)
status = get_status(server_version, dbi_thresholds);
if (config.metric == METRIC_SERVER_VERSION) {
status = get_status(server_version, config.dbi_thresholds);
}
if (verbose)
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 (verbose > 1)
printf("Selecting database '%s'\n", np_dbi_database);
if (config.dbi_database) {
if (verbose > 1) {
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);
if (status != STATE_OK)
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
} 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)
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
status = get_status(query_val, dbi_thresholds);
} else if (metric == METRIC_QUERY_TIME)
status = get_status(query_time, dbi_thresholds);
} else {
status = get_status(query_val, config.dbi_thresholds);
}
} else if (config.metric == METRIC_QUERY_TIME) {
status = get_status(query_time, config.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
* 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 : "<nothing>", 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 : "<nothing>", 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);
else
printf(", '%s' returned %f in %fs", np_dbi_query, query_val, query_time);
} else if (isnan(query_val)) {
printf(", '%s' query execution time: %fs", config.dbi_query, query_time);
} else {
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) {
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 : "");
((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, ((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, ((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,
@ -343,13 +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 */
@ -360,135 +360,148 @@ 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;
else if (!strcasecmp(optarg, "SERVER_VERSION"))
metric = METRIC_SERVER_VERSION;
else if (!strcasecmp(optarg, "QUERY_RESULT"))
metric = METRIC_QUERY_RESULT;
else if (!strcasecmp(optarg, "QUERY_TIME"))
metric = METRIC_QUERY_TIME;
else
if (!strcasecmp(optarg, "CONN_TIME")) {
result.config.metric = METRIC_CONN_TIME;
} else if (!strcasecmp(optarg, "SERVER_VERSION")) {
result.config.metric = METRIC_SERVER_VERSION;
} else if (!strcasecmp(optarg, "QUERY_RESULT")) {
result.config.metric = METRIC_QUERY_RESULT;
} else if (!strcasecmp(optarg, "QUERY_TIME")) {
result.config.metric = METRIC_QUERY_TIME;
} 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
host = optarg;
} else {
result.config.host = optarg;
}
break;
case 'v':
verbose++;
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 '<key>=<value>'"), 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) {
@ -518,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);
@ -592,13 +607,7 @@ void print_usage(void) {
printf(" [-e <string>] [-r|-R <regex>]\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) {
@ -608,17 +617,20 @@ 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;
}
if ((verbose && (type == TYPE_STRING)) || (verbose > 2))
if ((verbose && (type == TYPE_STRING)) || (verbose > 2)) {
printf("Query returned string '%s'\n", str);
}
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) {
@ -629,26 +641,33 @@ 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;
}
if ((endptr != NULL) && (*endptr != '\0')) {
if (verbose)
if (verbose) {
printf("Garbage after value: %s\n", endptr);
}
}
} 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"
@ -660,53 +679,66 @@ 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;
}
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
val = get_field(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, 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;
}
@ -715,19 +747,19 @@ 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);
if (verbose)
if (verbose) {
printf("Executing query '%s'\n", np_dbi_query);
}
gettimeofday(&timeval_start, NULL);
@ -737,13 +769,14 @@ 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);
if (verbose)
if (verbose) {
printf("Time elapsed: %f\n", *res_time);
}
return status;
}

View file

@ -0,0 +1,63 @@
#pragma once
#include "../../config.h"
#include <stddef.h>
#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;
}

View file

@ -1,40 +1,40 @@
/*****************************************************************************
*
* 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 <http://www.gnu.org/licenses/>.
*
*
*****************************************************************************/
*
* 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 <http://www.gnu.org/licenses/>.
*
*
*****************************************************************************/
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"
@ -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;
@ -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"
};
"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 */%'"
#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,158 +95,206 @@ main (int argc, char **argv)
char *result = NULL;
char *error = NULL;
char slaveresult[SLAVERESULTSIZE] = { 0 };
char* perf;
char replica_result[REPLICA_RESULTSIZE] = {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);
mysql_init(&mysql);
if (opt_group != NULL)
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
else
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");
if (opt_file != NULL) {
mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, opt_file);
}
if (ssl)
mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
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) {
/* check the slave status */
if (mysql_query (&mysql, "show slave status") != 0) {
if (check_replica) {
// 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, _("slave query error: %s\n"), error);
mysql_close(&mysql);
die(STATE_CRITICAL, _("replica 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, _("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 */
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, _("replica 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(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", 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;
MYSQL_FIELD* 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++) {
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) {
@ -270,150 +303,147 @@ 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");
/* 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, "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;
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", replica_result);
} else {
strncat(slaveresult, " Mysqldump: in progress", SLAVERESULTSIZE-1);
strncat(replica_result, " Mysqldump: in progress", REPLICA_RESULTSIZE - 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);
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);
}
}
}
/* 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);
if (check_replica) {
printf("%s %s|%s\n", result, replica_result, perf);
} else {
printf ("%s|%s\n", result, perf);
printf("%s|%s\n", result, perf);
}
return STATE_OK;
}
#define CHECK_REPLICA_OPT CHAR_MAX + 1
/* 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}
};
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)
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 +464,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 +476,41 @@ 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 */
case CHECK_REPLICA_OPT:
check_replica = 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 +518,122 @@ 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);
xasprintf(&myport, "%d", MYSQL_PORT);
print_revision (progname, NP_VERSION);
print_revision(progname, NP_VERSION);
printf (_(COPYRIGHT), copyright, email);
printf(_(COPYRIGHT), copyright, email);
printf ("%s\n", _("This program tests connections to a MySQL server"));
printf("%s\n", _("This program tests connections to a MySQL server"));
printf ("\n\n");
printf("\n\n");
print_usage ();
print_usage();
printf (UT_HELP_VRSN);
printf (UT_EXTRA_OPTS);
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(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", "-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(" %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. 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 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 replica 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", _("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 ("\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);
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");
}

View file

@ -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";
@ -35,26 +38,26 @@ 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
#endif
#define SSH_DFL_PORT 22
#define BUFF_SZ 256
#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);
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, "");
@ -64,24 +67,35 @@ 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;
mp_check overall = mp_check_init();
if (config.output_format_is_set) {
mp_set_format(config.output_format);
}
/* 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);
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 */
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 */
@ -93,22 +107,33 @@ int 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}};
if (argc < 2)
return ERROR;
process_arguments_wrapper result = {
.config = check_ssh_config_init(),
.errorcode = OK,
};
for (int i = 1; i < argc; i++)
if (strcmp("-to", argv[i]) == 0)
if (argc < 2) {
result.errorcode = ERROR;
return result;
}
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 +148,11 @@ int 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);
} else {
socket_timeout = (unsigned int)atoi(optarg);
}
break;
case '4':
address_family = AF_INET;
@ -139,50 +165,61 @@ 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))
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);
}
break;
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;
}
}
}
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();
}
if (result.config.server_name == NULL) {
result.errorcode = ERROR;
return result;
}
int validate_arguments(void) {
if (server_name == NULL)
return ERROR;
if (port == -1) /* funky, but allows -p to override stray integer in args */
port = SSH_DFL_PORT;
return OK;
return result;
}
/************************************************************************
@ -191,28 +228,34 @@ int validate_arguments(void) {
*
*-----------------------------------------------------------------------*/
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);
int socket;
int result = my_tcp_connect(haddr, hport, &socket);
if (result != STATE_OK)
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;
}
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*/
@ -243,14 +286,23 @@ int ssh_connect(char *haddr, int hport, char *remote_version, char *remote_proto
}
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 succeeded");
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
@ -259,8 +311,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;
@ -288,41 +341,65 @@ 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;
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);
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 version: %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) {
char *myport;
xasprintf(&myport, "%d", SSH_DFL_PORT);
xasprintf(&myport, "%d", default_ssh_port);
print_revision(progname, NP_VERSION);
@ -349,6 +426,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);
@ -357,5 +435,5 @@ void print_help(void) {
void print_usage(void) {
printf("%s\n", _("Usage:"));
printf("%s [-4|-6] [-t <timeout>] [-r <remote version>] [-p <port>] <host>\n", progname);
printf("%s [-4|-6] [-t <timeout>] [-r <remote version>] [-p <port>] --hostname <host>\n", progname);
}

View file

@ -0,0 +1,29 @@
#pragma once
#include <stddef.h>
#include "../../lib/monitoringplug.h"
const int default_ssh_port = 22;
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) {
check_ssh_config tmp = {
.port = default_ssh_port,
.server_name = NULL,
.remote_version = NULL,
.remote_protocol = NULL,
.output_format_is_set = false,
};
return tmp;
}

View file

@ -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);

View file

@ -28,6 +28,8 @@
*****************************************************************************/
#include "common.h"
#include "output.h"
#include "states.h"
#include "netutils.h"
unsigned int socket_timeout = DEFAULT_SOCKET_TIMEOUT;
@ -43,12 +45,19 @@ int address_family = AF_INET;
/* handles socket timeouts */
void socket_timeout_alarm_handler(int sig) {
if (sig == SIGALRM)
printf(_("%s - Socket timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout);
else
printf(_("%s - Abnormal timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout);
mp_subcheck timeout_sc = mp_subcheck_init();
timeout_sc = mp_set_subcheck_state(timeout_sc, socket_timeout_state);
exit(socket_timeout_state);
if (sig == SIGALRM) {
xasprintf(&timeout_sc.output, _("Socket timeout after %d seconds\n"), socket_timeout);
} else {
xasprintf(&timeout_sc.output, _("Abnormal timeout after %d seconds\n"), socket_timeout);
}
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
@ -65,12 +74,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 +97,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 +140,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 +180,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 +199,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 +238,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 +262,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 +280,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 +295,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 +303,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 +318,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 +356,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;
}

View file

@ -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"

View file

@ -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.+/';

View file

@ -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: {

View file

@ -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");
}

View file

@ -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 . '/';

View file

@ -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;
@ -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" );

View file

@ -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 => 14 + 6;
plan tests => 24;
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;
}

View file

@ -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");