示例#1
1
文件: rrd.php 项目: songchin/Cacti
function rrdtool_function_graph($local_graph_id, $rra_id, $graph_data_array, $rrd_struc = array()) {
	global $config;

	include_once($config["library_path"] . "/cdef.php");
	include_once($config["library_path"] . "/graph_variables.php");
	include($config["include_path"] . "/config_arrays.php");

	/* before we do anything; make sure the user has permission to view this graph,
	if not then get out */
	if ((read_config_option("global_auth") == "on") && (isset($_SESSION["sess_user_id"]))) {
		$access_denied = !(is_graph_allowed($local_graph_id));

		if ($access_denied == true) {
			return "GRAPH ACCESS DENIED";
		}
	}

	/* find the step and how often this graph is updated with new data */
	$ds_step = db_fetch_cell("select
		data_template_data.rrd_step
		from data_template_data,data_template_rrd,graph_templates_item
		where graph_templates_item.task_item_id=data_template_rrd.id
		and data_template_rrd.local_data_id=data_template_data.local_data_id
		and graph_templates_item.local_graph_id=$local_graph_id
		limit 0,1");
	$ds_step = empty($ds_step) ? 300 : $ds_step;

	/* if no rra was specified, we need to figure out which one RRDTool will choose using
	 * "best-fit" resolution fit algorithm */
	if (empty($rra_id)) {
		if ((empty($graph_data_array["graph_start"])) || (empty($graph_data_array["graph_end"]))) {
			$rra["rows"] = 600;
			$rra["steps"] = 1;
			$rra["timespan"] = 86400;
		}else{
			/* get a list of RRAs related to this graph */
			$rras = get_associated_rras($local_graph_id);

			if (sizeof($rras) > 0) {
				foreach ($rras as $unchosen_rra) {
					/* the timespan specified in the RRA "timespan" field may not be accurate */
					$real_timespan = ($ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"]);

					/* make sure the current start/end times fit within each RRA's timespan */
					if ( (($graph_data_array["graph_end"] - $graph_data_array["graph_start"]) <= $real_timespan) && ((time() - $graph_data_array["graph_start"]) <= $real_timespan) ) {
						/* is this RRA better than the already chosen one? */
						if ((isset($rra)) && ($unchosen_rra["steps"] < $rra["steps"])) {
							$rra = $unchosen_rra;
						}else if (!isset($rra)) {
							$rra = $unchosen_rra;
						}
					}
				}
			}

			if (!isset($rra)) {
				$rra["rows"] = 600;
				$rra["steps"] = 1;
			}
		}
	}else{
		$rra = db_fetch_row("select timespan,rows,steps from rra where id=$rra_id");
	}

	$seconds_between_graph_updates = ($ds_step * $rra["steps"]);

	$graph = db_fetch_row("select
		graph_local.host_id,
		graph_local.snmp_query_id,
		graph_local.snmp_index,
		graph_templates_graph.title_cache,
		graph_templates_graph.vertical_label,
		graph_templates_graph.auto_scale,
		graph_templates_graph.auto_scale_opts,
		graph_templates_graph.auto_scale_log,
		graph_templates_graph.auto_scale_rigid,
		graph_templates_graph.auto_padding,
		graph_templates_graph.base_value,
		graph_templates_graph.upper_limit,
		graph_templates_graph.lower_limit,
		graph_templates_graph.height,
		graph_templates_graph.width,
		graph_templates_graph.image_format_id,
		graph_templates_graph.unit_value,
		graph_templates_graph.unit_exponent_value,
		graph_templates_graph.export
		from graph_templates_graph,graph_local
		where graph_local.id=graph_templates_graph.local_graph_id
		and graph_templates_graph.local_graph_id=$local_graph_id");

	/* lets make that sql query... */
	$graph_items = db_fetch_assoc("select
		graph_templates_item.id as graph_templates_item_id,
		graph_templates_item.cdef_id,
		graph_templates_item.text_format,
		graph_templates_item.value,
		graph_templates_item.hard_return,
		graph_templates_item.consolidation_function_id,
		graph_templates_item.graph_type_id,
		graph_templates_gprint.gprint_text,
		colors.hex,
		data_template_rrd.id as data_template_rrd_id,
		data_template_rrd.local_data_id,
		data_template_rrd.rrd_minimum,
		data_template_rrd.rrd_maximum,
		data_template_rrd.data_source_name,
		data_template_rrd.local_data_template_rrd_id
		from graph_templates_item
		left join data_template_rrd on graph_templates_item.task_item_id=data_template_rrd.id
		left join colors on graph_templates_item.color_id=colors.id
		left join graph_templates_gprint on graph_templates_item.gprint_id=graph_templates_gprint.id
		where graph_templates_item.local_graph_id=$local_graph_id
		order by graph_templates_item.sequence");

	/* +++++++++++++++++++++++ GRAPH OPTIONS +++++++++++++++++++++++ */

	/* define some variables */
	$scale = "";
	$rigid = "";
	$unit_exponent_value = "";
	$graph_legend = "";
	$graph_defs = "";
	$txt_graph_items = "";
	$text_padding = "";
	$greatest_text_format = 0;
	$last_graph_type = "";

		if ($graph["auto_scale"] == "on") {
		if ($graph["auto_scale_opts"] == "1") {
			$scale = "--alt-autoscale" . RRD_NL;
		}elseif ($graph["auto_scale_opts"] == "2") {
			$scale = "--alt-autoscale-max" . RRD_NL;
			$scale .= "--lower-limit=" . $graph["lower_limit"] . RRD_NL;
		}

		if ($graph["auto_scale_log"] == "on") {
			$scale .= "--logarithmic" . RRD_NL;
		}
	}else{
		$scale =  "--upper-limit=" . $graph["upper_limit"] . RRD_NL;
		$scale .= "--lower-limit=" . $graph["lower_limit"] . RRD_NL;
	}

	if ($graph["auto_scale_rigid"] == "on") {
		$rigid = "--rigid" . RRD_NL;
	}

	if (!empty($graph["unit_value"])) {
		$unit_value = "--unit=" . $graph["unit_value"] . RRD_NL;
	}

	if (ereg("^[0-9]+$", $graph["unit_exponent_value"])) {
		$unit_exponent_value = "--units-exponent=" . $graph["unit_exponent_value"] . RRD_NL;
	}

	/*
	 * optionally you can specify and array that overrides some of the db's values, lets set
	 * that all up here
	 */

	/* override: graph start time */
	if ((!isset($graph_data_array["graph_start"])) || ($graph_data_array["graph_start"] == "0")) {
		$graph_start = -($rra["timespan"]);
	}else{
		$graph_start = $graph_data_array["graph_start"];
	}

	/* override: graph end time */
	if ((!isset($graph_data_array["graph_end"])) || ($graph_data_array["graph_end"] == "0")) {
		$graph_end = -($seconds_between_graph_updates);
	}else{
		$graph_end = $graph_data_array["graph_end"];
	}

	/* override: graph height (in pixels) */
	if (isset($graph_data_array["graph_height"])) {
		$graph_height = $graph_data_array["graph_height"];
	}else{
		$graph_height = $graph["height"];
	}

	/* override: graph width (in pixels) */
	if (isset($graph_data_array["graph_width"])) {
		$graph_width = $graph_data_array["graph_width"];
	}else{
		$graph_width = $graph["width"];
	}

	/* override: skip drawing the legend? */
	if (isset($graph_data_array["graph_nolegend"])) {
		$graph_legend = "--no-legend" . RRD_NL;
	}else{
		$graph_legend = "";
	}

	/* export options */
	if (isset($graph_data_array["export"])) {
		$graph_opts = read_config_option("path_html_export") . "/" . $graph_data_array["export_filename"] . RRD_NL;
	}else{
		if (empty($graph_data_array["output_filename"])) {
				$graph_opts = "-" . RRD_NL;
		}else{
			$graph_opts = $graph_data_array["output_filename"] . RRD_NL;
		}
	}

	/* setup date format */
	$date_fmt = read_graph_config_option("default_date_format");
	$datechar = read_graph_config_option("default_datechar");

	if ($datechar == GDC_HYPHEN) {
		$datechar = "-";
	}else {
		$datechar = "/";
	}

	switch ($date_fmt) {
		case GD_MO_D_Y:
			$graph_date = "m" . $datechar . "d" . $datechar . "Y H:i:s";
			break;
		case GD_MN_D_Y:
			$graph_date = "M" . $datechar . "d" . $datechar . "Y H:i:s";
			break;
		case GD_D_MO_Y:
			$graph_date = "d" . $datechar . "m" . $datechar . "Y H:i:s";
			break;
		case GD_D_MN_Y:
			$graph_date = "d" . $datechar . "M" . $datechar . "Y H:i:s";
			break;
		case GD_Y_MO_D:
			$graph_date = "Y" . $datechar . "m" . $datechar . "d H:i:s";
			break;
		case GD_Y_MN_D:
			$graph_date = "Y" . $datechar . "M" . $datechar . "d H:i:s";
			break;
	}

	/* display the timespan for zoomed graphs */
	if ((isset($graph_data_array["graph_start"])) && (isset($graph_data_array["graph_end"]))) {
		if (($graph_data_array["graph_start"] < 0) && ($graph_data_array["graph_end"] < 0)) {
			$graph_legend .= "COMMENT:\"From " . date($graph_date, time()+$graph_data_array["graph_start"]) . " To " . date($graph_date, time()+$graph_data_array["graph_end"]) . "\\c\"" . RRD_NL . "COMMENT:\"\\n\"" . RRD_NL;
		}else if (($graph_data_array["graph_start"] >= 0) && ($graph_data_array["graph_end"] >= 0)) {
			$graph_legend .= "COMMENT:\"From " . date($graph_date, $graph_data_array["graph_start"]) . " To " . date($graph_date, $graph_data_array["graph_end"]) . "\\c\"" . RRD_NL . "COMMENT:\"\\n\"" . RRD_NL;
		}
	}

	/* basic graph options */
	$graph_opts .=
		"--imgformat=" . $image_types{$graph["image_format_id"]} . RRD_NL .
		"--start=$graph_start" . RRD_NL .
		"--end=$graph_end" . RRD_NL .
		"--title=\"" . $graph["title_cache"] . "\"" . RRD_NL .
		"$rigid" .
		"--base=" . $graph["base_value"] . RRD_NL .
		"--height=$graph_height" . RRD_NL .
		"--width=$graph_width" . RRD_NL .
		"$scale" .
		"$unit_exponent_value" .
		"$graph_legend" .
		"--vertical-label=\"" . $graph["vertical_label"] . "\"" . RRD_NL;

	$i = 0;
	if (sizeof($graph_items > 0)) {
	foreach ($graph_items as $graph_item) {
		if ((ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_item["graph_type_id"]})) && ($graph_item["data_source_name"] != "")) {
			/* use a user-specified ds path if one is entered */
			$data_source_path = get_data_source_path($graph_item["local_data_id"], true);

			/* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
			$data_source_path = str_replace(":", "\:", $data_source_path);

			if (!empty($data_source_path)) {
				/* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
				to a function that matches the digits with letters. rrdtool likes letters instead
				of numbers in DEF names; especially with CDEF's. cdef's are created
				the same way, except a 'cdef' is put on the beginning of the hash */
				$graph_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=\"$data_source_path\":" . $graph_item["data_source_name"] . ":" . $consolidation_functions{$graph_item["consolidation_function_id"]} . RRD_NL;

				//print "ds: " . $graph_item["data_template_rrd_id"] . "<br>";
				$cf_ds_cache{$graph_item["data_template_rrd_id"]}{$graph_item["consolidation_function_id"]} = "$i";

				$i++;
			}
		}

		/* +++++++++++++++++++++++ LEGEND: TEXT SUBSITUTION (<>'s) +++++++++++++++++++++++ */

		/* note the current item_id for easy access */
		$graph_item_id = $graph_item["graph_templates_item_id"];

		/* the following fields will be searched for graph variables */
		$variable_fields = array(
			"text_format" => array(
				"process_no_legend" => false
				),
			"value" => array(
				"process_no_legend" => true
				)
			);

		/* loop through each field that we want to substitute values for:
		currently: text format and value */
		while (list($field_name, $field_array) = each($variable_fields)) {
			/* certain fields do not require values when the legend is not to be shown */
			if (($field_array["process_no_legend"] == false) && (isset($graph_data_array["graph_nolegend"]))) {
				continue;
			}

			$graph_variables[$field_name][$graph_item_id] = $graph_item[$field_name];

			/* date/time substitution */
			if (strstr($graph_variables[$field_name][$graph_item_id], "|date_time|")) {
				$graph_variables[$field_name][$graph_item_id] = str_replace("|date_time|", date('D d M H:i:s T Y', strtotime(db_fetch_cell("select value from settings where name='date'"))), $graph_variables[$field_name][$graph_item_id]);
			}

			/* data query variables */
			if (preg_match("/\|query_[a-zA-Z0-9_]+\|/", $graph_variables[$field_name][$graph_item_id])) {
				/* default to the graph data query information from the graph */
				if (empty($graph_item["local_data_id"])) {
					$graph_variables[$field_name][$graph_item_id] = substitute_snmp_query_data($graph_variables[$field_name][$graph_item_id], $graph["host_id"], $graph["snmp_query_id"], $graph["snmp_index"]);
				/* use the data query information from the data source if possible */
				}else{
					$data_local = db_fetch_row("select snmp_index,snmp_query_id,host_id from data_local where id='" . $graph_item["local_data_id"] . "'");
					$graph_variables[$field_name][$graph_item_id] = substitute_snmp_query_data($graph_variables[$field_name][$graph_item_id], $data_local["host_id"], $data_local["snmp_query_id"], $data_local["snmp_index"]);
				}
			}

			/* 95th percentile */
			if (preg_match_all("/\|95:(bits|bytes):(\d):(current|total|max)(:(\d))?\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
				foreach ($matches as $match) {
					$graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_ninety_fifth_percentile($match, $graph_item, $graph_items, $graph_start, $graph_end), $graph_variables[$field_name][$graph_item_id]);
				}
			}

			/* bandwidth summation */
			if (preg_match_all("/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
				foreach ($matches as $match) {
					$graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_bandwidth_summation($match, $graph_item, $graph_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $graph_variables[$field_name][$graph_item_id]);
				}
			}
		}

		/* if we are not displaying a legend there is no point in us even processing the auto padding,
		text format stuff. */
		if (!isset($graph_data_array["graph_nolegend"])) {
			/* set hard return variable if selected (\n) */
			if ($graph_item["hard_return"] == "on") {
				$hardreturn[$graph_item_id] = "\\n";
			}else{
				$hardreturn[$graph_item_id] = "";
			}

			/* +++++++++++++++++++++++ LEGEND: AUTO PADDING (<>'s) +++++++++++++++++++++++ */

			/* PADDING: remember this is not perfect! its main use is for the basic graph setup of:
			AREA - GPRINT-CURRENT - GPRINT-AVERAGE - GPRINT-MAXIMUM \n
			of course it can be used in other situations, however may not work as intended.
			If you have any additions to this small peice of code, feel free to send them to me. */
			if ($graph["auto_padding"] == "on") {
				/* only applies to AREA and STACK */
				if (ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_item["graph_type_id"]})) {
					$text_format_lengths{$graph_item["data_template_rrd_id"]} = strlen($graph_variables["text_format"][$graph_item_id]);

					if ((strlen($graph_variables["text_format"][$graph_item_id]) > $greatest_text_format) && ($graph_item_types{$graph_item["graph_type_id"]} != "COMMENT")) {
						$greatest_text_format = strlen($graph_variables["text_format"][$graph_item_id]);
					}
				}
			}
		}
	}
	}

	/* +++++++++++++++++++++++ GRAPH ITEMS: CDEF's +++++++++++++++++++++++ */

	$i = 0;
	reset($graph_items);

	if (sizeof($graph_items) > 0) {
	foreach ($graph_items as $graph_item) {
		/* first we need to check if there is a DEF for the current data source/cf combination. if so,
		we will use that */
		if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}{$graph_item["consolidation_function_id"]})) {
			$cf_id = $graph_item["consolidation_function_id"];
		}else{
		/* if there is not a DEF defined for the current data source/cf combination, then we will have to
		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
			if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[1])) {
				$cf_id = 1; /* CF: AVERAGE */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[3])) {
				$cf_id = 3; /* CF: MAX */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[2])) {
				$cf_id = 2; /* CF: MIN */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[4])) {
				$cf_id = 4; /* CF: LAST */
			}else{
				$cf_id = 1; /* CF: AVERAGE */
			}
		}

		/* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
		data source of global cdef, but is unique when those two variables combine. */
		$cdef_graph_defs = ""; $cdef_total_ds = ""; $cdef_similar_ds = "";

		if ((!empty($graph_item["cdef_id"])) && (!isset($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]))) {
			$cdef_string = get_cdef($graph_item["cdef_id"]);

			/* create cdef string for "total all data sources" if requested */
			if (ereg("ALL_DATA_SOURCES_(NO)?DUPS", $cdef_string)) {
				$item_count = 0;
				for ($t=0;($t<count($graph_items));$t++) {
					if ((ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_items[$t]["graph_type_id"]})) && (!empty($graph_items[$t]["data_template_rrd_id"]))) {
						/* if the user screws up CF settings, PHP will generate warnings if left unchecked */
						if (isset($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id])) {
							$def_name = generate_graph_def_name(strval($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id]));
							$cdef_total_ds .= ($item_count == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
							$item_count++;
						}
					}
				}

				/* if there is only one item to total, don't even bother with the summation. otherwise
				cdef=a,b,c,+,+ is fine. */
				if ($item_count > 1) {
					$cdef_total_ds .= str_repeat(",+", ($item_count - 2)) . ",+";
				}
			}

			/* create cdef string for "total similar data sources" if requested */
			if (ereg("SIMILAR_DATA_SOURCES_(NO)?DUPS", $cdef_string) ) {
				$sources_seen = array();
				$item_count = 0;

				for ($t=0;($t<count($graph_items));$t++) {
					if ((ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_items[$t]["graph_type_id"]})) && (!empty($graph_items[$t]["data_template_rrd_id"])) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) && ($graph_item["graph_templates_item_id"] != $graph_items[$t]["graph_templates_item_id"])) {
						/* if the user screws up CF settings, PHP will generate warnings if left unchecked */
						if (isset($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id]) && (!isset($sources_seen{$graph_items[$t]["data_template_rrd_id"]}))) {
							$def_name = generate_graph_def_name(strval($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id]));
							$cdef_similar_ds .= ($item_count == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
							$sources_seen{$graph_items[$t]["data_template_rrd_id"]} = 1;
							$item_count++;
						}
					}
				}

				/* if there is only one item to total, don't even bother with the summation. otherwise
				cdef=a,b,c,+,+ is fine. */
				if ($item_count > 1) {
					$cdef_similar_ds .= str_repeat(",+", ($item_count - 2)) . ",+";
				}
			}

			$cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval((isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]) ? $cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id] : "0"))), $cdef_string);
			$cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $cdef_total_ds, $cdef_string);
			$cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $cdef_similar_ds, $cdef_string);

			/* data source item variables */
			$cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", (empty($graph_item["rrd_minimum"]) ? "0" : $graph_item["rrd_minimum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", (empty($graph_item["rrd_maximum"]) ? "0" : $graph_item["rrd_maximum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", (empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", (empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"]), $cdef_string);

			/* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
			$cdef_graph_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
			$cdef_graph_defs .= $cdef_string;
			$cdef_graph_defs .= " \\\n";

			/* the CDEF cache is so we do not create duplicate CDEF's on a graph */
			$cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id] = "$i";
		}

		/* add the cdef string to the end of the def string */
		$graph_defs .= $cdef_graph_defs;

		/* note the current item_id for easy access */
		$graph_item_id = $graph_item["graph_templates_item_id"];

		/* if we are not displaying a legend there is no point in us even processing the auto padding,
		text format stuff. */
		if ((!isset($graph_data_array["graph_nolegend"])) && ($graph["auto_padding"] == "on") && (isset($text_format_lengths{$graph_item["data_template_rrd_id"]}))) {
			/* we are basing how much to pad on area and stack text format,
			not gprint. but of course the padding has to be displayed in gprint,
			how fun! */

			$pad_number = ($greatest_text_format - $text_format_lengths{$graph_item["data_template_rrd_id"]});
			//cacti_log("MAX: $greatest_text_format, CURR: $text_format_lengths[$item_dsid], DSID: $item_dsid");
			$text_padding = str_pad("", $pad_number);

			/* two GPRINT's in a row screws up the padding, lets not do that */
			if (($graph_item_types{$graph_item["graph_type_id"]} == "GPRINT") && ($last_graph_type == "GPRINT")) {
				$text_padding = "";
			}

			$last_graph_type = $graph_item_types{$graph_item["graph_type_id"]};
		}

		/* we put this in a variable so it can be manipulated before mainly used
		if we want to skip it, like below */
		$current_graph_item_type = $graph_item_types{$graph_item["graph_type_id"]};

		/* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
		to this graph item */
		if ($graph_item["cdef_id"] == "0") {
			if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id])) {
				$data_source_name = generate_graph_def_name(strval($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]));
			}else{
				$data_source_name = "";
			}
		}else{
			$data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]));
		}

		/* to make things easier... if there is no text format set; set blank text */
		if (!isset($graph_variables["text_format"][$graph_item_id])) {
			$graph_variables["text_format"][$graph_item_id] = "";
		}

		if (!isset($hardreturn[$graph_item_id])) {
			$hardreturn[$graph_item_id] = "";
		}

		/* +++++++++++++++++++++++ GRAPH ITEMS +++++++++++++++++++++++ */

		/* most of the calculations have been done above. now we have for print everything out
		in an RRDTool-friendly fashion */
		if (ereg("^(AREA|STACK|LINE[123])$", $graph_item_types{$graph_item["graph_type_id"]})) {
			$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
			$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . "#" . $graph_item["hex"] . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
		}elseif ($graph_item_types{$graph_item["graph_type_id"]} == "COMMENT") {
			$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
		}elseif (($graph_item_types{$graph_item["graph_type_id"]} == "GPRINT") && (!isset($graph_data_array["graph_nolegend"]))) {
			$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
			$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . ":" . $consolidation_functions{$graph_item["consolidation_function_id"]} . ":\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
		}elseif ($graph_item_types{$graph_item["graph_type_id"]} == "HRULE") {
			$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
			$graph_variables["value"][$graph_item_id] = str_replace(":", "\:", $graph_variables["value"][$graph_item_id]); /* escape colons */
			$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $graph_variables["value"][$graph_item_id] . "#" . $graph_item["hex"] . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
		}elseif ($graph_item_types{$graph_item["graph_type_id"]} == "VRULE") {
			$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */

			$value_array = explode(":", $graph_item["value"]);

			if ($value_array[0] < 0) {
				$value = date("U") - (-3600 * $value_array[0]) - 60 * $value_array[1];
			}else{
				$value = date("U", mktime($value_array[0],$value_array[1],0));
			}

			$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $value . "#" . $graph_item["hex"] . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
		}

		$i++;

		if ($i < sizeof($graph_items)) {
			$txt_graph_items .= RRD_NL;
		}
	}
	}

	/* either print out the source or pass the source onto rrdtool to get us a nice PNG */
	if (isset($graph_data_array["print_source"])) {
		print "<PRE>" . read_config_option("path_rrdtool") . " graph $graph_opts$graph_defs$txt_graph_items</PRE>";
	}else{
		if (isset($graph_data_array["export"])) {
			rrdtool_execute("graph $graph_opts$graph_defs$txt_graph_items", false, RRDTOOL_OUTPUT_NULL, $rrd_struc);
			return 0;
		}else{
			if (isset($graph_data_array["output_flag"])) {
				$output_flag = $graph_data_array["output_flag"];
			}else{
				$output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
			}

			return rrdtool_execute("graph $graph_opts$graph_defs$txt_graph_items", false, $output_flag, $rrd_struc);
		}
	}
}
示例#2
0
function api_poller_cache_item_add($host_id, $host_field_override, $local_data_id, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = "", $arg2 = "", $arg3 = "")
{
    $host = db_fetch_row("select\n\t\thost.id,\n\t\thost.hostname,\n\t\thost.snmp_community,\n\t\thost.snmp_version,\n\t\thost.snmp_username,\n\t\thost.snmp_password,\n\t\thost.snmp_port,\n\t\thost.snmp_timeout,\n\t\thost.disabled\n\t\tfrom host\n\t\twhere host.id={$host_id}");
    /* the $host_field_override array can be used to override certain host fields in the poller cache */
    if (isset($host)) {
        $host = array_merge($host, $host_field_override);
    }
    if (isset($host["id"]) || isset($host_id)) {
        if (isset($host)) {
            if ($host["disabled"] == "on") {
                return true;
            }
        } else {
            if ($poller_action_id == 0) {
                return true;
            }
            $host["id"] = 0;
            $host["snmp_community"] = "";
            $host["snmp_timeout"] = "";
            $host["snmp_username"] = "";
            $host["snmp_password"] = "";
            $host["snmp_version"] = "";
            $host["snmp_port"] = "";
            $host["hostname"] = "None";
        }
        if ($poller_action_id == 0) {
            if ($host["snmp_version"] < 1 || $host["snmp_version"] > 3 || $host["snmp_community"] == "" && $host["snmp_version"] != 3) {
                return true;
            }
        }
        return db_execute("insert into poller_item (local_data_id,host_id,action,hostname,\n\t\t\tsnmp_community,snmp_version,snmp_timeout,snmp_username,snmp_password,snmp_port,rrd_name,rrd_path,\n\t\t\trrd_num,arg1,arg2,arg3) values ({$local_data_id}," . $host["id"] . ",{$poller_action_id},'" . $host["hostname"] . "',\n\t\t\t'" . $host["snmp_community"] . "','" . $host["snmp_version"] . "','" . $host["snmp_timeout"] . "',\n\t\t\t'" . $host["snmp_username"] . "','" . $host["snmp_password"] . "','" . $host["snmp_port"] . "',\n\t\t\t'{$data_source_item_name}','" . addslashes(clean_up_path(get_data_source_path($local_data_id, true))) . "',\n\t\t\t'{$num_rrd_items}','{$arg1}','{$arg2}','{$arg3}')");
    }
}
示例#3
0
function api_poller_cache_item_add($host_id, $host_field_override, $local_data_id, $rrd_step, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = '', $arg2 = '', $arg3 = '')
{
    static $hosts = array();
    if (!isset($hosts[$host_id])) {
        $host = db_fetch_row_prepared('SELECT
		host.id,
		host.hostname,
		host.snmp_community,
		host.snmp_version,
		host.snmp_username,
		host.snmp_password,
		host.snmp_auth_protocol,
		host.snmp_priv_passphrase,
		host.snmp_priv_protocol,
		host.snmp_context,
		host.snmp_port,
		host.snmp_timeout,
		host.disabled
		FROM host
		WHERE host.id = ?', array($host_id));
        $hosts[$host_id] = $host;
    } else {
        $host = $hosts[$host_id];
    }
    /* the $host_field_override array can be used to override certain host fields in the poller cache */
    if (isset($host)) {
        $host = array_merge($host, $host_field_override);
    }
    if (isset($host['id']) || isset($host_id)) {
        if (isset($host)) {
            if ($host['disabled'] == 'on') {
                return;
            }
        } else {
            if ($poller_action_id == 0) {
                return;
            }
            $host['id'] = 0;
            $host['snmp_community'] = '';
            $host['snmp_timeout'] = '';
            $host['snmp_username'] = '';
            $host['snmp_password'] = '';
            $host['snmp_auth_protocol'] = '';
            $host['snmp_priv_passphrase'] = '';
            $host['snmp_priv_protocol'] = '';
            $host['snmp_context'] = '';
            $host['snmp_version'] = '';
            $host['snmp_port'] = '';
            $host['hostname'] = 'None';
        }
        if ($poller_action_id == 0) {
            if ($host['snmp_version'] < 1 || $host['snmp_version'] > 3 || $host['snmp_community'] == '' && $host['snmp_version'] != 3) {
                return;
            }
        }
        $rrd_next_step = api_poller_get_rrd_next_step($rrd_step, $num_rrd_items);
        return "({$local_data_id}, " . '0, ' . $host['id'] . ", {$poller_action_id}," . db_qstr($host['hostname']) . ",\n\t\t\t" . db_qstr($host['snmp_community']) . ', ' . db_qstr($host['snmp_version']) . ', ' . db_qstr($host['snmp_timeout']) . ",\n\t\t\t" . db_qstr($host['snmp_username']) . ', ' . db_qstr($host['snmp_password']) . ', ' . db_qstr($host['snmp_auth_protocol']) . ",\n\t\t\t" . db_qstr($host['snmp_priv_passphrase']) . ', ' . db_qstr($host['snmp_priv_protocol']) . ', ' . db_qstr($host['snmp_context']) . ",\n\t\t\t" . db_qstr($host['snmp_port']) . ', ' . db_qstr($data_source_item_name) . ', ' . db_qstr(clean_up_path(get_data_source_path($local_data_id, true))) . ",\n\t\t\t" . db_qstr($num_rrd_items) . ', ' . db_qstr($rrd_step) . ', ' . db_qstr($rrd_next_step) . ', ' . db_qstr($arg1) . ', ' . db_qstr($arg2) . ', ' . db_qstr($arg3) . ", '1')";
    }
}
示例#4
0
function api_poller_cache_item_add($host_id, $host_field_override, $local_data_id, $rrd_step, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = "", $arg2 = "", $arg3 = "")
{
    global $cnn_id;
    static $hosts = array();
    if (!isset($hosts[$host_id])) {
        $host = db_fetch_row("select\n\t\thost.id,\n\t\thost.hostname,\n\t\thost.snmp_community,\n\t\thost.snmp_version,\n\t\thost.snmp_username,\n\t\thost.snmp_password,\n\t\thost.snmp_auth_protocol,\n\t\thost.snmp_priv_passphrase,\n\t\thost.snmp_priv_protocol,\n\t\thost.snmp_context,\n\t\thost.snmp_port,\n\t\thost.snmp_timeout,\n\t\thost.disabled\n\t\tfrom host\n\t\twhere host.id={$host_id}");
        $hosts[$host_id] = $host;
    } else {
        $host = $hosts[$host_id];
    }
    /* the $host_field_override array can be used to override certain host fields in the poller cache */
    if (isset($host)) {
        $host = array_merge($host, $host_field_override);
    }
    if (isset($host["id"]) || isset($host_id)) {
        if (isset($host)) {
            if ($host["disabled"] == "on") {
                return;
            }
        } else {
            if ($poller_action_id == 0) {
                return;
            }
            $host["id"] = 0;
            $host["snmp_community"] = "";
            $host["snmp_timeout"] = "";
            $host["snmp_username"] = "";
            $host["snmp_password"] = "";
            $host["snmp_auth_protocol"] = "";
            $host["snmp_priv_passphrase"] = "";
            $host["snmp_priv_protocol"] = "";
            $host["snmp_context"] = "";
            $host["snmp_version"] = "";
            $host["snmp_port"] = "";
            $host["hostname"] = "None";
        }
        if ($poller_action_id == 0) {
            if ($host["snmp_version"] < 1 || $host["snmp_version"] > 3 || $host["snmp_community"] == "" && $host["snmp_version"] != 3) {
                return;
            }
        }
        $rrd_next_step = api_poller_get_rrd_next_step($rrd_step, $num_rrd_items);
        return "({$local_data_id}, " . "0, " . $host["id"] . ", {$poller_action_id}," . $cnn_id->qstr($host["hostname"]) . ",\n\t\t\t" . $cnn_id->qstr($host["snmp_community"]) . ", " . $cnn_id->qstr($host["snmp_version"]) . ", " . $cnn_id->qstr($host["snmp_timeout"]) . ",\n\t\t\t" . $cnn_id->qstr($host["snmp_username"]) . ", " . $cnn_id->qstr($host["snmp_password"]) . ", " . $cnn_id->qstr($host["snmp_auth_protocol"]) . ",\n\t\t\t" . $cnn_id->qstr($host["snmp_priv_passphrase"]) . ", " . $cnn_id->qstr($host["snmp_priv_protocol"]) . ", " . $cnn_id->qstr($host["snmp_context"]) . ",\n\t\t\t" . $cnn_id->qstr($host["snmp_port"]) . ", " . $cnn_id->qstr($data_source_item_name) . ", " . $cnn_id->qstr(clean_up_path(get_data_source_path($local_data_id, true))) . ",\n\t\t\t" . $cnn_id->qstr($num_rrd_items) . ", " . $cnn_id->qstr($rrd_step) . ", " . $cnn_id->qstr($rrd_next_step) . ", " . $cnn_id->qstr($arg1) . ", " . $cnn_id->qstr($arg2) . ", " . $cnn_id->qstr($arg3) . ", '1')";
    }
}
示例#5
0
function api_poller_cache_item_add($host_id, $host_field_override, $local_data_id, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = "", $arg2 = "", $arg3 = "") {
	$host = db_fetch_row("select
		host.id,
		host.hostname,
		host.snmp_community,
		host.snmp_version,
		host.snmp_username,
		host.snmp_password,
		host.snmp_port,
		host.snmp_timeout,
		host.disabled
		from host
		where host.id=$host_id");

	/* the $host_field_override array can be used to override certain host fields in the poller cache */
	if (isset($host)) {
		$host = array_merge($host, $host_field_override);
	}

	if (isset($host["id"]) || (isset($host_id))) {
		if (isset($host)) {
			if ($host["disabled"] == "on") {
				return true;
			}
		} else {
			$host["id"] = 0;
			$host["snmp_community"] = "";
			$host["snmp_timeout"] = "";
			$host["snmp_username"] = "";
			$host["snmp_password"] = "";
			$host["snmp_version"] = "";
			$host["snmp_port"] = "";
			$host["hostname"] = "None";
		}

		return db_execute("insert into poller_item (local_data_id,host_id,action,hostname,
			snmp_community,snmp_version,snmp_timeout,snmp_username,snmp_password,snmp_port,rrd_name,rrd_path,
			rrd_num,arg1,arg2,arg3) values ($local_data_id," . $host["id"] . ",$poller_action_id,'" . $host["hostname"] . "',
			'" . $host["snmp_community"] . "','" . $host["snmp_version"] . "','" . $host["snmp_timeout"] . "',
			'" . $host["snmp_username"] . "','" . $host["snmp_password"] . "','" . $host["snmp_port"] . "',
			'$data_source_item_name','" . addslashes(clean_up_path(get_data_source_path($local_data_id, true))) . "',
			'$num_rrd_items','$arg1','$arg2','$arg3')");
	}
}
示例#6
0
function errorimage_check_graphs()
{
    global $config;
    $local_graph_id = $_GET['local_graph_id'];
    $graph_items = db_fetch_assoc("select\r\n\t\tdata_template_rrd.local_data_id\r\n\t\tfrom graph_templates_item\r\n\t\tleft join data_template_rrd on (graph_templates_item.task_item_id=data_template_rrd.id)\r\n\t\twhere graph_templates_item.local_graph_id={$local_graph_id}\r\n\t\torder by graph_templates_item.sequence");
    $ids = array();
    foreach ($graph_items as $graph) {
        if ($graph['local_data_id'] != '') {
            $ids[] = $graph['local_data_id'];
        }
    }
    $ids = array_unique($ids);
    if (!empty($_GET["graph_nolegend"])) {
        $height = read_graph_config_option("default_height") + 62;
        $width = read_graph_config_option("default_width") + 95;
    } else {
        $hw = db_fetch_row("SELECT width, height \r\n\t\t\tFROM graph_templates_graph \r\n\t\t\tWHERE local_graph_id=" . $_GET['local_graph_id']);
        $hr = db_fetch_cell("SELECT count(*) FROM graph_templates_item WHERE local_graph_id=" . $_GET['local_graph_id'] . " AND hard_return='on'");
        $height = $hw['height'] + 16 * $hr + 90;
        // # hard rules, plus room for date
        $width = $hw['width'] + 95;
    }
    foreach ($ids as $id => $local_data_id) {
        $data_source_path = get_data_source_path($local_data_id, true);
        if (!file_exists($data_source_path)) {
            $filename = $config['base_path'] . '/plugins/errorimage/images/no-datasource.png';
            if (function_exists("imagecreatefrompng")) {
                echo errorimage_resize_png($filename, $width, $height);
            } else {
                $file = fopen($filename, 'rb');
                echo fread($file, filesize($filename));
                fclose($file);
            }
            exit;
        }
    }
}
示例#7
0
function api_poller_cache_item_add($host_id, $host_field_override, $local_data_id, $rrd_step, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = "", $arg2 = "", $arg3 = "") {
	$host = db_fetch_row("select
		host.id,
		host.hostname,
		host.snmp_community,
		host.snmp_version,
		host.snmp_username,
		host.snmp_password,
		host.snmp_auth_protocol,
		host.snmp_priv_passphrase,
		host.snmp_priv_protocol,
		host.snmp_context,
		host.snmp_port,
		host.snmp_timeout,
		host.disabled
		from host
		where host.id=$host_id");

	/* the $host_field_override array can be used to override certain host fields in the poller cache */
	if (isset($host)) {
		$host = array_merge($host, $host_field_override);
	}

	if (isset($host["id"]) || (isset($host_id))) {
		if (isset($host)) {
			if ($host["disabled"] == "on") {
				return true;
			}
		} else {
			if ($poller_action_id == 0) {
				return true;
			}

			$host["id"] = 0;
			$host["snmp_community"] = "";
			$host["snmp_timeout"] = 0;
			$host["snmp_username"] = "";
			$host["snmp_password"] = "";
			$host["snmp_auth_protocol"] = "";
			$host["snmp_priv_passphrase"] = "";
			$host["snmp_priv_protocol"] = "";
			$host["snmp_context"] = "";
			$host["snmp_version"] = 0;
			$host["snmp_port"] = 161;
			$host["hostname"] = "None";
		}

		if ($poller_action_id == 0) {
			if (($host["snmp_version"] < 1) || ($host["snmp_version"] > 3) ||
				($host["snmp_community"] == "" && $host["snmp_version"] != 3)) {
				return true;
			}
		}

		$rrd_next_step = api_poller_get_rrd_next_step($rrd_step, $num_rrd_items);

		return db_execute("INSERT INTO poller_item (local_data_id, host_id, action,hostname,
			snmp_community, snmp_version, snmp_timeout, snmp_username, snmp_password,
			snmp_auth_protocol, snmp_priv_passphrase, snmp_priv_protocol, snmp_context, snmp_port, rrd_name, rrd_path,
			rrd_num, rrd_step, rrd_next_step, arg1, arg2, arg3)
			VALUES
			($local_data_id, " . $host["id"] . ", $poller_action_id,'" . $host["hostname"] . "',
			'" . $host["snmp_community"]       . "', '" . $host["snmp_version"]       . "', '" . $host["snmp_timeout"] . "',
			'" . $host["snmp_username"]        . "', '" . $host["snmp_password"]      . "', '" . $host["snmp_auth_protocol"] . "',
			'" . $host["snmp_priv_passphrase"] . "', '" . $host["snmp_priv_protocol"] . "', '" . $host["snmp_context"] . "',
			'" . $host["snmp_port"]            . "', '$data_source_item_name', '"     . addslashes(clean_up_path(get_data_source_path($local_data_id, true))) . "',
			'$num_rrd_items', '$rrd_step', '$rrd_next_step', '$arg1', '$arg2', '$arg3')");
	}
}
示例#8
0
function process_poller_output_rt($rrdtool_pipe, $poller_id, $interval) {
	global $config;

	include_once($config["library_path"] . "/rrd.php");

	/* let's count the number of rrd files we processed */
	$rrds_processed = 0;

	/* create/update the rrd files */
	$results = db_fetch_assoc("SELECT
		poller_output_rt.output,
		poller_output_rt.time,
		poller_output_rt.local_data_id,
		poller_item.rrd_path,
		poller_item.rrd_name,
		poller_item.rrd_num
		FROM (poller_output_rt,poller_item)
		WHERE (poller_output_rt.local_data_id=poller_item.local_data_id
		AND poller_output_rt.rrd_name=poller_item.rrd_name)
		AND poller_output_rt.poller_id = $poller_id");

	if (sizeof($results) > 0) {
		/* create an array keyed off of each .rrd file */
		foreach ($results as $item) {
			$rt_graph_path    = read_config_option("realtime_cache_path") . "/realtime_" . $item["local_data_id"] . "_5.rrd";
			$data_source_path = get_data_source_path($item['local_data_id'], true);

			/* create rt rrd */
			if (!file_exists($rt_graph_path)) {
				/* get the syntax */
				$command = @rrdtool_function_create($item['local_data_id'], true);

				/* change permissions so that the poller can clear */
				@chmod($rt_graph_path, 0666);

				/* replace path */
				$command = str_replace($data_source_path, $rt_graph_path, $command);

				/* replace step */
				$command = preg_replace('/--step\s(\d+)/', '--step ' . $interval, $command);

				/* WIN32: before sending this command off to rrdtool, get rid
				of all of the '\' characters. Unix does not care; win32 does.
				Also make sure to replace all of the fancy \'s at the end of the line,
				but make sure not to get rid of the "\n"'s that are supposed to be
				in there (text format) */
				$command = str_replace("\\\n", " ", $command);

				/* create the rrdfile */
				shell_exec($command);
			}else{
				/* change permissions so that the poller can clear */
				@chmod($rt_graph_path, 0666);
			}

			/* now, let's update the path to keep the RRD's updated */
			$item["rrd_path"] = $rt_graph_path;

			/* cleanup the value */
			$value            = trim($item["output"]);
			$unix_time        = strtotime($item["time"]);

			$rrd_update_array{$item["rrd_path"]}["local_data_id"] = $item["local_data_id"];

			/* single one value output */
			if ((is_numeric($value)) || ($value == "U")) {
				$rrd_update_array{$item["rrd_path"]}["times"][$unix_time]{$item["rrd_name"]} = $value;
			/* multiple value output */
			}else{
				$values = explode(" ", $value);

				$rrd_field_names = array_rekey(db_fetch_assoc("SELECT
					data_template_rrd.data_source_name,
					data_input_fields.data_name
					FROM (data_template_rrd,data_input_fields)
					WHERE data_template_rrd.data_input_field_id=data_input_fields.id
					AND data_template_rrd.local_data_id=" . $item["local_data_id"]), "data_name", "data_source_name");

				for ($i=0; $i<count($values); $i++) {
					if (preg_match("/^([a-zA-Z0-9_\.-]+):([eE0-9\+\.-]+)$/", $values[$i], $matches)) {
						if (isset($rrd_field_names{$matches[1]})) {
							$rrd_update_array{$item["rrd_path"]}["times"][$unix_time]{$rrd_field_names{$matches[1]}} = $matches[2];
						}
					}
				}
			}

			/* fallback values */
			if ((!isset($rrd_update_array{$item["rrd_path"]}["times"][$unix_time])) && ($item["rrd_name"] != "")) {
				$rrd_update_array{$item["rrd_path"]}["times"][$unix_time]{$item["rrd_name"]} = "U";
			}else if ((!isset($rrd_update_array{$item["rrd_path"]}["times"][$unix_time])) && ($item["rrd_name"] == "")) {
				unset($rrd_update_array{$item["rrd_path"]});
			}
		}

		/* make sure each .rrd file has complete data */
		reset($results);
		foreach ($results as $item) {
			db_execute("DELETE FROM poller_output_rt
				WHERE local_data_id='" . $item["local_data_id"] . "'
				AND rrd_name='" . $item["rrd_name"] . "'
				AND time='" . $item["time"] . "'
				AND poller_id='" . $poller_id . "'");
		}

		$rrds_processed = rrdtool_function_update($rrd_update_array, $rrdtool_pipe);
	}

	return $rrds_processed;
}
示例#9
0
文件: rrd.php 项目: MrWnn/cacti
function rrdtool_function_graph($local_graph_id, $rra_id, $graph_data_array, $rrdtool_pipe = "", &$xport_meta = array())
{
    global $config, $consolidation_functions;
    include_once $config["library_path"] . "/cdef.php";
    include_once $config["library_path"] . "/graph_variables.php";
    include_once $config['library_path'] . '/boost.php';
    include_once $config['library_path'] . '/xml.php';
    include $config["include_path"] . "/global_arrays.php";
    /* prevent command injection
     * This function prepares an rrdtool graph statement to be executed by the web server.
     * We have to take care, that the attacker does not insert shell code.
     * As some rrdtool parameters accept "Cacti variables", we have to perform the
     * variable substitution prior to vulnerability checks.
     * We will enclose all parameters in quotes and substitute quotation marks within
     * those parameters. 
     */
    /* rrdtool fetches the default font from it's execution environment
     * you won't find that default font on the rrdtool statement itself!
     * set the rrdtool default font via environment variable */
    if (!isset($graph_data_array['export_csv'])) {
        if (read_config_option("path_rrdtool_default_font")) {
            putenv("RRD_DEFAULT_FONT=" . read_config_option("path_rrdtool_default_font"));
        }
    }
    /* before we do anything; make sure the user has permission to view this graph,
    	if not then get out */
    if (!is_graph_allowed($local_graph_id)) {
        return "GRAPH ACCESS DENIED";
    }
    /* check the boost image cache and if we find a live file there return it instead */
    if (!isset($graph_data_array['export_csv']) && !isset($graph_data_array['export_realtime'])) {
        $graph_data = boost_graph_cache_check($local_graph_id, $rra_id, $rrdtool_pipe, $graph_data_array, false);
        if ($graph_data != false) {
            return $graph_data;
        }
    }
    /* find the step and how often this graph is updated with new data */
    $ds_step = db_fetch_cell("SELECT\n\t\tdata_template_data.rrd_step\n\t\tFROM (data_template_data,data_template_rrd,graph_templates_item)\n\t\tWHERE graph_templates_item.task_item_id=data_template_rrd.id\n\t\tAND data_template_rrd.local_data_id=data_template_data.local_data_id\n\t\tAND graph_templates_item.local_graph_id={$local_graph_id}\n\t\tLIMIT 0,1");
    $ds_step = empty($ds_step) ? 300 : $ds_step;
    /* if no rra was specified, we need to figure out which one RRDTool will choose using
     * "best-fit" resolution fit algorithm */
    if (empty($rra_id)) {
        if (empty($graph_data_array["graph_start"]) || empty($graph_data_array["graph_end"])) {
            $rra["rows"] = 600;
            $rra["steps"] = 1;
            $rra["timespan"] = 86400;
        } else {
            /* get a list of RRAs related to this graph */
            $rras = get_associated_rras($local_graph_id);
            if (sizeof($rras) > 0) {
                foreach ($rras as $unchosen_rra) {
                    /* the timespan specified in the RRA "timespan" field may not be accurate */
                    $real_timespan = $ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"];
                    /* make sure the current start/end times fit within each RRA's timespan */
                    if ($graph_data_array["graph_end"] - $graph_data_array["graph_start"] <= $real_timespan && time() - $graph_data_array["graph_start"] <= $real_timespan) {
                        /* is this RRA better than the already chosen one? */
                        if (isset($rra) && $unchosen_rra["steps"] < $rra["steps"]) {
                            $rra = $unchosen_rra;
                        } else {
                            if (!isset($rra)) {
                                $rra = $unchosen_rra;
                            }
                        }
                    }
                }
            }
            if (!isset($rra)) {
                $rra["rows"] = 600;
                $rra["steps"] = 1;
            }
        }
    } else {
        $rra = db_fetch_row("SELECT timespan,rows,steps FROM rra WHERE id={$rra_id}");
    }
    if (!isset($graph_data_array['export_realtime'])) {
        $seconds_between_graph_updates = $ds_step * $rra["steps"];
    } else {
        $seconds_between_graph_updates = 5;
    }
    $graph = db_fetch_row("SELECT gl.id AS local_graph_id, gl.host_id,\n\t\tgl.snmp_query_id, gl.snmp_index, gtg.title_cache, gtg.vertical_label,\n\t\tgtg.slope_mode, gtg.auto_scale, gtg.auto_scale_opts, gtg.auto_scale_log,\n\t\tgtg.scale_log_units, gtg.auto_scale_rigid, gtg.auto_padding, gtg.base_value,\n\t\tgtg.upper_limit, gtg.lower_limit, gtg.height, gtg.width, gtg.image_format_id,\n\t\tgtg.unit_value, gtg.unit_exponent_value, gtg.export\n\t\tFROM graph_templates_graph AS gtg\n\t\tINNER JOIN graph_local AS gl\n\t\tON gl.id=gtg.local_graph_id\n\t\tWHERE gtg.local_graph_id={$local_graph_id}");
    /* lets make that sql query... */
    $graph_items = db_fetch_assoc("SELECT gti.id AS graph_templates_item_id,\n\t\tgti.cdef_id, gti.text_format, gti.value, gti.hard_return,\n\t\tgti.consolidation_function_id, gti.graph_type_id, gtgp.gprint_text,\n\t\tcolors.hex, gti.alpha, dtr.id AS data_template_rrd_id, dtr.local_data_id,\n\t\tdtr.rrd_minimum, dtr.rrd_maximum, dtr.data_source_name, dtr.local_data_template_rrd_id\n\t\tFROM graph_templates_item AS gti\n\t\tLEFT JOIN data_template_rrd AS dtr\n\t\tON gti.task_item_id=dtr.id\n\t\tLEFT JOIN colors \n\t\tON gti.color_id=colors.id\n\t\tLEFT JOIN graph_templates_gprint AS gtgp\n\t\tON gti.gprint_id=gtgp.id\n\t\tWHERE gti.local_graph_id={$local_graph_id}\n\t\tORDER BY gti.sequence");
    /* variables for use below */
    $graph_defs = "";
    $txt_graph_items = "";
    $text_padding = "";
    $padding_estimate = 0;
    $last_graph_type = "";
    /* override: graph start time */
    if (!isset($graph_data_array["graph_start"]) || $graph_data_array["graph_start"] == "0") {
        $graph_start = -$rra["timespan"];
    } else {
        $graph_start = $graph_data_array["graph_start"];
    }
    /* override: graph end time */
    if (!isset($graph_data_array["graph_end"]) || $graph_data_array["graph_end"] == "0") {
        $graph_end = -$seconds_between_graph_updates;
    } else {
        $graph_end = $graph_data_array["graph_end"];
    }
    /* +++++++++++++++++++++++ GRAPH OPTIONS +++++++++++++++++++++++ */
    if (!isset($graph_data_array['export_csv'])) {
        $graph_opts = rrd_function_process_graph_options($graph_start, $graph_end, $graph, $graph_data_array);
    } else {
        /* basic export options */
        $graph_opts = "--start=" . cacti_escapeshellarg($graph_start) . RRD_NL . "--end=" . cacti_escapeshellarg($graph_end) . RRD_NL . "--maxrows=10000" . RRD_NL;
    }
    /* +++++++++++++++++++++++ LEGEND: MAGIC +++++++++++++++++++++++ */
    $i = 0;
    $j = 0;
    $last_graph_cf = array();
    if (sizeof($graph_items)) {
        /* we need to add a new column "cf_reference", so unless PHP 5 is used, this foreach syntax is required */
        foreach ($graph_items as $key => $graph_item) {
            /* mimic the old behavior: LINE[123], AREA and STACK items use the CF specified in the graph item */
            if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_STACK) {
                $graph_cf = $graph_item["consolidation_function_id"];
                /* remember the last CF for this data source for use with GPRINT
                 * if e.g. an AREA/AVERAGE and a LINE/MAX is used
                 * we will have AVERAGE first and then MAX, depending on GPRINT sequence */
                $last_graph_cf["data_source_name"]["local_data_template_rrd_id"] = $graph_cf;
                /* remember this for second foreach loop */
                $graph_items[$key]["cf_reference"] = $graph_cf;
            } elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT) {
                /* ATTENTION!
                 * the "CF" given on graph_item edit screen for GPRINT is indeed NOT a real "CF",
                 * but an aggregation function
                 * see "man rrdgraph_data" for the correct VDEF based notation
                 * so our task now is to "guess" the very graph_item, this GPRINT is related to
                 * and to use that graph_item's CF */
                if (isset($last_graph_cf["data_source_name"]["local_data_template_rrd_id"])) {
                    $graph_cf = $last_graph_cf["data_source_name"]["local_data_template_rrd_id"];
                    /* remember this for second foreach loop */
                    $graph_items[$key]["cf_reference"] = $graph_cf;
                } else {
                    $graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
                    /* remember this for second foreach loop */
                    $graph_items[$key]["cf_reference"] = $graph_cf;
                }
            } else {
                /* all other types are based on the best matching CF */
                $graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
                /* remember this for second foreach loop */
                $graph_items[$key]["cf_reference"] = $graph_cf;
            }
            if (!empty($graph_item["local_data_id"]) && !isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$graph_cf])) {
                /* use a user-specified ds path if one is entered */
                if (isset($graph_data_array['export_realtime'])) {
                    $data_source_path = read_config_option("realtime_cache_path") . "/user_" . session_id() . "_" . $graph_item["local_data_id"] . ".rrd";
                } else {
                    $data_source_path = get_data_source_path($graph_item["local_data_id"], true);
                }
                /* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
                $data_source_path = str_replace(":", "\\:", $data_source_path);
                if (!empty($data_source_path)) {
                    /* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
                    			to a function that matches the digits with letters. rrdtool likes letters instead
                    			of numbers in DEF names; especially with CDEF's. cdef's are created
                    			the same way, except a 'cdef' is put on the beginning of the hash */
                    $graph_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=" . cacti_escapeshellarg($data_source_path) . ":" . cacti_escapeshellarg($graph_item["data_source_name"], true) . ":" . $consolidation_functions[$graph_cf] . RRD_NL;
                    $cf_ds_cache[$graph_item["data_template_rrd_id"]][$graph_cf] = "{$i}";
                    $i++;
                }
            }
            /* cache cdef value here to support data query variables in the cdef string */
            if (empty($graph_item["cdef_id"])) {
                $graph_item["cdef_cache"] = "";
                $graph_items[$j]["cdef_cache"] = "";
            } else {
                $graph_item["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
                $graph_items[$j]["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
            }
            /* +++++++++++++++++++++++ LEGEND: TEXT SUBSTITUTION (<>'s) +++++++++++++++++++++++ */
            /* note the current item_id for easy access */
            $graph_item_id = $graph_item["graph_templates_item_id"];
            /* the following fields will be searched for graph variables */
            $variable_fields = array("text_format" => array("process_no_legend" => false), "value" => array("process_no_legend" => true), "cdef_cache" => array("process_no_legend" => true));
            /* loop through each field that we want to substitute values for:
            			currently: text format and value */
            while (list($field_name, $field_array) = each($variable_fields)) {
                /* certain fields do not require values when the legend is not to be shown */
                if ($field_array["process_no_legend"] == false && isset($graph_data_array["graph_nolegend"])) {
                    continue;
                }
                $graph_variables[$field_name][$graph_item_id] = $graph_item[$field_name];
                /* date/time substitution */
                if (strstr($graph_variables[$field_name][$graph_item_id], "|date_time|")) {
                    $graph_variables[$field_name][$graph_item_id] = str_replace("|date_time|", date('D d M H:i:s T Y', strtotime(db_fetch_cell("SELECT value FROM settings WHERE name='date'"))), $graph_variables[$field_name][$graph_item_id]);
                }
                /* data source title substitution */
                if (strstr($graph_variables[$field_name][$graph_item_id], "|data_source_title|")) {
                    $graph_variables[$field_name][$graph_item_id] = str_replace("|data_source_title|", get_data_source_title($graph_item["local_data_id"]), $graph_variables[$field_name][$graph_item_id]);
                }
                /* data query variables */
                $graph_variables[$field_name][$graph_item_id] = rrd_substitute_host_query_data($graph_variables[$field_name][$graph_item_id], $graph, $graph_item);
                /* Nth percentile */
                if (preg_match_all("/\\|([0-9]{1,2}):(bits|bytes):(\\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\\d)?\\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        $graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_nth_percentile($match, $graph_item, $graph_items, $graph_start, $graph_end), $graph_variables[$field_name][$graph_item_id]);
                    }
                }
                /* bandwidth summation */
                if (preg_match_all("/\\|sum:(\\d|auto):(current|total|atomic):(\\d):(\\d+|auto)\\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        $graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_bandwidth_summation($match, $graph_item, $graph_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $graph_variables[$field_name][$graph_item_id]);
                    }
                }
            }
            /* if we are not displaying a legend there is no point in us even processing the auto padding,
            			text format stuff. */
            if (!isset($graph_data_array["graph_nolegend"])) {
                /* set hard return variable if selected (\n) */
                if ($graph_item["hard_return"] == "on") {
                    $hardreturn[$graph_item_id] = "\\n";
                } else {
                    $hardreturn[$graph_item_id] = "";
                }
                /* +++++++++++++++++++++++ LEGEND: AUTO PADDING (<>'s) +++++++++++++++++++++++ */
                /* PADDING: remember this is not perfect! its main use is for the basic graph setup of:
                			AREA - GPRINT-CURRENT - GPRINT-AVERAGE - GPRINT-MAXIMUM \n
                			of course it can be used in other situations, however may not work as intended.
                			If you have any additions to this small peice of code, feel free to send them to me. */
                if ($graph["auto_padding"] == "on") {
                    /* only applies to AREA, STACK and LINEs */
                    if (preg_match("/(AREA|STACK|LINE[123])/", $graph_item_types[$graph_item["graph_type_id"]])) {
                        $text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);
                        if ($text_format_length > $padding_estimate) {
                            $padding_estimate = $text_format_length;
                        }
                    }
                }
            }
            $j++;
        }
    }
    /* +++++++++++++++++++++++ GRAPH ITEMS: CDEF's +++++++++++++++++++++++ */
    $i = 0;
    reset($graph_items);
    /* hack for rrdtool 1.2.x support */
    $graph_item_stack_type = "";
    if (sizeof($graph_items)) {
        foreach ($graph_items as $graph_item) {
            /* first we need to check if there is a DEF for the current data source/cf combination. if so,
            		we will use that */
            if (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$graph_item["consolidation_function_id"]])) {
                $cf_id = $graph_item["consolidation_function_id"];
            } else {
                /* if there is not a DEF defined for the current data source/cf combination, then we will have to
                		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
                if (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][1])) {
                    $cf_id = 1;
                    /* CF: AVERAGE */
                } elseif (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][3])) {
                    $cf_id = 3;
                    /* CF: MAX */
                } elseif (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][2])) {
                    $cf_id = 2;
                    /* CF: MIN */
                } elseif (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][4])) {
                    $cf_id = 4;
                    /* CF: LAST */
                } else {
                    $cf_id = 1;
                    /* CF: AVERAGE */
                }
            }
            /* now remember the correct CF reference */
            $cf_id = $graph_item["cf_reference"];
            /* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
            		data source of global cdef, but is unique when those two variables combine. */
            $cdef_graph_defs = "";
            if (!empty($graph_item["cdef_id"]) && !isset($cdef_cache[$graph_item["cdef_id"]][$graph_item["data_template_rrd_id"]][$cf_id])) {
                $cdef_string = $graph_variables["cdef_cache"][$graph_item["graph_templates_item_id"]];
                $magic_item = array();
                $already_seen = array();
                $sources_seen = array();
                $count_all_ds_dups = 0;
                $count_all_ds_nodups = 0;
                $count_similar_ds_dups = 0;
                $count_similar_ds_nodups = 0;
                /* if any of those magic variables are requested ... */
                if (preg_match("/(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)/", $cdef_string) || preg_match("/(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)/", $cdef_string)) {
                    /* now walk through each case to initialize array*/
                    if (preg_match("/ALL_DATA_SOURCES_DUPS/", $cdef_string)) {
                        $magic_item["ALL_DATA_SOURCES_DUPS"] = "";
                    }
                    if (preg_match("/ALL_DATA_SOURCES_NODUPS/", $cdef_string)) {
                        $magic_item["ALL_DATA_SOURCES_NODUPS"] = "";
                    }
                    if (preg_match("/SIMILAR_DATA_SOURCES_DUPS/", $cdef_string)) {
                        $magic_item["SIMILAR_DATA_SOURCES_DUPS"] = "";
                    }
                    if (preg_match("/SIMILAR_DATA_SOURCES_NODUPS/", $cdef_string)) {
                        $magic_item["SIMILAR_DATA_SOURCES_NODUPS"] = "";
                    }
                    if (preg_match("/COUNT_ALL_DS_DUPS/", $cdef_string)) {
                        $magic_item["COUNT_ALL_DS_DUPS"] = "";
                    }
                    if (preg_match("/COUNT_ALL_DS_NODUPS/", $cdef_string)) {
                        $magic_item["COUNT_ALL_DS_NODUPS"] = "";
                    }
                    if (preg_match("/COUNT_SIMILAR_DS_DUPS/", $cdef_string)) {
                        $magic_item["COUNT_SIMILAR_DS_DUPS"] = "";
                    }
                    if (preg_match("/COUNT_SIMILAR_DS_NODUPS/", $cdef_string)) {
                        $magic_item["COUNT_SIMILAR_DS_NODUPS"] = "";
                    }
                    /* loop over all graph items */
                    for ($t = 0; $t < count($graph_items); $t++) {
                        /* only work on graph items, omit GRPINTs, COMMENTs and stuff */
                        if (preg_match("/(AREA|STACK|LINE[123])/", $graph_item_types[$graph_items[$t]["graph_type_id"]]) && !empty($graph_items[$t]["data_template_rrd_id"])) {
                            /* if the user screws up CF settings, PHP will generate warnings if left unchecked */
                            /* matching consolidation function? */
                            if (isset($cf_ds_cache[$graph_items[$t]["data_template_rrd_id"]][$cf_id])) {
                                $def_name = generate_graph_def_name(strval($cf_ds_cache[$graph_items[$t]["data_template_rrd_id"]][$cf_id]));
                                /* do we need ALL_DATA_SOURCES_DUPS? */
                                if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
                                    $magic_item["ALL_DATA_SOURCES_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                    /* convert unknowns to '0' first */
                                }
                                /* do we need COUNT_ALL_DS_DUPS? */
                                if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
                                    $magic_item["COUNT_ALL_DS_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                    /* convert unknowns to '0' first */
                                }
                                $count_all_ds_dups++;
                                /* check if this item also qualifies for NODUPS  */
                                if (!isset($already_seen[$def_name])) {
                                    if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
                                        $magic_item["ALL_DATA_SOURCES_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
                                        $magic_item["COUNT_ALL_DS_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    $count_all_ds_nodups++;
                                    $already_seen[$def_name] = TRUE;
                                }
                                /* check for SIMILAR data sources */
                                if ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                    /* do we need SIMILAR_DATA_SOURCES_DUPS? */
                                    if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"]) && $graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                        $magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    /* do we need COUNT_SIMILAR_DS_DUPS? */
                                    if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"]) && $graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                        $magic_item["COUNT_SIMILAR_DS_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    $count_similar_ds_dups++;
                                    /* check if this item also qualifies for NODUPS  */
                                    if (!isset($sources_seen[$graph_items[$t]["data_template_rrd_id"]])) {
                                        if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
                                            $magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                            /* convert unknowns to '0' first */
                                        }
                                        if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"]) && $graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                            $magic_item["COUNT_SIMILAR_DS_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                            /* convert unknowns to '0' first */
                                        }
                                        $count_similar_ds_nodups++;
                                        $sources_seen[$graph_items[$t]["data_template_rrd_id"]] = TRUE;
                                    }
                                }
                                # SIMILAR data sources
                            }
                            # matching consolidation function?
                        }
                        # only work on graph items, omit GRPINTs, COMMENTs and stuff
                    }
                    #  loop over all graph items
                    /* if there is only one item to total, don't even bother with the summation.
                     * Otherwise cdef=a,b,c,+,+ is fine. */
                    if ($count_all_ds_dups > 1 && isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
                        $magic_item["ALL_DATA_SOURCES_DUPS"] .= str_repeat(",+", $count_all_ds_dups - 2) . ",+";
                    }
                    if ($count_all_ds_nodups > 1 && isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
                        $magic_item["ALL_DATA_SOURCES_NODUPS"] .= str_repeat(",+", $count_all_ds_nodups - 2) . ",+";
                    }
                    if ($count_similar_ds_dups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
                        $magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= str_repeat(",+", $count_similar_ds_dups - 2) . ",+";
                    }
                    if ($count_similar_ds_nodups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
                        $magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= str_repeat(",+", $count_similar_ds_nodups - 2) . ",+";
                    }
                    if ($count_all_ds_dups > 1 && isset($magic_item["COUNT_ALL_DS_DUPS"])) {
                        $magic_item["COUNT_ALL_DS_DUPS"] .= str_repeat(",+", $count_all_ds_dups - 2) . ",+";
                    }
                    if ($count_all_ds_nodups > 1 && isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
                        $magic_item["COUNT_ALL_DS_NODUPS"] .= str_repeat(",+", $count_all_ds_nodups - 2) . ",+";
                    }
                    if ($count_similar_ds_dups > 1 && isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
                        $magic_item["COUNT_SIMILAR_DS_DUPS"] .= str_repeat(",+", $count_similar_ds_dups - 2) . ",+";
                    }
                    if ($count_similar_ds_nodups > 1 && isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
                        $magic_item["COUNT_SIMILAR_DS_NODUPS"] .= str_repeat(",+", $count_similar_ds_nodups - 2) . ",+";
                    }
                }
                $cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval(isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id]) ? $cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id] : "0")), $cdef_string);
                /* ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
                if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
                    $cdef_string = str_replace("ALL_DATA_SOURCES_DUPS", $magic_item["ALL_DATA_SOURCES_DUPS"], $cdef_string);
                }
                if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
                    $cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $magic_item["ALL_DATA_SOURCES_NODUPS"], $cdef_string);
                }
                if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
                    $cdef_string = str_replace("SIMILAR_DATA_SOURCES_DUPS", $magic_item["SIMILAR_DATA_SOURCES_DUPS"], $cdef_string);
                }
                if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
                    $cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $magic_item["SIMILAR_DATA_SOURCES_NODUPS"], $cdef_string);
                }
                /* COUNT_ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
                if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
                    $cdef_string = str_replace("COUNT_ALL_DS_DUPS", $magic_item["COUNT_ALL_DS_DUPS"], $cdef_string);
                }
                if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
                    $cdef_string = str_replace("COUNT_ALL_DS_NODUPS", $magic_item["COUNT_ALL_DS_NODUPS"], $cdef_string);
                }
                if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
                    $cdef_string = str_replace("COUNT_SIMILAR_DS_DUPS", $magic_item["COUNT_SIMILAR_DS_DUPS"], $cdef_string);
                }
                if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
                    $cdef_string = str_replace("COUNT_SIMILAR_DS_NODUPS", $magic_item["COUNT_SIMILAR_DS_NODUPS"], $cdef_string);
                }
                /* data source item variables */
                $cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", empty($graph_item["rrd_minimum"]) ? "0" : $graph_item["rrd_minimum"], $cdef_string);
                $cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", empty($graph_item["rrd_maximum"]) ? "0" : $graph_item["rrd_maximum"], $cdef_string);
                $cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"], $cdef_string);
                $cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"], $cdef_string);
                /* replace query variables in cdefs */
                $cdef_string = rrd_substitute_host_query_data($cdef_string, $graph, $graph_item);
                /* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
                $cdef_graph_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
                /* prohibit command injection and provide platform specific quoting */
                $cdef_graph_defs .= cacti_escapeshellarg(sanitize_cdef($cdef_string), true);
                $cdef_graph_defs .= " \\\n";
                /* the CDEF cache is so we do not create duplicate CDEF's on a graph */
                $cdef_cache[$graph_item["cdef_id"]][$graph_item["data_template_rrd_id"]][$cf_id] = "{$i}";
            }
            /* add the cdef string to the end of the def string */
            $graph_defs .= $cdef_graph_defs;
            /* note the current item_id for easy access */
            $graph_item_id = $graph_item["graph_templates_item_id"];
            /* if we are not displaying a legend there is no point in us even processing the auto padding,
            		text format stuff. */
            if (!isset($graph_data_array["graph_nolegend"]) && $graph["auto_padding"] == "on") {
                /* only applies to AREA, STACK and LINEs */
                if (preg_match("/(AREA|STACK|LINE[123])/", $graph_item_types[$graph_item["graph_type_id"]])) {
                    $text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);
                    /* we are basing how much to pad on area and stack text format,
                    			not gprint. but of course the padding has to be displayed in gprint,
                    			how fun! */
                    $pad_number = $padding_estimate - $text_format_length;
                    //cacti_log("MAX: $padding_estimate, CURR: $text_format_lengths[$item_dsid], DSID: $item_dsid");
                    $text_padding = str_pad("", $pad_number);
                    /* two GPRINT's in a row screws up the padding, lets not do that */
                } else {
                    if ($graph_item_types[$graph_item["graph_type_id"]] == "GPRINT" && $last_graph_type == "GPRINT") {
                        $text_padding = "";
                    }
                }
                $last_graph_type = $graph_item_types[$graph_item["graph_type_id"]];
            }
            /* we put this in a variable so it can be manipulated before mainly used
            		if we want to skip it, like below */
            $current_graph_item_type = $graph_item_types[$graph_item["graph_type_id"]];
            /* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
            		to this graph item */
            if ($graph_item["cdef_id"] == "0") {
                if (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id])) {
                    $data_source_name = generate_graph_def_name(strval($cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id]));
                } else {
                    $data_source_name = "";
                }
            } else {
                $data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache[$graph_item["cdef_id"]][$graph_item["data_template_rrd_id"]][$cf_id]));
            }
            /* to make things easier... if there is no text format set; set blank text */
            if (!isset($graph_variables["text_format"][$graph_item_id])) {
                $graph_variables["text_format"][$graph_item_id] = "";
            } else {
                $graph_variables["text_format"][$graph_item_id] = str_replace('"', '\\"', $graph_variables["text_format"][$graph_item_id]);
                /* escape doublequotes */
            }
            if (!isset($hardreturn[$graph_item_id])) {
                $hardreturn[$graph_item_id] = "";
            }
            /* +++++++++++++++++++++++ GRAPH ITEMS +++++++++++++++++++++++ */
            /* most of the calculations have been done above. now we have for print everything out
            		in an RRDTool-friendly fashion */
            $need_rrd_nl = TRUE;
            if (!isset($graph_data_array['export_csv'])) {
                if ($graph_item_types[$graph_item["graph_type_id"]] == "COMMENT") {
                    # perform variable substitution first (in case this will yield an empty results or brings command injection problems)
                    $comment_arg = rrd_substitute_host_query_data($graph_variables["text_format"][$graph_item_id], $graph, $graph_item);
                    # next, compute the argument of the COMMENT statement and perform injection counter measures
                    if (trim($comment_arg) == '') {
                        # an empty COMMENT must be treated with care
                        $comment_arg = cacti_escapeshellarg(' ' . $hardreturn[$graph_item_id]);
                    } else {
                        $comment_arg = cacti_escapeshellarg($comment_arg . $hardreturn[$graph_item_id]);
                    }
                    # create rrdtool specific command line
                    $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . str_replace(":", "\\:", $comment_arg) . " ";
                } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "GPRINT" && !isset($graph_data_array["graph_nolegend"])) {
                    $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                    /* escape colons */
                    $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $data_source_name . ":" . $consolidation_functions[$graph_item["consolidation_function_id"]] . ":" . cacti_escapeshellarg($text_padding . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id]) . " ";
                } elseif (preg_match("/^(AREA|LINE[123]|STACK|HRULE|VRULE)\$/", $graph_item_types[$graph_item["graph_type_id"]])) {
                    /* initialize any color syntax for graph item */
                    if (empty($graph_item["hex"])) {
                        $graph_item_color_code = "";
                    } else {
                        $graph_item_color_code = "#" . $graph_item["hex"];
                        $graph_item_color_code .= $graph_item["alpha"];
                    }
                    if (preg_match("/^(AREA|LINE[123])\$/", $graph_item_types[$graph_item["graph_type_id"]])) {
                        $graph_item_stack_type = $graph_item_types[$graph_item["graph_type_id"]];
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $data_source_name . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . " ";
                    } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "STACK") {
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        $txt_graph_items .= $graph_item_stack_type . ":" . $data_source_name . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . ":STACK";
                    } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "HRULE") {
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        $graph_variables["value"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["value"][$graph_item_id]);
                        /* escape colons */
                        /* perform variable substitution; if this does not return a number, rrdtool will FAIL! */
                        $substitute = rrd_substitute_host_query_data($graph_variables["value"][$graph_item_id], $graph, $graph_item);
                        if (is_numeric($substitute)) {
                            $graph_variables["value"][$graph_item_id] = $substitute;
                        }
                        $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $graph_variables["value"][$graph_item_id] . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . " ";
                    } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "VRULE") {
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        if (substr_count($graph_item["value"], ":")) {
                            $value_array = explode(":", $graph_item["value"]);
                            if ($value_array[0] < 0) {
                                $value = date("U") - -3600 * $value_array[0] - 60 * $value_array[1];
                            } else {
                                $value = date("U", mktime($value_array[0], $value_array[1], 0));
                            }
                        } else {
                            if (is_numeric($graph_item["value"])) {
                                $value = $graph_item["value"];
                            }
                        }
                        $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $value . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . " ";
                    }
                } else {
                    $need_rrd_nl = FALSE;
                }
            } else {
                if (preg_match("/^(AREA|LINE[123]|STACK)\$/", $graph_item_types[$graph_item["graph_type_id"]])) {
                    /* give all export items a name */
                    if (trim($graph_variables["text_format"][$graph_item_id]) == "") {
                        $legend_name = "col" . $j . "-" . $data_source_name;
                    } else {
                        $legend_name = $graph_variables["text_format"][$graph_item_id];
                    }
                    $stacked_columns["col" . $j] = $graph_item_types[$graph_item["graph_type_id"]] == "STACK" ? 1 : 0;
                    $j++;
                    $txt_graph_items .= "XPORT:" . cacti_escapeshellarg($data_source_name) . ":" . str_replace(":", "", cacti_escapeshellarg($legend_name));
                } else {
                    $need_rrd_nl = FALSE;
                }
            }
            $i++;
            if ($i < sizeof($graph_items) && $need_rrd_nl) {
                $txt_graph_items .= RRD_NL;
            }
        }
    }
    if (!isset($graph_data_array['export_csv']) || $graph_data_array['export_csv'] != true) {
        $graph_array = api_plugin_hook_function('rrd_graph_graph_options', array('graph_opts' => $graph_opts, 'graph_defs' => $graph_defs, 'txt_graph_items' => $txt_graph_items, 'graph_id' => $local_graph_id, 'start' => $graph_start, 'end' => $graph_end));
        if (!empty($graph_array)) {
            $graph_defs = $graph_array['graph_defs'];
            $txt_graph_items = $graph_array['txt_graph_items'];
            $graph_opts = $graph_array['graph_opts'];
        }
        /* either print out the source or pass the source onto rrdtool to get us a nice PNG */
        if (isset($graph_data_array["print_source"])) {
            print "<PRE>" . htmlspecialchars(read_config_option("path_rrdtool") . " graph " . $graph_opts . $graph_defs . $txt_graph_items) . "</PRE>";
        } else {
            if (isset($graph_data_array["export"])) {
                rrdtool_execute("graph {$graph_opts}{$graph_defs}{$txt_graph_items}", false, RRDTOOL_OUTPUT_NULL, $rrdtool_pipe);
                return 0;
            } elseif (isset($graph_data_array['export_realtime'])) {
                $output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
                $output = rrdtool_execute("graph {$graph_opts}{$graph_defs}{$txt_graph_items}", false, $output_flag, $rrdtool_pipe);
                //cacti_log(str_replace(RRD_NL, ' ', "rrdtool graph $graph_opts$graph_defs$txt_graph_items"));
                if ($fp = fopen($graph_data_array['export_realtime'], 'w')) {
                    fwrite($fp, $output, strlen($output));
                    fclose($fp);
                    chmod($graph_data_array['export_realtime'], 0644);
                }
                return $output;
            } else {
                $graph_data_array = boost_prep_graph_array($graph_data_array);
                if (!isset($graph_data_array["output_flag"])) {
                    $output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
                } else {
                    $output_flag = $graph_data_array["output_flag"];
                }
                $output = rrdtool_execute("graph {$graph_opts}{$graph_defs}{$txt_graph_items}", false, $output_flag, $rrdtool_pipe);
                boost_graph_set_file($output, $local_graph_id, $rra_id);
                return $output;
            }
        }
    } else {
        $output_flag = RRDTOOL_OUTPUT_STDOUT;
        $xport_array = rrdxport2array(rrdtool_execute("xport {$graph_opts}{$graph_defs}{$txt_graph_items}", false, $output_flag));
        /* add host and graph information */
        $xport_array["meta"]["stacked_columns"] = $stacked_columns;
        $xport_array["meta"]["title_cache"] = cacti_escapeshellarg($graph["title_cache"]);
        $xport_array["meta"]["vertical_label"] = cacti_escapeshellarg($graph["vertical_label"]);
        $xport_array["meta"]["local_graph_id"] = $local_graph_id;
        $xport_array["meta"]["host_id"] = $graph["host_id"];
        return $xport_array;
    }
}
示例#10
0
function get_rrd_cfs($local_data_id)
{
    global $rrd_cfs, $consolidation_functions;
    $rrdfile = get_data_source_path($local_data_id, TRUE);
    if (!isset($rrd_cfs)) {
        $rrd_cfs = array();
    } else {
        if (array_key_exists($local_data_id, $rrd_cfs)) {
            return $rrd_cfs[$local_data_id];
        }
    }
    $cfs = array();
    $output = rrdtool_execute("info {$rrdfile}", FALSE, RRDTOOL_OUTPUT_STDOUT);
    /* search for
     * 		rra[0].cf = "LAST"
     * or similar
     */
    if (strlen($output)) {
        $output = explode("\n", $output);
        if (sizeof($output)) {
            foreach ($output as $line) {
                if (substr_count($line, ".cf")) {
                    $values = explode("=", $line);
                    if (!in_array(trim($values[1], '" '), $cfs)) {
                        $cfs[] = trim($values[1], '" ');
                    }
                }
            }
        }
    }
    $new_cfs = array();
    if (sizeof($cfs)) {
        foreach ($cfs as $cf) {
            switch ($cf) {
                case "AVG":
                case "AVERAGE":
                    $new_cfs[] = array_search('AVERAGE', $consolidation_functions);
                    break;
                case "MIN":
                    $new_cfs[] = array_search('MIN', $consolidation_functions);
                    break;
                case "MAX":
                    $new_cfs[] = array_search('MAX', $consolidation_functions);
                    break;
                case "LAST":
                    $new_cfs[] = array_search('LAST', $consolidation_functions);
                    break;
            }
        }
    }
    $rrd_cfs[$local_data_id] = $new_cfs;
    return $new_cfs;
}
示例#11
0
function thold_rrd_last($local_data_id)
{
    $last_time_entry = @rrdtool_execute('last ' . trim(get_data_source_path($local_data_id, true)), false, RRDTOOL_OUTPUT_STDOUT);
    return trim($last_time_entry);
}
示例#12
0
function get_rrd_cfs($local_data_id) {
	global $rrd_cfs;
	require(CACTI_BASE_PATH . "/include/presets/preset_rra_arrays.php");

	$rrdfile = get_data_source_path($local_data_id, TRUE);

	if (!isset($rrd_cfs)) {
		$rrd_cfs = array();
	}else if (array_key_exists($local_data_id, $rrd_cfs)) {
		return $rrd_cfs[$local_data_id];
	}

	$cfs = array();

	$output = rrdtool_execute("info $rrdfile", FALSE, RRDTOOL_OUTPUT_STDOUT);

	/* search for
	 * 		rra[0].cf = "LAST"
	 * or similar
	 */
	if (strlen($output)) {
		$output = explode("\n", $output);

		if (sizeof($output)) {
			foreach($output as $line) {
				if (substr_count($line, ".cf")) {
					$values = explode("=",$line);

					if (!in_array(trim($values[1]), $cfs)) {
						$cfs[] = trim($values[1], '" ');
					}
				}
			}
		}
	}

	$new_cfs = array();

	if (sizeof($cfs)) {
		foreach($cfs as $cf) {
			$new_cfs[] = array_search($cf, $consolidation_functions);
		}
	}

	$rrd_cfs[$local_data_id] = $new_cfs;

	return $new_cfs;
}
示例#13
0
/** api_poller_cache_item_add - add an item to the poller cache
 *
 * @param int $device_id
 * @param string $device_field_override
 * @param int $local_data_id
 * @param int $rrd_step
 * @param int $poller_action_id
 * @param string $data_source_item_name
 * @param int $num_rrd_items
 * @param string $arg1
 * @param string $arg2
 * @param string $arg3
 * @return unknown_type
 */
