Ejemplo n.º 1
0
int
fm<Label>::minimal_numbering()
{
	bits	map(max_state().value());

	// set a bit map

	for (int i=0; i<arcs.size(); ++i)
	{
		map.set(arcs[i].get_source().value());
		map.set(arcs[i].get_sink().value());
	}

	// for every zero in the map, renumber 
	// the max-valued transitions

	for (int i=0; i<map.size(); ++i)
	{
		if (map[i] != 0) 
			continue;

		for (j=0; j:wq

}
Ejemplo n.º 2
0
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;
}
Ejemplo n.º 3
0
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;
}
Ejemplo n.º 4
0
int
main (int argc, char **argv)
{
	char command_line[1024];
	int result = STATE_UNKNOWN;
	int line;
	char input_buffer[MAX_INPUT_BUFFER];
	char query_string[512];
	char *errmsg;
	char *temp_buffer;
	int line_status = ONLINE;
	int paper_status = 0;
	int intervention_required = 0;
	int peripheral_error = 0;
	int paper_jam = 0;
	int paper_out = 0;
	int toner_low = 0;
	int page_punt = 0;
	int memory_out = 0;
	int door_open = 0;
	int paper_output = 0;
	char display_message[MAX_INPUT_BUFFER];

	errmsg = 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"));

	/* removed ' 2>1' at end of command 10/27/1999 - EG */
	/* create the query string */
	sprintf
		(query_string,
		 "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0",
		 HPJD_LINE_STATUS,
		 HPJD_PAPER_STATUS,
		 HPJD_INTERVENTION_REQUIRED,
		 HPJD_GD_PERIPHERAL_ERROR,
		 HPJD_GD_PAPER_JAM,
		 HPJD_GD_PAPER_OUT,
		 HPJD_GD_TONER_LOW,
		 HPJD_GD_PAGE_PUNT,
		 HPJD_GD_MEMORY_OUT,
		 HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY);

	/* get the command to run */
	sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%hd %s", PATH_TO_SNMPGET, community,
									address, port, query_string);

	/* 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);
	}

	result = STATE_OK;

	line = 0;
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {

		/* strip the newline character from the end of the input */
		if (input_buffer[strlen (input_buffer) - 1] == '\n')
			input_buffer[strlen (input_buffer) - 1] = 0;

		line++;

		temp_buffer = strtok (input_buffer, "=");
		temp_buffer = strtok (NULL, "=");

		if (temp_buffer == NULL && line < 13) {

				result = STATE_UNKNOWN;
				strcpy (errmsg, input_buffer);

		} else {

			switch (line) {

			case 1:										/* 1st line should contain the line status */
				line_status = atoi (temp_buffer);
				break;
			case 2:										/* 2nd line should contain the paper status */
				paper_status = atoi (temp_buffer);
				break;
			case 3:										/* 3rd line should be intervention required */
				intervention_required = atoi (temp_buffer);
				break;
			case 4:										/* 4th line should be peripheral error */
				peripheral_error = atoi (temp_buffer);
				break;
			case 5:										/* 5th line should contain the paper jam status */
				paper_jam = atoi (temp_buffer);
				break;
			case 6:										/* 6th line should contain the paper out status */
				paper_out = atoi (temp_buffer);
				break;
			case 7:										/* 7th line should contain the toner low status */
				toner_low = atoi (temp_buffer);
				break;
			case 8:										/* did data come too slow for engine */
				page_punt = atoi (temp_buffer);
				break;
			case 9:										/* did we run out of memory */
				memory_out = atoi (temp_buffer);
				break;
			case 10:										/* is there a door open */
				door_open = atoi (temp_buffer);
				break;
			case 11:										/* is output tray full */
				paper_output = atoi (temp_buffer);
				break;
			case 12:										/* display panel message */
				strcpy (display_message, temp_buffer + 1);
				break;
			default:										/* fold multiline message */
				strncat (display_message, input_buffer,
						sizeof (display_message) - strlen (display_message) - 1);
			}

		}

		/* break out of the read loop if we encounter an error */
		if (result != STATE_OK)
			break;
	}

	/* WARNING if output found on stderr */
	if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
		result = max_state (result, STATE_WARNING);
		/* remove CRLF */
		if (input_buffer[strlen (input_buffer) - 1] == '\n')
			input_buffer[strlen (input_buffer) - 1] = 0;
		sprintf (errmsg, "%s", input_buffer );

	}

	/* close stderr */
	(void) fclose (child_stderr);

	/* close the pipe */
	if (spclose (child_process))
		result = max_state (result, STATE_WARNING);

	/* if there wasn't any output, display an error */
	if (line == 0) {

		/* might not be the problem, but most likely is. */
		result = STATE_UNKNOWN ;
		xasprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address );

	}

	/* if we had no read errors, check the printer status results... */
	if (result == STATE_OK) {

		if (paper_jam) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Paper Jam"));
		}
		else if (paper_out) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Out of Paper"));
		}
		else if (line_status == OFFLINE) {
			if (strcmp (errmsg, "POWERSAVE ON") != 0) {
				result = STATE_WARNING;
				strcpy (errmsg, _("Printer Offline"));
			}
		}
		else if (peripheral_error) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Peripheral Error"));
		}
		else if (intervention_required) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Intervention Required"));
		}
		else if (toner_low) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Toner Low"));
		}
		else if (memory_out) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Insufficient Memory"));
		}
		else if (door_open) {
			result = STATE_WARNING;
			strcpy (errmsg, _("A Door is Open"));
		}
		else if (paper_output) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Output Tray is Full"));
		}
		else if (page_punt) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Data too Slow for Engine"));
		}
		else if (paper_status) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Unknown Paper Error"));
		}
	}

	if (result == STATE_OK)
		printf (_("Printer ok - (%s)\n"), display_message);

	else if (result == STATE_UNKNOWN) {

		printf ("%s\n", errmsg);

		/* if printer could not be reached, escalate to critical */
		if (strstr (errmsg, "Timeout"))
			result = STATE_CRITICAL;
	}

	else if (result == STATE_WARNING)
		printf ("%s (%s)\n", errmsg, display_message);

	return result;
}
Ejemplo n.º 5
0
int
main (int argc, char **argv)
{
	char *input_buffer;
	char *input_line;
	char *procprog;

	pid_t mypid = 0;
	int procuid = 0;
	pid_t procpid = 0;
	pid_t procppid = 0;
	int procvsz = 0;
	int procrss = 0;
	int procseconds = 0;
	float procpcpu = 0;
	char procstat[8];
	char procetime[MAX_INPUT_BUFFER] = { '\0' };
	char *procargs;

	const char *zombie = "Z";

	int resultsum = 0; /* bitmask of the filter criteria met by a process */
	int found = 0; /* counter for number of lines returned in `ps` output */
	int procs = 0; /* counter for number of processes meeting filter criteria */
	int pos; /* number of spaces before 'args' in `ps` output */
	int cols; /* number of columns in ps output */
	int expected_cols = PS_COLS - 1;
	int warn = 0; /* number of processes in warn state */
	int crit = 0; /* number of processes in crit state */
	int i = 0, j = 0;
	int result = STATE_UNKNOWN;
	output chld_out, chld_err;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);
	setlocale(LC_NUMERIC, "POSIX");

	input_buffer = malloc (MAX_INPUT_BUFFER);
	procprog = malloc (MAX_INPUT_BUFFER);

	xasprintf (&metric_name, "PROCS");
	metric = METRIC_PROCS;

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	/* get our pid */
	mypid = getpid();

	/* Set signal handling and alarm timeout */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
		die (STATE_UNKNOWN, _("Cannot catch SIGALRM"));
	}
	(void) alarm ((unsigned) timeout_interval);

	if (verbose >= 2)
		printf (_("CMD: %s\n"), PS_COMMAND);

	if (input_filename == NULL) {
		result = cmd_run( PS_COMMAND, &chld_out, &chld_err, 0);
		if (chld_err.lines > 0) {
			printf ("%s: %s", _("System call sent warnings to stderr"), chld_err.line[0]);
			exit(STATE_WARNING);
		}
	} else {
		result = cmd_file_read( input_filename, &chld_out, 0);
	}

	/* flush first line: j starts at 1 */
	for (j = 1; j < chld_out.lines; j++) {
		input_line = chld_out.line[j];

		if (verbose >= 3)
			printf ("%s", input_line);

		strcpy (procprog, "");
		xasprintf (&procargs, "%s", "");

		cols = sscanf (input_line, PS_FORMAT, PS_VARLIST);

		/* Zombie processes do not give a procprog command */
		if ( cols < expected_cols && strstr(procstat, zombie) ) {
			cols = expected_cols;
		}
		if ( cols >= expected_cols ) {
			resultsum = 0;
			xasprintf (&procargs, "%s", input_line + pos);
			strip (procargs);

			/* Some ps return full pathname for command. This removes path */
			strcpy(procprog, base_name(procprog));

			/* we need to convert the elapsed time to seconds */
			procseconds = convert_to_seconds(procetime);

			if (verbose >= 3)
				printf ("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", 
					procs, procuid, procvsz, procrss,
					procpid, procppid, procpcpu, procstat, 
					procetime, procprog, procargs);

			/* Ignore self */
			if (mypid == procpid) continue;

			if ((options & STAT) && (strstr (statopts, procstat)))
				resultsum |= STAT;
			if ((options & ARGS) && procargs && (strstr (procargs, args) != NULL))
				resultsum |= ARGS;
			if ((options & EREG_ARGS) && procargs && (regexec(&re_args, procargs, (size_t) 0, NULL, 0) == 0))
				resultsum |= EREG_ARGS;
			if ((options & PROG) && procprog && (strcmp (prog, procprog) == 0))
				resultsum |= PROG;
			if ((options & PPID) && (procppid == ppid))
				resultsum |= PPID;
			if ((options & USER) && (procuid == uid))
				resultsum |= USER;
			if ((options & VSZ)  && (procvsz >= vsz))
				resultsum |= VSZ;
			if ((options & RSS)  && (procrss >= rss))
				resultsum |= RSS;
			if ((options & PCPU)  && (procpcpu >= pcpu))
				resultsum |= PCPU;

			found++;

			/* Next line if filters not matched */
			if (!(options == resultsum || options == ALL))
				continue;

			procs++;
			if (verbose >= 2) {
				printf ("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", 
					procuid, procvsz, procrss,
					procpid, procppid, procpcpu, procstat, 
					procetime, procprog, procargs);
			}

			if (metric == METRIC_VSZ)
				i = get_status ((double)procvsz, procs_thresholds);
			else if (metric == METRIC_RSS)
				i = get_status ((double)procrss, procs_thresholds);
			/* TODO? float thresholds for --metric=CPU */
			else if (metric == METRIC_CPU)
				i = get_status (procpcpu, procs_thresholds);
			else if (metric == METRIC_ELAPSED)
				i = get_status ((double)procseconds, procs_thresholds);

			if (metric != METRIC_PROCS) {
				if (i == STATE_WARNING) {
					warn++;
					xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
					result = max_state (result, i);
				}
				if (i == STATE_CRITICAL) {
					crit++;
					xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
					result = max_state (result, i);
				}
			}
		} 
		/* This should not happen */
		else if (verbose) {
			printf(_("Not parseable: %s"), input_buffer);
		}
	}

	if (found == 0) {							/* no process lines parsed so return STATE_UNKNOWN */
		printf (_("Unable to read output\n"));
		return STATE_UNKNOWN;
	}

	if ( result == STATE_UNKNOWN ) 
		result = STATE_OK;

	/* Needed if procs found, but none match filter */
	if ( metric == METRIC_PROCS ) {
		result = max_state (result, get_status ((double)procs, procs_thresholds) );
	}

	if ( result == STATE_OK ) {
		printf ("%s %s: ", metric_name, _("OK"));
	} else if (result == STATE_WARNING) {
		printf ("%s %s: ", metric_name, _("WARNING"));
		if ( metric != METRIC_PROCS ) {
			printf (_("%d warn out of "), warn);
		}
	} else if (result == STATE_CRITICAL) {
		printf ("%s %s: ", metric_name, _("CRITICAL"));
		if (metric != METRIC_PROCS) {
			printf (_("%d crit, %d warn out of "), crit, warn);
		}
	} 
	printf (ngettext ("%d process", "%d processes", (unsigned long) procs), procs);
	
	if (strcmp(fmt,"") != 0) {
		printf (_(" with %s"), fmt);
	}

	if ( verbose >= 1 && strcmp(fails,"") )
		printf (" [%s]", fails);

	if (metric == METRIC_PROCS)
		printf (" | procs=%d;%s;%s;0;", procs,
				warning_range ? warning_range : "",
				critical_range ? critical_range : "");
	else
		printf (" | procs=%d;;;0; procs_warn=%d;;;0; procs_crit=%d;;;0;", procs, warn, crit);

	printf ("\n");
	return result;
}
Ejemplo n.º 6
0
int
main (int argc, char **argv)
{
	int result = STATE_UNKNOWN;
	char input_buffer[MAX_INPUT_BUFFER];
	unsigned long latest_entry_time = 0L;
	unsigned long temp_entry_time = 0L;
	int proc_entries = 0;
	time_t current_time;
	char *temp_ptr;
	FILE *fp;
	int procuid = 0;
	int procpid = 0;
	int procppid = 0;
	int procvsz = 0;
	int procrss = 0;
	float procpcpu = 0;
	char procstat[8];
#ifdef PS_USES_PROCETIME
	char procetime[MAX_INPUT_BUFFER];
#endif /* PS_USES_PROCETIME */
	char procprog[MAX_INPUT_BUFFER];
	char *procargs;
	int pos, cols;
	int expected_cols = PS_COLS - 1;
	const char *zombie = "Z";
	char *temp_string;
	output chld_out, chld_err;
	size_t i;

	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_va(_("Could not parse arguments"));

	/* Set signal handling and alarm timeout */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
		usage_va(_("Cannot catch SIGALRM"));
	}

	/* handle timeouts gracefully... */
	alarm (timeout_interval);

	/* open the status log */
	fp = fopen (status_log, "r");
	if (fp == NULL) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Cannot open status log for reading!"));
	}

	/* get the date/time of the last item updated in the log */
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
		if ((temp_ptr = strstr (input_buffer, "created=")) != NULL) {
			temp_entry_time = strtoul (temp_ptr + 8, NULL, 10);
			latest_entry_time = temp_entry_time;
			break;
		} else if ((temp_ptr = strtok (input_buffer, "]")) != NULL) {
			temp_entry_time = strtoul (temp_ptr + 1, NULL, 10);
			if (temp_entry_time > latest_entry_time)
				latest_entry_time = temp_entry_time;
		}
	}
	fclose (fp);

	if (verbose >= 2)
		printf("command: %s\n", PS_COMMAND);

	/* run the command to check for the Nagios process.. */
	if((result = np_runcmd(PS_COMMAND, &chld_out, &chld_err, 0)) != 0)
		result = STATE_WARNING;

	/* count the number of matching Nagios processes... */
	for(i = 0; i < chld_out.lines; i++) {
		cols = sscanf (chld_out.line[i], PS_FORMAT, PS_VARLIST);
		/* Zombie processes do not give a procprog command */
		if ( cols == (expected_cols - 1) && strstr(procstat, zombie) ) {
			cols = expected_cols;
			/* Set some value for procargs for the strip command further below
			 * Seen to be a problem on some Solaris 7 and 8 systems */
			chld_out.line[i][pos] = '\n';
			chld_out.line[i][pos+1] = 0x0;
		}
		if ( cols >= expected_cols ) {
			xasprintf (&procargs, "%s", chld_out.line[i] + pos);
			strip (procargs);

			/* Some ps return full pathname for command. This removes path */
			temp_string = strtok ((char *)procprog, "/");
			while (temp_string) {
				strcpy(procprog, temp_string);
				temp_string = strtok (NULL, "/");
			}

			/* May get empty procargs */
			if (!strstr(procargs, argv[0]) && strstr(procargs, process_string) && strcmp(procargs,"")) {
				proc_entries++;
				if (verbose >= 2) {
					printf (_("Found process: %s %s\n"), procprog, procargs);
				}
			}
		}
	}

	/* If we get anything on stderr, at least set warning */
	if(chld_err.buflen)
		result = max_state (result, STATE_WARNING);

	/* reset the alarm handler */
	alarm (0);

	if (proc_entries == 0) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Could not locate a running Nagios process!"));
	}

	if (latest_entry_time == 0L) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Cannot parse Nagios log file for valid time"));
	}

	time (&current_time);
	if ((int)(current_time - latest_entry_time) > (expire_minutes * 60)) {
		result = STATE_WARNING;
	} else {
		result = STATE_OK;
	}

	printf ("NAGIOS %s: ", (result == STATE_OK) ? _("OK") : _("WARNING"));
	printf (ngettext ("%d process", "%d processes", proc_entries), proc_entries);
	printf (", ");
	printf (
	  ngettext ("status log updated %d second ago",
	    "status log updated %d seconds ago",
	    (int) (current_time - latest_entry_time) ),
	    (int) (current_time - latest_entry_time) );
	printf ("\n");

	return result;
}
Ejemplo n.º 7
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char *temp_buffer = NULL;
  int non_authoritative = FALSE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

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

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], ".in-addr.arpa")) {
      if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
        addresses[n_addresses++] = strdup (temp_buffer + 7);
      else {
        msg = (char *)_("Warning plugin error");
        result = STATE_WARNING;
      }
    }

    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
             strstr (chld_out.line[i], "Addresses:"))) {
      temp_buffer = index (chld_out.line[i], ':');
      temp_buffer++;

      /* Strip leading spaces */
      for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
        /* NOOP */;

      strip(temp_buffer);
      if (temp_buffer==NULL || strlen(temp_buffer)==0) {
        die (STATE_CRITICAL,
             _("DNS CRITICAL - '%s' returned empty host name string\n"),
             NSLOOKUP_COMMAND);
      }

      addresses[n_addresses++] = strdup(temp_buffer);
    }
    else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }


    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) {
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && non_authoritative) {
    result = STATE_CRITICAL;
    xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Ejemplo n.º 8
0
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;
}
Ejemplo n.º 9
0
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;
}
Ejemplo n.º 10
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char query_found[16] = "";
  char *temp_buffer = NULL;
  int non_authoritative = TRUE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

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

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s %s", NSLOOKUP_COMMAND, query_type, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], "Authoritative answers can be found from:")) {
      non_authoritative = FALSE;
      break;
    }
    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    /* begin handling types of records */
    if (strstr (chld_out.line[i], "AAAA address")) {
      if (verbose) printf("Found AAAA record\n");
      temp_buffer = rindex (chld_out.line[i], ' ');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=AAAA", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "exchanger =")) {
      if (verbose) printf("Found MX record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=MX", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "service =")) {
      if (verbose) printf("Found SRV record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=SRV", sizeof(query_found));
    }
    else if (accept_cname && strstr (chld_out.line[i], "canonical name =")) {
      if (verbose) printf("Found CNAME record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=CNAME", sizeof(query_found));
    }
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") || strstr (chld_out.line[i], "Addresses:"))) {
      if (verbose) printf("Found A record\n");
      temp_buffer = index (chld_out.line[i], ':');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=A", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "nameserver =")) {
      if (verbose) printf("Found NS record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=NS", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "dname =")) {
      if (verbose) printf("Found DNAME record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=DNAME", sizeof(query_found));
    }
    /* must be after other records with "name" as an identifier, as ptr does not spefify */
    else if (strstr (chld_out.line[i], "name =")) {
      if (verbose) printf("Found PTR record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=PTR", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "protocol =")) {
      if (verbose) printf("Found WKS record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=WKS", sizeof(query_found));
    }
    /* TODO: needs to be changed to handle txt output and max size of txt recrods */
    else if (strstr (chld_out.line[i], "text =")) {
      if (verbose) printf("Found TXT record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=TXT", sizeof(query_found));
    }
    /* only matching for origin records, if requested other fields could be included at a later date */
    else if (strstr (chld_out.line[i], "origin =")) {
      if (verbose) printf("Found SOA record\n");
      temp_buffer = index(chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=SOA", sizeof(query_found));
    }

    if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }

    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) { 
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && !non_authoritative) {
    result = STATE_CRITICAL;

    if (strncmp(dns_server, "", 1))
      xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
    else
      xasprintf(&msg, _("there is no authoritative server for %s"), query_address);
  }

  /* compare query type to query found, if query type is ANY we can skip as any record is accepted*/
  if (result == STATE_OK && strncmp(query_type, "", 1) && (strncmp(query_type, "-querytype=ANY", 15) != 0)) {
    if (strncmp(query_type, query_found, 16) != 0) {
      if (verbose)
        printf( "Failed query for %s only found %s, or nothing\n", query_type, query_found);
      result = STATE_CRITICAL;
      xasprintf(&msg, _("query type of %s was not found for %s"), query_type, query_address);
    }
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  FALSE, 0,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  FALSE, 0,
                                  TRUE, 0, FALSE, 0));
    } else
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Ejemplo n.º 11
0
int
main (int argc, char **argv)
{
	int found = 0, result = STATE_UNKNOWN;
	char *url = NULL;
	char *cmd;
	char *buf;
	char *nstr;
	char tstr[MAX_INPUT_BUFFER];

	int c;
	int option = 0;
	static struct option longopts[] = {
		{"help", no_argument, 0, 'h'},
		{"version", no_argument, 0, 'V'},
		{"url", required_argument, 0, 'u'},
		{0, 0, 0, 0}
	};

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* Need at least 2 args */
	if (argc < 3) {
		print_help();
		exit (STATE_UNKNOWN);
	}

	while (1) {
		c = getopt_long (argc, argv, "+hVu:", longopts, &option);

		if (c == -1 || c == EOF)
			break;

		switch (c) {
		case 'h':     /* help */
			print_help ();
			exit (EXIT_SUCCESS);
			break;
		case 'V':     /* version */
			print_revision (progname, NP_VERSION);
			exit (EXIT_SUCCESS);
			break;
		case 'u':
			url = strdup (argv[optind]);
			break;
		case '?':
		default:
			usage5 ();
		}
	}

	if (url == NULL)
		url = strdup (argv[optind++]);

	cmd = strdup (argv[optind++]);
	for (c = optind; c < argc; c++) {
		xasprintf (&cmd, "%s %s", cmd, argv[c]);
	}

	child_process = spopen (cmd);
	if (child_process == NULL) {
		printf (_("Could not open pipe: %s\n"), cmd);
		exit (STATE_UNKNOWN);
	}

	child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
	if (child_stderr == NULL) {
		printf (_("Could not open stderr for %s\n"), cmd);
	}

	bzero(tstr, sizeof(tstr));
	buf = malloc(MAX_INPUT_BUFFER);
	printf ("<A href=\"%s\">", argv[1]);
	while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
		found++;
		/* Collect the string in temp str so we can tokenize */
		strcat(tstr, buf);
	}

	if (!found)
		die (STATE_UNKNOWN,
		     _("%s UNKNOWN - No data received from host\nCMD: %s</A>\n"),
		     argv[0], cmd);


	/* chop the newline character */
	if ((nstr = strchr(tstr, NEWLINE_CHARACTER)) != NULL)
		*nstr = '\0';

	/* tokenize the string for Perfdata if there is some */
	nstr = strtok(tstr, PERF_CHARACTER);
	printf ("%s", nstr);
	printf ("</A>");
	nstr = strtok(NULL, PERF_CHARACTER);
	if (nstr != NULL)
		printf (" | %s", nstr);

	/* close the pipe */
	result = spclose (child_process);

	/* WARNING if output found on stderr */
	if (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
		result = max_state (result, STATE_WARNING);

	/* close stderr */
	(void) fclose (child_stderr);

	return result;
}
Ejemplo n.º 12
0
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;
}
Ejemplo n.º 13
0
int
main (int argc, char **argv)
{
/* normaly should be  int result = STATE_UNKNOWN; */

  int status = STATE_UNKNOWN;
  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)
    asprintf(&option_string, "%s-t %d ", option_string, target_timeout);
  if (packet_interval)
    asprintf(&option_string, "%s-p %d ", option_string, packet_interval);

  asprintf (&command_line, "%s %s-b %d -c %d %s", PATH_TO_FPING,
            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 (spclose (child_process))
    /* need to use max_state not max */
    status = max_state (status, STATE_WARNING);

  printf ("FPING %s - %s\n", state_text (status), server_name);

  return status;
}
Ejemplo n.º 14
0
int
main (int argc, char **argv)
{
    char *cmd = NULL;
    char *rawcmd = NULL;
    int result = STATE_UNKNOWN;
    int this_result = STATE_UNKNOWN;
    int i;

    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
    bindtextdomain (PACKAGE, LOCALEDIR);
    textdomain (PACKAGE);

    addresses = malloc (sizeof(char*) * max_addr);
    addresses[0] = NULL;

    /* Parse extra opts if any */
    argv=np_extra_opts (&argc, argv, progname);

    if (process_arguments (argc, argv) == ERROR)
        usage4 (_("Could not parse arguments"));

    /* Set signal handling and alarm */
    if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
        usage4 (_("Cannot catch SIGALRM"));
    }

    /* If ./configure finds ping has timeout values, set plugin alarm slightly
     * higher so that we can use response from command line ping */
