#!/usr/bin/env php /cli/ and NETAVO-BNG-MIB.mib to * /resource/snmp_queries/, then run as the user the poller runs as: * * --add-host --host-id=N Graph everything the device answers. Safe to repeat: an object * that already has a data source on the device is left alone. * --list --host-id=N Show what would be graphed. Changes nothing. */ foreach (array('/../include/cli_check.php', '/../site/include/cli_check.php') as $inc) { if (file_exists(__DIR__ . $inc)) { require(__DIR__ . $inc); break; } } if (!isset($config)) { fwrite(STDERR, "FATAL: not in a Cacti cli/ directory (include/cli_check.php not found)\n"); exit(1); } require_once($config['base_path'] . '/lib/api_automation_tools.php'); require_once($config['base_path'] . '/lib/api_data_source.php'); require_once($config['base_path'] . '/lib/api_graph.php'); require_once($config['base_path'] . '/lib/api_device.php'); require_once($config['base_path'] . '/lib/data_query.php'); require_once($config['base_path'] . '/lib/poller.php'); require_once($config['base_path'] . '/lib/snmp.php'); require_once($config['base_path'] . '/lib/template.php'); require_once($config['base_path'] . '/lib/utility.php'); require_once($config['base_path'] . '/lib/variables.php'); define('BNG_OID', '.1.3.6.1.4.1.66418'); define('SUBSCRIBER_TABLE', BNG_OID . '.22.'); define('MIB_FILE', 'NETAVO-BNG-MIB.mib'); /* Cacti's stock single-OID templates, by hash so a renamed copy is still found. */ define('GAUGE_GT_HASH', '010b90500e1fc6a05abfd542940584d0'); define('GAUGE_DT_HASH', 'd429e4a6019c91e6e84562593c1968ca'); define('COUNTER_NAME', 'NetavoBng - Counter OID'); define('DATA_SOURCE_TYPE_COUNTER', 2); $mode = ''; $host_id = 0; foreach (array_slice($_SERVER['argv'], 1) as $arg) { if (preg_match('/^--(add-host|list)$/', $arg, $m)) { $mode = $m[1]; } elseif (preg_match('/^--host-id=(\d+)$/', $arg, $m)) { $host_id = (int)$m[1]; } else { fwrite(STDERR, "unknown argument: $arg\n"); exit(1); } } if ($mode == '' || !$host_id) { fwrite(STDERR, "usage: bng_cacti_box.php --add-host --host-id=N | --list --host-id=N\n"); exit(1); } function fatal($msg) { fwrite(STDERR, "FATAL: $msg\n"); exit(1); } /* Numeric OID => array(object name, SYNTAX), from the MIB file. Empty if the file is not installed; the graphs are then titled by OID. */ function mib_names() { global $config; $path = ''; foreach (array(__DIR__, $config['base_path'] . '/resource/snmp_queries') as $dir) { if (file_exists("$dir/" . MIB_FILE)) { $path = "$dir/" . MIB_FILE; break; } } if ($path == '') { echo "NOTE: " . MIB_FILE . " not found beside this script or in resource/snmp_queries; titles will be OIDs\n"; return array(); } $text = file_get_contents($path); $parent = array(); $syntax = array(); preg_match_all('/^(\w+)[ \t]+(?:OBJECT IDENTIFIER|MODULE-IDENTITY|OBJECT-TYPE)\b(.*?)::=\s*\{\s*(\w+)\s+(\d+)\s*\}/ms', $text, $all, PREG_SET_ORDER); foreach ($all as $m) { $parent[$m[1]] = array($m[3], $m[4]); if (preg_match('/\bSYNTAX\s+(\w+)/', $m[2], $sx)) { $syntax[$m[1]] = $sx[1]; } } $names = array(); foreach ($parent as $name => $unused) { $oid = ''; for ($n = $name, $depth = 0; isset($parent[$n]) && $depth < 16; $n = $parent[$n][0], $depth++) { $oid = '.' . $parent[$n][1] . $oid; } if ($n == 'enterprises') { $names['.1.3.6.1.4.1' . $oid] = array($name, isset($syntax[$name]) ? $syntax[$name] : ''); } } return $names; } /* "bngAddressPoolUtilPct" => "Address Pool Util Pct" */ function readable($name) { $name = preg_replace('/^bng(?=[A-Z])/', '', $name); return trim(preg_replace('/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/', ' ', $name)); } /* Everything the device answers under the enterprise OID: oid => array(type, value). */ function walk_device($host) { if (!class_exists('SNMP')) fatal('the PHP snmp extension is required'); $timeout = max(1000, (int)$host['snmp_timeout']) * 1000; if ($host['snmp_version'] == 3) { $s = new SNMP(SNMP::VERSION_3, $host['hostname'] . ':' . $host['snmp_port'], $host['snmp_username'], $timeout, 2); $priv = $host['snmp_priv_passphrase'] != ''; $ok = $s->setSecurity( $priv ? 'authPriv' : 'authNoPriv', $host['snmp_auth_protocol'], $host['snmp_password'], $priv ? preg_replace('/^AES128$/', 'AES', $host['snmp_priv_protocol']) : '', $priv ? $host['snmp_priv_passphrase'] : '', $host['snmp_context']); if (!$ok) fatal('SNMPv3 security parameters were refused: ' . $s->getError()); } else { $s = new SNMP($host['snmp_version'] == 1 ? SNMP::VERSION_1 : SNMP::VERSION_2c, $host['hostname'] . ':' . $host['snmp_port'], $host['snmp_community'], $timeout, 2); } $s->valueretrieval = SNMP_VALUE_OBJECT | SNMP_VALUE_PLAIN; $s->oid_output_format = SNMP_OID_OUTPUT_NUMERIC; $s->exceptions_enabled = 0; /* Subtree by subtree, so the per-subscriber table is never fetched at all. */ $out = array(); for ($sub = 1; $sub <= 64; $sub++) { if (BNG_OID . ".$sub." == SUBSCRIBER_TABLE) continue; $rows = @$s->walk(BNG_OID . ".$sub", false, 20); if (!is_array($rows)) continue; foreach ($rows as $oid => $v) { if (is_object($v) && strpos($oid, BNG_OID . ".$sub.") === 0) { $out[$oid] = array($v->type, $v->value); } } } $s->close(); return $out; } /* The metrics to graph: array(oid, title, is_counter), in OID order. */ function metrics($walk, $names) { /* PHP reports Gauge32 and Counter32 as the same type, so only Counter64 is known to be a counter from the walk; for the rest the MIB's SYNTAX decides, and a gauge is assumed without it. */ $numeric = array(SNMP_INTEGER, SNMP_UNSIGNED, SNMP_COUNTER, SNMP_TIMETICKS, SNMP_COUNTER64); /* A table row is labelled by its first text column (a pool's or a port's name) when it has one, else by its index. Text values keyed by "|". */ $labels = array(); $located = array(); $in_table = array(); foreach ($walk as $oid => $tv) { /* longest known prefix */ $parts = explode('.', $oid); $index = array(); while (cacti_sizeof($parts) > 8 && !isset($names[implode('.', $parts)])) { array_unshift($index, array_pop($parts)); } $object = implode('.', $parts); $located[$oid] = array($object, implode('.', $index)); $entry = substr($object, 0, strrpos($object, '.')); /* A column of a table (its parent is the table's Entry), not a scalar's .0 instance. */ $in_table[$oid] = isset($names[$entry]) && substr($names[$entry][0], -5) == 'Entry'; if ($tv[0] == SNMP_OCTET_STR && $in_table[$oid]) { $key = $entry . '|' . implode('.', $index); if (!isset($labels[$key]) && trim($tv[1]) != '') { $labels[$key] = trim($tv[1]); } } } $out = array(); foreach ($walk as $oid => $tv) { if (!in_array($tv[0], $numeric)) continue; list($object, $index) = $located[$oid]; $counter = $tv[0] == SNMP_COUNTER64 || (isset($names[$object]) && strpos($names[$object][1], 'Counter') === 0); $title = isset($names[$object]) ? readable($names[$object][0]) : ltrim(substr($oid, strlen(BNG_OID)), '.'); if ($in_table[$oid]) { $entry = substr($object, 0, strrpos($object, '.')); $label = isset($labels["$entry|$index"]) ? $labels["$entry|$index"] : $index; /* "Worker Rx Pps - 2", "Address Pool Used - fttx-south-v4" */ $title .= ' - ' . $label; } $out[] = array($oid, $title . ($counter ? ' (per sec)' : ''), $counter); } usort($out, function ($a, $b) { return strnatcmp($a[0], $b[0]); }); return $out; } /* The template-level data source item of a data template. */ function template_rrd($data_template_id) { return (int)db_fetch_cell_prepared('SELECT id FROM data_template_rrd WHERE data_template_id = ? AND local_data_id = 0 ORDER BY id LIMIT 1', array($data_template_id)); } /* array(graph template id, data template id) for gauges and for counters. The counter pair is a copy of Cacti's stock single-OID pair with the data source type set to COUNTER. */ function templates() { $g_gt = (int)db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE hash = ?', array(GAUGE_GT_HASH)); $g_dt = (int)db_fetch_cell_prepared('SELECT id FROM data_template WHERE hash = ?', array(GAUGE_DT_HASH)); if (!$g_gt || !$g_dt) fatal("Cacti's stock 'SNMP - Generic OID Template' graph and data templates are required"); $c_dt = (int)db_fetch_cell_prepared('SELECT id FROM data_template WHERE name = ?', array(COUNTER_NAME)); if (!$c_dt) { api_duplicate_data_source(0, $g_dt, COUNTER_NAME); $c_dt = (int)db_fetch_cell_prepared('SELECT id FROM data_template WHERE name = ?', array(COUNTER_NAME)); if (!$c_dt) fatal('could not create the counter data template'); db_execute_prepared('UPDATE data_template_rrd SET data_source_type_id = ? WHERE data_template_id = ? AND local_data_id = 0', array(DATA_SOURCE_TYPE_COUNTER, $c_dt)); echo "created data template: " . COUNTER_NAME . " (id $c_dt)\n"; } $c_gt = (int)db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE name = ?', array(COUNTER_NAME)); if (!$c_gt) { api_duplicate_graph(0, $g_gt, COUNTER_NAME, false); $c_gt = (int)db_fetch_cell_prepared('SELECT id FROM graph_templates WHERE name = ?', array(COUNTER_NAME)); if (!$c_gt) fatal('could not create the counter graph template'); db_execute_prepared('UPDATE graph_templates_item SET task_item_id = ? WHERE graph_template_id = ? AND local_graph_id = 0 AND task_item_id = ?', array(template_rrd($c_dt), $c_gt, template_rrd($g_dt))); echo "created graph template: " . COUNTER_NAME . " (id $c_gt)\n"; } return array(false => array($g_gt, $g_dt), true => array($c_gt, $c_dt)); } /* Does the device already have a data source for this OID? */ function has_data_source($host_id, $oid) { return (bool)db_fetch_cell_prepared("SELECT dl.id FROM data_local dl JOIN data_template_data dtd ON dtd.local_data_id = dl.id JOIN data_input_fields dif ON dif.data_input_id = dtd.data_input_id AND dif.data_name = 'oid' JOIN data_input_data did ON did.data_template_data_id = dtd.id AND did.data_input_field_id = dif.id WHERE dl.host_id = ? AND did.value = ? LIMIT 1", array($host_id, $oid)); } function create_graph($host_id, $graph_template_id, $data_template_id, $oid, $title) { $field_id = db_fetch_cell_prepared("SELECT dif.id FROM data_template_data dtd JOIN data_input_fields dif ON dif.data_input_id = dtd.data_input_id AND dif.data_name = 'oid' AND dif.input_output = 'in' WHERE dtd.data_template_id = ? AND dtd.local_data_id = 0", array($data_template_id)); if (!$field_id) fatal("data template $data_template_id has no oid input field"); $sv = array($graph_template_id => array('custom_data' => array($data_template_id => array($field_id => $oid)))); $ret = create_complete_graph_from_template($graph_template_id, $host_id, null, $sv); if (!is_array($ret) || !isset($ret['local_graph_id'])) fatal("graph creation failed for $oid"); db_execute_prepared('UPDATE graph_templates_graph SET title = ? WHERE local_graph_id = ?', array('|host_description| - ' . $title, $ret['local_graph_id'])); update_graph_title_cache($ret['local_graph_id']); if (isset($ret['local_data_id']) && cacti_sizeof($ret['local_data_id'])) { foreach ($ret['local_data_id'] as $local_data_id) { db_execute_prepared('UPDATE data_template_data SET name = ? WHERE local_data_id = ?', array('|host_description| - ' . $title, $local_data_id)); update_data_source_title_cache($local_data_id); push_out_host($host_id, $local_data_id); } } db_execute_prepared('REPLACE INTO host_graph (host_id, graph_template_id) VALUES (?, ?)', array($host_id, $graph_template_id)); } $host = db_fetch_row_prepared("SELECT * FROM host WHERE id = ? AND deleted = ''", array($host_id)); if (!cacti_sizeof($host)) fatal("no device with id $host_id"); $walk = walk_device($host); if (!cacti_sizeof($walk)) { fatal("{$host['description']} answered nothing under " . BNG_OID . " - check SNMP access, and that it is a NetavoBNG appliance"); } $metrics = metrics($walk, mib_names()); if ($mode == 'list') { foreach ($metrics as $m) { printf("%-34s %-7s %s%s\n", $m[0], $m[2] ? 'counter' : 'gauge', $m[1], has_data_source($host_id, $m[0]) ? ' [exists]' : ''); } echo cacti_sizeof($metrics) . " metrics on {$host['description']}\n"; exit(0); } $templates = templates(); $created = 0; foreach ($metrics as $m) { list($oid, $title, $counter) = $m; if (has_data_source($host_id, $oid)) continue; create_graph($host_id, $templates[$counter][0], $templates[$counter][1], $oid, $title); $created++; } printf("%s (host %d): %d metrics, %d graphs created, %d already present\n", $host['description'], $host_id, cacti_sizeof($metrics), $created, cacti_sizeof($metrics) - $created);