function api_poller_cache_item_add($device_id, $device_field_override, $local_data_id, $rrd_step, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = "", $arg2 = "", $arg3 = "") {
	static $devices = array();

	if (!isset($devices[$device_id])) {
		$device = db_fetch_row("select
			device.id,
			device.poller_id,
			device.hostname,
			device.snmp_community,
			device.snmp_version,
			device.snmp_username,
			device.snmp_password,
			device.snmp_auth_protocol,
			device.snmp_priv_passphrase,
			device.snmp_priv_protocol,
			device.snmp_context,
			device.snmp_port,
			device.snmp_timeout,
			device.disabled
			from device
			where device.id=$device_id");

		$devices[$device_id] = $device;
	} else {
		$device = $devices[$device_id];
	}

	/* the $device_field_override array can be used to override certain device fields in the poller cache */
	if (isset($device)) {
		$device = array_merge($device, $device_field_override);
	}

	if (isset($device["id"]) || (isset($device_id))) {
		if (isset($device)) {
			if ($device["disabled"] == CHECKED) {
				return;
			}
		} else {
			if ($poller_action_id == 0) {
				return;
			}

			$device["id"] = 0;
			$device["poller_id"] = 0;
			$device["snmp_community"] = "";
			$device["snmp_timeout"] = "";
			$device["snmp_username"] = "";
			$device["snmp_password"] = "";
			$device["snmp_auth_protocol"] = "";
			$device["snmp_priv_passphrase"] = "";
			$device["snmp_priv_protocol"] = "";
			$device["snmp_context"] = "";
			$device["snmp_version"] = "";
			$device["snmp_port"] = "";
			$device["hostname"] = "None";
		}

		if ($poller_action_id == 0) {
			if (($device["snmp_version"] < 1) || ($device["snmp_version"] > 3) ||
				($device["snmp_community"] == "" && $device["snmp_version"] != 3)) {
				return;
			}
		}

		$rrd_next_step = api_poller_get_rrd_next_step($rrd_step, $num_rrd_items);

		return "($local_data_id, " . $device["poller_id"] . ", " . $device["id"] . ", $poller_action_id,'" . $device["hostname"] . "',
			'" . $device["snmp_community"]       . "', '" . $device["snmp_version"]       . "', '" . $device["snmp_timeout"] . "',
			'" . $device["snmp_username"]        . "', '" . $device["snmp_password"]      . "', '" . $device["snmp_auth_protocol"] . "',
			'" . $device["snmp_priv_passphrase"] . "', '" . $device["snmp_priv_protocol"] . "', '" . $device["snmp_context"] . "',
			'" . $device["snmp_port"]            . "', '$data_source_item_name', '"     . addslashes(clean_up_path(get_data_source_path($local_data_id, true))) . "',
			'$num_rrd_items', '$rrd_step', '$rrd_next_step', '$arg1', '$arg2', '$arg3', '1')";
	}
}
示例#14
0
文件: rrd.php 项目: songchin/Cacti
function rrdtool_function_info($data_source_id) {
	global $config;

	/* Get the path to rrdtool file */
	$data_source_path = get_data_source_path($data_source_id, true);

	/* Execute rrdtool info command */
	$cmd_line = " info " . $data_source_path;
	$output = rrdtool_execute($cmd_line, RRDTOOL_OUTPUT_NULL, RRDTOOL_OUTPUT_STDOUT);
	if (sizeof($output) == 0) {
		return false;
	}

	/* Parse the output */
	$matches = array();
	$rrd_info = array( 'rra' => array(), "ds" => array() );
	$output = explode("\n", $output);
	foreach ($output as $line) {
		$line = trim($line);
		if (preg_match("/^ds\[(\S+)\]\.(\S+) = (\S+)$/", $line, $matches)) {
			$rrd_info["ds"][$matches[1]][$matches[2]] = $matches[3];
		} elseif (preg_match("/^rra\[(\S+)\]\.(\S+)\[(\S+)\]\.(\S+) = (\S+)$/", $line, $matches)) {
			$rrd_info['rra'][$matches[1]][$matches[2]][$matches[3]][$matches[4]] = $matches[5];
		} elseif (preg_match("/^rra\[(\S+)\]\.(\S+) = (\S+)$/", $line, $matches)) {
			$rrd_info['rra'][$matches[1]][$matches[2]] = $matches[3];
		} elseif (preg_match("/^(\S+) = \"(\S+)\"$/", $line, $matches)) {
			$rrd_info[$matches[1]] = $matches[2];
		} elseif (preg_match("/^(\S+) = (\S+)$/", $line, $matches)) {
			$rrd_info[$matches[1]] = $matches[2];
		}
	}
	$output = "";
	$matches = array();

	/* Return parsed values */
	return $rrd_info;

}
示例#15
0
文件: boost.php 项目: MrWnn/cacti
function boost_rrdtool_function_create($local_data_id, $initial_time, $show_source)
{
    global $config;
    include $config['include_path'] . '/global_arrays.php';
    $data_source_path = get_data_source_path($local_data_id, true);
    /* ok, if that passes lets check to make sure an rra does not already
    	exist, the last thing we want to do is overright data! */
    if ($show_source != true) {
        if (file_exists($data_source_path) == true) {
            return -1;
        }
    }
    /* the first thing we must do is make sure there is at least one
    	rra associated with this data source... *
    	UPDATE: As of version 0.6.6, we are splitting this up into two
    	SQL strings because of the multiple DS per RRD support. This is
    	not a big deal however since this function gets called once per
    	data source */
    $rras = db_fetch_assoc_prepared('SELECT
		data_template_data.rrd_step,
		rra.x_files_factor,
		rra.steps,
		rra.rows,
		rra_cf.consolidation_function_id,
		(rra.rows * rra.steps) AS rra_order
		FROM data_template_data
		LEFT JOIN data_template_data_rra ON (data_template_data.id = data_template_data_rra.data_template_data_id)
		LEFT JOIN rra ON (data_template_data_rra.rra_id = rra.id)
		LEFT JOIN rra_cf ON (rra.id = rra_cf.rra_id)
		WHERE data_template_data.local_data_id = ?
		AND (rra.steps is not null OR rra.rows is not null)
		ORDER BY rra_cf.consolidation_function_id, rra_order', array($local_data_id));
    /* if we find that this DS has no RRA associated; get out.  This would
     * indicate that a data sources has been deleted
     */
    if (sizeof($rras) <= 0) {
        return false;
    }
    /* back off the initial time to allow updates */
    $initial_time -= 300;
    /* create the "--step" line */
    $create_ds = RRD_NL . '--start ' . $initial_time . ' --step ' . $rras[0]['rrd_step'] . ' ' . RRD_NL;
    /* query the data sources to be used in this .rrd file */
    $data_sources = db_fetch_assoc_prepared('SELECT
		data_template_rrd.id,
		data_template_rrd.rrd_heartbeat,
		data_template_rrd.rrd_minimum,
		data_template_rrd.rrd_maximum,
		data_template_rrd.data_source_type_id
		FROM data_template_rrd
		WHERE data_template_rrd.local_data_id = ?
		ORDER BY local_data_template_rrd_id', array($local_data_id));
    /* ONLY make a new DS entry if:
    	- There is multiple data sources and this item is not the main one.
    	- There is only one data source (then use it) */
    if (sizeof($data_sources) > 0) {
        foreach ($data_sources as $data_source) {
            /* use the cacti ds name by default or the user defined one, if entered */
            $data_source_name = get_data_source_item_name($data_source['id']);
            if (empty($data_source['rrd_maximum'])) {
                /* in case no maximum is given, use "Undef" value */
                $data_source['rrd_maximum'] = 'U';
            } elseif (strpos($data_source['rrd_maximum'], '|query_') !== false) {
                $data_local = db_fetch_row_prepared('SELECT * FROM data_local WHERE id = ?', array($local_data_id));
                if ($data_source['rrd_maximum'] == '|query_ifSpeed|' || $data_source['rrd_maximum'] == '|query_ifHighSpeed|') {
                    $highSpeed = db_fetch_cell_prepared("SELECT field_value\n\t\t\t\t\tFROM host_snmp_cache\n\t\t\t\t\tWHERE host_id = ?\n\t\t\t\t\tAND snmp_query_id = ?\n\t\t\t\t\tAND snmp_index = ?\n\t\t\t\t\tAND field_name = 'ifHighSpeed'", array($data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']));
                    if (!empty($highSpeed)) {
                        $data_source['rrd_maximum'] = $highSpeed * 1000000;
                    } else {
                        $data_source['rrd_maximum'] = substitute_snmp_query_data('|query_ifSpeed|', $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']);
                    }
                } else {
                    $data_source['rrd_maximum'] = substitute_snmp_query_data($data_source['rrd_maximum'], $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']);
                }
            } elseif ($data_source['rrd_maximum'] != 'U' && (int) $data_source['rrd_maximum'] <= (int) $data_source['rrd_minimum']) {
                /* max > min required, but take care of an "Undef" value */
                $data_source['rrd_maximum'] = (int) $data_source['rrd_minimum'] + 1;
            }
            /* min==max==0 won't work with rrdtool */
            if ($data_source['rrd_minimum'] == 0 && $data_source['rrd_maximum'] == 0) {
                $data_source['rrd_maximum'] = 'U';
            }
            $create_ds .= "DS:{$data_source_name}:" . $data_source_types[$data_source['data_source_type_id']] . ':' . $data_source['rrd_heartbeat'] . ':' . $data_source['rrd_minimum'] . ':' . $data_source['rrd_maximum'] . RRD_NL;
        }
    }
    $create_rra = '';
    /* loop through each available RRA for this DS */
    foreach ($rras as $rra) {
        $create_rra .= 'RRA:' . $consolidation_functions[$rra['consolidation_function_id']] . ':' . $rra['x_files_factor'] . ':' . $rra['steps'] . ':' . $rra['rows'] . RRD_NL;
    }
    /* check for structured path configuration, if in place verify directory
    	   exists and if not create it.
    	 */
    if (read_config_option('extended_paths') == 'on') {
        if (!is_dir(dirname($data_source_path))) {
            if (mkdir(dirname($data_source_path), 0775)) {
                if ($config['cacti_server_os'] != 'win32') {
                    $owner_id = fileowner($config['rra_path']);
                    $group_id = filegroup($config['rra_path']);
                    if (chown(dirname($data_source_path), $owner_id) && chgrp(dirname($data_source_path), $group_id)) {
                        /* permissions set ok */
                    } else {
                        cacti_log("ERROR: Unable to set directory permissions for '" . dirname($data_source_path) . "'", false);
                    }
                }
            } else {
                cacti_log("ERROR: Unable to create directory '" . dirname($data_source_path) . "'", false);
            }
        }
    }
    if ($show_source == true) {
        return read_config_option('path_rrdtool') . ' create' . RRD_NL . "{$data_source_path}{$create_ds}{$create_rra}";
    } else {
        return boost_rrdtool_execute("create {$data_source_path} {$create_ds}{$create_rra}", false, RRDTOOL_OUTPUT_STDOUT);
    }
}
示例#16
0
function boost_rrdtool_function_create($local_data_id, $initial_time, $show_source)
{
    global $config;
    include $config["include_path"] . "/global_arrays.php";
    $data_source_path = get_data_source_path($local_data_id, TRUE);
    /* ok, if that passes lets check to make sure an rra does not already
    	exist, the last thing we want to do is overright data! */
    if ($show_source != TRUE) {
        if (file_exists($data_source_path) == TRUE) {
            return -1;
        }
    }
    /* the first thing we must do is make sure there is at least one
    	rra associated with this data source... *
    	UPDATE: As of version 0.6.6, we are splitting this up into two
    	SQL strings because of the multiple DS per RRD support. This is
    	not a big deal however since this function gets called once per
    	data source */
    $rras = db_fetch_assoc("select\r\n\t\tdata_template_data.rrd_step,\r\n\t\trra.x_files_factor,\r\n\t\trra.steps,\r\n\t\trra.rows,\r\n\t\trra_cf.consolidation_function_id,\r\n\t\t(rra.rows*rra.steps) as rra_order\r\n\t\tfrom data_template_data\r\n\t\tleft join data_template_data_rra on (data_template_data.id=data_template_data_rra.data_template_data_id)\r\n\t\tleft join rra on (data_template_data_rra.rra_id=rra.id)\r\n\t\tleft join rra_cf on (rra.id=rra_cf.rra_id)\r\n\t\twhere data_template_data.local_data_id={$local_data_id}\r\n\t\tand (rra.steps is not null or rra.rows is not null)\r\n\t\torder by rra_cf.consolidation_function_id,rra_order");
    /* if we find that this DS has no RRA associated; get out.  This would
     * indicate that a data sources has been deleted
     */
    if (sizeof($rras) <= 0) {
        return FALSE;
    }
    /* back off the initial time to allow updates */
    $initial_time -= 300;
    /* create the "--step" line */
    $create_ds = RRD_NL . "--start " . $initial_time . " --step " . $rras[0]["rrd_step"] . " " . RRD_NL;
    /* query the data sources to be used in this .rrd file */
    $data_sources = db_fetch_assoc("SELECT\r\n\t\tdata_template_rrd.id,\r\n\t\tdata_template_rrd.rrd_heartbeat,\r\n\t\tdata_template_rrd.rrd_minimum,\r\n\t\tdata_template_rrd.rrd_maximum,\r\n\t\tdata_template_rrd.data_source_type_id\r\n\t\tFROM data_template_rrd\r\n\t\tWHERE data_template_rrd.local_data_id={$local_data_id}\r\n\t\tORDER BY local_data_template_rrd_id");
    /* ONLY make a new DS entry if:
    	- There is multiple data sources and this item is not the main one.
    	- There is only one data source (then use it) */
    if (sizeof($data_sources) > 0) {
        foreach ($data_sources as $data_source) {
            /* use the cacti ds name by default or the user defined one, if entered */
            $data_source_name = get_data_source_item_name($data_source["id"]);
            if (empty($data_source["rrd_maximum"])) {
                /* in case no maximum is given, use "Undef" value */
                $data_source["rrd_maximum"] = "U";
            } elseif (strpos($data_source["rrd_maximum"], "|query_") !== false) {
                if ($data_source["rrd_maximum"] == "|query_ifSpeed|" || $data_source["rrd_maximum"] == "|query_ifHighSpeed|") {
                    $highSpeed = db_fetch_cell("SELECT field_value\r\n\t\t\t\t\tFROM host_snmp_cache\r\n\t\t\t\t\tWHERE host_id=" . $data_local["host_id"] . "\r\n\t\t\t\t\tAND snmp_query_id=" . $data_local["snmp_query_id"] . "\r\n\t\t\t\t\tAND snmp_index='" . $data_local["snmp_index"] . "'\r\n\t\t\t\t\tAND field_name='ifHighSpeed'");
                    if (!empty($highSpeed)) {
                        $data_source["rrd_maximum"] = $highSpeed * 1000000;
                    } else {
                        $data_source["rrd_maximum"] = substitute_snmp_query_data("|query_ifSpeed|", $data_local["host_id"], $data_local["snmp_query_id"], $data_local["snmp_index"]);
                    }
                } else {
                    $data_source["rrd_maximum"] = substitute_snmp_query_data($data_source["rrd_maximum"], $data_local["host_id"], $data_local["snmp_query_id"], $data_local["snmp_index"]);
                }
            } elseif ($data_source["rrd_maximum"] != "U" && (int) $data_source["rrd_maximum"] <= (int) $data_source["rrd_minimum"]) {
                /* max > min required, but take care of an "Undef" value */
                $data_source["rrd_maximum"] = (int) $data_source["rrd_minimum"] + 1;
            }
            /* min==max==0 won't work with rrdtool */
            if ($data_source["rrd_minimum"] == 0 && $data_source["rrd_maximum"] == 0) {
                $data_source["rrd_maximum"] = "U";
            }
            $create_ds .= "DS:{$data_source_name}:" . $data_source_types[$data_source["data_source_type_id"]] . ":" . $data_source["rrd_heartbeat"] . ":" . $data_source["rrd_minimum"] . ":" . $data_source["rrd_maximum"] . RRD_NL;
        }
    }
    $create_rra = "";
    /* loop through each available RRA for this DS */
    foreach ($rras as $rra) {
        $create_rra .= "RRA:" . $consolidation_functions[$rra["consolidation_function_id"]] . ":" . $rra["x_files_factor"] . ":" . $rra["steps"] . ":" . $rra["rows"] . RRD_NL;
    }
    /* check for structured path configuration, if in place verify directory
    	   exists and if not create it.
    	 */
    if (read_config_option("extended_paths") == "on") {
        if (!is_dir(dirname($data_source_path))) {
            if (mkdir(dirname($data_source_path), 0775)) {
                if ($config["cacti_server_os"] != "win32") {
                    $owner_id = fileowner($config["rra_path"]);
                    $group_id = filegroup($config["rra_path"]);
                    if (chown(dirname($data_source_path), $owner_id) && chgrp(dirname($data_source_path), $group_id)) {
                        /* permissions set ok */
                    } else {
                        cacti_log("ERROR: Unable to set directory permissions for '" . dirname($data_source_path) . "'", FALSE);
                    }
                }
            } else {
                cacti_log("ERROR: Unable to create directory '" . dirname($data_source_path) . "'", FALSE);
            }
        }
    }
    if ($show_source == TRUE) {
        return read_config_option("path_rrdtool") . " create" . RRD_NL . "{$data_source_path}{$create_ds}{$create_rra}";
    } else {
        return boost_rrdtool_execute("create {$data_source_path} {$create_ds}{$create_rra}", FALSE, RRDTOOL_OUTPUT_STDOUT);
    }
}
示例#17
0
function thold_rrd_last($rra)
{
    global $config;
    $last_time_entry = @rrdtool_execute('last ' . trim(get_data_source_path($rra, true)), false, RRDTOOL_OUTPUT_STDOUT);
    return trim($last_time_entry);
}
示例#18
0
文件: rrd.php 项目: songchin/Cacti
function rrdtool_function_xport($local_graph_id, $rra_id, $xport_data_array, &$xport_meta, $rrd_struc = array()) {
	global $config, $consolidation_functions;

	include_once($config["library_path"] . "/cdef.php");
	include_once($config["library_path"] . "/graph_variables.php");
	include_once($config["library_path"] . "/xml.php");
	include($config["include_path"] . "/global_arrays.php");

	/* before we do anything; make sure the user has permission to view this graph,
	if not then get out */
	if ((read_config_option("auth_method") != 0) && (isset($_SESSION["sess_user_id"]))) {
		$access_denied = !(is_graph_allowed($local_graph_id));

		if ($access_denied == true) {
			return "GRAPH ACCESS DENIED";
		}
	}

	/* find the step and how often this graph is updated with new data */
	$ds_step = db_fetch_cell("select
		data_template_data.rrd_step
		from (data_template_data,data_template_rrd,graph_templates_item)
		where graph_templates_item.task_item_id=data_template_rrd.id
		and data_template_rrd.local_data_id=data_template_data.local_data_id
		and graph_templates_item.local_graph_id=$local_graph_id
		limit 0,1");
	$ds_step = empty($ds_step) ? 300 : $ds_step;

	/* if no rra was specified, we need to figure out which one RRDTool will choose using
	 * "best-fit" resolution fit algorithm */
	if (empty($rra_id)) {
		if ((empty($xport_data_array["graph_start"])) || (empty($xport_data_array["graph_end"]))) {
			$rra["rows"] = 600;
			$rra["steps"] = 1;
			$rra["timespan"] = 86400;
		}else{
			/* get a list of RRAs related to this graph */
			$rras = get_associated_rras($local_graph_id);

			if (sizeof($rras) > 0) {
				foreach ($rras as $unchosen_rra) {
					/* the timespan specified in the RRA "timespan" field may not be accurate */
					$real_timespan = ($ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"]);

					/* make sure the current start/end times fit within each RRA's timespan */
					if ( (($xport_data_array["graph_end"] - $xport_data_array["graph_start"]) <= $real_timespan) && ((time() - $xport_data_array["graph_start"]) <= $real_timespan) ) {
						/* is this RRA better than the already chosen one? */
						if ((isset($rra)) && ($unchosen_rra["steps"] < $rra["steps"])) {
							$rra = $unchosen_rra;
						}else if (!isset($rra)) {
							$rra = $unchosen_rra;
						}
					}
				}
			}

			if (!isset($rra)) {
				$rra["rows"] = 600;
				$rra["steps"] = 1;
			}
		}
	}else{
		$rra = db_fetch_row("select timespan,rows,steps from rra where id=$rra_id");
	}

	$seconds_between_graph_updates = ($ds_step * $rra["steps"]);

	/* override: graph start time */
	if ((!isset($graph_data_array["graph_start"])) || ($graph_data_array["graph_start"] == "0")) {
		$graph_start = -($rra["timespan"]);
	}else{
		$graph_start = $graph_data_array["graph_start"];
	}

	/* override: graph end time */
	if ((!isset($graph_data_array["graph_end"])) || ($graph_data_array["graph_end"] == "0")) {
		$graph_end = -($seconds_between_graph_updates);
	}else{
		$graph_end = $graph_data_array["graph_end"];
	}

	$graph = db_fetch_row("select
		graph_local.host_id,
		graph_local.snmp_query_id,
		graph_local.snmp_index,
		graph_templates_graph.title_cache,
		graph_templates_graph.vertical_label,
		graph_templates_graph.slope_mode,
		graph_templates_graph.auto_scale,
		graph_templates_graph.auto_scale_opts,
		graph_templates_graph.auto_scale_log,
		graph_templates_graph.scale_log_units,
		graph_templates_graph.auto_scale_rigid,
		graph_templates_graph.auto_padding,
		graph_templates_graph.base_value,
		graph_templates_graph.upper_limit,
		graph_templates_graph.lower_limit,
		graph_templates_graph.height,
		graph_templates_graph.width,
		graph_templates_graph.image_format_id,
		graph_templates_graph.unit_value,
		graph_templates_graph.unit_exponent_value,
		graph_templates_graph.export
		from (graph_templates_graph,graph_local)
		where graph_local.id=graph_templates_graph.local_graph_id
		and graph_templates_graph.local_graph_id=$local_graph_id");

	/* lets make that sql query... */
	$xport_items = db_fetch_assoc("select
		graph_templates_item.id as graph_templates_item_id,
		graph_templates_item.cdef_id,
		graph_templates_item.text_format,
		graph_templates_item.value,
		graph_templates_item.hard_return,
		graph_templates_item.consolidation_function_id,
		graph_templates_item.graph_type_id,
		graph_templates_gprint.gprint_text,
		colors.hex,
		graph_templates_item.alpha,
		data_template_rrd.id as data_template_rrd_id,
		data_template_rrd.local_data_id,
		data_template_rrd.rrd_minimum,
		data_template_rrd.rrd_maximum,
		data_template_rrd.data_source_name,
		data_template_rrd.local_data_template_rrd_id
		from graph_templates_item
		left join data_template_rrd on (graph_templates_item.task_item_id=data_template_rrd.id)
		left join colors on (graph_templates_item.color_id=colors.id)
		left join graph_templates_gprint on (graph_templates_item.gprint_id=graph_templates_gprint.id)
		where graph_templates_item.local_graph_id=$local_graph_id
		order by graph_templates_item.sequence");

	/* +++++++++++++++++++++++ XPORT OPTIONS +++++++++++++++++++++++ */

	/* override: graph start time */
	if ((!isset($xport_data_array["graph_start"])) || ($xport_data_array["graph_start"] == "0")) {
		$xport_start = -($rra["timespan"]);
	}else{
		$xport_start = $xport_data_array["graph_start"];
	}

	/* override: graph end time */
	if ((!isset($xport_data_array["graph_end"])) || ($xport_data_array["graph_end"] == "0")) {
		$xport_end = -($seconds_between_graph_updates);
	}else{
		$xport_end = $xport_data_array["graph_end"];
	}

	/* basic export options */
	$xport_opts =
		"--start=$xport_start" . RRD_NL .
		"--end=$xport_end" . RRD_NL .
		"--maxrows=10000" . RRD_NL;

	$xport_defs = "";

	$i = 0; $j = 0;
	$nth = 0; $sum = 0;
	if (sizeof($xport_items) > 0) {
		/* we need to add a new column "cf_reference", so unless PHP 5 is used, this foreach syntax is required */
		foreach ($xport_items as $key => $xport_item) {
			/* mimic the old behavior: LINE[123], AREA, STACK and GPRINT items use the CF specified in the graph item */
			if (($xport_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1) ||
				($xport_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2) ||
				($xport_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3) ||
				($xport_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA)  ||
				($xport_item["graph_type_id"] == GRAPH_ITEM_TYPE_STACK)) {
				$xport_cf = $xport_item["consolidation_function_id"];
				$last_xport_cf["data_source_name"]["local_data_template_rrd_id"] = $xport_cf;
				/* remember this for second foreach loop */
				$xport_items[$key]["cf_reference"] = $xport_cf;
			}elseif ($xport_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT) {
				/* ATTENTION!
				 * the "CF" given on graph_item edit screen for GPRINT is indeed NOT a real "CF",
				 * but an aggregation function
				 * see "man rrdgraph_data" for the correct VDEF based notation
				 * so our task now is to "guess" the very graph_item, this GPRINT is related to
				 * and to use that graph_item's CF */
				if (isset($last_xport_cf["data_source_name"]["local_data_template_rrd_id"])) {
					$xport_cf = $last_xport_cf["data_source_name"]["local_data_template_rrd_id"];
					/* remember this for second foreach loop */
					$xport_items[$key]["cf_reference"] = $xport_cf;
				} else {
					$xport_cf = generate_graph_best_cf($xport_item["local_data_id"], $xport_item["consolidation_function_id"]);
					/* remember this for second foreach loop */
					$xport_items[$key]["cf_reference"] = $xport_cf;
				}
			}else{
				/* all other types are based on the best matching CF */
				$xport_cf = generate_graph_best_cf($xport_item["local_data_id"], $xport_item["consolidation_function_id"]);
				/* remember this for second foreach loop */
				$xport_items[$key]["cf_reference"] = $xport_cf;
			}

			if ((!empty($xport_item["local_data_id"])) &&
				(!isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[$xport_cf]))) {
				/* use a user-specified ds path if one is entered */
				$data_source_path = get_data_source_path($xport_item["local_data_id"], true);

				/* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
				$data_source_path = str_replace(":", "\:", $data_source_path);

				if (!empty($data_source_path)) {
					/* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
					to a function that matches the digits with letters. rrdtool likes letters instead
					of numbers in DEF names; especially with CDEF's. cdef's are created
					the same way, except a 'cdef' is put on the beginning of the hash */
					$xport_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=\"$data_source_path\":" . $xport_item["data_source_name"] . ":" . $consolidation_functions[$xport_cf] . RRD_NL;

					$cf_ds_cache{$xport_item["data_template_rrd_id"]}[$xport_cf] = "$i";

					$i++;
				}
			}

			/* cache cdef value here to support data query variables in the cdef string */
			if (empty($xport_item["cdef_id"])) {
				$xport_item["cdef_cache"] = "";
				$xport_items[$j]["cdef_cache"] = "";
			}else{
				$xport_item["cdef_cache"] = get_cdef($xport_item["cdef_id"]);
				$xport_items[$j]["cdef_cache"] = get_cdef($xport_item["cdef_id"]);
			}

			/* +++++++++++++++++++++++ LEGEND: TEXT SUBSITUTION (<>'s) +++++++++++++++++++++++ */

			/* note the current item_id for easy access */
			$xport_item_id = $xport_item["graph_templates_item_id"];

			/* the following fields will be searched for graph variables */
			$variable_fields = array(
				"text_format" => array(
					"process_no_legend" => false
					),
				"value" => array(
					"process_no_legend" => true
					),
				"cdef_cache" => array(
					"process_no_legend" => true
					)
				);

			/* loop through each field that we want to substitute values for:
			currently: text format and value */
			while (list($field_name, $field_array) = each($variable_fields)) {
				/* certain fields do not require values when the legend is not to be shown */
				if (($field_array["process_no_legend"] == false) && (isset($xport_data_array["graph_nolegend"]))) {
					continue;
				}

				$xport_variables[$field_name][$xport_item_id] = $xport_item[$field_name];

				/* date/time substitution */
				if (strstr($xport_variables[$field_name][$xport_item_id], "|date_time|")) {
					$xport_variables[$field_name][$xport_item_id] = str_replace("|date_time|", date('D d M H:i:s T Y', strtotime(db_fetch_cell("select value from settings where name='date'"))), $xport_variables[$field_name][$xport_item_id]);
				}

				/* data query variables */
				$xport_variables[$field_name][$xport_item_id] = rrd_substitute_host_query_data($xport_variables[$field_name][$xport_item_id], $graph, $xport_item);

				/* Nth percentile */
				if (preg_match_all("/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/", $xport_variables[$field_name][$xport_item_id], $matches, PREG_SET_ORDER)) {
					foreach ($matches as $match) {
						if ($field_name == "value") {
							$xport_meta["NthPercentile"][$nth]["format"] = $match[0];
							$xport_meta["NthPercentile"][$nth]["value"]  = str_replace($match[0], variable_nth_percentile($match, $xport_item, $xport_items, $graph_start, $graph_end), $xport_variables[$field_name][$xport_item_id]);
							$nth++;
						}
					}
				}

				/* bandwidth summation */
				if (preg_match_all("/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/", $xport_variables[$field_name][$xport_item_id], $matches, PREG_SET_ORDER)) {
					foreach ($matches as $match) {
						if ($field_name == "text_format") {
							$xport_meta["Summation"][$sum]["format"] = $match[0];
							$xport_meta["Summation"][$sum]["value"]  = str_replace($match[0], variable_bandwidth_summation($match, $xport_item, $xport_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $xport_variables[$field_name][$xport_item_id]);
							$sum++;
						}
					}
				}
			}

			$j++;
		}
	}

	/* +++++++++++++++++++++++ CDEF's +++++++++++++++++++++++ */

	$i = 0;
	$j = 1;
	reset($xport_items);

	$xport_item_stack_type = "";
	$txt_xport_items       = "";

	if (sizeof($xport_items) > 0) {
	foreach ($xport_items as $xport_item) {
		/* first we need to check if there is a DEF for the current data source/cf combination. if so,
		we will use that */
		if (isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}{$xport_item["consolidation_function_id"]})) {
			$cf_id = $xport_item["consolidation_function_id"];
		}else{
		/* if there is not a DEF defined for the current data source/cf combination, then we will have to
		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
			if (isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[1])) {
				$cf_id = 1; /* CF: AVERAGE */
			}elseif (isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[3])) {
				$cf_id = 3; /* CF: MAX */
			}elseif (isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[2])) {
				$cf_id = 2; /* CF: MIN */
			}elseif (isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[4])) {
				$cf_id = 4; /* CF: LAST */
			}else{
				$cf_id = 1; /* CF: AVERAGE */
			}
		}
		/* now remember the correct CF reference */
		$cf_id = $xport_item["cf_reference"];

		/* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
		data source of global cdef, but is unique when those two variables combine. */
		$cdef_xport_defs = ""; $cdef_all_ds_dups = ""; $cdef_similar_ds_dups = "";
		$cdef_similar_ds_nodups = ""; $cdef_all_ds_nodups = "";

		if ((!empty($xport_item["cdef_id"])) && (!isset($cdef_cache{$xport_item["cdef_id"]}{$xport_item["data_template_rrd_id"]}[$cf_id]))) {

			$cdef_string = $xport_variables["cdef_cache"]{$xport_item["graph_templates_item_id"]};
			$magic_item 	= array();
			$already_seen	= array();
			$sources_seen	= array();
			$count_all_ds_dups = 0;
			$count_all_ds_nodups = 0;
			$count_similar_ds_dups = 0;
			$count_similar_ds_nodups = 0;

			/* if any of those magic variables are requested ... */
			if (ereg("(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)", $cdef_string) ||
				ereg("(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)", $cdef_string)) {

				/* now walk through each case to initialize array*/
				if (ereg("ALL_DATA_SOURCES_DUPS", $cdef_string)) {
					$magic_item["ALL_DATA_SOURCES_DUPS"] = "";
				}
				if (ereg("ALL_DATA_SOURCES_NODUPS", $cdef_string)) {
					$magic_item["ALL_DATA_SOURCES_NODUPS"] = "";
				}
				if (ereg("SIMILAR_DATA_SOURCES_DUPS", $cdef_string)) {
					$magic_item["SIMILAR_DATA_SOURCES_DUPS"] = "";
				}
				if (ereg("SIMILAR_DATA_SOURCES_NODUPS", $cdef_string)) {
					$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] = "";
				}
				if (ereg("COUNT_ALL_DS_DUPS", $cdef_string)) {
					$magic_item["COUNT_ALL_DS_DUPS"] = "";
				}
				if (ereg("COUNT_ALL_DS_NODUPS", $cdef_string)) {
					$magic_item["COUNT_ALL_DS_NODUPS"] = "";
				}
				if (ereg("COUNT_SIMILAR_DS_DUPS", $cdef_string)) {
					$magic_item["COUNT_SIMILAR_DS_DUPS"] = "";
				}
				if (ereg("COUNT_SIMILAR_DS_NODUPS", $cdef_string)) {
					$magic_item["COUNT_SIMILAR_DS_NODUPS"] = "";
				}

				/* loop over all graph items */
				for ($t=0;($t<count($xport_items));$t++) {

					/* don't count any entry where a magic item was entered */
					if (ereg("(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)", $xport_items[$t]["cdef_cache"]) ||
						ereg("(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)", $xport_items[$t]["cdef_cache"])) {
						continue;
					}

					/* only work on graph items, omit GRPINTs, COMMENTs and stuff */
					if ((ereg("(AREA|STACK|LINE[123])", $graph_item_types{$xport_items[$t]["graph_type_id"]})) && (!empty($xport_items[$t]["data_template_rrd_id"]))) {
						/* if the user screws up CF settings, PHP will generate warnings if left unchecked */

						/* matching consolidation function? */
						if (isset($cf_ds_cache{$xport_items[$t]["data_template_rrd_id"]}[$cf_id])) {
							$def_name = generate_graph_def_name(strval($cf_ds_cache{$xport_items[$t]["data_template_rrd_id"]}[$cf_id]));

							/* do we need ALL_DATA_SOURCES_DUPS? */
							if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
								$magic_item["ALL_DATA_SOURCES_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
							}

							/* do we need COUNT_ALL_DS_DUPS? */
							if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
								$magic_item["COUNT_ALL_DS_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
							}

							$count_all_ds_dups++;

							/* check if this item also qualifies for NODUPS  */
							if(!isset($already_seen[$def_name])) {
								if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
									$magic_item["ALL_DATA_SOURCES_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
								}
								if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
									$magic_item["COUNT_ALL_DS_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
								}
								$count_all_ds_nodups++;
								$already_seen[$def_name]=TRUE;
							}

							/* check for SIMILAR data sources */
							if ($xport_item["data_source_name"] == $xport_items[$t]["data_source_name"]) {

								/* do we need SIMILAR_DATA_SOURCES_DUPS? */
								if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"]) && ($xport_item["data_source_name"] == $xport_items[$t]["data_source_name"])) {
									$magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
								}

								/* do we need COUNT_SIMILAR_DS_DUPS? */
								if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"]) && ($xport_item["data_source_name"] == $xport_items[$t]["data_source_name"])) {
									$magic_item["COUNT_SIMILAR_DS_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
								}

								$count_similar_ds_dups++;

								/* check if this item also qualifies for NODUPS  */
								if(!isset($sources_seen{$xport_items[$t]["data_template_rrd_id"]})) {
									if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
										$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
									}
									if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"]) && ($xport_item["data_source_name"] == $xport_items[$t]["data_source_name"])) {
										$magic_item["COUNT_SIMILAR_DS_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
									}
									$count_similar_ds_nodups++;
									$sources_seen{$xport_items[$t]["data_template_rrd_id"]} = TRUE;
								}
							} # SIMILAR data sources
						} # matching consolidation function?
					} # only work on graph items, omit GRPINTs, COMMENTs and stuff
				} #  loop over all graph items

				/* if there is only one item to total, don't even bother with the summation.
				 * Otherwise cdef=a,b,c,+,+ is fine. */
				if ($count_all_ds_dups > 1 && isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
					$magic_item["ALL_DATA_SOURCES_DUPS"] .= str_repeat(",+", ($count_all_ds_dups - 2)) . ",+";
				}
				if ($count_all_ds_nodups > 1 && isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
					$magic_item["ALL_DATA_SOURCES_NODUPS"] .= str_repeat(",+", ($count_all_ds_nodups - 2)) . ",+";
				}
				if ($count_similar_ds_dups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
					$magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= str_repeat(",+", ($count_similar_ds_dups - 2)) . ",+";
				}
				if ($count_similar_ds_nodups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
					$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= str_repeat(",+", ($count_similar_ds_nodups - 2)) . ",+";
				}
				if ($count_all_ds_dups > 1 && isset($magic_item["COUNT_ALL_DS_DUPS"])) {
					$magic_item["COUNT_ALL_DS_DUPS"] .= str_repeat(",+", ($count_all_ds_dups - 2)) . ",+";
				}
				if ($count_all_ds_nodups > 1 && isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
					$magic_item["COUNT_ALL_DS_NODUPS"] .= str_repeat(",+", ($count_all_ds_nodups - 2)) . ",+";
				}
				if ($count_similar_ds_dups > 1 && isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
					$magic_item["COUNT_SIMILAR_DS_DUPS"] .= str_repeat(",+", ($count_similar_ds_dups - 2)) . ",+";
				}
				if ($count_similar_ds_nodups > 1 && isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
					$magic_item["COUNT_SIMILAR_DS_NODUPS"] .= str_repeat(",+", ($count_similar_ds_nodups - 2)) . ",+";
				}
			}

			$cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval((isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[$cf_id]) ? $cf_ds_cache{$xport_item["data_template_rrd_id"]}[$cf_id] : "0"))), $cdef_string);

			/* ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
			if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
				$cdef_string = str_replace("ALL_DATA_SOURCES_DUPS", $magic_item["ALL_DATA_SOURCES_DUPS"], $cdef_string);
			}
			if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
				$cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $magic_item["ALL_DATA_SOURCES_NODUPS"], $cdef_string);
			}
			if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
				$cdef_string = str_replace("SIMILAR_DATA_SOURCES_DUPS", $magic_item["SIMILAR_DATA_SOURCES_DUPS"], $cdef_string);
			}
			if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
				$cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $magic_item["SIMILAR_DATA_SOURCES_NODUPS"], $cdef_string);
			}

			/* COUNT_ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
			if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
				$cdef_string = str_replace("COUNT_ALL_DS_DUPS", $magic_item["COUNT_ALL_DS_DUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
				$cdef_string = str_replace("COUNT_ALL_DS_NODUPS", $magic_item["COUNT_ALL_DS_NODUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
				$cdef_string = str_replace("COUNT_SIMILAR_DS_DUPS", $magic_item["COUNT_SIMILAR_DS_DUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
				$cdef_string = str_replace("COUNT_SIMILAR_DS_NODUPS", $magic_item["COUNT_SIMILAR_DS_NODUPS"], $cdef_string);
			}

			/* data source item variables */
			$cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", (empty($xport_item["rrd_minimum"]) ? "0" : $xport_item["rrd_minimum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", (empty($xport_item["rrd_maximum"]) ? "0" : $xport_item["rrd_maximum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", (empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", (empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"]), $cdef_string);

			/* replace query variables in cdefs */
			$cdef_string = rrd_substitute_host_query_data($cdef_string, $graph, $xport_item);

			/* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
			$cdef_xport_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
			$cdef_xport_defs .= $cdef_string;
			$cdef_xport_defs .= " \\\n";

			/* the CDEF cache is so we do not create duplicate CDEF's on a graph */
			$cdef_cache{$xport_item["cdef_id"]}{$xport_item["data_template_rrd_id"]}[$cf_id] = "$i";
		}

		/* add the cdef string to the end of the def string */
		$xport_defs .= $cdef_xport_defs;

		/* note the current item_id for easy access */
		$xport_item_id = $xport_item["graph_templates_item_id"];

		/* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
		to this graph item */
		if ($xport_item["cdef_id"] == "0") {
			if (isset($cf_ds_cache{$xport_item["data_template_rrd_id"]}[$cf_id])) {
				$data_source_name = generate_graph_def_name(strval($cf_ds_cache{$xport_item["data_template_rrd_id"]}[$cf_id]));
			}else{
				$data_source_name = "";
			}
		}else{
			$data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache{$xport_item["cdef_id"]}{$xport_item["data_template_rrd_id"]}[$cf_id]));
		}

		/* +++++++++++++++++++++++ XPORT ITEMS +++++++++++++++++++++++ */

		$need_rrd_nl = TRUE;
		if (ereg("^(AREA|LINE[123]|STACK)$", $graph_item_types{$xport_item["graph_type_id"]})) {
			/* give all export items a name */
			if (trim($xport_variables["text_format"][$xport_item_id]) == "") {
				$legend_name = "col" . $j . "-" . $data_source_name;
			}else{
				$legend_name = $xport_variables["text_format"][$xport_item_id];
			}
			$j++;

			$txt_xport_items .= "XPORT:" . $data_source_name . ":" . "\"" . str_replace(":", "", $legend_name) . "\"";
		}else{
			$need_rrd_nl = FALSE;
		}

		$i++;

		if (($i < sizeof($xport_items)) && ($need_rrd_nl)) {
			$txt_xport_items .= RRD_NL;
		}
	}
	}

	$output_flag = RRDTOOL_OUTPUT_STDOUT;

	$xport_array = rrdxport2array(rrdtool_execute("xport $xport_opts$xport_defs$txt_xport_items", false, $output_flag, $rrd_struc));

	/* add host and graph information */
	$xport_array["meta"]["title_cache"]    = $graph["title_cache"];
	$xport_array["meta"]["vertical_label"] = $graph["vertical_label"];
	$xport_array["meta"]["local_graph_id"] = $local_graph_id;
	$xport_array["meta"]["host_id"]        = $graph["host_id"];

	return $xport_array;
}
示例#19
0
function rrdtool_function_xport($local_graph_id, $rra_id, $xport_data_array, &$xport_meta, $rrd_struc = array())
{
    global $config;
    include_once $config["library_path"] . "/cdef.php";
    include_once $config["library_path"] . "/graph_variables.php";
    include_once $config["library_path"] . "/xml.php";
    include $config["include_path"] . "/global_arrays.php";
    /* before we do anything; make sure the user has permission to view this graph,
    	if not then get out */
    if (read_config_option("auth_method") != 0 && isset($_SESSION["sess_user_id"])) {
        $access_denied = !is_graph_allowed($local_graph_id);
        if ($access_denied == true) {
            return "GRAPH ACCESS DENIED";
        }
    }
    /* find the step and how often this graph is updated with new data */
    $ds_step = db_fetch_cell("select\n\t\tdata_template_data.rrd_step\n\t\tfrom (data_template_data,data_template_rrd,graph_templates_item)\n\t\twhere graph_templates_item.task_item_id=data_template_rrd.id\n\t\tand data_template_rrd.local_data_id=data_template_data.local_data_id\n\t\tand graph_templates_item.local_graph_id={$local_graph_id}\n\t\tlimit 0,1");
    $ds_step = empty($ds_step) ? 300 : $ds_step;
    /* if no rra was specified, we need to figure out which one RRDTool will choose using
     * "best-fit" resolution fit algorithm */
    if (empty($rra_id)) {
        if (empty($xport_data_array["graph_start"]) || empty($xport_data_array["graph_end"])) {
            $rra["rows"] = 600;
            $rra["steps"] = 1;
            $rra["timespan"] = 86400;
        } else {
            /* get a list of RRAs related to this graph */
            $rras = get_associated_rras($local_graph_id);
            if (sizeof($rras) > 0) {
                foreach ($rras as $unchosen_rra) {
                    /* the timespan specified in the RRA "timespan" field may not be accurate */
                    $real_timespan = $ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"];
                    /* make sure the current start/end times fit within each RRA's timespan */
                    if ($xport_data_array["graph_end"] - $xport_data_array["graph_start"] <= $real_timespan && time() - $xport_data_array["graph_start"] <= $real_timespan) {
                        /* is this RRA better than the already chosen one? */
                        if (isset($rra) && $unchosen_rra["steps"] < $rra["steps"]) {
                            $rra = $unchosen_rra;
                        } else {
                            if (!isset($rra)) {
                                $rra = $unchosen_rra;
                            }
                        }
                    }
                }
            }
            if (!isset($rra)) {
                $rra["rows"] = 600;
                $rra["steps"] = 1;
            }
        }
    } else {
        $rra = db_fetch_row("select timespan,rows,steps from rra where id={$rra_id}");
    }
    $seconds_between_graph_updates = $ds_step * $rra["steps"];
    /* override: graph start time */
    if (!isset($graph_data_array["graph_start"]) || $graph_data_array["graph_start"] == "0") {
        $graph_start = -$rra["timespan"];
    } else {
        $graph_start = $graph_data_array["graph_start"];
    }
    /* override: graph end time */
    if (!isset($graph_data_array["graph_end"]) || $graph_data_array["graph_end"] == "0") {
        $graph_end = -$seconds_between_graph_updates;
    } else {
        $graph_end = $graph_data_array["graph_end"];
    }
    $graph = db_fetch_row("select\n\t\tgraph_local.host_id,\n\t\tgraph_local.snmp_query_id,\n\t\tgraph_local.snmp_index,\n\t\tgraph_templates_graph.title_cache,\n\t\tgraph_templates_graph.vertical_label,\n\t\tgraph_templates_graph.slope_mode,\n\t\tgraph_templates_graph.auto_scale,\n\t\tgraph_templates_graph.auto_scale_opts,\n\t\tgraph_templates_graph.auto_scale_log,\n\t\tgraph_templates_graph.auto_scale_rigid,\n\t\tgraph_templates_graph.auto_padding,\n\t\tgraph_templates_graph.base_value,\n\t\tgraph_templates_graph.upper_limit,\n\t\tgraph_templates_graph.lower_limit,\n\t\tgraph_templates_graph.height,\n\t\tgraph_templates_graph.width,\n\t\tgraph_templates_graph.image_format_id,\n\t\tgraph_templates_graph.unit_value,\n\t\tgraph_templates_graph.unit_exponent_value,\n\t\tgraph_templates_graph.export\n\t\tfrom (graph_templates_graph,graph_local)\n\t\twhere graph_local.id=graph_templates_graph.local_graph_id\n\t\tand graph_templates_graph.local_graph_id={$local_graph_id}");
    /* lets make that sql query... */
    $xport_items = db_fetch_assoc("select\n\t\tgraph_templates_item.id as graph_templates_item_id,\n\t\tgraph_templates_item.cdef_id,\n\t\tgraph_templates_item.text_format,\n\t\tgraph_templates_item.value,\n\t\tgraph_templates_item.hard_return,\n\t\tgraph_templates_item.consolidation_function_id,\n\t\tgraph_templates_item.graph_type_id,\n\t\tgraph_templates_gprint.gprint_text,\n\t\tcolors.hex,\n\t\tdata_template_rrd.id as data_template_rrd_id,\n\t\tdata_template_rrd.local_data_id,\n\t\tdata_template_rrd.rrd_minimum,\n\t\tdata_template_rrd.rrd_maximum,\n\t\tdata_template_rrd.data_source_name,\n\t\tdata_template_rrd.local_data_template_rrd_id\n\t\tfrom graph_templates_item\n\t\tleft join data_template_rrd on (graph_templates_item.task_item_id=data_template_rrd.id)\n\t\tleft join colors on (graph_templates_item.color_id=colors.id)\n\t\tleft join graph_templates_gprint on (graph_templates_item.gprint_id=graph_templates_gprint.id)\n\t\twhere graph_templates_item.local_graph_id={$local_graph_id}\n\t\torder by graph_templates_item.sequence");
    /* +++++++++++++++++++++++ XPORT OPTIONS +++++++++++++++++++++++ */
    /* override: graph start time */
    if (!isset($xport_data_array["graph_start"]) || $xport_data_array["graph_start"] == "0") {
        $xport_start = -$rra["timespan"];
    } else {
        $xport_start = $xport_data_array["graph_start"];
    }
    /* override: graph end time */
    if (!isset($xport_data_array["graph_end"]) || $xport_data_array["graph_end"] == "0") {
        $xport_end = -$seconds_between_graph_updates;
    } else {
        $xport_end = $xport_data_array["graph_end"];
    }
    /* basic export options */
    $xport_opts = "--start={$xport_start}" . RRD_NL . "--end={$xport_end}" . RRD_NL;
    $xport_defs = "";
    $i = 0;
    $j = 0;
    $nth = 0;
    $sum = 0;
    if (sizeof($xport_items) > 0) {
        foreach ($xport_items as $xport_item) {
            /* mimic the old behavior: LINE[123], AREA, and STACK items use the CF specified in the graph item */
            if ($xport_item["graph_type_id"] == 4 || $xport_item["graph_type_id"] == 5 || $xport_item["graph_type_id"] == 6 || $xport_item["graph_type_id"] == 7 || $xport_item["graph_type_id"] == 8) {
                $xport_cf = $xport_item["consolidation_function_id"];
                /* all other types are based on the AVERAGE CF */
            } else {
                $xport_cf = 1;
            }
            if (!empty($xport_item["local_data_id"]) && !isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][$xport_cf])) {
                /* use a user-specified ds path if one is entered */
                $data_source_path = get_data_source_path($xport_item["local_data_id"], true);
                /* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
                $data_source_path = str_replace(":", "\\:", $data_source_path);
                if (!empty($data_source_path)) {
                    /* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
                    			to a function that matches the digits with letters. rrdtool likes letters instead
                    			of numbers in DEF names; especially with CDEF's. cdef's are created
                    			the same way, except a 'cdef' is put on the beginning of the hash */
                    $xport_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=\"{$data_source_path}\":" . $xport_item["data_source_name"] . ":" . $consolidation_functions[$xport_cf] . RRD_NL;
                    $cf_ds_cache[$xport_item["data_template_rrd_id"]][$xport_cf] = "{$i}";
                    $i++;
                }
            }
            /* cache cdef value here to support data query variables in the cdef string */
            if (empty($xport_item["cdef_id"])) {
                $xport_item["cdef_cache"] = "";
                $xport_items[$j]["cdef_cache"] = "";
            } else {
                $xport_item["cdef_cache"] = get_cdef($xport_item["cdef_id"]);
                $xport_items[$j]["cdef_cache"] = get_cdef($xport_item["cdef_id"]);
            }
            /* +++++++++++++++++++++++ LEGEND: TEXT SUBSITUTION (<>'s) +++++++++++++++++++++++ */
            /* note the current item_id for easy access */
            $xport_item_id = $xport_item["graph_templates_item_id"];
            /* the following fields will be searched for graph variables */
            $variable_fields = array("text_format" => array("process_no_legend" => false), "value" => array("process_no_legend" => true), "cdef_cache" => array("process_no_legend" => true));
            /* loop through each field that we want to substitute values for:
            			currently: text format and value */
            while (list($field_name, $field_array) = each($variable_fields)) {
                /* certain fields do not require values when the legend is not to be shown */
                if ($field_array["process_no_legend"] == false && isset($xport_data_array["graph_nolegend"])) {
                    continue;
                }
                $xport_variables[$field_name][$xport_item_id] = $xport_item[$field_name];
                /* date/time substitution */
                if (strstr($xport_variables[$field_name][$xport_item_id], "|date_time|")) {
                    $xport_variables[$field_name][$xport_item_id] = str_replace("|date_time|", date('D d M H:i:s T Y', strtotime(db_fetch_cell("select value from settings where name='date'"))), $xport_variables[$field_name][$xport_item_id]);
                }
                /* data query variables */
                $xport_variables[$field_name][$xport_item_id] = rrd_substitute_host_query_data($xport_variables[$field_name][$xport_item_id], $graph, $xport_item);
                /* Nth percentile */
                if (preg_match_all("/\\|([0-9]{1,2}):(bits|bytes):(\\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\\d)?\\|/", $xport_variables[$field_name][$xport_item_id], $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        if ($field_name == "value") {
                            $xport_meta["NthPercentile"][$nth]["format"] = $match[0];
                            $xport_meta["NthPercentile"][$nth]["value"] = str_replace($match[0], variable_nth_percentile($match, $xport_item, $xport_items, $graph_start, $graph_end), $xport_variables[$field_name][$xport_item_id]);
                            $nth++;
                        }
                    }
                }
                /* bandwidth summation */
                if (preg_match_all("/\\|sum:(\\d|auto):(current|total|atomic):(\\d):(\\d+|auto)\\|/", $xport_variables[$field_name][$xport_item_id], $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        if ($field_name == "text_format") {
                            $xport_meta["Summation"][$sum]["format"] = $match[0];
                            $xport_meta["Summation"][$sum]["value"] = str_replace($match[0], variable_bandwidth_summation($match, $xport_item, $xport_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $xport_variables[$field_name][$xport_item_id]);
                            $sum++;
                        }
                    }
                }
            }
            $j++;
        }
    }
    /* +++++++++++++++++++++++ CDEF's +++++++++++++++++++++++ */
    $i = 0;
    reset($xport_items);
    $xport_item_stack_type = "";
    $txt_xport_items = "";
    if (sizeof($xport_items) > 0) {
        foreach ($xport_items as $xport_item) {
            /* first we need to check if there is a DEF for the current data source/cf combination. if so,
            		we will use that */
            if (isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][$xport_item["consolidation_function_id"]])) {
                $cf_id = $xport_item["consolidation_function_id"];
            } else {
                /* if there is not a DEF defined for the current data source/cf combination, then we will have to
                		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
                if (isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][1])) {
                    $cf_id = 1;
                    /* CF: AVERAGE */
                } elseif (isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][3])) {
                    $cf_id = 3;
                    /* CF: MAX */
                } elseif (isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][2])) {
                    $cf_id = 2;
                    /* CF: MIN */
                } elseif (isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][4])) {
                    $cf_id = 4;
                    /* CF: LAST */
                } else {
                    $cf_id = 1;
                    /* CF: AVERAGE */
                }
            }
            /* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
            		data source of global cdef, but is unique when those two variables combine. */
            $cdef_xport_defs = "";
            $cdef_total_ds = "";
            $cdef_similar_ds = "";
            if (!empty($xport_item["cdef_id"]) && !isset($cdef_cache[$xport_item["cdef_id"]][$xport_item["data_template_rrd_id"]][$cf_id])) {
                $cdef_string = $xport_variables["cdef_cache"][$xport_item["graph_templates_item_id"]];
                /* create cdef string for "total all data sources" if requested */
                if (ereg("ALL_DATA_SOURCES_(NO)?DUPS", $cdef_string)) {
                    $item_count = 0;
                    for ($t = 0; $t < count($xport_items); $t++) {
                        if (ereg("(AREA|STACK|LINE[123])", $graph_item_types[$xport_items[$t]["graph_type_id"]]) && !empty($xport_items[$t]["data_template_rrd_id"])) {
                            /* if the user screws up CF settings, PHP will generate warnings if left unchecked */
                            if (isset($cf_ds_cache[$xport_items[$t]["data_template_rrd_id"]][$cf_id])) {
                                $def_name = generate_graph_def_name(strval($cf_ds_cache[$xport_items[$t]["data_template_rrd_id"]][$cf_id]));
                                $cdef_total_ds .= ($item_count == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                /* convert unknowns to '0' first */
                                $item_count++;
                            }
                        }
                    }
                    /* if there is only one item to total, don't even bother with the summation. otherwise
                    			cdef=a,b,c,+,+ is fine. */
                    if ($item_count > 1) {
                        $cdef_total_ds .= str_repeat(",+", $item_count - 2) . ",+";
                    }
                }
                /* create cdef string for "total similar data sources" if requested */
                if (ereg("SIMILAR_DATA_SOURCES_(NO)?DUPS", $cdef_string)) {
                    $sources_seen = array();
                    $item_count = 0;
                    for ($t = 0; $t < count($xport_items); $t++) {
                        if (ereg("(AREA|STACK|LINE[123])", $graph_item_types[$xport_items[$t]["graph_type_id"]]) && !empty($xport_items[$t]["data_template_rrd_id"]) && $xport_item["data_source_name"] == $xport_items[$t]["data_source_name"]) {
                            /* if the user screws up CF settings, PHP will generate warnings if left unchecked */
                            if (isset($cf_ds_cache[$xport_items[$t]["data_template_rrd_id"]][$cf_id]) && !isset($sources_seen[$xport_items[$t]["data_template_rrd_id"]])) {
                                $def_name = generate_graph_def_name(strval($cf_ds_cache[$xport_items[$t]["data_template_rrd_id"]][$cf_id]));
                                $cdef_similar_ds .= ($item_count == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                /* convert unknowns to '0' first */
                                $sources_seen[$xport_items[$t]["data_template_rrd_id"]] = 1;
                                $item_count++;
                            }
                        }
                    }
                    /* if there is only one item to total, don't even bother with the summation. otherwise
                    			cdef=a,b,c,+,+ is fine. */
                    if ($item_count > 1) {
                        $cdef_similar_ds .= str_repeat(",+", $item_count - 2) . ",+";
                    }
                }
                $cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval(isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][$cf_id]) ? $cf_ds_cache[$xport_item["data_template_rrd_id"]][$cf_id] : "0")), $cdef_string);
                $cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $cdef_total_ds, $cdef_string);
                $cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $cdef_similar_ds, $cdef_string);
                /* data source item variables */
                $cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", empty($xport_item["rrd_minimum"]) ? "0" : $xport_item["rrd_minimum"], $cdef_string);
                $cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", empty($xport_item["rrd_maximum"]) ? "0" : $xport_item["rrd_maximum"], $cdef_string);
                $cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"], $cdef_string);
                $cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"], $cdef_string);
                /* replace query variables in cdefs */
                $cdef_string = rrd_substitute_host_query_data($cdef_string, $graph, $xport_item);
                /* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
                $cdef_xport_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
                $cdef_xport_defs .= $cdef_string;
                $cdef_xport_defs .= " \\\n";
                /* the CDEF cache is so we do not create duplicate CDEF's on a graph */
                $cdef_cache[$xport_item["cdef_id"]][$xport_item["data_template_rrd_id"]][$cf_id] = "{$i}";
            }
            /* add the cdef string to the end of the def string */
            $xport_defs .= $cdef_xport_defs;
            /* note the current item_id for easy access */
            $xport_item_id = $xport_item["graph_templates_item_id"];
            /* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
            		to this graph item */
            if ($xport_item["cdef_id"] == "0") {
                if (isset($cf_ds_cache[$xport_item["data_template_rrd_id"]][$cf_id])) {
                    $data_source_name = generate_graph_def_name(strval($cf_ds_cache[$xport_item["data_template_rrd_id"]][$cf_id]));
                } else {
                    $data_source_name = "";
                }
            } else {
                $data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache[$xport_item["cdef_id"]][$xport_item["data_template_rrd_id"]][$cf_id]));
            }
            /* +++++++++++++++++++++++ XPORT ITEMS +++++++++++++++++++++++ */
            $need_rrd_nl = TRUE;
            if (ereg("^(AREA|LINE[123]|STACK)\$", $graph_item_types[$xport_item["graph_type_id"]])) {
                $txt_xport_items .= "XPORT:" . $data_source_name . ":" . "\"" . $xport_variables["text_format"][$xport_item_id] . "\"";
            } else {
                $need_rrd_nl = FALSE;
            }
            $i++;
            if ($i < sizeof($xport_items) && $need_rrd_nl) {
                $txt_xport_items .= RRD_NL;
            }
        }
    }
    $output_flag = RRDTOOL_OUTPUT_STDOUT;
    $xport_array = rrdxport2array(rrdtool_execute("xport {$xport_opts}{$xport_defs}{$txt_xport_items}", false, $output_flag, $rrd_struc));
    /* add host and graph information */
    $xport_array["meta"]["title_cache"] = $graph["title_cache"];
    $xport_array["meta"]["vertical_label"] = $graph["vertical_label"];
    $xport_array["meta"]["local_graph_id"] = $local_graph_id;
    $xport_array["meta"]["host_id"] = $graph["host_id"];
    return $xport_array;
}