#if defined(PING_PACKETS_FIRST) && defined(PING_HAS_TIMEOUT)
    alarm (timeout_interval + 1);
#else
    alarm (timeout_interval);
#endif

    for (i = 0 ; i < n_addresses ; i++) {

#ifdef PING6_COMMAND
        if (address_family != AF_INET && is_inet6_addr(addresses[i]))
            rawcmd = strdup(PING6_COMMAND);
        else
            rawcmd = strdup(PING_COMMAND);
#else
        rawcmd = strdup(PING_COMMAND);
#endif

        /* does the host address of number of packets argument come first? */
#ifdef PING_PACKETS_FIRST
# ifdef PING_HAS_TIMEOUT
        xasprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
# else
        xasprintf (&cmd, rawcmd, max_packets, addresses[i]);
# endif
#else
        xasprintf (&cmd, rawcmd, addresses[i], max_packets);
#endif

        if (verbose >= 2)
            printf ("CMD: %s\n", cmd);

        /* run the command */
        this_result = run_ping (cmd, addresses[i]);

        if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
            printf ("%s\n", cmd);
            die (STATE_UNKNOWN,
                 _("CRITICAL - Could not interpret output from ping command\n"));
        }

        if (pl >= cpl || rta >= crta || rta < 0)
            this_result = STATE_CRITICAL;
        else if (pl >= wpl || rta >= wrta)
            this_result = STATE_WARNING;
        else if (pl >= 0 && rta >= 0)
            this_result = max_state (STATE_OK, this_result);

        if (n_addresses > 1 && this_result != STATE_UNKNOWN)
            die (STATE_OK, "%s is alive\n", addresses[i]);

        if (display_html == TRUE)
            printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
        if (pl == 100)
            printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
                    pl);
        else
            printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
                    state_text (this_result), warn_text, pl, rta);
        if (display_html == TRUE)
            printf ("</A>");

        /* Print performance data */
        printf("|%s", fperfdata ("rta", (double) rta, "ms",
                                 wrta>0?TRUE:FALSE, wrta,
                                 crta>0?TRUE:FALSE, crta,
                                 TRUE, 0, FALSE, 0));
        printf(" %s\n", perfdata ("pl", (long) pl, "%",
                                  wpl>0?TRUE:FALSE, wpl,
                                  cpl>0?TRUE:FALSE, cpl,
                                  TRUE, 0, FALSE, 0));

        if (verbose >= 2)
            printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);

        result = max_state (result, this_result);
        free (rawcmd);
        free (cmd);
    }

    return result;
}
Ejemplo n.º 15
0
int
run_ping (const char *cmd, const char *addr)
{
    char buf[MAX_INPUT_BUFFER];
    int result = STATE_UNKNOWN;
    int match;

    if ((child_process = spopen (cmd)) == NULL)
        die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);

    child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
    if (child_stderr == NULL)
        printf (_("Cannot open stderr for %s\n"), cmd);

    while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {

        if (verbose >= 3)
            printf("Output: %s", buf);

        result = max_state (result, error_scan (buf, addr));

        /* get the percent loss statistics */
        match = 0;
        if((sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) ||
                (sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) ||
                (sscanf(buf,"%*[^(](%d%% %*[^)])%n",&pl,&match) && match)
          )
            continue;

        /* get the round trip average */
        else if((sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
                (sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms%n",&rta,&match) && match) ||
                (sscanf(buf, "%*[^=] = %*fms, %*[^=] = %*fms, %*[^=] = %fms%n", &rta, &match) && match)
               )
            continue;
    }

    /* this is needed because there is no rta if all packets are lost */
    if (pl == 100)
        rta = crta;

    /* check stderr, setting at least WARNING if there is output here */
    /* Add warning into warn_text */
    while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
        if (
            ! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP")
            && ! strstr(buf,"Warning: time of day goes back")

        ) {
            if (verbose >= 3) {
                printf("Got stderr: %s", buf);
            }
            if ((result=error_scan(buf, addr)) == STATE_OK) {
                result = STATE_WARNING;
                if (warn_text == NULL) {
                    warn_text = strdup(_("System call sent warnings to stderr "));
                } else {
                    xasprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
                }
            }
        }
    }

    (void) fclose (child_stderr);


    spclose (child_process);

    if (warn_text == NULL)
        warn_text = strdup("");

    return result;
}
Ejemplo n.º 16
0
int
main (int argc, char **argv)
{
	int percent_used, percent;
	float total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0;
	float dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0, tmp_mb = 0;
	int result = STATE_UNKNOWN;
	char input_buffer[MAX_INPUT_BUFFER];
#ifdef HAVE_PROC_MEMINFO
	FILE *fp;
#else
	int conv_factor = SWAP_CONVERSION;
# ifdef HAVE_SWAP
	char *temp_buffer;
	char *swap_command;
	char *swap_format;
# else
#  ifdef HAVE_DECL_SWAPCTL
	int i=0, nswaps=0, swapctl_res=0;
#   ifdef CHECK_SWAP_SWAPCTL_SVR4
	swaptbl_t *tbl=NULL;
	swapent_t *ent=NULL;
#   else
#    ifdef CHECK_SWAP_SWAPCTL_BSD
	struct swapent *ent;
#    endif /* CHECK_SWAP_SWAPCTL_BSD */
#   endif /* CHECK_SWAP_SWAPCTL_SVR4 */
#  endif /* HAVE_DECL_SWAPCTL */
# endif
#endif
	char str[32];
	char *status;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	status = strdup ("");

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

#ifdef HAVE_PROC_MEMINFO
	if (verbose >= 3) {
		printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
	}
	fp = fopen (PROC_MEMINFO, "r");
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
		if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) {
			dsktotal_mb = dsktotal_mb / 1048576;	/* Apply conversion */
			dskused_mb = dskused_mb / 1048576;
			dskfree_mb = dskfree_mb / 1048576;
			total_swap_mb += dsktotal_mb;
			used_swap_mb += dskused_mb;
			free_swap_mb += dskfree_mb;
			if (allswaps) {
				if (dsktotal_mb == 0)
					percent=100.0;
				else
					percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
				result = max_state (result, check_swap (percent, dskfree_mb));
				if (verbose)
					xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
			}
		}
		else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) {
			if (verbose >= 3) {
				printf("Got %s with %f\n", str, tmp_mb);
			}
			/* I think this part is always in Kb, so convert to mb */
			if (strcmp ("Total", str) == 0) {
				dsktotal_mb = tmp_mb / 1024;
			}
			else if (strcmp ("Free", str) == 0) {
				dskfree_mb = tmp_mb / 1024;
			}
		}
	}
	fclose(fp);
	dskused_mb = dsktotal_mb - dskfree_mb;
	total_swap_mb = dsktotal_mb;
	used_swap_mb = dskused_mb;
	free_swap_mb = dskfree_mb;
