/* 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); exit (socket_timeout_state); }
// Sets a connection's current state in the state machine. Any special // processing that needs to happen on certain state transitions can happen // here. void conn_set_state(conn *c, enum conn_states state) { assert(c != NULL); assert(state > conn_min_state && state < conn_max_state); if (state != c->state) { if (config.verbose > 2) { fprintf(stderr, "%d: going from %s to %s\n", c->sfd, state_text(c->state), state_text(state)); } c->state = state; } }
void SarkofagSupervisor::stateAll() { for (int i = 0; i < number_of_servos_; i++) { RTT::Attribute<ECServoState> * servo_ec_state = (RTT::Attribute<ECServoState> *) EC ->provides(services_names_[i])->getAttribute("state"); ec_servo_state_ = servo_ec_state->get(); std::cout << services_names_[i] << ": " << state_text(ec_servo_state_) << std::endl; } }
void timeout_alarm_handler (int signo) { if (signo == SIGALRM) { printf (_("%s - Plugin timed out after %d seconds\n"), state_text(timeout_state), timeout_interval); exit (timeout_state); } }
int main (int argc, char **argv) { int elapsed_time; int status = STATE_UNKNOWN; /* begin, by setting the parameters for a backend connection if the * parameters are null, then the system will try to use reasonable * defaults by looking up environment variables or, failing that, * using hardwired constants */ pgoptions = NULL; /* special options to start up the backend server */ pgtty = NULL; /* debugging tty for the backend server */ setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* Set signal handling and alarm */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage4 (_("Cannot catch SIGALRM")); } alarm (timeout_interval); /* make a connection to the database */ time (&start_time); conn = PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd); time (&end_time); elapsed_time = (int) (end_time - start_time); /* check to see that the backend connection was successfully made */ if (PQstatus (conn) == CONNECTION_BAD) { printf (_("CRITICAL - no connection to '%s' (%s).\n"), dbName, PQerrorMessage (conn)); PQfinish (conn); return STATE_CRITICAL; } else if (elapsed_time > tcrit) { status = STATE_CRITICAL; } else if (elapsed_time > twarn) { status = STATE_WARNING; } else { status = STATE_OK; } PQfinish (conn); printf (_(" %s - database %s (%d sec.)|%s\n"), state_text(status), dbName, elapsed_time, fperfdata("time", elapsed_time, "s", (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0)); return status; }
int main (int argc, char **argv) { int users = -1; int result = STATE_UNKNOWN; char *perf; struct utmpx *putmpx; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); perf = strdup (""); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); users = 0; /* get currently logged users from utmpx */ setutxent (); while ((putmpx = getutxent ()) != NULL) if (putmpx->ut_type == USER_PROCESS) users++; endutxent (); /* check the user count against warning and critical thresholds */ if (users > cusers) result = STATE_CRITICAL; else if (users > wusers) result = STATE_WARNING; else if (users >= 0) result = STATE_OK; if (result == STATE_UNKNOWN) printf ("%s\n", _("Unable to read output")); else { asprintf (&perf, "%s", perfdata ("users", users, "", TRUE, wusers, TRUE, cusers, TRUE, 0, FALSE, 0)); printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result), users, perf); } return result; }
int main (int argc, char **argv) { int c, i; nagstatus status = STATE_OK; set_program_name (argv[0]); while ((c = getopt_long (argc, argv, GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1) { switch (c) { default: usage (stderr); case_GETOPT_HELP_CHAR case_GETOPT_VERSION_CHAR } } if (argc <= optind) usage (stderr); mount_list = read_file_system_list (false); if (NULL == mount_list) /* Couldn't read the table of mounted file systems. */ plugin_error (STATE_UNKNOWN, 0, "cannot read table of mounted file systems"); for (i = optind; i < argc; ++i) if (STATE_CRITICAL == check_entry (argv[i])) status = STATE_CRITICAL; else /* This is allowed. See: * http://www.open-std.org/JTC1/sc22/wg14/www/docs/n1256.pdf */ argv[i] = NULL; printf ("filesystems %s", state_text (status)); for (i = optind; i < argc; ++i) if (argv[i]) printf (" %s", argv[i]); if (STATE_CRITICAL == status) printf (" unmounted!"); putchar ('\n'); return status; }
int main (int argc, char **argv) { int result = STATE_OK; FILE *fp; int line; char input_buffer[MAX_INPUT_BUFFER]; char *temp_buffer; time_t current_time; char *error_message; time_t timestamp = 0L; unsigned long average_incoming_rate = 0L; unsigned long average_outgoing_rate = 0L; unsigned long maximum_incoming_rate = 0L; unsigned long maximum_outgoing_rate = 0L; unsigned long incoming_rate = 0L; unsigned long outgoing_rate = 0L; double adjusted_incoming_rate = 0.0; double adjusted_outgoing_rate = 0.0; char incoming_speed_rating[8]; char outgoing_speed_rating[8]; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* open the MRTG log file for reading */ fp = fopen (log_file, "r"); if (fp == NULL) usage4 (_("Unable to open MRTG log file")); line = 0; while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) { line++; /* skip the first line of the log file */ if (line == 1) continue; /* break out of read loop */ /* if we've passed the number of entries we want to read */ if (line > 2) break; /* grab the timestamp */ temp_buffer = strtok (input_buffer, " "); timestamp = strtoul (temp_buffer, NULL, 10); /* grab the average incoming transfer rate */ temp_buffer = strtok (NULL, " "); average_incoming_rate = strtoul (temp_buffer, NULL, 10); /* grab the average outgoing transfer rate */ temp_buffer = strtok (NULL, " "); average_outgoing_rate = strtoul (temp_buffer, NULL, 10); /* grab the maximum incoming transfer rate */ temp_buffer = strtok (NULL, " "); maximum_incoming_rate = strtoul (temp_buffer, NULL, 10); /* grab the maximum outgoing transfer rate */ temp_buffer = strtok (NULL, " "); maximum_outgoing_rate = strtoul (temp_buffer, NULL, 10); } /* close the log file */ fclose (fp); /* if we couldn't read enough data, return an unknown error */ if (line <= 2) usage4 (_("Unable to process MRTG log file")); /* make sure the MRTG data isn't too old */ time (¤t_time); if ((expire_minutes > 0) && (current_time - timestamp) > (expire_minutes * 60)) die (STATE_WARNING, _("MRTG data has expired (%d minutes old)\n"), (int) ((current_time - timestamp) / 60)); /* else check the incoming/outgoing rates */ if (use_average == TRUE) { incoming_rate = average_incoming_rate; outgoing_rate = average_outgoing_rate; } else { incoming_rate = maximum_incoming_rate; outgoing_rate = maximum_outgoing_rate; } /* report incoming traffic in Bytes/sec */ if (incoming_rate < 1024) { strcpy (incoming_speed_rating, "B/s"); adjusted_incoming_rate = (double) incoming_rate; } /* report incoming traffic in KBytes/sec */ else if (incoming_rate < (1024 * 1024)) { strcpy (incoming_speed_rating, "KB/s"); adjusted_incoming_rate = (double) (incoming_rate / 1024.0); } /* report incoming traffic in MBytes/sec */ else { strcpy (incoming_speed_rating, "MB/s"); adjusted_incoming_rate = (double) (incoming_rate / 1024.0 / 1024.0); } /* report outgoing traffic in Bytes/sec */ if (outgoing_rate < 1024) { strcpy (outgoing_speed_rating, "B/s"); adjusted_outgoing_rate = (double) outgoing_rate; } /* report outgoing traffic in KBytes/sec */ else if (outgoing_rate < (1024 * 1024)) { strcpy (outgoing_speed_rating, "KB/s"); adjusted_outgoing_rate = (double) (outgoing_rate / 1024.0); } /* report outgoing traffic in MBytes/sec */ else { strcpy (outgoing_speed_rating, "MB/s"); adjusted_outgoing_rate = (double) (outgoing_rate / 1024.0 / 1024.0); } if (incoming_rate > incoming_critical_threshold || outgoing_rate > outgoing_critical_threshold) { result = STATE_CRITICAL; } else if (incoming_rate > incoming_warning_threshold || outgoing_rate > outgoing_warning_threshold) { result = STATE_WARNING; } xasprintf (&error_message, _("%s. In = %0.1f %s, %s. Out = %0.1f %s|%s %s\n"), (use_average == TRUE) ? _("Avg") : _("Max"), adjusted_incoming_rate, incoming_speed_rating, (use_average == TRUE) ? _("Avg") : _("Max"), adjusted_outgoing_rate, outgoing_speed_rating, fperfdata("in", adjusted_incoming_rate, incoming_speed_rating, (int)incoming_warning_threshold, incoming_warning_threshold, (int)incoming_critical_threshold, incoming_critical_threshold, TRUE, 0, FALSE, 0), fperfdata("out", adjusted_outgoing_rate, outgoing_speed_rating, (int)outgoing_warning_threshold, outgoing_warning_threshold, (int)outgoing_critical_threshold, outgoing_critical_threshold, TRUE, 0, FALSE, 0)); printf (_("Traffic %s - %s\n"), state_text(result), error_message); return result; }
int main (int argc, char **argv) { int c, err; bool verbose, cpu_model, per_cpu_stats; unsigned long len, i, count, delay; char *critical = NULL, *warning = NULL; char *p = NULL, *cpu_progname; nagstatus currstatus, status; thresholds *my_threshold = NULL; float cpu_perc = 0.0; unsigned int tog = 0; /* toggle switch for cleaner code */ struct cpu_desc *cpudesc = NULL; set_program_name (argv[0]); len = strlen (program_name); if (len > 6 && !strncmp (program_name, "check_", 6)) p = (char *) program_name + 6; else plugin_error (STATE_UNKNOWN, 0, "bug: the plugin does not have a standard name"); if (!strncmp (p, "iowait", 6)) /* check_iowait --> cpu_iowait */ { cpu_progname = xstrdup ("iowait"); program_shorthelp = xstrdup ("This plugin checks I/O wait bottlenecks\n"); } else /* check_cpu --> cpu_user (the default) */ { cpu_progname = xstrdup ("user");; program_shorthelp = xstrdup ("This plugin checks the CPU (user mode) utilization\n"); } err = cpu_desc_new (&cpudesc); if (err < 0) plugin_error (STATE_UNKNOWN, err, "memory exhausted"); /* default values */ verbose = per_cpu_stats = false; cpu_model = true; while ((c = getopt_long ( argc, argv, "c:w:vifmp" GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1) { switch (c) { default: usage (stderr); case 'i': cpu_desc_read (cpudesc); cpu_desc_summary (cpudesc); return STATE_UNKNOWN; case 'm': cpu_model = false; break; case 'p': per_cpu_stats = true; break; case 'c': critical = optarg; break; case 'w': warning = optarg; break; case 'v': verbose = true; break; case_GETOPT_HELP_CHAR case_GETOPT_VERSION_CHAR } } delay = DELAY_DEFAULT, count = COUNT_DEFAULT; if (optind < argc) { delay = strtol_or_err (argv[optind++], "failed to parse argument"); if (delay < 1) plugin_error (STATE_UNKNOWN, 0, "delay must be positive integer"); else if (DELAY_MAX < delay) plugin_error (STATE_UNKNOWN, 0, "too large delay value (greater than %d)", DELAY_MAX); } if (optind < argc) { count = strtol_or_err (argv[optind++], "failed to parse argument"); if (COUNT_MAX < count) plugin_error (STATE_UNKNOWN, 0, "too large count value (greater than %d)", COUNT_MAX); } status = set_thresholds (&my_threshold, warning, critical); if (status == NP_RANGE_UNPARSEABLE) usage (stderr); int ncpus = per_cpu_stats ? get_processor_number_total () + 1 : 1; jiff duser[ncpus], dsystem[ncpus], didle[ncpus], diowait[ncpus], dsteal[ncpus], ratio[ncpus]; int debt[ncpus]; /* handle idle ticks running backwards */ struct cpu_time cpuv[2][ncpus]; jiff *cpu_value = strncmp (p, "iowait", 6) ? duser : diowait; const char *cpuname; cpu_stats_get_time (cpuv[0], ncpus); for (c = 0; c < ncpus; c++) { duser[c] = cpuv[0][c].user + cpuv[0][c].nice; dsystem[c] = cpuv[0][c].system + cpuv[0][c].irq + cpuv[0][c].softirq; didle[c] = cpuv[0][c].idle; diowait[c] = cpuv[0][c].iowait; dsteal[c] = cpuv[0][c].steal; debt[c] = 0; ratio[c] = duser[c] + dsystem[c] + didle[c] + diowait[c] + dsteal[c]; if (!ratio[c]) ratio[c] = 1, didle[c] = 1; } for (i = 1; i < count; i++) { sleep (delay); tog = !tog; cpu_stats_get_time (cpuv[tog], ncpus); for (c = 0; c < ncpus; c++) { duser[c] = cpuv[tog][c].user - cpuv[!tog][c].user + cpuv[tog][c].nice - cpuv[!tog][c].nice; dsystem[c] = cpuv[tog][c].system - cpuv[!tog][c].system + cpuv[tog][c].irq - cpuv[!tog][c].irq + cpuv[tog][c].softirq - cpuv[!tog][c].softirq; didle[c] = cpuv[tog][c].idle - cpuv[!tog][c].idle; diowait[c] = cpuv[tog][c].iowait - cpuv[!tog][c].iowait; dsteal[c] = cpuv[tog][c].steal - cpuv[!tog][c].steal; /* idle can run backwards for a moment -- kernel "feature" */ if (debt[c]) { didle[c] = (int) didle[c] + debt[c]; debt[c] = 0; } if ((int) didle[c] < 0) { debt[c] = (int) didle[c]; didle[c] = 0; } ratio[c] = duser[c] + dsystem[c] + didle[c] + diowait[c] + dsteal[c]; if (!ratio[c]) ratio[c] = 1, didle[c] = 1; if (NULL == (cpuname = cpuv[0][c].cpuname)) cpuname = "n/a"; if (verbose) printf ("%s_user=%.1f%%, %s_system=%.1f%%, %s_idle=%.1f%%, " "%s_iowait=%.1f%%, %s_steal=%.1f%%\n" , cpuname, 100.0 * duser[c] / ratio[c] , cpuname, 100.0 * dsystem[c] / ratio[c] , cpuname, 100.0 * didle[c] / ratio[c] , cpuname, 100.0 * diowait[c] / ratio[c] , cpuname, 100.0 * dsteal[c] / ratio[c]); dbg ("sum (%s_*) = %.1f%%\n", cpuname, (100.0 * duser[c] / ratio[c]) + (100.0 * dsystem[c] / ratio[c]) + (100.0 * didle[c] / ratio[c]) + (100.0 * diowait[c] / ratio[c]) + (100.0 * dsteal[c] / ratio[c])); } } for (c = 0, status = STATE_OK; c < ncpus; c++) { cpu_perc = (100.0 * (cpu_value[c]) / ratio[c]); currstatus = get_status (cpu_perc, my_threshold); if (currstatus > status) status = currstatus; } cpu_desc_read (cpudesc); char *cpu_model_str = cpu_model ? xasprintf ("(%s) ", cpu_desc_get_model_name (cpudesc)) : NULL; printf ("%s %s%s - cpu %s %.1f%% |" , program_name_short, cpu_model ? cpu_model_str : "" , state_text (status), cpu_progname, cpu_perc); for (c = 0; c < ncpus; c++) { if ((cpuname = cpuv[0][c].cpuname)) printf (" %s_user=%.1f%% %s_system=%.1f%% %s_idle=%.1f%%" " %s_iowait=%.1f%% %s_steal=%.1f%%" , cpuname, 100.0 * duser[c] / ratio[c] , cpuname, 100.0 * dsystem[c] / ratio[c] , cpuname, 100.0 * didle[c] / ratio[c] , cpuname, 100.0 * diowait[c] / ratio[c] , cpuname, 100.0 * dsteal[c] / ratio[c]); } putchar ('\n'); cpu_desc_unref (cpudesc); return status; }
int main (int argc, char **argv) { char *command_line; output chld_out, chld_err; char *msg = NULL; size_t i; char *t; long microsec; double elapsed_time; int result = STATE_UNKNOWN; int timeout_interval_dig; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Set signal handling and alarm */ if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) usage_va(_("Cannot catch SIGALRM")); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage_va(_("Could not parse arguments")); /* dig applies the timeout to each try, so we need to work around this */ timeout_interval_dig = timeout_interval / number_tries + number_tries; /* get the command to run */ xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +tries=%d +time=%d", PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig); alarm (timeout_interval); gettimeofday (&tv, NULL); if (verbose) { printf ("%s\n", command_line); if(expected_address != NULL) { printf (_("Looking for: '%s'\n"), expected_address); } else { printf (_("Looking for: '%s'\n"), query_address); } } /* run the command */ if(np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) { result = STATE_WARNING; msg = (char *)_("dig returned an error status"); } for(i = 0; i < chld_out.lines; i++) { /* the server is responding, we just got the host name... */ if (strstr (chld_out.line[i], ";; ANSWER SECTION:")) { /* loop through the whole 'ANSWER SECTION' */ for(; i < chld_out.lines; i++) { /* get the host address */ if (verbose) printf ("%s\n", chld_out.line[i]); if (strstr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) { msg = chld_out.line[i]; result = STATE_OK; /* Translate output TAB -> SPACE */ t = msg; while ((t = strchr(t, '\t')) != NULL) *t = ' '; break; } } if (result == STATE_UNKNOWN) { msg = (char *)_("Server not found in ANSWER SECTION"); result = STATE_WARNING; } /* we found the answer section, so break out of the loop */ break; } } if (result == STATE_UNKNOWN) { msg = (char *)_("No ANSWER SECTION found"); result = STATE_CRITICAL; } /* If we get anything on STDERR, at least set warning */ if(chld_err.buflen > 0) { result = max_state(result, STATE_WARNING); if(!msg) for(i = 0; i < chld_err.lines; i++) { msg = strchr(chld_err.line[0], ':'); if(msg) { msg++; break; } } } microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (critical_interval > UNDEFINED && elapsed_time > critical_interval) result = STATE_CRITICAL; else if (warning_interval > UNDEFINED && elapsed_time > warning_interval) result = STATE_WARNING; printf ("DNS %s - %.3f seconds response time (%s)|%s\n", state_text (result), elapsed_time, msg ? msg : _("Probably a non-existent host/domain"), fperfdata("time", elapsed_time, "s", (warning_interval>UNDEFINED?TRUE:FALSE), warning_interval, (critical_interval>UNDEFINED?TRUE:FALSE), critical_interval, TRUE, 0, FALSE, 0)); return result; }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; int disk_result = STATE_UNKNOWN; char *output; char *details; char *perf; char *preamble; double inode_space_pct; double warning_high_tide; double critical_high_tide; int temp_result; struct mount_entry *me; struct fs_usage fsp, tmpfsp; struct parameter_list *temp_list, *path; preamble = strdup (" - free space:"); output = strdup (""); details = strdup (""); perf = strdup (""); stat_buf = malloc(sizeof *stat_buf); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); mount_list = read_file_system_list (0); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If a list of paths has not been selected, find entire mount list and create list of paths */ if (path_selected == FALSE) { for (me = mount_list; me; me = me->me_next) { if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) { path = np_add_parameter(&path_select_list, me->me_mountdir); } path->best_match = me; path->group = group; set_all_thresholds(path); } } np_set_best_match(path_select_list, mount_list, exact_match); /* Error if no match found for specified paths */ temp_list = path_select_list; while (temp_list) { if (! temp_list->best_match) { die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name); } temp_list = temp_list->name_next; } /* Process for every path in list */ for (path = path_select_list; path; path=path->name_next) { if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) printf("Thresholds(pct) for %s warn: %f crit %f\n",path->name, path->freespace_percent->warning->end, path->freespace_percent->critical->end); if (verbose >= 3 && path->group != NULL) printf("Group of %s: %s\n",path->name,path->group); /* reset disk result */ disk_result = STATE_UNKNOWN; me = path->best_match; /* Filters */ /* Remove filesystems already seen */ if (np_seen_name(seen, me->me_mountdir)) { continue; } np_add_name(&seen, me->me_mountdir); if (path->group == NULL) { /* Skip remote filesystems if we're not interested in them */ if (me->me_remote && show_local_fs) { if (stat_remote_fs) stat_path(path); continue; /* Skip pseudo fs's if we haven't asked for all fs's */ } else if (me->me_dummy && !show_all_fs) { continue; /* Skip excluded fstypes */ } else if (fs_exclude_list && np_find_name (fs_exclude_list, me->me_type)) { continue; /* Skip excluded fs's */ } else if (dp_exclude_list && (np_find_name (dp_exclude_list, me->me_devname) || np_find_name (dp_exclude_list, me->me_mountdir))) { continue; /* Skip not included fstypes */ } else if (fs_include_list && !np_find_name (fs_include_list, me->me_type)) { continue; } } stat_path(path); get_fs_usage (me->me_mountdir, me->me_devname, &fsp); if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) { get_stats (path, &fsp); if (verbose >= 3) { printf ("For %s, used_pct=%g free_pct=%g used_units=%g free_units=%g total_units=%g used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", me->me_mountdir, path->dused_pct, path->dfree_pct, path->dused_units, path->dfree_units, path->dtotal_units, path->dused_inodes_percent, path->dfree_inodes_percent, fsp.fsu_blocksize, mult); } /* Threshold comparisons */ temp_result = get_status(path->dfree_units, path->freespace_units); if (verbose >=3) printf("Freespace_units result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dfree_pct, path->freespace_percent); if (verbose >=3) printf("Freespace%% result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dused_units, path->usedspace_units); if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dused_pct, path->usedspace_percent); if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent); if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent); if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); result = max_state(result, disk_result); /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf data. Assumption that start=0. Roll on new syntax... */ /* *_high_tide must be reinitialized at each run */ warning_high_tide = UINT_MAX; critical_high_tide = UINT_MAX; if (path->freespace_units->warning != NULL) { warning_high_tide = path->dtotal_units - path->freespace_units->warning->end; } if (path->freespace_percent->warning != NULL) { warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)*path->dtotal_units )); } if (path->freespace_units->critical != NULL) { critical_high_tide = path->dtotal_units - path->freespace_units->critical->end; } if (path->freespace_percent->critical != NULL) { critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*path->dtotal_units )); } /* Nb: *_high_tide are unset when == UINT_MAX */ xasprintf (&perf, "%s %s", perf, perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dused_units, units, (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide, (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide, TRUE, 0, TRUE, path->dtotal_units)); if (disk_result==STATE_OK && erronly && !verbose) continue; xasprintf (&output, "%s %s %.0f %s (%.0f%%", output, (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dfree_units, units, path->dfree_pct); /* Whether or not to put all disks on new line */ if (newlines) { if (path->dused_inodes_percent < 0) { xasprintf(&output, "%s inode=-);\n", output); } else { xasprintf(&output, "%s inode=%.0f%%);\n", output, path->dfree_inodes_percent ); } } else { if (path->dused_inodes_percent < 0) { xasprintf(&output, "%s inode=-);", output); } else { xasprintf(&output, "%s inode=%.0f%%);", output, path->dfree_inodes_percent ); } } /* TODO: Need to do a similar debug line xasprintf (&details, _("%s\n\ %.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"), details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct, me->me_devname, me->me_type, me->me_mountdir, (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp); */ } } if (verbose >= 2) xasprintf (&output, "%s%s", output, details); if (newlines) { printf ("DISK %s%s\n%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf); } else { printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf); } return result; }
int main (int argc, char **argv) { int found = 0, result = STATE_UNKNOWN; char *buf, *sub; char **command_line; output chld_out, chld_err; int i; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); timeout_interval = DEFAULT_TIMEOUT; command_line = (char **) process_arguments (argc, argv); /* Set signal handling and alarm */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) die (STATE_UNKNOWN, _("Cannot catch SIGALRM")); (void) alarm ((unsigned) timeout_interval); /* catch when the command is quoted */ if(command_line[1] == NULL) { result = cmd_run (command_line[0], &chld_out, &chld_err, 0); } else { result = cmd_run_array (command_line, &chld_out, &chld_err, 0); } if (chld_err.lines > 0) { printf ("Error output from command:\n"); for (i = 0; i < chld_err.lines; i++) { printf ("%s\n", chld_err.line[i]); } exit (STATE_WARNING); } /* Return UNKNOWN or worse if no output is returned */ if (chld_out.lines == 0) die (max_state_alt (result, STATE_UNKNOWN), _("No data returned from command\n")); for (i = 0; i < chld_out.lines; i++) { if (subst_text && result != state[result] && result >= 0 && result <= 4) { /* Loop over each match found */ while ((sub = strstr (chld_out.line[i], state_text (result)))) { /* Terminate the first part and skip over the string we'll substitute */ *sub = '\0'; sub += strlen (state_text (result)); /* then put everything back together */ xasprintf (&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text (state[result]), sub); } } printf ("%s\n", chld_out.line[i]); } if (result >= 0 && result <= 4) { exit (state[result]); } else { exit (result); } }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; int i; char *status = NULL; struct timeval tv; size_t len; int match = -1; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* determine program- and service-name quickly */ progname = strrchr(argv[0], '/'); if(progname != NULL) progname++; else progname = argv[0]; len = strlen(progname); if(len > 6 && !memcmp(progname, "check_", 6)) { SERVICE = strdup(progname + 6); for(i = 0; i < len - 6; i++) SERVICE[i] = toupper(SERVICE[i]); } /* set up a resonable buffer at first (will be realloc()'ed if * user specifies other options) */ server_expect = calloc(sizeof(char *), 2); /* determine defaults for this service's protocol */ if (!strncmp(SERVICE, "UDP", 3)) { PROTOCOL = IPPROTO_UDP; } else if (!strncmp(SERVICE, "FTP", 3)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 21; } else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; PORT = 110; } else if (!strncmp(SERVICE, "SMTP", 4)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 25; } else if (!strncmp(SERVICE, "IMAP", 4)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; PORT = 143; } #ifdef HAVE_SSL else if (!strncmp(SERVICE, "SIMAP", 5)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; flags |= FLAG_SSL; PORT = 993; } else if (!strncmp(SERVICE, "SPOP", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 995; } else if (!strncmp(SERVICE, "SSMTP", 5)) { EXPECT = "220"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 465; } else if (!strncmp(SERVICE, "JABBER", 6)) { SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n"; EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'"; QUIT = "</stream:stream>\n"; flags |= FLAG_HIDE_OUTPUT; PORT = 5222; } else if (!strncmp (SERVICE, "NNTPS", 5)) { server_expect_count = 2; server_expect[0] = "200"; server_expect[1] = "201"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 563; } #endif else if (!strncmp (SERVICE, "NNTP", 4)) { server_expect_count = 2; server_expect = malloc(sizeof(char *) * server_expect_count); server_expect[0] = strdup("200"); server_expect[1] = strdup("201"); QUIT = "QUIT\r\n"; PORT = 119; } else if (!strncmp(SERVICE, "CLAMD", 5)) { SEND = "PING"; EXPECT = "PONG"; QUIT = NULL; PORT = 3310; } /* fallthrough check, so it's supposed to use reverse matching */ else if (strcmp (SERVICE, "TCP")) usage (_("CRITICAL - Generic check_tcp called with unknown service\n")); server_address = "127.0.0.1"; server_port = PORT; server_send = SEND; server_quit = QUIT; status = NULL; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if(flags & FLAG_VERBOSE) { printf("Using service %s\n", SERVICE); printf("Port: %d\n", server_port); printf("flags: 0x%x\n", (int)flags); } if(EXPECT && !server_expect_count) server_expect_count++; if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){ usage(_("With UDP checks, a send/expect string must be specified.")); } /* set up the timer */ signal (SIGALRM, socket_timeout_alarm_handler); alarm (socket_timeout); /* try to connect to the host at the given port number */ gettimeofday (&tv, NULL); result = np_net_connect (server_address, server_port, &sd, PROTOCOL); if (result == STATE_CRITICAL) return STATE_CRITICAL; #ifdef HAVE_SSL if (flags & FLAG_SSL){ result = np_net_ssl_init(sd); if (result == STATE_OK && check_cert == TRUE) { result = np_net_ssl_check_cert(days_till_exp); } } if(result != STATE_OK || check_cert == TRUE){ np_net_ssl_cleanup(); if(sd) close(sd); return result; } #endif /* HAVE_SSL */ if (server_send != NULL) { /* Something to send? */ my_send(server_send, strlen(server_send)); } if (delay > 0) { tv.tv_sec += delay; sleep (delay); } if(flags & FLAG_VERBOSE) { if (server_send) { printf("Send string: %s\n", server_send); } if (server_quit) { printf("Quit string: %s\n", server_quit); } printf("server_expect_count: %d\n", (int)server_expect_count); for(i = 0; i < server_expect_count; i++) printf("\t%d: %s\n", i, server_expect[i]); } /* if(len) later on, we know we have a non-NULL response */ len = 0; if (server_expect_count) { /* watch for the expect string */ while ((i = my_recv(buffer, sizeof(buffer))) > 0) { status = realloc(status, len + i + 1); memcpy(&status[len], buffer, i); len += i; /* stop reading if user-forced or data-starved */ if(i < sizeof(buffer) || (maxbytes && len >= maxbytes)) break; if (maxbytes && len >= maxbytes) break; } /* no data when expected, so return critical */ if (len == 0) die (STATE_CRITICAL, _("No data received from host\n")); /* force null-termination and strip whitespace from end of output */ status[len--] = '\0'; /* print raw output if we're debugging */ if(flags & FLAG_VERBOSE) printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); while(isspace(status[len])) status[len--] = '\0'; match = np_expect_match(status, server_expect, server_expect_count, (flags & FLAG_MATCH_ALL ? TRUE : FALSE), (flags & FLAG_EXACT_MATCH ? TRUE : FALSE), (flags & FLAG_VERBOSE ? TRUE : FALSE)); } if (server_quit != NULL) { my_send(server_quit, strlen(server_quit)); } #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif if (sd) close (sd); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time) result = STATE_CRITICAL; else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time) result = STATE_WARNING; /* did we get the response we hoped? */ if(match == FALSE && result != STATE_CRITICAL) result = expect_mismatch_state; /* reset the alarm */ alarm (0); /* this is a bit stupid, because we don't want to print the * response time (which can look ok to the user) if we didn't get * the response we were looking for. if-else */ printf("%s %s - ", SERVICE, state_text(result)); if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT)) printf("Unexpected response from host/socket: %s", status); else { if(match == FALSE) printf("Unexpected response from host/socket on "); else printf("%.3f second response time on ", elapsed_time); if(server_address[0] != '/') printf("port %d", server_port); else printf("socket %s", server_address); } if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len) printf (" [%s]", status); /* perf-data doesn't apply when server doesn't talk properly, * so print all zeroes on warn and crit. Use fperfdata since * localisation settings can make different outputs */ if(match == FALSE) printf ("|%s", fperfdata ("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? TRUE : FALSE), 0, (flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0, TRUE, 0, TRUE, socket_timeout) ); else printf("|%s", fperfdata ("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time, (flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time, TRUE, 0, TRUE, socket_timeout) ); putchar('\n'); return result; }
int main (int argc, char **argv) { int sd; int result = STATE_UNKNOWN; char buffer[MAX_INPUT_BUFFER]; char *status_line = NULL; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (socket_timeout); time (&start_time); /* try to connect to the host at the given port number */ if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK) die (STATE_CRITICAL, _("Unable to connect to %s on port %d\n"), server_address, server_port); /* Part I - Server Check */ /* send the OPTIONS request */ sprintf (buffer, "OPTIONS rtsp://%s:%d RTSP/1.0\r\n", host_name, server_port); result = send (sd, buffer, strlen (buffer), 0); /* send the header sync */ sprintf (buffer, "CSeq: 1\r\n"); result = send (sd, buffer, strlen (buffer), 0); /* send a newline so the server knows we're done with the request */ sprintf (buffer, "\r\n"); result = send (sd, buffer, strlen (buffer), 0); /* watch for the REAL connection string */ result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0); /* return a CRITICAL status if we couldn't read any data */ if (result == -1) die (STATE_CRITICAL, _("No data received from %s\n"), host_name); /* make sure we find the response we are looking for */ if (!strstr (buffer, server_expect)) { if (server_port == PORT) printf ("%s\n", _("Invalid REAL response received from host")); else printf (_("Invalid REAL response received from host on port %d\n"), server_port); } else { /* else we got the REAL string, so check the return code */ time (&end_time); result = STATE_OK; status_line = (char *) strtok (buffer, "\n"); if (strstr (status_line, "200")) result = STATE_OK; /* client errors result in a warning state */ else if (strstr (status_line, "400")) result = STATE_WARNING; else if (strstr (status_line, "401")) result = STATE_WARNING; else if (strstr (status_line, "402")) result = STATE_WARNING; else if (strstr (status_line, "403")) result = STATE_WARNING; else if (strstr (status_line, "404")) result = STATE_WARNING; /* server errors result in a critical state */ else if (strstr (status_line, "500")) result = STATE_CRITICAL; else if (strstr (status_line, "501")) result = STATE_CRITICAL; else if (strstr (status_line, "502")) result = STATE_CRITICAL; else if (strstr (status_line, "503")) result = STATE_CRITICAL; else result = STATE_UNKNOWN; } /* Part II - Check stream exists and is ok */ if ((result == STATE_OK )&& (server_url != NULL) ) { /* Part I - Server Check */ /* send the OPTIONS request */ sprintf (buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\n", host_name, server_port, server_url); result = send (sd, buffer, strlen (buffer), 0); /* send the header sync */ sprintf (buffer, "CSeq: 2\n"); result = send (sd, buffer, strlen (buffer), 0); /* send a newline so the server knows we're done with the request */ sprintf (buffer, "\n"); result = send (sd, buffer, strlen (buffer), 0); /* watch for the REAL connection string */ result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0); /* return a CRITICAL status if we couldn't read any data */ if (result == -1) { printf (_("No data received from host\n")); result = STATE_CRITICAL; } else { /* make sure we find the response we are looking for */ if (!strstr (buffer, server_expect)) { if (server_port == PORT) printf ("%s\n", _("Invalid REAL response received from host")); else printf (_("Invalid REAL response received from host on port %d\n"), server_port); } else { /* else we got the REAL string, so check the return code */ time (&end_time); result = STATE_OK; status_line = (char *) strtok (buffer, "\n"); if (strstr (status_line, "200")) result = STATE_OK; /* client errors result in a warning state */ else if (strstr (status_line, "400")) result = STATE_WARNING; else if (strstr (status_line, "401")) result = STATE_WARNING; else if (strstr (status_line, "402")) result = STATE_WARNING; else if (strstr (status_line, "403")) result = STATE_WARNING; else if (strstr (status_line, "404")) result = STATE_WARNING; /* server errors result in a critical state */ else if (strstr (status_line, "500")) result = STATE_CRITICAL; else if (strstr (status_line, "501")) result = STATE_CRITICAL; else if (strstr (status_line, "502")) result = STATE_CRITICAL; else if (strstr (status_line, "503")) result = STATE_CRITICAL; else result = STATE_UNKNOWN; } } } /* Return results */ if (result == STATE_OK) { if (check_critical_time == TRUE && (end_time - start_time) > critical_time) result = STATE_CRITICAL; else if (check_warning_time == TRUE && (end_time - start_time) > warning_time) result = STATE_WARNING; /* Put some HTML in here to create a dynamic link */ printf (_("REAL %s - %d second response time\n"), state_text (result), (int) (end_time - start_time)); } else printf ("%s\n", status_line); /* close the connection */ close (sd); /* reset the alarm */ alarm (0); return result; }
int main (int argc, char **argv) { int c, n_ports, n_online; bool verbose = false, summary = false; char *critical = NULL, *warning = NULL; nagstatus status = STATE_OK; thresholds *my_threshold = NULL; unsigned long delay, count; unsigned int sleep_time = 1; set_program_name (argv[0]); while ((c = getopt_long (argc, argv, "c:w:vi" GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1) { switch (c) { default: usage (stderr); case 'i': summary = true; break; case 'c': critical = optarg; break; case 'w': warning = optarg; break; case 'v': verbose = true; break; case_GETOPT_HELP_CHAR case_GETOPT_VERSION_CHAR } } if (summary) { fc_host_summary (verbose); return STATE_UNKNOWN; } delay = DELAY_DEFAULT, count = COUNT_DEFAULT; if (optind < argc) { delay = strtol_or_err (argv[optind++], "failed to parse argument"); if (delay < 1) plugin_error (STATE_UNKNOWN, 0, "delay must be positive integer"); else if (UINT_MAX < delay) plugin_error (STATE_UNKNOWN, 0, "too large delay value"); sleep_time = delay; } if (optind < argc) count = strtol_or_err (argv[optind++], "failed to parse argument"); status = set_thresholds (&my_threshold, warning, critical); if (status == NP_RANGE_UNPARSEABLE) usage (stderr); fc_host_statistics stats = {0}; fc_host_status (&n_ports, &n_online, &stats, sleep_time, count); status = get_status (n_online, my_threshold); printf ("%s %s - Fiber Channel ports status: %d/%d Online " "| rx_frames=%Lu tx_frames=%Lu" " error_frames=%Lu" " invalid_crc_count=%Lu" " link_failure_count=%Lu" " loss_of_signal_count=%Lu" " loss_of_sync_count=%Lu\n", program_name_short, state_text (status), n_online, n_ports, (unsigned long long) stats.rx_frames, (unsigned long long) stats.tx_frames, (unsigned long long) stats.error_frames, (unsigned long long) stats.invalid_crc_count, (unsigned long long) stats.link_failure_count, (unsigned long long) stats.loss_of_signal_count, (unsigned long long) stats.loss_of_sync_count ); return status; }
int main(int argc, char **argv){ char *ptr; int data_val; int return_code=STATE_OK; thresholds *thresholds = NULL; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts(&argc, argv, progname); if(process_arguments(argc,argv)==ERROR) usage(_("Could not parse arguments")); /* Initialize the thresholds */ set_thresholds(&thresholds, warn_threshold, crit_threshold); if(verbose) print_thresholds("check_cluster", thresholds); /* check the data values */ for(ptr=strtok(data_vals,",");ptr!=NULL;ptr=strtok(NULL,",")){ data_val=atoi(ptr); if(check_type==CHECK_SERVICES){ switch(data_val){ case 0: total_services_ok++; break; case 1: total_services_warning++; break; case 2: total_services_critical++; break; case 3: total_services_unknown++; break; default: break; } } else{ switch(data_val){ case 0: total_hosts_up++; break; case 1: total_hosts_down++; break; case 2: total_hosts_unreachable++; break; default: break; } } } /* return the status of the cluster */ if(check_type==CHECK_SERVICES){ return_code=get_status(total_services_warning+total_services_unknown+total_services_critical, thresholds); printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n", state_text(return_code), (label==NULL)?"Service cluster":label, total_services_ok,total_services_warning, total_services_unknown,total_services_critical); } else{ return_code=get_status(total_hosts_down+total_hosts_unreachable, thresholds); printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", state_text(return_code), (label==NULL)?"Host cluster":label, total_hosts_up,total_hosts_down,total_hosts_unreachable); } return return_code; }
/* * Processes an incoming "handle a new connection" item. This is called when * input arrives on the libevent wakeup pipe. */ static void thread_libevent_process(int fd, short which, void *arg) { LIBEVENT_THREAD *me = arg; assert(me->type == GENERAL); CQ_ITEM *item; if (recv(fd, devnull, sizeof(devnull), 0) == -1) { if (settings.verbose > 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "Can't read from libevent pipe: %s\n", strerror(errno)); } } if (memcached_shutdown) { event_base_loopbreak(me->base); return ; } while ((item = cq_pop(me->new_conn_queue)) != NULL) { conn *c = conn_new(item->sfd, item->parent_port, item->init_state, item->event_flags, item->read_buffer_size, item->transport, me->base, NULL); if (c == NULL) { if (IS_UDP(item->transport)) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "Can't listen for events on UDP socket\n"); exit(1); } else { if (settings.verbose > 0) { settings.extensions.logger->log(EXTENSION_LOG_INFO, NULL, "Can't listen for events on fd %d\n", item->sfd); } closesocket(item->sfd); } } else { assert(c->thread == NULL); c->thread = me; } cqi_free(item); } LOCK_THREAD(me); conn* pending = me->pending_io; me->pending_io = NULL; while (pending != NULL) { conn *c = pending; assert(me == c->thread); pending = pending->next; c->next = NULL; if (c->sfd != INVALID_SOCKET && !c->registered_in_libevent) { // The socket may have been shut down while we're looping // in delayed shutdown register_event(c, 0); } /* * We don't want the thread to keep on serving all of the data * from the context of the notification pipe, so just let it * run one time to set up the correct mask in libevent */ c->nevents = 1; do { if (settings.verbose) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, c, "%d - Running task: (%s)\n", c->sfd, state_text(c->state)); } } while (c->state(c)); } UNLOCK_THREAD(me); }
int main (int argc, char **argv) { bool show_swapping = false; int c, status, err; char *critical = NULL, *warning = NULL; char *status_msg; char *perfdata_paging_msg, *perfdata_swapping_msg = NULL; unsigned int i, tog = 0, sleep_time = 1; thresholds *my_threshold = NULL; struct proc_vmem *vmem = NULL; unsigned long dpgpgin, dpgpgout, dpgfault, dpgfree, dpgmajfault, dpgscand, dpgscank, dpgsteal; unsigned long nr_vmem_pgpgin[2], nr_vmem_pgpgout[2]; unsigned long nr_vmem_pgfault[2]; unsigned long nr_vmem_pgfree[2]; unsigned long nr_vmem_pgmajfault[2]; unsigned long nr_vmem_pgsteal[2]; unsigned long nr_vmem_pgscand[2]; unsigned long nr_vmem_pgscank[2]; unsigned long dpswpin, dpswpout; unsigned long nr_vmem_dpswpin[2], nr_vmem_dpswpout[2]; unsigned long *tracked_value = &dpgmajfault; set_program_name (argv[0]); while ((c = getopt_long (argc, argv, "psc:w:bkmg" GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1) { switch (c) { default: usage (stderr); case 'p': /* show_paging = true; */ break; case 's': show_swapping = true; break; case 'c': critical = optarg; break; case 'w': warning = optarg; break; case_GETOPT_HELP_CHAR case_GETOPT_VERSION_CHAR } } status = set_thresholds (&my_threshold, warning, critical); if (status == NP_RANGE_UNPARSEABLE) usage (stderr); err = proc_vmem_new (&vmem); if (err < 0) plugin_error (STATE_UNKNOWN, err, "memory exhausted"); for (i = 0; i < 2; i++) { proc_vmem_read (vmem); nr_vmem_pgpgin[tog] = proc_vmem_get_pgpgin (vmem); nr_vmem_pgpgout[tog] = proc_vmem_get_pgpgout (vmem); nr_vmem_pgfault[tog] = proc_vmem_get_pgfault (vmem); nr_vmem_pgmajfault[tog] = proc_vmem_get_pgmajfault (vmem); nr_vmem_pgfree[tog] = proc_vmem_get_pgfree (vmem); nr_vmem_pgsteal[tog] = proc_vmem_get_pgsteal (vmem); if (show_swapping) { nr_vmem_dpswpin[tog] = proc_vmem_get_pswpin (vmem); nr_vmem_dpswpout[tog] = proc_vmem_get_pswpout (vmem); } nr_vmem_pgscand[tog] = proc_vmem_get_pgscand (vmem); nr_vmem_pgscank[tog] = proc_vmem_get_pgscank (vmem); sleep (sleep_time); tog = !tog; } dpgpgin = nr_vmem_pgpgin[1] - nr_vmem_pgpgin[0]; dpgpgout = nr_vmem_pgpgout[1] - nr_vmem_pgpgout[0]; dpgfault = nr_vmem_pgfault[1] - nr_vmem_pgfault[0]; dpgmajfault = nr_vmem_pgmajfault[1] - nr_vmem_pgmajfault[0]; dpgfree = nr_vmem_pgfree[1] - nr_vmem_pgfree[0]; dpgsteal = nr_vmem_pgsteal[1] - nr_vmem_pgsteal[0]; dpgscand = nr_vmem_pgscand[1] - nr_vmem_pgscand[0]; dpgscank = nr_vmem_pgscank[1] - nr_vmem_pgscank[0]; if (show_swapping) { dpswpin = nr_vmem_dpswpin[1] - nr_vmem_dpswpin[0]; dpswpout = nr_vmem_dpswpout[1] - nr_vmem_dpswpout[0]; perfdata_swapping_msg = xasprintf (" vmem_pswpin/s=%lu vmem_pswpout/s=%lu", dpswpin, dpswpout); } proc_vmem_unref (vmem); status = get_status (*tracked_value, my_threshold); free (my_threshold); status_msg = xasprintf ("%s: %lu majfault/s", state_text (status), *tracked_value); perfdata_paging_msg = xasprintf ("vmem_pgpgin/s=%lu vmem_pgpgout/s=%lu vmem_pgfault/s=%lu " "vmem_pgmajfault/s=%lu vmem_pgfree/s=%lu vmem_pgsteal/s=%lu " "vmem_pgscand/s=%lu vmem_pgscank/s=%lu", dpgpgin, dpgpgout, dpgfault, dpgmajfault, dpgfree, dpgsteal, dpgscand, dpgscank); printf ("%s %s | %s%s\n", "PAGING", status_msg, perfdata_paging_msg, perfdata_swapping_msg ? perfdata_swapping_msg : ""); return status; }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; int disk_result = STATE_UNKNOWN; char *output; char *details; char *perf; char *preamble; double inode_space_pct; uintmax_t total, available, available_to_root, used; double dfree_pct = -1, dused_pct = -1; double dused_units, dfree_units, dtotal_units; double dused_inodes_percent, dfree_inodes_percent; double warning_high_tide; double critical_high_tide; int temp_result; struct mount_entry *me; struct fs_usage fsp, tmpfsp; struct parameter_list *temp_list, *path; struct name_list *seen = NULL; preamble = strdup (" - free space:"); output = strdup (""); details = strdup (""); perf = strdup (""); stat_buf = malloc(sizeof *stat_buf); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); mount_list = read_file_system_list (0); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If a list of paths has not been selected, find entire mount list and create list of paths */ if (path_selected == FALSE) { for (me = mount_list; me; me = me->me_next) { if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) { path = np_add_parameter(&path_select_list, me->me_mountdir); } path->best_match = me; path->group = group; set_all_thresholds(path); } } np_set_best_match(path_select_list, mount_list, exact_match); /* Error if no match found for specified paths */ temp_list = path_select_list; while (temp_list) { if (! temp_list->best_match) { die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name); } temp_list = temp_list->name_next; } /* Process for every path in list */ for (path = path_select_list; path; path=path->name_next) { if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) printf("Thresholds(pct) for %s warn: %f crit %f\n",path->name, path->freespace_percent->warning->end, path->freespace_percent->critical->end); if (verbose >= 3 && path->group != NULL) printf("Group of %s: %s\n",path->name,path->group); /* reset disk result */ disk_result = STATE_UNKNOWN; me = path->best_match; /* Filters */ /* Remove filesystems already seen */ if (np_seen_name(seen, me->me_mountdir)) { continue; } else { if (path->group != NULL) { /* find all group members */ fsp.fsu_blocksize = 0; fsp.fsu_blocks = 0; fsp.fsu_bfree = 0; fsp.fsu_bavail = 0; fsp.fsu_files = 0; fsp.fsu_ffree = 0; for (temp_list = path_select_list; temp_list; temp_list=temp_list->name_next) { if (temp_list->group && ! (strcmp(temp_list->group, path->group))) { stat_path(path); get_fs_usage (temp_list->best_match->me_mountdir, temp_list->best_match->me_devname, &tmpfsp); /* possibly differing blocksizes if disks are grouped. Calculating average */ fsp.fsu_blocksize = (fsp.fsu_blocksize * fsp.fsu_blocks + tmpfsp.fsu_blocksize * tmpfsp.fsu_blocks) / \ (fsp.fsu_blocks + tmpfsp.fsu_blocks); /* Size of a block. */ fsp.fsu_blocks += tmpfsp.fsu_blocks; /* Total blocks. */ fsp.fsu_bfree += tmpfsp.fsu_bfree; /* Free blocks available to superuser. */ /* Gnulib workaround - see comment about it a few lines below */ fsp.fsu_bavail += (tmpfsp.fsu_bavail > tmpfsp.fsu_bfree ? 0 : tmpfsp.fsu_bavail); /* Free blocks available to non-superuser. */ fsp.fsu_files += tmpfsp.fsu_files; /* Total file nodes. */ fsp.fsu_ffree += tmpfsp.fsu_ffree; /* Free file nodes. */ if (verbose >= 3) printf("Group %s: add %llu blocks (%s) \n", path->group, tmpfsp.fsu_bavail, temp_list->name); /* printf("Group %s: add %u blocks (%s)\n", temp_list->name); *//* path->group, tmpfsp.fsu_bavail, temp_list->name); */ np_add_name(&seen, temp_list->best_match->me_mountdir); } } /* modify devname and mountdir for output */ me->me_mountdir = me->me_devname = path->group; } else np_add_name(&seen, me->me_mountdir); } if (path->group == NULL) { /* Skip remote filesystems if we're not interested in them */ if (me->me_remote && show_local_fs) { if (stat_remote_fs) stat_path(path); continue; /* Skip pseudo fs's if we haven't asked for all fs's */ } else if (me->me_dummy && !show_all_fs) { continue; /* Skip excluded fstypes */ } else if (fs_exclude_list && np_find_name (fs_exclude_list, me->me_type)) { continue; /* Skip excluded fs's */ } else if (dp_exclude_list && (np_find_name (dp_exclude_list, me->me_devname) || np_find_name (dp_exclude_list, me->me_mountdir))) { continue; } stat_path(path); get_fs_usage (me->me_mountdir, me->me_devname, &fsp); } if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) { total = fsp.fsu_blocks; /* 2007-12-08 - Workaround for Gnulib reporting insanely high available * space on BSD (the actual value should be negative but fsp.fsu_bavail * is unsigned) */ available = fsp.fsu_bavail > fsp.fsu_bfree ? 0 : fsp.fsu_bavail; available_to_root = fsp.fsu_bfree; used = total - available_to_root; if (verbose >= 3) printf ("For %s, total=%llu, available=%llu, available_to_root=%llu, used=%llu, fsp.fsu_files=%llu, fsp.fsu_ffree=%llu\n", me->me_mountdir, total, available, available_to_root, used, fsp.fsu_files, fsp.fsu_ffree); dused_pct = calculate_percent( used, used + available ); /* used + available can never be > uintmax */ dfree_pct = 100 - dused_pct; dused_units = used*fsp.fsu_blocksize/mult; dfree_units = available*fsp.fsu_blocksize/mult; dtotal_units = total*fsp.fsu_blocksize/mult; dused_inodes_percent = calculate_percent(fsp.fsu_files - fsp.fsu_ffree, fsp.fsu_files); dfree_inodes_percent = 100 - dused_inodes_percent; if (verbose >= 3) { printf ("For %s, used_pct=%g free_pct=%g used_units=%g free_units=%g total_units=%g used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", me->me_mountdir, dused_pct, dfree_pct, dused_units, dfree_units, dtotal_units, dused_inodes_percent, dfree_inodes_percent, fsp.fsu_blocksize, mult); } /* Threshold comparisons */ temp_result = get_status(dfree_units, path->freespace_units); if (verbose >=3) printf("Freespace_units result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(dfree_pct, path->freespace_percent); if (verbose >=3) printf("Freespace%% result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(dused_units, path->usedspace_units); if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(dused_pct, path->usedspace_percent); if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(dused_inodes_percent, path->usedinodes_percent); if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(dfree_inodes_percent, path->freeinodes_percent); if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); result = max_state(result, disk_result); /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf data. Assumption that start=0. Roll on new syntax... */ /* *_high_tide must be reinitialized at each run */ warning_high_tide = UINT_MAX; critical_high_tide = UINT_MAX; if (path->freespace_units->warning != NULL) { warning_high_tide = dtotal_units - path->freespace_units->warning->end; } if (path->freespace_percent->warning != NULL) { warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)*dtotal_units )); } if (path->freespace_units->critical != NULL) { critical_high_tide = dtotal_units - path->freespace_units->critical->end; } if (path->freespace_percent->critical != NULL) { critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*dtotal_units )); } /* Nb: *_high_tide are unset when == UINT_MAX */ asprintf (&perf, "%s %s", perf, perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, dused_units, units, (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide, (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide, TRUE, 0, TRUE, dtotal_units)); if (disk_result==STATE_OK && erronly && !verbose) continue; asprintf (&output, "%s %s %.0f %s (%.0f%%", output, (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, dfree_units, units, dfree_pct); if (dused_inodes_percent < 0) { asprintf(&output, "%s inode=-);", output); } else { asprintf(&output, "%s inode=%.0f%%);", output, dfree_inodes_percent ); } /* TODO: Need to do a similar debug line asprintf (&details, _("%s\n\ %.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"), details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct, me->me_devname, me->me_type, me->me_mountdir, (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp); */ } } if (verbose >= 2) asprintf (&output, "%s%s", output, details); printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf); return result; }
int main (int argc, char **argv) { int sd; int result = STATE_UNKNOWN; time_t conntime; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (socket_timeout); time (&start_time); /* try to connect to the host at the given port number */ if (use_udp) { result = my_udp_connect (server_address, server_port, &sd); } else { result = my_tcp_connect (server_address, server_port, &sd); } if (result != STATE_OK) { if (check_critical_time == TRUE) result = STATE_CRITICAL; else if (check_warning_time == TRUE) result = STATE_WARNING; else result = STATE_UNKNOWN; die (result, _("TIME UNKNOWN - could not connect to server %s, port %d\n"), server_address, server_port); } if (use_udp) { if (send (sd, "", 0, 0) < 0) { if (check_critical_time == TRUE) result = STATE_CRITICAL; else if (check_warning_time == TRUE) result = STATE_WARNING; else result = STATE_UNKNOWN; die (result, _("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"), server_address, server_port); } } /* watch for the connection string */ result = recv (sd, (void *)&raw_server_time, sizeof (raw_server_time), 0); /* close the connection */ close (sd); /* reset the alarm */ time (&end_time); alarm (0); /* return a WARNING status if we couldn't read any data */ if (result <= 0) { if (check_critical_time == TRUE) result = STATE_CRITICAL; else if (check_warning_time == TRUE) result = STATE_WARNING; else result = STATE_UNKNOWN; die (result, _("TIME UNKNOWN - no data received from server %s, port %d\n"), server_address, server_port); } result = STATE_OK; conntime = (end_time - start_time); if (check_critical_time == TRUE && conntime > critical_time) result = STATE_CRITICAL; else if (check_warning_time == TRUE && conntime > warning_time) result = STATE_WARNING; if (result != STATE_OK) die (result, _("TIME %s - %d second response time|%s\n"), state_text (result), (int)conntime, perfdata ("time", (long)conntime, "s", check_warning_time, (long)warning_time, check_critical_time, (long)critical_time, TRUE, 0, FALSE, 0)); server_time = ntohl (raw_server_time) - UNIX_EPOCH; if (server_time > (unsigned long)end_time) diff_time = server_time - (unsigned long)end_time; else diff_time = (unsigned long)end_time - server_time; if (check_critical_diff == TRUE && diff_time > critical_diff) result = STATE_CRITICAL; else if (check_warning_diff == TRUE && diff_time > warning_diff) result = STATE_WARNING; printf (_("TIME %s - %lu second time difference|%s %s\n"), state_text (result), diff_time, perfdata ("time", (long)conntime, "s", check_warning_time, (long)warning_time, check_critical_time, (long)critical_time, TRUE, 0, FALSE, 0), perfdata ("offset", diff_time, "s", check_warning_diff, warning_diff, check_critical_diff, critical_diff, TRUE, 0, FALSE, 0)); return result; }
/* process command-line arguments */ static int process_arguments (int argc, char **argv) { int c; int escape = 0; int option = 0; static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"critical-codes", required_argument, 0, 'C'}, {"warning-codes", required_argument, 0, 'W'}, {"timeout", required_argument, 0, 't'}, {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */ {"port", required_argument, 0, 'p'}, {"escape", no_argument, 0, 'E'}, {"all", no_argument, 0, 'A'}, {"send", required_argument, 0, 's'}, {"expect", required_argument, 0, 'e'}, {"maxbytes", required_argument, 0, 'm'}, {"quit", required_argument, 0, 'q'}, {"jail", no_argument, 0, 'j'}, {"delay", required_argument, 0, 'd'}, {"refuse", required_argument, 0, 'r'}, {"mismatch", required_argument, 0, 'M'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"ssl", no_argument, 0, 'S'}, {"certificate", required_argument, 0, 'D'}, {0, 0, 0, 0} }; if (argc < 2) usage4 (_("No arguments found")); /* backwards compatibility */ for (c = 1; c < argc; c++) { if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); else if (strcmp ("-wt", argv[c]) == 0) strcpy (argv[c], "-w"); else if (strcmp ("-ct", argv[c]) == 0) strcpy (argv[c], "-c"); } if (!is_option (argv[1])) { server_address = argv[1]; argv[1] = argv[0]; argv = &argv[1]; argc--; } while (1) { c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'v': /* verbose mode */ flags |= FLAG_VERBOSE; break; case '4': address_family = AF_INET; break; case '6': #ifdef USE_IPV6 address_family = AF_INET6; #else usage4 (_("IPv6 support not available")); #endif break; case 'H': /* hostname */ server_address = optarg; break; case 'c': /* critical */ critical_time = strtod (optarg, NULL); flags |= FLAG_TIME_CRIT; break; case 'j': /* hide output */ flags |= FLAG_HIDE_OUTPUT; break; case 'w': /* warning */ warning_time = strtod (optarg, NULL); flags |= FLAG_TIME_WARN; break; case 'C': crit_codes = realloc (crit_codes, ++crit_codes_count); crit_codes[crit_codes_count - 1] = optarg; break; case 'W': warn_codes = realloc (warn_codes, ++warn_codes_count); warn_codes[warn_codes_count - 1] = optarg; break; case 't': /* timeout */ if (!is_intpos (optarg)) usage4 (_("Timeout interval must be a positive integer")); else socket_timeout = atoi (optarg); break; case 'p': /* port */ if (!is_intpos (optarg)) usage4 (_("Port must be a positive integer")); else server_port = atoi (optarg); break; case 'E': escape = 1; break; case 's': if (escape) server_send = np_escaped_string(optarg); else asprintf(&server_send, "%s", optarg); break; case 'e': /* expect string (may be repeated) */ flags &= ~FLAG_EXACT_MATCH; if (server_expect_count == 0) server_expect = malloc (sizeof (char *) * (++server_expect_count)); else server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count)); server_expect[server_expect_count - 1] = optarg; break; case 'm': if (!is_intpos (optarg)) usage4 (_("Maxbytes must be a positive integer")); else maxbytes = strtol (optarg, NULL, 0); break; case 'q': if (escape) server_quit = np_escaped_string(optarg); else asprintf(&server_quit, "%s\r\n", optarg); break; case 'r': if (!strncmp(optarg,"ok",2)) econn_refuse_state = STATE_OK; else if (!strncmp(optarg,"warn",4)) econn_refuse_state = STATE_WARNING; else if (!strncmp(optarg,"crit",4)) econn_refuse_state = STATE_CRITICAL; else usage4 (_("Refuse must be one of ok, warn, crit")); break; case 'M': if (!strncmp(optarg,"ok",2)) expect_mismatch_state = STATE_OK; else if (!strncmp(optarg,"warn",4)) expect_mismatch_state = STATE_WARNING; else if (!strncmp(optarg,"crit",4)) expect_mismatch_state = STATE_CRITICAL; else usage4 (_("Mismatch must be one of ok, warn, crit")); break; case 'd': if (is_intpos (optarg)) delay = atoi (optarg); else usage4 (_("Delay must be a positive integer")); break; case 'D': /* Check SSL cert validity - days 'til certificate expiration */ #ifdef HAVE_SSL # ifdef USE_OPENSSL /* XXX */ if (!is_intnonneg (optarg)) usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp = atoi (optarg); check_cert = TRUE; flags |= FLAG_SSL; break; # endif /* USE_OPENSSL */ #endif /* fallthrough if we don't have ssl */ case 'S': #ifdef HAVE_SSL flags |= FLAG_SSL; #else die (STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case 'A': flags |= FLAG_MATCH_ALL; break; } } if (server_address == NULL) usage4 (_("You must provide a server address")); else if (server_address[0] != '/' && is_host (server_address) == FALSE) die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address); return TRUE; }
void peer_update_callback(enum crm_status_type type, crm_node_t * node, const void *data) { uint32_t old = 0; uint32_t changed = 0; bool appeared = FALSE; bool is_remote = is_set(node->flags, crm_remote_node); const char *status = NULL; /* Crmd waits to receive some information from the membership layer before * declaring itself operational. If this is being called for a cluster node, * indicate that we have it. */ if (!is_remote) { set_bit(fsa_input_register, R_PEER_DATA); } if (node->uname == NULL) { return; } switch (type) { case crm_status_uname: /* If we've never seen the node, then it also won't be in the status section */ crm_info("%s node %s is now %s", (is_remote? "Remote" : "Cluster"), node->uname, state_text(node->state)); return; case crm_status_rstate: case crm_status_nstate: /* This callback should not be called unless the state actually * changed, but here's a failsafe just in case. */ CRM_CHECK(safe_str_neq(data, node->state), return); crm_info("%s node %s is now %s (was %s)", (is_remote? "Remote" : "Cluster"), node->uname, state_text(node->state), state_text(data)); if (safe_str_eq(CRM_NODE_MEMBER, node->state)) { appeared = TRUE; if (!is_remote) { remove_stonith_cleanup(node->uname); } } crmd_alert_node_event(node); break; case crm_status_processes: if (data) { old = *(const uint32_t *)data; changed = node->processes ^ old; } status = (node->processes & proc_flags) ? ONLINESTATUS : OFFLINESTATUS; crm_info("Client %s/%s now has status [%s] (DC=%s, changed=%6x)", node->uname, peer2text(proc_flags), status, AM_I_DC ? "true" : crm_str(fsa_our_dc), changed); if ((changed & proc_flags) == 0) { /* Peer process did not change */ crm_trace("No change %6x %6x %6x", old, node->processes, proc_flags); return; } else if (is_not_set(fsa_input_register, R_CIB_CONNECTED)) { crm_trace("Not connected"); return; } else if (fsa_state == S_STOPPING) { crm_trace("Stopping"); return; } appeared = (node->processes & proc_flags) != 0; if (safe_str_eq(node->uname, fsa_our_uname) && (node->processes & proc_flags) == 0) { /* Did we get evicted? */ crm_notice("Our peer connection failed"); register_fsa_input(C_CRMD_STATUS_CALLBACK, I_ERROR, NULL); } else if (safe_str_eq(node->uname, fsa_our_dc) && crm_is_peer_active(node) == FALSE) { /* Did the DC leave us? */ crm_notice("Our peer on the DC (%s) is dead", fsa_our_dc); register_fsa_input(C_CRMD_STATUS_CALLBACK, I_ELECTION, NULL); /* @COMPAT DC < 1.1.13: If a DC shuts down normally, we don't * want to fence it. Newer DCs will send their shutdown request * to all peers, who will update the DC's expected state to * down, thus avoiding fencing. We can safely erase the DC's * transient attributes when it leaves in that case. However, * the only way to avoid fencing older DCs is to leave the * transient attributes intact until it rejoins. */ if (compare_version(fsa_our_dc_version, "3.0.9") > 0) { erase_status_tag(node->uname, XML_TAG_TRANSIENT_NODEATTRS, cib_scope_local); } } else if(AM_I_DC && appeared == FALSE) { crm_info("Peer %s left us", node->uname); erase_status_tag(node->uname, XML_TAG_TRANSIENT_NODEATTRS, cib_scope_local); } break; } if (AM_I_DC) { xmlNode *update = NULL; int flags = node_update_peer; gboolean alive = is_remote? appeared : crm_is_peer_active(node); crm_action_t *down = match_down_event(node->uuid, appeared); crm_trace("Alive=%d, appeared=%d, down=%d", alive, appeared, (down? down->id : -1)); if (alive && type == crm_status_processes) { register_fsa_input_before(C_FSA_INTERNAL, I_NODE_JOIN, NULL); } if (down) { const char *task = crm_element_value(down->xml, XML_LRM_ATTR_TASK); if (safe_str_eq(task, CRM_OP_FENCE)) { /* tengine_stonith_callback() confirms fence actions */ crm_trace("Updating CIB %s stonithd reported fencing of %s complete", (down->confirmed? "after" : "before"), node->uname); } else if ((alive == FALSE) && safe_str_eq(task, CRM_OP_SHUTDOWN)) { crm_notice("%s of peer %s is complete "CRM_XS" op=%d", task, node->uname, down->id); /* down->confirmed = TRUE; */ stop_te_timer(down->timer); if (!is_remote) { flags |= node_update_join | node_update_expected; crmd_peer_down(node, FALSE); check_join_state(fsa_state, __FUNCTION__); } update_graph(transition_graph, down); trigger_graph(); } else { crm_trace("Node %s is %salive, was expected to %s (op %d)", node->uname, (alive? "" : "not "), task, down->id); } } else if (appeared == FALSE) { crm_notice("Stonith/shutdown of %s not matched", node->uname); if (!is_remote) { crm_update_peer_join(__FUNCTION__, node, crm_join_none); check_join_state(fsa_state, __FUNCTION__); } abort_transition(INFINITY, tg_restart, "Node failure", NULL); fail_incompletable_actions(transition_graph, node->uuid); } else { crm_trace("Node %s came up, was not expected to be down", node->uname); } if (is_remote) { /* A pacemaker_remote node won't have its cluster status updated * in the CIB by membership-layer callbacks, so do it here. */ flags |= node_update_cluster; /* Trigger resource placement on newly integrated nodes */ if (appeared) { abort_transition(INFINITY, tg_restart, "pacemaker_remote node integrated", NULL); } } /* Update the CIB node state */ update = create_node_state_update(node, flags, NULL, __FUNCTION__); fsa_cib_anon_update(XML_CIB_TAG_STATUS, update, cib_scope_local | cib_quorum_override | cib_can_create); free_xml(update); } trigger_fsa(fsa_source); }
int main (int argc, char **argv) { char *status_text; int cresult; int result = STATE_UNKNOWN; int i; time_t local_time; FILE *fp = NULL; output chld_out, chld_err; remotecmd = ""; comm_append(SSH_COMMAND); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); /* process arguments */ if (process_arguments (argc, argv) == ERROR) usage_va(_("Could not parse arguments")); /* Set signal handling and alarm timeout */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage_va(_("Cannot catch SIGALRM")); } alarm (timeout_interval); /* run the command */ if (verbose) { printf ("Command: %s\n", commargv[0]); for (i=1; i<commargc; i++) printf ("Argument %i: %s\n", i, commargv[i]); } result = cmd_run_array (commargv, &chld_out, &chld_err, 0); if (skip_stdout == -1) /* --skip-stdout specified without argument */ skip_stdout = chld_out.lines; if (skip_stderr == -1) /* --skip-stderr specified without argument */ skip_stderr = chld_err.lines; /* UNKNOWN or worse if (non-skipped) output found on stderr */ if(chld_err.lines > skip_stderr) { printf (_("Remote command execution failed: %s\n"), chld_err.line[skip_stderr]); return max_state_alt(result, STATE_UNKNOWN); } /* this is simple if we're not supposed to be passive. * Wrap up quickly and keep the tricks below */ if(!passive) { if (chld_out.lines > skip_stdout) for (i = skip_stdout; i < chld_out.lines; i++) puts (chld_out.line[i]); else printf (_("%s - check_by_ssh: Remote command '%s' returned status %d\n"), state_text(result), remotecmd, result); return result; /* return error status from remote command */ } /* * Passive mode */ /* process output */ if (!(fp = fopen (outputfile, "a"))) { printf (_("SSH WARNING: could not open %s\n"), outputfile); exit (STATE_UNKNOWN); } local_time = time (NULL); commands = 0; for(i = skip_stdout; i < chld_out.lines; i++) { status_text = chld_out.line[i++]; if (i == chld_out.lines || strstr (chld_out.line[i], "STATUS CODE: ") == NULL) die (STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); if (service[commands] && status_text && sscanf (chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) { fprintf (fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int) local_time, host_shortname, service[commands++], cresult, status_text); } } /* Multiple commands and passive checking should always return OK */ return result; }
int main (int argc, char **argv) { int users = -1; int result = STATE_UNKNOWN; char *perf; #if HAVE_WTSAPI32_H WTS_SESSION_INFO *wtsinfo; DWORD wtscount; DWORD index; #elif HAVE_UTMPX_H struct utmpx *putmpx; #else char input_buffer[MAX_INPUT_BUFFER]; #endif setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); perf = strdup (""); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); users = 0; #if HAVE_WTSAPI32_H if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) { printf(_("Could not enumerate RD sessions: %d\n"), GetLastError()); return STATE_UNKNOWN; } for (index = 0; index < wtscount; index++) { LPTSTR username; DWORD size; int len; if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size)) continue; len = lstrlen(username); WTSFreeMemory(username); if (len == 0) continue; if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected) users++; } WTSFreeMemory(wtsinfo); #elif HAVE_UTMPX_H /* get currently logged users from utmpx */ setutxent (); while ((putmpx = getutxent ()) != NULL) if (putmpx->ut_type == USER_PROCESS) users++; endutxent (); #else /* run the command */ child_process = spopen (WHO_COMMAND); if (child_process == NULL) { printf (_("Could not open pipe: %s\n"), WHO_COMMAND); return STATE_UNKNOWN; } child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); if (child_stderr == NULL) printf (_("Could not open stderr for %s\n"), WHO_COMMAND); while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { /* increment 'users' on all lines except total user count */ if (input_buffer[0] != '#') { users++; continue; } /* get total logged in users */ if (sscanf (input_buffer, _("# users=%d"), &users) == 1) break; } /* check STDERR */ if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) result = possibly_set (result, STATE_UNKNOWN); (void) fclose (child_stderr); /* close the pipe */ if (spclose (child_process)) result = possibly_set (result, STATE_UNKNOWN); #endif /* check the user count against warning and critical thresholds */ if (users > cusers) result = STATE_CRITICAL; else if (users > wusers) result = STATE_WARNING; else if (users >= 0) result = STATE_OK; if (result == STATE_UNKNOWN) printf ("%s\n", _("Unable to read output")); else { xasprintf (&perf, "%s", perfdata ("users", users, "", TRUE, wusers, TRUE, cusers, TRUE, 0, FALSE, 0)); printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result), users, perf); } return result; }
int main (int argc, char *argv[]) { LDAP *ld; LDAPMessage *result; /* should be int result = STATE_UNKNOWN; */ int status = STATE_UNKNOWN; long microsec; double elapsed_time; /* for ldap tls */ int tls; int version=3; /* for entry counting */ LDAPMessage *next_entry; int status_entries = STATE_OK; int num_entries = 0; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (strstr(argv[0],"check_ldaps")) { xasprintf (&progname, "check_ldaps"); } /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if (strstr(argv[0],"check_ldaps") && ! starttls && ! ssl_on_connect) starttls = TRUE; /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (timeout_interval); /* get the start time */ gettimeofday (&tv, NULL); /* initialize ldap */ if (ld_uri != NULL) { #ifdef HAVE_LDAP_INITIALIZE int result = ldap_initialize(&ld, ld_uri); if (result != LDAP_SUCCESS) { printf ("Failed to connect to LDAP server at %s: %s\n", ld_uri, ldap_err2string(result)); return STATE_CRITICAL; } #else printf ("Sorry, this version of %s was compiled without URI support!\n", argv[0]); return STATE_CRITICAL; #endif } #ifdef HAVE_LDAP_INIT else if (!(ld = ldap_init (ld_host, ld_port))) { printf ("Could not connect to the server at port %i\n", ld_port); return STATE_CRITICAL; } #else else if (!(ld = ldap_open (ld_host, ld_port))) { if (verbose) ldap_perror(ld, "ldap_open"); printf (_("Could not connect to the server at port %i\n"), ld_port); return STATE_CRITICAL; } #endif /* HAVE_LDAP_INIT */ #ifdef HAVE_LDAP_SET_OPTION /* set ldap options */ if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ld_protocol) != LDAP_OPT_SUCCESS ) { printf(_("Could not set protocol version %d\n"), ld_protocol); return STATE_CRITICAL; } #endif if (ld_port == LDAPS_PORT || ssl_on_connect) { xasprintf (&SERVICE, "LDAPS"); #if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS) /* ldaps: set option tls */ tls = LDAP_OPT_X_TLS_HARD; if (ldap_set_option (ld, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldaps_option"); printf (_("Could not init TLS at port %i!\n"), ld_port); return STATE_CRITICAL; } #else printf (_("TLS not supported by the libraries!\n")); return STATE_CRITICAL; #endif /* LDAP_OPT_X_TLS */ } else if (starttls) { xasprintf (&SERVICE, "LDAP-TLS"); #if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S) /* ldap with startTLS: set option version */ if (ldap_get_option(ld,LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS ) { if (version < LDAP_VERSION3) { version = LDAP_VERSION3; ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version); } } /* call start_tls */ if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_start_tls"); printf (_("Could not init startTLS at port %i!\n"), ld_port); return STATE_CRITICAL; } #else printf (_("startTLS not supported by the library, needs LDAPv3!\n")); return STATE_CRITICAL; #endif /* HAVE_LDAP_START_TLS_S */ } /* bind to the ldap server */ if (ldap_bind_s (ld, ld_binddn, ld_passwd, LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_bind"); printf (_("Could not bind to the LDAP server\n")); return STATE_CRITICAL; } /* do a search of all objectclasses in the base dn */ if (ldap_search_s (ld, ld_base, (crit_entries!=NULL || warn_entries!=NULL) ? LDAP_SCOPE_SUBTREE : LDAP_SCOPE_BASE, ld_attr, NULL, 0, &result) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_search"); printf (_("Could not search/find objectclasses in %s\n"), ld_base); return STATE_CRITICAL; } else if (crit_entries!=NULL || warn_entries!=NULL) { num_entries = ldap_count_entries(ld, result); } /* unbind from the ldap server */ ldap_unbind (ld); /* reset the alarm handler */ alarm (0); /* calcutate the elapsed time and compare to thresholds */ microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (crit_time!=UNDEFINED && elapsed_time>crit_time) status = STATE_CRITICAL; else if (warn_time!=UNDEFINED && elapsed_time>warn_time) status = STATE_WARNING; else status = STATE_OK; if(entries_thresholds != NULL) { if (verbose) { printf ("entries found: %d\n", num_entries); print_thresholds("entry threasholds", entries_thresholds); } status_entries = get_status(num_entries, entries_thresholds); if (status_entries == STATE_CRITICAL) { status = STATE_CRITICAL; } else if (status != STATE_CRITICAL) { status = status_entries; } } /* print out the result */ if (crit_entries!=NULL || warn_entries!=NULL) { printf (_("LDAP %s - found %d entries in %.3f seconds|%s %s\n"), state_text (status), num_entries, elapsed_time, fperfdata ("time", elapsed_time, "s", (int)warn_time, warn_time, (int)crit_time, crit_time, TRUE, 0, FALSE, 0), sperfdata ("entries", (double)num_entries, "", warn_entries, crit_entries, TRUE, 0.0, FALSE, 0.0)); } else { printf (_("LDAP %s - %.3f seconds response time|%s\n"), state_text (status), elapsed_time, fperfdata ("time", elapsed_time, "s", (int)warn_time, warn_time, (int)crit_time, crit_time, TRUE, 0, FALSE, 0)); } return status; }
int main (int argc, char **argv) { /* normaly should be int result = STATE_UNKNOWN; */ int status = STATE_UNKNOWN; int result = 0; char *fping_prog = NULL; char *server = NULL; char *command_line = NULL; char *input_buffer = NULL; char *option_string = ""; input_buffer = malloc (MAX_INPUT_BUFFER); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); server = strscpy (server, server_name); /* compose the command */ if (target_timeout) xasprintf(&option_string, "%s-t %d ", option_string, target_timeout); if (packet_interval) xasprintf(&option_string, "%s-p %d ", option_string, packet_interval); if (sourceip) xasprintf(&option_string, "%s-S %s ", option_string, sourceip); if (sourceif) xasprintf(&option_string, "%s-I %s ", option_string, sourceif); #ifdef PATH_TO_FPING6 if (address_family == AF_INET6) fping_prog = strdup(PATH_TO_FPING6); else fping_prog = strdup(PATH_TO_FPING); #else fping_prog = strdup(PATH_TO_FPING); #endif xasprintf (&command_line, "%s %s-b %d -c %d %s", fping_prog, option_string, packet_size, packet_count, server); if (verbose) printf ("%s\n", command_line); /* run the command */ child_process = spopen (command_line); if (child_process == NULL) { printf (_("Could not open pipe: %s\n"), command_line); return STATE_UNKNOWN; } child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); if (child_stderr == NULL) { printf (_("Could not open stderr for %s\n"), command_line); } while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { if (verbose) printf ("%s", input_buffer); status = max_state (status, textscan (input_buffer)); } /* If we get anything on STDERR, at least set warning */ while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { status = max_state (status, STATE_WARNING); if (verbose) printf ("%s", input_buffer); status = max_state (status, textscan (input_buffer)); } (void) fclose (child_stderr); /* close the pipe */ if (result = spclose (child_process)) /* need to use max_state not max */ status = max_state (status, STATE_WARNING); if (result > 1 ) { status = max_state (status, STATE_UNKNOWN); if (result == 2) { die (STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n")); } if (result == 3) { die (STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n")); } if (result == 4) { die (STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n")); } } printf ("FPING %s - %s\n", state_text (status), server_name); return status; }
int main (int argc, char **argv) { short supports_tls=FALSE; int n = 0; double elapsed_time; long microsec; int result = STATE_UNKNOWN; char *cmd_str = NULL; char *helocmd = NULL; char *error_msg = ""; struct timeval tv; /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */ (void) signal (SIGPIPE, SIG_IGN); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If localhostname not set on command line, use gethostname to set */ if(! localhostname){ localhostname = malloc (HOST_MAX_BYTES); if(!localhostname){ printf(_("malloc() failed!\n")); return STATE_CRITICAL; } if(gethostname(localhostname, HOST_MAX_BYTES)){ printf(_("gethostname() failed!\n")); return STATE_CRITICAL; } } if(use_ehlo) xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n"); else xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n"); if (verbose) printf("HELOCMD: %s", helocmd); /* initialize the MAIL command with optional FROM command */ xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n"); if (verbose && send_mail_from) printf ("FROM CMD: %s", cmd_str); /* initialize alarm signal handling */ (void) signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ (void) alarm (socket_timeout); /* start timer */ gettimeofday (&tv, NULL); /* try to connect to the host at the given port number */ result = my_tcp_connect (server_address, server_port, &sd); if (result == STATE_OK) { /* we connected */ /* watch for the SMTP connection string and */ /* return a WARNING status if we couldn't read any data */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else { if (verbose) printf ("%s", buffer); /* strip the buffer of carriage returns */ strip (buffer); /* make sure we find the response we are looking for */ if (!strstr (buffer, server_expect)) { if (server_port == SMTP_PORT) printf (_("Invalid SMTP response received from host: %s\n"), buffer); else printf (_("Invalid SMTP response received from host on port %d: %s\n"), server_port, buffer); return STATE_WARNING; } } /* send the HELO/EHLO command */ send(sd, helocmd, strlen(helocmd), 0); /* allow for response to helo command to reach us */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else if(use_ehlo){ if(strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL){ supports_tls=TRUE; } } if(use_ssl && ! supports_tls){ printf(_("WARNING - TLS not supported by server\n")); smtp_quit(); return STATE_WARNING; } #ifdef HAVE_SSL if(use_ssl) { /* send the STARTTLS command */ send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0); recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */ if (!strstr (buffer, server_expect)) { printf (_("Server does not support STARTTLS\n")); smtp_quit(); return STATE_UNKNOWN; } result = np_net_ssl_init(sd); if(result != STATE_OK) { printf (_("CRITICAL - Cannot create SSL context.\n")); np_net_ssl_cleanup(); close(sd); return STATE_CRITICAL; } else { ssl_established = 1; } /* * Resend the EHLO command. * * RFC 3207 (4.2) says: ``The client MUST discard any knowledge * obtained from the server, such as the list of SMTP service * extensions, which was not obtained from the TLS negotiation * itself. The client SHOULD send an EHLO command as the first * command after a successful TLS negotiation.'' For this * reason, some MTAs will not allow an AUTH LOGIN command before * we resent EHLO via TLS. */ if (my_send(helocmd, strlen(helocmd)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) printf(_("sent %s"), helocmd); if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) { printf("%s", buffer); } # ifdef USE_OPENSSL if ( check_cert ) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); my_close(); return result; } # endif /* USE_OPENSSL */ } #endif if (send_mail_from) { my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); } while (n < ncommands) { xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); strip (buffer); if (n < nresponses) { cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; errcode = regcomp (&preg, responses[n], cflags); if (errcode != 0) { regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Could Not Compile Regular Expression")); return ERROR; } excode = regexec (&preg, buffer, 10, pmatch, eflags); if (excode == 0) { result = STATE_OK; } else if (excode == REG_NOMATCH) { result = STATE_WARNING; printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]); } else { regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Execute Error: %s\n"), errbuf); result = STATE_UNKNOWN; } } n++; } if (authtype != NULL) { if (strcmp (authtype, "LOGIN") == 0) { char *abuf; int ret; do { if (authuser == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authuser specified, ")); break; } if (authpass == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authpass specified, ")); break; } /* send AUTH LOGIN */ my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN)); if (verbose) printf (_("sent %s\n"), "AUTH LOGIN"); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, ")); result = STATE_WARNING; break; } if (verbose) printf (_("received %s\n"), buffer); if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, ")); break; } /* encode authuser with base64 */ base64_encode_alloc (authuser, strlen(authuser), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) printf (_("sent %s\n"), abuf); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authuser, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authuser, ")); break; } /* encode authpass with base64 */ base64_encode_alloc (authpass, strlen(authpass), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) { printf (_("sent %s\n"), abuf); } if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authpass, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "235", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authpass, ")); break; } break; } while (0); } else { result = STATE_CRITICAL; xasprintf(&error_msg, _("only authtype LOGIN is supported, ")); } } /* tell the server we're done */ smtp_quit(); /* finally close the connection */ close (sd); } /* reset the alarm */ alarm (0); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (result == STATE_OK) { if (check_critical_time && elapsed_time > critical_time) result = STATE_CRITICAL; else if (check_warning_time && elapsed_time > warning_time) result = STATE_WARNING; } printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), state_text (result), error_msg, elapsed_time, verbose?", ":"", verbose?buffer:"", fperfdata ("time", elapsed_time, "s", (int)check_warning_time, warning_time, (int)check_critical_time, critical_time, TRUE, 0, FALSE, 0)); return result; }
int main (int argc, char **argv) { int c; bool verbose = false; char *critical = NULL, *warning = NULL; nagstatus status = STATE_OK; thresholds *my_threshold = NULL; unsigned long long nctxt[2]; unsigned int sleep_time = 1, tog = 0; /* toggle switch for cleaner code */ unsigned long i, delay, count; set_program_name (argv[0]); while ((c = getopt_long (argc, argv, "c:w:v" GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1) { switch (c) { default: usage (stderr); case 'c': critical = optarg; break; case 'w': warning = optarg; break; case 'v': verbose = true; break; case_GETOPT_HELP_CHAR case_GETOPT_VERSION_CHAR } } delay = DELAY_DEFAULT, count = COUNT_DEFAULT; if (optind < argc) { delay = strtol_or_err (argv[optind++], "failed to parse argument"); if (delay < 1) plugin_error (STATE_UNKNOWN, 0, "delay must be positive integer"); else if (UINT_MAX < delay) plugin_error (STATE_UNKNOWN, 0, "too large delay value"); sleep_time = delay; } if (optind < argc) count = strtol_or_err (argv[optind++], "failed to parse argument"); status = set_thresholds (&my_threshold, warning, critical); if (status == NP_RANGE_UNPARSEABLE) usage (stderr); unsigned long long dnctxt = nctxt[0] = cpu_stats_get_cswch (); if (verbose) printf ("ctxt = %Lu\n", dnctxt); for (i = 1; i < count; i++) { sleep (sleep_time); tog = !tog; nctxt[tog] = cpu_stats_get_cswch (); dnctxt = (nctxt[tog] - nctxt[!tog]) / sleep_time; if (verbose) printf ("ctxt = %Lu --> %Lu/s\n", nctxt[tog], dnctxt); } status = get_status (dnctxt, my_threshold); free (my_threshold); char *time_unit = (count > 1) ? "/s" : ""; printf ("%s %s - number of context switches%s %Lu | cswch%s=%Lu\n", program_name_short, state_text (status), time_unit, dnctxt, time_unit, dnctxt); return status; }
int textscan (char *buf) { char *rtastr = NULL; char *losstr = NULL; char *xmtstr = NULL; double loss; double rta; double xmt; int status = STATE_UNKNOWN; if (strstr (buf, "not found")) { die (STATE_CRITICAL, _("FPING UNKNOW - %s not found\n"), server_name); } else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) { die (STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"), "host"); } else if (strstr (buf, "Operation not permitted") || strstr (buf, "No such device") ) { die (STATE_UNKNOWN, _("FPING UNKNOWN - %s parameter error\n"), "host"); } else if (strstr (buf, "is down")) { die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); } else if (strstr (buf, "is alive")) { status = STATE_OK; } else if (strstr (buf, "xmt/rcv/%loss") && strstr (buf, "min/avg/max")) { losstr = strstr (buf, "="); losstr = 1 + strstr (losstr, "/"); losstr = 1 + strstr (losstr, "/"); rtastr = strstr (buf, "min/avg/max"); rtastr = strstr (rtastr, "="); rtastr = 1 + index (rtastr, '/'); loss = strtod (losstr, NULL); rta = strtod (rtastr, NULL); if (cpl_p == TRUE && loss > cpl) status = STATE_CRITICAL; else if (crta_p == TRUE && rta > crta) status = STATE_CRITICAL; else if (wpl_p == TRUE && loss > wpl) status = STATE_WARNING; else if (wrta_p == TRUE && rta > wrta) status = STATE_WARNING; else status = STATE_OK; die (status, _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), state_text (status), server_name, loss, rta, perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100), fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, TRUE, 0, FALSE, 0)); } else if(strstr (buf, "xmt/rcv/%loss") ) { /* no min/max/avg if host was unreachable in fping v2.2.b1 */ /* in v2.4b2: 10.99.0.1 : xmt/rcv/%loss = 0/0/0% */ losstr = strstr (buf, "="); xmtstr = 1 + losstr; xmt = strtod (xmtstr, NULL); if(xmt == 0) die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); losstr = 1 + strstr (losstr, "/"); losstr = 1 + strstr (losstr, "/"); loss = strtod (losstr, NULL); if (atoi(losstr) == 100) status = STATE_CRITICAL; else if (cpl_p == TRUE && loss > cpl) status = STATE_CRITICAL; else if (wpl_p == TRUE && loss > wpl) status = STATE_WARNING; else status = STATE_OK; /* loss=%.0f%%;%d;%d;0;100 */ die (status, _("FPING %s - %s (loss=%.0f%% )|%s\n"), state_text (status), server_name, loss , perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100)); } else { status = max_state (status, STATE_WARNING); } return status; }
int main (int argc, char **argv) { int c; bool verbose = false; char *critical = NULL, *warning = NULL; nagstatus status = STATE_OK; thresholds *my_threshold = NULL; unsigned long long nintr[2]; unsigned int sleep_time = 1, tog = 0, /* toggle switch for cleaner code */ ncpus0, ncpus1; unsigned long i, delay, count, *vintr[2] = { NULL, NULL }; set_program_name (argv[0]); while ((c = getopt_long (argc, argv, "c:w:v" GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1) { switch (c) { default: usage (stderr); case 'c': critical = optarg; break; case 'w': warning = optarg; break; case 'v': verbose = true; break; case_GETOPT_HELP_CHAR case_GETOPT_VERSION_CHAR } } delay = DELAY_DEFAULT, count = COUNT_DEFAULT; if (optind < argc) { delay = strtol_or_err (argv[optind++], "failed to parse argument"); if (delay < 1) plugin_error (STATE_UNKNOWN, 0, "delay must be positive integer"); else if (UINT_MAX < delay) plugin_error (STATE_UNKNOWN, 0, "too large delay value"); sleep_time = delay; } if (optind < argc) count = strtol_or_err (argv[optind++], "failed to parse argument"); status = set_thresholds (&my_threshold, warning, critical); if (status == NP_RANGE_UNPARSEABLE) usage (stderr); unsigned long long dnintr = nintr[0] = cpu_stats_get_intr (); if (verbose) printf ("intr = %Lu\n", dnintr); if (count <= 2) vintr[0] = proc_interrupts_get_nintr_per_cpu (&ncpus0); for (i = 1; i < count; i++) { sleep (sleep_time); tog = !tog; nintr[tog] = cpu_stats_get_intr (); dnintr = (nintr[tog] - nintr[!tog]) / sleep_time; if (verbose) printf ("intr = %Lu --> %Lu/s\n", nintr[tog], dnintr); if (count - 2 == i) vintr[0] = proc_interrupts_get_nintr_per_cpu (&ncpus0); else if (count - 1 == i) vintr[1] = proc_interrupts_get_nintr_per_cpu (&ncpus1); } status = get_status (dnintr, my_threshold); free (my_threshold); char *time_unit = (count > 1) ? "/s" : ""; printf ("%s %s - number of interrupts%s %Lu | intr%s=%Lu", program_name_short, state_text (status), time_unit, dnintr, time_unit, dnintr); for (i = 0; i < MIN (ncpus0, ncpus1); i++) printf (" intr_cpu%lu%s=%lu", i, time_unit, (count > 1) ? (vintr[1][i] - vintr[0][i]) / sleep_time : vintr[0][i]); printf ("\n"); free (vintr[1]); free (vintr[0]); return status; }