#else
# ifdef HAVE_SWAP
	xasprintf(&swap_command, "%s", SWAP_COMMAND);
	xasprintf(&swap_format, "%s", SWAP_FORMAT);

/* These override the command used if a summary (and thus ! allswaps) is required */
/* The summary flag returns more accurate information about swap usage on these OSes */
#  ifdef _AIX
	if (!allswaps) {
		xasprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
		xasprintf(&swap_format, "%s", "%f%*s %f");
		conv_factor = 1;
	}
#  endif

	if (verbose >= 2)
		printf (_("Command: %s\n"), swap_command);
	if (verbose >= 3)
		printf (_("Format: %s\n"), swap_format);

	child_process = spopen (swap_command);
	if (child_process == NULL) {
		printf (_("Could not open pipe: %s\n"), swap_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"), swap_command);

	sprintf (str, "%s", "");
	/* read 1st line */
	fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
	if (strcmp (swap_format, "") == 0) {
		temp_buffer = strtok (input_buffer, " \n");
		while (temp_buffer) {
			if (strstr (temp_buffer, "blocks"))
				sprintf (str, "%s %s", str, "%f");
			else if (strstr (temp_buffer, "dskfree"))
				sprintf (str, "%s %s", str, "%f");
			else
				sprintf (str, "%s %s", str, "%*s");
			temp_buffer = strtok (NULL, " \n");
		}
	}

/* If different swap command is used for summary switch, need to read format differently */
#  ifdef _AIX
	if (!allswaps) {
		fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process);	/* Ignore first line */
		sscanf (input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
		free_swap_mb = total_swap_mb * (100 - used_swap_mb) /100;
		used_swap_mb = total_swap_mb - free_swap_mb;
		if (verbose >= 3)
			printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
	} else {
#  endif
		while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
			sscanf (input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);

			dsktotal_mb = dsktotal_mb / conv_factor;
			/* AIX lists percent used, so this converts to dskfree in MBs */
#  ifdef _AIX
			dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
#  else
			dskfree_mb = dskfree_mb / conv_factor;
#  endif
			if (verbose >= 3)
				printf (_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);

			dskused_mb = dsktotal_mb - dskfree_mb;
			total_swap_mb += dsktotal_mb;
			used_swap_mb += dskused_mb;
			free_swap_mb += dskfree_mb;
			if (allswaps) {
				percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
				result = max_state (result, check_swap (percent, dskfree_mb));
				if (verbose)
					xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
			}
		}
#  ifdef _AIX
	}
#  endif

	/* If we get anything on STDERR, at least set warning */
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
		result = max_state (result, STATE_WARNING);

	/* close stderr */
	(void) fclose (child_stderr);

	/* close the pipe */
	if (spclose (child_process))
		result = max_state (result, STATE_WARNING);
# else
#  ifdef CHECK_SWAP_SWAPCTL_SVR4

	/* get the number of active swap devices */
	if((nswaps=swapctl(SC_GETNSWP, NULL))== -1)
		die(STATE_UNKNOWN, _("Error getting swap devices\n") );

	if(nswaps == 0)
		die(STATE_OK, _("SWAP OK: No swap devices defined\n"));

	if(verbose >= 3)
		printf("Found %d swap device(s)\n", nswaps);

	/* initialize swap table + entries */
	tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));

	if(tbl==NULL)
		die(STATE_UNKNOWN, _("malloc() failed!\n"));

	memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
	tbl->swt_n=nswaps;
	for(i=0;i<nswaps;i++){
		if((tbl->swt_ent[i].ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN)) == NULL)
			die(STATE_UNKNOWN, _("malloc() failed!\n"));
	}

	/* and now, tally 'em up */
	swapctl_res=swapctl(SC_LIST, tbl);
	if(swapctl_res < 0){
		perror(_("swapctl failed: "));
		die(STATE_UNKNOWN, _("Error in swapctl call\n"));
	}

	for(i=0;i<nswaps;i++){
		dsktotal_mb = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
		dskfree_mb = (float) tbl->swt_ent[i].ste_free /  SWAP_CONVERSION;
		dskused_mb = ( dsktotal_mb - dskfree_mb );

		if (verbose >= 3)
			printf ("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb);

		if(allswaps && dsktotal_mb > 0){
			percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
			result = max_state (result, check_swap (percent, dskfree_mb));
			if (verbose) {
				xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
			}
		}

		total_swap_mb += dsktotal_mb;
		free_swap_mb += dskfree_mb;
		used_swap_mb += dskused_mb;
	}

	/* and clean up after ourselves */
	for(i=0;i<nswaps;i++){
		free(tbl->swt_ent[i].ste_path);
	}
	free(tbl);
#  else
#   ifdef CHECK_SWAP_SWAPCTL_BSD

	/* get the number of active swap devices */
	nswaps=swapctl(SWAP_NSWAP, NULL, 0);

	/* initialize swap table + entries */
	ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps);

	/* and now, tally 'em up */
	swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
	if(swapctl_res < 0){
		perror(_("swapctl failed: "));
		die(STATE_UNKNOWN, _("Error in swapctl call\n"));
	}

	for(i=0;i<nswaps;i++){
		dsktotal_mb = (float) ent[i].se_nblks / conv_factor;
		dskused_mb = (float) ent[i].se_inuse / conv_factor;
		dskfree_mb = ( dsktotal_mb - dskused_mb );

		if(allswaps && dsktotal_mb > 0){
			percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
			result = max_state (result, check_swap (percent, dskfree_mb));
			if (verbose) {
				xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
			}
		}

		total_swap_mb += dsktotal_mb;
		free_swap_mb += dskfree_mb;
		used_swap_mb += dskused_mb;
	}

	/* and clean up after ourselves */
	free(ent);

#   endif /* CHECK_SWAP_SWAPCTL_BSD */
#  endif /* CHECK_SWAP_SWAPCTL_SVR4 */
# endif /* HAVE_SWAP */
#endif /* HAVE_PROC_MEMINFO */

	/* if total_swap_mb == 0, let's not divide by 0 */
	if(total_swap_mb) {
		percent_used = 100 * ((double) used_swap_mb) / ((double) total_swap_mb);
	} else {
		percent_used = 0;
	}

	result = max_state (result, check_swap (percent_used, free_swap_mb));
	printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"),
			state_text (result),
			(100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status);

	puts (perfdata ("swap", (long) free_swap_mb, "MB",
	                TRUE, (long) max (warn_size_bytes/(1024 * 1024), warn_percent/100.0*total_swap_mb),
	                TRUE, (long) max (crit_size_bytes/(1024 * 1024), crit_percent/100.0*total_swap_mb),
	                TRUE, 0,
	                TRUE, (long) total_swap_mb));

	return result;
}