initial commit; version 22.5.12042

This commit is contained in:
2022-12-12 23:28:25 -05:00
commit af1b03d79f
17653 changed files with 22692970 additions and 0 deletions

1
html/includes/.htaccess Normal file
View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1,37 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
if ($_SESSION['userlevel'] >= 8) {
if (is_intnum($vars['form_alert_table_id']) && request_token_valid($vars)) {
$alert_entry = get_alert_entry_by_id($vars['form_alert_table_id']);
$update_array = array();
if ($alert_entry['ignore_until_ok'] != 1) { $update_array['ignore_until_ok'] = '1'; }
if ($alert_entry['alert_status'] == 0) { $update_array['alert_status'] = '3'; }
if (count($update_array)) {
//r($alert_entry);
dbUpdate($update_array, 'alert_table', 'alert_table_id = ?', array($alert_entry['alert_table_id']));
$alert_device = device_by_id_cache($alert_entry['device_id']);
print_message("Alert entry [{$vars['form_alert_table_id']}] for device '{$alert_device['hostname']}' suppressed.");
}
unset($update_array);
// FIXME - eventlog? audit log?
}
}
// EOF

View File

@ -0,0 +1,25 @@
<?php
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
if (strlen($vars['role_name']) &&
strlen($vars['role_descr']))
{
$oid_id = dbInsert('roles', array('role_descr' => $vars['role_descr'],
'role_name' => $vars['role_name'])
);
if ($oid_id)
{
print_success("<strong>SUCCESS:</strong> Added role");
}
else
{
print_warning("<strong>WARNING:</strong> Role not added");
}
}
else
{
print_error("<strong>ERROR:</strong> All fields must be completed to add a new role.");
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2020 Observium Limited
*
*/
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
if (isset($vars['entity_id']))
{
} // use entity_id
elseif (isset($vars[$vars['entity_type'] . '_entity_id'])) // use type_entity_id
{
$vars['entity_id'] = $vars[$vars['entity_type'] . '_entity_id'];
}
if (!is_array($vars['entity_id']))
{
$vars['entity_id'] = array($vars['entity_id']);
}
foreach ($vars['entity_id'] as $entity_id)
{
if (get_entity_by_id_cache($vars['entity_type'], $entity_id)) // Skip not exist entities
{
if (!dbExist('roles_entity_permissions', '`role_id` = ? AND `entity_type` = ? AND `entity_id` = ?',
array($vars['role_id'], $vars['entity_type'], $entity_id)
))
{
if(!in_array($vars['access'], array('ro', 'rw'))) { $vars['access'] = 'ro'; }
dbInsert(array('entity_id' => $entity_id, 'entity_type' => $vars['entity_type'], 'role_id' => $vars['role_id'], 'access' => $vars['access']),
'roles_entity_permissions'
);
}
} else { print_error('Error: Invalid Entity.'); }
}
}
// EOF

View File

@ -0,0 +1,37 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2020 Observium Limited
*
*/
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
if (isset($vars['entity_id']))
{
} // use entity_id
elseif (isset($vars[$vars['entity_type'] . '_entity_id'])) // use type_entity_id
{
$vars['entity_id'] = $vars[$vars['entity_type'] . '_entity_id'];
}
$where = '`role_id` = ? AND `entity_type` = ?' . generate_query_values($vars['entity_id'], 'entity_id');
//if (@dbFetchCell("SELECT COUNT(*) FROM `entity_permissions` WHERE " . $where, array($vars['user_id'], $vars['entity_type'])))
if (dbExist('roles_entity_permissions', $where, array($vars['role_id'], $vars['entity_type'])))
{
dbDelete('roles_entity_permissions', $where, array($vars['role_id'], $vars['entity_type']));
//print_vars(dbError());
} else { }
}
echo ("nope"); // Hrm?
// EOF

View File

@ -0,0 +1,18 @@
<?php
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
foreach ($vars['permission'] as $permission)
{
if(isset($config['permissions'][$permission]))
{
if (!dbExist('roles_permissions', '`role_id` = ? AND `permission` = ?',
array($vars['role_id'], $permission)
))
{
dbInsert(array('permission' => $permission, 'role_id' => $vars['role_id']), 'roles_permissions');
}
}
}
}

View File

@ -0,0 +1,12 @@
<?php
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
$where = '`role_id` = ? AND `permission` = ?';
if (dbExist('roles_permissions', $where, array($vars['role_id'], $vars['permission'])))
{
dbDelete('roles_permissions', $where, array($vars['role_id'], $vars['permission']));
} else { }
}

View File

@ -0,0 +1,45 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2020 Observium Limited
*
*/
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
if (!is_array($vars['user_id'])) {
$vars['user_ids'] = array($vars['user_id']);
} else {
$vars['user_ids'] = $vars['user_id'];
}
if (!is_array($vars['role_id'])) {
$vars['role_id'] = array($vars['role_id']);
}
$user_list = auth_user_list();
foreach ($vars['user_ids'] as $user_id) {
if (is_array($user_list[$user_id])) {
foreach ($vars['role_id'] as $role_id) {
if (!dbExist('roles_users', '`role_id` = ? AND `user_id` = ? AND `auth_mechanism` = ?', [ $role_id, $user_id, $config['auth_mechanism'] ]))
{
dbInsert([ 'user_id' => $user_id, 'role_id' => $role_id, 'auth_mechanism' => $config['auth_mechanism'] ], 'roles_users');
} else {
print_warning("<strong>WARNING:</strong> User " . $user_id . " is already a role " . $role_id . " member.");
}
}
} else {
print_error("<strong>ERROR:</strong> Invalid user id.");
}
}
}
// EOF

View File

@ -0,0 +1,24 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2020 Observium Limited
*
*/
if ($_SESSION['userlevel'] == 10 && request_token_valid($vars)) // Only valid forms from level 10 users
{
$where = '`role_id` = ? AND `user_id` = ? AND `auth_mechanism` = ?';
$params = [ $vars['role_id'], $vars['user_id'], $config['auth_mechanism'] ];
if (dbExist('roles_users', $where, $params))
{
dbDelete('roles_users', $where, $params);
} else { }
}
// EOF

View File

@ -0,0 +1,212 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
/// CONTACTS ACTIONS
$readonly = $_SESSION['userlevel'] < 10;
if (!$readonly)
{
// FIXME: move all actions to separate include(s) with common options!
if (isset($vars['submit']) && !isset($vars['action']))
{
// Convert submit to action (for compatibility)
$vars['action'] = $vars['submit'];
}
if (isset($vars['action']) && isset($vars['contact_id']))
{
switch ($vars['action'])
{
case 'add_alert_checker_contact': // new ([action]_[type]_[action_target]_[param_to_change])
case 'associate_alert_check': // old
if (is_numeric($vars['alert_checker_id']))
{
$vars['alert_test_id'] = $vars['alert_checker_id'];
}
else if (is_numeric($vars['alert_test_id']))
{
// ok
} else {
break;
}
//$vars['contact_id'] = (array)$vars['contact_id'];
foreach ((array)$vars['contact_id'] as $contact_id)
{
if (!is_numeric($contact_id)) { continue; }
$id = dbInsert('alert_contacts_assoc', array('aca_type' => 'alert', // $vars['type']
'contact_id' => $contact_id,
'alert_checker_id' => $vars['alert_test_id']));
if ($id) { $rows_updated++; }
}
break;
case 'add_alert_checker_contactall':
if (!is_numeric($vars['alert_test_id']) || !$vars['confirm_add_all'])
{
break;
}
$exist_contacts = dbFetchColumn('SELECT `contact_id` FROM `alert_contacts_assoc` WHERE `aca_type` = ? AND `alert_checker_id` = ?', array('alert', $vars['alert_test_id']));
//print_vars($exist_contacts);
$sql = "SELECT `contact_id` FROM `alert_contacts` WHERE `contact_disabled` = 0 AND `contact_method` != 'syscontact'" .
generate_query_values($exist_contacts, 'contact_id', '!='); // exclude exist contacts
//print_vars($sql);
foreach (dbFetchColumn($sql) as $contact_id)
{
$id = dbInsert('alert_contacts_assoc', array('aca_type' => 'alert',
'contact_id' => $contact_id,
'alert_checker_id' => $vars['alert_test_id']));
if ($id) { $rows_updated++; }
}
unset($exist_contacts);
break;
case 'delete_alert_checker_contact': // new
case 'delete_alert_contact_assoc': // old
if (!is_numeric($vars['alert_test_id']))
{
break;
}
//$vars['contact_id'] = (array)$vars['contact_id'];
foreach ((array)$vars['contact_id'] as $contact_id)
{
if (!is_numeric($contact_id)) { continue; }
$rows_updated += dbDelete('alert_contacts_assoc', '`aca_type` = ? AND `contact_id` = ? AND `alert_checker_id` = ?', array('alert', $contact_id, $vars['alert_test_id']));
}
break;
case 'delete_alert_checker_contactall':
if (!is_numeric($vars['alert_test_id']) || !$vars['confirm_delete_all'])
{
break;
}
$rows_updated += dbDelete('alert_contacts_assoc', '`aca_type` = ? AND `alert_checker_id` = ?', array('alert', $vars['alert_test_id']));
break;
case 'associate_syslog_rule':
if (is_numeric($vars['la_id']))
{
//$vars['contact_id'] = (array)$vars['contact_id'];
foreach ((array)$vars['contact_id'] as $contact_id)
{
$id = dbInsert('alert_contacts_assoc', array('aca_type' => 'syslog', // $vars['type']
'contact_id' => $vars['contact_id'],
'alert_checker_id' => $vars['la_id']));
if ($id) { $rows_updated++; }
}
set_obs_attrib('syslog_rules_changed', time()); // Trigger reload syslog script
}
break;
case 'delete_syslog_checker_contact': // new
if (!is_numeric($vars['alert_test_id']))
{
break;
}
//$vars['contact_id'] = (array)$vars['contact_id'];
foreach ((array)$vars['contact_id'] as $contact_id)
{
if (!is_numeric($contact_id)) { continue; }
$rows_updated += dbDelete('alert_contacts_assoc', '`aca_type` = ? AND `contact_id` = ? AND `alert_checker_id` = ?', array('syslog', $contact_id, $vars['alert_test_id']));
}
set_obs_attrib('syslog_rules_changed', time()); // Trigger reload syslog script
break;
}
// Clean common action vars
//unset($vars['submit'], $vars['action'], $vars['confirm']);
}
}
/// END CONTACTS ACTIONS
if (!is_array($alert_rules)) { $alert_rules = cache_alert_rules(); }
/* Hardcode Device sysContact
if ($_SESSION['userlevel'] >= 7 &&
!dbExist('alert_contacts', '`contact_method` = ?', [ 'syscontact' ])) {
$syscontact = [
'contact_descr' => 'Device sysContact',
'contact_method' => 'syscontact',
'contact_endpoint' => '{"syscontact":"device"}',
//'contact_disabled' => '0',
//'contact_disabled_until' => NULL,
//'contact_message_custom' => 0,
//'contact_message_template' => NULL
];
dbInsert($syscontact, 'alert_contacts');
}
*/
$navbar['class'] = 'navbar-narrow';
$navbar['brand'] = 'Alerting';
$pages = array('alerts' => 'Alerts',
'alert_checks' => 'Alert Checkers',
'alert_log' => 'Alert Logging',
'alert_maintenance' => 'Scheduled Maintenance',
'syslog_alerts' => 'Syslog Alerts',
'syslog_rules' => 'Syslog Rules',
'contacts' => 'Contacts');
foreach ($pages as $page_name => $page_desc)
{
if ($vars['page'] == $page_name)
{
$navbar['options'][$page_name]['class'] = "active";
}
$navbar['options'][$page_name]['url'] = generate_url(array('page' => $page_name));
$navbar['options'][$page_name]['text'] = escape_html($page_desc);
if (in_array($page_name, array('alert_checks', 'alert_maintenance', 'contacts', 'syslog_rules')))
{
$navbar['options'][$page_name]['userlevel'] = 5; // Minimum user level to display item
}
}
$navbar['options']['alert_maintenance']['community'] = FALSE; // Not exist in Community Edition
$navbar['options']['update']['url'] = generate_url(array('page' => 'alert_regenerate', 'action' => 'update'));
$navbar['options']['update']['text'] = 'Rebuild';
$navbar['options']['update']['icon'] = $config['icon']['rebuild'];
$navbar['options']['update']['right'] = TRUE;
$navbar['options']['update']['userlevel'] = 10; // Minimum user level to display item
// We don't really need to highlight Regenerate, as it's not a display option, but an action.
// if ($vars['action'] == 'update') { $navbar['options']['update']['class'] = 'active'; }
$navbar['options']['sadd']['url'] = generate_url(array('page' => 'add_syslog_rule'));
$navbar['options']['sadd']['text'] = 'Add Syslog Rule';
$navbar['options']['sadd']['icon'] = $config['icon']['syslog-rule-add'];
$navbar['options']['sadd']['right'] = TRUE;
$navbar['options']['sadd']['userlevel'] = 10; // Minimum user level to display item
$navbar['options']['add']['url'] = generate_url(array('page' => 'add_alert_check'));
$navbar['options']['add']['text'] = 'Add Checker';
$navbar['options']['add']['icon'] = $config['icon']['alert-rule-add'];
$navbar['options']['add']['right'] = TRUE;
$navbar['options']['add']['userlevel'] = 10; // Minimum user level to display item
// Print out the navbar defined above
print_navbar($navbar);
unset($navbar);
// EOF

View File

@ -0,0 +1,265 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
// DOCME needs phpdoc block
function authenticate($username, $password)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_authenticate'))
{
// Can't consider remote_user setting here, as for example the LDAP plugin still needs to check
// group membership before logging in. So remote_user currently needs to be considered in
// mech_authenticate() by the module itself until we split this up, maybe...
return call_user_func($config['auth_mechanism'] . '_authenticate', $username, $password);
} else {
return call_user_func('mysql_authenticate', $username, $password);
}
}
// DOCME needs phpdoc block
function auth_can_logout()
{
global $config;
// If logged in through Apache REMOTE_USER, logout is not possible
if ($config['auth']['remote_user'])
{
return FALSE;
} else if (function_exists($config['auth_mechanism'] . '_auth_can_logout'))
{
return call_user_func($config['auth_mechanism'] . '_auth_can_logout');
} else {
return call_user_func('mysql_auth_can_logout');
}
}
/**
* Returns the URL redirection required for logout, or null if internal logout is sufficient.
* @return string logout url
*/
function auth_logout_url()
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_logout_url'))
{
return call_user_func($config['auth_mechanism'] . '_auth_logout_url');
} else {
return null;
}
}
// DOCME needs phpdoc block
function auth_can_change_password($username = "")
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_can_change_password'))
{
return call_user_func($config['auth_mechanism'] . '_auth_can_change_password', $username);
} else {
return call_user_func('mysql_auth_can_change_password', $username);
}
}
// DOCME needs phpdoc block
function auth_change_password($username, $password)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_change_password'))
{
return call_user_func($config['auth_mechanism'] . '_auth_change_password', $username, $password);
} else {
return call_user_func('mysql_auth_change_password', $username, $password);
}
}
// DOCME needs phpdoc block
function auth_usermanagement()
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_usermanagement'))
{
return call_user_func($config['auth_mechanism'] . '_auth_usermanagement');
} else {
return call_user_func('mysql_auth_usermanagement');
}
}
// DOCME needs phpdoc block
function adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd = '1', $description = "")
{
global $config;
if (function_exists($config['auth_mechanism'] . '_adduser'))
{
return call_user_func($config['auth_mechanism'] . '_adduser', $username, $password, $level, $email, $realname, $can_modify_passwd, $description);
} else {
return call_user_func('mysql_adduser', $username, $password, $level, $email, $realname, $can_modify_passwd, $description);
}
}
// DOCME needs phpdoc block
function auth_user_exists($username)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_user_exists'))
{
return call_user_func($config['auth_mechanism'] . '_auth_user_exists', $username);
} else {
return call_user_func('mysql_auth_user_exists', $username);
}
}
// DOCME needs phpdoc block
function auth_user_level($username)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_user_level'))
{
return call_user_func($config['auth_mechanism'] . '_auth_user_level', $username);
} else {
return call_user_func('mysql_auth_user_level', $username);
}
}
// DOCME needs phpdoc block
function auth_user_level_permissions($user_level)
{
$user = array('level' => -1, 'permission' => 0); // level -1 equals "not exist" user
if (is_numeric($user_level))
{
krsort($GLOBALS['config']['user_level']); // Order levels from max to low
foreach ($GLOBALS['config']['user_level'] as $level => $entry)
{
if ($user_level >= $level)
{
$user['level'] = $level; // Real (normalized) user level
$user['permission'] = $entry['permission'];
break;
}
}
}
// Convert permission flags to Boolean permissions
$user['permission_admin'] = is_flag_set(OBS_PERMIT_ALL, $user['permission'], TRUE); // Administrator
$user['permission_edit'] = is_flag_set(OBS_PERMIT_EDIT, $user['permission']); // Limited Edit
$user['permission_secure'] = is_flag_set(OBS_PERMIT_SECURE, $user['permission']); // Secure Read
$user['permission_read'] = is_flag_set(OBS_PERMIT_READ, $user['permission']); // Global Read
$user['permission_access'] = is_flag_set(OBS_PERMIT_ACCESS, $user['permission']); // Access (logon) allowed
// Set quick boolen flag that user limited
$user['limited'] = !$user['permission_read'] && !$user['permission_secure'] && !$user['permission_edit'] && !$user['permission_admin'];
return $user;
}
// DOCME needs phpdoc block
function auth_user_id($username)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_user_id'))
{
return call_user_func($config['auth_mechanism'] . '_auth_user_id', $username);
} else {
return call_user_func('mysql_auth_user_id', $username);
}
}
// DOCME needs phpdoc block
function auth_username_by_id($user_id)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_username_by_id'))
{
return call_user_func($config['auth_mechanism'] . '_auth_username_by_id', $user_id);
} else {
return call_user_func('mysql_auth_username_by_id', $user_id);
}
}
// DOCME needs phpdoc block
function deluser($username)
{
global $config;
if (function_exists($config['auth_mechanism'] . '_deluser'))
{
return call_user_func($config['auth_mechanism'] . '_deluser', $username);
} else {
return call_user_func('mysql_deluser', $username);
}
}
// DOCME needs phpdoc block
function auth_user_list()
{
global $config;
if (function_exists($config['auth_mechanism'] . '_auth_user_list'))
{
$user_list_sort = call_user_func($config['auth_mechanism'] . '_auth_user_list');
} else {
$user_list_sort = call_user_func('mysql_auth_user_list');
}
// Process the user list here to provide all of the additional data used elsewhere in the UI
// This prepares user_ids for LDAP to be used in AJAX and other places
$user_list_sort = array_sort_by($user_list_sort, 'level', SORT_DESC, SORT_NUMERIC, 'username', SORT_ASC, SORT_STRING);
$user_list = array();
foreach ($user_list_sort as $entry)
{
humanize_user($entry);
/*
if (isset($user_list[$entry['user_id']]))
{
r($user_list[$entry['user_id']]);
r($entry);
break;
}
*/
$user_list[$entry['user_id']] = $entry;
$user_list[$entry['user_id']]['name'] = escape_html($entry['username']);
if ($entry['row_class'])
{
$user_list[$entry['user_id']]['class'] = 'bg-'.$entry['row_class'];
}
$user_list[$entry['user_id']]['group'] = $entry['level_label'];
$user_list[$entry['user_id']]['subtext'] = $entry['realname'];
}
unset($user_list_sort);
return $user_list;
}
// DOCME needs phpdoc block
function auth_user_info($username)
{
if (function_exists($GLOBALS['config']['auth_mechanism'] . '_auth_user_info'))
{
return call_user_func($GLOBALS['config']['auth_mechanism'] . '_auth_user_info', $username);
} else {
return call_user_func('mysql_auth_user_info', $username);
}
}
// EOF

View File

@ -0,0 +1,857 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
//print_r($_SERVER);
// OBS_API set to TRUE only in html/api/index.php
if (!defined('OBS_API')) { define('OBS_API', FALSE); }
// OBS_GRAPH set to TRUE only in html/graph.php
if (!defined('OBS_GRAPH')) { define('OBS_GRAPH', FALSE); }
// Detect AJAX request
define('OBS_AJAX', (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') ||
str_starts($_SERVER['REQUEST_URI'], '/ajax/'));
$debug_auth = FALSE; // Do not use this debug unless you Observium Developer ;)
if (PHP_VERSION_ID < 70100)
{
// Use sha1 to generate the session ID (option removed in php 7.1)
// session.sid_length (Number of session ID characters - 22 to 256.
// session.sid_bits_per_character (Bits used per character - 4 to 6.
@ini_set('session.hash_function', '1');
}
@ini_set('session.referer_check', ''); // This config was causing so much trouble with Chrome
@ini_set('session.name', 'OBSID'); // Session name
@ini_set('session.use_cookies', '1'); // Use cookies to store the session id on the client side
@ini_set('session.use_only_cookies', '1'); // This prevents attacks involved passing session ids in URLs
@ini_set('session.use_trans_sid', '0'); // Disable SID (no session id in url)
$currenttime = time();
$lifetime = 60*60*24; // Session lifetime (default one day)
$cookie_expire = $currenttime + 60*60*24*14; // Cookies expire time (14 days)
$cookie_path = '/'; // Cookie path
$cookie_domain = ''; // RFC 6265, to have a "host-only" cookie is to NOT set the domain attribute.
/// FIXME. Some old browsers not supports secure/httponly cookies params.
$cookie_https = is_ssl();
// AJAX request not have access to cookies with httponly, and for example widgets lost auth
$cookie_httponly = FALSE;
//$cookie_httponly = TRUE;
// Use custom session lifetime
if (is_numeric($GLOBALS['config']['web_session_lifetime']) && $GLOBALS['config']['web_session_lifetime'] >= 0) {
$lifetime = (int)$GLOBALS['config']['web_session_lifetime'];
}
@ini_set('session.gc_maxlifetime', $lifetime); // Session lifetime (for non "remember me" sessions)
if (PHP_VERSION_ID >= 70300)
{
// Allows servers to assert that a cookie ought not to be sent along with cross-site requests.
// Lax will sent the cookie for cross-domain GET requests, while Strict will not
//@ini_set('session.cookie_samesite', 'Strict');
$cookie_params = [
'lifetime' => $lifetime,
'path' => $cookie_path,
'domain' => $cookie_domain,
'secure' => $cookie_https,
'httponly' => $cookie_httponly,
'samesite' => 'Strict'
];
session_set_cookie_params($cookie_params);
} else {
session_set_cookie_params($lifetime, $cookie_path, $cookie_domain, $cookie_https, $cookie_httponly);
}
//session_cache_limiter('private');
//register_shutdown_function('session_commit'); // This already done at end of script run
if (!session_is_active()) {
session_regenerate();
}
if ($debug_auth && empty($_SESSION['authenticated']))
{
logfile('debug_auth.log', __LINE__ . " NOT Authenticated!!!. IP=[" . get_remote_addr($config['web_session_ip_by_header']) . "]. URL=[" . $_SERVER['REQUEST_URI'] . "]");
logfile('debug_auth.log', __LINE__ . ' ' . json_encode($_SESSION));
}
// Fallback to MySQL auth as default - FIXME do this in sqlconfig file?
if (!isset($config['auth_mechanism']))
{
$config['auth_mechanism'] = "mysql";
}
// Trust Apache authenticated user, if configured to do so and username is available
if ($config['auth']['remote_user'] && $_SERVER['REMOTE_USER'] != '')
{
session_set_var('username', $_SERVER['REMOTE_USER']);
}
$auth_file = $config['html_dir'].'/includes/authentication/' . $config['auth_mechanism'] . '.inc.php';
if (is_file($auth_file)) {
if (isset($_SESSION['auth_mechanism']) && $_SESSION['auth_mechanism'] != $config['auth_mechanism'])
{
// Logout if AUTH mechanism changed
session_logout();
reauth_with_message('Authentication mechanism changed, please log in again!');
} else {
session_set_var('auth_mechanism', $config['auth_mechanism']);
}
// Always load mysql as backup
include($config['html_dir'].'/includes/authentication/mysql.inc.php');
// Load primary module if not mysql
if ($config['auth_mechanism'] !== 'mysql') { include($auth_file); }
// Include base auth functions calls
include($config['html_dir'].'/includes/authenticate-functions.inc.php');
} else {
session_logout();
reauth_with_message('Invalid auth_mechanism defined, please correct your configuration!');
}
// Check logout
if ($_SESSION['authenticated'] && str_starts(ltrim($_SERVER['REQUEST_URI'], '/'), 'logout')) {
// Do not use $vars and get_vars here!
//print_vars($_SERVER['REQUEST_URI']);
if (auth_can_logout())
{
// No need for a feedback message if user requested a logout
session_logout(function_exists('auth_require_login'));
$redirect = auth_logout_url();
if ($redirect)
{
redirect_to_url($redirect);
exit();
}
}
redirect_to_url($config['base_url']);
exit();
}
$user_unique_id = session_unique_id(); // Get unique user id and check if IP changed (if required by config)
// Store logged remote IP with real proxied IP (if configured and available)
$remote_addr = get_remote_addr();
$remote_addr_header = get_remote_addr(TRUE); // Remote addr by http header
if ($remote_addr_header && $remote_addr != $remote_addr_header)
{
$remote_addr = $remote_addr_header . ' (' . $remote_addr . ')';
}
// Check if allowed auth by CIDR
$auth_allow_cidr = TRUE;
if (isset($config['web_session_cidr']) && count($config['web_session_cidr'])) {
$auth_allow_cidr = match_network(get_remote_addr($config['web_session_ip_by_header']), $config['web_session_cidr']);
}
if (!$_SESSION['authenticated']) {
if (isset($_GET['username']) && isset($_GET['password']) &&
is_string($_GET['username']) && is_string($_GET['password'])) {
session_set_var('username', $_GET['username']);
$auth_password = $_GET['password'];
//r($_GET);
//r($_SESSION);
} elseif (isset($_POST['username']) && isset($_POST['password']) &&
is_string($_POST['username']) && is_string($_POST['password']))
{
session_set_var('username', $_POST['username']);
$auth_password = $_POST['password'];
} elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
session_set_var('username', $_SERVER['PHP_AUTH_USER']);
$auth_password = $_SERVER['PHP_AUTH_PW'];
} elseif (OBS_ENCRYPT && isset($_COOKIE['ckey']) && is_string($_COOKIE['ckey'])) {
///DEBUG
if ($debug_auth) {
$debug_log = $GLOBALS['config']['log_dir'] . '/debug_cookie_' . date("Y-m-d_H:i:s") . '.log';
file_put_contents($debug_log, var_export($_SERVER, TRUE), FILE_APPEND);
file_put_contents($debug_log, var_export($_SESSION, TRUE), FILE_APPEND);
file_put_contents($debug_log, var_export($_COOKIE, TRUE), FILE_APPEND);
}
$ckey = dbFetchRow("SELECT * FROM `users_ckeys` WHERE `user_uniq` = ? AND `user_ckey` = ? LIMIT 1",
[ $user_unique_id, $_COOKIE['ckey'] ]);
if (is_array($ckey)) {
if ($ckey['expire'] > $currenttime && $auth_allow_cidr) {
session_set_var('username', $ckey['username']);
$auth_password = decrypt($ckey['user_encpass'], $_COOKIE['dkey']);
// Store encrypted password
session_encrypt_password($auth_password, $user_unique_id);
// If userlevel == 0 - user disabled an can not be logon
if (auth_user_level($ckey['username']) < 1)
{
session_logout(FALSE, 'User disabled');
reauth_with_message('User login disabled');
}
session_set_var('user_ckey_id', $ckey['user_ckey_id']);
session_set_var('cookie_auth', TRUE);
dbInsert([ 'user' => $_SESSION['username'],
'address' => $remote_addr,
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'result' => 'Logged In (cookie)' ], 'authlog');
//logfile('wui_auth_cookie.log', var_export($_SERVER, TRUE)); ///DEBUG
}
}
}
}
if (isset($_COOKIE['password'])) { setcookie("password", NULL); }
if (isset($_COOKIE['username'])) { setcookie("username", NULL); }
if (isset($_COOKIE['user_id'])) { setcookie("user_id", NULL); }
$auth_success = FALSE; // Variable for check if just logged
if (isset($_SESSION['username'])) {
// Check for allowed by CIDR range
if (!$auth_allow_cidr) {
session_logout(FALSE, 'Remote IP not allowed in CIDR ranges');
reauth_with_message('Remote IP not allowed in CIDR ranges');
}
// Auth from COOKIEs
if (isset($_SESSION['cookie_auth']) && $_SESSION['cookie_auth']) {
@session_start();
$_SESSION['authenticated'] = TRUE;
$auth_success = TRUE;
dbUpdate(array('expire' => $cookie_expire), 'users_ckeys', '`user_ckey_id` = ?', array($_SESSION['user_ckey_id']));
unset($_SESSION['user_ckey_id'], $_SESSION['cookie_auth']);
session_commit();
}
// Auth from ...
if (!$_SESSION['authenticated'] && (authenticate($_SESSION['username'], $auth_password) || // login/password
(auth_usermanagement() && auth_user_level($_SESSION['origusername']) >= 10))) // FIXME?
{
// If we get here, it means the password for the user was correct (authenticate() called)
// Store encrypted password
session_encrypt_password($auth_password, $user_unique_id);
// If userlevel == 0 - user disabled and can not log in
if (auth_user_level($_SESSION['username']) < 1)
{
session_logout(FALSE, 'User disabled');
reauth_with_message('User login disabled');
exit();
}
session_set_var('authenticated', TRUE);
$auth_success = TRUE;
dbInsert(array('user' => $_SESSION['username'],
'address' => $remote_addr,
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'result' => 'Logged In'), 'authlog');
// Generate keys for cookie auth
if (isset($_POST['remember']) && OBS_ENCRYPT)
{
$ckey = md5(strgen());
$dkey = md5(strgen());
$encpass = encrypt($auth_password, $dkey);
dbDelete('users_ckeys', "`username` = ? AND `expire` < ?", array($_SESSION['username'], $currenttime - 3600)); // Remove old ckeys from DB
dbInsert(array('user_encpass' => $encpass,
'expire' => $cookie_expire,
'username' => $_SESSION['username'],
'user_uniq' => $user_unique_id,
'user_ckey' => $ckey), 'users_ckeys');
// AJAX request not have access to cookies with httponly, and for example widgets lost auth
//setcookie("ckey", $ckey, $cookie_expire, $cookie_path, $cookie_domain, $cookie_https, $cookie_httponly);
//setcookie("dkey", $dkey, $cookie_expire, $cookie_path, $cookie_domain, $cookie_https, $cookie_httponly);
setcookie("ckey", $ckey, $cookie_expire, $cookie_path, $cookie_domain, $cookie_https, FALSE);
setcookie("dkey", $dkey, $cookie_expire, $cookie_path, $cookie_domain, $cookie_https, FALSE);
session_unset_var('user_ckey_id');
}
} elseif (!$_SESSION['authenticated']) {
// Not authenticated
session_set_var('auth_message', 'Authentication Failed');
session_logout(function_exists('auth_require_login'));
}
// Retrieve user ID and permissions
if ($_SESSION['authenticated'])
{
@session_start();
if (!is_numeric($_SESSION['userlevel']) || !is_numeric($_SESSION['user_id']) || $_SESSION['user_id'] == -1)
{
$_SESSION['userlevel'] = auth_user_level($_SESSION['username']);
$_SESSION['user_id'] = auth_user_id($_SESSION['username']);
}
//$level_permissions = auth_user_level_permissions($_SESSION['userlevel']);
// If userlevel == 0 - user disabled an can not be logon
if ($_SESSION['userlevel'] == 0)
{
session_logout(FALSE, 'User disabled');
reauth_with_message('User login disabled');
exit();
}
elseif ($_SESSION['userlevel'] < 5)
{
// Store user limited flag, required for quick permissions list generate
$_SESSION['user_limited'] = TRUE;
}
session_commit();
// Hardcoded level permissions
$user_perms = array();
$perms[0] = [];
$perms[1] = ['LOGIN'];
$perms[2] = [];
$perms[3] = [];
$perms[5] = ['GLOBAL_READ'];
$perms[6] = [];
$perms[7] = [];
$perms[8] = [];
$perms[9] = [];
$perms[10] = ['ADMIN'];
foreach($perms as $level => $array)
{
if($_SESSION['userlevel'] >= $level)
{
foreach($array AS $entry) { $user_perms[$entry] = $entry; }
}
}
//print_vars($user_perms);
//print_vars($_SESSION);
//print_vars($level_permissions);
// Generate a CSRF Token
// https://stackoverflow.com/questions/6287903/how-to-properly-add-csrf-token-using-php
// For validate use: request_token_valid($vars['requesttoken'])
if (empty($_SESSION['requesttoken'])) {
try {
$requesttoken = bin2hex(random_bytes(32));
} catch(Exception $e) {
$requesttoken = bin2hex(openssl_random_pseudo_bytes(32));
}
session_set_var('requesttoken', $requesttoken);
}
// Now we can enable debug if user is privileged (Global Secure Read and greater)
if (!defined('OBS_DEBUG')) // OBS_DEBUG not defined by default for unprivileged users in definitions
{
if ($_SESSION['userlevel'] < 7 || !$debug_web_requested) // && !$config['permit_user_debug']) // Note, use $config['web_debug_unprivileged'] = TRUE;
{
// DO NOT ALLOW show debug output for users with privilege level less than "Global Secure Read"
define('OBS_DEBUG', 0);
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
//ini_set('error_reporting', 0); // Use default php config
} else {
define('OBS_DEBUG', 1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
//ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('error_reporting', E_ALL ^ E_NOTICE ^ E_WARNING);
}
}
//$a = utime();
$permissions = permissions_cache($_SESSION['user_id']);
//echo utime() - $a . 's for permissions cache';
// Add feeds & api keys after first auth
if (OBS_ENCRYPT && !OBS_GRAPH && !OBS_API && !OBS_AJAX &&
!get_user_pref($_SESSION['user_id'], 'atom_key')) {
// Generate unique token
do {
$atom_key = md5(strgen());
}
//while (dbFetchCell("SELECT COUNT(*) FROM `users_prefs` WHERE `pref` = ? AND `value` = ?;", array('atom_key', $atom_key)) > 0);
while (dbExist('users_prefs', '`pref` = ? AND `value` = ?', array('atom_key', $atom_key)));
set_user_pref($_SESSION['user_id'], 'atom_key', $atom_key);
}
}
if ($auth_success && !OBS_GRAPH && !OBS_API && !OBS_AJAX) {
// If just logged in go to request uri, unless we're debugging or in API,
// in which case we want to see authentication module output first.
if (!OBS_DEBUG) {
redirect_to_url($_SERVER['REQUEST_URI']);
} else {
print_message("Debugging mode has disabled redirect to front page; please click <a href=\"" . $_SERVER['REQUEST_URI'] . "\">here</a> to continue.");
}
exit();
}
}
// Load user defined configs
if ($_SESSION['authenticated'] && $_SESSION['user_id']) {
load_user_config($config, $_SESSION['user_id']);
}
///r($_SESSION);
///r($_COOKIE);
///r($permissions);
//logfile('debug_auth.log', __LINE__ . ' ' . 'auth session_commit() called at '.time());
//session_commit(); // Write and unblock current session (use session_set_var() and session_unset_var() for write to session variables!)
/* Session manager specific functions */
// DOCME needs phpdoc block
function session_is_active()
{
if (!is_cli())
{
if (PHP_VERSION_ID >= 50400)
{
return session_status() === PHP_SESSION_ACTIVE;
}
return session_id() !== '';
}
return FALSE;
}
/**
* Generate unique id for current user/browser, based on some unique params
*
* @return string
*/
function session_unique_id()
{
global $config, $debug_auth;
$id = $_SERVER['HTTP_USER_AGENT']; // User agent
//$id .= $_SERVER['HTTP_ACCEPT']; // Browser accept headers // WTF, this header different for main and js/ajax queries
// Less entropy than HTTP_ACCEPT, but stable!
$id .= $_SERVER['HTTP_ACCEPT_ENCODING'];
$id .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($config['web_session_ip'])
{
$remote_ip = get_remote_addr($config['web_session_ip_by_header']); // Remote address by header if configured
$config['web_session_ipv6_prefix'] = ltrim($config['web_session_ipv6_prefix'], '/');
if (is_numeric($config['web_session_ipv6_prefix']) &&
$config['web_session_ipv6_prefix'] >= 1 && $config['web_session_ipv6_prefix'] <= 127 &&
get_ip_version($remote_ip) === 6)
{
$remote_addr = Net_IPv6::getNetmask($remote_ip, (int) $config['web_session_ipv6_prefix']);
} else {
$remote_addr = $remote_ip;
}
$id .= $remote_addr; // User IP address
// Force reauth if remote IP changed
if ($_SESSION['authenticated'])
{
if (isset($_SESSION['PREV_REMOTE_ADDR']) && $remote_addr != $_SESSION['PREV_REMOTE_ADDR'])
{
if ($debug_auth)
{
logfile('debug_auth.log', __LINE__ . " IP changed. IP=[$remote_ip]. ID=[$id]. URL=[" . $_SERVER['REQUEST_URI'] . "]");
logfile('debug_auth.log', __LINE__ . ' ' . var_export($_SESSION, TRUE));
}
// FIXME. Hrm, I forgot why not just session_logout()
//session_logout();
unset($_SESSION['authenticated'],
$_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['user_encpass'], $_SESSION['password'],
$_SESSION['userlevel'],
$_SESSION['PREV_REMOTE_ADDR']);
reauth_with_message('Remote IP has changed.');
}
session_set_var('PREV_REMOTE_ADDR', $remote_addr); // Store current remote IP
}
}
// Force reauth if user agent changed
if ($_SESSION['authenticated'])
{
// Check and validate if User agent not changed
$ua = md5($_SERVER['HTTP_USER_AGENT']);
if (!isset($_SESSION['ua']))
{
session_set_var('ua', $ua);
}
if ($_SESSION['ua'] != $ua)
{
if ($debug_auth)
{
logfile('debug_auth.log', __LINE__ . " UA changed. IP=[" . get_remote_addr($config['web_session_ip_by_header']) . "]. ID=[$id]. URL=[" . $_SERVER['REQUEST_URI'] . "]");
logfile('debug_auth.log', __LINE__ . ' ' . var_export($_SESSION, TRUE));
}
session_logout();
reauth_with_message('Browser has changed.');
}
//if ($debug_auth)
//{
// logfile('debug_auth.log', __LINE__ . ' ' . "IP=[".get_remote_addr($config['web_session_ip_by_header'])."]. ID=[$id]. URL=[".$_SERVER['REQUEST_URI']."]");
//}
}
$user_unique_id = md5($id);
// Next required JS cals:
// resolution = screen.width+"x"+screen.height+"x"+screen.colorDepth;
// timezone = new Date().getTimezoneOffset();
if (FALSE && $debug_auth)
{
$debug_log_array = array($user_unique_id, $remote_addr, $_SERVER['HTTP_USER_AGENT'],
$_SERVER['HTTP_ACCEPT_ENCODING'], $_SERVER['HTTP_ACCEPT_LANGUAGE'],
$_COOKIE['OBSID']);
logfile('debug_auth.log', __LINE__ . ' ' . json_encode($debug_log_array));
}
//print_vars($id);
return $user_unique_id;
}
/**
* Store encrypted password in $_SESSION['user_encpass'], required for some auth mechanism, ie ldap
*
* @param string $auth_password Plain password
* @param string $key Key for password encrypt
* @return string Encrypted password
*/
function session_encrypt_password($auth_password, $key)
{
// Store encrypted password
if ($GLOBALS['config']['auth_mechanism'] === 'ldap' &&
!($GLOBALS['config']['auth_ldap_bindanonymous'] || strlen($GLOBALS['config']['auth_ldap_binddn'].$GLOBALS['config']['auth_ldap_bindpw'])))
{
if (OBS_ENCRYPT)
{
if (OBS_ENCRYPT_MODULE === 'mcrypt')
{
$key .= get_unique_id();
}
// For some admin LDAP functions required store encrypted password in session (userslist)
session_set_var('user_encpass', encrypt($auth_password, $key));
} else {
//session_set_var('user_encpass', base64_encode($auth_password));
session_set_var('encrypt_required', 1);
}
}
return $_SESSION['user_encpass'];
}
// DOCME needs phpdoc block
function session_logout($relogin = FALSE, $message = NULL)
{
global $debug_auth;
// Save auth failure message for later re-use
$auth_message = $_SESSION['auth_message'];
if ($_SESSION['authenticated'])
{
$auth_log = 'Logged Out';
} else {
$auth_log = 'Authentication Failure';
}
if ($message)
{
$auth_log .= ' (' . $message . ')';
}
if ($debug_auth)
{
$debug_log = $GLOBALS['config']['log_dir'].'/debug_logout_'.date("Y-m-d_H:i:s").'.log';
file_put_contents($debug_log, var_export($_SERVER, TRUE), FILE_APPEND);
file_put_contents($debug_log, var_export($_SESSION, TRUE), FILE_APPEND);
file_put_contents($debug_log, var_export($_COOKIE, TRUE), FILE_APPEND);
}
// Store logged remote IP with real proxied IP (if configured and avialable)
$remote_addr = get_remote_addr();
$remote_addr_header = get_remote_addr(TRUE); // Remote addr by http header
if ($remote_addr_header && $remote_addr != $remote_addr_header)
{
$remote_addr = $remote_addr_header . ' (' . $remote_addr . ')';
}
dbInsert(array('user' => $_SESSION['username'],
'address' => $remote_addr,
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'result' => $auth_log), 'authlog');
if (isset($_COOKIE['ckey'])) dbDelete('users_ckeys', "`username` = ? AND `user_ckey` = ?", array($_SESSION['username'], $_COOKIE['ckey'])); // Remove old ckeys from DB
// Unset cookies
$cookie_params = session_get_cookie_params();
$past = time() - 3600;
foreach ($_COOKIE as $cookie => $value)
{
if (empty($cookie_params['domain']))
{
setcookie($cookie, '', $past, $cookie_params['path']);
} else {
setcookie($cookie, '', $past, $cookie_params['path'], $cookie_params['domain']);
}
}
unset($_COOKIE);
// Clean cache if possible
$cache_tags = array('__anonymous');
if ($_SESSION['authenticated'])
{
$cache_tags = array('__username='.$_SESSION['username']);
}
del_cache_items($cache_tags);
// Unset session
@session_start();
if ($relogin)
{
// Reset session and relogin (for example: HTTP auth)
$_SESSION['relogin'] = TRUE;
unset($_SESSION['authenticated'],
$_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['user_encpass'], $_SESSION['password'],
$_SESSION['userlevel']);
session_commit();
session_regenerate_id(TRUE);
} else {
// Kill current session, as authentication failed
unset($_SESSION);
session_unset();
session_destroy();
session_commit();
//setcookie(session_name(),'',0,'/');
session_regenerate_id(TRUE);
// Re-set auth failure message for use on login page
//session_start();
$_SESSION['auth_message'] = $message;
}
}
/**
* Regenerate session ID for prevent attacks session hijacking and session fixation.
* Note, use this function after session_start() and before next session_commit()!
*
* Code borrowed from https://www.php.net/manual/en/function.session-regenerate-id.php
*
* @param int $lifetime_id Time in seconds for next regenerate session ID (default 30 min)
*/
function session_regenerate($lifetime_id = 1800)
{
session_start();
if (isset($_SESSION['destroyed']))
{
// logfile('debug_auth.log', __LINE__ . ' session destroyed ' . json_encode($_SESSION));
if ($_SESSION['destroyed'] < time() - 300)
{
// logfile('debug_auth.log', __LINE__ . ' < 300 - logout');
// Should not happen usually. This could be attack or due to unstable network.
// Remove all authentication status of this users session.
session_logout(true, 'Session destroyed');
return;
}
if (isset($_SESSION['new_session_id']))
{
// logfile('debug_auth.log', __LINE__ . ' got new_session_id: ' . $_SESSION['new_session_id']);
// Not fully expired yet. Could be lost cookie by unstable network.
// Try again to set proper session ID cookie.
// NOTE: Do not try to set session ID again if you would like to remove
// authentication flag.
session_commit();
session_id($_SESSION['new_session_id']);
// New session ID should exist
session_start();
return;
}
}
$currenttime = time();
if ($lifetime_id != 1800 && is_numeric($lifetime_id) && $lifetime_id >= 300)
{
$lifetime_id = intval($lifetime_id);
} else {
$lifetime_id = 1800;
}
if (isset($_SESSION['starttime']))
{
// logfile('debug_auth.log', __LINE__ . ' ' . json_encode([$_SESSION['starttime'], $currenttime, $currenttime - $_SESSION['starttime']]));
if ($currenttime - $_SESSION['starttime'] >= $lifetime_id &&
!is_graph()) // Skip regenerate in graphs, but probably need skip in OBS_AJAX
{
// logfile('debug_auth.log', __LINE__ . ' ' . 'session_regenerate() called at '.$currenttime);
// ID Lifetime expired, regenerate
safe_session_regenerate_id();
// Clean cache from _SESSION first, this cache used in ajax calls
if (isset($_SESSION['cache'])) { unset($_SESSION['cache']); }
$_SESSION['starttime'] = $currenttime;
}
} else {
$_SESSION['starttime'] = $currenttime;
}
}
/**
* Safe session_regenerate_id that doesn't loose session
*
* Code borrowed from https://www.php.net/manual/en/function.session-regenerate-id.php
*/
function safe_session_regenerate_id()
{
global $config, $debug_auth;
if (PHP_VERSION_ID < 70100)
{
// While session_create_id() not exist in php less than 7.1
// and not possible make userland implementation, use this hack
$_SESSION['destroyed'] = time();
$tmp = $_SESSION; // Somehow the SESSION data is not kept
session_regenerate_id(TRUE);
if (!isset($_SESSION['destroyed']))
{
// restore old session vars
$_SESSION = $tmp;
if ($debug_auth)
{
logfile('debug_auth.log', __LINE__ . " OLD session_regenerate_id() lost session. IP=[" . get_remote_addr($config['web_session_ip_by_header']) . "]. URL=[" . $_SERVER['REQUEST_URI'] . "]");
logfile('debug_auth.log', __LINE__ . ' ' . var_export($_SESSION, TRUE));
}
}
unset($_SESSION['destroyed']);
return;
}
// New session ID is required to set proper session ID
// when session ID is not set due to unstable network.
$new_session_id = session_create_id();
// logfile('debug_auth.log', __LINE__ . ' new_session_id: ' . $new_session_id);
$_SESSION['new_session_id'] = $new_session_id;
// Set destroy timestamp
$_SESSION['destroyed'] = time();
// Write and close current session;
session_commit();
$tmp = $_SESSION; // Somehow the SESSION data is not kept
// Start session with new session ID
session_id($new_session_id);
ini_set('session.use_strict_mode', 0);
session_start();
ini_set('session.use_strict_mode', 1);
$_SESSION = $tmp;
// New session does not need them
unset($_SESSION['destroyed'], $_SESSION['new_session_id']);
}
/**
* Use this function for write to $_SESSION global var.
* And prevent session blocking.
* If value is NULL, this session variable will unset
*
* @param string $var
* @param mixed $value
*/
function session_set_var($var, $value)
{
//logfile('debug_auth.log', __LINE__ . ' ' . "session_set_var($var, $value) called at " . time());
$nested_key = explode('->', $var, 2);
switch (count($nested_key))
{
case 2:
// Currently only 2 levels for nesting in sessions var!
if (isset($_SESSION[$nested_key[0]][$nested_key[1]]) &&
$_SESSION[$nested_key[0]][$nested_key[1]] === $value) { return; } // Just return if session var unchanged
@session_start(); // Unblock session again
if (is_null($value))
{
unset($_SESSION[$nested_key[0]][$nested_key[1]]);
} else {
$_SESSION[$nested_key[0]][$nested_key[1]] = $value;
}
session_commit(); // Write and block session
//r($_SESSION[$nested_key[0]]);
break;
default:
if (isset($_SESSION[$var]) && $_SESSION[$var] === $value) { return; } // Just return if session var unchanged
@session_start(); // Unblock session again
if (is_null($value))
{
unset($_SESSION[$var]);
} else {
$_SESSION[$var] = $value;
}
session_commit(); // Write and block session
}
}
function session_unset_var($var)
{
session_set_var($var, NULL);
}
/**
* Redirects to the front page with the specified authentication failure message.
* In the case of 'remote', no redirect is performed (as this would create an infinite loop,
* as there is no way to logout), so the message is simply printed.
*
* @param string $message Message to display to the user
*/
function reauth_with_message($message)
{
global $config;
// Detect AJAX request, do not write any messages or redirects there!
if (OBS_API || OBS_AJAX)
{
// FIXME. But probably here required redirect to requested ajax page with params..
return;
}
if ($config['auth_mechanism'] === 'remote')
{
print('<h1>' . $message . '</h1>');
} else {
session_set_var('auth_message', $message);
//redirect_to_url($config['base_url'] . '?lm='.var_encode($message));
// Message encrypted for prevent hijacking any custom messages
redirect_to_url($config['base_url'] . '?lm='.encrypt($message, OBSERVIUM_PRODUCT.OBSERVIUM_VERSION));
}
exit();
}
// EOF

View File

@ -0,0 +1,123 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
/**
CAS authentication support.
Uses mysql (same schema as mysql module) for authorization but CAS for authentication.
Requires phpCAS https://wiki.jasig.org/display/casc/phpcas
New configuration settings:
auth_cas_host
auth_cas_port
auth_cas_context
auth_cas_ca_cert
FIXME these should go into defaults and sql-config!
*/
require_once('CAS.php');
phpCAS::client(CAS_VERSION_2_0, $config['auth_cas_host'], $config['auth_cas_port'], $config['auth_cas_context']);
phpCAS::setCasServerCACert($config['auth_cas_ca_cert']);
phpCAS::handleLogoutRequests(false);
phpCAS::forceAuthentication();
if (phpCAS::getUser())
{
session_set_var('username', phpCAS::getUser());
}
/**
* Check username against CAS authentication backend. User needs to exist in MySQL to be able to log in.
*
* @param string $username User name to check
* @param string $password User password to check
* @return int Authentication success (0 = fail, 1 = success) FIXME bool
*/
function cas_authenticate($username, $password)
{
$row = dbFetchRow("SELECT `username`, `password` FROM `users` WHERE `username`= ?", array($username));
if ($row['username'] && $row['username'] == $username)
{
if ($username == phpCAS::getUser())
{
return 1;
}
dbInsert(array('user' => $_SESSION['username'], 'address' => $_SERVER["REMOTE_ADDR"], 'result' => 'CAS: username does not match CAS user'), 'authlog');
} else {
dbInsert(array('user' => $_SESSION['username'], 'address' => $_SERVER["REMOTE_ADDR"], 'result' => 'CAS: NOT found in DB'), 'authlog');
}
//session_logout();
return 0;
}
/**
* Check if the backend allows users to log out.
* As the login is done outside our system, we don't allow users to log out.
*
* @return bool TRUE if logout is possible, FALSE if it is not
*/
function cas_auth_can_logout()
{
return FALSE;
}
/**
* Check if the backend allows a specific user to change their password.
* This is not currently possible using the CAS backend.
*
* @param string $username Username to check
* @return bool TRUE if password change is possible, FALSE if it is not
*/
function cas_auth_can_change_password($username = "")
{
return FALSE;
}
/**
* Check if the backend allows user management at all (create/delete/modify users).
* The CAS module requires users to exist in MySQL first, so we allow MySQL user management.
*
* @return bool TRUE if user management is possible, FALSE if it is not
*/
function cas_auth_usermanagement()
{
return 1;
}
/**
* Adds a new user to the user backend.
*
* @param string $username User's username
* @param string $password User's password (plain text)
* @param int $level User's auth level
* @param string $email User's e-mail address
* @param string $realname User's real name
* @param bool $can_modify_passwd TRUE if user can modify their own password, FALSE if not
* @param string $description User's description
* @return bool TRUE if user addition is successful, FALSE if it is not
*/
function cas_adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd='1', $description = "")
{
if (!cas_auth_user_exists($username))
{
$hash = password_hash($password, PASSWORD_DEFAULT);
return dbInsert(array('username' => $username, 'password' => $hash, 'level' => $level, 'email' => $email, 'realname' => $realname, 'can_modify_passwd' => $can_modify_passwd, 'descr' => $description), 'users');
} else {
return FALSE;
}
}
// EOF

View File

@ -0,0 +1,51 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
if (!$_SESSION['authenticated'] && !is_cli())
{
if (isset($_SERVER['PHP_AUTH_USER']))
{
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
}
elseif (isset($_SERVER['HTTP_AUTHENTICATION']))
{
if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']), 'basic') === 0) list($username, $password) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
}
if ($_SESSION['relogin'] || empty($username) || !mysql_authenticate($username, $password))
{
http_auth_require_login();
} else {
session_set_var('username', $username);
session_set_var('password', $password);
}
}
/**
* This function forces a login prompt via basic HTTP authentication by making the browser believe
* the authentication has failed. Required to log out a basic HTTP auth session.
*/
function http_auth_require_login()
{
$realm = $GLOBALS['config']['login_message'];
header('WWW-Authenticate: Basic realm="' . $realm . '"');
header('HTTP/1.1 401 Unauthorized');
print_error_permission();
session_logout();
die();
}
// EOF

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,223 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
/**
* Check username and password against MySQL authentication backend.
* Cut short if remote_user setting is on, as we assume the user has already authed against Apache.
*
* @param string $username User name to check
* @param string $password User password to check
* @return int Authentication success (0 = fail, 1 = success) FIXME bool
*/
function mysql_authenticate($username, $password)
{
global $config;
$row = dbFetchRow("SELECT `username`, `password` FROM `users` WHERE `username` = ?", array($username));
if ($row['username'] && $row['username'] == $username)
{
if ($config['auth']['remote_user']) { return 1; }
if (str_starts($row['password'], '$1$'))
{
// Old MD5 hashes, need rehash/change passwords
if ($row['password'] == crypt($password, $row['password']))
{
// Rehash password
mysql_auth_change_password($username, $password);
return 1;
}
}
elseif (password_verify($password, $row['password']))
{
// New password hash verified
if (password_needs_rehash($row['password'], PASSWORD_DEFAULT))
{
// Required password rehash
//$hash = password_hash($password, PASSWORD_DEFAULT);
mysql_auth_change_password($username, $password);
}
return 1;
}
}
//session_logout();
return 0;
}
/**
* Check if the backend allows users to log out.
* We don't check for Apache authentication (remote_user) as this is done already before calling into this function.
*
* @return bool TRUE if logout is possible, FALSE if it is not
*/
function mysql_auth_can_logout()
{
return TRUE;
}
/**
* Check if the backend allows a specific user to change their password.
* Default is yes, unless the existing user is explicitly prohibited to do so.
* Also, if user authed to Apache, we can't change his password.
*
* @param string $username Username to check
* @return bool TRUE if password change is possible, FALSE if it is not
*/
function mysql_auth_can_change_password($username = "")
{
global $config;
if ((empty($username) || !mysql_auth_user_exists($username)) && !$config['auth']['remote_user'])
{
return TRUE;
} else {
return dbFetchCell("SELECT `can_modify_passwd` FROM `users` WHERE `username` = ?", array($username)); // FIXME should return BOOL
}
}
/**
* Changes a user's password.
*
* @param string $username Username to modify the password for
* @param string $password New password
* @return bool TRUE if password change is successful, FALSE if it is not
*/
function mysql_auth_change_password($username,$password)
{
if (get_db_version() < 414) { return 0; } // Do not update if DB schema old, new hashes require longer field
// $hash = crypt($password, '$1$' . strgen(8).'$'); // This is old hash, do not used anymore (keep for history)
$hash = password_hash($password, PASSWORD_DEFAULT);
return dbUpdate(array('password' => $hash), 'users', '`username` = ?', array($username)); // FIXME should return BOOL
}
/**
* Check if the backend allows user management at all (create/delete/modify users).
*
* @return bool TRUE if user management is possible, FALSE if it is not
*/
function mysql_auth_usermanagement()
{
return TRUE;
}
/**
* Adds a new user to the user backend.
*
* @param string $username User's username
* @param string $password User's password (plain text)
* @param int $level User's auth level
* @param string $email User's e-mail address
* @param string $realname User's real name
* @param bool $can_modify_passwd TRUE if user can modify their own password, FALSE if not
* @param string $description User's description
* @return bool TRUE if user addition is successful, FALSE if it is not
*/
function mysql_adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd='1', $description = "")
{
if (!mysql_auth_user_exists($username))
{
// $hash = crypt($password, '$1$' . strgen(8).'$'); // This is old hash, do not used anymore (keep for history)
$hash = password_hash($password, PASSWORD_DEFAULT);
return dbInsert(array('username' => $username, 'password' => $hash, 'level' => $level, 'email' => $email, 'realname' => $realname, 'can_modify_passwd' => $can_modify_passwd, 'descr' => $description), 'users');
} else {
return FALSE;
}
}
/**
* Check if a user, specified by username, exists in the user backend.
*
* @param string $username Username to check
* @return bool TRUE if the user exists, FALSE if they do not
*/
function mysql_auth_user_exists($username)
{
//return @dbFetchCell("SELECT COUNT(*) FROM `users` WHERE `username` = ?", array($username)); // FIXME should return BOOL
return dbExist('users', '`username` = ?', array($username));
}
/**
* Find the user's username by specifying their user ID.
*
* @param int $user_id The user's ID to look up the username for
* @return string The user's user name, or FALSE if the user ID is not found
*/
function mysql_auth_username_by_id($user_id)
{
return dbFetchCell("SELECT `username` FROM `users` WHERE `user_id` = ?", array($user_id)); // FIXME should return FALSE if not found
}
/**
* Retrieve user auth level for specified user.
*
* @param string $username Username to retrieve the auth level for
* @return int User's auth level
*/
function mysql_auth_user_level($username)
{
return dbFetchCell("SELECT `level` FROM `users` WHERE `username` = ?", array($username));
}
/**
* Retrieve user id for specified user.
*
* @param string $username Username to retrieve the ID for
* @return int User's ID
*/
function mysql_auth_user_id($username)
{
return dbFetchCell("SELECT `user_id` FROM `users` WHERE `username` = ?", array($username));
}
/**
* Deletes a user from the user database.
*
* @param string $username Username to delete
* @return bool TRUE if user deletion is successful, FALSE if it is not
*/
function mysql_deluser($username)
{
$user_id = mysql_auth_user_id($username);
dbDelete('entity_permissions', "`user_id` = ? AND `auth_mechanism` = ?", [ $user_id, $GLOBALS['config']['auth_mechanism'] ]);
dbDelete('roles_users', "`user_id` = ? AND `auth_mechanism` = ?", [ $user_id, $GLOBALS['config']['auth_mechanism'] ]);
dbDelete('users_prefs', "`user_id` = ?", array($user_id));
dbDelete('users_ckeys', "`username` = ?", array($username));
return dbDelete('users', "`username` = ?", array($username)); // FIXME should return BOOL
}
/**
* Retrieve list of users with all details.
*
* @return array Rows of user data
*/
function mysql_auth_user_list()
{
return dbFetchRows("SELECT * FROM `users`"); // FIXME hardcode list of returned fields as in all other backends; array content should not depend on db changes/column names.
}
/**
* Get the user information by username
*
* @param string $username Username
* @return string The user's user name, or FALSE if the user ID is not found
*/
function mysql_auth_user_info($username)
{
return dbFetchRow("SELECT * FROM `users` WHERE `username` = ?", array($username));
}
// EOF

View File

@ -0,0 +1,331 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
/**
* Initializes the RADIUS connection to the specified server(s). Cycles through all servers, throws error when no server can be reached.
* Private function for this RADIUS module only.
*/
function radius_init()
{
global $rad, $config;
if (!is_resource($rad))
{
$success = 0;
$rad = radius_auth_open();
foreach ($config['auth_radius_server'] as $server)
{
if (radius_add_server($rad, $server, $config['auth_radius_port'], $config['auth_radius_secret'], $config['auth_radius_timeout'], $config['auth_radius_retries']))
{
$success = 1;
}
}
if (!$success)
{
print_error("Fatal error: Could not connect to configured RADIUS server(s).");
session_logout();
exit;
}
}
}
/**
* Check username and password against RADIUS authentication backend.
*
* @param string $username User name to check
* @param string $password User password to check
* @return int Authentication success (0 = fail, 1 = success) FIXME bool
*/
function radius_authenticate($username, $password)
{
global $config, $rad;
radius_init();
if ($username && $rad)
{
//print_vars(radius_server_secret($rad));
radius_create_request($rad, RADIUS_ACCESS_REQUEST);
radius_put_attr($rad, RADIUS_USER_NAME, $username);
switch(strtolower($config['auth_radius_method']))
{
// CHAP-MD5 see RFC1994
case 'chap':
case 'chap_md5':
$chapid = 1; // Specify a CHAP identifier
//$challenge = mt_rand(); // Generate a challenge
//$cresponse = md5(pack('Ca*', $chapid, $password.$challenge), TRUE);
new Crypt_CHAP(); // Pre load class
$crpt = new Crypt_CHAP_MD5();
$crpt->password = $password;
$challenge = $crpt->challenge;
$resp_md5 = $crpt->challengeResponse();
$resp = pack('C', $chapid) . $resp_md5;
radius_put_attr($rad, RADIUS_CHAP_PASSWORD, $resp); // Add the Chap-Password attribute
radius_put_attr($rad, RADIUS_CHAP_CHALLENGE, $challenge); // Add the Chap-Challenge attribute.
break;
// MS-CHAPv1 see RFC2433
case 'mschapv1':
$chapid = 1; // Specify a CHAP identifier
$flags = 1; // 0 = use LM-Response, 1 = use NT-Response (we not use old LM)
new Crypt_CHAP(); // Pre load class
$crpt = new Crypt_CHAP_MSv1();
$crpt->password = $password;
$challenge = $crpt->challenge;
$resp_lm = str_repeat("\0", 24);
$resp_nt = $crpt->challengeResponse();
$resp = pack('CC', $chapid, $flags) . $resp_lm . $resp_nt;
radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_RESPONSE, $resp);
radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_CHALLENGE, $challenge);
break;
// MS-CHAPv2 see RFC2759
case 'mschapv2':
$chapid = 1; // Specify a CHAP identifier
$flags = 1; // 0 = use LM-Response, 1 = use NT-Response (we not use old LM)
new Crypt_CHAP(); // Pre load class
$crpt = new Crypt_CHAP_MSv2();
$crpt->username = $username;
$crpt->password = $password;
$challenge = $crpt->authChallenge;
$challenge_p = $crpt->peerChallenge;
$resp_nt = $crpt->challengeResponse();
// Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response
$resp = pack('CCa16a8a24', $chapid , $flags, $challenge_p, str_repeat("\0", 8), $resp_nt);
radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP2_RESPONSE, $resp);
radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_CHALLENGE, $challenge);
break;
// PAP (Plaintext)
default:
radius_put_attr($rad, RADIUS_USER_PASSWORD, $password);
}
// Puts standard attributes
$radius_ip = get_ip_version($config['auth_radius_nas_address']) ? $config['auth_radius_nas_address'] : $_SERVER['SERVER_ADDR'];
if (get_ip_version($radius_ip) == 6)
{
// FIXME, not sure that this work correctly
radius_put_attr($rad, RADIUS_NAS_IPV6_ADDRESS, $radius_ip);
} else {
radius_put_addr($rad, RADIUS_NAS_IP_ADDRESS, $radius_ip);
}
$radius_id = (empty($config['auth_radius_id']) ? get_localhost() : $config['auth_radius_id']);
radius_put_attr($rad, RADIUS_NAS_IDENTIFIER, $radius_id);
//radius_put_attr($rad, RADIUS_NAS_PORT_TYPE, RADIUS_VIRTUAL);
//radius_put_attr($rad, RADIUS_SERVICE_TYPE, RADIUS_FRAMED);
//radius_put_attr($rad, RADIUS_FRAMED_PROTOCOL, RADIUS_PPP);
radius_put_attr($rad, RADIUS_CALLING_STATION_ID, isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1');
$response = radius_send_request($rad);
//print_vars($response);
switch ($response)
{
case RADIUS_ACCESS_ACCEPT:
// An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.
//echo 'Authentication successful';
return 1;
break;
case RADIUS_ACCESS_REJECT:
// An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.
//echo 'Authentication failed';
break;
case RADIUS_ACCESS_CHALLENGE:
// An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information
// in another Access-Request before authenticating the user.
//echo 'Challenge required';
break;
default:
print_error('A RADIUS error has occurred: ' . radius_strerror($rad));
}
}
//session_logout();
return 0;
}
/**
* Check if the backend allows a specific user to change their password.
* This is not currently possible using the RADIUS backend.
*
* @param string $username Username to check
* @return bool TRUE if password change is possible, FALSE if it is not
*/
function radius_auth_can_change_password($username = "")
{
return 0;
}
/**
* Changes a user's password.
* This is not currently possible using the RADIUS backend.
*
* @param string $username Username to modify the password for
* @param string $password New password
* @return bool TRUE if password change is successful, FALSE if it is not
*/
function radius_auth_change_password($username, $newpassword)
{
# Not supported
return FALSE;
}
/**
* Check if the backend allows user management at all (create/delete/modify users).
* This is not currently possible using the RADIUS backend.
*
* @return bool TRUE if user management is possible, FALSE if it is not
*/
function radius_auth_usermanagement()
{
return 0;
}
/**
* Adds a new user to the user backend.
* This is not currently possible using the RADIUS backend.
*
* @param string $username User's username
* @param string $password User's password (plain text)
* @param int $level User's auth level
* @param string $email User's e-mail address
* @param string $realname User's real name
* @param bool $can_modify_passwd TRUE if user can modify their own password, FALSE if not
* @param string $description User's description
* @return bool TRUE if user addition is successful, FALSE if it is not
*/
function radius_adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd = '1')
{
// Not supported
return FALSE;
}
/**
* Check if a user, specified by username, exists in the user backend.
* This is not currently possible using the RADIUS backend.
*
* @param string $username Username to check
* @return bool TRUE if the user exists, FALSE if they do not
*/
function radius_auth_user_exists($username)
{
return FALSE;
}
/**
* Retrieve user auth level for specified user.
*
* @param string $username Username to retrieve the auth level for
* @return int User's auth level
*/
function radius_auth_user_level($username)
{
global $config, $rad, $cache;
$rad_userlevel = 0;
if (isset($config['auth_radius_groups']))
{
// If groups set, try to search group attribute and set user level
if (!isset($cache['radius']['level'][$username]))
{
if ($config['auth_radius_groupmemberattr'] == 18 || strtolower($config['auth_radius_groupmemberattr']) == 'reply-message')
{
// Reply-Message (18)
$attribute = RADIUS_REPLY_MESSAGE;
} else {
// Filter-Id (11)
$attribute = RADIUS_FILTER_ID;
}
$rad_groups = array();
while ($rad_attr = radius_get_attr($rad))
{
if ($rad_attr['attr'] == $attribute)
{
$rad_groups[] = radius_cvt_string($rad_attr['data']);
//r($rad_attr);
//break;
}
}
//r($rad_groups);
foreach($rad_groups as $rad_group)
{
if (isset($config['auth_radius_groups'][$rad_group]) && $config['auth_radius_groups'][$rad_group]['level'] > $rad_userlevel)
{
$rad_userlevel = intval($config['auth_radius_groups'][$rad_group]['level']);
}
}
$cache['radius']['level'][$username] = $rad_userlevel;
} else {
$rad_userlevel = $cache['radius']['level'][$username];
}
} else {
// Old non-groups, by default always user level 10
if (strlen($username) > 0)
{
$rad_userlevel = 10;
}
}
//r($rad_userlevel);
return $rad_userlevel;
}
/**
* Retrieve user id for specified user.
* Returns a hash of the username.
*
* @param string $username Username to retrieve the ID for
* @return int User's ID
*/
function radius_auth_user_id($username)
{
//return -1;
return string_to_id('radius|' . $username);
}
/**
* Deletes a user from the user database.
* This is not currently possible using the RADIUS backend.
*
* @param string $username Username to delete
* @return bool TRUE if user deletion is successful, FALSE if it is not
*/
function radius_deluser($username)
{
// Not supported
return FALSE;
}
/**
* Retrieve list of users with all details.
* This is not currently possible using the RADIUS backend.
*
* @return array Rows of user data
*/
function radius_auth_user_list()
{
$userlist = array();
return $userlist;
}
// EOF

View File

@ -0,0 +1,180 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* This authentication method assumes that the user has already been authenticated by the web server,
* using the trusted specified variable (REMOTE_USER by default). It is important to configure the server
* such that this variable cannot be overridden by users.
*
* There is no local user storage and all users will be assumed to have the privilege level specified
* (which defaults to 1).
*
* A possible future improvement to this auth method would be to have the remote user automatically
* created in the mysql auth method upon login with a basic user level, but could later be edited and
* assigned higher privileges.
*
* Configuration variables:
*
* $config['auth_mechanism'] = "remote";
* - Enables this authentication method
*
* $config['auth_remote_userlevel'] = 10;
* - What userlevel to assign to users, defaults to 1. https://docs.observium.org/user_levels/
*
* $config['auth_remote_variable'] = 'REMOTE_USER';
* - What server variable to to use, if unspecified then REMOTE_USER is assumed.
*
* $config['auth_remote_logout_url'] = 'http://blah';
* - URL to redirect users when they click the logout button. If this is not specified, no logout button
* will be available.
*
* @package observium
* @subpackage authentication
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
if (!$_SESSION['authenticated'] && !is_cli())
{
$var = isset($config['auth_remote_variable']) ? $config['auth_remote_variable']: 'REMOTE_USER';
if (isset($_SERVER[$var]) && !empty($_SERVER[$var]))
{
$username = $_SERVER[$var];
session_set_var('username', $username);
session_set_var('authenticated', true);
}
else {
header('HTTP/1.1 401 Unauthorized');
print_error_permission();
die();
}
}
/**
* Check if the backend allows users to log out.
*
* @return bool TRUE if logout is possible, FALSE if it is not
*/
function remote_auth_can_logout()
{
global $config;
return isset($config['auth_remote_logout_url']);
}
/**
* Returns the URL to lgoout.
*
* @return string logout url
*/
function remote_auth_logout_url()
{
global $config;
return isset($config['auth_remote_logout_url']) ? $config['auth_remote_logout_url'] : null;
}
/**
* Check if the backend allows a specific user to change their password.
* This is not possible using the remote backend.
*
* @param string $username Username to check
* @return bool TRUE if password change is possible, FALSE if it is not
*/
function remote_auth_can_change_password($username = "")
{
return 0;
}
/**
* Changes a user's password.
* This is not possible using the remote backend.
*
* @param string $username Username to modify the password for
* @param string $password New password
* @return bool TRUE if password change is successful, FALSE if it is not
*/
function remote_auth_change_password($username, $newpassword)
{
# Not supported
return FALSE;
}
/**
* Check if the backend allows user management at all (create/delete/modify users).
* This is not possible using the remote backend.
*
* @return bool TRUE if user management is possible, FALSE if it is not
*/
function remote_auth_usermanagement()
{
return 0;
}
/**
* Check if a user, specified by username, exists in the user backend.
* This is not possible using the remote backend.
*
* @param string $username Username to check
* @return bool TRUE if the user exists, FALSE if they do not
*/
function remote_auth_user_exists($username)
{
return FALSE;
}
/**
* Retrieve user auth level for specified user.
*
* @param string $username Username to retrieve the auth level for
* @return int User's auth level
*/
function remote_auth_user_level($username)
{
global $config;
return isset($config['auth_remote_userlevel']) ? $config['auth_remote_userlevel'] : 1;
}
/**
* Retrieve user id for specified user.
* Returns a hash of the username.
*
* @param string $username Username to retrieve the ID for
* @return int User's ID
*/
function remote_auth_user_id($username)
{
//return -1;
return string_to_id('remote|' . $username);
}
/**
* Deletes a user from the user database.
* This is not possible using the remote backend.
*
* @param string $username Username to delete
* @return bool TRUE if user deletion is successful, FALSE if it is not
*/
function remote_deluser($username)
{
// Not supported
return FALSE;
}
/**
* Retrieve list of users with all details.
* This is not possible using the remote backend.
*
* @return array Rows of user data
*/
function remote_auth_user_list()
{
$userlist = array();
return $userlist;
}
// EOF

View File

@ -0,0 +1,661 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2020 Observium Limited
*
*/
$cache_item = get_cache_item('data');
//print_vars($cache_item->isHit());
if (!ishit_cache_item($cache_item))
{
// Devices
$cache['devices'] = array('id' => array(),
'hostname' => array(),
'permitted' => array(),
'ignored' => array(),
'disabled' => array());
$cache['devices']['stat'] = array('count' => 0,
'up' => 0,
'down' => 0,
'ignored' => 0,
'disabled' => 0);
// This code fetches all devices and fills the cache array.
// This means device_by_id_cache actually never has to do any queries by itself, it'll always get the
// cached version when running from the web interface. From the commandline obviously we'll need to fetch
// the data per-device. We pre-fetch the graphs list as well, much faster than a query per device obviously.
$graphs_array = dbFetchRows("SELECT * FROM `device_graphs` FORCE INDEX (`graph`) ORDER BY `graph`;");
foreach ($graphs_array as $graph)
{
// Cache this per device_id so we can assign it to the correct (cached) device in the for loop below
if ($graph['enabled'])
{
$device_graphs[$graph['device_id']][$graph['graph']] = $graph;
}
}
$cache['graphs'] = array(); // All permitted graphs
// Cache scheduled maintenance currently active
$cache['maint'] = cache_alert_maintenance();
if ($GLOBALS['config']['geocoding']['enable'])
{
$devices_array = dbFetchRows("SELECT * FROM `devices` LEFT JOIN `devices_locations` USING (`device_id`) ORDER BY `hostname`;");
} else {
$devices_array = dbFetchRows("SELECT * FROM `devices` ORDER BY `hostname`;");
}
foreach ($devices_array as $device)
{
if (device_permitted($device['device_id']))
{
// Process device and add all the human-readable stuff.
humanize_device($device);
// Assign device graphs from array created above
$device['graphs'] = (array)$device_graphs[$device['device_id']];
$cache['graphs'] = array_unique(array_merge($cache['graphs'], array_keys($device['graphs']))); // Add to global array cache
$cache['devices']['permitted'][] = (int)$device['device_id']; // Collect IDs for permitted
$cache['devices']['hostname'][$device['hostname']] = $device['device_id'];
$cache['devices']['id'][$device['device_id']] = $device;
if ($device['disabled'])
{
$cache['devices']['stat']['disabled']++;
$cache['devices']['disabled'][] = (int)$device['device_id']; // Collect IDs for disabled
if (!$config['web_show_disabled']) { continue; }
// Stat for disabled collect after web_show_disabled
$cache['devices']['types'][$device['type']]['disabled']++;
}
if ($device['ignore'] || (!is_null($device['ignore_until']) && strtotime($device['ignore_until']) > time()) )
{
$cache['devices']['stat']['ignored']++;
$cache['devices']['ignored'][] = (int)$device['device_id']; // Collect IDs for ignored
$cache['devices']['types'][$device['type']]['ignored']++;
} else {
if ($device['status']) {
$cache['devices']['stat']['up']++;
$cache['devices']['types'][$device['type']]['up']++;
} else {
$cache['devices']['stat']['down']++;
$cache['devices']['types'][$device['type']]['down']++;
}
}
$cache['devices']['stat']['count']++;
$cache['devices']['timers']['polling'] += $device['last_polled_timetaken'];
$cache['devices']['timers']['discovery'] += $device['last_discovered_timetaken'];
$cache['devices']['types'][$device['type']]['count']++;
$cache['device_types'][$device['type']]++;
$cache['device_locations'][$device['location']]++;
if (isset($config['geocoding']['enable']) && $config['geocoding']['enable'])
{
$country_code = $device['location_country'];
$cache['locations']['entries'][$country_code]['count']++;
$cache['locations']['entries'][$country_code]['level'] = 'location_country';
if (isset($config['location_countries_with_counties']) && in_array($country_code, $config['location_countries_with_counties']) )
{
$cache['locations']['entries'][$country_code]['entries'][$device['location_county']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_county']]['level'] = 'location_county';
$cache['locations']['entries'][$country_code]['entries'][$device['location_county']]['entries'][$device['location_city']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_county']]['entries'][$device['location_city']]['level'] = 'location_city';
$cache['locations']['entries'][$country_code]['entries'][$device['location_county']]['entries'][$device['location_city']]['entries'][$device['location']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_county']]['entries'][$device['location_city']]['entries'][$device['location']]['level'] = 'location';
} //county only
else
{ //check for county and states
if (isset($config['location_countries_with_counties_and_states']) && in_array($country_code, $config['location_countries_with_counties_and_states']) )
{
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['level'] = 'location_state';
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_county']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_county']]['level'] = 'location_county';
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_county']]['entries'][$device['location_city']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_county']]['entries'][$device['location_city']]['level'] = 'location_city';
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_county']]['entries'][$device['location_city']]['entries'][$device['location']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_county']]['entries'][$device['location_city']]['entries'][$device['location']]['level'] = 'location';
} //state and county
else
{
//state only
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['level'] = 'location_state';
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_city']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_city']]['level'] = 'location_city';
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_city']]['entries'][$device['location']]['count']++;
$cache['locations']['entries'][$country_code]['entries'][$device['location_state']]['entries'][$device['location_city']]['entries'][$device['location']]['level'] = 'location';
} //state only
} //county only / else
}
}
}
sort($cache['graphs']);
// Ports
$cache['ports'] = array(//'id' => array(),
//'permitted' => array(),
'ignored' => array(),
'errored' => array(),
//'disabled' => array(),
'poll_disabled' => array(),
'device_ignored' => array(),
'device_disabled' => array(),
'deleted' => array());
$cache['ports']['stat'] = array('count' => 0,
'up' => 0,
'down' => 0,
'ignored' => 0,
'shutdown' => 0,
'errored' => 0,
'alerts' => 0,
'deleted' => 0);
$where_permitted = generate_query_permitted(array('device', 'port'));
$where_hide = " AND `deleted` = 0";
// Deleted
$cache['ports']['deleted'] = dbFetchColumn("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . " AND `deleted` = 1");
$cache['ports']['stat']['deleted'] = count($cache['ports']['deleted']);
// Devices disabled
if (isset($cache['devices']['disabled']) && count($cache['devices']['disabled']) > 0)
{
$cache['ports']['device_disabled'] = dbFetchColumn("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . generate_query_values($cache['devices']['disabled'], 'device_id'));
if (!$config['web_show_disabled'])
{
$where_hide .= generate_query_values($cache['devices']['disabled'], 'device_id', '!=');
}
}
// Devices ignored
$where_devices_ignored = '';
if (isset($cache['devices']['ignored']) && count($cache['devices']['ignored']) > 0)
{
$cache['ports']['device_ignored'] = dbFetchColumn("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . $where_hide . generate_query_values($cache['devices']['ignored'], 'device_id'));
$where_hide .= generate_query_values($cache['devices']['ignored'], 'device_id', '!=');
$where_devices_ignored = generate_query_values($cache['devices']['ignored'], 'device_id');
}
$cache['ports']['stat']['device_ignored'] = count($cache['ports']['device_ignored']);
// Ports poll disabled
$cache['ports']['poll_disabled'] = dbFetchColumn("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND `disabled` = '1'");
$cache['ports']['stat']['poll_disabled'] = count($cache['ports']['poll_disabled']);
// Ports ignored
$cache['ports']['ignored'] = dbFetchColumn("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND (`ignore` = '1')");
$cache['ports']['stat']['ignored'] = count($cache['ports']['ignored']);
// r("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND (`ignore` = '1'" . $where_devices_ignored . ")");
//r($cache['ports']['ignored']);
$where_hide .= " AND `ignore` = 0";
// Ports errored
$cache['ports']['errored'] = dbFetchColumn("SELECT `port_id` FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND `ifAdminStatus` = 'up' AND (`ifOperStatus` = 'up' OR `ifOperStatus` = 'testing') AND (`ifOutErrors_delta` > 0 OR `ifInErrors_delta` > 0)");
//$cache['ports']['errored'] = dbFetchColumn("SELECT `port_id` FROM `ports` LEFT JOIN `ports-state` USING(`port_id`) WHERE 1 " . $where_permitted . $where_hide . " AND `ifAdminStatus` = 'up' AND (`ifOperStatus` = 'up' OR `ifOperStatus` = 'testing') AND (`ifOutErrors_delta` > 0 OR `ifInErrors_delta` > 0)");
$cache['ports']['stat']['errored'] = count($cache['ports']['errored']);
// Ports counts
$cache['ports']['stat']['count'] = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE 1 " . $where_permitted . $where_hide);
$cache['ports']['stat']['shutdown'] = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND `ifAdminStatus` = ?", array('down'));
$cache['ports']['stat']['down'] = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND `ifAdminStatus` = ? AND `ifOperStatus` IN (?, ?) AND `ports`.`disabled` = '0' AND `ports`.`deleted` = '0'", array('up', 'down', 'lowerLayerDown'));
$cache['ports']['stat']['up'] = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE 1 " . $where_permitted . $where_hide . " AND `ifAdminStatus` = ? AND `ifOperStatus` IN (?, ?, ?)", array('up', 'up', 'testing', 'monitoring'));
//r($where_hide);
//r($cache['devices']);
//r($cache['ports']);
//r($cache['ports']['stat']);
//r($ports_db);
//r($permissions);
// Sensors
$cache['sensors']['stat'] = array('count' => 0,
'ok' => 0,
'alert' => 0,
'warning' => 0,
'ignored' => 0,
'device_ignored' => 0,
'disabled' => 0,
'deleted' => 0);
$cache['sensors']['devices'] = array(); // Stats per device ids
$cache['sensor_types'] = array(); // FIXME -> $cache['sensors']['types']
$sensors_array = dbFetchRows('SELECT `device_id`, `sensor_id`, `sensor_class`, `sensor_type`, `sensor_ignore`, `sensor_disable`,
`sensor_value`, `sensor_deleted`, `sensor_event` FROM `sensors` WHERE 1 ' . generate_query_permitted(array('device', 'sensor')));
foreach ($sensors_array as $sensor)
{
//if (!is_entity_permitted($sensor['sensor_id'], 'sensor', $sensor['device_id'])) { continue; } // Check device permitted
if (!$config['web_show_disabled'])
{
if ($cache['devices']['id'][$sensor['device_id']]['disabled']) { continue; }
}
if ($sensor['sensor_deleted']) { $cache['sensors']['stat']['deleted']++; continue; }
$cache['sensors']['stat']['count']++;
$cache['sensors']['devices'][$sensor['device_id']]['count']++;
$cache['sensors']['types'][$sensor['sensor_class']]['count']++;
$cache['sensor_types'][$sensor['sensor_class']]['count']++;
if ($sensor['sensor_disable'])
{
$cache['sensors']['stat']['disabled']++;
$cache['sensors']['devices'][$sensor['device_id']]['disabled']++;
$cache['sensors']['types'][$sensor['sensor_class']]['disabled']++;
continue;
}
if ($sensor['sensor_event'] === 'ignore' || $sensor['sensor_ignore'] ||
in_array($sensor['device_id'], $cache['devices']['ignored']))
{
$cache['sensors']['stat']['ignored']++;
$cache['sensors']['devices'][$sensor['device_id']]['ignored']++;
$cache['sensors']['types'][$sensor['sensor_class']]['ignored']++;
continue;
}
switch ($sensor['sensor_event'])
{
case 'warning':
$cache['sensors']['stat']['warning']++;
$cache['sensors']['devices'][$sensor['device_id']]['warning']++;
$cache['sensors']['types'][$sensor['sensor_class']]['warning']++;
break;
case 'ok':
$cache['sensors']['stat']['ok']++;
$cache['sensors']['devices'][$sensor['device_id']]['ok']++;
$cache['sensors']['types'][$sensor['sensor_class']]['ok']++;
break;
case 'alert':
$cache['sensors']['stat']['alert']++;
$cache['sensors']['devices'][$sensor['device_id']]['alert']++;
$cache['sensors']['types'][$sensor['sensor_class']]['alert']++;
$cache['sensor_types'][$sensor['sensor_class']]['alert']++;
break;
default:
$cache['sensors']['stat']['alert']++; // unknown event (empty) also alert
$cache['sensors']['devices'][$sensor['device_id']]['alert']++;
$cache['sensors']['types'][$sensor['sensor_class']]['alert']++;
}
}
//r($cache['sensors']);
//r($cache['sensor_types']);
// Statuses
$cache['statuses']['stat'] = array('count' => 0,
'ok' => 0,
'alert' => 0,
'warning' => 0,
'ignored' => 0,
'disabled' => 0,
'deleted' => 0);
$cache['statuses']['devices'] = array(); // Stats per device id
$cache['status_classes'] = array(); // FIXME -> $cache['statuses']['classes']
$status_array = dbFetchRows('SELECT `device_id`, `status_id`, `entPhysicalClass`, `status_ignore`, `status_disable`,
`status_deleted`, `status_event` FROM `status`');
foreach ($status_array as $status)
{
if (!isset($cache['devices']['id'][$status['device_id']])) { continue; } // Check device permitted
if (!$config['web_show_disabled'])
{
if ($cache['devices']['id'][$status['device_id']]['disabled']) { continue; }
}
if ($status['status_deleted']) { $cache['statuses']['stat']['deleted']++; continue; }
$cache['statuses']['stat']['count']++;
$cache['statuses']['devices'][$status['device_id']]['count']++;
$cache['status_classes'][$status['entPhysicalClass']]['count']++;
if ($status['status_disable'])
{
$cache['statuses']['stat']['disabled']++;
$cache['statuses']['devices'][$status['device_id']]['disabled']++;
continue;
}
if ($status['status_event'] === 'ignore' || $status['status_ignore'] ||
in_array($status['device_id'], $cache['devices']['ignored']))
{
$cache['statuses']['stat']['ignored']++;
$cache['statuses']['devices'][$status['device_id']]['ignored']++;
continue;
}
switch ($status['status_event'])
{
case 'warning':
$cache['statuses']['stat']['warning']++; // 'warning' also 'ok', hrm but now I not sure
$cache['statuses']['devices'][$status['device_id']]['warning']++;
break;
case 'ok':
$cache['statuses']['stat']['ok']++;
$cache['statuses']['devices'][$status['device_id']]['ok']++;
break;
case 'alert':
$cache['statuses']['stat']['alert']++;
$cache['statuses']['devices'][$status['device_id']]['alert']++;
$cache['status_classes'][$status['entPhysicalClass']]['alert']++;
break;
default:
$cache['statuses']['stat']['alert']++; // unknown event (empty) also alert
$cache['statuses']['devices'][$status['device_id']]['alert']++;
}
}
//r($cache['statuses']);
// Counters
$cache['counters']['stat'] = array('count' => 0,
'ok' => 0,
'alert' => 0,
'warning' => 0,
'ignored' => 0,
'disabled' => 0,
'deleted' => 0);
$cache['counters']['devices'] = array(); // Stats per device ids
$counters_array = dbFetchRows('SELECT `device_id`, `counter_id`, `counter_class`, `counter_ignore`, `counter_disable`,
`counter_value`, `counter_deleted`, `counter_event` FROM `counters` WHERE 1 ' . generate_query_permitted(array('device', 'counter')));
foreach ($counters_array as $counter)
{
//if (!is_entity_permitted($counter['counter_id'], 'counter', $counter['device_id'])) { continue; } // Check device permitted
if (!$config['web_show_disabled'])
{
if ($cache['devices']['id'][$counter['device_id']]['disabled']) { continue; }
}
if ($counter['counter_deleted']) { $cache['counters']['stat']['deleted']++; continue; }
$cache['counters']['stat']['count']++;
$cache['counters']['devices'][$counter['device_id']]['count']++;
//$cache['counters']['types'][$counter['counter_class']]['count']++;
if ($counter['counter_disable'])
{
$cache['counters']['stat']['disabled']++;
$cache['counters']['devices'][$counter['device_id']]['disabled']++;
//$cache['counters']['types'][$counter['counter_class']]['disabled']++;
continue;
}
if ($counter['counter_event'] === 'ignore' || $counter['counter_ignore'] ||
in_array($counter['device_id'], $cache['devices']['ignored']))
{
$cache['counters']['stat']['ignored']++;
$cache['counters']['devices'][$counter['device_id']]['ignored']++;
//$cache['counters']['types'][$counter['counter_class']]['ignored']++;
continue;
}
switch ($counter['counter_event'])
{
case 'warning':
$cache['counters']['stat']['warning']++;
$cache['counters']['devices'][$counter['device_id']]['warning']++;
//$cache['counters']['types'][$counter['counter_class']]['warning']++;
break;
case 'ok':
$cache['counters']['stat']['ok']++;
$cache['counters']['devices'][$counter['device_id']]['ok']++;
//$cache['counters']['types'][$counter['counter_class']]['ok']++;
break;
case 'alert':
$cache['counters']['stat']['alert']++;
$cache['counters']['devices'][$counter['device_id']]['alert']++;
//$cache['counters']['types'][$counter['counter_class']]['alert']++;
break;
default:
$cache['counters']['stat']['alert']++; // unknown event (empty) also alert
$cache['counters']['devices'][$counter['device_id']]['alert']++;
//$cache['counters']['types'][$counter['counter_class']]['alert']++;
}
}
//r($cache['counters']);
// Alerts
$query = 'SELECT `alert_status` FROM `alert_table`';
$query .= ' WHERE 1' . generate_query_permitted(array('alert'));
$alert_entries = dbFetchRows($query);
$cache['alert_entries'] = array('count' => safe_count($alert_entries),
'up' => 0,
'down' => 0,
'unknown' => 0,
'delay' => 0,
'suppress' => 0);
foreach ($alert_entries as $alert_table_id => $alert_entry) {
switch ($alert_entry['alert_status']) {
case '0':
++$cache['alert_entries']['down'];
break;
case '1':
++$cache['alert_entries']['up'];
break;
case '2':
++$cache['alert_entries']['delay'];
break;
case '3':
++$cache['alert_entries']['suppress'];
break;
case '-1': // FIXME, what mean status '-1'?
default:
++$cache['alert_entries']['unknown'];
}
}
// Routing
// BGP
if (isset($config['enable_bgp']) && $config['enable_bgp']) {
// Init variables to 0
$cache['routing']['bgp']['internal'] = 0;
$cache['routing']['bgp']['external'] = 0;
$cache['routing']['bgp']['count'] = 0;
$cache['routing']['bgp']['up'] = 0;
$cache['routing']['bgp']['down'] = 0;
$cache['routing']['bgp']['last_seen'] = $config['time']['now'];
foreach (dbFetchRows('SELECT `device_id`,`bgpPeer_id`,`local_as`,`bgpPeerState`,`bgpPeerAdminStatus`,`bgpPeerRemoteAs` FROM `bgpPeers`;') as $bgp) {
if (!$config['web_show_disabled']) {
if ($cache['devices']['id'][$bgp['device_id']]['disabled']) { continue; }
}
if (device_permitted($bgp)) {
$cache['routing']['bgp']['count']++;
$cache['bgp']['permitted'][] = (int)$bgp['bgpPeer_id']; // Collect permitted peers
if ($bgp['bgpPeerAdminStatus'] === 'start' || $bgp['bgpPeerAdminStatus'] === 'running') {
$cache['routing']['bgp']['up']++;
$cache['bgp']['start'][] = (int)$bgp['bgpPeer_id']; // Collect START peers (bgpPeerAdminStatus = (start || running))
if ($bgp['bgpPeerState'] !== 'established') {
$cache['routing']['bgp']['alerts']++;
} else {
$cache['bgp']['up'][] = (int)$bgp['bgpPeer_id']; // Collect UP peers (bgpPeerAdminStatus = (start || running), bgpPeerState = established)
}
} else {
$cache['routing']['bgp']['down']++;
}
if ($bgp['local_as'] == $bgp['bgpPeerRemoteAs']) {
$cache['routing']['bgp']['internal']++;
$cache['bgp']['internal'][] = (int)$bgp['bgpPeer_id']; // Collect iBGP peers
} else {
$cache['routing']['bgp']['external']++;
$cache['bgp']['external'][] = (int)$bgp['bgpPeer_id']; // Collect eBGP peers
}
}
}
}
// OSPF
if (isset($config['enable_ospf']) && $config['enable_ospf'])
{
$cache['routing']['ospf']['last_seen'] = $config['time']['now'];
foreach (dbFetchRows("SELECT `device_id`, `ospfAdminStat` FROM `ospf_instances`") as $ospf)
{
if (!$config['web_show_disabled'])
{
if ($cache['devices']['id'][$ospf['device_id']]['disabled']) { continue; }
}
if (device_permitted($ospf))
{
if ($ospf['ospfAdminStat'] == 'enabled')
{
$cache['routing']['ospf']['up']++;
}
else if ($ospf['ospfAdminStat'] == 'disabled')
{
$cache['routing']['ospf']['down']++;
} else {
continue;
}
$cache['routing']['ospf']['count']++;
}
}
}
// if (isset($config['enable_eigrp']) && $config['enable_eigrp']) {
$cache['routing']['eigrp']['last_seen'] = $config['time']['now'];
foreach (dbFetchRows("SELECT `device_id` FROM `eigrp_vpns`") as $eigrp)
{
if (!$config['web_show_disabled'])
{
if ($cache['devices']['id'][$eigrp['device_id']]['disabled'])
{
continue;
}
}
if (device_permitted($ospf))
{
$cache['routing']['eigrp']['count']++;
}
}
// }
// Common permission sql query
//r(range_to_list($cache['devices']['permitted']));
//unset($cache['devices']['permitted']);
//$cache['where']['devices_ports_permitted'] = generate_query_permitted(array('device', 'port'));
$cache['where']['devices_permitted'] = generate_query_permitted(array('device'));
// This needs to do both, otherwise it only permits permitted ports and not ports on permitted devices.s
$cache['where']['ports_permitted'] = generate_query_permitted(array('port', 'device'));
// CEF
$cache['routing']['cef']['count'] = safe_count(dbFetchColumn("SELECT `cef_switching_id` FROM `cef_switching` WHERE 1 ".$cache['where']['devices_permitted']." GROUP BY `device_id`, `afi`;"));
// VRF
if ($config['enable_vrfs']) {
$cache['routing']['vrf']['count'] = safe_count(dbFetchColumn("SELECT DISTINCT `vrf_rd` FROM `vrfs` WHERE 1 " . $cache['where']['devices_permitted']));
}
// Status
$cache['status']['count'] = $cache['statuses']['stat']['count']; //dbFetchCell("SELECT COUNT(`status_id`) FROM `status` WHERE 1 ".$cache['where']['devices_permitted']);
// Counter
$cache['counter']['count'] = $cache['counters']['stat']['count'];
// Additional common counts
if ($config['enable_pseudowires'])
{
$cache['ports']['pseudowires'] = dbFetchColumn('SELECT DISTINCT `port_id` FROM `pseudowires` WHERE 1 '.$cache['where']['ports_permitted']);
$cache['pseudowires']['count'] = safe_count($cache['ports']['pseudowires']);
}
if ($config['poller_modules']['cisco-cbqos'] || $config['discovery_modules']['cisco-cbqos'])
{
$cache['ports']['cbqos'] = dbFetchColumn('SELECT DISTINCT `port_id` FROM `ports_cbqos` WHERE 1 '.$cache['where']['ports_permitted']);
$cache['cbqos']['count'] = safe_count($cache['ports']['cbqos']);
}
if ($config['poller_modules']['mac-accounting'] || $config['discovery_modules']['mac-accounting'])
{
$cache['ports']['mac_accounting'] = dbFetchColumn('SELECT DISTINCT `port_id` FROM `mac_accounting` WHERE 1 '.$cache['where']['ports_permitted']);
$cache['mac_accounting']['count'] = safe_count($cache['ports']['mac_accounting']);
}
// if ($config['poller_modules']['unix-agent'])
// {
$cache['packages']['count'] = dbFetchCell("SELECT COUNT(*) FROM `packages` WHERE 1 ".$cache['where']['devices_permitted']);
// }
if ($config['poller_modules']['applications'])
{
$cache['applications']['count'] = dbFetchCell("SELECT COUNT(*) FROM `applications` WHERE 1 ".$cache['where']['devices_permitted']);
}
if ($config['poller_modules']['wifi'] || $config['discovery_modules']['wifi'])
{
$cache['wifi_sessions']['count'] = dbFetchCell("SELECT COUNT(*) FROM `wifi_sessions` WHERE 1 ".$cache['where']['devices_permitted']);
}
if ($config['poller_modules']['printersupplies'] || $config['discovery_modules']['printersupplies'])
{
$cache['printersupplies']['count'] = dbFetchCell("SELECT COUNT(*) FROM `printersupplies` WHERE 1 ".$cache['where']['devices_permitted']);
}
$cache['neighbours']['count'] = dbFetchCell("SELECT COUNT(*) FROM `neighbours` WHERE `active` = 1 " . $cache['where']['ports_permitted']);
//r("SELECT COUNT(*) FROM `neighbours` WHERE `active` = 1 " . $cache['where']['ports_permitted']);
$cache['sla']['count'] = dbFetchCell("SELECT COUNT(*) FROM `slas` WHERE `deleted` = 0 " . $cache['where']['devices_permitted']);
$cache['p2pradios']['count'] = dbFetchCell("SELECT COUNT(*) FROM `p2p_radios` WHERE `deleted` = 0 " . $cache['where']['devices_permitted']);
$cache['vm']['count'] = dbFetchCell("SELECT COUNT(*) FROM `vminfo` WHERE 1 " . $cache['where']['devices_permitted']);
// Clean arrays (from DB queries)
unset($devices_array, $ports_array, $sensors_array, $status_array, $graphs_array, $device_graphs);
// Clean variables (generated by foreach)
unset($device, $port, $sensor, $status, $bgp, $ospf);
// Store $cache in fast caching
set_cache_item($cache_item, $cache);
// Clear expired cache
del_cache_expired();
} // End build cache
else {
//print_vars(get_cache_data($cache_item));
$cache = array_merge(get_cache_data($cache_item), $cache);
}
// Clean cache item
unset($cache_item);
//del_cache_expired();
//print_vars(get_cache_items('__wui'));
//print_vars(get_cache_stats());
// EOF
//$a = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE 1 AND (( (`device_id` != '' AND `device_id` IS NOT NULL)) OR ((`port_id` != '' AND `port_id` IS NOT NULL))) AND `deleted` = 0 AND `ignore` = 0");
//$b = dbFetchCell("SELECT COUNT(*) FROM `ports` INNER JOIN `devices` USING (`device_id`) WHERE `ports`.`ignore` = '0' AND `ports`.`disabled` = '0' AND `ports`.`deleted` = '0'");
//$c = dbFetchCell("SELECT COUNT(*) FROM `ports` INNER JOIN `devices` USING (`device_id`) WHERE 1 AND `ports`.`disabled` = '0' AND `ports`.`deleted` = '0'");
//r($a, $b, $c);

View File

@ -0,0 +1,4 @@
The code in this directory is distributed under the GPL
http://gnu.org/copyleft/gpl.html
Please see the headers of the code for more details.

View File

@ -0,0 +1,69 @@
<?php
/**
* Configuration file for Collectd graph browser
*/
// Array of paths when collectd's rrdtool plugin writes RRDs
$config['datadirs'] = array($config['collectd_dir']);
// Width of graph to be generated by rrdgraph
if(isset($_GET['width'])) {
$config['rrd_width'] = $_GET['width'];
} else {
$config['rrd_width'] = 270;
}
// Height of graph to be generated by rrdgraph
if(isset($_GET['height'])) {
$config['rrd_height'] = $_GET['height'];
} else {
$config['rrd_height'] = 120;
}
// List of supported timespans (used for period drop-down list)
$config['timespan'] = array(
array('name'=>'hour', 'label'=>'past hour', 'seconds'=>3600),
array('name'=>'day', 'label'=>'past day', 'seconds'=>86400),
array('name'=>'week', 'label'=>'past week', 'seconds'=>604800),
array('name'=>'month', 'label'=>'past month', 'seconds'=>2678400),
array('name'=>'year', 'label'=>'past year', 'seconds'=>31622400));
// Interval at which values are collectd (currently ignored)
$config['rrd_interval'] = 10;
// Average rows/rra (currently ignored)
$config['rrd_rows'] = 2400;
// Additional options to pass to rrdgraph
#$config['rrd_opts'] = (isset($config['rrdgraph_defaults']) ? $config['rrdgraph_defaults'] : '');
#$config['rrd_opts'] = array('-E', "-c", "SHADEA#a5a5a5", "-c", "SHADEB#a5a5a5", "-c", "FONT#000000", "-c", "CANVAS#FFFFFF", "-c", "GRID#aaaaaa",
# "-c", "MGRID#FFAAAA", "-c", "FRAME#3e3e3e", "-c", "ARROW#5e5e5e", "-R", "normal");
// Predefined set of colors for use by collectd_draw_rrd()
$config['rrd_colors'] = array(
'h_1'=>'F7B7B7', 'f_1'=>'FF0000', // Red
'h_2'=>'B7EFB7', 'f_2'=>'00E000', // Green
'h_3'=>'B7B7F7', 'f_3'=>'0000FF', // Blue
'h_4'=>'F3DFB7', 'f_4'=>'F0A000', // Yellow
'h_5'=>'B7DFF7', 'f_5'=>'00A0FF', // Cyan
'h_6'=>'DFB7F7', 'f_6'=>'A000FF', // Magenta
'h_7'=>'FFC782', 'f_7'=>'FF8C00', // Orange
'h_8'=>'DCFF96', 'f_8'=>'AAFF00', // Lime
'h_9'=>'83FFCD', 'f_9'=>'00FF99',
'h_10'=>'81D9FF', 'f_10'=>'00B2FF',
'h_11'=>'FF89F5', 'f_11'=>'FF00EA',
'h_12'=>'FF89AE', 'f_12'=>'FF0051',
'h_13'=>'BBBBBB', 'f_13'=>'555555',
);
/*
* URL to collectd's unix socket (unixsock plugin)
* enabled: 'unix:///var/run/collectd/collectd-unixsock'
* disabled: null
*/
$config['collectd_sock'] = null;
/*
* Path to TTF font file to use in error images
* (fallback when file does not exist is GD fixed font)
*/
$config['error_font'] = '/usr/share/fonts/corefonts/arial.ttf';
/*
* Constant defining full path to rrdtool
*/
define('RRDTOOL', $config['rrdtool']);
?>

View File

@ -0,0 +1,79 @@
<?php // vim:fenc=utf-8:filetype=php:ts=4
/*
* Copyright (C) 2009 Bruno Prémont <bonbons AT linux-vserver.org>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; only version 2 of the License is applicable.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
function load_graph_definitions_local($logarithmic = false, $tinylegend = false) {
global $GraphDefs, $MetaGraphDefs;
// Define 1-rrd Graph definitions here
$GraphDefs['local_type'] = array(
'-v', 'Commits',
'DEF:avg={file}:value:AVERAGE',
'DEF:min={file}:value:MIN',
'DEF:max={file}:value:MAX',
"AREA:max#B7B7F7",
"AREA:min#FFFFFF",
"LINE1:avg#0000FF:Commits",
'GPRINT:min:MIN:%6.1lf Min,',
'GPRINT:avg:AVERAGE:%6.1lf Avg,',
'GPRINT:max:MAX:%6.1lf Max,',
'GPRINT:avg:LAST:%6.1lf Last\l');
// Define MetaGraph definition type -> function mappings here
$MetaGraphDefs['local_meta'] = 'meta_graph_local';
}
function meta_graph_local($host, $plugin, $plugin_instance, $type, $type_instances, $opts = array()) {
global $config;
$sources = array();
$title = "$host/$plugin".(!is_null($plugin_instance) ? "-$plugin_instance" : '')."/$type";
if (!isset($opts['title']))
$opts['title'] = $title;
$opts['rrd_opts'] = array('-v', 'Events');
$files = array();
/* $opts['colors'] = array(
'ham' => '00e000',
'spam' => '0000ff',
'malware' => '990000',
'sent' => '00e000',
'deferred' => 'a0e000',
'reject' => 'ff0000',
'bounced' => 'a00050'
);
$type_instances = array('ham', 'spam', 'malware', 'sent', 'deferred', 'reject', 'bounced'); */
foreach ($type_instances as $inst) {
$file = '';
foreach ($config['datadirs'] as $datadir)
if (is_file($datadir.'/'.$title.'-'.$inst.'.rrd')) {
$file = $datadir.'/'.$title.'-'.$inst.'.rrd';
break;
}
if ($file == '')
continue;
$sources[] = array('name'=>$inst, 'file'=>$file);
}
// return collectd_draw_meta_stack($opts, $sources);
return collectd_draw_meta_line($opts, $sources);
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,955 @@
<?php // vim:fenc=utf-8:filetype=php:ts=4
/*
* Copyright (C) 2009 Bruno Prémont <bonbons AT linux-vserver.org>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; only version 2 of the License is applicable.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
define('REGEXP_HOST', '/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/');
define('REGEXP_PLUGIN', '/^[a-zA-Z0-9_.-]+$/');
function makeTextBlock($text, $fontfile, $fontsize, $width) {
// TODO: handle explicit line-break!
$words = explode(' ', $text);
$lines = array($words[0]);
$currentLine = 0;
foreach ($words as $word) {
$lineSize = imagettfbbox($fontsize, 0, $fontfile, $lines[$currentLine] . ' ' . $word);
if ($lineSize[2] - $lineSize[0] < $width) {
$lines[$currentLine] .= ' ' . $word;
} else {
$currentLine++;
$lines[$currentLine] = $word;
}
}
//error_log(sprintf('Handles message "%s", %d words => %d/%d lines', $text, count($words), $currentLine, count($lines)));
return implode("\n", $lines);
}
/**
* No RRD files found that could match request
* @code HTTP error code
* @code_msg Short text description of HTTP error code
* @title Title for fake RRD graph
* @msg Complete error message to display in place of graph content
*/
function error_collectd($code, $code_msg, $title, $msg) {
global $config;
header(sprintf("HTTP/1.0 %d %s", $code, $code_msg));
header("Pragma: no-cache");
header("Expires: Mon, 01 Jan 2008 00:00:00 CET");
header("Content-Type: image/png");
$w = $config['rrd_width']+81;
$h = $config['rrd_height']+79;
$png = imagecreate($w, $h);
$c_bkgnd = imagecolorallocate($png, 240, 240, 240);
$c_fgnd = imagecolorallocate($png, 255, 255, 255);
$c_blt = imagecolorallocate($png, 208, 208, 208);
$c_brb = imagecolorallocate($png, 160, 160, 160);
$c_grln = imagecolorallocate($png, 114, 114, 114);
$c_grarr = imagecolorallocate($png, 128, 32, 32);
$c_txt = imagecolorallocate($png, 0, 0, 0);
$c_etxt = imagecolorallocate($png, 64, 0, 0);
if (function_exists('imageantialias'))
imageantialias($png, true);
imagefilledrectangle($png, 0, 0, $w, $h, $c_bkgnd);
imagefilledrectangle($png, 51, 33, $w-31, $h-47, $c_fgnd);
imageline($png, 51, 30, 51, $h-43, $c_grln);
imageline($png, 48, $h-46, $w-28, $h-46, $c_grln);
imagefilledpolygon($png, array(49, 30, 51, 26, 53, 30), 3, $c_grarr);
imagefilledpolygon($png, array($w-28, $h-48, $w-24, $h-46, $w-28, $h-44), 3, $c_grarr);
imageline($png, 0, 0, $w, 0, $c_blt);
imageline($png, 0, 1, $w, 1, $c_blt);
imageline($png, 0, 0, 0, $h, $c_blt);
imageline($png, 1, 0, 1, $h, $c_blt);
imageline($png, $w-1, 0, $w-1, $h, $c_brb);
imageline($png, $w-2, 1, $w-2, $h, $c_brb);
imageline($png, 1, $h-2, $w, $h-2, $c_brb);
imageline($png, 0, $h-1, $w, $h-1, $c_brb);
imagestring($png, 4, ceil(($w-strlen($title)*imagefontwidth(4)) / 2), 10, $title, $c_txt);
imagestring($png, 5, 60, 35, sprintf('%s [%d]', $code_msg, $code), $c_etxt);
if (function_exists('imagettfbbox') && is_file($config['error_font'])) {
// Detailled error message
$fmt_msg = makeTextBlock($msg, $errorfont, 10, $w-86);
$fmtbox = imagettfbbox(12, 0, $errorfont, $fmt_msg);
imagettftext($png, 10, 0, 55, 35+3+imagefontwidth(5)-$fmtbox[7]+$fmtbox[1], $c_txt, $errorfont, $fmt_msg);
} else {
imagestring($png, 4, 53, 35+6+imagefontwidth(5), $msg, $c_txt);
}
imagepng($png);
imagedestroy($png);
}
/**
* No RRD files found that could match request
*/
function error404($title, $msg) {
error_collectd(404, "Not found", $title, $msg);
}
function error500($title, $msg) {
error_collectd(500, "Not found", $title, $msg);
}
/**
* Incomplete / invalid request
*/
function error400($title, $msg) {
error_collectd(400, "Bad request", $title, $msg);
}
/**
* Read input variable from GET, POST or COOKIE taking
* care of magic quotes
* @name Name of value to return
* @array User-input array ($_GET, $_POST or $_COOKIE)
* @default Default value
* @return $default if name in unknown in $array, otherwise
* input value with magic quotes stripped off
*/
function read_var($name, &$array, $default = null) {
if (isset($array[$name])) {
/*
if (is_array($array[$name])) {
if (get_magic_quotes_gpc()) {
$ret = array();
foreach ($array[$name] as $k => $v) {
$ret[stripslashes($k)] = stripslashes($v);
}
return $ret;
} else
return $array[$name];
} else if (is_string($array[$name]) && get_magic_quotes_gpc()) {
return stripslashes($array[$name]);
} else
*/
return $array[$name];
}
return $default;
}
/**
* Alphabetically compare host names, comparing label
* from tld to node name
*/
function collectd_compare_host($a, $b) {
$ea = explode('.', $a);
$eb = explode('.', $b);
$i = count($ea) - 1;
$j = count($eb) - 1;
while ($i >= 0 && $j >= 0) {
if (($r = strcmp($ea[$i--], $eb[$j--])) != 0) {
return $r;
}
}
return 0;
}
/**
* Fetch list of hosts found in collectd's datadirs.
* @return array Sorted list of hosts (sorted by label from right to left)
*/
function collectd_list_hosts() {
global $config;
$hosts = array();
foreach($config['datadirs'] as $datadir) {
if ($d = @opendir($datadir)) {
while (($dent = readdir($d)) !== FALSE) {
if ($dent != '.' && $dent != '..' && is_dir($datadir . '/' . $dent) && preg_match(REGEXP_HOST, $dent)) {
$hosts[] = $dent;
}
}
closedir($d);
} else {
//error_log('Failed to open datadir: ' . $datadir);
}
}
$hosts = array_unique($hosts);
usort($hosts, 'collectd_compare_host');
return $hosts;
}
/**
* Fetch list of plugins found in collectd's datadirs for given host.
* @arg_host Name of host for which to return plugins
* @return array Sorted list of plugins (sorted alphabetically)
*/
function collectd_list_plugins($arg_host) {
global $config;
$plugins = array();
foreach ($config['datadirs'] as $datadir) {
if (preg_match(REGEXP_HOST, $arg_host) && ($d = @opendir($datadir . '/' . $arg_host))) {
while (($dent = readdir($d)) !== FALSE) {
if ($dent != '.' && $dent != '..' && is_dir($datadir . '/' . $arg_host . '/' . $dent)) {
if ($i = strpos($dent, '-')) {
$plugins[] = substr($dent, 0, $i);
} else {
$plugins[] = $dent;
}
}
}
closedir($d);
}
}
$plugins = array_unique($plugins);
sort($plugins);
return $plugins;
}
/**
* Fetch list of plugin instances found in collectd's datadirs for given host+plugin
* @arg_host Name of host
* @arg_plugin Name of plugin
* @return array Sorted list of plugin instances (sorted alphabetically)
*/
function collectd_list_pinsts($arg_host, $arg_plugin) {
global $config;
$pinsts = array();
foreach ($config['datadirs'] as $datadir) {
if (preg_match(REGEXP_HOST, $arg_host) && ($d = opendir($datadir . '/' . $arg_host))) {
while (($dent = readdir($d)) !== FALSE) {
if ($dent != '.' && $dent != '..' && is_dir($datadir . '/' . $arg_host . '/' . $dent)) {
if ($i = strpos($dent, '-')) {
$plugin = substr($dent, 0, $i);
$pinst = substr($dent, $i + 1);
} else {
$plugin = $dent;
$pinst = '';
}
if ($plugin == $arg_plugin) {
$pinsts[] = $pinst;
}
}
}
closedir($d);
}
}
$pinsts = array_unique($pinsts);
sort($pinsts);
return $pinsts;
}
/**
* Fetch list of types found in collectd's datadirs for given host+plugin+instance
* @arg_host Name of host
* @arg_plugin Name of plugin
* @arg_pinst Plugin instance
* @return Sorted list of types (sorted alphabetically)
*/
function collectd_list_types($arg_host, $arg_plugin, $arg_pinst) {
global $config;
$types = array();
$my_plugin = $arg_plugin . (strlen($arg_pinst) ? '-'.$arg_pinst : '');
if (!preg_match(REGEXP_PLUGIN, $my_plugin)) {
return $types;
}
foreach ($config['datadirs'] as $datadir) {
if (preg_match(REGEXP_HOST, $arg_host) && ($d = @opendir($datadir . '/' . $arg_host . '/' . $my_plugin))) {
while (($dent = readdir($d)) !== FALSE) {
if ($dent != '.' && $dent != '..' && is_file($datadir . '/' . $arg_host . '/' . $my_plugin . '/' . $dent) && substr($dent, strlen($dent) - 4) == '.rrd') {
$dent = substr($dent, 0, strlen($dent) - 4);
if ($i = strpos($dent, '-')) {
$types[] = substr($dent, 0, $i);
} else {
$types[] = $dent;
}
}
}
closedir($d);
}
}
$types = array_unique($types);
sort($types);
return $types;
}
/**
* Fetch list of type instances found in collectd's datadirs for given host+plugin+instance+type
* @arg_host Name of host
* @arg_plugin Name of plugin
* @arg_pinst Plugin instance
* @arg_type Type
* @return Sorted list of type instances (sorted alphabetically)
*/
function collectd_list_tinsts($arg_host, $arg_plugin, $arg_pinst, $arg_type) {
global $config;
$tinsts = array();
$my_plugin = $arg_plugin . (strlen($arg_pinst) ? '-'.$arg_pinst : '');
if (!preg_match(REGEXP_PLUGIN, $my_plugin)) {
return $types;
}
foreach ($config['datadirs'] as $datadir) {
if (preg_match(REGEXP_HOST, $arg_host) && ($d = @opendir($datadir . '/' . $arg_host . '/' . $my_plugin))) {
while (($dent = readdir($d)) !== FALSE) {
if ($dent != '.' && $dent != '..' && is_file($datadir . '/' . $arg_host . '/' . $my_plugin . '/' . $dent) && substr($dent, strlen($dent) - 4) == '.rrd') {
$dent = substr($dent, 0, strlen($dent) - 4);
if ($i = strpos($dent, '-')) {
$type = substr($dent, 0, $i);
$tinst = substr($dent, $i + 1);
} else {
$type = $dent;
$tinst = '';
}
if ($type == $arg_type) {
$tinsts[] = $tinst;
}
}
}
closedir($d);
}
}
$tinsts = array_unique($tinsts);
sort($tinsts);
return $tinsts;
}
/**
* Parse symlinks in order to get an identifier that collectd understands
* (e.g. virtualisation is collected on host for individual VMs and can be
* symlinked to the VM's hostname, support FLUSH for these by flushing
* on the host-identifier instead of VM-identifier)
* @host Host name
* @plugin Plugin name
* @pinst Plugin instance
* @type Type name
* @tinst Type instance
* @return Identifier that collectd's FLUSH command understands
*/
function collectd_identifier($host, $plugin, $pinst, $type, $tinst) {
global $config;
$rrd_realpath = null;
$orig_identifier = sprintf('%s/%s%s%s/%s%s%s', $host, $plugin, strlen($pinst) ? '-' : '', $pinst, $type, strlen($tinst) ? '-' : '', $tinst);
$identifier = null;
foreach ($config['datadirs'] as $datadir) {
if (is_file($datadir . '/' . $orig_identifier . '.rrd')) {
$rrd_realpath = realpath($datadir . '/' . $orig_identifier . '.rrd');
break;
}
}
if ($rrd_realpath) {
$identifier = basename($rrd_realpath);
$identifier = substr($identifier, 0, strlen($identifier)-4);
$rrd_realpath = dirname($rrd_realpath);
$identifier = basename($rrd_realpath).'/'.$identifier;
$rrd_realpath = dirname($rrd_realpath);
$identifier = basename($rrd_realpath).'/'.$identifier;
}
if (is_null($identifier)) {
return $orig_identifier;
}
return $identifier;
}
/**
* Tell collectd that it should FLUSH all data it has regarding the
* graph we are about to generate.
* @host Host name
* @plugin Plugin name
* @pinst Plugin instance
* @type Type name
* @tinst Type instance
*/
function collectd_flush($identifier) {
global $config;
if (!$config['collectd_sock']) {
return FALSE;
}
if (is_null($identifier) || (is_array($identifier) && count($identifier) == 0) || !(is_string($identifier) || is_array($identifier))) {
return FALSE;
}
if (is_null($host) || !is_string($host) || strlen($host) == 0) {
return FALSE;
}
if (is_null($plugin) || !is_string($plugin) || strlen($plugin) == 0) {
return FALSE;
}
if (is_null($pinst) || !is_string($pinst)) {
return FALSE;
}
if (is_null($type) || !is_string($type) || strlen($type) == 0) {
return FALSE;
}
if (is_null($tinst) || (is_array($tinst) && count($tinst) == 0) || !(is_string($tinst) || is_array($tinst))) {
return FALSE;
}
$u_errno = 0;
$u_errmsg = '';
if ($socket = @fsockopen($config['collectd_sock'], 0, $u_errno, $u_errmsg)) {
$cmd = 'FLUSH plugin=rrdtool';
if (is_array($identifier)) {
foreach ($identifier as $val) {
$cmd .= sprintf(' identifier="%s"', $val);
}
} else {
$cmd .= sprintf(' identifier="%s"', $identifier);
}
$cmd .= "\n";
$r = fwrite($socket, $cmd, strlen($cmd));
if ($r === false || $r != strlen($cmd)) {
error_log(sprintf("graph.php: Failed to write whole command to unix-socket: %d out of %d written", $r === FALSE ? -1 : $r, strlen($cmd)));
}
$resp = fgets($socket);
if ($resp === false) {
error_log(sprintf("graph.php: Failed to read response from collectd for command: %s", trim($cmd)));
}
$n = (int)$resp;
while ($n-- > 0) {
fgets($socket);
}
fclose($socket);
} else {
error_log(sprintf("graph.php: Failed to open unix-socket to collectd: %d: %s", $u_errno, $u_errmsg));
}
}
class CollectdColor {
private $r = 0;
private $g = 0;
private $b = 0;
function __construct($value = null) {
if (is_null($value)) {
} elseif (is_array($value)) {
if (isset($value['r'])) {
$this->r = $value['r'] > 0 ? ($value['r'] > 1 ? 1 : $value['r']) : 0;
}
if (isset($value['g'])) {
$this->g = $value['g'] > 0 ? ($value['g'] > 1 ? 1 : $value['g']) : 0;
}
if (isset($value['b'])) {
$this->b = $value['b'] > 0 ? ($value['b'] > 1 ? 1 : $value['b']) : 0;
}
} elseif (is_string($value)) {
$matches = array();
if ($value == 'random') {
$this->randomize();
} else if (preg_match('/([0-9A-Fa-f][0-9A-Fa-f])([0-9A-Fa-f][0-9A-Fa-f])([0-9A-Fa-f][0-9A-Fa-f])/', $value, $matches)) {
$this->r = hexdec($matches[1]) / 255.0;
$this->g = hexdec($matches[2]) / 255.0;
$this->b = hexdec($matches[3]) / 255.0;
}
} elseif (is_a($value, 'CollectdColor')) {
$this->r = $value->r;
$this->g = $value->g;
$this->b = $value->b;
}
}
function randomize() {
$this->r = mt_rand(0, 255) / 255.0;
$this->g = mt_rand(0, 255) / 255.0;
$this->b = 0.0;
$min = 0.0;
$max = 1.0;
if (($this->r + $this->g) < 1.0) {
$min = 1.0 - ($this->r + $this->g);
} else {
$max = 2.0 - ($this->r + $this->g);
}
$this->b = $min + ((mt_rand(0, 255) / 255.0) * ($max - $min));
}
function fade($bkgnd = null, $alpha = 0.25) {
if (is_null($bkgnd) || !is_a($bkgnd, 'CollectdColor')) {
$bg_r = 1.0;
$bg_g = 1.0;
$bg_b = 1.0;
} else {
$bg_r = $bkgnd->r;
$bg_g = $bkgnd->g;
$bg_b = $bkgnd->b;
}
$this->r = $alpha * $this->r + ((1.0 - $alpha) * $bg_r);
$this->g = $alpha * $this->g + ((1.0 - $alpha) * $bg_g);
$this->b = $alpha * $this->b + ((1.0 - $alpha) * $bg_b);
}
function as_array() {
return array('r'=>$this->r, 'g'=>$this->g, 'b'=>$this->b);
}
function as_string() {
$r = (int)($this->r*255);
$g = (int)($this->g*255);
$b = (int)($this->b*255);
return sprintf('%02x%02x%02x', $r > 255 ? 255 : $r, $g > 255 ? 255 : $g, $b > 255 ? 255 : $b);
}
}
function rrd_get_color($code, $line = true) {
global $config;
$name = ($line ? 'f_' : 'h_').$code;
if (!isset($config['rrd_colors'][$name])) {
$c_f = new CollectdColor('random');
$c_h = new CollectdColor($c_f);
$c_h->fade();
$config['rrd_colors']['f_'.$code] = $c_f->as_string();
$config['rrd_colors']['h_'.$code] = $c_h->as_string();
}
return $config['rrd_colors'][$name];
}
/**
* Draw RRD file based on it's structure
* @host
* @plugin
* @pinst
* @type
* @tinst
* @opts
* @return Commandline to call RRDGraph in order to generate the final graph
*/
function collectd_draw_rrd($host, $plugin, $pinst = null, $type, $tinst = null, $opts = array()) {
global $config;
$timespan_def = null;
if (!isset($opts['timespan'])) {
$timespan_def = reset($config['timespan']);
} else {
foreach ($config['timespan'] as &$ts) {
if ($ts['name'] == $opts['timespan']) {
$timespan_def = $ts;
}
}
}
if (!isset($opts['rrd_opts'])) {
$opts['rrd_opts'] = array();
}
if (isset($opts['logarithmic']) && $opts['logarithmic']) {
array_unshift($opts['rrd_opts'], '-o');
}
$rrdinfo = null;
$rrdfile = sprintf('%s/%s%s%s/%s%s%s', $host, $plugin, is_null($pinst) ? '' : '-', $pinst, $type, is_null($tinst) ? '' : '-', $tinst);
foreach ($config['datadirs'] as $datadir) {
if (is_file($datadir.'/'.$rrdfile.'.rrd')) {
$rrdinfo = rrdtool_file_info($datadir.'/'.$rrdfile.'.rrd');
if (isset($rrdinfo['RRA']) && is_array($rrdinfo['RRA'])) {
break;
} else {
$rrdinfo = NULL;
}
}
}
if (is_null($rrdinfo)) {
return FALSE;
}
$graph = array();
$has_avg = false;
$has_max = false;
$has_min = false;
reset($rrdinfo['RRA']);
$l_max = 0;
foreach ($rrdinfo['RRA'] as $k => $v) {
if ($v['cf'] == 'MAX') {
$has_max = TRUE;
} elseif ($v['cf'] == 'AVERAGE') {
$has_avg = TRUE;
} elseif ($v['cf'] == 'MIN') {
$has_min = TRUE;
}
}
// Build legend. This may not work for all RRDs, i don't know :)
if ($has_avg) {
$graph[] = "COMMENT: Last";
}
if ($has_min) {
$graph[] = "COMMENT: Min";
}
if ($has_max) {
$graph[] = "COMMENT: Max";
}
if ($has_avg) {
$graph[] = "COMMENT: Avg\\n";
}
reset($rrdinfo['DS']);
foreach ($rrdinfo['DS'] as $k => $v) {
if (strlen($k) > $l_max) {
$l_max = strlen($k);
}
if ($has_min) {
$graph[] = sprintf('DEF:%s_min=%s:%s:MIN', $k, $rrdinfo['filename'], $k);
}
if ($has_avg) {
$graph[] = sprintf('DEF:%s_avg=%s:%s:AVERAGE', $k, $rrdinfo['filename'], $k);
}
if ($has_max) {
$graph[] = sprintf('DEF:%s_max=%s:%s:MAX', $k, $rrdinfo['filename'], $k);
}
}
if (($has_min && $has_max) || ($has_min && $has_avg) || ($has_avg && $has_max)) {
$n = 1;
reset($rrdinfo['DS']);
foreach ($rrdinfo['DS'] as $k => $v) {
$graph[] = sprintf('LINE:%s_%s', $k, $has_min ? 'min' : 'avg');
$graph[] = sprintf('CDEF:%s_var=%s_%s,%s_%s,-', $k, $k, $has_max ? 'max' : 'avg', $k, $has_min ? 'min' : 'avg');
$graph[] = sprintf('AREA:%s_var#%s::STACK', $k, rrd_get_color($n++, false));
}
}
reset($rrdinfo['DS']);
$n = 1;
foreach ($rrdinfo['DS'] as $k => $v) {
$graph[] = sprintf('LINE1:%s_avg#%s:%s ', $k, rrd_get_color($n++, true), $k.substr(' ', 0, $l_max-strlen($k)));
if (isset($opts['tinylegend']) && $opts['tinylegend']) {
continue;
}
if ($has_avg) {
$graph[] = sprintf('GPRINT:%s_avg:AVERAGE:%%5.1lf%%s', $k, $has_max || $has_min || $has_avg ? ',' : "\\l");
}
if ($has_min) {
$graph[] = sprintf('GPRINT:%s_min:MIN:%%5.1lf%%s', $k, $has_max || $has_avg ? ',' : "\\l");
}
if ($has_max) {
$graph[] = sprintf('GPRINT:%s_max:MAX:%%5.1lf%%s', $k, $has_avg ? ',' : "\\l");
}
if ($has_avg) {
$graph[] = sprintf('GPRINT:%s_avg:LAST:%%5.1lf%%s\\l', $k);
}
}
#$rrd_cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height'], '-t', $rrdfile);
#$rrd_cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
$rrd_cmd = array('-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
if ($config['rrd_width'] <= "300") {
$small_opts = array ('--font', "LEGEND:7:mono", '--font', "AXIS:6:mono", "--font-render-mode", "normal");
$rrd_cmd = array_merge($rrd_cmd, $small_opts);
}
//$rrd_cmd = array_merge($rrd_cmd, $config['rrd_opts_array'], $opts['rrd_opts'], $graph);
$rrd_cmd = collectd_rrdcmd($rrd_cmd, $opts['rrd_opts'], $graph);
$cmd = RRDTOOL; $cmd = '';
for ($i = 1; $i < count($rrd_cmd); $i++) {
$cmd .= ' ' . escapeshellarg($rrd_cmd[$i]);
}
return $cmd;
}
/**
* Draw RRD file based on it's structure
* @timespan
* @host
* @plugin
* @pinst
* @type
* @tinst
* @opts
* @return Commandline to call RRDGraph in order to generate the final graph
*/
function collectd_draw_generic($timespan, $host, $plugin, $pinst = null, $type, $tinst = null) {
global $config, $GraphDefs;
$timespan_def = NULL;
foreach ($config['timespan'] as &$ts) {
if ($ts['name'] == $timespan) {
$timespan_def = $ts;
}
}
if (is_null($timespan_def)) {
$timespan_def = reset($config['timespan']);
}
if (!isset($GraphDefs[$type])) {
return FALSE;
}
$rrd_file = sprintf('%s/%s%s%s/%s%s%s', $host, $plugin, is_null($pinst) ? '' : '-', $pinst, $type, is_null($tinst) ? '' : '-', $tinst);
#$rrd_cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height'], '-t', $rrd_file);
#$rrd_cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
$rrd_cmd = array('-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
if ($config['rrd_width'] <= "300") {
$small_opts = array ('--font', 'LEGEND:7:mono', '--font', 'AXIS:6:mono', '--font-render-mode', 'normal');
$rrd_cmd = array_merge($rrd_cmd, $small_opts);
}
//$rrd_cmd = array_merge($rrd_cmd, $config['rrd_opts_array']);
$rrd_cmd = collectd_rrdcmd($rrd_cmd);
$rrd_args = $GraphDefs[$type];
foreach ($config['datadirs'] as $datadir) {
$file = $datadir.'/'.$rrd_file.'.rrd';
if (!is_file($file)) {
continue;
}
$file = str_replace(":", "\\:", $file);
$rrd_args = str_replace('{file}', $file, $rrd_args);
$rrdgraph = array_merge($rrd_cmd, $rrd_args);
#$cmd = RRDTOOL;
$cmd = '';
for ($i = 1; $i < count($rrdgraph); $i++) {
$cmd .= ' ' . escapeshellarg($rrdgraph[$i]);
}
return $cmd;
}
return false;
}
/**
* Draw stack-graph for set of RRD files
* @opts Graph options like colors
* @sources List of array(name, file, ds)
* @return Commandline to call RRDGraph in order to generate the final graph
*/
function collectd_draw_meta_stack(&$opts, &$sources) {
global $config;
$timespan_def = null;
if (!isset($opts['timespan'])) {
$timespan_def = reset($config['timespan']);
} else {
foreach ($config['timespan'] as &$ts) {
if ($ts['name'] == $opts['timespan']) {
$timespan_def = $ts;
}
}
}
if (!isset($opts['title'])) {
$opts['title'] = 'Unknown title';
}
if (!isset($opts['rrd_opts'])) {
$opts['rrd_opts'] = array();
}
if (!isset($opts['colors'])) {
$opts['colors'] = array();
}
if (isset($opts['logarithmic']) && $opts['logarithmic']) {
array_unshift($opts['rrd_opts'], '-o');
}
# $cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height'],
# '-t', $opts['title']);
#$cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
$cmd = array('-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
if ($config['rrd_width'] <= "300") {
$small_opts = array ('--font', 'LEGEND:7:mono', '--font', 'AXIS:6:mono', '--font-render-mode', 'normal');
$cmd = array_merge($cmd, $small_opts);
}
//$cmd = array_merge($cmd, $config['rrd_opts_array'], $opts['rrd_opts']);
$cmd = collectd_rrdcmd($cmd, $opts['rrd_opts']);
$max_inst_name = 0;
foreach($sources as &$inst_data) {
$inst_name = $inst_data['name'];
$file = $inst_data['file'];
$ds = isset($inst_data['ds']) ? $inst_data['ds'] : 'value';
if (strlen($inst_name) > $max_inst_name) {
$max_inst_name = strlen($inst_name);
}
if (!is_file($file)) {
continue;
}
$cmd[] = 'DEF:'.$inst_name.'_min='.$file.':'.$ds.':MIN';
$cmd[] = 'DEF:'.$inst_name.'_avg='.$file.':'.$ds.':AVERAGE';
$cmd[] = 'DEF:'.$inst_name.'_max='.$file.':'.$ds.':MAX';
$cmd[] = 'CDEF:'.$inst_name.'_nnl='.$inst_name.'_avg,UN,0,'.$inst_name.'_avg,IF';
}
$inst_data = end($sources);
$inst_name = $inst_data['name'];
$cmd[] = 'CDEF:'.$inst_name.'_stk='.$inst_name.'_nnl';
$inst_data1 = end($sources);
while (($inst_data0 = prev($sources)) !== false) {
$inst_name0 = $inst_data0['name'];
$inst_name1 = $inst_data1['name'];
$cmd[] = 'CDEF:'.$inst_name0.'_stk='.$inst_name0.'_nnl,'.$inst_name1.'_stk,+';
$inst_data1 = $inst_data0;
}
foreach($sources as &$inst_data) {
$inst_name = $inst_data['name'];
# $legend = sprintf('%s', $inst_name);
$legend = $inst_name;
while (strlen($legend) < $max_inst_name) {
$legend .= ' ';
}
$number_format = isset($opts['number_format']) ? $opts['number_format'] : '%6.1lf';
if (isset($opts['colors'][$inst_name])) {
$line_color = new CollectdColor($opts['colors'][$inst_name]);
} else {
$line_color = new CollectdColor('random');
}
$area_color = new CollectdColor($line_color);
$area_color->fade();
$cmd[] = 'AREA:'.$inst_name.'_stk#'.$area_color->as_string();
$cmd[] = 'LINE1:'.$inst_name.'_stk#'.$line_color->as_string().':'.$legend;
if (!(isset($opts['tinylegend']) && $opts['tinylegend'])) {
$cmd[] = 'GPRINT:'.$inst_name.'_avg:LAST:'.$number_format.'';
$cmd[] = 'GPRINT:'.$inst_name.'_avg:AVERAGE:'.$number_format.'';
$cmd[] = 'GPRINT:'.$inst_name.'_min:MIN:'.$number_format.'';
$cmd[] = 'GPRINT:'.$inst_name.'_max:MAX:'.$number_format.'\\l';
}
}
$rrdargs = "";
for ($i = 1; $i < count($cmd); $i++) {
$rrdargs .= ' ' . escapeshellarg($cmd[$i]);
}
return $rrdargs;
}
/**
* Draw stack-graph for set of RRD files
* @opts Graph options like colors
* @sources List of array(name, file, ds)
* @return Commandline to call RRDGraph in order to generate the final graph
*/
function collectd_draw_meta_line(&$opts, &$sources) {
global $config;
$timespan_def = null;
if (!isset($opts['timespan'])) {
$timespan_def = reset($config['timespan']);
} else {
foreach ($config['timespan'] as &$ts) {
if ($ts['name'] == $opts['timespan']) {
$timespan_def = $ts;
}
}
}
if (!isset($opts['title'])) {
$opts['title'] = 'Unknown title';
}
if (!isset($opts['rrd_opts'])) {
$opts['rrd_opts'] = array();
}
if (!isset($opts['colors'])) {
$opts['colors'] = array();
}
if (isset($opts['logarithmic']) && $opts['logarithmic']) {
array_unshift($opts['rrd_opts'], '-o');
}
# $cmd = array(RRDTOOL, 'graph', '-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height'], '-t', $opts['title']);
# $cmd = array_merge($cmd, $config['rrd_opts_array'], $opts['rrd_opts']);
$cmd = array('-', '-E', '-a', 'PNG', '-w', $config['rrd_width'], '-h', $config['rrd_height']);
if ($config['rrd_width'] <= "300") {
$small_opts = array ('--font', 'LEGEND:7:mono', '--font', 'AXIS:6:mono', '--font-render-mode', 'normal');
$cmd = array_merge($cmd, $small_opts);
}
//$cmd = array_merge($cmd, $config['rrd_opts_array'], $opts['rrd_opts']);
$cmd = collectd_rrdcmd($cmd, $opts['rrd_opts']);
$max_inst_name = 0;
foreach ($sources as &$inst_data) {
$inst_name = $inst_data['name'];
$file = $inst_data['file'];
$ds = isset($inst_data['ds']) ? $inst_data['ds'] : 'value';
if (strlen($inst_name) > $max_inst_name) {
$max_inst_name = strlen($inst_name);
}
if (!is_file($file)) {
continue;
}
$cmd[] = 'DEF:'.$inst_name.'_min='.$file.':'.$ds.':MIN';
$cmd[] = 'DEF:'.$inst_name.'_avg='.$file.':'.$ds.':AVERAGE';
$cmd[] = 'DEF:'.$inst_name.'_max='.$file.':'.$ds.':MAX';
}
foreach ($sources as &$inst_data) {
$inst_name = $inst_data['name'];
$legend = sprintf('%s', $inst_name);
while (strlen($legend) < $max_inst_name) {
$legend .= ' ';
}
$number_format = isset($opts['number_format']) ? $opts['number_format'] : '%6.1lf';
if (isset($opts['colors'][$inst_name])) {
$line_color = new CollectdColor($opts['colors'][$inst_name]);
} else {
$line_color = new CollectdColor('random');
}
$cmd[] = 'LINE1:'.$inst_name.'_avg#'.$line_color->as_string().':'.$legend;
if (!(isset($opts['tinylegend']) && $opts['tinylegend'])) {
$cmd[] = 'GPRINT:'.$inst_name.'_min:MIN:'.$number_format.'';
$cmd[] = 'GPRINT:'.$inst_name.'_avg:AVERAGE:'.$number_format.'';
$cmd[] = 'GPRINT:'.$inst_name.'_max:MAX:'.$number_format.'';
$cmd[] = 'GPRINT:'.$inst_name.'_avg:LAST:'.$number_format.'\\l';
}
}
$rrdargs = "";
for ($i = 1; $i < count($cmd); $i++) {
$rrdargs .= ' ' . escapeshellarg($cmd[$i]);
}
return $rrdargs;
}
// DERP compatibility
function collectd_rrdcmd($rrd_cmd, $rrd_opts = [], $graph = []) {
if ($GLOBALS['config']['themes'][$_SESSION['theme']]['type'] == 'dark') {
$rrd_opts_array = str_replace(" ", " ", $GLOBALS['config']['rrdgraph']['dark']);
} else {
$rrd_opts_array = str_replace(" ", " ", $GLOBALS['config']['rrdgraph']['light']);
}
$rrd_opts_array = explode(" ", trim($rrd_opts_array));
return array_merge($rrd_cmd, $rrd_opts_array, $rrd_opts, $graph);
}
// EOF

View File

@ -0,0 +1,481 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
*
*/
if (!is_array($alert_rules)) { $alert_rules = cache_alert_rules(); }
$navbar['class'] = 'navbar-narrow';
$navbar['brand'] = 'Contacts';
$pages = [ 'contacts' => 'Contact List' ];
foreach ($pages as $page_name => $page_desc) {
if ($vars['page'] == $page_name) {
$navbar['options'][$page_name]['class'] = "active";
}
$navbar['options'][$page_name]['url'] = generate_url(array('page' => $page_name));
$navbar['options'][$page_name]['text'] = escape_html($page_desc);
}
$navbar['options_right']['add']['url'] = '#modal-add_contact';
$navbar['options_right']['add']['link_opts'] = 'data-toggle="modal"';
$navbar['options_right']['add']['text'] = 'Add Contact';
$navbar['options_right']['add']['icon'] = $config['icon']['contact-add'];
$navbar['options_right']['add']['userlevel'] = 10;
// Print out the navbar defined above
print_navbar($navbar);
unset($navbar);
/* Begin Add contact */
/*
$modal_args = array(
'id' => 'modal-add_contact',
'title' => 'Add New Contact',
'icon' => 'oicon-sql-join-inner',
//'hide' => TRUE,
//'fade' => TRUE,
//'role' => 'dialog',
//'class' => 'modal-md',
);
*/
$form = [
'type' => 'horizontal',
'userlevel' => 10, // Minimum user level for display form
'id' => 'modal-add_contact',
'title' => 'Add New Contact',
'icon' => 'oicon-sql-join-inner',
//'modal_args' => [ 'class' => 'modal-lg' ], // !!! This generate modal specific form
//'class' => '', // Clean default box class!
'url' => 'contacts/'
];
//$form['fieldset']['body'] = array('class' => 'modal-body'); // Required this class for modal body!
//$form['fieldset']['footer'] = array('class' => 'modal-footer'); // Required this class for modal footer!
$row = 0;
$form_params = [];
$form['row'][++$row]['contact_method'] = [
'type' => 'select',
'fieldset' => 'body',
'name' => 'Transport',
'width' => '270px',
//'live-search' => FALSE,
//'values' => $form_params['method'],
'value' => 'email'
];
$row_tmp = $row; // Store row number
foreach (array_keys($config['transports']) as $transport) {
$form_params['method'][$transport] = $config['transports'][$transport]['name'];
if (isset($config['transports'][$transport]['docs'])) {
// Known key in docs page (use if transport name is different with docs page)
$docs_link = OBSERVIUM_DOCS_URL . '/alerting_transports/#' . $config['transports'][$transport]['docs'];
} else {
$docs_link = OBSERVIUM_DOCS_URL . '/alerting_transports/#' . str_replace(' ', '-', strtolower($config['transports'][$transport]['name']));
}
$form['row'][++$row]['contact_' . $transport . '_doc'] = [
'type' => 'html',
'fieldset' => 'body',
'offset' => TRUE,
'html' => '<a id="contact_' . $transport . '_doc" href="' . $docs_link . '" target="_blank">See documentation for this Transport (new page)</a>'
];
}
if (is_array($form_params['method'])) {
asort($form_params['method']);
}
$form['row'][$row_tmp]['contact_method']['values'] = $form_params['method'];
$form['row'][++$row]['contact_descr'] = [
'type' => 'text',
'fieldset' => 'body',
'name' => 'Description',
'class' => 'input-xlarge',
'value' => ''
];
foreach ($config['transports'] as $transport => $data) {
$row++;
if (safe_count($data['parameters']['required']) || safe_count($data['parameters']['global'])) {
$form['row'][$row]['contact_' . $transport . '_required'] = [
'type' => 'html',
'fieldset' => 'body',
'html' => '<h3 id="contact_' . $transport . '_required">Required parameters</h3>'
];
$row++;
// Temporary merge req & global
foreach (array_merge((array)$data['parameters']['required'], (array)$data['parameters']['global']) as $parameter => $param_data) {
switch($param_data['type']) {
case 'enum-freeinput':
$form_param = [
'type' => 'tags',
'fieldset' => 'body',
'name' => $param_data['description'],
'width' => '270px',// '100%',
'value' => isset($param_data['default']) ? $param_data['default'] : '',
'values' => $param_data['params']
];
break;
case 'bool':
case 'boolean':
// Boolean type is just select with true/false string
if (!isset($param_data['params'])) {
$param_data['params'] = [ '' => 'Unset', 'true' => 'True', 'false' => 'False' ];
}
// do not break here
case 'enum':
$form_param = [
'type' => 'select',
'fieldset' => 'body',
'name' => $param_data['description'],
'width' => '270px', //'100%',
'value' => isset($param_data['default']) ? $param_data['default'] : '',
'values' => $param_data['params']
];
break;
case 'textarea':
$form_param = [
'type' => 'textarea',
'fieldset' => 'body',
'name' => $param_data['description'],
'width' => '270px',
'rows' => 5,
'value' => isset($param_data['default']) ? $param_data['default'] : ''
];
// Prettify JSON
if (isset($param_data['format']) && $param_data['format'] === 'json' &&
$json = safe_json_decode($form_param['value'])) {
$form_param['value'] = safe_json_encode($json, JSON_PRETTY_PRINT);
}
break;
default:
$form_param = [
'type' => 'text',
'fieldset' => 'body',
'name' => $param_data['description'],
'class' => 'input-xlarge',
'value' => isset($param_data['default']) ? $param_data['default'] : ''
];
}
$form['row'][$row]['contact_' . $transport . '_' . $parameter] = $form_param;
if (isset($param_data['tooltip'])) {
//r($param_data);
$form['row'][$row]['contact_' . $transport . '_tooltip'] = [
'type' => 'html',
'fieldset' => 'body',
'html' => generate_tooltip_link(NULL, '&nbsp;<i class="'.$config['icon']['question'].'"></i>', escape_html($param_data['tooltip']))
];
}
$row++;
}
}
if (safe_count($data['parameters']['optional'])) {
$form['row'][$row]['contact_' . $transport . '_optional'] = [
'type' => 'html',
'fieldset' => 'body',
'html' => '<h3 id="contact_' . $transport . '_optional">Optional parameters</h3>'
];
$row++;
foreach ($data['parameters']['optional'] as $parameter => $param_data) {
switch($param_data['type']) {
case 'enum-freeinput':
$form_param = [
'type' => 'tags',
'fieldset' => 'body',
'name' => $param_data['description'],
'width' => '270px',// '100%',
//'value' => isset($param_data['default']) ? $param_data['default'] : '',
'value' => isset($param_data['default']) ? $param_data['default'] : '',
'values' => $param_data['params']
];
break;
case 'bool':
case 'boolean':
// Boolean type is just select with true/false string
if (!isset($param_data['params'])) {
$param_data['params'] = ['' => 'Unset', 'true' => 'True', 'false' => 'False' ];
}
// do not break here
case 'enum':
$form_param = [
'type' => 'select',
'fieldset' => 'body',
'name' => $param_data['description'],
'width' => '270px', //'100%',
'value' => isset($param_data['default']) ? $param_data['default'] : '',
'values' => $param_data['params']
];
break;
case 'textarea':
$form_param = [
'type' => 'textarea',
'fieldset' => 'body',
'name' => $param_data['description'],
'width' => '270px',
'rows' => 5,
'value' => isset($param_data['default']) ? $param_data['default'] : ''
];
// Prettify JSON
if (isset($param_data['format']) && $param_data['format'] === 'json' &&
$json = safe_json_decode($form_param['value'])) {
$form_param['value'] = safe_json_encode($json, JSON_PRETTY_PRINT);
}
break;
default:
$form_param = [
'type' => 'text',
'fieldset' => 'body',
'name' => $param_data['description'],
'class' => 'input-xlarge',
'value' => isset($param_data['default']) ? $param_data['default'] : ''
];
}
$form['row'][$row]['contact_' . $transport . '_' . $parameter] = $form_param;
if (isset($param_data['tooltip'])) {
$form['row'][$row]['contact_' . $transport . '_tooltip'] = [
'type' => 'html',
'fieldset' => 'body',
'html' => generate_tooltip_link(NULL, '&nbsp;<i class="'.$config['icon']['question'].'"></i>', $param_data['tooltip'])
];
}
$row++;
}
}
// Custom notification templates if allowed for transport
// if (isset($data['notification']['message_template'])) {
// $form['row'][$row]['contact_' . $transport . '_notification'] = array(
// 'type' => 'html',
// 'fieldset' => 'body',
// 'html' => '<h3 id="contact_' . $transport . '_optional">Notification parameters</h3>');
// $row++;
//
// $form_param = [
// 'type' => 'toggle',
// 'view' => 'toggle',
// 'size' => 'large',
// 'palette' => 'blue',
// 'fieldset' => 'body',
// 'name' => 'Use custom template',
// 'onchange' => "toggleAttrib('disabled', 'contact_" . $transport . "_message_template')",
// 'value' => 'off'
// ];
// $form['row'][$row]['contact_' . $transport . '_custom_template'] = $form_param;
// $row++;
//
// $form['row'][$row++]['contact_' . $transport . '_doc_mustache'] = array(
// 'type' => 'html',
// 'fieldset' => 'body',
// 'offset' => TRUE,
// 'html' => 'See <a href="https://mustache.github.com/mustache.5.html" target="_blank">Mustache templates syntax</a>');
//
// $template = get_template('notification', $data['notification']['message_template']);
// // Remove header comment(s)
// $template = preg_replace('!^\s*/\*[\*\s]+Observium\s.*?\*/\s!is', '', $template);
// $form_param = [
// 'type' => 'textarea',
// 'fieldset' => 'body',
// 'disabled' => TRUE,
// 'name' => 'Message template',
// 'class' => 'input-xlarge',
// 'rows' => 6,
// 'value' => $template
// ];
// $form['row'][$row]['contact_' . $transport . '_message_template'] = $form_param;
// $row++;
// }
}
$form['row'][$row]['close'] = [
'type' => 'submit',
'fieldset' => 'footer',
'div_class' => '', // Clean default form-action class!
'name' => 'Close',
'icon' => '',
'attribs' => [ 'data-dismiss' => 'modal',
'aria-hidden' => 'true' ]
];
$form['row'][$row]['action'] = [
'type' => 'submit',
'fieldset' => 'footer',
'div_class' => '', // Clean default form-action class!
'name' => 'Add Contact',
'icon' => 'icon-ok icon-white',
//'right' => TRUE,
'class' => 'btn-primary',
'value' => 'add_contact'
];
echo generate_form_modal($form);
unset($form, $form_params);
$script = '
$("#contact_method").change(function() {
var select = this.value;
';
// Generate javascript function which hides all configuration part panels except the ones for the currently chosen transport
// Alternative would be to hide them all, then unhide the one selected. Hmm...
$count = 0;
foreach (array_keys($config['transports']) as $transport) {
if ($count == 0) {
$script .= " if (select === '" . $transport . "') {" . PHP_EOL;
} else {
$script .= PHP_EOL . " } else if (select === '" . $transport . "') {" . PHP_EOL;
}
$script .= " \$('div[id^=\"contact_${transport}_\"]').show();" . PHP_EOL . " ";
foreach (array_keys($config['transports']) as $ltransport) {
if ($transport != $ltransport) {
$script .= " \$('div[id^=\"contact_${ltransport}_\"]').hide();";
}
}
$count++;
}
$script .= ' }
}).change();';
register_html_resource('script', $script);
// End add contact
// Begin Actions
$readonly = $_SESSION['userlevel'] < 10; // Currently, edit allowed only for Admins
if (!$readonly && isset($vars['action'])) {
switch ($vars['action']) {
case 'add_contact':
// Only proceed if the contact_method is valid in our transports array
if (is_array($config['transports'][$vars['contact_method']])) {
foreach ($config['transports'][$vars['contact_method']]['parameters'] as $section => $parameters) {
foreach ($parameters as $parameter => $param_data) {
if (isset($vars['contact_' . $vars['contact_method'] . '_' . $parameter])) {
$value = smart_quotes($vars['contact_' . $vars['contact_method'] . '_' . $parameter]);
// Validate if passed correct JSON
if ($param_data['format'] === 'json') {
safe_json_decode($value);
if (json_last_error() !== JSON_ERROR_NONE) {
// Incorrect JSON
print_error('Contact not added. Incorrect JSON.');
break 2;
}
}
$endpoint_data[$parameter] = $value;
}
}
}
if ($endpoint_data) {
dbInsert('alert_contacts', [ 'contact_descr' => $vars['contact_descr'], 'contact_endpoint' => safe_json_encode($endpoint_data), 'contact_method' => $vars['contact_method'] ]);
}
}
break;
case 'edit_contact':
case 'update_contact':
$update_state = array();
$contact = get_contact_by_id($vars['contact_id']);
foreach (safe_json_decode($contact['contact_endpoint']) as $field => $value) {
$contact['endpoint_parameters'][$field] = $value;
}
$update_state['contact_disabled'] = get_var_true($vars['contact_enabled']) ? 0 : 1;
if (!safe_empty($vars['contact_descr']) && $vars['contact_descr'] != $contact['contact_descr']) {
$update_state['contact_descr'] = $vars['contact_descr'];
}
$data = $config['transports'][$contact['contact_method']];
if (!safe_count($data['parameters']['global'])) {
// Temporary until we separate "global" out.
$data['parameters']['global'] = [];
}
if (!safe_count($data['parameters']['optional'])) {
$data['parameters']['optional'] = [];
}
// Plan: add defaults for transport types to global settings, which we use by default, then be able to override the settings via this GUI
// This needs supporting code in the transport to check for set variable and if not, use the global default
$update_endpoint = $contact['endpoint_parameters'];
foreach (array_merge((array)$data['parameters']['required'],
(array)$data['parameters']['global'],
(array)$data['parameters']['optional']) as $parameter => $param_data) {
if ((isset($data['parameters']['optional'][$parameter]) || // Allow optional param as empty
is_array($vars['contact_endpoint_'.$parameter]) || strlen($vars['contact_endpoint_'.$parameter])) &&
smart_quotes($vars['contact_endpoint_'.$parameter]) != $contact['endpoint_parameters'][$parameter]) {
$value = smart_quotes($vars['contact_endpoint_'.$parameter]);
// Validate if passed correct JSON
if ($param_data['format'] === 'json') {
//r($value);
//r($param_data);
safe_json_decode($value);
if (json_last_error() !== JSON_ERROR_NONE) {
// Incorrect JSON
print_error('Contact not updated. Incorrect JSON.');
break 2;
}
}
$update_endpoint[$parameter] = $value;
}
}
//r($update_endpoint);
$update_endpoint = safe_json_encode($update_endpoint);
if ($update_endpoint != $contact['contact_endpoint']) {
//r($update_endpoint);
//r($contact['contact_endpoint']);
$update_state['contact_endpoint'] = $update_endpoint;
}
// custom template
$vars['contact_message_custom'] = get_var_true($vars['contact_message_custom']);
if ($vars['contact_message_custom'] != (bool)$contact['contact_message_custom']) {
$update_state['contact_message_custom'] = $vars['contact_message_custom'] ? '1' : '0';
}
if ($vars['contact_message_custom'] && $vars['contact_message_template'] != $contact['contact_message_template']) {
$update_state['contact_message_template'] = $vars['contact_message_template'];
}
//r($contact);
//r($vars);
$rows_updated = dbUpdate($update_state, 'alert_contacts', 'contact_id = ?', [ $vars['contact_id'] ]);
break;
case 'delete_contact':
if (get_var_true($vars['confirm_'.$vars['contact_id']], 'confirm')) {
$rows_deleted = dbDelete('alert_contacts', '`contact_id` = ?', [ $vars['contact_id'] ]);
$rows_deleted += dbDelete('alert_contacts_assoc', '`contact_id` = ?', [ $vars['contact_id'] ]);
if ($rows_deleted) {
print_success('Deleted contact and all associations ('.$vars['contact_id'].')');
}
}
unset($vars['contact_id']);
break;
}
}
// End Actions
// EOF

View File

@ -0,0 +1,364 @@
<?php
$blank = '{}';
dbInsert(array('dash_id' => '1', 'dash_name' => 'Default Dashboard'), 'dashboards');
$y = 0;
// Migrate an existing front page arrangement if it exists. Remove this after next CE.
if (!isset($config['frontpage']['order']) || FALSE)
{
$height = round((100 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1', 'widget_type' => 'welcome', 'widget_config' => $blank, 'x' => '6', 'y' => $y, 'width' => '12', 'height' => $height ), 'dash_widgets');
$y += $height;
$height = round(240 / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'map',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '6',
'height' => $height), 'dash_widgets'
);
dbInsert(array('dash_id' => '1',
'widget_type' => 'status_summary',
'widget_config' => $blank,
'x' => '6',
'y' => $y,
'width' => '6',
'height' => $height), 'dash_widgets'
);
$y += $height;
$height = ceil((90 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'alert_boxes',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
$height = ceil((280 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'eventlog',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '6',
'height' => $height), 'dash_widgets'
);
dbInsert(array('dash_id' => '1',
'widget_type' => 'alertlog',
'widget_config' => $blank,
'x' => '6',
'y' => $y,
'width' => '6',
'height' => $height), 'dash_widgets'
);
$y += $height;
}
else
{
$height = ceil((80 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'welcome',
'widget_config' => json_encode(array('converted' => TRUE)),
'x' => '6',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$x = 0;
$y += $height;
foreach ($config['frontpage']['order'] AS $entry)
{
switch ($entry)
{
case "map":
$height = ceil((250 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'map',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "portpercent":
$height = ceil((240 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'port_percent',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "status_summary":
$height = ceil((140 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'status_summary',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "alert_table":
$height = ceil((240 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'alert_table',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "device_status_boxes":
$height = ceil((90 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'old_status_boxes',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "eventlog":
$height = ceil((240 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'eventlog',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "syslog":
$height = ceil((240 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'syslog',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "device_status":
$height = ceil((240 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'old_status_table',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '12',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "splitlog":
$height = ceil((240 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
dbInsert(array('dash_id' => '1',
'widget_type' => 'syslog',
'widget_config' => $blank,
'x' => '0',
'y' => $y,
'width' => '6',
'height' => $height), 'dash_widgets'
);
dbInsert(array('dash_id' => '1',
'widget_type' => 'eventlog',
'widget_config' => $blank,
'x' => '6',
'y' => $y,
'width' => '6',
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "overall_traffic":
//$peering_count = dbFetchCell("SELECT COUNT(port_id) FROM `ports` WHERE `port_descr_type` = 'peering'");
//$transit_count = dbFetchCell("SELECT COUNT(port_id) FROM `ports` WHERE `port_descr_type` = 'transit'");
$peering_exist = dbExist('ports', '`port_descr_type` = ?', array('peering'));
$transit_exist = dbExist('ports', '`port_descr_type` = ?', array('transit'));
$height = ceil((120 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
if ($transit_exist)
{
$graph_array = array('type' => 'global_bits', 'port_type' => 'transit', 'title' => 'Transit Traffic', 'separate' => 'yes');
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 6,
'height' => $height), 'dash_widgets'
);
$x += 6;
}
if ($peering_exist)
{
$graph_array = array('type' => 'global_bits', 'port_type' => 'peering', 'title' => 'Peering Traffic', 'separate' => 'yes');
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 6,
'height' => $height), 'dash_widgets'
);
$x += 6;
}
$y +=$height;
$height = ceil((160 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
$graph_array = array('type' => 'global_bits_types', 'type_a' => 'transit', 'type_b' => 'peering', 'from' => '-1m', 'title' => 'Monthly Transit and Peering Traffic');
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 12,
'height' => $height), 'dash_widgets'
);
$x = 0;
$y += $height;
break;
case "custom_traffic":
if (isset($config['frontpage']['custom_traffic']['title'])) { $title = $config['frontpage']['custom_traffic']['title']; } else { $title = "Custom Traffic"; }
$height = ceil((120 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
$graph_array = array('type' => 'multi-port_bits', 'id' => $config['frontpage']['custom_traffic']['ids'], 'from' => '-1d', 'title' => $title . ' Today');
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 6,
'height' => $height), 'dash_widgets'
);
$x += 6;
$graph_array = array('type' => 'multi-port_bits', 'id' => $config['frontpage']['custom_traffic']['ids'], 'from' => '-7d', 'title' => $title . ' This Week');
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 6,
'height' => $height), 'dash_widgets'
);
$y += $height;
$x = 0;
$graph_array = array('type' => 'multi-port_bits', 'id' => $config['frontpage']['custom_traffic']['ids'], 'from' => '-1m', 'title' => $title . ' This Month');
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 12,
'height' => $height), 'dash_widgets'
);
$y += $height;
break;
case "micrographs":
$height = ceil((40 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
foreach ($config['frontpage']['micrographs'] as $row)
{
foreach (explode(';', $row['ids']) as $graph)
{
if (!$graph)
{
continue;
}
list($device, $type, $header) = explode(',', $graph, 3);
$graph_array = array('type' => $type, 'id' => $device, 'title' => $header);
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => 2,
'height' => $height), 'dash_widgets'
);
$x += 2;
}
$y += $height;
$x = 0;
}
break;
case "minigraphs":
$height = ceil((100 + $grid_v_margin) / ($grid_cell_height + $grid_v_margin));
$width = 3;
foreach (explode(';', $config['frontpage']['minigraphs']['ids']) as $graph)
{
if (!$graph)
{
continue;
}
if($x+$width > 12) { $x = 0; $y += $height; }
list($id, $type, $header) = explode(',', $graph, 3);
$id = str_replace("%2C", ",", $id); // Replace the HTML code for comma with a comma.
$graph_array = array('type' => $type, 'id' => $id, 'title' => $header);
$widget_id = dbInsert(array('dash_id' => '1',
'widget_config' => json_encode($graph_array),
'widget_type' => 'graph',
'x' => $x,
'y' => $y,
'width' => $width,
'height' => $height), 'dash_widgets'
);
$x += 3;
}
$y += $height;
$x = 0;
break;
}
}
}

View File

@ -0,0 +1,158 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function build_cbqos_query($vars)
{
$sql = 'SELECT * FROM `ports_cbqos`';
//if ($vars['sort'] == 'hostname' || $vars['sort'] == 'device' || $vars['sort'] == 'device_id') {
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
//}
$sql .= ' LEFT JOIN `ports` USING (`port_id`)';
// Rewrite `device_id` to use `ports_cbqos` table name to avoid dupe field error.
$sql .= ' WHERE 1' . str_replace('`device_id`', '`ports_cbqos`.`device_id`', generate_query_permitted(array('device')));
// Build query
foreach ($vars as $var => $value) {
switch ($var) {
case "policy_name":
case "object_name":
$sql .= generate_query_values($value, $var);
break;
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'cbqos_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'ports_cbqos.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'ports_cbqos.device_id');
break;
}
}
switch ($vars['sort_order']) {
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch ($vars['sort']) {
case 'policy_name':
case 'object_name':
case 'PrePolicyByte_rate':
case 'PostPolicyByte_rate':
case 'DropByte_rate':
$sql .= ' ORDER BY '.$vars['sort'].' ' . $sort_order;
break;
default:
$sql .= ' ORDER BY `hostname` ' . $sort_order . ', `port_label_short` '. $sort_order;
}
return $sql;
}
function print_cbqos_table_header($vars)
{
echo('<table class="' . (get_var_true($vars['graphs']) ? OBS_CLASS_TABLE_STRIPED_TWO : OBS_CLASS_TABLE_STRIPED) . '">');
$cols[] = array('', 'class="state-marker"');
if(!isset($vars['device_id'])) { $cols['hostname'] = array('Device', 'style="width: 200px;"'); }
if(!isset($vars['device_id'])) { $cols['port_label'] = array('Port', 'style="width: 200px;"'); }
$cols['policy_name'] = array('Policy', 'style="width: 150px;"');
$cols['object_name'] = array('Object', 'style="width: 200px;"');
$cols['PrePolicyByte_rate'] = array('Traffic');
$cols['DropByte_rate'] = array('Dropped');
$cols[] = array();
echo get_table_header($cols, $vars);
echo '<tbody>' . PHP_EOL;
}
function print_cbqos_table($vars) {
global $config;
$sql = build_cbqos_query($vars);
$entries = dbFetchRows($sql);
if (!safe_empty($entries)) {
echo generate_box_open();
print_cbqos_table_header($vars);
foreach ($entries as $cbqos_id => $entry) {
$perc_drop = float_div($entry['DropByte_rate'], $entry['PrePolicyByte_rate']) * 100;
echo '<tr>';
echo '<td class="state-marker"></td>';
echo '<td class="entity">'.generate_device_link($entry).'</td>';
echo '<td class="entity">'.generate_port_link($entry).'</td>';
echo '<td class="entity"><a href="'.generate_url(array('page' => 'device', 'device' => $entry['device_id'], 'tab' => 'port', 'port' => $entry['port_id'], 'view' => 'cbqos')).'">'.$entry['policy_name'].'</a></td>';
echo '<td class="entity"><a href="'.generate_url(array('page' => 'device', 'device' => $entry['device_id'], 'tab' => 'port', 'port' => $entry['port_id'], 'view' => 'cbqos')).'">'.$entry['object_name'].'</a></td>';
echo '<td>'.format_number($entry['PrePolicyByte_rate']).'bps / '.format_number($entry['PostPolicyByte_rate']).'bps</td>';
echo '<td>'.format_number($entry['DropByte_rate']).'bps ('.$perc_drop.'%)</td>';
echo '<td></td>';
echo '</tr>';
if (get_var_true($vars['graphs'])) {
$vars['graph'] = "graph";
}
if ($vars['graph']) {
$graph_array = array();
$graph_title = $entry['oid_descr'];
$graph_array['type'] = "cbqos_".$vars['graph'];
$graph_array['id'] = $entry['cbqos_id'];
echo '<tr>';
echo ' <td class="state-marker"></td>';
echo ' <td colspan=8>';
print_graph_row($graph_array);
echo ' </td>';
echo '</tr>';
}
}
echo ' </table>' . PHP_EOL;
echo generate_box_close();
}
}
// EOF

View File

@ -0,0 +1,681 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
/**
* Humanize counter.
*
* Returns a the $counter array with processed information:
* counter_state (TRUE: state counter, FALSE: normal counter)
* human_value, counter_symbol, state_name, state_event, state_class
*
* @param array $counter
* @return array $counter
*
*/
// TESTME needs unit testing
function humanize_counter(&$counter)
{
global $config;
// Exit if already humanized
if ($counter['humanized']) { return; }
$counter['counter_symbol'] = $GLOBALS['config']['counter_types'][$counter['counter_class']]['symbol'];
$counter['counter_format'] = strval($GLOBALS['config']['counter_types'][$counter['counter_class']]['format']);
$counter['state_class'] = ''; //'text-success';
// Generate "pretty" thresholds
$have_limit = FALSE;
if (is_numeric($counter['counter_limit_low']))
{
$counter_limit_low = format_value($counter['counter_limit_low'], $counter['counter_format']) . $counter['counter_symbol'];
$have_limit = TRUE;
} else {
$counter_limit_low = "&infin;";
}
if (is_numeric($counter['counter_limit_low_warn']))
{
$counter_warn_low = format_value($counter['counter_limit_low_warn'], $counter['counter_format']) . $counter['counter_symbol'];
$have_limit = TRUE;
} else {
$counter_warn_low = NULL;
}
if ($counter_warn_low) { $counter_limit_low = $counter_limit_low . " (".$counter_warn_low.")"; }
if (is_numeric($counter['counter_limit']))
{
$counter_limit_high = format_value($counter['counter_limit'], $counter['counter_format']) . $counter['counter_symbol'];
$have_limit = TRUE;
} else {
$counter_limit_high = "&infin;";
}
if (is_numeric($counter['counter_limit_warn']))
{
$counter_warn_high = format_value($counter['counter_limit_warn'], $counter['counter_format']) . $counter['counter_symbol'];
$have_limit = TRUE;
} else {
$counter_warn_high = "&infin;";
}
if ($counter_warn_high) { $counter_limit_high = "(".$counter_warn_high.") " . $counter_limit_high; }
switch ($counter['counter_limit_by'])
{
case 'sec':
$limit_by = 'Rate /sec';
break;
case 'min':
$limit_by = 'Rate /min';
break;
case '5min':
$limit_by = 'Rate /5min';
break;
case 'hour':
$limit_by = 'Rate /hour';
break;
case 'value':
$limit_by = 'Value';
break;
}
$counter['counter_thresholds'] = $have_limit ? "$limit_by: $counter_limit_low - $counter_limit_high" : '&infin;';
// generate pretty value / rate
foreach (['value', 'rate', 'rate_5min', 'rate_hour'] as $param)
{
if (!is_numeric($counter['counter_'.$param]))
{
//$counter['human_'.$param] = 'NaN';
if ($param == 'value')
{
$counter['counter_symbol'] = '';
$counter['human_'.$param] = 'NaN';
} else {
// Rates
$counter['human_'.$param] = '-';
}
} else {
// Rate can be negative (ie lifetime always grow down)
if ($counter['counter_'.$param] < 0)
{
$counter['human_' . $param] = '-' . format_value(abs($counter['counter_' . $param]), $counter['counter_format']);
} else {
$counter['human_' . $param] = format_value($counter['counter_' . $param], $counter['counter_format']);
}
}
}
if (isset($config['entity_events'][$counter['counter_event']]))
{
$counter = array_merge($counter, $config['entity_events'][$counter['counter_event']]);
} else {
$counter['event_class'] = 'label label-primary';
$counter['row_class'] = '';
}
//r($counter);
if ($counter['counter_deleted'])
{
$counter['row_class'] = 'disabled';
}
$device = &$GLOBALS['cache']['devices']['id'][$counter['device_id']];
if ((isset($device['status']) && !$device['status']) || (isset($device['disabled']) && $device['disabled']))
{
$counter['row_class'] = 'error';
}
// Set humanized entry in the array so we can tell later
$counter['humanized'] = TRUE;
}
function build_counter_query($vars, $query_count = FALSE)
{
if ($query_count)
{
$sql = "SELECT COUNT(*) FROM `counters`";
} else {
$sql = "SELECT * FROM `counters`";
if ($vars['sort'] == 'hostname' || $vars['sort'] == 'device' || $vars['sort'] == 'device_id')
{
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
}
}
$sql .= " WHERE `counter_deleted` = 0";
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'counters.counter_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'counters.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'counters.device_id');
break;
case "id":
case "counter_id":
$sql .= generate_query_values($value, 'counters.counter_id');
break;
case "entity_id":
$sql .= generate_query_values($value, 'counters.measured_entity');
break;
case "entity_type":
$sql .= generate_query_values($value, 'counters.measured_class');
break;
case 'entity_state':
case "measured_state":
$sql .= build_entity_measured_where('counter', ['measured_state' => $value]);
break;
case 'class':
case "counter_class":
$sql .= generate_query_values($value, 'counter_class');
break;
case "descr":
case "counter_descr":
$sql .= generate_query_values($value, 'counters.counter_descr', '%LIKE%');
break;
case "event":
case "counter_event":
$sql .= generate_query_values($value, 'counter_event');
break;
}
}
// $sql .= $GLOBALS['cache']['where']['devices_permitted'];
$sql .= generate_query_permitted(array('device', 'counter'));
// If need count, just return sql without sorting
if ($query_count)
{
return $sql;
}
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch($vars['sort'])
{
case 'device':
$sql .= ' ORDER BY `hostname` '.$sort_order;
break;
case 'descr':
case 'event':
$sql .= ' ORDER BY `counter_'.$vars['sort'].'` '.$sort_order;
break;
case 'value':
case 'rate':
case 'rate_hour':
case 'last_change':
$sql .= ' ORDER BY `counter_'.$vars['sort'].'` '.$sort_order;
break;
default:
// $sql .= ' ORDER BY `hostname` '.$sort_order.', `counter_descr` '.$sort_order;
}
if (isset($vars['pageno']))
{
$start = $vars['pagesize'] * ($vars['pageno'] - 1);
$sql .= ' LIMIT '.$start.','.$vars['pagesize'];
}
return $sql;
}
function print_counter_table($vars)
{
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$sql = build_counter_query($vars);
//r($vars);
//r($sql);
$counters = array();
//foreach(dbFetchRows($sql, NULL, TRUE) as $counter)
foreach(dbFetchRows($sql) as $counter)
{
//if (isset($GLOBALS['cache']['devices']['id'][$counter['device_id']]))
//{
$counter['hostname'] = $GLOBALS['cache']['devices']['id'][$counter['device_id']]['hostname'];
$counters[] = $counter;
//}
}
//$counters_count = count($counters); // This is count incorrect, when pagination used!
//$counters_count = dbFetchCell(build_counter_query($vars, TRUE), NULL, TRUE);
$counters_count = dbFetchCell(build_counter_query($vars, TRUE));
// Pagination
$pagination_html = pagination($vars, $counters_count);
echo $pagination_html;
echo generate_box_open();
print_counter_table_header($vars);
foreach($counters as $counter)
{
print_counter_row($counter, $vars);
}
echo("</tbody></table>");
echo generate_box_close();
echo $pagination_html;
}
function print_counter_table_header($vars)
{
if ($vars['view'] == "graphs" || $vars['graph'] || isset($vars['id']))
{
$stripe_class = "table-striped-two";
} else {
$stripe_class = "table-striped";
}
echo('<table class="table ' . $stripe_class . ' table-condensed ">' . PHP_EOL);
$cols = [];
$cols[] = array(NULL, 'class="state-marker"');
$cols['device'] = array('Device', 'style="width: 250px;"');
//$cols[] = array(NULL, 'class="no-width"'); // Measure entity link
$cols['descr'] = array('Description');
$cols['class'] = array('Class', 'style="width: 100px;"');
$cols['mib'] = array('MIB::Object');
//$cols[] = array('Thresholds', 'style="width: 100px;"');
$cols[] = array('History', 'style="text-align: right;"');
$cols['last_change'] = array('Last&nbsp;changed', 'style="width: 80px;"');
$cols['event'] = array('Event', 'style="width: 60px; text-align: right;"');
$cols['rate'] = array('Rate', 'style="width: 80px; text-align: right;"');
$cols['value'] = array('Value', 'style="width: 70px; text-align: right;"');
if ($vars['page'] == "device") { unset($cols['device']); }
if ($vars['page'] != "device" || $vars['tab'] == "overview") { unset($cols['mib']); unset($cols['object']); }
if (!$vars['show_class']) { unset($cols['class']); }
if ($vars['tab'] == "overview") { unset($cols[2]); } // Thresholds
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_counter_row($counter, $vars)
{
echo generate_counter_row($counter, $vars);
}
function generate_counter_row($counter, $vars)
{
global $config;
humanize_counter($counter);
$table_cols = 4;
if ($counter['counter_event'] && is_numeric($counter['counter_value']))
{
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $counter['counter_id'];
$graph_array['type'] = "counter_graph";
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
$mini_graph = generate_graph_tag($graph_array);
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $counter['counter_id'];
$graph_array['type'] = "counter_rate";
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
$mini_graph .= generate_graph_tag($graph_array);
} else {
// Do not show "Draw Error" minigraph
$mini_graph = '';
}
$row = '
<tr class="'.$counter['row_class'].'">
<td class="state-marker"></td>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE)
{
$row .= ' <td class="entity">' . generate_device_link($counter) . '</td>' . PHP_EOL;
$table_cols++;
}
// Measured link & icon
/* Disabled because it breaks the overview table layout
if ($vars['entity_icon']) // this used for entity popup
{
$row .= get_icon($config['counter_types'][$counter['counter_class']]['icon']);
}
elseif ($counter['measured_entity'] &&
(!isset($vars['measured_icon']) || $vars['measured_icon'])) // hide measured icon if not required
{
//$row .= generate_entity_link($counter['measured_class'], $counter['measured_entity'], get_icon($counter['measured_class']));
$row .= generate_entity_icon_link($counter['measured_class'], $counter['measured_entity']);
}
$row .= '</td>';
$table_cols++;
*/
$row .= ' <td class="entity">' . generate_entity_link("counter", $counter) . '</td>';
$table_cols++;
if ($vars['show_class'])
{
$row .= ' <td>' . nicecase($counter['counter_class']). '</td>' . PHP_EOL;
$table_cols++;
}
// FIXME -- Generify this. It's not just for counters.
if ($vars['page'] === "device" && $vars['tab'] !== "overview") {
$row .= ' <td>' . (!safe_empty($counter['counter_mib']) ? '<a href="'.OBSERVIUM_MIBS_URL.'/'.$counter['counter_mib'].'/" target="_blank">' . nicecase($counter['counter_mib']) .'</a>' : '') .
( ( !safe_empty($counter['counter_mib']) && !safe_empty($counter['counter_object'])) ? '::' : '') .
(!safe_empty($counter['counter_mib']) ? '<a href="'.OBSERVIUM_MIBS_URL.'/'.$counter['counter_mib'].'/#'.$counter['counter_object'].'" target="_blank">' . $counter['counter_object'] .'</a>' : '') .
'.'.$counter['counter_index'].'</td>' . PHP_EOL;
$table_cols++;
}
// Disable show thresholds
// if ($vars['tab'] != 'overview')
// {
// $row .= ' <td><span class="label ' . ($counter['counter_custom_limit'] ? 'label-warning' : '') . '">' . $counter['counter_thresholds'] . '</span></td>' . PHP_EOL;
// $table_cols++;
// }
$row .= ' <td style="width: 180px; text-align: right;">' . generate_entity_link('counter', $counter, $mini_graph, NULL, FALSE) . '</td>';
if ($vars['tab'] != 'overview')
{
$row .= ' <td style="white-space: nowrap">' . ($counter['counter_last_change'] == '0' ? 'Never' : generate_tooltip_link(NULL, format_uptime(($config['time']['now'] - $counter['counter_last_change']), 'short-2') . ' ago', format_unixtime($counter['counter_last_change']))) . '</td>';
$table_cols++;
$row .= ' <td style="text-align: right;"><strong>' . generate_tooltip_link('', $counter['counter_event'], $counter['event_descr'], $counter['event_class']) . '</strong></td>';
$table_cols++;
}
$counter_tooltip = $counter['event_descr'];
// Append value in alternative units to tooltip
if (isset($config['counter_types'][$counter['counter_class']]['alt_units']))
{
foreach (value_to_units($counter['counter_value'],
$config['counter_types'][$counter['counter_class']]['symbol'],
$counter['counter_class'],
$config['counter_types'][$counter['counter_class']]['alt_units']) as $unit => $unit_value)
{
if (is_numeric($unit_value)) { $counter_tooltip .= "<br />${unit_value}${unit}"; }
}
}
// Set to TRUE if this counter in time based format (ie lifetime)
$format_time = isset($config['counter_types'][$counter['counter_class']]['format']) &&
str_contains_array($config['counter_types'][$counter['counter_class']]['format'], 'time');
$rates = [];
// FIXME. Probably do not show rates for time based counters?.. (it's always around 1s/5m/1h)
if (!$format_time)
{
$rate_text = $format_time ? $counter['human_rate'] : $counter['human_rate'] . ' /s';
if ($counter['counter_limit_by'] == 'sec' && $counter['counter_event'] != 'ok')
{
$rates[] = ['event' => $counter['event_class'], 'text' => $rate_text];
} else {
$rates[] = ['event' => 'success', 'text' => $rate_text];
}
$rate_text = $format_time ? $counter['human_rate_5min'] : $counter['human_rate_5min'] . ' /5min';
if ($counter['counter_limit_by'] == '5min' && $counter['counter_event'] != 'ok')
{
$rates[] = ['event' => $counter['event_class'], 'text' => $rate_text];
} else {
$rates[] = ['event' => 'info', 'text' => $rate_text];
}
$rate_text = $format_time ? $counter['human_rate_hour'] : $counter['human_rate_hour'] . ' /h';
if ($counter['counter_limit_by'] == 'hour' && $counter['counter_event'] != 'ok')
{
$rates[] = ['event' => $counter['event_class'], 'text' => $rate_text];
} else {
$rates[] = ['event' => 'primary', 'text' => $rate_text];
}
}
$row .= ' <td style="width: 80px; text-align: right;">' . get_label_group($rates) . '</td>';
$row .= ' <td style="width: 70px; text-align: right;"><strong>' . generate_tooltip_link('', $counter['human_value'] . $counter['counter_symbol'], $counter_tooltip, $counter['event_class']) . '</strong></td>';
$row .= ' </tr>' . PHP_EOL;
if ($vars['view'] == "graphs" || $vars['id'] == $counter['counter_id']) { $vars['graph'] = "graph"; }
if ($vars['graph'])
{
$row .= '
<tr class="'.$counter['row_class'].'">
<td class="state-marker"></td>
<td colspan="'.$table_cols.'">';
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $counter['counter_id'];
$graph_array['type'] = 'counter_'.$vars['graph'];
$row .= generate_graph_row($graph_array, TRUE);
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $counter['counter_id'];
$graph_array['type'] = 'counter_rate';
$row .= generate_graph_row($graph_array, TRUE);
$row .= '</td></tr>';
} # endif graphs
return $row;
}
function print_counter_form($vars, $single_device = FALSE)
{
global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `counters`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
$counter_permitted = generate_query_permitted(array('device', 'counter'));
foreach ([ 'counter_class' => 'Counter Class', 'counter_event' => 'Counter Event' ] as $param => $param_name) {
$sql = 'SELECT DISTINCT `'.$param.'` FROM `counters` WHERE `counter_deleted` = ?' . $counter_permitted;
if ($entries = dbFetchColumn($sql, [ 0 ])) {
asort($entries);
}
foreach ($entries as $entry) {
if (safe_empty($entry)) { $entry = OBS_VAR_UNSET; }
if ($param === 'counter_class')
{
$name = nicecase($entry);
if (isset($config['counter_types'][$entry]['icon']))
{
$name = ['name' => $name, 'icon' => $config['counter_types'][$entry]['icon']];
} else {
$name = ['name' => $name, 'icon' => $config['icon']['counter']];
}
} else {
$name = $entry;
}
$form_items[$param][$entry] = $name;
}
// Alternative param name, ie event
$short_param = str_replace('counter_', '', $param);
if (!isset($vars[$param]) && isset($vars[$short_param]))
{
$vars[$param] = $vars[$short_param];
}
$form['row'][0][$param] = array(
'type' => 'multiselect',
'name' => $param_name,
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars[$param],
'values' => $form_items[$param]);
}
// Currently unused, just dumb space
$form['row'][0]['counter_value'] = array(
'type' => 'hidden',
'name' => 'Value',
'width' => '100%', //'180px',
'grid' => 0,
'value' => $vars['counter_value']);
// Measured entities
$form['row'][0]['measured_state'] = array(
'type' => 'multiselect',
'name' => 'Measured State',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['measured_state'],
'values' => ['none' => ['name' => 'Without Measure', 'icon' => $config['icon']['filter']],
'up' => ['name' => 'Measured UP', 'icon' => $config['icon']['up']],
'down' => ['name' => 'Measured DOWN', 'icon' => $config['icon']['down']],
'shutdown' => ['name' => 'Measured SHUTDOWN', 'icon' => $config['icon']['shutdown']]]);
$form['row'][1]['counter_descr'] = array(
'type' => 'text',
'placeholder' => 'Counter description',
'width' => '100%', //'180px',
'grid' => 6,
'value' => $vars['counter_descr']);
// $form['row'][1]['counter_type'] = array(
// 'type' => 'text',
// 'placeholder' => 'Counter type',
// 'width' => '100%', //'180px',
// 'grid' => 4,
// 'value' => $vars['status_descr']);
// Groups
foreach (get_type_groups('counter') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][1]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][1]['search'] = array(
'type' => 'submit',
'grid' => 4,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Counters',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['counter_class'] = $form['row'][0]['counter_class'];
$panel_form['row'][1]['counter_event'] = $form['row'][0]['counter_event'];
$panel_form['row'][1]['counter_value'] = $form['row'][0]['counter_value'];
$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
$panel_form['row'][2]['group'] = $form['row'][1]['group'];
//$panel_form['row'][3]['counter_type'] = $form['row'][1]['counter_type'];
$panel_form['row'][4]['counter_descr'] = $form['row'][1]['counter_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][1]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,801 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
/**
* Build devices where array
*
* This function returns an array of "WHERE" statements from a $vars array.
* The returned array can be implode()d and used on the devices table.
* Originally extracted from the /devices/ page
*
* @param array $vars
* @return array
*/
function build_devices_where_array($vars)
{
$where_array = array();
foreach ($vars as $var => $value)
{
if ($value != '')
{
switch ($var)
{
case 'group':
case 'group_id':
$values = get_group_entities($value);
$where_array[$var] = generate_query_values($values, 'device_id');
break;
case 'device':
case 'device_id':
$where_array[$var] = generate_query_values($value, 'device_id');
break;
case 'hostname':
case 'sysname':
case 'sysContact':
case 'sysDescr':
case 'serial':
case 'purpose':
$where_array[$var] = generate_query_values($value, $var, '%LIKE%');
break;
case 'location_text':
$where_array[$var] = generate_query_values($value, 'devices.location', '%LIKE%');
break;
case 'location':
$where_array[$var] = generate_query_values($value, 'devices.location');
break;
case 'location_lat':
case 'location_lon':
case 'location_country':
case 'location_state':
case 'location_county':
case 'location_city':
if ($GLOBALS['config']['geocoding']['enable'])
{
$where_array[$var] = generate_query_values($value, 'devices_locations.' . $var);
}
break;
case 'os':
case 'version':
case 'hardware':
case 'vendor':
case 'features':
case 'type':
case 'status':
case 'status_type':
case 'distro':
case 'ignore':
case 'disabled':
$where_array[$var] = generate_query_values($value, $var);
break;
case 'graph':
$where_array[$var] = generate_query_values(devices_with_graph($value), "devices.device_id");
}
}
}
return $where_array;
}
function devices_with_graph($graph)
{
$devices = array();
$sql = "SELECT `device_id` FROM `device_graphs` WHERE `graph` = ? AND `enabled` = '1'";
foreach(dbFetchRows($sql, array($graph)) AS $entry)
{
$devices[$entry['device_id']] = $entry['device_id'];
}
return $devices;
}
function build_devices_sort($vars)
{
$order = '';
$desc_order = isset($vars['sort_desc']) && $vars['sort_desc'];
switch ($vars['sort'])
{
case 'uptime':
case 'location':
case 'version':
case 'features':
case 'type':
case 'os':
case 'device_id':
$order = ' ORDER BY `devices`.`'.$vars['sort'].'`';
if ($desc_order)
{
$order .= " DESC";
}
break;
case 'domain':
// Special order hostnames in Domain Order
// SELECT `hostname`,
// SUBSTRING_INDEX(SUBSTRING_INDEX(`hostname`,'.',-3),'.',1) AS `leftmost`,
// SUBSTRING_INDEX(SUBSTRING_INDEX(`hostname`,'.',-2),'.',1) AS `middle`,
// SUBSTRING_INDEX(`hostname`,'.',-1) AS `rightmost`
// FROM `devices` ORDER by `middle`, `rightmost`, `leftmost`;
if ($desc_order)
{
$order = ' ORDER BY `middle` DESC, `rightmost` DESC, `leftmost` DESC';
} else {
$order = ' ORDER BY `middle`, `rightmost`, `leftmost`';
}
break;
default:
$order = ' ORDER BY `devices`.`hostname`';
if ($desc_order)
{
$order .= " DESC";
}
break;
}
return $order;
}
// DOCME needs phpdoc block
function print_device_header($device, $args = array()) {
global $config;
if (!is_array($device)) { print_error("Invalid device passed to print_device_header()!"); }
/* FIXME. Unused?
if ($device['status'] == '0') { $class = "div-alert"; } else { $class = "div-normal"; }
if ($device['ignore'] == '1')
{
$class = "div-ignore-alert";
if ($device['status'] == '1')
{
$class = "div-ignore";
}
}
if ($device['disabled'] == '1')
{
$class = "div-disabled";
}
$type = strtolower($device['os']);
*/
$div_class = 'box box-solid';
if (!safe_empty($args['div-class'])) {
$div_class .= " ${args['div-class']}";
}
echo '<div class="'.$div_class.'">
<table class=" table table-hover table-condensed '.$args['class'].'" style="margin-bottom: 10px; min-height: 70px; border-radius: 2px;">';
echo '
<tr class="'.$device['html_row_class'].' vertical-align">
<td class="state-marker"></td>
<td style="width: 70px; text-align: center;">'.get_device_icon($device).'</td>
<td><span style="font-size: 20px;">' . generate_device_link($device) . '</span>
<br /><a href="'.generate_location_url($device['location']).'">' . escape_html($device['location']) . '</a></td>
';
if (device_permitted($device) && !$args['no_graphs']) {
echo '<td>';
// Only show graphs for device_permitted(), don't show device graphs to users who can only see a single entity.
if (isset($config['os'][$device['os']]['graphs'])) {
$graphs = $config['os'][$device['os']]['graphs'];
} elseif (isset($device['os_group'], $config['os'][$device['os_group']]['graphs'])) {
$graphs = $config['os'][$device['os_group']]['graphs'];
} else {
// Default group
$graphs = $config['os_group']['default']['graphs'];
}
$graph_array = [];
$graph_array['height'] = "100";
$graph_array['width'] = "310";
$graph_array['to'] = $config['time']['now'];
$graph_array['device'] = $device['device_id'];
$graph_array['type'] = "device_bits";
$graph_array['from'] = $config['time']['day'];
$graph_array['legend'] = "no";
$graph_array['height'] = "45";
$graph_array['width'] = "150";
$graph_array['style'] = array('width: 150px !important'); // Fix for FF issue on HiDPI screen
$graph_array['bg'] = "FFFFFF00";
// Preprocess device graphs array
$graphs_enabled = [];
foreach ($device['graphs'] as $graph) {
$graphs_enabled[] = $graph['graph'];
}
foreach ($graphs as $entry) {
if ($entry && in_array(str_replace('device_', '', $entry), $graphs_enabled, TRUE)) {
$graph_array['type'] = $entry;
if (preg_match(OBS_PATTERN_GRAPH_TYPE, $entry, $graphtype)) {
$type = $graphtype['type'];
$subtype = $graphtype['subtype'];
$text = $config['graph_types'][$type][$subtype]['descr'];
} else {
$text = nicecase($entry); // Fallback to the type itself as a string, should not happen!
}
echo '<div class="pull-right" style="padding: 2px; margin: 0;">';
//echo generate_graph_tag($graph_array);
echo generate_graph_popup($graph_array);
echo '<div style="padding: 0px; font-weight: bold; font-size: 7pt; text-align: center;">'.$text.'</div>';
echo '</div>';
}
}
echo ' </td>';
} // Only show graphs for device_permitted()
echo('
</tr>
</table>
</div>');
}
function print_device_row($device, $vars = array('view' => 'basic'), $link_vars = array())
{
global $config, $cache;
if (!is_array($device)) { print_error("Invalid device passed to print_device_row()!"); }
if (!is_array($vars)) { $vars = array('view' => $vars); } // For compatibility
humanize_device($device);
$tags = array(
'html_row_class' => $device['html_row_class'],
'device_id' => $device['device_id'],
'device_link' => generate_device_link($device, NULL, $link_vars),
'device_url' => generate_device_url($device, $link_vars),
'hardware' => escape_html($device['hardware']),
'features' => escape_html($device['features']),
'os_text' => $device['os_text'],
'version' => escape_html($device['version']),
//'sysName' => escape_html($device['sysName']),
'device_uptime' => deviceUptime($device, 'short'),
'location' => escape_html(truncate($device['location'], 40, ''))
);
switch (strtolower($config['web_device_name'])) {
case 'sysname':
case 'purpose':
case 'descr':
case 'description':
$tags['sysName'] = escape_html($device['hostname']);
if (!safe_empty($device['sysName'])) {
$tags['sysName'] .= ' / ' . escape_html($device['sysName']);
}
break;
default:
$tags['sysName'] = escape_html($device['sysName']);
}
switch ($vars['view'])
{
case 'detail':
case 'details':
$table_cols = 7;
$tags['device_image'] = get_device_icon($device);
$tags['ports_count'] = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE `device_id` = ? AND `deleted` = ?", array($device['device_id'], 0));
//$tags['sensors_count'] = dbFetchCell("SELECT COUNT(*) FROM `sensors` WHERE `device_id` = ? AND `sensor_deleted` = ?", array($device['device_id'], 0));
//$tags['sensors_count'] += dbFetchCell("SELECT COUNT(*) FROM `status` WHERE `device_id` = ? AND `status_deleted` = ?", array($device['device_id'], 0));
$tags['sensors_count'] = $cache['sensors']['devices'][$device['device_id']]['count'];
$tags['sensors_count'] += $cache['statuses']['devices'][$device['device_id']]['count'];
$hostbox = '
<tr class="'.$tags['html_row_class'].'" onclick="openLink(\''.$tags['device_url'].'\')" style="cursor: pointer;">
<td class="state-marker"></td>
<td class="text-center vertical-align" style="width: 64px; text-align: center;">'.$tags['device_image'].'</td>
<td style="width: 300px;"><span class="entity-title">'.$tags['device_link'].'</span><br />'.$tags['location'].'</td>
<td class="text-nowrap" style="width: 55px;">';
if ($tags['ports_count'])
{
$hostbox .= '<i class="'.$config['icon']['port'].'"></i> <span class="label">'.$tags['ports_count'].'</span>';
}
$hostbox .= '<br />';
if ($tags['sensors_count'])
{
$hostbox .= '<i class="'.$config['icon']['sensor'].'"></i> ';
$sensor_items = [];
// Ok
if ($event_count = $cache['sensors']['devices'][$device['device_id']]['ok'] + $cache['statuses']['devices'][$device['device_id']]['ok'])
{
$sensor_items[] = ['event' => 'success', 'text' => $event_count];
}
// Warning
if ($event_count = $cache['sensors']['devices'][$device['device_id']]['warning'] + $cache['statuses']['devices'][$device['device_id']]['warning'])
{
$sensor_items[] = ['event' => 'warning', 'text' => $event_count];
}
// Alert
if ($event_count = $cache['sensors']['devices'][$device['device_id']]['alert'] + $cache['statuses']['devices'][$device['device_id']]['alert'])
{
$sensor_items[] = ['event' => 'danger', 'text' => $event_count];
}
// Ignored
if ($event_count = $cache['sensors']['devices'][$device['device_id']]['ignored'] + $cache['statuses']['devices'][$device['device_id']]['ignored'])
{
$sensor_items[] = ['event' => 'default', 'text' => $event_count];
}
$hostbox .= get_label_group($sensor_items);
//'<span class="label">'.$tags['sensors_count'].'</span>';
}
$hostbox .= '</td>
<td>'.$tags['os_text'].' '.$tags['version']. (!empty($tags['features']) ? ' ('.$tags['features'].')' : '').'<br />
'.$tags['hardware'].'</td>
<td>'.$tags['device_uptime'].'<br />'.$tags['sysName'].'</td>
</tr>';
break;
case 'perf':
if ($_SESSION['userlevel'] >= "10")
{
$tags['device_image'] = get_device_icon($device);
$graph_array = array(
'type' => 'device_poller_perf',
'device' => $device['device_id'],
'operation' => 'poll',
'legend' => 'no',
'width' => 600,
'height' => 90,
'from' => $config['time']['week'],
'to' => $config['time']['now'],
);
$hostbox = '
<tr class="'.$tags['html_row_class'].'" onclick="openLink(\''.generate_device_url($device, ['tab' => 'perf']).'\')" style="cursor: pointer;">
<td class="state-marker"></td>
<td class="vertical-align" style="width: 64px; text-align: center;">'.$tags['device_image'].'</td>
<td class="vertical-align" style="width: 300px;"><span class="entity-title">' . $tags['device_link'] . '</span><br />'.$tags['location'].'</td>
<td><div class="pull-right" style="height: 130px; padding: 2px; margin: 0;">' . generate_graph_tag($graph_array) . '</div></td>
</tr>';
}
break;
case 'status':
$tags['device_image'] = get_device_icon($device);
// Graphs
$graph_array = array();
$graph_array['height'] = "100";
$graph_array['width'] = "310";
$graph_array['to'] = $config['time']['now'];
$graph_array['device'] = $device['device_id'];
$graph_array['type'] = "device_bits";
$graph_array['from'] = $config['time']['day'];
$graph_array['legend'] = "no";
$graph_array['height'] = "45";
$graph_array['width'] = "175";
$graph_array['bg'] = "FFFFFF00";
if (isset($config['os'][$device['os']]['graphs']))
{
$graphs = $config['os'][$device['os']]['graphs'];
}
else if (isset($device['os_group']) && isset($config['os'][$device['os_group']]['graphs']))
{
$graphs = $config['os'][$device['os_group']]['graphs'];
} else {
// Default group
$graphs = $config['os_group']['default']['graphs'];
}
// Preprocess device graphs array
$graphs_enabled = [];
foreach ($GLOBALS['cache']['devices']['id'][$device['device_id']]['graphs'] as $graph)
{
$graphs_enabled[] = $graph['graph'];
}
foreach ($graphs as $entry)
{
list(,$graph_subtype) = explode("_", $entry, 2);
if ($entry && in_array(str_replace("device_", "", $entry), $graphs_enabled))
{
$graph_array['type'] = $entry;
if(isset($config['graph_types']['device'][$graph_subtype]))
{
$title = $config['graph_types']['device'][$graph_subtype]['descr'];
} else {
$title = nicecase(str_replace("_", " ", $graph_subtype));
}
$tags['graphs'][] = '<div class="pull-right" style="margin: 5px; margin-bottom: 0px;">'. generate_graph_popup($graph_array) .'<br /><div style="text-align: center; padding: 0px; font-size: 7pt; font-weight: bold;">'.$title.'</div></div>';
}
}
$hostbox = '
<tr class="'.$tags['html_row_class'].'" onclick="openLink(\''.$tags['device_url'].'\')" style="cursor: pointer;">
<td class="state-marker"></td>
<td class="vertical-align" style="width: 64px; text-align: center;">'.$tags['device_image'].'</td>
<td style="width: 300px;"><span class="entity-title">'.$tags['device_link'].'</span><br />'.$tags['location'].'</td>
<td>';
if ($tags['graphs'])
{
$hostbox .= '' . implode($tags['graphs']) . '';
}
$hostbox .= '</td>
</tr>';
break;
default: // basic
$table_cols = 6;
$tags['device_image'] = get_device_icon($device);
$tags['ports_count'] = dbFetchCell("SELECT COUNT(*) FROM `ports` WHERE `device_id` = ? AND `deleted` = 0;", array($device['device_id']));
$tags['sensors_count'] = dbFetchCell("SELECT COUNT(*) FROM `sensors` WHERE `device_id` = ?;", array($device['device_id']));
$tags['sensors_count'] += dbFetchCell("SELECT COUNT(*) FROM `status` WHERE `device_id` = ?;", array($device['device_id']));
$hostbox = '
<tr class="'.$tags['html_row_class'].'" onclick="openLink(\''.$tags['device_url'].'\')" style="cursor: pointer;">
<td class="state-marker"></td>
<td class="vertical-align" style="width: 64px; text-align: center;">'.$tags['device_image'].'</td>
<td style="width: 300;"><span class="entity-title">'.$tags['device_link'].'</span><br />'.$tags['location'].'</td>
<td>'.$tags['hardware'].' '.$tags['features'].'</td>
<td>'.$tags['os_text'].' '.$tags['version'].'</td>
<td>'.$tags['device_uptime'].'</td>
</tr>';
}
// If we're showing graphs, generate the graph
if ($vars['graph'])
{
$hostbox .= '<tr><td colspan="'.$table_cols.'">';
$graph_array['to'] = $config['time']['now'];
$graph_array['device'] = $device['device_id'];
$graph_array['type'] = 'device_'.$vars['graph'];
$hostbox .= generate_graph_row($graph_array);
$hostbox .= '</td></tr>';
}
echo($hostbox);
}
/**
* Returns icon tag (by default) or icon name for current device array
*
* @param array $device Array with device info (from DB)
* @param bool $base_icon Return complete img tag with icon (by default) or just base icon name
* @param bool $dark Prefer dark variant of icon (also set by session var)
*
* @return string Img tag with icon or base icon name
*/
function get_device_icon($device, $base_icon = FALSE, $dark = FALSE) {
global $config;
$icon = 'generic';
$device['os'] = strtolower($device['os']);
$model = $config['os'][$device['os']]['model'];
if (!safe_empty($device['icon']) && is_file($config['html_dir'] . '/images/os/' . $device['icon'] . '.png')) {
// Custom device icon from DB
$icon = $device['icon'];
} elseif ($model && isset($config['model'][$model][$device['sysObjectID']]['icon']) &&
is_file($config['html_dir'] . '/images/os/' . $config['model'][$model][$device['sysObjectID']]['icon'] . '.png')) {
// Per model icon
$icon = $config['model'][$model][$device['sysObjectID']]['icon'];
} elseif (isset($config['os'][$device['os']]['icon']) &&
is_file($config['html_dir'] . '/images/os/' . $config['os'][$device['os']]['icon'] . '.png')) {
// Icon defined in os definition
$icon = $config['os'][$device['os']]['icon'];
} else {
if ($device['distro']) {
// Icon by distro name
// Red Hat Enterprise -> redhat
$distro = strtolower(trim(str_replace([ ' Enterprise', 'Red Hat' ], [ '', 'redhat' ], $device['distro'])));
$distro = safename($distro);
if (is_file($config['html_dir'] . '/images/os/' . $distro . '.png')) {
$icon = $distro;
}
}
if ($icon === 'generic' && is_file($config['html_dir'] . '/images/os/' . $device['os'] . '.png')) {
// Icon by OS name
$icon = $device['os'];
}
}
// Icon by vendor name
if ($icon === 'generic' && ($config['os'][$device['os']]['vendor'] || $device['vendor']))
{
if ($device['vendor'])
{
$vendor = $device['vendor'];
} else {
$vendor = rewrite_vendor($config['os'][$device['os']]['vendor']); // Compatibility, if device not polled for long time
}
$vendor_safe = safename(strtolower($vendor));
if (isset($config['vendors'][$vendor_safe]['icon']))
{
$icon = $config['vendors'][$vendor_safe]['icon'];
}
elseif (is_file($config['html_dir'] . '/images/os/' . $vendor_safe . '.png'))
{
$icon = $vendor_safe;
}
elseif (isset($config['os'][$device['os']]['icons']))
{
// Fallback to os alternative icon
$icon = array_values($config['os'][$device['os']]['icons'])[0];
}
}
// Set dark mode by session
if (isset($_SESSION['theme']))
{
$dark = str_contains($_SESSION['theme'], 'dark');
}
// Prefer dark variant of icon in dark mode
if ($dark && is_file($config['html_dir'] . '/images/os/' . $icon . '-dark.png'))
{
$icon .= '-dark';
}
if ($base_icon)
{
// return base name for os icon
return $icon;
}
// return image html tag
$srcset = '';
// Now we always have 2x icon variant!
//if (is_file($config['html_dir'] . '/images/os/' . $icon . '_2x.png')) // HiDPI image exist?
//{
// Detect allowed screen ratio for current browser
$ua_info = detect_browser();
if ($ua_info['screen_ratio'] > 1)
{
$srcset = ' srcset="' .$config['base_url'] . '/images/os/' . $icon . '_2x.png'.' 2x"';
}
//}
// Image tag -- FIXME re-engineer this code to do this properly. This is messy.
return '<img src="' . $config['base_url'] . '/images/os/' . $icon . '.png"' . $srcset . ' alt="" />';
}
// TESTME needs unit testing
// DOCME needs phpdoc block
function generate_device_url($device, $vars = array())
{
return generate_url(array('page' => 'device', 'device' => $device['device_id']), $vars);
}
// TESTME needs unit testing
// DOCME needs phpdoc block
function generate_device_popup_header($device, $vars = []) {
humanize_device($device);
$device_name = device_name($device);
if ($device['hostname'] !== $device_name) {
$sysName = $device['hostname'];
if (!safe_empty($device['sysName'])) {
$sysName .= ' / ' . $device['sysName'];
}
} else {
$sysName = $device['sysName'];
}
return generate_box_open() . '
<table class="table table-striped table-rounded table-condensed">
<tr class="' . $device['html_row_class'] . '" style="font-size: 10pt;">
<td class="state-marker"></td>
<td class="vertical-align" style="width: 64px; text-align: center;">' . get_device_icon($device) . '</td>
<td width="200px"><a href="'.generate_device_url($device).'" class="' . device_link_class($device) . '" style="font-size: 15px; font-weight: bold;">' .
escape_html(device_name($device)) . '</a><br />' . escape_html(truncate($device['location'], 64, '')) . '</td>
<td>' . $device['os_text'] . ' ' . escape_html($device['version']) . ' <br /> ' .
($device['vendor'] ? escape_html($device['vendor']).' ' : '') . escape_html($device['hardware']) . '</td>
<td>' . deviceUptime($device, 'short') . '<br />' . escape_html($sysName) . '</td>
</tr>
</table>
' . generate_box_close();
}
// TESTME needs unit testing
// DOCME needs phpdoc block
function generate_device_popup($device, $vars = []) {
global $config;
$content = generate_device_popup_header($device, $vars);
if (isset($config['os'][$device['os']]['graphs'])) {
$graphs = $config['os'][$device['os']]['graphs'];
} elseif (isset($device['os_group'], $config['os'][$device['os_group']]['graphs'])) {
$graphs = $config['os'][$device['os_group']]['graphs'];
} else {
// Default group
$graphs = $config['os_group']['default']['graphs'];
}
// Preprocess device graphs array
$graphs_enabled = [];
foreach ($device['graphs'] as $graph) {
if ($graph['enabled'] != '0') {
$graphs_enabled[] = $graph['graph'];
}
}
foreach ($graphs as $entry) {
if ($entry && in_array(str_replace('device_', '', $entry), $graphs_enabled, TRUE)) {
// No text provided for the minigraph, fetch from array
if (preg_match(OBS_PATTERN_GRAPH_TYPE, $entry, $graphtype)) {
$type = $graphtype['type'];
$subtype = $graphtype['subtype'];
$text = $config['graph_types'][$type][$subtype]['descr'];
} else {
$text = nicecase($entry); // Fallback to the type itself as a string, should not happen!
}
// FIXME -- function!
$graph_array = array();
$graph_array['height'] = "100";
$graph_array['width'] = "290";
$graph_array['to'] = get_time();
$graph_array['device'] = $device['device_id'];
$graph_array['type'] = $entry;
$graph_array['from'] = get_time('day');
$graph_array['legend'] = "no";
$content .= '<div style="width: 730px; white-space: nowrap;">';
$content .= "<div class=entity-title><h4>" . $text . "</h4></div>";
/*
$content .= generate_box_open(array('title' => $text,
'body-style' => 'white-space: nowrap;'));
*/
$content .= generate_graph_tag($graph_array);
$graph_array['from'] = get_time('week');
$content .= generate_graph_tag($graph_array);
$content .= '</div>';
//$content .= generate_box_close();
}
}
//r($content);
return $content;
}
// TESTME needs unit testing
// DOCME needs phpdoc block
function generate_device_link($device, $text = NULL, $vars = array(), $escape = TRUE, $short = FALSE) {
if (is_array($device) && !($device['hostname'] && isset($device['status']))) {
// partial device array, get full
$device = device_by_id_cache($device['device_id']);
} elseif (is_numeric($device)) {
$device = device_by_id_cache($device);
}
if (!$device) {
return escape_html($text);
}
if (!device_permitted($device['device_id'])) {
$text = device_name($device, $short);
return $escape ? escape_html($text) : $text;
}
$class = device_link_class($device);
if (safe_empty($text)) {
$text = device_name($device, $short);
}
$url = generate_device_url($device, $vars);
if ($escape) {
$text = escape_html($text);
}
return '<a href="' . $url . '" class="entity-popup ' . $class . ' text-nowrap" data-eid="' . $device['device_id'] . '" data-etype="device">' . $text . '</a>';
}
// Simple wrapper to generate_device_link() for common usage with only device_name
function generate_device_link_short($device, $vars = [], $short = TRUE) {
// defaults - always short device name, escaped
return generate_device_link($device, NULL, $vars, TRUE, $short);
}
function device_name($device, $max_len = FALSE) {
global $config;
switch (strtolower($config['web_device_name'])) {
case 'sysname':
$name_field = 'sysName';
break;
case 'purpose':
case 'descr':
case 'description':
$name_field = 'purpose';
break;
default:
$name_field = 'hostname';
}
if ($max_len && !is_intnum($max_len)) {
$max_len = $config['short_hostname']['length'];
}
if ($name_field !== 'hostname' && !safe_empty($device[$name_field])) {
if ($name_field === 'sysName' && $max_len && $max_len > 3) {
// short sysname when is valid hostname (do not escape here)
return short_hostname($device[$name_field], $max_len, FALSE);
}
return $device[$name_field];
}
if ($max_len && $max_len > 3) {
// short hostname (do not escape here)
return short_hostname($device['hostname'], $max_len, FALSE);
}
return $device['hostname'];
}
function generate_device_form_values($form_filter = FALSE, $column = 'device_id', $options = array())
{
global $cache;
$form_items = array();
foreach ($cache['devices']['hostname'] as $hostname => $device_id)
{
if (is_array($form_filter) && !in_array($device_id, $form_filter)) { continue; } // Devices only with entries
if ($cache['devices']['id'][$device_id]['disabled'] === '1')
{
if (isset($options['disabled']))
{
// Force display disabled devices
if (!$options['disabled']) { continue; }
}
elseif ($cache['devices']['id'][$device_id]['disabled'] && !$GLOBALS['config']['web_show_disabled']) { continue; }
$form_items[$device_id]['group'] = 'DISABLED';
}
elseif ($cache['devices']['id'][$device_id]['status'] === '0')
{
if (isset($options['down']) && !$options['down']) { continue; } // Skip down
$form_items[$device_id]['group'] = 'DOWN';
} else {
if (isset($options['up']) && !$options['up']) { continue; } // Skip up
$form_items[$device_id]['group'] = 'UP';
}
$form_items[$device_id]['name'] = $hostname;
if (isset($cache['devices']['id'][$device_id]['row_class'][0]))
{
// Set background color for non empty row_class (disabled/down/ignored)
$form_items[$device_id]['class'] = 'bg-' . $cache['devices']['id'][$device_id]['row_class'];
}
}
return $form_items;
}
// EOF

View File

@ -0,0 +1,442 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage functions
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2022 Observium Limited
*
*/
// F5 TEMP STUFF
function print_f5_lb_virtual_table_header($vars)
{
if ($vars['view'] == "graphs")
{
$table_class = OBS_CLASS_TABLE_STRIPED_TWO;
} else {
$table_class = OBS_CLASS_TABLE_STRIPED;
}
echo('<table class="' . $table_class . '">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'device' => array('Device', 'style="width: 200px;"'),
'virt_name' => array('Virtual'),
array('', 'style="width: 100px;"'),
'virt_ip' => array('Address', 'style="width: 250px;"'),
'virt_type' => array('Type', 'style="width: 250px;"'),
'virt_state' => array('Status', 'style="width: 250px;"'),
);
if ($vars['page'] == "device")
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function get_customoid_by_id($oid_id) {
if (is_numeric($oid_id)) {
$oid = dbFetchRow('SELECT * FROM `oids` WHERE `oid_id` = ?', array($oid_id));
}
if (safe_count($oid)) {
return $oid;
}
return FALSE;
} // end function get_customoid_by_id()
function generate_entity_popup_graphs($entity, $vars)
{
global $config;
$entity_type = $vars['entity_type'];
if (is_array($config['entities'][$entity_type]['graph']))
{
if (isset($config['entities'][$entity_type]['graph']['type']))
{
$graphs[] = $config['entities'][$entity_type]['graph'];
} else {
$graphs = $config['entities'][$entity_type]['graph'];
}
foreach($graphs as $graph_array)
{
//$graph_array = $config['entities'][$entity_type]['graph'];
// We can draw a graph for this type/metric pair!
foreach($graph_array as $key => $val)
{
// Check to see if we need to do any substitution
if (substr($val, 0, 1) == "@")
{
$nval = substr($val, 1);
$graph_array[$key] = $entity[$nval];
}
}
$graph_array['height'] = "100";
$graph_array['width'] = "323";
$content = '<div style="white-space: nowrap;">';
$content .= "<div class=entity-title><h4>" . nicecase(str_replace("_", " ", $graph_array['type'])) . "</h4></div>";
/*
$content = generate_box_open(array('title' => nicecase(str_replace("_", " ", $graph_array['type'])),
'body-style' => 'white-space: nowrap;'));
*/
foreach(array('day', 'month') as $period)
{
$graph_array['from'] = $config['time'][$period];
$content .= generate_graph_tag($graph_array);
}
$content .= "</div>";
//$content .= generate_box_close();
}
//r($content);
return $content;
}
}
function generate_entity_popup_header($entity, $vars)
{
$translate = entity_type_translate_array($vars['entity_type']);
$vars['popup'] = TRUE;
$vars['entity_icon'] = TRUE;
$contents = '';
switch($vars['entity_type'])
{
case "sensor":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_sensor_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "toner":
case "printersupply":
case "supply":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_printersupplies_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "bgp_peer":
if ($entity['peer_device_id'])
{
$peer_dev = device_by_id_cache($entity['peer_device_id']);
$peer_name = '<br /><a class="entity" style="font-weight: bold;">'.$peer_dev['hostname'].'</a>';
}
else if ($entity['reverse_dns'])
{
$peer_name = '<br /><span style="font-weight: bold;">' . $entity['reverse_dns'] . '</span>';
}
$astext = '<span>AS'.$entity['human_remote_as'];
if ($entity['astext'])
{
$astext .= '<br />' . $entity['astext'] . '</span>';
}
$astext .= '</span>';
$contents .= generate_box_open();
$contents .= '
<table class="'. OBS_CLASS_TABLE .'">
<tr class="' . $entity['row_class'] . ' vertical-align" style="font-size: 10pt;">
<td class="state-marker"></td>
<td style="width: 10px;"></td>
<td style="width: 10px;"><i class="'.$translate['icon'].'"></i></td>
<td><a class="entity-popup" style="font-size: 15px; font-weight: bold;">'.escape_html($entity['entity_shortname']).'</a>'.$peer_name.'</td>
<td class="text-nowrap" style="width: 20%;">'.$astext.'</td>
<td></td>
</tr>
</table>';
$contents .= generate_box_close();
break;
case "sla":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_sla_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "processor":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_processor_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "mempool":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_mempool_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "p2pradio":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_p2pradio_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "status":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_status_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "counter":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_counter_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "storage":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_storage_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "netscalervsvr":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_netscalervsvr_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "netscalersvc":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_netscalersvc_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
case "netscalersvcgrpmem":
$contents .= generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">';
$contents .= generate_netscalersvcmem_row($entity, $vars);
$contents .= '</table>';
$contents .= generate_box_close();
break;
default:
entity_rewrite($vars['entity_type'], $entity);
$contents = generate_box_open(). '
<table class="' . OBS_CLASS_TABLE_STRIPED . '">
<tr class="' . $entity['row_class'] . '" style="font-size: 10pt;">
<td class="state-marker"></td>
<td style="width: 10px;"></td>
<td width="400"><i class="'.$translate['icon'].'" style="margin-right: 10px;"></i> <a class="entity-popup" style="font-size: 15px; font-weight: bold;">'.escape_html($entity['entity_name']).'</a></td>
<td width="100"></td>
<td></td>
</tr>
</table>'.generate_box_close();
}
return $contents;
}
function generate_entity_popup($entity, $vars)
{
if (is_numeric($entity)) { $entity = get_entity_by_id_cache($vars['entity_type'], $entity); }
$device = device_by_id_cache($entity['device_id']);
$content = generate_device_popup_header($device);
$content .= generate_entity_popup_header($entity, $vars);
$content .= generate_entity_popup_graphs($entity, $vars);
return $content;
}
function generate_entity_popup_multi($entities, $vars)
{
// Note here limited only to one entity_type and one device_id
$count = count($entities);
// First element
$entity = array_shift($entities);
if (is_numeric($entity))
{
$entity = get_entity_by_id_cache($vars['entity_type'], $entity);
}
$device = device_by_id_cache($entity['device_id']);
$header = generate_entity_popup_header($entity, $vars);
if ($count > 1)
{
// Multiple entities graph
/// FIXME. Need add multi-graphs
$graphs = generate_entity_popup_graphs($entity, $vars);// This is incorrect, only first graph
} else {
// Single entity graph
$graphs = generate_entity_popup_graphs($entity, $vars);
}
// All other elements
foreach ($entities as $entity)
{
if (is_numeric($entity))
{
$entity = get_entity_by_id_cache($vars['entity_type'], $entity);
}
if ($entity['device_id'] != $device['device_id'])
{
// Skip if passed entity from different device
continue;
}
$header .= generate_entity_popup_header($entity, $vars);
//$graphs .= generate_entity_popup_graphs($entity, $vars); // Currently disabled, need multi graph
}
$content = generate_device_popup_header($device);
$content .= $header;
$content .= $graphs;
return $content;
}
// Measured specific functions
function build_entity_measured_where($entity_type, $vars)
{
$entity_array = entity_type_translate_array($entity_type);
$column_measured_id = $entity_array['table_fields']['measured_id'];
$column_measured_type = $entity_array['table_fields']['measured_type'];
$measure_array = [];
// Build query
foreach($vars as $var => $value)
{
if (!is_array($value)) { $value = explode(',', $value); }
switch ($var)
{
case 'measured_group':
foreach (dbFetchColumn('SELECT DISTINCT `'.$column_measured_type.'` FROM `'.$entity_array['table'].'` WHERE `'.$entity_array['table_fields']['deleted'].'` = ?', [0]) as $measured_type)
{
if (!$measured_type) { continue; }
$entities = get_group_entities($value, $measured_type);
$measure_sql = '';
switch ($measured_type)
{
case 'port':
case 'printersupply':
$measure_sql = generate_query_values($measured_type, $column_measured_type, NULL, OBS_DB_NO_LEADING_AND);
$measure_sql .= generate_query_values($entities, $column_measured_id);
break;
}
if ($measure_sql) { $measure_array[] = $measure_sql; }
}
break;
case 'measured_state':
// UP / DOWN / STUTDOWN / NONE states
//$value = (array)$value;
// Select all without measured entities
if (in_array('none', $value)) {
$measure_array[] = generate_query_values(1, $column_measured_id, 'NULL', OBS_DB_NO_LEADING_AND);
$value = array_diff($value, [ 'none' ]);
}
if (count($value))
{
// Limit statuses with measured entities
foreach (dbFetchColumn('SELECT DISTINCT `'.$column_measured_type.'` FROM `'.$entity_array['table'].'` WHERE `'.$entity_array['table_fields']['deleted'].'` = ?', [0]) as $measured_type)
{
if (!$measured_type) { continue; }
$measure_sql = '';
$measure_entities = dbFetchColumn('SELECT DISTINCT `'.$column_measured_id.'` FROM `'.$entity_array['table'].'` WHERE `'.$column_measured_type.'` = ? AND `'.$entity_array['table_fields']['deleted'].'` = ?', [$measured_type, 0]);
switch ($measured_type)
{
case 'port':
$where_array = build_ports_where_array(['port_id' => $measure_entities, 'state' => $value]);
$entity_sql = 'SELECT `port_id` FROM `ports` WHERE 1 ';
$entity_sql .= implode('', $where_array);
$entities = dbFetchColumn($entity_sql);
//$entities = dbFetchColumn($entity_sql, NULL, TRUE);
//r($entities);
$measure_sql = generate_query_values($measured_type, $column_measured_type, NULL, OBS_DB_NO_LEADING_AND);
$measure_sql .= generate_query_values($entities, $column_measured_id);
break;
case 'printersupply':
break;
}
if ($measure_sql) { $measure_array[] = $measure_sql; }
}
}
break;
}
}
switch (count($measure_array))
{
case 0:
$sql = '';
break;
case 1:
$sql = ' AND ' . $measure_array[0];
break;
default:
$sql = ' AND (('.implode(') OR (', $measure_array).'))';
}
return $sql;
}
// EOF

View File

@ -0,0 +1,359 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function build_mempool_query($vars)
{
global $config, $cache;
$sql = 'SELECT *, `mempools`.`mempool_id` AS `mempool_id` FROM `mempools`';
//$sql .= ' LEFT JOIN `mempools-state` USING(`mempool_id`)';
if ($vars['sort'] === 'hostname' || $vars['sort'] === 'device' || $vars['sort'] === 'device_id') {
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
}
$sql .= ' WHERE 1' . generate_query_permitted(array('device'));
// Build query
foreach ($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'mempools.mempool_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'mempools.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'mempools.device_id');
break;
case "descr":
case "mempool_descr";
$sql .= generate_query_values($value, 'mempool_descr', '%LIKE%');
break;
}
}
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch($vars['sort'])
{
case 'usage':
$sql .= ' ORDER BY `mempool_used` '.$sort_neg;
break;
case 'used':
$sql .= ' ORDER BY `mempool_perc` '.$sort_neg;
break;
case 'hostname':
$sql .= ' ORDER BY `hostname` '.$sort_order.', `mempool_descr` '.$sort_order;
break;
case 'descr':
default:
$sql .= ' ORDER BY `mempool_descr` '.$sort_order;
break;
}
return $sql;
}
function print_mempool_table($vars)
{
global $cache;
$sql = build_mempool_query($vars);
$mempools = array();
foreach (dbFetchRows($sql) as $mempool)
{
if (isset($cache['devices']['id'][$mempool['device_id']]))
{
$mempool['hostname'] = $cache['devices']['id'][$mempool['device_id']]['hostname'];
$mempool['html_row_class'] = $cache['devices']['id'][$mempool['device_id']]['html_row_class'];
$mempools[] = $mempool;
}
}
$mempools_count = count($mempools);
// Pagination
$pagination_html = pagination($vars, $mempools_count);
echo $pagination_html;
if ($vars['pageno'])
{
$mempools = array_chunk($mempools, $vars['pagesize']);
$mempools = $mempools[$vars['pageno'] - 1];
}
// End Pagination
echo generate_box_open();
print_mempool_table_header($vars);
foreach ($mempools as $mempool)
{
print_mempool_row($mempool, $vars);
}
echo("</tbody></table>");
echo generate_box_close();
echo $pagination_html;
}
function print_mempool_table_header($vars)
{
if ($vars['view'] === "graphs")
{
$table_class = OBS_CLASS_TABLE_STRIPED_TWO;
} else {
$table_class = OBS_CLASS_TABLE_STRIPED;
}
echo('<table class="' . $table_class . '">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'device' => array('Device', 'style="width: 200px;"'),
'descr' => array('Memory'),
array('', 'style="width: 100px;"'),
'usage' => array('Usage', 'style="width: 280px;"'),
'used' => array('Used', 'style="width: 50px;"'),
);
if ($vars['page'] === "device")
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_mempool_row($mempool, $vars)
{
echo generate_mempool_row($mempool, $vars);
}
function generate_mempool_row($mempool, $vars)
{
global $config;
$table_cols = 7;
if ($vars['page'] !== "device" && $vars['popup'] != TRUE) { $table_cols++; } // Add a column for device.
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $mempool['mempool_id'];
$graph_array['type'] = "mempool_usage";
$graph_array['legend'] = "no";
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link_graph = generate_url($link_array);
$link = generate_url(array("page" => "device", "device" => $mempool['device_id'], "tab" => "health", "metric" => 'mempool'));
$overlib_content = generate_overlib_content($graph_array, $mempool['hostname'] . " - " . rewrite_entity_name($mempool['mempool_descr'], 'mempool'));
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
$mini_graph = generate_graph_tag($graph_array);
if ($mempool['mempool_total'] != '100')
{
$total = formatStorage($mempool['mempool_total']);
$used = formatStorage($mempool['mempool_used']);
$free = formatStorage($mempool['mempool_free']);
}
else
{
// If total == 100, than memory not have correct size and uses percents only
$total = $mempool['mempool_total'] . '%';
$used = $mempool['mempool_used'] . '%';
$free = $mempool['mempool_free'] . '%';
}
$background = get_percentage_colours($mempool['mempool_perc']);
$mempool['html_row_class'] = $background['class'];
$row .= '<tr class="' . $mempool['html_row_class'] . '">
<td class="state-marker"></td>';
if ($vars['page'] !== "device" && $vars['popup'] != TRUE)
{
$row .= '<td class="entity">' . generate_device_link($mempool) . '</td>';
}
$row .= '<td class="entity">' . generate_entity_link('mempool', $mempool) . '</td>
<td>' . overlib_link($link_graph, $mini_graph, $overlib_content) . '</td>
<td><a href="' . $link_graph . '">
' . print_percentage_bar(400, 20, $mempool['mempool_perc'], $used . '/' . $total . ' (' . $mempool['mempool_perc'] . '%)', "ffffff", $background['left'], $free . ' (' . (100 - $mempool['mempool_perc']) . '%)', "ffffff", $background['right']) . '
</a>
</td>
<td>' . $mempool['mempool_perc'] . '%</td>
</tr>
';
if ($vars['view'] === "graphs")
{
$vars['graph'] = "usage";
}
if ($vars['graph'])
{
$row .= '<tr class="' . $mempool['html_row_class'] . '">';
$row .= '<td class="state-marker"></td>';
$row .= '<td colspan="' . $table_cols . '">';
unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $mempool['mempool_id'];
$graph_array['type'] = 'mempool_' . $vars['graph'];
$row .= generate_graph_row($graph_array, TRUE);
$row .= '</td></tr>';
} # endif graphs
return $row;
}
function print_mempool_form($vars, $single_device = FALSE)
{
//global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `mempools`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
//$sensor_permitted = generate_query_permitted(array('device', 'sensor'));
$form['row'][0]['mempool_descr'] = array(
'type' => 'text',
'placeholder' => 'Mempool',
'width' => '100%', //'180px',
'grid' => 6,
'value' => $vars['mempool_descr']);
// Groups
foreach (get_type_groups('storage') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][0]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][0]['search'] = array(
'type' => 'submit',
'grid' => 2,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE,
);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Mempools',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['group'] = $form['row'][0]['group'];
//$panel_form['row'][1]['supply_colour'] = $form['row'][0]['supply_colour'];
//$panel_form['row'][1]['supply_type'] = $form['row'][0]['supply_type'];
//$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
//$panel_form['row'][2]['group'] = $form['row'][1]['group'];
$panel_form['row'][3]['mempool_descr'] = $form['row'][0]['mempool_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][0]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,258 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function generate_oid_template_link($entry)
{
$url = generate_url(array('page' => 'customoid', 'oid_id' => $entry['oid_id']));
$link = '<a href="'.$url.'">'.$entry['oid_descr'].'</a>';
return $link;
}
function build_oid_query($vars)
{
$sql = 'SELECT * FROM `oids_entries` LEFT JOIN `oids` USING (`oid_id`)';
//if ($vars['sort'] == 'hostname' || $vars['sort'] == 'device' || $vars['sort'] == 'device_id') {
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
//}
$sql .= ' WHERE 1' . generate_query_permitted(array('device'));
// Build query
foreach ($vars as $var => $value) {
switch ($var) {
case "oid_id":
case "oid_descr":
case "oid":
case "oid_name":
$sql .= generate_query_values($value, $var);
break;
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'oid_entry_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'oids_entries.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'oids_entries.device_id');
break;
}
}
switch ($vars['sort_order']) {
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch ($vars['sort']) {
case 'value':
case 'oid_descr':
case 'oid_name':
case 'oid':
case 'event':
$sql .= ' ORDER BY '.$vars['sort'].' ' . $sort_order;
break;
default:
$sql .= ' ORDER BY `hostname` ' . $sort_order;
}
return $sql;
}
function print_oid_table_header($vars, $entries)
{
echo('<table class="' . (get_var_true($vars['graphs']) ? OBS_CLASS_TABLE_STRIPED_TWO : OBS_CLASS_TABLE_STRIPED) . '">');
$cols[] = array('', 'class="state-marker"');
$cols['hostname'] = array('Device', 'style="width: 280px;"');
if(!isset($vars['oid_id'])){
$cols['oid_descr'] = array('OID Description');
} else { $cols[] = array(''); }
$cols[] = array('', 'style="width: 140px;"');
$cols[] = array('Thresholds', 'style="width: 100px;"');
$cols['value'] = array('Value', 'style="width: 80px;"');
$cols['event'] = array('Event', 'style="width: 60px;"');
if ($entries[0]['oid_autodiscover'] == '0' && $vars['page'] === "customoid") {
$cols['actions'] = array('', 'style="width: 40px;"'); echo "derp";
}
echo get_table_header($cols, $vars);
echo '<tbody>' . PHP_EOL;
}
function print_oid_table($vars)
{
global $config;
$sql = build_oid_query($vars);
$entries = dbFetchRows($sql);
$count = count($entries);
if (count($entries)) {
echo generate_box_open();
print_oid_table_header($vars, $entries);
foreach ($entries as $device_id => $entry) {
//$device = device_by_id_cache($device_id);
if (!is_numeric($entry['value'])) {
$entry['human_value'] = 'NaN';
} else {
if($entry['oid_kibi'] == 1) {
$entry['human_value'] = format_value($entry['value'], 'bi') . $entry['oid_symbol'];
} else {
$entry['human_value'] = format_value($entry['value'], 'si') . $entry['oid_symbol'];
}
}
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $entry['oid_entry_id'];
$graph_array['type'] = "customoid_graph";
$graph_array['width'] = 100;
$graph_array['height'] = 20;
$graph_array['from'] = $config['time']['day'];
if (is_numeric($entry['value']) || TRUE) {
$mini_graph = generate_graph_tag($graph_array);
} else {
// Do not show "Draw Error" minigraph
$mini_graph = '';
}
$thresholds = threshold_string($entry['alert_low'], $entry['warn_low'], $entry['warn_high'],
$entry['alert_high'], $entry['oid_symbol']);
switch ($entry['event']) {
case "ok";
$entry['html_row_class'] = "up";
$entry['event_class'] = "success";
break;
case "warn";
$entry['html_row_class'] = "warning";
$entry['event_class'] = "warning";
break;
case "alert";
$entry['html_row_class'] = "error";
$entry['event_class'] = "error";
break;
case "ignore";
default:
$entry['html_row_class'] = "ignore";
$entry['event_class'] = "ignore";
break;
}
$event = '<span class="label label-' . $entry['event_class'] . '">' . $entry['event'] . '</span>';
echo '
<tr class="' . $entry['html_row_class'] . '">
<td class="state-marker"></td>
<td><i class="' . $config['entities']['device']['icon'] . '"></i> <b>' . generate_device_link($entry) . '</b></td>';
if(!isset($vars['oid_id']))
{
echo '
<td>'.generate_oid_template_link($entry).'</td> ';
} else {
echo '
<td></td>';
}
echo '
<td>' . $mini_graph . '</td>
<td>' . $thresholds . '</td>
<td><span class="label label-' . $entry['event_class'] . '">' . $entry['human_value'] . '</span></td>
<td>' . $event . '</td>
';
if ($entries[0]['oid_autodiscover'] == '0' && $vars['page'] == "customoid") {
$form = array('type' => 'simple',
//'userlevel' => 10, // Minimum user level for display form
'id' => 'delete_customoid_device_' . $entry['device_id'],
'style' => 'display:inline;',
);
$form['row'][0]['form_oid_id'] = array(
'type' => 'hidden',
'value' => $entry['oid_id']);
$form['row'][0]['form_device_id'] = array(
'type' => 'hidden',
'value' => $entry['device_id']);
$form['row'][99]['action'] = array(
'type' => 'submit',
'icon_only' => TRUE, // hide button styles
'name' => '',
'icon' => $config['icon']['cancel'],
//'right' => TRUE,
//'class' => 'btn-small',
// confirmation dialog
'attribs' => array('data-toggle' => 'confirm', // Enable confirmation dialog
'data-confirm-placement' => 'left',
'data-confirm-content' => 'Delete associated device "' . escape_html($entry['hostname']) . '"?',
),
'value' => 'delete_customoid_device');
echo('<td>');
print_form($form);
unset($form);
echo('</td>');
}
echo '
</tr>';
if ($vars['graphs'] == "yes")
{
$vars['graph'] = "graph";
}
if ($vars['graph'])
{
$graph_array = array();
$graph_title = $entry['oid_descr'];
$graph_array['type'] = "customoid_".$vars['graph'];
$graph_array['id'] = $entry['oid_entry_id'];
echo '<tr><td colspan=8>';
print_graph_row($graph_array);
echo '</td></tr>';
}
}
echo ' </table>' . PHP_EOL;
echo generate_box_close();
} else {
echo '<p class="text-center text-warning bg-warning" style="padding: 10px; margin: 0;"><strong>This Custom OID is not currently associated with any devices</strong></p>';
}
}

View File

@ -0,0 +1,162 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function generate_p2pradio_query($vars)
{
$sql = "SELECT * FROM `p2p_radios`";
$sql .= ' WHERE 1' . generate_query_permitted(array('device'));
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'radio_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'p2p_radios.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'device_id');
break;
}
}
return $sql;
}
function print_p2pradio_table_header($vars)
{
echo('<thead><tr>
<th class="state-marker"></th>
<th width="1"></th>');
if ($vars['page'] != "device" && $vars['popup'] != TRUE) { echo(' <th style="width: 200px;">Device</th>'); }
echo('
<th>Radio</th>
<th>Modulation</th>
<th>Capacity</th>
<th>Max Capacity</th>
<th>Max Eth Cap</th>
<th># E1/T1</th>
<th>Tx Power</th>
<th>Rx Level</th>
<th>Tx Freq</th>
<th>Rx Freq</th>
</tr></thead>');
}
function print_p2pradio_row($radio, $vars)
{
echo generate_p2pradio_row($radio, $vars);
}
function print_p2pradio_table($vars)
{
if ($vars['view'] == "graphs" || isset($vars['graph']))
{
$stripe_class = "table-striped-two";
} else {
$stripe_class = "table-striped";
}
echo generate_box_open();
echo '<table class="table table-hover '.$stripe_class.' table-condensed">';
print_p2pradio_table_header($vars);
$sql = generate_p2pradio_query($vars);
$radios = dbFetchRows($sql);
foreach($radios as $radio)
{
print_p2pradio_row($radio, $vars);
}
echo('</table>');
echo generate_box_close();
}
function generate_p2pradio_row($radio, $vars)
{
global $config;
$device = device_by_id_cache($radio['device_id']);
$table_cols = 12;
if ($vars['page'] != "device" && $vars['popup'] != TRUE) { $table_cols++; } // Add a column for device.
$row .= '<tr class="' . $radio['row_class'] . '">
<td class="state-marker"></td>
<td></td>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE) {
$row .=('<td class="entity">' . generate_device_link_short($device) . '</td>');
}
$row .= '
<td class="entity">' . generate_entity_link('p2pradio', $radio) . '</td>
<td width="100"><span class="label">' . strtoupper($radio['radio_modulation']) . '</span></td>
<td width="90">' . format_si($radio['radio_cur_capacity']) . 'bps</td>
<td width="100">' . format_si($radio['radio_total_capacity']) . 'bps</td>
<td width="90">' . format_si($radio['radio_eth_capacity']) . 'bps</td>
<td width="70">' . ($radio['radio_e1t1_channels'] ?: "N/A") . '</td>
<td width="70"><span class="label label-error">' . $radio['radio_tx_power'] . 'dBm</span></td>
<td width="70"><span class="label label-warning">' . $radio['radio_rx_level'] . 'dBm</span></td>
<td width="90"><span class="label label-success">' . ($radio['radio_tx_freq'] / 1000000) . 'GHz</span></td>
<td width="90"><span class="label label-info">' . ($radio['radio_rx_freq'] / 1000000) . 'GHz</span></td>
';
$row .= '</tr>';
if ($vars['view'] == "graphs")
{
$graphs = array('capacity', 'power', 'rxlevel', 'gain', 'rmse', 'symbol_rates');
$show_graph_title = TRUE;
} elseif (isset($vars['graph'])) { $graphs = explode(",", $vars['graph']); }
if (is_array($graphs))
{
$row .= '<tr class="' . $radio['row_class'] . '">';
$row .= '<td class="state-marker"></td>';
$row .= '<td colspan=' . $table_cols . '>';
unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $radio['radio_id'];
foreach($graphs as $graph_type)
{
$graph_array['type'] = 'p2pradio_' . $graph_type;
if ($show_graph_title) { $row .= '<h3>'.$config['graph_types']['p2pradio'][$graph_type]['name'].'</h3>'; }
$row .= generate_graph_row($graph_array, TRUE);
}
$row .= "</td>";
$row .= "</tr>";
}
return $row;
}
// EOF

View File

@ -0,0 +1,904 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
/**
* Build ports WHERE array
*
* This function returns an array of "WHERE" statements from a $vars array.
* The returned array can be implode()d and used on the ports table.
* Originally extracted from the /ports/ page
*
* @param array $vars
* @return array
*/
function build_ports_where_array($vars) {
$where = array();
foreach($vars as $var => $value) {
if (!safe_empty($value)) {
switch ($var) {
case 'location':
$where[] = generate_query_values($value, $var);
break;
case 'device_id':
$where[] = generate_query_values($value, 'ports.device_id');
break;
case 'group':
case 'group_id':
$values = get_group_entities($value);
$where[] = generate_query_values($values, 'ports.port_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$where[] = generate_query_values($values, 'ports.device_id');
break;
case 'disable':
$var = 'disabled';
case 'disabled': // FIXME. 'disabled' column never used in ports..
case 'deleted':
case 'ignore':
case 'ifSpeed':
case 'ifType':
case 'port_id':
$where[] = generate_query_values($value, 'ports.'.$var);
break;
case 'hostname':
case 'ifAlias':
case 'ifDescr': // FIXME, probably better always use port_label instead ifDescr for search
$where[] = generate_query_values($value, $var, '%LIKE%');
break;
case 'label':
case 'port_label':
$where[] = generate_query_values($value, 'port_label', '%LIKE%');
break;
case 'mac':
case 'ifPhysAddress':
$value = str_replace([ '.', '-', ':' ], '', $value);
$where[] = generate_query_values($value, 'ifPhysAddress', '%LIKE%');
break;
case 'port_descr_type':
$where[] = generate_query_values($value, $var, 'LIKE');
break;
case 'errors':
if (get_var_true($value)) {
$where[] = " AND (`ifInErrors_delta` > '0' OR `ifOutErrors_delta` > '0')";
}
break;
case 'alerted':
if (get_var_true($value)) {
// this is just state=down
//$where[] = ' AND `ifAdminStatus` = "up" AND (`ifOperStatus` = "lowerLayerDown" OR `ifOperStatus` = "down")';
$var = 'state';
$value = 'down';
}
// do not break here
case 'state':
// Allowed multiple states as array
$state_where = [];
foreach ((array)$value as $state) {
if ($state === "down") {
$state_where[] = '`ifAdminStatus` = "up" AND `ifOperStatus` IN ("lowerLayerDown", "down")';
//$state_where[] = generate_query_values('up', 'ifAdminStatus', NULL, FALSE) . generate_query_values(['down', 'lowerLayerDown'], 'ifOperStatus');
} elseif ($state === "up") {
$state_where[] = '`ifAdminStatus` = "up" AND `ifOperStatus` IN ("up", "testing", "monitoring")';
//$state_where[] = generate_query_values('up', 'ifAdminStatus', NULL, FALSE) . generate_query_values(['up', 'testing', 'monitoring'], 'ifOperStatus');
} elseif ($state === "admindown" || $state === "shutdown") {
$state_where[] = '`ifAdminStatus` = "down"';
//$state_where[] = generate_query_values('down', 'ifAdminStatus', NULL, FALSE);
}
}
switch (count($state_where)) {
case 0:
// incorrect state passed, ignore
break;
case 1:
$where[] = ' AND ' . $state_where[0];
break;
default:
$where[] = ' AND ((' . implode(') OR (', $state_where) . '))';
}
break;
case 'cbqos':
if ($value && $value !== 'no') {
$where[] = generate_query_values($GLOBALS['cache']['ports']['cbqos'], 'ports.port_id');
}
break;
case 'mac_accounting':
if ($value && $value !== 'no') {
$where[] = generate_query_values($GLOBALS['cache']['ports']['mac_accounting'], 'ports.port_id');
}
break;
}
}
}
return $where;
}
/**
* Returns a string containing an HTML table to be used in popups for the port entity type
*
* @param array $port array
*
* @return string Table containing port header for popups
*/
function generate_port_popup_header($port) {
// Push through processing function to set attributes
humanize_port($port);
$contents = generate_box_open();
$contents .= '<table class="'. OBS_CLASS_TABLE .'">
<tr class="' . $port['row_class'] . '" style="font-size: 10pt;">
<td class="state-marker"></td>
<td style="width: 10px;"></td>
<td style="width: 250px;"><a href="'.generate_entity_url('port', $port).'" class="' . $port['html_class'] .
'" style="font-size: 15px; font-weight: bold;">' . escape_html($port['port_label']) . '</a><br />' .
escape_html($port['ifAlias']) . '</td>
<td style="width: 100px;">' . $port['human_speed'] . '<br />' . $port['ifMtu'] . '</td>
<td>' . $port['human_type'] . '<br />' . $port['human_mac'] . '</td>
</tr>
</table>';
$contents .= generate_box_close();
return $contents;
}
/**
* Returns a string containing an HTML to be used as a port popups
*
* @param array $port array
* @param string $text to be used as port label
* @param string $type graph type to be used in graphs (bits, nupkts, etc)
*
* @return string HTML port popup contents
*/
function generate_port_popup($port, $text = NULL, $type = NULL)
{
$time = $GLOBALS['config']['time'];
if (!isset($port['os']))
{
$port = array_merge($port, device_by_id_cache($port['device_id']));
}
humanize_port($port);
if (!$text)
{
$text = escape_html($port['port_label']);
}
if ($type)
{
$port['graph_type'] = $type;
}
if (!isset($port['graph_type']))
{
$port['graph_type'] = 'port_bits';
}
if (!isset($port['os']))
{
$port = array_merge($port, device_by_id_cache($port['device_id']));
}
$content = generate_device_popup_header($port);
$content .= generate_port_popup_header($port);
$content .= '<div style="width: 700px">';
//$content .= generate_box_open(array('body-style' => 'width: 700px;'));
$graph_array['type'] = $port['graph_type'];
$graph_array['legend'] = "yes";
$graph_array['height'] = "100";
$graph_array['width'] = "275";
$graph_array['to'] = $time['now'];
$graph_array['from'] = $time['day'];
$graph_array['id'] = $port['port_id'];
$content .= generate_graph_tag($graph_array);
$graph_array['from'] = $time['week'];
$content .= generate_graph_tag($graph_array);
$graph_array['from'] = $time['month'];
$content .= generate_graph_tag($graph_array);
$graph_array['from'] = $time['year'];
$content .= generate_graph_tag($graph_array);
$content .= "</div>";
//$content .= generate_box_close();
return $content;
}
/**
* Returns an HTML port page link with mouse-over popup to permitted users or a text label to non-permitted users
*
* @param array $port array
* @param string $text text to be used as port label
* @param string $type graph type to be used in graphs (bits, nupkts, etc)
*
* @return string HTML link or text string
*/
function generate_port_link($port, $text = NULL, $type = NULL, $escape = FALSE, $short = FALSE)
{
humanize_port($port);
// Fixme -- does this function even need alternative $text? I think not. It's a hangover from before label.
// Sometime in $text included html
if (empty($text))
{
$text = $short ? $port['port_label_short'] : $port['port_label'];
$escape = TRUE; // FORCE label escaping
}
if (port_permitted($port['port_id'], $port['device_id']))
{
$url = generate_port_url($port);
if ($escape)
{
$text = escape_html($text);
}
return '<a href="' . $url . '" class="entity-popup ' . $port['html_class'] . '" data-eid="' . $port['port_id'] . '" data-etype="port">' . $text . '</a>';
}
else
{
return escape_html($text);
}
}
// Just simplify function call, instead generate_port_link($port, NULL, NULL, TRUE, TRUE)
function generate_port_link_short($port, $text = NULL, $type = NULL, $escape = FALSE, $short = TRUE)
{
return generate_port_link($port, $text, $type, $escape, $short);
}
/**
* Returns a string containing a page URL built from a $port array and an array of optional variables
*
* @param array $port array
* @param array optional variables used when building the URL
*
* @return string port page URL
*/
function generate_port_url($port, $vars = array())
{
return generate_url(array('page' => 'device', 'device' => $port['device_id'], 'tab' => 'port', 'port' => $port['port_id']), $vars);
}
/**
* Returns or echos a port graph thumbnail
*
* @param array $args of arguments used to build the graph image tag URL
* @param boolean $echo variable defining wether output should be returned or echoed
*
* @return string HTML port popup contents
*/
function generate_port_thumbnail($args, $echo = TRUE)
{
if (!$args['bg'])
{
$args['bg'] = "FFFFFF";
}
$graph_array = array();
$graph_array['from'] = $args['from'];
$graph_array['to'] = $args['to'];
$graph_array['id'] = $args['port_id'];
$graph_array['type'] = $args['graph_type'];
$graph_array['width'] = $args['width'];
$graph_array['height'] = $args['height'];
$graph_array['bg'] = 'FFFFFF00';
$mini_graph = generate_graph_tag($graph_array);
$img = generate_port_link($args, $mini_graph);
if ($echo)
{
echo($img);
} else {
return $img;
}
}
function print_port_row($port, $vars = array())
{
echo generate_port_row($port, $vars);
}
function generate_port_row($port, $vars = array())
{
global $config, $cache;
$device = device_by_id_cache($port['device_id']);
humanize_port($port);
if (!isset($vars['view'])) { $vars['view'] = "basic"; }
// Populate $port_adsl if the port has ADSL-MIB data
if (!isset($cache['ports_option']['ports_adsl']) || in_array($port['port_id'], $cache['ports_option']['ports_adsl'])) {
$port_adsl = dbFetchRow("SELECT * FROM `ports_adsl` WHERE `port_id` = ?", array($port['port_id']));
}
// Populate $port['tags'] with various tags to identify port statuses and features
// Port Errors
if ($port['ifInErrors_delta'] > 0 || $port['ifOutErrors_delta'] > 0) {
$port['tags'] .= generate_port_link($port, '<span class="label label-important">Errors</span>', 'port_errors');
}
// Port Deleted
if ($port['deleted']) {
$port['tags'] .= '<a href="'.generate_url(array('page' => 'deleted-ports')).'"><span class="label label-important">Deleted</span></a>';
}
if ($port['ignore']) {
$port['tags'] .= '<span class="label label-suppressed">Ignored</span>';
}
if ($port['disabled']) {
$port['tags'] .= '<span class="label label-disabled">Poll disabled</span>';
}
// Port IPv6
if (isset($port['attribs']['ipv6-octets'])) {
$port['tags'] .= '<span class="label label-primary">IPv6</span>';
}
// Port CBQoS
if (isset($cache['ports_option']['ports_cbqos']))
{
if (in_array($port['port_id'], $cache['ports_option']['ports_cbqos']))
{
$port['tags'] .= '<a href="' . generate_port_url($port, array('view' => 'cbqos')) . '"><span class="label label-info">CBQoS</span></a>';
}
}
//else if (dbFetchCell("SELECT COUNT(*) FROM `ports_cbqos` WHERE `port_id` = ?", array($port['port_id'])))
else if (dbExist('ports_cbqos', '`port_id` = ?', array($port['port_id'])))
{
$port['tags'] .= '<a href="' . generate_port_url($port, array('view' => 'cbqos')) . '"><span class="label label-info">CBQoS</span></a>';
}
// Port MAC Accounting
if (isset($cache['ports_option']['mac_accounting']))
{
if (in_array($port['port_id'], $cache['ports_option']['mac_accounting']))
{
$port['tags'] .= '<a href="' . generate_port_url($port, array('view' => 'macaccounting')) . '"><span class="label label-info">MAC</span></a>';
}
}
//else if (dbFetchCell("SELECT COUNT(*) FROM `mac_accounting` WHERE `port_id` = ?", array($port['port_id'])))
else if (dbExist('mac_accounting', '`port_id` = ?', array($port['port_id'])))
{
$port['tags'] .= '<a href="' . generate_port_url($port, array('view' => 'macaccounting')) . '"><span class="label label-info">MAC</span></a>';
}
// Populated formatted versions of port rates.
$port['bps_in'] = formatRates($port['ifInOctets_rate'] * 8);
$port['bps_out'] = formatRates($port['ifOutOctets_rate'] * 8);
$port['pps_in'] = format_si($port['ifInUcastPkts_rate'])."pps";
$port['pps_out'] = format_si($port['ifOutUcastPkts_rate'])."pps";
$string = '';
if ($vars['view'] === "basic" || $vars['view'] === "graphs") // Print basic view table row
{
$table_cols = '8';
$string .= '<tr class="' . $port['row_class'] . '">
<td class="state-marker"></td>
<td style="width: 1px;"></td>';
if ($vars['page'] !== "device" && $vars['popup'] != TRUE) // Print device name link if we're not inside the device page hierarchy.
{
$table_cols++; // Increment table columns by one to make sure graph line draws correctly
$string .= ' <td style="width: 200px;"><span class="entity">' . generate_device_link_short($device, [], 20) . '</span><br />
<span class="em">' . escape_html(truncate($port['location'], 32, "")) . '</span></td>';
}
$string .=
' <td><span class="entity">' . generate_port_link($port) . '</span> <span class="pull-right">' . $port['tags'] . '</span><br />' .
' <span class="em">' . escape_html(truncate($port['ifAlias'], 50, '')) . '</span></td>' .
'<td style="width: 110px;">' . get_icon('arrow-down', NULL, [ 'style' => $port['bps_in_style'] ]) . ' <span class="small" style="' . $port['bps_in_style'] . '">' . formatRates($port['in_rate']) . '</span><br />' .
get_icon('arrow-up', NULL, [ 'style' => $port['bps_out_style'] ]) . ' <span class="small" style="' . $port['bps_out_style'] . '">' . formatRates($port['out_rate']) . '</span><br /></td>' .
'<td style="width: 90px;">' . get_icon('arrow-down', NULL, [ 'style' => $port['bps_in_style'] ]) . ' <span class="small" style="' . $port['bps_in_style'] . '">' . $port['ifInOctets_perc'] . '%</span><br />' .
get_icon('arrow-up', NULL, [ 'style' => $port['bps_out_style'] ]) . ' <span class="small" style="' . $port['bps_out_style'] . '">' . $port['ifOutOctets_perc'] . '%</span><br /></td>' .
'<td style="width: 110px;">' . get_icon('arrow-down', NULL, [ 'style' => $port['pps_in_style'] ]) . ' <span class="small" style="' . $port['pps_in_style'] . '">' . format_bi($port['ifInUcastPkts_rate']) . 'pps</span><br />' .
get_icon('arrow-up', NULL, [ 'style' => $port['pps_out_style'] ]) . ' <span class="small" style="' . $port['pps_out_style'] . '">' . format_bi($port['ifOutUcastPkts_rate']) . 'pps</span></td>' .
'<td style="width: 110px;"><small>' . $port['human_speed'] . '<br />' . $port['ifMtu'] . '</small></td>
<td ><small>' . $port['human_type'] . '<br />' . $port['human_mac'] . '</small></td>
</tr>';
}
elseif ($vars['view'] === "details" || $vars['view'] === "detail") // Print detailed view table row
{
$table_cols = '9';
$string .= '<tr class="' . $port['row_class'] . '"';
if ($vars['tab'] !== "port") { $string .= ' onclick="openLink(\'' . generate_port_url($port) . '\')" style="cursor: pointer;"'; }
$string .= '>';
$string .= ' <td class="state-marker"></td>
<td style="width: 1px;"></td>';
if ($vars['page'] !== "device" && $vars['popup'] != TRUE) // Print device name link if we're not inside the device page hierarchy.
{
$table_cols++; // Increment table columns by one to make sure graph line draws correctly
$string .= ' <td width="200"><span class="entity">' . generate_device_link_short($device, [], 20) . '</span><br />
<span class="em">' . escape_html(truncate($port['location'], 32, "")) . '</span></td>';
}
$string .= '
<td style="min-width: 250px;">';
$string .= ' <span class="entity-title">
' . generate_port_link($port) . '</span> <span class="pull-right">'.$port['tags'].'
</span><br /><span class="small">'.escape_html($port['ifAlias']).'</span>';
if ($port['ifAlias']) { $string .= '<br />'; }
unset($break);
$ignore_type = $GLOBALS['config']['ip-address']['ignore_type'];
if (!isset($cache['ports_option']['ipv4_addresses']) || in_array($port['port_id'], $cache['ports_option']['ipv4_addresses'])) {
$sql = "SELECT * FROM `ipv4_addresses` WHERE `port_id` = ?";
// Do not exclude IPv4 link-local
$sql .= generate_query_values(array_diff($ignore_type, [ 'link-local' ]), 'ipv4_type', '!='); // Do not show ignored ip types
foreach (dbFetchRows($sql, array($port['port_id'])) as $ip)
{
$string .= $break . generate_popup_link('ip', $ip['ipv4_address'].'/'.$ip['ipv4_prefixlen'], NULL, 'small');
$break = "<br />";
}
}
if (!isset($cache['ports_option']['ipv6_addresses']) || in_array($port['port_id'], $cache['ports_option']['ipv6_addresses']))
{
$sql = "SELECT * FROM `ipv6_addresses` WHERE `port_id` = ?";
$sql .= generate_query_values($ignore_type, 'ipv6_type', '!='); // Do not show ignored ip types
foreach (dbFetchRows($sql, array($port['port_id'])) as $ip6)
{
$string .= $break . generate_popup_link('ip', $ip6['ipv6_address'].'/'.$ip6['ipv6_prefixlen'], NULL, 'small');
$break = "<br />";
}
}
//$string .= '</span>';
$string .= '</td>';
// Print port graph thumbnails
$string .= '<td style="width: 147px;">';
$port['graph_type'] = "port_bits";
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $port['port_id'];
$graph_array['type'] = $port['graph_type'];
$graph_array['width'] = 100;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
$string .= generate_port_link($port, generate_graph_tag($graph_array));
$port['graph_type'] = "port_upkts";
$graph_array['type'] = $port['graph_type'];
$string .= generate_port_link($port, generate_graph_tag($graph_array));
$port['graph_type'] = "port_errors";
$graph_array['type'] = $port['graph_type'];
$string .= generate_port_link($port, generate_graph_tag($graph_array));
$string .= '</td>';
$string .= '<td style="width: 100px; white-space: nowrap;">';
if ($port['ifOperStatus'] === "up" || $port['ifOperStatus'] === "monitoring") {
// Colours generated by humanize_port
$string .= '<i class="icon-circle-arrow-down" style="'.$port['bps_in_style']. '"></i> <span class="small" style="'.$port['bps_in_style']. '">' . formatRates($port['in_rate']) . '</span><br />
<i class="icon-circle-arrow-up" style="'.$port['bps_out_style'].'"></i> <span class="small" style="'.$port['bps_out_style'].'">' . formatRates($port['out_rate']). '</span><br />
<i class="icon-circle-arrow-down" style="'.$port['pps_in_style']. '"></i> <span class="small" style="'.$port['pps_in_style']. '">' . format_bi($port['ifInUcastPkts_rate']). 'pps</span><br />
<i class="icon-circle-arrow-up" style="'.$port['pps_out_style'].'"></i> <span class="small" style="'.$port['pps_out_style'].'">' . format_bi($port['ifOutUcastPkts_rate']).'pps</span>';
}
$string .= '</td><td style="width: 110px;">';
if ($port['ifType'] && $port['ifType'] != "") { $string .= '<span class="small">' . $port['human_type'] . '</span>'; } else { $string .= '-'; }
$string .= '<br />';
if ($port['ifSpeed']) { $string .= '<span class="small">'.humanspeed($port['ifSpeed']).'</span>'; }
if ($port['ifDuplex'] && $port['ifDuplex'] !== "unknown") { $string .= '<span class="small"> (' . str_replace("Duplex", "", $port['ifDuplex']) . ')</span>'; }
$string .= '<br />';
if ($port['ifMtu'] && $port['ifMtu'] != "") { $string .= '<span class="small">MTU ' . $port['ifMtu'] . '</span>'; } else { $string .= '<span class="small">Unknown MTU</span>'; }
// if ($ifHardType && $ifHardType != "") { $string .= '<span class="small">" . $ifHardType . "</span>"); } else { $string .= '-'; }
//$string .= '<br />';
// Set VLAN data if the port has ifTrunk populated
if (strlen($port['ifTrunk']) &&
!in_array($port['ifTrunk'], array('access', 'routed'))) // Skip on routed (or access)
{
if ($port['ifVlan']) {
// Native VLAN
if (!isset($cache['ports_vlan'])) {
$native_state = dbFetchCell('SELECT `state` FROM `ports_vlans` WHERE `device_id` = ? AND `port_id` = ?', array($device['device_id'], $port['port_id']));
$native_name = dbFetchCell('SELECT `vlan_name` FROM vlans WHERE `device_id` = ? AND `vlan_vlan` = ?;', array($device['device_id'], $port['ifVlan']));
} else {
$native_state = $cache['ports_vlan'][$port['port_id']][$port['ifVlan']]['state'];
$native_name = $cache['ports_vlan'][$port['port_id']][$port['ifVlan']]['vlan_name'];
}
switch ($native_state) {
case 'blocking': $class = 'text-danger'; break;
case 'forwarding': $class = 'text-success'; break;
default: $class = 'muted';
}
if (empty($native_name)) { $native_name = 'VLAN'.str_pad($port['ifVlan'], 4, '0', STR_PAD_LEFT); }
$native_tooltip = 'NATIVE: <strong class='.$class.'>'.$port['ifVlan'].' ['.$native_name.']</strong><br />';
}
if (!isset($cache['ports_vlan'])) {
$vlans = dbFetchRows('SELECT * FROM `ports_vlans` AS PV
LEFT JOIN vlans AS V ON PV.`vlan` = V.`vlan_vlan` AND PV.`device_id` = V.`device_id`
WHERE PV.`port_id` = ? AND PV.`device_id` = ? ORDER BY PV.`vlan`;', array($port['port_id'], $device['device_id']));
} else {
$vlans = $cache['ports_vlan'][$port['port_id']];
}
$vlans_count = safe_count($vlans);
$rel = ($vlans_count || $native_tooltip) ? 'tooltip' : ''; // Hide tooltip for empty
$string .= '<p class="small"><a class="label label-info" data-rel="'.$rel.'" data-tooltip="<div class=\'small\' style=\'max-width: 320px; text-align: justify;\'>'.$native_tooltip;
if ($vlans_count) {
$string .= 'ALLOWED: ';
$vlans_aggr = array();
foreach ($vlans as $vlan) {
if ($vlans_count > 20) {
// Aggregate VLANs
$vlans_aggr[] = $vlan['vlan'];
} else {
// List VLANs
switch ($vlan['state']) {
case 'blocking': $class = 'text-danger'; break;
case 'forwarding': $class = 'text-success'; break;
default: $class = 'muted';
}
if (empty($vlan['vlan_name'])) {
$vlan['vlan_name'] = 'VLAN'.str_pad($vlan['vlan'], 4, '0', STR_PAD_LEFT);
}
$string .= '<strong class='.$class.'>'.$vlan['vlan'] .' ['.$vlan['vlan_name'].']</strong><br />';
}
}
if ($vlans_count > 20) {
// End aggregate VLANs
$string .= '<strong>'.range_to_list($vlans_aggr, ', ').'</strong>';
}
}
$string .= '</div>">'.$port['ifTrunk'].'</a></p>';
} elseif ($port['ifVlan']) {
if (!isset($cache['ports_vlan'])) {
$native_state = dbFetchCell('SELECT `state` FROM `ports_vlans` WHERE `device_id` = ? AND `port_id` = ?', array($device['device_id'], $port['port_id']));
$native_name = dbFetchCell('SELECT `vlan_name` FROM vlans WHERE `device_id` = ? AND `vlan_vlan` = ?;', array($device['device_id'], $port['ifVlan']));
} else {
$native_state = $cache['ports_vlan'][$port['port_id']][$port['ifVlan']]['state'];
$native_name = $cache['ports_vlan'][$port['port_id']][$port['ifVlan']]['vlan_name'];
}
switch ($native_state) {
case 'blocking': $class = 'label-error'; break;
case 'forwarding': $class = 'label-success'; break;
default: $class = '';
}
$rel = ($native_name) ? 'tooltip' : ''; // Hide tooltip for empty
$vlan_name = ($port['ifTrunk'] !== 'access') ? nicecase($port['ifTrunk']) . ' ' : '';
$vlan_name .= 'VLAN ' . $port['ifVlan'];
$string .= '<br /><span data-rel="'.$rel.'" class="label '.$class.'" data-tooltip="<strong class=\'small\'>'.$port['ifVlan'].' ['.$native_name.']</strong>">' . $vlan_name . '</span>';
} elseif ($port['ifVrf']) { // Print the VRF name if the port is assigned to a VRF
$vrf_name = dbFetchCell("SELECT `vrf_name` FROM `vrfs` WHERE `vrf_id` = ?", array($port['ifVrf']));
$string .= '<br /><span class="label label-success" data-rel="tooltip" data-tooltip="VRF">'.$vrf_name.'</span>';
}
$string .= '</td>';
// If the port is ADSL, print ADSL port data.
if ($port_adsl['adslLineCoding']) {
$string .= '<td style="width: 200px;"><span class="small">';
$string .= '<span class="label">'.$port_adsl['adslLineCoding'].'</span> <span class="label">' . rewrite_adslLineType($port_adsl['adslLineType']).'</span>';
$string .= '<br />';
$string .= 'SYN <i class="icon-circle-arrow-down green"></i> '.formatRates($port_adsl['adslAtucChanCurrTxRate']) . ' <i class="icon-circle-arrow-up blue"></i> '. formatRates($port_adsl['adslAturChanCurrTxRate']);
$string .= '<br />';
//$string .= 'Max:'.formatRates($port_adsl['adslAtucCurrAttainableRate']) . '/'. formatRates($port_adsl['adslAturCurrAttainableRate']);
//$string .= '<br />';
$string .= 'ATN <i class="icon-circle-arrow-down green"></i> '.$port_adsl['adslAtucCurrAtn'] . 'dBm <i class="icon-circle-arrow-up blue"></i> '. $port_adsl['adslAturCurrAtn'] . 'dBm';
$string .= '<br />';
$string .= 'SNR <i class="icon-circle-arrow-down green"></i> '.$port_adsl['adslAtucCurrSnrMgn'] . 'dB <i class="icon-circle-arrow-up blue"></i> '. $port_adsl['adslAturCurrSnrMgn']. 'dB';
$string .= '</span>';
} else {
// Otherwise print normal port data
$string .= '<td style="width: 150px;"><span class="small">';
if ($port['ifPhysAddress'] && $port['ifPhysAddress'] != "") { $string .= $port['human_mac']; } else { $string .= '-'; }
$string .= '<br />' . $port['ifLastChange'] . '</span>';
}
$string .= '</td>';
$string .= '<td style="min-width: 200px" class="small">';
if ($port['ifType'] !== 'softwareLoopback' && !str_contains($port['port_label'], 'oopback') &&
safe_empty($graph_type)) {
$br = '';
// Populate links array for ports with direct links
if (!isset($cache['ports_option']['neighbours']) || in_array($port['port_id'], $cache['ports_option']['neighbours'])) {
foreach (dbFetchRows('SELECT * FROM `neighbours` WHERE `port_id` = ? AND `active` = ?', [ $port['port_id'], 1 ]) as $neighbour) {
// print_r($neighbour);
if ($neighbour['remote_port_id']) {
// Do not show some "non-physical" interfaces links,
// see: https://jira.observium.org/browse/OBS-2979
$remote_port = get_port_by_id_cache($neighbour['remote_port_id']);
if (!in_array($remote_port['ifType'], [ 'propVirtual', 'ieee8023adLag' ])) {
$int_links[$neighbour['remote_port_id']] = $neighbour['remote_port_id'];
$int_links_phys[$neighbour['remote_port_id']] = $neighbour['protocol'];
}
} else {
$int_links_unknown[] = $neighbour;
}
}
} // else { }
// Populate links array for devices which share an IPv4 subnet
if (!isset($cache['ports_option']['ipv4_addresses']) || in_array($port['port_id'], $cache['ports_option']['ipv4_addresses']))
{
foreach (dbFetchColumn('SELECT DISTINCT(`ipv4_network_id`) FROM `ipv4_addresses`
LEFT JOIN `ipv4_networks` USING(`ipv4_network_id`)
WHERE `port_id` = ? AND `ipv4_network` NOT IN (?);', array($port['port_id'], $config['ignore_common_subnet'])) as $network_id)
{
$sql = 'SELECT N.*, P.`port_id`, P.`device_id` FROM `ipv4_addresses` AS A, `ipv4_networks` AS N, `ports` AS P
WHERE A.`port_id` = P.`port_id` AND P.`device_id` != ?
AND A.`ipv4_network_id` = ? AND N.`ipv4_network_id` = A.`ipv4_network_id`
AND P.`ifAdminStatus` = "up"';
$params = array($device['device_id'], $network_id);
foreach (dbFetchRows($sql, $params) as $new)
{
if ($cache['devices']['id'][$new['device_id']]['disabled'] && !$config['web_show_disabled']) { continue; }
$int_links[$new['port_id']] = $new['port_id'];
$int_links_v4[$new['port_id']][] = $new['ipv4_network'];
}
}
}
// Populate links array for devices which share an IPv6 subnet
if (!isset($cache['ports_option']['ipv6_addresses']) || in_array($port['port_id'], $cache['ports_option']['ipv6_addresses']))
{
foreach (dbFetchColumn("SELECT DISTINCT(`ipv6_network_id`) FROM `ipv6_addresses`
LEFT JOIN `ipv6_networks` USING(`ipv6_network_id`)
WHERE `port_id` = ? AND `ipv6_network` NOT IN (?);", array($port['port_id'], $config['ignore_common_subnet'])) as $network_id)
{
$sql = "SELECT N.*, P.`port_id`, P.`device_id` FROM `ipv6_addresses` AS A, `ipv6_networks` AS N, `ports` AS P
WHERE A.`port_id` = P.`port_id` AND P.device_id != ?
AND A.`ipv6_network_id` = ? AND N.`ipv6_network_id` = A.`ipv6_network_id`
AND P.`ifAdminStatus` = 'up' AND A.`ipv6_origin` != 'linklayer' AND A.`ipv6_origin` != 'wellknown'";
$params = array($device['device_id'], $network_id);
foreach (dbFetchRows($sql, $params) as $new)
{
if ($cache['devices']['id'][$new['device_id']]['disabled'] && !$config['web_show_disabled']) { continue; }
$int_links[$new['port_id']] = $new['port_id'];
$int_links_v6[$new['port_id']][] = $new['ipv6_network'];
}
}
}
// Output contents of links array
foreach ($int_links as $int_link)
{
//r($int_link);
//r($int_links_phys);
$link_if = get_port_by_id_cache($int_link);
if (!device_permitted($link_if['device_id'])) { continue; } // Skip not permitted links
$link_dev = device_by_id_cache($link_if['device_id']);
$string .= $br;
if ($int_links_phys[$int_link])
{
$string .= generate_tooltip_link(NULL, NULL, 'Directly connected', $config['icon']['connected']) . ' ';
} else {
$string .= generate_tooltip_link(NULL, NULL, 'Same subnet', $config['icon']['network']) . ' ';
}
// for port_label_short - generate_port_link($link_if, NULL, NULL, TRUE, TRUE)
$string .= '<b>' . generate_port_link_short($link_if) . ' on ' . generate_device_link_short($link_dev) . '</b>';
if (isset($int_links_phys[$int_link]) && !is_numeric($int_links_phys[$int_link]))
{
$string .= '&nbsp;<span class="label">'.nicecase($int_links_phys[$int_link]).'</span>';
}
## FIXME -- do something fancy here.
if ($int_links_v6[$int_link]) { $string .= '&nbsp;'.overlib_link('', '<span class="label label-success">IPv6</span>', implode("<br />", $int_links_v6[$int_link]), NULL); }
if ($int_links_v4[$int_link]) { $string .= '&nbsp;'.overlib_link('', '<span class="label label-info">IPv4</span>', implode("<br />", $int_links_v4[$int_link]), NULL); }
$br = "<br />";
}
// Output content of unknown links array (where ports don't exist in our database, or they weren't matched)
foreach ($int_links_unknown as $int_link) {
//r($int_link);
$string .= generate_tooltip_link(NULL, NULL, 'Directly connected', $config['icon']['connected']) . ' ';
$string .= '<b><i>'.short_ifname($int_link['remote_port']).'</i></b> on ';
$text = '<div class="small" style="max-width: 500px;">';
if (!safe_empty($int_link['remote_platform'])) {
$text .= '<strong>' . $int_link['remote_platform'].'</strong><br />';
}
$text .= $int_link['remote_version'].'</div>';
$string .= '<i><b>'.generate_tooltip_link(NULL, $int_link['remote_hostname'], $text).'</b></i>';
$string .= '&nbsp;<span class="label">'.nicecase($int_link['protocol']).'</span><br />';
}
}
if (!isset($cache['ports_option']['pseudowires']) || in_array($port['port_id'], $cache['ports_option']['pseudowires'])) {
foreach (dbFetchRows("SELECT * FROM `pseudowires` WHERE `port_id` = ?", array($port['port_id'])) as $pseudowire) {
//`port_id`,`peer_device_id`,`peer_ldp_id`,`pwID`,`pwIndex`
# $pw_peer_dev = dbFetchRow("SELECT * FROM `devices` WHERE `device_id` = ?", array($pseudowire['peer_device_id']));
$pw_peer_int = dbFetchRow("SELECT * FROM `ports` AS I, `pseudowires` AS P WHERE I.`device_id` = ? AND P.`pwID` = ? AND P.`port_id` = I.`port_id`", array($pseudowire['peer_device_id'], $pseudowire['pwID']));
# $pw_peer_int = get_port_by_id_cache($pseudowire['peer_device_id']);
$pw_peer_dev = device_by_id_cache($pseudowire['peer_device_id']);
if (is_array($pw_peer_int))
{
humanize_port($pw_peer_int);
$string .= $br.'<i class="'.$config['icon']['cross-connect'].'"></i> <strong>' . generate_port_link_short($pw_peer_int) .' on '. generate_device_link_short($pw_peer_dev) . '</strong>';
} else {
$string .= $br.'<i class="'.$config['icon']['cross-connect'].'"></i> <strong> VC ' . $pseudowire['pwID'] .' on '. $pseudowire['peer_addr'] . '</strong>';
}
$string .= ' <span class="label">'.$pseudowire['pwPsnType'].'</span>';
$string .= ' <span class="label">'.$pseudowire['pwType'].'</span>';
$br = "<br />";
}
}
/** Disabled pending database rejigging to add it back
if (!isset($cache['ports_option']['ports_pagp']) || in_array($port['ifIndex'], $cache['ports_option']['ports_pagp']))
{
foreach (dbFetchRows("SELECT * FROM `ports` WHERE `pagpGroupIfIndex` = ? AND `device_id` = ?", array($port['ifIndex'], $device['device_id'])) as $member)
{
humanize_port($member);
$pagp[$device['device_id']][$port['ifIndex']][$member['ifIndex']] = TRUE;
$string .= $br.'<i class="'.$config['icon']['merge'].'"></i> <strong>' . generate_port_link($member) . ' [PAgP]</strong>';
$br = "<br />";
}
}
if ($port['pagpGroupIfIndex'] && $port['pagpGroupIfIndex'] != $port['ifIndex'])
{
$pagp[$device['device_id']][$port['pagpGroupIfIndex']][$port['ifIndex']] = TRUE;
$parent = dbFetchRow("SELECT * FROM `ports` WHERE `ifIndex` = ? and `device_id` = ?", array($port['pagpGroupIfIndex'], $device['device_id']));
humanize_port($parent);
$string .= $br.'<i class="'.$config['icon']['split'].'"></i> <strong>' . generate_port_link($parent) . ' [PAgP]</strong>';
$br = "<br />";
}
**/
if (!isset($cache['ports_option']['ports_stack_low']) ||
in_array($port['ifIndex'], $cache['ports_option']['ports_stack_low'])) {
foreach (dbFetchRows("SELECT * FROM `ports_stack` WHERE `port_id_low` = ? AND `device_id` = ? AND `ifStackStatus` = ?", [ $port['ifIndex'], $device['device_id'], 'active' ]) as $higher_if) {
if ($higher_if['port_id_high']) {
if (isset($pagp[$device['device_id']][$higher_if['port_id_high']][$port['ifIndex']])) { continue; } // Skip if same PAgP port
if ($this_port = get_port_by_index_cache($device['device_id'], $higher_if['port_id_high'])) {
$label = '';
if ($this_port['ifType'] === 'l2vlan') {
$label = '<span class="label label-primary">L2 VLAN</span> ';
} elseif ($this_port['ifType'] === 'l3ipvlan' || $this_port['ifType'] === 'l3ipxvlan') {
$label = '<span class="label label-info">L3 VLAN</span> ';
} elseif ($this_port['ifType'] === 'ieee8023adLag') {
$label = '<span class="label label-success">LAG</span> ';
} elseif (str_starts($this_port['port_label'], 'Stack')) {
$label = '<span class="label label-warning">STACK</span> ';
} else {
$label = '<span class="label label-default">'.$this_port['human_type'].'</span> ';
//r($this_port);
}
$string .= $br.'<i class="'.$config['icon']['split'].'"></i> <strong>' . generate_port_link($this_port) . '</strong> '.$label;
$br = "<br />";
}
}
}
}
if (!isset($cache['ports_option']['ports_stack_high']) ||
in_array($port['ifIndex'], $cache['ports_option']['ports_stack_high'])) {
foreach (dbFetchRows("SELECT * FROM `ports_stack` WHERE `port_id_high` = ? AND `device_id` = ? AND `ifStackStatus` = ?", [ $port['ifIndex'], $device['device_id'], 'active' ]) as $lower_if) {
if ($lower_if['port_id_low']) {
if (isset($pagp[$device['device_id']][$port['ifIndex']][$lower_if['port_id_low']])) { continue; } // Skip if same PAgP ports
if ($this_port = get_port_by_index_cache($device['device_id'], $lower_if['port_id_low'])) {
$string .= $br.'<i class="'.$config['icon']['merge'].'"></i> <strong>' . generate_port_link($this_port) . '</strong>';
$br = "<br />";
}
}
}
}
unset($int_links, $int_links_v6, $int_links_v4, $int_links_phys, $br);
$string .= '</td></tr>';
} // End Detailed View
// If we're showing graphs, generate the graph and print the img tags
if ($vars['graph'] === "etherlike")
{
$graph_file = get_port_rrdfilename($port, "dot3", TRUE);
} else {
$graph_file = get_port_rrdfilename($port, NULL, TRUE);
}
if ($vars['graph'] && is_file($graph_file))
{
$string .= '<tr><td colspan="'.$table_cols.'">';
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $port['port_id'];
$graph_array['type'] = 'port_'.$vars['graph'];
$string .= generate_graph_row($graph_array);
$string .= '</td></tr>';
}
return $string;
}
function print_port_minigraph($port, $graph_type = 'port_bits', $period = 'day') {
$port['graph_type'] = $graph_type;
$graph_array = [];
$graph_array['to'] = get_time();
$graph_array['from'] = get_time($period);
$graph_array['id'] = $port['port_id'];
$graph_array['type'] = $port['graph_type'];
$graph_array['width'] = 400; //100;
$graph_array['height'] = 150; //20;
$graph_array['bg'] = 'ffffff00';
$graph_array['legend'] = "no";
$graph_array['graph_only'] = "yes";
$graph_array_zoom = $graph_array;
$graph_array_zoom['height'] = "175";
$graph_array_zoom['width'] = "600";
unset($graph_array_zoom['legend'], $graph_array_zoom['graph_only']);
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['height'], $link_array['width']);
$link = generate_url($link_array);
echo '
<div class="box box-solid" style="float: left; margin-left: 10px; margin-bottom: 10px; width:302px; min-width: 302px; max-width:302px; min-height:158px; max-height:158;">
<div class="box-header with-border">
<a href="device/device=682/"><h3 class="box-title">'.escape_html($port['port_label_short']).'</h3></a>
</div>
<div class="box-body no-padding">
'.overlib_link($link, generate_graph_tag($graph_array), generate_graph_tag($graph_array_zoom), NULL).'
</div>
<div class="box-footer" style="padding: 0px 10px"><span style="font-size: 0.7em">'.short_port_descr($port['ifAlias']).'</span></div>
</div>';
}
// EOF

View File

@ -0,0 +1,329 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function build_printersupplies_query($vars)
{
$sql = 'SELECT * FROM `printersupplies`';
$sql .= ' WHERE 1' . generate_query_permitted(array('device'));
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'printersupplies.supply_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'printersupplies.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'printersupplies.device_id');
break;
case "supply":
case "supply_type";
$sql .= generate_query_values($value, 'printersupplies.supply_type');
break;
case "colour":
case "supply_colour";
$sql .= generate_query_values($value, 'supply_colour');
break;
case "descr":
case "supply_descr";
$sql .= generate_query_values($value, 'supply_descr', '%LIKE%');
break;
}
}
return $sql;
}
function print_printersupplies_table($vars)
{
$supplies = array();
foreach(dbFetchRows(build_printersupplies_query($vars)) as $supply)
{
global $cache;
if (isset($cache['devices']['id'][$supply['device_id']]))
{
$supply['hostname'] = $cache['devices']['id'][$supply['device_id']]['hostname'];
$supply['html_row_class'] = $cache['devices']['id'][$supply['device_id']]['html_row_class'];
$supplies[] = $supply;
}
}
$supplies = array_sort_by($supplies, 'hostname', SORT_ASC, SORT_STRING, 'supply_descr', SORT_ASC, SORT_STRING);
$supplies_count = count($supplies);
echo generate_box_open();
// Pagination
$pagination_html = pagination($vars, $supplies_count);
echo $pagination_html;
if ($vars['pageno'])
{
$supplies = array_chunk($supplies, $vars['pagesize']);
$supplies = $supplies[$vars['pageno'] - 1];
}
// End Pagination
if ($vars['view'] == "graphs")
{
$stripe_class = "table-striped-two";
} else {
$stripe_class = "table-striped";
}
// Allow the table to be printed headerless for use in some places.
if ($vars['headerless'] != TRUE)
{
echo('<table class="table ' . $stripe_class . ' table-condensed">');
echo(' <thead>');
echo '<tr class="strong">';
echo '<th class="state-marker"></th>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE)
{
echo(' <th style="width: 250px;">Device</th>');
}
echo '<th>Toner</th>';
if (!isset($vars['supply']))
{
echo '<th>Type</th>';
}
echo '<th></th>';
echo '<th>Level</th>';
echo '<th>Remaining</th>';
echo '</tr>';
echo '</thead>';
}
foreach($supplies as $supply)
{
print_printersupplies_row($supply, $vars);
}
echo("</table>");
echo generate_box_close();
echo $pagination_html;
}
function print_printersupplies_row($supply, $vars)
{
echo generate_printersupplies_row($supply, $vars);
}
function generate_printersupplies_row($supply, $vars)
{
$graph_type = "printersupply_usage";
$table_cols = 5;
$total = $supply['supply_capacity'];
$perc = $supply['supply_value'];
$graph_array['type'] = $graph_type;
$graph_array['id'] = $supply['supply_id'];
$graph_array['from'] = $GLOBALS['config']['time']['day'];
$graph_array['to'] = $GLOBALS['config']['time']['now'];
$graph_array['height'] = "20";
$graph_array['width'] = "80";
if ($supply['supply_colour'] != '')
{
$background = toner_to_colour($supply['supply_colour'], $perc);
} else {
$background = toner_to_colour($supply['supply_descr'], $perc);
}
/// FIXME - popup for printersupply entity.
$output = '<tr class="' . $supply['html_row_class'] . '">';
$output .= '<td class="state-marker"></td>';
if ($vars['popup'] == TRUE )
{
$output .= '<td style="width: 40px; text-align: center;">'.get_icon($GLOBALS['config']['entities']['printersupply']['icon']).'</td>';
} else {
//$output .= '<td style="width: 1px;"></td>';
}
if ($vars['page'] != "device" && $vars['popup'] != TRUE)
{
$output .= '<td class="entity">' . generate_device_link($supply) . '</td>';
$table_cols++;
}
$output .= '<td class="entity">' . generate_entity_link('printersupply', $supply) . '</td>';
if (!isset($vars['supply']))
{
$output .= '<td><span class="label">' . nicecase($supply['supply_type']) . '</label></td>';
}
$output .= '<td style="width: 70px;">' . generate_graph_popup($graph_array) . '</td>';
$output .= '<td style="width: 200px;">' . print_percentage_bar(400, 20, $perc, $perc . '%', 'ffffff', $background['right'], NULL, "ffffff", $background['left']) . '</td>';
if ($vars['popup'] != TRUE)
{
$output .= '<td style="width: 50px; text-align: right;"><span class="label">' . $perc . '%</span></td>';
}
$output .= '</tr>';
if ($vars['view'] == "graphs")
{
$output .= '<tr class="' . $supply['html_row_class'] . '">';
$output .= '<td class="state-marker"></td>';
$output .= '<td colspan='.$table_cols.'>';
unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $supply['supply_id'];
$graph_array['type'] = $graph_type;
$output .= generate_graph_row($graph_array, TRUE);
$output .= "</td></tr>";
} # endif graphs
return $output;
}
function print_printersupplies_form($vars, $single_device = FALSE)
{
global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `printersupplies`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
//$sensor_permitted = generate_query_permitted(array('device', 'sensor'));
$form['row'][0]['supply_descr'] = array(
'type' => 'text',
'placeholder' => 'Toner',
'width' => '100%', //'180px',
'grid' => 3,
'value' => $vars['status_descr']);
foreach ([ 'supply_colour' => 'Colour', 'supply_type' => 'Type' ] as $param => $param_name) {
$sql = 'SELECT DISTINCT `'.$param.'` FROM `printersupplies` WHERE 1' . $GLOBALS['cache']['where']['devices_permitted'];
if ($entries = dbFetchColumn($sql)) {
asort($entries);
}
foreach ($entries as $entry) {
if (safe_empty($entry)) { $entry = OBS_VAR_UNSET; }
$name = nicecase($entry);
$form_items[$param][$entry] = $name;
}
$form['row'][0][$param] = array(
'type' => 'multiselect',
'name' => $param_name,
'width' => '100%', //'180px',
'grid' => $param === 'supply_colour' ? 1: 2,
'value' => $vars[$param],
'values' => $form_items[$param]);
}
// Groups
foreach (get_type_groups('printersupply') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][0]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][0]['search'] = array(
'type' => 'submit',
'grid' => 2,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE,
);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Sensors',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['group'] = $form['row'][0]['group'];
$panel_form['row'][1]['supply_colour'] = $form['row'][0]['supply_colour'];
$panel_form['row'][1]['supply_type'] = $form['row'][0]['supply_type'];
//$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
//$panel_form['row'][2]['group'] = $form['row'][1]['group'];
$panel_form['row'][3]['supply_descr'] = $form['row'][0]['supply_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][0]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,338 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function generate_processor_query($vars)
{
$sql = "SELECT * FROM `processors`";
if(!isset($vars['sort']) || $vars['sort'] == 'hostname' || $vars['sort'] == 'device' || $vars['sort'] == 'device_id')
{
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
}
$sql .= ' WHERE 1' . generate_query_permitted(array('device'));
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'processor_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'processors.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'processors.device_id');
break;
case "descr":
case "processor_descr";
$sql .= generate_query_values($value, 'processor_descr', '%LIKE%');
break;
}
}
switch ($vars['sort_order'])
{
case 'descr':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch($vars['sort'])
{
case 'usage':
$sql .= ' ORDER BY `processor_usage` '.$sort_neg;
break;
case 'descr':
$sql .= ' ORDER BY `processor_descr` '.$sort_order;
break;
default:
$sql .= ' ORDER BY `hostname` '.$sort_order.', `processor_descr` '.$sort_order;
break;
}
return $sql;
}
function print_processor_table($vars)
{
global $cache;
$sql = generate_processor_query($vars);
$processors = array();
foreach(dbFetchRows($sql) as $proc)
{
if (isset($cache['devices']['id'][$proc['device_id']]))
{
$proc['hostname'] = $cache['devices']['id'][$proc['device_id']]['hostname'];
$proc['html_row_class'] = $cache['devices']['id'][$proc['device_id']]['html_row_class'];
$processors[] = $proc;
}
}
$processors_count = count($processors);
// Pagination
$pagination_html = pagination($vars, $processors_count);
echo $pagination_html;
if ($vars['pageno'])
{
$processors = array_chunk($processors, $vars['pagesize']);
$processors = $processors[$vars['pageno']-1];
}
// End Pagination
echo generate_box_open();
print_processor_table_header($vars);
foreach($processors as $processor)
{
print_processor_row($processor, $vars);
}
echo("</tbody></table>");
echo generate_box_close();
echo $pagination_html;
}
function print_processor_table_header($vars)
{
if ($vars['view'] == "graphs")
{
$table_class = OBS_CLASS_TABLE_STRIPED_TWO;
} else {
$table_class = OBS_CLASS_TABLE_STRIPED;
}
echo('<table class="' . $table_class . '">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'device' => array('Device', 'style="width: 200px;"'),
'descr' => array('Processor'),
array('', 'style="width: 100px;"'),
'usage' => array('Usage', 'style="width: 250px;"'),
);
if ($vars['page'] == "device")
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_processor_row($processor, $vars)
{
echo generate_processor_row($processor, $vars);
}
function generate_processor_row($processor, $vars)
{
global $config;
$table_cols = 4;
if ($vars['page'] != "device" && $vars['popup'] != TRUE) { $table_cols++; } // Add a column for device.
// FIXME should that really be done here? :-)
// FIXME - not it shouldn't. we need some per-os rewriting on discovery-time.
$text_descr = rewrite_entity_name($processor['processor_descr'], 'processor');
//$text_descr = $processor['processor_descr'];
//$text_descr = str_replace("Routing Processor", "RP", $text_descr);
//$text_descr = str_replace("Switching Processor", "SP", $text_descr);
//$text_descr = str_replace("Sub-Module", "Module ", $text_descr);
//$text_descr = str_replace("DFC Card", "DFC", $text_descr);
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $processor['processor_id'];
$graph_array['type'] = 'processor_usage';
$graph_array['legend'] = "no";
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link_graph = generate_url($link_array);
$link = generate_url(array("page" => "device", "device" => $processor['device_id'], "tab" => "health", "metric" => 'processor'));
$overlib_content = generate_overlib_content($graph_array, $processor['hostname'] ." - " . $text_descr);
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
$mini_graph = generate_graph_tag($graph_array);
$perc = round($processor['processor_usage']);
$background = get_percentage_colours($perc);
$processor['html_row_class'] = $background['class'];
$row = '<tr class="' . $processor['html_row_class'] . '">
<td class="state-marker"></td>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE) { $row .= '<td class="entity">' . generate_device_link($processor) . '</td>'; }
$row .= ' <td class="entity">'.generate_entity_link('processor', $processor).'</td>
<td>'.overlib_link($link_graph, $mini_graph, $overlib_content).'</td>
<td><a href="'.$link_graph.'">
'.print_percentage_bar (400, 20, $perc, $perc."%", "ffffff", $background['left'], (100 - $perc)."%" , "ffffff", $background['right']).'
</a>
</td>
</tr>
';
if ($vars['view'] == "graphs" || in_array($processor['processor_id'], (array)$vars['processor_id']))
{
$vars['graph'] = "usage";
$row .= '<tr class="' . $processor['html_row_class'] . '">';
$row .= '<td class="state-marker"></td>';
$row .= '<td colspan='.$table_cols.'>';
unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $processor['processor_id'];
$graph_array['type'] = 'processor_'.$vars['graph'];
$row .= generate_graph_row($graph_array, TRUE);
$row .= '</td></tr>';
} # endif graphs
return $row;
}
function print_processor_form($vars, $single_device = FALSE)
{
//global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `processors`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
//$sensor_permitted = generate_query_permitted(array('device', 'sensor'));
$form['row'][0]['processor_descr'] = array(
'type' => 'text',
'placeholder' => 'Processor',
'width' => '100%', //'180px',
'grid' => 6,
'value' => $vars['processor_descr']);
// Groups
foreach (get_type_groups('storage') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][0]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][0]['search'] = array(
'type' => 'submit',
'grid' => 2,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE,
);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Processors',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['group'] = $form['row'][0]['group'];
//$panel_form['row'][1]['supply_colour'] = $form['row'][0]['supply_colour'];
//$panel_form['row'][1]['supply_type'] = $form['row'][0]['supply_type'];
//$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
//$panel_form['row'][2]['group'] = $form['row'][1]['group'];
$panel_form['row'][3]['processor_descr'] = $form['row'][0]['processor_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][0]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,355 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
function generate_pseudowire_query($vars)
{
$sql = 'SELECT * FROM `pseudowires` ';
$sql .= ' WHERE 1';
// Build query
foreach ($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'pseudowire_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'device_id');
break;
case "port":
case "port_id":
$sql .= generate_query_values($value, 'port_id');
break;
case "id":
$sql .= generate_query_values($value, 'pseudowire_id');
break;
case "pwid":
case "pwID":
$sql .= generate_query_values($value, 'pwID');
break;
case "pwtype":
$sql .= generate_query_values($value, 'pwType');
break;
case "psntype":
$sql .= generate_query_values($value, 'pwPsnType');
break;
case "peer_id":
$sql .= generate_query_values($value, 'peer_device_id');
break;
case "peer_addr":
$sql .= generate_query_values($value, 'peer_addr');
break;
case "event":
$sql .= generate_query_values($value, 'event');
break;
}
}
$sql .= $GLOBALS['cache']['where']['devices_permitted'];
return $sql;
}
function print_pseudowire_table_header($vars)
{
if ($vars['view'] == "graphs" || isset($vars['graph']) || isset($vars['id']))
{
$table_class = OBS_CLASS_TABLE_STRIPED_TWO;
} else {
$table_class = OBS_CLASS_TABLE_STRIPED;
}
echo('<table class="' . $table_class . '">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'pwid' => array('pwID', 'style="width: 60px; text-align: right;"'),
'pwtype' => array('Type / PSN Type', 'style="width: 100px;"'),
'device' => array('Local Device', 'style="width: 180px;"'),
'port' => array('Local Port', 'style="width: 100px;"'),
array(NULL, 'style="width: 20px;"'), // arrow icon
'peer_addr' => array('Remote Peer', 'style="width: 180px;"'),
'peer_port' => array('Remote Port', 'style="width: 100px;"'),
array('History', 'style="width: 100px;"'),
'last_change' => array('Last&nbsp;changed', 'style="width: 60px;"'),
'event' => array('Event', 'style="width: 60px; text-align: right;"'),
'status' => array('Status', 'style="width: 60px; text-align: right;"'),
'uptime' => array('Uptime', 'style="width: 80px;"'),
);
if ($vars['page'] == "device" || $vars['popup'] == TRUE)
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function get_pseudowire_table($vars)
{
$sql = generate_pseudowire_query($vars);
$entries = array();
foreach (dbFetchRows($sql) as $entry)
{
if (!isset($GLOBALS['cache']['devices']['id'][$entry['device_id']])) { continue; }
// Device hostname
$entry['hostname'] = $GLOBALS['cache']['devices']['id'][$entry['device_id']]['hostname'];
// Remote Peer
$peer_addr = $entry['peer_addr'];
$peer_addr_type = get_ip_version($peer_addr);
if ($peer_addr_type && $entry['peer_device_id'])
{
if ($peer_addr_type == 6)
{
$peer_addr = Net_IPv6::uncompress($peer_addr, TRUE);
}
$peer_addr_type = 'ipv'.$peer_addr_type;
//$entry['peer_addr'] = $peer_addr;
//$entry['peer_addr_type'] = $peer_addr_type;
if (!is_array($cache_pseudowires['ips'][$peer_addr]))
{
$cache_pseudowires['ips'][$peer_addr]['port_id'] = dbFetchCell('SELECT `port_id` FROM `'.$peer_addr_type.'_addresses` WHERE `'.$peer_addr_type.'_address` = ? '.generate_query_values($GLOBALS['cache']['ports']['pseudowires'], 'port_id').' LIMIT 1;', array($peer_addr));
if (!is_numeric($cache_pseudowires['ips'][$peer_addr]['port_id']))
{
// Separate entry for find correct port
$cache_pseudowires['ips'][$peer_addr]['port_id_fix'] = dbFetchCell('SELECT `port_id` FROM `'.$peer_addr_type.'_addresses` WHERE `'.$peer_addr_type.'_address` = ? '.$GLOBALS['cache']['where']['ports_permitted'].' LIMIT 1;', array($peer_addr));
}
//$cache_pseudowires['ips'][$peer_addr]['host'] = $entry['reverse_dns'];
}
$entry['peer_port_id'] = $cache_pseudowires['ips'][$peer_addr]['port_id'];
if (is_numeric($cache_pseudowires['ips'][$peer_addr]['port_id_fix']))
{
// If we found port on remote device, than both devices in DB and will try to fix real port
$peer_port_tmp = get_port_by_id_cache($cache_pseudowires['ips'][$peer_addr]['port_id_fix']);
$peer_port_fix = dbFetchCell('SELECT `port_id` FROM `pseudowires` WHERE `device_id` = ? AND `pwID` = ? LIMIT 1;', array($peer_port_tmp['device_id'], $entry['pwID']));
if (is_numeric($peer_port_fix))
{
$entry['peer_port_id'] = $peer_port_fix;
} else {
$entry['peer_port_id'] = $cache_pseudowires['ips'][$peer_addr]['port_id_fix'];
}
}
//r($entry['peer_port_id']);
if ($entry['peer_port_id'])
{
$entry['peer_port'] = get_port_by_id_cache($entry['peer_port_id']);
//r($entry['peer_port']);
$entry['peer_device_id'] = $entry['peer_port']['device_id'];
//r($entry['peer_device_id']);
$entry['peer_device'] = device_by_id_cache($entry['peer_device_id']);
}
}
$entry['hostname'] = $GLOBALS['cache']['devices']['id'][$entry['device_id']]['hostname']; // Attach hostname for sorting
$entries[] = $entry;
}
// Sorting
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = SORT_DESC;
$sort_neg = SORT_ASC;
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = SORT_ASC;
$sort_neg = SORT_DESC;
}
switch ($vars['sort'])
{
case 'device':
$entries = array_sort_by($entries, 'hostname', $sort_order, SORT_STRING);
break;
case 'pwid':
$entries = array_sort_by($entries, 'pwID', $sort_order, SORT_NUMERIC);
break;
case 'pwtype':
$entries = array_sort_by($entries, 'pwType', $sort_order, SORT_STRING, 'pwPsnType', $sort_order, SORT_STRING);
//$pws = array_sort_by($pws, 'pwType', $sort_order, SORT_STRING);
break;
case 'peer_addr':
$entries = array_sort_by($entries, 'peer_addr', $sort_order, SORT_NUMERIC);
break;
case 'event':
$entries = array_sort_by($entries, 'event', $sort_order, SORT_STRING);
break;
case 'uptime':
$entries = array_sort_by($entries, 'pwUptime', $sort_order, SORT_NUMERIC);
break;
case 'last_change':
$entries = array_sort_by($entries, 'last_change', $sort_neg, SORT_NUMERIC);
break;
case 'status':
$entries = array_sort_by($entries, 'pwOperStatus', $sort_order, SORT_STRING);
break;
default:
// Not sorted
}
return $entries;
}
function print_pseudowire_table($vars)
{
$pws = get_pseudowire_table($vars);
$pws_count = count($pws);
// Pagination
$pagination_html = pagination($vars, $pws_count);
echo $pagination_html;
if ($vars['pageno'])
{
$pws = array_chunk($pws, $vars['pagesize']);
$pws = $pws[$vars['pageno'] - 1];
}
// End Pagination
echo generate_box_open();
print_pseudowire_table_header($vars);
foreach ($pws as $pw)
{
print_pseudowire_row($pw, $vars);
}
echo '</tbody></table>';
echo generate_box_close();
echo $pagination_html;
}
function humanize_pseudowire(&$pw)
{
global $config;
if (isset($pw['humanized'])) { return; }
if (isset($config['entity_events'][$pw['event']]))
{
$pw = array_merge($pw, $config['entity_events'][$pw['event']]);
} else {
$pw['event_class'] = 'label label-primary';
$pw['row_class'] = '';
}
if ($pw['pwRowStatus'] != 'active')
{
$pw['row_class'] = 'ignore';
}
$device = &$GLOBALS['cache']['devices']['id'][$pw['device_id']];
if ((isset($device['status']) && !$device['status']) || (isset($device['disabled']) && $device['disabled']))
{
$pw['row_class'] = 'error';
}
$translate = entity_type_translate_array('pseudowire');
$pw['graph'] = $translate['graph']['type']; // Default graph
$pw['humanized'] = TRUE;
}
function print_pseudowire_row($pw, $vars)
{
echo generate_pseudowire_row($pw, $vars);
}
function generate_pseudowire_row($pw, $vars)
{
global $config;
humanize_pseudowire($pw);
$table_cols = 11;
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $pw['pseudowire_id'];
$graph_array['type'] = $pw['graph'];
$graph_array['legend'] = "no";
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
if ($pw['event'] && $pw['pwOperStatus'])
{
$mini_graph = generate_graph_tag($graph_array);
} else {
// Do not show "Draw Error" minigraph
$mini_graph = '';
}
$out = '<tr class="' . $pw['row_class'] . '"><td class="state-marker"></td>';
$out .= '<td class="entity" style="text-align: right;">'. generate_entity_link('pseudowire', $pw, NULL, NULL, TRUE, TRUE) .'</td>';
$out .= '<td>'. nicecase($pw['pwType']) . '/' . nicecase($pw['pwPsnType']) .'</td>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE)
{
$out .= '<td class="entity">' . generate_device_link($pw, NULL, array('tab' => 'pseudowires')) . '</td>';
$table_cols++;
}
$out .= '<td class="entity">'. generate_entity_link('port', $pw['port_id']) .'</td>';
$out .= '<td><span class="text-success"><i class="glyphicon glyphicon-arrow-right"></i></span></td>';
if ($pw['peer_port_id'])
{
$out .= '<td class="entity">' . generate_entity_link('device', $pw['peer_device_id']) . '</td>';
$out .= '<td class="entity">' . generate_entity_link('port', $pw['peer_port_id']) . '</td>';
} else {
$out .= '<td class="entity">'. generate_popup_link('ip', $pw['peer_addr']) .'</td>';
$out .= '<td>'. $pw['pwRemoteIfString'] .'</td>';
}
$out .= '<td>' . generate_entity_link('pseudowire', $pw, $mini_graph, NULL, FALSE) . '</td>';
$out .= '<td style="white-space: nowrap">' . generate_tooltip_link(NULL, format_uptime(($config['time']['now'] - $pw['last_change']), 'short-2') . ' ago', format_unixtime($pw['last_change'])) . '</td>';
$out .= '<td style="text-align: right;"><strong>' . generate_tooltip_link('', $pw['event'], $pw['event_descr'], $pw['event_class']) . '</strong></td>';
$out .= '<td style="text-align: right;"><strong>' . generate_tooltip_link('', $pw['pwOperStatus'], $pw['event_descr'], $pw['event_class']) . '</strong></td>';
$out .= '<td>' . format_uptime($pw['pwUptime'], 'short-2') . '</td>';
$out .= '</tr>';
if ($vars['graph'] || $vars['view'] == "graphs" || $vars['id'] == $pw['pseudowire_id'])
{
// If id set in vars, display only specific graphs
$graph_array = array();
$graph_array['type'] = ($vars['graph'] ? $vars['graph'] : $pw['graph']);
$graph_array['id'] = $pw['pseudowire_id'];
$out .= '<tr class="' . $pw['row_class'] . '">';
$out .= ' <td class="state-marker"></td>';
$out .= ' <td colspan="'.$table_cols.'">';
$out .= generate_graph_row($graph_array, TRUE);
$out .= ' </td>';
$out .= '</tr>';
}
return $out;
}
// EOF

View File

@ -0,0 +1,606 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
/**
* Humanize sensor.
*
* Returns a the $sensor array with processed information:
* sensor_state (TRUE: state sensor, FALSE: normal sensor)
* human_value, sensor_symbol, state_name, state_event, state_class
*
* @param array $sensor
* @return array $sensor
*
*/
// TESTME needs unit testing
function humanize_sensor(&$sensor) {
global $config, $cache;
// Exit if already humanized
if ($sensor['humanized']) { return; }
$sensor['sensor_symbol'] = $GLOBALS['config']['sensor_types'][$sensor['sensor_class']]['symbol'];
$sensor['sensor_format'] = (string)$GLOBALS['config']['sensor_types'][$sensor['sensor_class']]['format'];
$sensor['state_class'] = ''; //'text-success';
// Generate "pretty" thresholds
if (is_numeric($sensor['sensor_limit_low'])) {
$sensor_threshold_low = format_value($sensor['sensor_limit_low'], $sensor['sensor_format']) . $sensor['sensor_symbol'];
} else {
$sensor_threshold_low = "&infin;";
}
if (is_numeric($sensor['sensor_limit_low_warn'])) {
$sensor_warn_low = format_value($sensor['sensor_limit_low_warn'], $sensor['sensor_format']) . $sensor['sensor_symbol'];
} else {
$sensor_warn_low = NULL;
}
if ($sensor_warn_low) { $sensor_threshold_low = $sensor_threshold_low . " (".$sensor_warn_low.")"; }
if (is_numeric($sensor['sensor_limit'])) {
$sensor_threshold_high = format_value($sensor['sensor_limit'], $sensor['sensor_format']) . $sensor['sensor_symbol'];
} else {
$sensor_threshold_high = "&infin;";
}
if (is_numeric($sensor['sensor_limit_warn'])) {
$sensor_warn_high = format_value($sensor['sensor_limit_warn'], $sensor['sensor_format']) . $sensor['sensor_symbol'];
} else {
$sensor_warn_high = "&infin;";
}
if ($sensor_warn_high) { $sensor_threshold_high = "(".$sensor_warn_high.") " . $sensor_threshold_high; }
$sensor['sensor_thresholds'] = $sensor_threshold_low . ' - ' . $sensor_threshold_high;
// generate pretty value
if (!is_numeric($sensor['sensor_value'])) {
$sensor['human_value'] = 'NaN';
$sensor['sensor_symbol'] = '';
} else {
$sensor['human_value'] = format_value($sensor['sensor_value'], $sensor['sensor_format'], 2, 4);
}
if (isset($config['entity_events'][$sensor['sensor_event']])) {
$sensor = array_merge($sensor, $config['entity_events'][$sensor['sensor_event']]);
} else {
$sensor['event_class'] = 'label label-primary';
$sensor['row_class'] = '';
}
if (device_is_ignored($sensor['device_id']) &&
($sensor['row_class'] === "error" || $sensor['row_class'] === "warning")) {
$sensor['row_class'] = 'suppressed';
}
if ($sensor['sensor_deleted']) {
$sensor['row_class'] = 'disabled';
}
/* We shouldn't pass through the parent status.
$device = &$GLOBALS['cache']['devices']['id'][$sensor['device_id']];
if ((isset($device['status']) && !$device['status']) || (isset($device['disabled']) && $device['disabled']))
{
//$sensor['row_class'] = 'error';
}
*/
// Set humanized entry in the array so we can tell later
$sensor['humanized'] = TRUE;
}
function build_sensor_query($vars, $query_count = FALSE) {
if ($query_count) {
$sql = "SELECT COUNT(*) FROM `sensors`";
} else {
$sql = "SELECT * FROM `sensors`";
if ($vars['sort'] === 'hostname' || $vars['sort'] === 'device' || $vars['sort'] === 'device_id') {
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
}
}
$sql .= " WHERE `sensor_deleted` = 0";
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'sensors.sensor_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'sensors.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'sensors.device_id');
break;
case "id":
case "sensor_id":
$sql .= generate_query_values($value, 'sensors.sensor_id');
break;
case "entity_id":
$sql .= generate_query_values($value, 'sensors.measured_entity');
break;
case "entity_type":
$sql .= generate_query_values($value, 'sensors.measured_class');
break;
case 'entity_state':
case "measured_state":
$sql .= build_entity_measured_where('sensor', ['measured_state' => $value]);
break;
case "metric":
// old metric param not allow array
if (!isset($GLOBALS['config']['sensor_types'][$value])) {
break;
}
case 'class':
case "sensor_class":
$sql .= generate_query_values($value, 'sensor_class');
break;
case "descr":
case "sensor_descr":
$sql .= generate_query_values($value, 'sensors.sensor_descr', '%LIKE%');
break;
case "type":
case "sensor_type":
$sql .= generate_query_values($value, 'sensor_type', '%LIKE%');
break;
case "event":
case "sensor_event":
$sql .= generate_query_values($value, 'sensor_event');
break;
}
}
$sql .= generate_query_permitted(array('device', 'sensor'));
// If need count, just return sql without sorting
if ($query_count) {
return $sql;
}
switch ($vars['sort_order']) {
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch($vars['sort'])
{
case 'device':
$sql .= ' ORDER BY `hostname` '.$sort_order;
break;
case 'descr':
case 'event':
$sql .= ' ORDER BY `sensor_'.$vars['sort'].'` '.$sort_order;
break;
case 'value':
case 'last_change':
$sql .= ' ORDER BY `sensor_'.$vars['sort'].'` '.$sort_order;
break;
default:
// $sql .= ' ORDER BY `hostname` '.$sort_order.', `sensor_descr` '.$sort_order;
}
if (isset($vars['pageno'])) {
$start = $vars['pagesize'] * ($vars['pageno'] - 1);
$sql .= ' LIMIT '.$start.','.$vars['pagesize'];
}
return $sql;
}
function print_sensor_table($vars, $default_order = []) {
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$sql = build_sensor_query($vars);
//r($vars);
//r($sql);
$sensors = array();
//foreach(dbFetchRows($sql, NULL, TRUE) as $sensor)
foreach(dbFetchRows($sql) as $sensor) {
//if (isset($GLOBALS['cache']['devices']['id'][$sensor['device_id']]))
//{
$sensor['hostname'] = $GLOBALS['cache']['devices']['id'][$sensor['device_id']]['hostname'];
$sensors[$sensor['sensor_class']][] = $sensor;
//}
}
//r($sensors);
// order dom sensors always by temperature, voltage, current, dbm, power
$order = [];
if (safe_count($sensors)) {
if (safe_count($default_order)) {
$types = array_keys($sensors);
//r($types);
$order = array_intersect($default_order, $types);
$order = array_merge($order, array_diff($types, $order));
//r($order);
} else {
$order = array_keys($sensors);
}
}
//$sensors_count = count($sensors); // This is count incorrect, when pagination used!
//$sensors_count = dbFetchCell(build_sensor_query($vars, TRUE), NULL, TRUE);
$sensors_count = dbFetchCell(build_sensor_query($vars, TRUE));
// Pagination
$pagination_html = pagination($vars, $sensors_count);
echo $pagination_html;
echo generate_box_open();
print_sensor_table_header($vars);
foreach ($order as $type) {
foreach ($sensors[$type] as $sensor) {
print_sensor_row($sensor, $vars);
}
}
echo("</tbody></table>");
echo generate_box_close();
echo $pagination_html;
}
function print_sensor_table_header($vars) {
if ($vars['view'] === "graphs" || get_var_true($vars['graph']) || isset($vars['id'])) {
$stripe_class = "table-striped-two";
} else {
$stripe_class = "table-striped";
}
echo('<table class="table ' . $stripe_class . ' table-condensed ">' . PHP_EOL);
$cols = [];
$cols[] = array(NULL, 'class="state-marker"');
$cols['device'] = array('Device', 'style="width: 250px;"');
//$cols[] = array(NULL, 'class="no-width"'); // Measured entity link
$cols['descr'] = array('Description');
$cols['class'] = array('Class', 'style="width: 100px;"');
$cols['mib'] = array('MIB::Object');
$cols[] = array('Thresholds', 'style="width: 100px;"');
$cols[] = array('History');
$cols['last_change'] = array('Last&nbsp;changed', 'style="width: 80px;"');
$cols['event'] = array('Event', 'style="width: 60px; text-align: right;"');
$cols['value'] = array('Value', 'style="width: 80px; text-align: right;"');
if ($vars['page'] == "device") { unset($cols['device']); }
if ($vars['page'] != "device" || $vars['tab'] == "overview") { unset($cols['mib']); unset($cols['object']); }
if (!$vars['show_class']) { unset($cols['class']); }
if ($vars['tab'] == "overview") { unset($cols[2]); } // Thresholds
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_sensor_row($sensor, $vars)
{
echo generate_sensor_row($sensor, $vars);
}
function generate_sensor_row($sensor, $vars)
{
global $config;
humanize_sensor($sensor);
$table_cols = 4;
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $sensor['sensor_id'];
$graph_array['type'] = "sensor_graph";
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
if ($sensor['sensor_event'] && is_numeric($sensor['sensor_value']))
{
$mini_graph = generate_graph_tag($graph_array);
} else {
// Do not show "Draw Error" minigraph
$mini_graph = '';
}
$row = '
<tr class="'.$sensor['row_class'].'">
<td class="state-marker"></td>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE)
{
$row .= ' <td class="entity">' . generate_device_link($sensor) . '</td>' . PHP_EOL;
$table_cols++;
}
// Measured link & icon
/* Disabled because it breaks the overview box layout
$row .= ' <td style="padding-right: 0px;" class="no-width vertical-align">'; // minify column if empty
if ($vars['entity_icon']) // this used for entity popup
{
$row .= get_icon($config['sensor_types'][$sensor['sensor_class']]['icon']);
}
else if ($sensor['measured_entity'] &&
(!isset($vars['measured_icon']) || $vars['measured_icon'])) // hide measured icon if not required
{
//$row .= generate_entity_link($sensor['measured_class'], $sensor['measured_entity'], get_icon($sensor['measured_class']));
$row .= generate_entity_icon_link($sensor['measured_class'], $sensor['measured_entity']);
}
$row .= '</td>';
$table_cols++;
*/
$row .= ' <td class="entity">' . generate_entity_link("sensor", $sensor) . '</td>';
$table_cols++;
if ($vars['show_class'])
{
$row .= ' <td>' . nicecase($sensor['sensor_class']). '</td>' . PHP_EOL;
$table_cols++;
}
// FIXME -- Generify this. It's not just for sensors.
if ($vars['page'] === "device" && $vars['tab'] !== "overview") {
$row .= ' <td>' . (!safe_empty($sensor['sensor_mib']) ? '<a href="'.OBSERVIUM_MIBS_URL.'/'.$sensor['sensor_mib'].'/" target="_blank">' .nicecase($sensor['sensor_mib']) .'</a>' : '') .
( ( !safe_empty($sensor['sensor_mib']) && !safe_empty($sensor['sensor_object'])) ? '::' : '') .
(!safe_empty($sensor['sensor_mib']) ? '<a href="'.OBSERVIUM_MIBS_URL.'/'.$sensor['sensor_mib'].'/#'.$sensor['sensor_object'].'" target="_blank">' .$sensor['sensor_object'] .'</a>' : '') .
'.'.$sensor['sensor_index'].'</td>' . PHP_EOL;
$table_cols++;
}
if ($vars['tab'] !== 'overview') {
$sensor_thresholds_class = $sensor['sensor_custom_limit'] ? ' label-suppressed' : '';
$sensor_thresholds = $sensor['sensor_custom_limit'] ? generate_tooltip_link(NULL, $sensor['sensor_thresholds'], 'Custom thresholds') : $sensor['sensor_thresholds'];
$row .= ' <td><span class="label' . $sensor_thresholds_class . '">' . $sensor_thresholds . '</span></td>' . PHP_EOL;
$table_cols++;
}
$row .= ' <td style="width: 90px; text-align: right;">' . generate_entity_link('sensor', $sensor, $mini_graph, NULL, FALSE) . '</td>';
if ($vars['tab'] !== 'overview') {
$row .= ' <td style="white-space: nowrap">' . ($sensor['sensor_last_change'] == '0' ? 'Never' : generate_tooltip_link(NULL, format_uptime(($config['time']['now'] - $sensor['sensor_last_change']), 'short-2') . ' ago', format_unixtime($sensor['sensor_last_change']))) . '</td>';
$table_cols++;
$row .= ' <td style="text-align: right;"><strong>' . generate_tooltip_link('', $sensor['sensor_event'], $sensor['event_descr'], $sensor['event_class']) . '</strong></td>';
$table_cols++;
}
$sensor_tooltip = $sensor['event_descr'];
// Append value in alternative units to tooltip
if (isset($config['sensor_types'][$sensor['sensor_class']]['alt_units']))
{
foreach (value_to_units($sensor['sensor_value'],
$config['sensor_types'][$sensor['sensor_class']]['symbol'],
$sensor['sensor_class'],
$config['sensor_types'][$sensor['sensor_class']]['alt_units']) as $unit => $unit_value)
{
if (is_numeric($unit_value)) { $sensor_tooltip .= "<br />${unit_value}${unit}"; }
}
}
$row .= ' <td style="width: 80px; text-align: right;"><strong>' . generate_tooltip_link('', $sensor['human_value'] . $sensor['sensor_symbol'], $sensor_tooltip, $sensor['event_class']) . '</strong>
</tr>' . PHP_EOL;
if ($vars['view'] == "graphs" || $vars['id'] == $sensor['sensor_id']) { $vars['graph'] = "graph"; }
if ($vars['graph'])
{
$row .= '
<tr class="'.$sensor['row_class'].'">
<td class="state-marker"></td>
<td colspan="'.$table_cols.'">';
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $sensor['sensor_id'];
$graph_array['type'] = 'sensor_'.$vars['graph'];
$row .= generate_graph_row($graph_array, TRUE);
$row .= '</td></tr>';
} # endif graphs
return $row;
}
function print_sensor_form($vars, $single_device = FALSE)
{
global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `sensors`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
$sensor_permitted = generate_query_permitted(array('device', 'sensor'));
foreach ([ 'sensor_class' => 'Sensor Class', 'sensor_event' => 'Sensor Event' ] as $param => $param_name)
{
$sql = 'SELECT DISTINCT `'.$param.'` FROM `sensors` WHERE `sensor_deleted` = ?' . $sensor_permitted;
if ($entries = dbFetchColumn($sql, [ 0 ])) {
asort($entries);
}
foreach ($entries as $entry)
{
if (safe_empty($entry)) { $entry = OBS_VAR_UNSET; }
if ($param === 'sensor_class') {
$name = nicecase($entry);
if (isset($config['sensor_types'][$entry]['icon']))
{
$name = ['name' => $name, 'icon' => $config['sensor_types'][$entry]['icon']];
} else {
$name = ['name' => $name, 'icon' => $config['icon']['sensor']];
}
} else {
$name = $entry;
}
$form_items[$param][$entry] = $name;
}
// Alternative param name, ie event
$short_param = str_replace('sensor_', '', $param);
if (!isset($vars[$param]) && isset($vars[$short_param]))
{
$vars[$param] = $vars[$short_param];
}
$form['row'][0][$param] = array(
'type' => 'multiselect',
'name' => $param_name,
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars[$param],
'values' => $form_items[$param]);
}
// Currently unused, just dumb space
$form['row'][0]['sensor_value'] = array(
'type' => 'hidden',
'name' => 'Value',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['sensor_value']);
// Measured entities
$form['row'][0]['measured_state'] = array(
'type' => 'multiselect',
'name' => 'Measured State',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['measured_state'],
'values' => ['none' => ['name' => 'Without Measure', 'icon' => $config['icon']['filter']],
'up' => ['name' => 'Measured UP', 'icon' => $config['icon']['up']],
'down' => ['name' => 'Measured DOWN', 'icon' => $config['icon']['down']],
'shutdown' => ['name' => 'Measured SHUTDOWN', 'icon' => $config['icon']['shutdown']]]);
$form['row'][1]['sensor_descr'] = array(
'type' => 'text',
'placeholder' => 'Sensor description',
'width' => '100%', //'180px',
'grid' => 4,
'value' => $vars['sensor_descr']);
$form['row'][1]['sensor_type'] = array(
'type' => 'text',
'placeholder' => 'Sensor type',
'width' => '100%', //'180px',
'grid' => 4,
'value' => $vars['status_descr']);
// Groups
foreach (get_type_groups('sensor') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][1]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][1]['search'] = array(
'type' => 'submit',
'grid' => 2,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Sensors',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['sensor_class'] = $form['row'][0]['sensor_class'];
$panel_form['row'][1]['sensor_event'] = $form['row'][0]['sensor_event'];
$panel_form['row'][1]['sensor_value'] = $form['row'][0]['sensor_value'];
$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
$panel_form['row'][2]['group'] = $form['row'][1]['group'];
$panel_form['row'][3]['sensor_type'] = $form['row'][1]['sensor_type'];
$panel_form['row'][4]['sensor_descr'] = $form['row'][1]['sensor_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][1]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,361 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2020 Observium Limited
*
*/
function generate_sla_query($vars)
{
$sql = 'SELECT * FROM `slas` ';
$sql .= ' WHERE `deleted` = 0';
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'slas.sla_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'storage.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'slas.device_id');
break;
case "id":
case "sla_id":
$sql .= generate_query_values($value, 'slas.sla_id');
break;
case "owner":
$sql .= generate_query_values($value, 'slas.sla_owner');
break;
case "target":
case "sla_target":
$sql .= generate_query_values($value, 'slas.sla_target', '%LIKE%');
break;
case "sla_tag":
$sql .= generate_query_values($value, 'slas.sla_tag');
break;
case "rtt_type":
case "rtt_sense":
$sql .= generate_query_values($value, 'slas.'.$var);
break;
case "event":
case "rtt_event":
$sql .= generate_query_values($value, 'slas.rtt_event');
break;
}
}
$sql .= $GLOBALS['cache']['where']['devices_permitted'];
return $sql;
}
function print_sla_table_header($vars)
{
if ($vars['view'] == "graphs" || isset($vars['graph']) || isset($vars['id']))
{
$stripe_class = "table-striped-two";
} else {
$stripe_class = "table-striped";
}
echo('<table class="table ' . $stripe_class . ' table-condensed ">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'device' => array('Device', 'style="width: 250px;"'),
'descr' => array('Description'),
'owner' => array('Owner', 'style="width: 180px;"'),
'type' => array('Type', 'style="width: 100px;"'),
array('History', 'style="width: 100px;"'),
'last_change' => array('Last&nbsp;changed', 'style="width: 80px;"'),
'event' => array('Event', 'style="width: 60px; text-align: right;"'),
'sense' => array('Sense', 'style="width: 100px; text-align: right;"'),
'rtt' => array('RTT', 'style="width: 60px;"'),
);
if ($vars['page'] == "device" || $vars['popup'] == TRUE )
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_sla_table($vars)
{
$sql = generate_sla_query($vars);
$slas = array();
foreach(dbFetchRows($sql) as $sla)
{
if (isset($GLOBALS['cache']['devices']['id'][$sla['device_id']]))
{
$sla['hostname'] = $GLOBALS['cache']['devices']['id'][$sla['device_id']]['hostname'];
$slas[] = $sla;
}
}
// Sorting
// FIXME. Sorting can be as function, but in must before print_table_header and after get table from db
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = SORT_DESC;
$sort_neg = SORT_ASC;
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = SORT_ASC;
$sort_neg = SORT_DESC;
}
switch ($vars['sort'])
{
case 'device':
$slas = array_sort_by($slas, 'hostname', $sort_order, SORT_STRING);
break;
case 'descr':
$slas = array_sort_by($slas, 'sla_index', $sort_order, SORT_STRING, 'sla_tag', $sort_order, SORT_STRING);
break;
case 'owner':
$slas = array_sort_by($slas, 'sla_owner', $sort_order, SORT_STRING);
break;
case 'type':
$slas = array_sort_by($slas, 'rtt_type', $sort_order, SORT_STRING);
break;
case 'event':
$slas = array_sort_by($slas, 'rtt_event', $sort_order, SORT_STRING);
break;
case 'sense':
$slas = array_sort_by($slas, 'rtt_sense', $sort_order, SORT_STRING);
break;
case 'last_change':
$slas = array_sort_by($slas, 'rtt_last_change', $sort_neg, SORT_NUMERIC);
break;
case 'rtt':
$slas = array_sort_by($slas, 'rtt_value', $sort_order, SORT_NUMERIC);
break;
default:
// Not sorted
}
$slas_count = count($slas);
// Pagination
$pagination_html = pagination($vars, $slas_count);
echo $pagination_html;
if ($vars['pageno'])
{
$slas = array_chunk($slas, $vars['pagesize']);
$slas = $slas[$vars['pageno'] - 1];
}
// End Pagination
echo generate_box_open();
print_sla_table_header($vars);
foreach($slas as $sla)
{
print_sla_row($sla, $vars);
}
echo '</tbody></table>';
echo generate_box_close();
echo $pagination_html;
}
function humanize_sla(&$sla)
{
global $config;
if (isset($sla['humanized'])) { return; }
$sla['sla_descr'] = 'SLA #' . $sla['sla_index'];
if (!empty($sla['sla_target']) && ($sla['sla_target'] != $sla['sla_tag']))
{
if (get_ip_version($sla['sla_target']) === 6)
{
$sla_target = Net_IPv6::compress($sla['sla_target'], TRUE);
} else {
$sla_target = $sla['sla_target'];
}
$sla['sla_descr'] .= ' (' . $sla['sla_tag'] . ': ' . $sla_target . ')';
} else {
$sla['sla_descr'] .= ' (' . $sla['sla_tag'] . ')';
}
if (isset($config['entity_events'][$sla['rtt_event']]))
{
$sla = array_merge($sla, $config['entity_events'][$sla['rtt_event']]);
} else {
$sla['event_class'] = 'label label-primary';
$sla['row_class'] = '';
}
if ($sla['sla_status'] != 'active')
{
$sla['row_class'] = 'ignore';
}
$device = &$GLOBALS['cache']['devices']['id'][$sla['device_id']];
if (isset($device['status']) && !$device['status'])
{
$sla['row_class'] = 'error';
}
else if (isset($device['disabled']) && $device['disabled'])
{
$sla['row_class'] = 'ignore';
}
if (!empty($sla['sla_graph']))
{
$sla['graph_type'] = "sla_" . $sla['sla_graph'];
} else {
if (stripos($sla['rtt_type'], 'jitter') !== FALSE)
{
$sla['graph_type'] = "sla_jitter";
} else {
$sla['graph_type'] = "sla_echo";
}
}
if (isset($GLOBALS['config']['sla_type_labels'][$sla['rtt_type']]))
{
$sla['rtt_label'] = $GLOBALS['config']['sla_type_labels'][$sla['rtt_type']];
} else {
$sla['rtt_label'] = nicecase($sla['rtt_type']);
}
if (is_numeric($sla['rtt_value']))
{
if ($sla['rtt_value'] > 950)
{
$sla['human_value'] = round($sla['rtt_value'] / 1000, 2);
$sla['human_unit'] = 's';
} else {
$sla['human_value'] = $sla['rtt_value'];
$sla['human_unit'] = 'ms';
}
$sla['human_value'] = str_replace('.00', '', $sla['human_value']);
}
/*
// FIXME, add table columns in discovery time 'rtt_high', 'rtt_warning'
if ($sla['rtt_value'] > 200)
{
$sla['sla_class'] = 'label label-error';
}
else if ($sla['rtt_value'] > 80)
{
$sla['sla_class'] = 'label label-warning';
} else {
$sla['sla_class'] = 'label';
}
*/
if ($sla['rtt_event'] == 'ok')
{
$sla['sla_class'] = 'label';
//$sla['rtt_class'] = 'label label-success';
}
else if ($sla['rtt_event'] == 'alert')
{
$sla['sla_class'] = 'label label-error';
//$sla['rtt_class'] = 'label label-error';
}
else if ($sla['rtt_event'] == 'ignore')
{
$sla['sla_class'] = 'label';
//$sla['rtt_class'] = 'label';
} else {
$sla['sla_class'] = 'label label-warning';
//$sla['rtt_class'] = 'label label-warning';
}
$sla['humanized'] = TRUE;
}
function print_sla_row($sla, $vars)
{
echo generate_sla_row($sla, $vars);
}
function generate_sla_row($sla, $vars)
{
global $config;
humanize_sla($sla);
$table_cols = "8";
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $sla['sla_id'];
$graph_array['type'] = $sla['graph_type'];
$graph_array['legend'] = "no";
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
if ($sla['rtt_event'] && $sla['rtt_sense'])
{
$mini_graph = generate_graph_tag($graph_array);
} else {
// Do not show "Draw Error" minigraph
$mini_graph = '';
}
$out = '<tr class="' . $sla['row_class'] . '"><td class="state-marker"></td>';
if ($vars['page'] != "device" && $vars['popup'] != TRUE )
{
$out .= '<td class="entity">' . generate_device_link($sla) . '</td>';
$table_cols++;
}
$out .= '<td class="entity">'. generate_entity_link('sla', $sla) .'</td>';
$out .= '<td>'. $sla['sla_owner'] .'</td>';
$out .= '<td>'. $sla['rtt_label'] .'</td>';
$out .= '<td>' . generate_entity_link('sla', $sla, $mini_graph, NULL, FALSE) . '</td>';
$out .= '<td style="white-space: nowrap">' . generate_tooltip_link(NULL, format_uptime(($config['time']['now'] - $sla['rtt_last_change']), 'short-2') . ' ago', format_unixtime($sla['rtt_last_change'])) . '</td>';
$out .= '<td style="text-align: right;"><strong>' . generate_tooltip_link('', $sla['rtt_event'], $sla['event_descr'], $sla['event_class']) . '</strong></td>';
$out .= '<td style="text-align: right;"><strong>' . generate_tooltip_link('', $sla['rtt_sense'], $sla['event_descr'], $sla['event_class']) . '</strong></td>';
$out .= '<td><span class="' . $sla['sla_class'] . '">' . $sla['human_value'] . $sla['human_unit'] . '</span></td>';
$out .= '</tr>';
if ($vars['graph'] || $vars['view'] == "graphs" || $vars['id'] == $sla['sla_id'])
{
// If id set in vars, display only specific graphs
$graph_array = array();
$graph_array['type'] = $sla['graph_type'];
$graph_array['id'] = $sla['sla_id'];
$out .= '<tr class="' . $sla['row_class'] . '">';
$out .= ' <td class="state-marker"></td>';
$out .= ' <td colspan="'.$table_cols.'">';
$out .= generate_graph_row($graph_array, TRUE);
$out .= ' </td>';
$out .= '</tr>';
}
return $out;
}
// EOF

View File

@ -0,0 +1,522 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
/**
* Humanize status indicator.
*
* Returns a the $status array with processed information:
* sensor_state (TRUE: state sensor, FALSE: normal sensor)
* human_value, sensor_symbol, state_name, state_event, event_class
*
* @param array $status
* @return array $status
*
*/
// TESTME needs unit testing
function humanize_status(&$status)
{
global $config;
// Exit if already humanized
if ($status['humanized']) { return; }
if (isset($config['entity_events'][$status['status_event']]))
{
$status = array_merge($status, $config['entity_events'][$status['status_event']]);
} else {
$status['event_class'] = 'label label-primary';
$status['row_class'] = '';
}
if ($status['status_deleted'])
{
$status['row_class'] = 'disabled';
}
$device = &$GLOBALS['cache']['devices']['id'][$status['device_id']];
if ((isset($device['status']) && !$device['status']) ||
(isset($device['disabled']) && $device['disabled'])) {
$status['row_class'] = $status['row_class'] !== 'disabled' ? 'error' : $status['row_class'];
}
// this is pseudo class only for js selectors
$status['row_class'] .= ' entity-status';
// Set humanized entry in the array so we can tell later
$status['humanized'] = TRUE;
}
function generate_status_query($vars, $query_count = FALSE) {
if ($query_count) {
$sql = "SELECT COUNT(*) FROM `status`";
} else {
$sql = "SELECT * FROM `status`";
if ($vars['sort'] == 'hostname' || $vars['sort'] == 'device' || $vars['sort'] == 'device_id') {
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
}
}
//$sql .= " WHERE 1";
$sql .= " WHERE `status_deleted` = 0";
// Build query
foreach($vars as $var => $value) {
switch ($var) {
case "group":
case "group_id":
$values = get_group_entities($value, 'status');
$sql .= generate_query_values($values, 'status.status_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'status.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'status.device_id');
break;
case "id":
case 'status_id':
$sql .= generate_query_values($value, 'status.status_id');
break;
case "entity_id":
$sql .= generate_query_values($value, 'measured_entity');
break;
case "entity_type":
$sql .= generate_query_values($value, 'measured_class');
break;
case 'entity_state':
case "measured_state":
$sql .= build_entity_measured_where('status', [ 'measured_state' => $value ]);
break;
case "class":
case 'entPhysicalClass':
$sql .= generate_query_values($value, 'entPhysicalClass');
break;
case "event":
case "status_event":
$sql .= generate_query_values($value, 'status_event');
break;
case "status":
case "status_name":
$sql .= generate_query_values($value, 'status_name');
break;
case "descr":
case "status_descr":
$sql .= generate_query_values($value, 'status_descr', '%LIKE%');
break;
case 'type':
case "status_type":
$sql .= generate_query_values($value, 'status_type', '%LIKE%');
break;
}
}
//$sql .= $GLOBALS['cache']['where']['devices_permitted'];
$sql .= generate_query_permitted(array('device', 'status'));
// If need count, just return sql without sorting
if ($query_count) {
return $sql;
}
switch ($vars['sort_order']) {
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch($vars['sort']) {
case 'device':
$sql .= ' ORDER BY `hostname` '.$sort_order;
break;
case 'descr':
$sql .= ' ORDER BY `status_descr` '.$sort_order;
break;
case 'class':
$sql .= ' ORDER BY `entPhysicalClass` '.$sort_order;
break;
case 'event':
$sql .= ' ORDER BY `status_event` '.$sort_order;
break;
case 'status':
$sql .= ' ORDER BY `status_name` '.$sort_order;
break;
case 'last_change':
$sql .= ' ORDER BY `status_last_change` '.$sort_neg;
break;
default:
$sql .= ' ORDER BY `measured_entity_label`, `status_descr` '.$sort_order;
}
return $sql;
}
function print_status_table($vars)
{
pagination($vars, 0, TRUE); // Get default pagesize/pageno
$sql = generate_status_query($vars);
$status_list = array();
foreach(dbFetchRows($sql) as $status) {
//if (isset($GLOBALS['cache']['devices']['id'][$status['device_id']]))
//{
$status['hostname'] = $GLOBALS['cache']['devices']['id'][$status['device_id']]['hostname'];
$status_list[] = $status;
//}
}
//$status_count = count($status_list); // This is count incorrect, when pagination used!
$status_count = dbFetchCell(generate_status_query($vars, TRUE));
// Pagination
$pagination_html = pagination($vars, $status_count);
echo $pagination_html;
if ($vars['pageno'])
{
$status_list = array_chunk($status_list, $vars['pagesize']);
$status_list = $status_list[$vars['pageno'] - 1];
}
// End Pagination
echo generate_box_open();
print_status_table_header($vars);
foreach($status_list as $status)
{
print_status_row($status, $vars);
}
echo("</tbody></table>");
echo generate_box_close();
echo $pagination_html;
}
function print_status_table_header($vars)
{
if ($vars['view'] == "graphs" || isset($vars['id']))
{
$stripe_class = "table-striped-two";
} else {
$stripe_class = "table-striped";
}
echo('<table class="table ' . $stripe_class . ' table-condensed ">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'device' => array('Device', 'style="width: 250px;"'),
//array(NULL, 'class="no-width"'), // Measure entity link
'descr' => array('Description'),
'mib' => array('MIB::Object'),
'class' => array('Physical&nbsp;Class', 'style="width: 100px;"'),
array('History', 'style="width: 90px;"'),
'last_change' => array('Last&nbsp;changed', 'style="width: 80px;"'),
'event' => array('Event', 'style="width: 60px; text-align: right;"'),
'status' => array('Status', 'style="width: 80px; text-align: right;"'),
);
if ($vars['page'] == "device") { unset($cols['device']); }
if ($vars['page'] != "device" || $vars['tab'] == "overview") { unset($cols['mib']); unset($cols['object']); }
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_status_row($status, $vars)
{
echo generate_status_row($status, $vars);
}
function generate_status_row($status, $vars) {
$table_cols = 7;
humanize_status($status);
// FIXME - make this "four graphs in popup" a function/include and "small graph" a function.
// FIXME - DUPLICATED IN device/overview/status
$graph_array = array();
$graph_array['to'] = get_time();
$graph_array['id'] = $status['status_id'];
$graph_array['type'] = "status_graph";
$graph_array['legend'] = "no";
$graph_array['width'] = 80;
$graph_array['height'] = 20;
$graph_array['bg'] = 'ffffff00';
$graph_array['from'] = get_time('day');
//$status_misc = '<span class="label">' . $status['entPhysicalClass'] . '</span>';
$short = $vars['page'] === "device" && $vars['tab'] === "overview";
$hide_style = $status['status_event'] === 'ignore' && $short ? ' style="display: none;"' : '';
$row = '<tr class="' . $status['row_class'] . '"'.$hide_style.'>
<td class="state-marker"></td>';
if ($vars['page'] !== "device" && $vars['popup'] != TRUE)
{
$row .= '<td class="entity">' . generate_device_link($status) . '</td>';
$table_cols++;
}
if ($status['status_event'] && $status['status_name'])
{
$mini_graph = generate_graph_tag($graph_array);
} else {
// Do not show "Draw Error" minigraph
$mini_graph = '';
}
// Measured link & icon
/* Disabled because it breaks the overview table layout
$row .= ' <td style="padding-right: 0px;" class="no-width vertical-align">'; // minify column if empty
if ($status['measured_entity'] &&
(!isset($vars['measured_icon']) || $vars['measured_icon'])) // hide measured icon if not required
{
$row .= generate_entity_icon_link($status['measured_class'], $status['measured_entity']);
}
$row .= '</td>';
$table_cols++;
*/
$row .= '<td class="entity">' . generate_entity_link('status', $status) . '</td>';
// FIXME -- Generify this. It's not just for sensors.
if ($vars['page'] === "device" && $vars['tab'] !== "overview")
{
$row .= ' <td>' . (!safe_empty($status['status_mib']) ? '<a href="'.OBSERVIUM_MIBS_URL.'/'.$status['status_mib'].'/" target="_blank">' .nicecase($status['status_mib']) .'</a>' : '') .
( ( !safe_empty($status['status_mib']) && !safe_empty($status['status_object'])) ? '::' : '') .
(!safe_empty($status['status_mib']) ? '<a href="'.OBSERVIUM_MIBS_URL.'/'.$status['status_mib'].'/#'.$status['status_object'].'" target="_blank">' . $status['status_object'] .'</a>' : '') .
'.'.$status['status_index'].'</td>' . PHP_EOL;
$table_cols++;
}
if ($vars['tab'] !== "overview")
{
$row .= '<td><span class="label">' . $status['entPhysicalClass'] . '</span></td>';
$table_cols++;
}
$row .= '<td style="width: 90px; text-align: right;">' . generate_entity_link('status', $status, $mini_graph, NULL, FALSE) . '</td>';
if ($vars['tab'] !== "overview")
{
$row .= '<td style="white-space: nowrap">' . generate_tooltip_link('', format_uptime((get_time() - $status['status_last_change']), 'short-2') . ' ago', format_unixtime($status['status_last_change'])) . '</td>
<td style="text-align: right;"><strong>' . generate_tooltip_link('', $status['status_event'], $status['event_descr'], $status['event_class']) . '</strong></td>';
$table_cols++;
$table_cols++;
}
$row .= '<td style="width: 80px; text-align: right;"><strong>' . generate_tooltip_link('', $status['status_name'], $status['event_descr'], $status['event_class']) . '</strong></td>
</tr>' . PHP_EOL;
if ($vars['view'] === "graphs")
{
$vars['graph'] = "status";
}
if ($vars['graph'] || $vars['id'] == $status['status_id'])
{
// If id set in vars, display only specific graphs
$row .= '<tr class="' . $status['row_class'] . '">
<td class="state-marker"></td>
<td colspan="' . $table_cols . '">';
unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
$graph_array['to'] = get_time();
$graph_array['id'] = $status['status_id'];
$graph_array['type'] = "status_graph";
$row .= generate_graph_row($graph_array, TRUE);
$row .= '</td></tr>';
} # endif graphs
return $row;
}
function print_status_form($vars, $single_device = FALSE)
{
global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `status`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
$status_permitted = generate_query_permitted(array('device', 'status'));
foreach ([ 'entPhysicalClass' => 'Physical Class', 'status_event' => 'Status Event', 'status_name' => 'Status' ] as $param => $param_name) {
$sql = 'SELECT DISTINCT `'.$param.'` FROM `status` WHERE `status_deleted` = ?' . $status_permitted;
if ($entries = dbFetchColumn($sql, [ 0 ])) {
asort($entries);
}
foreach ($entries as $entry) {
if (safe_empty($entry)) { $entry = OBS_VAR_UNSET; }
if ($param === 'entPhysicalClass')
{
$name = nicecase($entry);
if (isset($config['icon'][strtolower($entry)]))
{
$name = ['name' => $name, 'icon' => $config['icon'][strtolower($entry)]];
} else {
$name = ['name' => $name, 'icon' => $config['icon']['status']];
}
} else {
$name = $entry;
}
$form_items[$param][$entry] = $name;
}
// Alternative param name, ie event
$short_param = str_replace('status_', '', $param);
if (!isset($vars[$param]) && isset($vars[$short_param]))
{
$vars[$param] = $vars[$short_param];
}
// Status specific forms
$form['row'][0][$param] = array(
'type' => 'multiselect',
'name' => $param_name,
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars[$param],
'values' => $form_items[$param]);
}
// Measured entities
$form['row'][0]['measured_state'] = array(
'type' => 'multiselect',
'name' => 'Measured State',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['measured_state'],
'values' => ['none' => ['name' => 'Without Measure', 'icon' => $config['icon']['filter']],
'up' => ['name' => 'Measured UP', 'icon' => $config['icon']['up']],
'down' => ['name' => 'Measured DOWN', 'icon' => $config['icon']['down']],
'shutdown' => ['name' => 'Measured SHUTDOWN', 'icon' => $config['icon']['shutdown']]]);
$form['row'][1]['status_descr'] = array(
'type' => 'text',
'placeholder' => 'Status description',
'width' => '100%', //'180px',
'grid' => 4,
'value' => $vars['status_descr']);
$form['row'][1]['status_type'] = array(
'type' => 'text',
'placeholder' => 'Status type',
'width' => '100%', //'180px',
'grid' => 4,
'value' => $vars['status_descr']);
// Groups
foreach (get_type_groups('status') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][1]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][1]['search'] = array(
'type' => 'submit',
'grid' => 2,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE,
);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Statuses',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['entPhysicalClass'] = $form['row'][0]['entPhysicalClass'];
$panel_form['row'][1]['status_event'] = $form['row'][0]['status_event'];
$panel_form['row'][1]['status_name'] = $form['row'][0]['status_name'];
$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
$panel_form['row'][2]['group'] = $form['row'][1]['group'];
$panel_form['row'][3]['status_type'] = $form['row'][1]['status_type'];
$panel_form['row'][4]['status_descr'] = $form['row'][1]['status_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][1]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,370 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2021 Observium Limited
*
*/
function generate_storage_query($vars)
{
$sql = "SELECT * FROM `storage`";
if (in_array($vars['sort'], [ 'hostname', 'device', 'device_id' ]))
{
$sql .= ' LEFT JOIN `devices` USING(`device_id`)';
}
$sql .= ' WHERE 1' . generate_query_permitted(array('device'));
// Build query
if (!isset($vars['ignored'])) { $vars['ignored'] = 0; }
foreach($vars as $var => $value)
{
switch ($var) {
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'storage.storage_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'storage.device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'storage.device_id');
break;
case "descr":
case "storage_descr";
$sql .= generate_query_values($value, 'storage_descr', '%LIKE%');
break;
case 'ignored':
$sql .= generate_query_values($value, 'storage.storage_ignore');
break;
}
}
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = 'DESC';
$sort_neg = 'ASC';
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = 'ASC';
$sort_neg = 'DESC';
}
switch($vars['sort'])
{
case 'usage':
$sql .= ' ORDER BY `storage_perc` '.$sort_neg;
break;
case 'descr':
case 'mountpoint':
$sql .= ' ORDER BY `storage_descr` '.$sort_order;
break;
case 'size':
case 'free':
case 'used':
$sql .= ' ORDER BY `storage_'.$vars['sort'].'` '.$sort_order;
break;
case 'device':
case 'hostname':
$sql .= ' ORDER BY `hostname` '.$sort_order;
break;
default:
$sql .= ' ORDER BY `storage_descr` '.$sort_order;
break;
}
return $sql;
}
function print_storage_table($vars)
{
global $cache, $config;
$graph_type = "storage_usage";
$sql = generate_storage_query($vars);
$storages = array();
foreach (dbFetchRows($sql) as $storage)
{
if (isset($cache['devices']['id'][$storage['device_id']]))
{
$storage['hostname'] = $cache['devices']['id'][$storage['device_id']]['hostname'];
$storage['html_row_class'] = $cache['devices']['id'][$storage['device_id']]['html_row_class'];
$storages[] = $storage;
}
}
$storages_count = count($storages);
// Pagination
$pagination_html = pagination($vars, $storages_count);
echo $pagination_html;
if ($vars['pageno'])
{
$storages = array_chunk($storages, $vars['pagesize']);
$storages = $storages[$vars['pageno']-1];
}
// End Pagination
echo generate_box_open();
print_storage_table_header($vars);
foreach ($storages as $storage)
{
print_storage_row($storage, $vars);
}
echo("</tbody></table>");
echo generate_box_close();
echo $pagination_html;
}
function print_storage_table_header($vars)
{
if ($vars['view'] === "graphs" || isset($vars['graph']))
{
$table_class = OBS_CLASS_TABLE_STRIPED_TWO;
} else {
$table_class = OBS_CLASS_TABLE_STRIPED;
}
echo('<table class="' . $table_class . '">' . PHP_EOL);
$cols = array(
array(NULL, 'class="state-marker"'),
'device' => array('Device', 'style="width: 250px;"'),
'mountpoint' => array('Mountpoint'),
'size' => array('Size', 'style="width: 100px;"'),
'used' => array('Used', 'style="width: 100px;"'),
'free' => array('Free', 'style="width: 100px;"'),
array('', 'style="width: 100px;"'),
'usage' => array('Usage %', 'style="width: 200px;"'),
);
if ($vars['page'] === "device")
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_storage_row($storage, $vars) {
echo generate_storage_row($storage, $vars);
}
function generate_storage_row($storage, $vars) {
global $config;
$table_cols = 8;
if ($vars['page'] !== "device" && $vars['popup'] != TRUE) { $table_cols++; } // Add a column for device.
if(isset($vars['graph_type']) && $vars['graph_type'] == "perc")
$graph_array = array();
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $storage['storage_id'];
$graph_array['type'] = 'storage_usage';
$graph_array['legend'] = "no";
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link_graph = generate_url($link_array);
$link = generate_url( array("page" => "device", "device" => $storage['device_id'], "tab" => "health", "metric" => 'storage'));
$overlib_content = generate_overlib_content($graph_array, $storage['hostname'] . ' - ' . $storage['storage_descr']);
$graph_array['width'] = 80; $graph_array['height'] = 20; $graph_array['bg'] = 'ffffff00';
$graph_array['from'] = $config['time']['day'];
$mini_graph = generate_graph_tag($graph_array);
$total = formatStorage($storage['storage_size']);
$used = formatStorage($storage['storage_used']);
$free = formatStorage($storage['storage_free']);
$background = get_percentage_colours($storage['storage_perc']);
if ($storage['storage_ignore'])
{
$storage['row_class'] = 'suppressed';
} else {
$storage['row_class'] = $background['class'];
}
$row = '<tr class="ports ' . $storage['row_class'] . '">
<td class="state-marker"></td>';
if ($vars['page'] !== "device" && $vars['popup'] != TRUE) { $row .= '<td class="entity">' . generate_device_link($storage) . '</td>'; }
$row .= ' <td class="entity">'.generate_entity_link('storage', $storage).'</td>
<td>'.$total.'</td>
<td>'.$used.'</td>
<td>'.$free.'</td>
<td>'.overlib_link($link_graph, $mini_graph, $overlib_content).'</td>
<td><a href="'.$link_graph.'">
' . print_percentage_bar(400, 20, $storage['storage_perc'], $storage['storage_perc'].'%', "ffffff", $background['left'], 100-$storage['storage_perc']."%" , "ffffff", $background['right']).'
</a>
</td>
</tr>
';
if ($vars['view'] === "graphs" && !isset($vars['graph'])) { $vars['graph'] = "bytes,perc"; }
if (isset($vars['graph']))
{
$graph_types = explode(',', $vars['graph']);
foreach ($graph_types AS $graph_type) {
$graph_type = 'storage_'.$graph_type;
$row .= '<tr class="' . $storage['row_class'] . '">';
$row .= '<td class="state-marker"></td>';
$row .= '<td colspan="' . $table_cols . '">';
unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $storage['storage_id'];
$graph_array['type'] = $graph_type;
$row .= generate_graph_row($graph_array, TRUE);
$row .= '</td></tr>';
}
} # endif graphs
return $row;
}
function print_storage_form($vars, $single_device = FALSE)
{
//global $config;
$form = array('type' => 'rows',
'space' => '10px',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
$form_items = array();
if ($single_device)
{
// Single device, just hidden field
$form['row'][0]['device_id'] = array(
'type' => 'hidden',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%');
} else {
$form_items['devices'] = generate_form_values('device', dbFetchColumn('SELECT DISTINCT `device_id` FROM `storage`'));
$form['row'][0]['device_id'] = array(
'type' => 'multiselect',
'name' => 'Device',
'value' => $vars['device_id'],
'grid' => 2,
'width' => '100%', //'180px',
'values' => $form_items['devices']);
}
//$sensor_permitted = generate_query_permitted(array('device', 'sensor'));
$form['row'][0]['storage_descr'] = array(
'type' => 'text',
'placeholder' => 'Storage',
'width' => '100%', //'180px',
'grid' => 6,
'value' => $vars['storage_descr']);
// Groups
foreach (get_type_groups('storage') as $entry)
{
$form_items['group'][$entry['group_id']] = $entry['group_name'];
}
$form['row'][0]['group'] = array(
'community' => FALSE,
'type' => 'multiselect',
'name' => 'Select Groups',
'width' => '100%', //'180px',
'grid' => 2,
'value' => $vars['group'],
'values' => $form_items['group']);
$form['row'][0]['search'] = array(
'type' => 'submit',
'grid' => 2,
//'name' => 'Search',
//'icon' => 'icon-search',
'right' => TRUE,
);
// Show search form
echo '<div class="hidden-xl">';
print_form($form);
echo '</div>';
// Custom panel form
$panel_form = array('type' => 'rows',
'title' => 'Search Storage',
'space' => '10px',
//'brand' => NULL,
//'class' => '',
'submit_by_key' => TRUE,
'url' => generate_url($vars));
// Clean grids
foreach ($form['row'] as $row => $rows) {
foreach (array_keys($rows) as $param) {
if (isset($form['row'][$row][$param]['grid'])) { unset($form['row'][$row][$param]['grid']); }
}
}
// Copy forms
$panel_form['row'][0]['device_id'] = $form['row'][0]['device_id'];
$panel_form['row'][0]['group'] = $form['row'][0]['group'];
//$panel_form['row'][1]['supply_colour'] = $form['row'][0]['supply_colour'];
//$panel_form['row'][1]['supply_type'] = $form['row'][0]['supply_type'];
//$panel_form['row'][2]['measured_state'] = $form['row'][0]['measured_state'];
//$panel_form['row'][2]['group'] = $form['row'][1]['group'];
$panel_form['row'][3]['storage_descr'] = $form['row'][0]['storage_descr'];
//$panel_form['row'][5]['sort'] = $form['row'][0]['sort'];
$panel_form['row'][5]['search'] = $form['row'][0]['search'];
// Register custom panel
register_html_panel(generate_form($panel_form));
}
// EOF

View File

@ -0,0 +1,207 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage web
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
function generate_vm_query($vars)
{
$sql = 'SELECT * FROM `vminfo` WHERE 1 ';
// Build query
foreach($vars as $var => $value)
{
switch ($var)
{
case "group":
case "group_id":
$values = get_group_entities($value);
$sql .= generate_query_values($values, 'vm_id');
break;
case 'device_group_id':
case 'device_group':
$values = get_group_entities($value, 'device');
$sql .= generate_query_values($values, 'device_id');
break;
case "device":
case "device_id":
$sql .= generate_query_values($value, 'device_id');
break;
case "os":
$sql .= generate_query_values($value, 'vm_guestos');
break;
case "state":
$sql .= generate_query_values($value, 'vm_state');
break;
case "memory":
$sql .= generate_query_values($value, 'vm_memory');
break;
case "cpu":
$sql .= generate_query_values($value, 'vm_cpucount');
break;
}
}
$sql .= $GLOBALS['cache']['where']['devices_permitted'];
return $sql;
}
function print_vm_table_header($vars)
{
$stripe_class = "table-striped";
echo('<table class="table ' . $stripe_class . ' table-condensed ">' . PHP_EOL);
$cols = array(
// array(NULL, 'class="state-marker"'), // FIXME useful when we start polling VM status
'device' => array('Device', 'style="width: 250px;"'),
'name' => array('Name'),
'state' => array('State'),
'os' => array('Operating System'),
'memory' => array('Memory'),
'cpu' => array('CPU'),
);
if ($vars['page'] == "device" || $vars['popup'] == TRUE )
{
unset($cols['device']);
}
echo(get_table_header($cols, $vars));
echo('<tbody>' . PHP_EOL);
}
function print_vm_table($vars)
{
$sql = generate_vm_query($vars);
$vms = array();
foreach(dbFetchRows($sql) as $vm)
{
if (isset($GLOBALS['cache']['devices']['id'][$vm['device_id']]))
{
$vm['hostname'] = $GLOBALS['cache']['devices']['id'][$vm['device_id']]['hostname'];
$vms[] = $vm;
}
}
// Sorting
// FIXME. Sorting can be as function, but in must before print_table_header and after get table from db
switch ($vars['sort_order'])
{
case 'desc':
$sort_order = SORT_DESC;
$sort_neg = SORT_ASC;
break;
case 'reset':
unset($vars['sort'], $vars['sort_order']);
// no break here
default:
$sort_order = SORT_ASC;
$sort_neg = SORT_DESC;
}
switch ($vars['sort'])
{
case 'name':
$vms = array_sort_by($vms, 'vm_name', $sort_order, SORT_STRING);
break;
case 'os':
$vms = array_sort_by($vms, 'vm_os', $sort_order, SORT_STRING);
break;
case 'state':
$vms = array_sort_by($vms, 'vm_state', $sort_order, SORT_STRING);
break;
case 'memory':
$vms = array_sort_by($vms, 'vm_memory', $sort_order, SORT_NUMERIC);
break;
case 'cpu':
$vms = array_sort_by($vms, 'vm_cpucount', $sort_order, SORT_NUMERIC);
break;
default:
// Not sorted
}
$vms_count = count($vms);
// Pagination
$pagination_html = pagination($vars, $vms_count);
echo $pagination_html;
if ($vars['pageno'])
{
$vms = array_chunk($vms, $vars['pagesize']);
$vms = $vms[$vars['pageno'] - 1];
}
// End Pagination
echo generate_box_open();
print_vm_table_header($vars);
foreach($vms as $vm)
{
print_vm_row($vm, $vars);
}
echo '</tbody></table>';
echo generate_box_close();
echo $pagination_html;
}
function print_vm_row($vm, $vars)
{
echo generate_vm_row($vm, $vars);
}
function generate_vm_row($vm, $vars)
{
global $config;
$table_cols = "8";
$out = '<tr class="' . $vm['row_class'] . '">'; // <td class="state-marker"></td>'; // FIXME useful when we start polling VM state
if ($vars['page'] != "device" && $vars['popup'] != TRUE )
{
$out .= '<td class="entity">' . generate_device_link($vm) . '</td>';
$table_cols++;
}
$out .= '<td class="entity">'. generate_entity_link('virtualmachine', $vm) .'</td>';
$out .= '<td>'. nicecase($vm['vm_state']) .'</td>';
switch ($vm['vm_guestos'])
{
case 'E: tools not installed':
$out .= ' <td class="small">Unknown (VMware Tools not installed)</td>';
break;
case 'E: tools not running':
$out .= ' <td class="small">Unknown (VMware Tools not running)</td>';
break;
case '':
$out .= ' <td class="small"><i>(Unknown)</i></td>';
break;
default:
if (isset($config['vmware_guestid'][$vm['vm_guestos']]))
{
$out .= ' <td>' . $config['vmware_guestid'][$vm['vm_guestos']] . '</td>';
} else {
$out .= ' <td>' . $vm['vm_guestos'] . '</td>';
}
break;
}
$out .= '<td>'. format_bi($vm['vm_memory'] * 1024 * 1024, 3, 3) .'B</td>';
$out .= '<td>'. $vm['vm_cpucount'] .'</td>';
$out .= '</tr>';
return $out;
}
// EOF

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,76 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$device = device_by_id_cache($id);
$rrd_filename = get_rrd_path($device, "mem.rrd");
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$rrd_options .= " -b 1024";
$rrd_options .= " DEF:atotalswap=$rrd_filename_escape:totalswap:AVERAGE";
$rrd_options .= " DEF:aavailswap=$rrd_filename_escape:availswap:AVERAGE";
$rrd_options .= " DEF:atotalreal=$rrd_filename_escape:totalreal:AVERAGE";
$rrd_options .= " DEF:aavailreal=$rrd_filename_escape:availreal:AVERAGE";
$rrd_options .= " DEF:atotalfree=$rrd_filename_escape:totalfree:AVERAGE";
$rrd_options .= " DEF:ashared=$rrd_filename_escape:shared:AVERAGE";
$rrd_options .= " DEF:abuffered=$rrd_filename_escape:buffered:AVERAGE";
$rrd_options .= " DEF:acached=$rrd_filename_escape:cached:AVERAGE";
$rrd_options .= " CDEF:totalswap=atotalswap,1024,*";
$rrd_options .= " CDEF:availswap=aavailswap,1024,*";
$rrd_options .= " CDEF:totalreal=atotalreal,1024,*";
$rrd_options .= " CDEF:availreal=aavailreal,1024,*";
$rrd_options .= " CDEF:totalfree=atotalfree,1024,*";
$rrd_options .= " CDEF:shared=ashared,1024,*";
$rrd_options .= " CDEF:buffered=abuffered,1024,*";
$rrd_options .= " CDEF:cached=acached,1024,*";
$rrd_options .= " CDEF:usedreal=totalreal,availreal,-";
$rrd_options .= " CDEF:usedswap=totalswap,availswap,-";
$rrd_options .= " CDEF:cusedswap=usedswap,-1,*";
$rrd_options .= " CDEF:cdeftot=availreal,shared,buffered,usedreal,cached,usedswap,+,+,+,+,+";
$rrd_options .= " COMMENT:'Bytes Current Average Maximum\\n'";
$rrd_options .= " LINE1:usedreal#d0b080:";
$rrd_options .= " AREA:usedreal#f0e0a0:used";
$rrd_options .= " GPRINT:usedreal:LAST:\ \ \ %7.2lf%sB";
$rrd_options .= " GPRINT:usedreal:AVERAGE:%7.2lf%sB";
$rrd_options .= " GPRINT:usedreal:MAX:%7.2lf%sB\\n";
$rrd_options .= " STACK:availreal#e5e5e5:free";
$rrd_options .= " GPRINT:availreal:LAST:\ \ \ %7.2lf%sB";
$rrd_options .= " GPRINT:availreal:AVERAGE:%7.2lf%sB";
$rrd_options .= " GPRINT:availreal:MAX:%7.2lf%sB\\n";
$rrd_options .= " LINE1:usedreal#d0b080:";
$rrd_options .= " AREA:shared#afeced::";
$rrd_options .= " AREA:buffered#cc0000::STACK";
$rrd_options .= " AREA:cached#ffaa66::STACK";
$rrd_options .= " LINE1.25:shared#008fea:shared";
$rrd_options .= " GPRINT:shared:LAST:\ %7.2lf%sB";
$rrd_options .= " GPRINT:shared:AVERAGE:%7.2lf%sB";
$rrd_options .= " GPRINT:shared:MAX:%7.2lf%sB\\n";
$rrd_options .= " LINE1.25:buffered#ff1a00:buffers:STACK";
$rrd_options .= " GPRINT:buffered:LAST:%7.2lf%sB";
$rrd_options .= " GPRINT:buffered:AVERAGE:%7.2lf%sB";
$rrd_options .= " GPRINT:buffered:MAX:%7.2lf%sB\\n";
$rrd_options .= " LINE1.25:cached#ea8f00:cached:STACK";
$rrd_options .= " GPRINT:cached:LAST:\ %7.2lf%sB";
$rrd_options .= " GPRINT:cached:AVERAGE:%7.2lf%sB";
$rrd_options .= " GPRINT:cached:MAX:%7.2lf%sB\\n";
$rrd_options .= " LINE1:totalreal#050505:";
$rrd_options .= " AREA:cusedswap#C3D9FF:swap";
$rrd_options .= " LINE1.25:cusedswap#356AA0:";
$rrd_options .= " GPRINT:usedswap:LAST:\ \ \ %7.2lf%sB";
$rrd_options .= " GPRINT:usedswap:AVERAGE:%7.2lf%sB";
$rrd_options .= " GPRINT:usedswap:MAX:%7.2lf%sB\\n";
$rrd_options .= " LINE1:totalreal#050505:total";
$rrd_options .= " GPRINT:totalreal:AVERAGE:\ \ %7.2lf%sB";
// EOF

View File

@ -0,0 +1,32 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
if (is_numeric($vars['id']))
{
$ap = accesspoint_by_id($vars['id']);
if (is_numeric($ap['device_id']) && ($auth || device_permitted($ap['device_id'])))
{
$device = device_by_id_cache($ap['device_id']);
$cleanmac = str_replace(':','', $ap['mac_addr']);
$rrd_filename = get_rrd_path($device, "arubaap-".$cleanmac."-".$ap['radio_number'].".rrd");
$title = generate_device_link($device);
$title .= " :: AP :: " . escape_html($ap['name']);
$auth = TRUE;
}
}
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Channel";
$rrd_list[0]['ds'] = "channel";
$unit_text = "Channel";
$units='';
$total_units='';
$colours='mixed';
$scale_min = "0";
$nototal = 1;
if ($rrd_list)
{
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
}
?>

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Interference";
$rrd_list[0]['ds'] = "interference";
$unit_text = "Int";
$units='';
$total_units='';
$colours='mixed';
$scale_min = "0";
$nototal = 1;
if ($rrd_list)
{
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
}
?>

View File

@ -0,0 +1,24 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$ds = "numasoclients";
$colour_line = "008C00";
$colour_area = "CDEB8B";
$colour_area_max = "c0c0c0";
$graph_max = 1;
$graph_min = 0;
$unit_text = "Clients";
include($config['html_dir']."/includes/graphs/generic_simplex.inc.php");
?>

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "MonBSSIDs";
$rrd_list[0]['ds'] = "nummonbssid";
$unit_text = "BSSIDs";
$units='';
$total_units='';
$colours='mixed';
$scale_min = "0";
$nototal = 1;
if ($rrd_list)
{
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
}
?>

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Mon Clients";
$rrd_list[0]['ds'] = "nummonclients";
$unit_text = "Clients";
$units='';
$total_units='';
$colours='mixed';
$scale_min = "0";
$nototal = 1;
if ($rrd_list)
{
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
}
?>

View File

@ -0,0 +1,25 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$ds = "radioutil";
$colour_line = "555555";
$colour_area = "999999";
$colour_area_max = "e0e0e0";
$scale_max = 100;
$scale_min = 0;
$unit_text = "Utilisation";
$units = "%";
include($config['html_dir']."/includes/graphs/generic_simplex.inc.php");
?>

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "txpow";
$rrd_list[0]['ds'] = "txpow";
$unit_text = "dBm";
$units='';
$total_units='';
$colours='mixed';
$scale_min = "0";
$nototal = 1;
if ($rrd_list)
{
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
}
?>

View File

@ -0,0 +1,37 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
if (is_numeric($vars['id']) && $alert = get_alert_entry_by_id($vars['id']))
{
$entity = get_entity_by_id_cache($alert['entity_type'], $alert['entity_id']);
$device = device_by_id_cache($alert['device_id']);
if (device_permitted($device['device_id']) || $auth)
{
$title = generate_device_link($device);
$title_array = array();
$title_array[] = array('text' => $device['hostname'], 'url' => generate_url(array('page' => 'device', 'device' => $device['device_id'])));
$auth = TRUE;
$rrd_filename = get_rrd_path($device, "alert-".$alert['alert_test_id']."-".$alert['entity_type']."-".$alert['entity_id'].".rrd");
}
} else {
// error?
}
?>

View File

@ -0,0 +1,54 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = "0";
$scale_max = "1";
$step = TRUE;
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$rrd_options .= " COMMENT:' Min Last Max\\n'";
$rrd_options .= " DEF:status=".$rrd_filename_escape.":status:AVERAGE";
$rrd_options .= " DEF:code=".$rrd_filename_escape.":code:AVERAGE";
$rrd_options .= " CDEF:percent=status,UN,UNKN,status,IF,100,* ";
$rrd_options .= " CDEF:unknown=status,UN,100,UNKN,IF";
$rrd_options .= " CDEF:percent10=10,percent,LE,0,100,IF ";
$rrd_options .= " CDEF:percent20=10,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent30=20,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent40=30,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent50=40,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent60=50,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent70=60,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent80=70,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent90=80,percent,GT,0,100,IF ";
$rrd_options .= " CDEF:percent100=90,percent,GT,0,100,IF ";
$rrd_options .= " AREA:percent10#d94c20:' 0-10%'";
$rrd_options .= " AREA:percent20#de6822:'11-20%'";
$rrd_options .= " AREA:percent30#eaa322:'21-30%'";
$rrd_options .= " AREA:percent40#f4bd1b:'31-40%'";
$rrd_options .= " AREA:percent50#fee610:'41-50%'";
$rrd_options .= " AREA:percent60#e4e11e:'51-60%'";
$rrd_options .= " AREA:percent70#b8d029:'61-70%'";
$rrd_options .= " AREA:percent80#90c22f:'71-80%'";
$rrd_options .= " AREA:percent90#75b731:'81-90%'";
$rrd_options .= " AREA:percent100#5ca53f:'91-100%'";
$rrd_options .= " AREA:unknown#e5e5e5:'Unknown \\n'";
$rrd_options .= " GPRINT:percent:AVERAGE:'Percent availability\: %8.3lf %%'";
?>

View File

@ -0,0 +1,43 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = "0";
$device = device_by_id_cache($id);
$rrd_filename = get_rrd_path($device, "/altiga-ssl.rrd.rrd");
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$rrd_options .= " DEF:TotalSessions=$rrd_filename_escape:TotalSessions:AVERAGE";
$rrd_options .= " DEF:ActiveSessions=$rrd_filename_escape:ActiveSessions:AVERAGE";
$rrd_options .= " DEF:MaxSessions=$rrd_filename_escape:MaxSessions:AVERAGE";
$rrd_options .= " CDEF:a=1min,100,/";
$rrd_options .= " CDEF:b=5min,100,/";
$rrd_options .= " CDEF:c=15min,100,/";
$rrd_options .= " CDEF:cdefd=a,b,c,+,+";
$rrd_options .= " COMMENT:Load\ Average\ \ Current\ \ \ \ Average\ \ \ \ Maximum\\n";
$rrd_options .= " AREA:a#ffeeaa:1\ Min:";
$rrd_options .= " LINE1:a#c5aa00:";
$rrd_options .= " GPRINT:a:LAST:\ \ \ \ %7.2lf";
$rrd_options .= " GPRINT:a:AVERAGE:\ \ %7.2lf";
$rrd_options .= " GPRINT:a:MAX:\ \ %7.2lf\\n";
$rrd_options .= " LINE1.25:b#ea8f00:5\ Min:";
$rrd_options .= " GPRINT:b:LAST:\ \ \ \ %7.2lf";
$rrd_options .= " GPRINT:b:AVERAGE:\ \ %7.2lf";
$rrd_options .= " GPRINT:b:MAX:\ \ %7.2lf\\n";
$rrd_options .= " LINE1.25:c#cc0000:15\ Min";
$rrd_options .= " GPRINT:c:LAST:\ \ \ %7.2lf";
$rrd_options .= " GPRINT:c:AVERAGE:\ \ %7.2lf";
$rrd_options .= " GPRINT:c:MAX:\ \ %7.2lf\\n";
// EOF

View File

@ -0,0 +1,47 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = 0;
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$rrd_filename = get_rrd_path($device, "app-asterisk-".$app['app_id'].".rrd");
$array = array('activechan' => array('descr' => 'Active Channels', 'colour' => '750F7DFF'),
'activecall' => array('descr' => 'Active Calls', 'colour' => '00FF00FF'),
'iaxchannels' => array('descr' => 'IAX Channels', 'colour' => '4444FFFF'),
'sipchannels' => array('descr' => 'SIP Channels', 'colour' => '157419FF'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else { echo("file missing: $rrd_filename"); }
$colours = "mixed";
$nototal = 0;
$unit_text = "Channels";
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
#include($config['html_dir']."/includes/graphs/generic_multi_simplex_separated.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$rrd_filename = get_rrd_path($device, "app-asterisk-".$app['app_id'].".rrd");
$array = array('sippeers' => array('descr' => 'SIP Peers', 'colour' => '750F7DFF'),
'sippeersonline' => array('descr' => 'SIP Peers Active', 'colour' => '00FF00FF'),
'iaxpeers' => array('descr' => 'IAX Peers', 'colour' => '4444FFFF'),
'iaxpeersonline' => array('descr' => 'IAX Peers Active', 'colour' => '157419FF'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else { echo("file missing: $rrd_filename"); }
$colours = "mixed";
$nototal = 0;
$unit_text = "Peers";
#include($config['html_dir']."/includes/graphs/generic_multi_simplex_separated.inc.php");
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,23 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
if (is_numeric($vars['id']) && ($auth || application_permitted($vars['id'])))
{
$app = get_application_by_id($vars['id']);
$device = device_by_id_cache($app['device_id']);
$title = generate_device_link($device);
$title .= $graph_subtype;
$auth = TRUE;
}
// EOF

View File

@ -0,0 +1,53 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-ns-stats.rrd");
$array = array(
'Response' => array('descr' => "Responses sent", 'colour' => '999999'),
'QrySuccess' => array('descr' => "Successful answers", 'colour' => '33cc33'),
'QryAuthAns' => array('descr' => "Authoritative answer", 'colour' => '009900'),
'QryNoauthAns' => array('descr' => "Non-authoritative answer", 'colour' => '336633'),
'QryReferral' => array('descr' => "Referral answer", 'colour' => '996633'),
'QryNxrrset' => array('descr' => "Empty answers", 'colour' => '36393d'),
'QrySERVFAIL' => array('descr' => "SERVFAIL answer", 'colour' => 'ff3333'),
'QryFORMERR' => array('descr' => "FORMERR answer", 'colour' => 'ffcccc'),
'QryNXDOMAIN' => array('descr' => "NXDOMAIN answers", 'colour' => 'ff33ff'),
'QryDropped' => array('descr' => "Dropped queries", 'colour' => '666666'),
'QryFailure' => array('descr' => "Failed queries", 'colour' => 'ff0000'),
'XfrReqDone' => array('descr' => "Transfers completed", 'colour' => '6666ff'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,51 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Entries";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-cache-default.rrd");
#$rrtypes = array('SOA', 'A', 'AAAA', 'NS', 'MX', 'CNAME', 'TXT', 'PTR', 'DNSKEY', 'RRSIG');
$rrtypes = array('SOA', 'A', 'AAAA', 'NS', 'MX', 'CNAME', 'DNAME', 'TXT', 'SPF', 'SRV', 'SSHFP', 'TLSA', 'IPSECKEY', 'PTR', 'DNSKEY', 'RRSIG', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'DS', 'DLV');
$array = array();
foreach ($rrtypes as $rrtype)
{
// Consistent random colours, offset picked for funny colours :-)
$colour = substr(md5($rrtype), 1, 6);
$array[$rrtype] = array('descr' => $rrtype, 'colour' => $colour, 'invert' => False);
$array['NEG_'.$rrtype] = array('descr' => '!'.$rrtype, 'colour' => $colour, 'invert' => True);
}
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$rrd_list[$i]['invert'] = $data['invert'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
#include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,48 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Requests";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-query-in.rrd");
#$rrtypes = array('A', 'AAAA', 'PTR', 'ANY', 'IXFR', 'AXFR');
$rrtypes = array('SOA', 'A', 'AAAA', 'NS', 'MX', 'CNAME', 'DNAME', 'TXT', 'SPF', 'SRV', 'SSHFP', 'TLSA', 'IPSECKEY', 'PTR', 'DNSKEY', 'RRSIG', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'DS', 'DLV', 'ANY', 'IXFR', 'AXFR');
$inverted = array('ANY', 'IXFR', 'AXFR');
$array = array();
foreach ($rrtypes as $rrtype)
{
$array[$rrtype] = array('descr' => $rrtype);
}
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['invert'] = in_array($data['descr'], $inverted);
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
#include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,48 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Requests";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-query-out-default.rrd");
#$rrtypes = array('A', 'AAAA', 'PTR', 'ANY', 'IXFR', 'AXFR');
$rrtypes = array('SOA', 'A', 'AAAA', 'NS', 'MX', 'CNAME', 'DNAME', 'TXT', 'SPF', 'SRV', 'SSHFP', 'TLSA', 'IPSECKEY', 'PTR', 'DNSKEY', 'RRSIG', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'DS', 'DLV', 'ANY', 'IXFR', 'AXFR');
$inverted = array('ANY', 'IXFR', 'AXFR');
$array = array();
foreach ($rrtypes as $rrtype)
{
$array[$rrtype] = array('descr' => $rrtype);
}
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['invert'] = in_array($data['descr'], $inverted);
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
#include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,46 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-ns-stats.rrd");
$array = array(
'AuthQryRej' => array('descr' => "Auth queries rejected", 'colour' => '6495ed'),
'RecQryRej' => array('descr' => "Recursive queries rejected", 'colour' => '40e0d0'),
'XfrRej' => array('descr' => "Transfer requests rejected", 'colour' => 'ffd700'),
'UpdateRej' => array('descr' => "Update requests rejected", 'colour' => 'cd853f'),
'UpdateBadPrereq' => array('descr' => "Updates rejected due to prereq fail", 'colour' => 'ff8c00'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Requests";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-req-in.rrd");
$array = array(
'query' => array('descr' => 'Query'),
'status' => array('descr' => 'Status'),
'notify' => array('descr' => 'Notify'),
'update' => array('descr' => 'Update'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,52 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-ns-stats.rrd");
$array = array(
'Requestv4' => array('descr' => "IPv4 requests", 'colour' => '006600'),
'Requestv6' => array('descr' => "IPv6 requests", 'colour' => '66cc66'),
'ReqEdns0' => array('descr' => "EDNS(0) requests", 'colour' => '9999ff'),
'RespEDNS0' => array('descr' => "EDNS(0) responses", 'colour' => '6666ff'),
'ReqTSIG' => array('descr' => "TSIG requests", 'colour' => 'ff9999'),
'RespTSIG' => array('descr' => "TSIG responses", 'colour' => 'ff6666'),
'ReqSIG0' => array('descr' => "SIG(0) requests", 'colour' => 'da70d6'),
'RespSIG0' => array('descr' => "responses with SIG(0) sent", 'colour' => '9932cc'),
'ReqTCP' => array('descr' => "TCP requests", 'colour' => 'ffd700'),
'Response' => array('descr' => "Responses sent", 'colour' => '999999'),
'TruncatedResp' => array('descr' => "Truncated Responses", 'colour' => 'ff0000'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,46 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-resolver-default.rrd");
$array = array(
'ValAttempt' => array('descr' => "Attempted validation", 'colour' => '4242CC', 'invert' => True),
'ValOk' => array('descr' => "Succeeded validation", 'colour' => '33A533'),
'ValNegOk' => array('descr' => "NX Succeeded validation", 'colour' => 'FFA500'),
'ValFail' => array('descr' => "Failed validation", 'colour' => 'ff0000'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$rrd_list[$i]['invert'] = $data['invert'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,50 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-resolver-default.rrd");
$array = array(
'EDNS0Fail' => array('descr' => "EDNS(0) query failures", 'colour' => '87cefa'),
'Mismatch' => array('descr' => "Mismatch responses received", 'colour' => '00bfff'),
'Truncated' => array('descr' => "Truncated responses received", 'colour' => 'ff69b4'),
'Lame' => array('descr' => "Lame delegations received", 'colour' => 'ff1493'),
'Retry' => array('descr' => "Retried queries", 'colour' => 'ffa07a'),
'QueryAbort' => array('descr' => "Aborted due to quota", 'colour' => 'ff6533'),
'QuerySockFail' => array('descr' => "Socket errors", 'colour' => 'ff8c00'),
'QueryTimeout' => array('descr' => "Timeouts", 'colour' => 'ff0000'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,50 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-resolver-default.rrd");
$array = array(
'Queryv4' => array('descr' => "Queries sent IPv4", 'colour' => '87cefa'),
'Responsev4' => array('descr' => "Responses received IPv4", 'colour' => '00bfff'),
'Queryv6' => array('descr' => "Queries sent IPv6", 'colour' => 'ff69b4'),
'Responsev6' => array('descr' => "Responses received IPv6", 'colour' => 'ff1493'),
'NXDOMAIN' => array('descr' => "NXDOMAIN received", 'colour' => 'ffa07a', 'invert' => True),
'SERVFAIL' => array('descr' => "SERVFAIL received", 'colour' => 'ff6533', 'invert' => True),
'FORMERR' => array('descr' => "FORMERR received", 'colour' => 'ff8c00', 'invert' => True),
'OtherError' => array('descr' => "Other error received", 'colour' => 'ff0000', 'invert' => True),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$rrd_list[$i]['invert'] = $data['invert'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,47 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-resolver-default.rrd");
$array = array(
'QryRTT10' => array('descr' => "< 10ms", 'colour' => '00d200'),
'QryRTT100' => array('descr' => "10-100ms", 'colour' => '26ac00'),
'QryRTT500' => array('descr' => "100-500ms", 'colour' => '498900'),
'QryRTT800' => array('descr' => "500-800ms", 'colour' => '894900'),
'QryRTT1600' => array('descr' => "800-1600ms", 'colour' => 'ac2600'),
'QryRTT1600plus' => array('descr' => "> 1600ms", 'colour' => 'd20000'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,48 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-ns-stats.rrd");
$array = array(
'UpdateDone' => array('descr' => "Completed", 'colour' => '228b22'),
'UpdateFail' => array('descr' => "Failed", 'colour' => 'ff0000'),
'UpdateRej' => array('descr' => "Rejected", 'colour' => 'cd853f'),
'UpdateBadPrereq' => array('descr' => "Rejected due to prereq fail", 'colour' => 'ff8c00'),
'UpdateReqFwd' => array('descr' => "Fwd request", 'colour' => '6495ed'),
'UpdateRespFwd' => array('descr' => "Fwd response", 'colour' => '40e0d0'),
'UpdateFwdFail' => array('descr' => "Fwd failed", 'colour' => 'ffd700'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,54 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-bind-".$app['app_id']."-zone-maint.rrd");
$array = array(
'NotifyOutv4' => array('descr' => "Notifies sent IPv4", 'colour' => '87cefa'),
'NotifyOutv6' => array('descr' => "Notifies sent IPv6", 'colour' => '00bfff'),
'NotifyInv4' => array('descr' => "Notifies received IPv4", 'colour' => '3cb371'),
'NotifyInv6' => array('descr' => "Notifies received IPv6", 'colour' => '2e8b57'),
'NotifyRej' => array('descr' => "Notifies rejected", 'colour' => 'ff8c00'),
'SOAOutv4' => array('descr' => "SOA queries sent IPv4", 'colour' => 'daa520'),
'SOAOutv6' => array('descr' => "SOA queries sent IPv6", 'colour' => 'b8860b'),
'AXFRReqv4' => array('descr' => "AXFR requested IPv4", 'colour' => 'da70d6'),
'AXFRReqv6' => array('descr' => "AXFR requested IPv6", 'colour' => '9932cc'),
'IXFRReqv4' => array('descr' => "IXFR requested IPv4", 'colour' => 'ff69b4'),
'IXFRReqv6' => array('descr' => "IXFR requested IPv6", 'colour' => 'ff1493'),
'XfrSuccess' => array('descr' => "Successful transfer", 'colour' => '32cd32'),
'XfrFail' => array('descr' => "Failed transfer", 'colour' => 'ff0000'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $data['colour'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "opsd";
$nototal = "true";
$rrd_filename = get_rrd_path($device, "app-ceph-".$app['app_id'].".rrd");
$array = array(
'ops' => array('descr' => 'Ceph Operations per second'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$i];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include("includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,46 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = 0;
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "app-ceph-".$app['app_id'].".rrd");
$array = array(
'OSD_total' => array('descr' => 'OSD total'),
'OSD_in' => array('descr' => 'OSD in'),
'OSD_out' => array('descr' => 'OSD out'),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$i];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,30 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$mysql_rrd = get_rrd_path($device, "app-ceph-".$app['app_id'].".rrd");
if (rrd_is_file($mysql_rrd))
{
$rrd_filename = $mysql_rrd;
}
$format = "bytes";
$ds_in = "wrbps";
$ds_out = "rdbps";
include($config['html_dir']."/includes/graphs/generic_data.inc.php");
// EOF

View File

@ -0,0 +1,53 @@
<?php
/**
* Observium Network Management and Monitoring System
*
* @package observium
* @subpackage graphs
* @author Sander Steffann <sander@steffann.nl>
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = str_replace('%index%', $app['app_id'], $config['rrd_types']['dhcpkit-stats']['file']);
$rrd_filename = get_rrd_path($device, $rrd_filename);
$simple_rrd = TRUE;
$array = array(
'msg_in_solicit' => array('descr' => 'Solicit', 'invert' => FALSE),
'msg_in_request' => array('descr' => 'Request', 'invert' => FALSE),
'msg_in_confirm' => array('descr' => 'Confirm', 'invert' => FALSE),
'msg_in_renew' => array('descr' => 'Renew', 'invert' => FALSE),
'msg_in_rebind' => array('descr' => 'Rebind', 'invert' => FALSE),
'msg_in_release' => array('descr' => 'Release', 'invert' => FALSE),
'msg_in_decline' => array('descr' => 'Decline', 'invert' => FALSE),
'msg_in_inf_req' => array('descr' => 'Inform. Request', 'invert' => FALSE),
'msg_out_advertise' => array('descr' => 'Advertise', 'invert' => TRUE),
'msg_out_reply' => array('descr' => 'Reply', 'invert' => TRUE),
'msg_out_reconfigure' => array('descr' => 'Reconfigure', 'invert' => TRUE),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['invert'] = $data['invert'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,49 @@
<?php
/**
* Observium Network Management and Monitoring System
*
* @package observium
* @subpackage graphs
* @author Sander Steffann <sander@steffann.nl>
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = (($width<224) ? 1 : 0);
$unit_text = "Count";
$rrd_filename = str_replace('%index%', $app['app_id'], $config['rrd_types']['dhcpkit-stats']['file']);
$rrd_filename = get_rrd_path($device, $rrd_filename);
$simple_rrd = TRUE;
$array = array(
'incoming_packets' => array('descr' => 'Incoming', 'invert' => FALSE),
'outgoing_packets' => array('descr' => 'Outgoing', 'invert' => TRUE),
'unparsable_packets' => array('descr' => 'Unparsable', 'invert' => TRUE),
'handling_errors' => array('descr' => 'Handling error', 'invert' => TRUE),
'for_other_server' => array('descr' => 'For other server', 'invert' => TRUE),
'do_not_respond' => array('descr' => 'Ignored', 'invert' => TRUE),
'use_multicast' => array('descr' => 'Use multicast', 'invert' => TRUE),
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['invert'] = $data['invert'];
$i++;
}
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,47 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'auth_successes' => array('descr' => 'Successful auths / s'),
'auth_master_success' => array('descr' => 'Master auths / s'),
'auth_failures' => array('descr' => 'Failed auths / s'),
'auth_db_tempfails' => array('descr' => 'Temporary failures / s')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'auth_cache_hits' => array('descr' => 'hits')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'mail_cache_hits' => array('descr' => 'Mail cache hits')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'num_cmds' => array('descr' => 'Commands')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,44 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'num_connected_sess' => array('descr' => 'Connected sessions')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,45 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'user_cpu' => array('descr' => 'User CPU'),
'sys_cpu' => array('descr' => 'System CPU')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,49 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'disk_input' => array('descr' => 'Disk Input'),
'disk_output' => array('descr' => 'Disk Output'),
'read_count' => array('descr' => 'Read Count'),
'read_bytes' => array('descr' => 'Read Bytes'),
'write_count' => array('descr' => 'Write Count'),
'write_bytes' => array('descr' => 'Write Bytes')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,45 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'min_faults' => array('descr' => 'Minor page reclaims'),
'maj_faults' => array('descr' => 'Major page reclaims')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,47 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'mail_lookup_path' => array('descr' => 'open() and stat() calls'),
'mail_lookup_attr' => array('descr' => 'stat() and fstat() calls'),
'mail_read_count' => array('descr' => 'read() calls for messages'),
'mail_read_bytes' => array('descr' => 'message bytes read()')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,45 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$scale_min = 0;
$colours = "mixed";
$nototal = (($width < 550) ? 1 : 0);
$rrd_filename = get_rrd_path($device, "app-dovecot.rrd");
$array = array(
'vol_cs' => array('descr' => 'Voluntary Context Switchess'),
'invol_cs' => array('descr' => 'Involuntary Context Switches')
);
$i = 0;
$x = 0;
if (rrd_is_file($rrd_filename))
{
$max_colours = safe_count($config['graph_colours'][$colours]);
foreach ($array as $ds => $data)
{
$x = (($x<=$max_colours) ? $x : 0);
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $data['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $config['graph_colours'][$colours][$x];
$i++;
$x++;
}
}
include($config['html_dir']."/includes/graphs/generic_multi.inc.php");
// EOF

View File

@ -0,0 +1,36 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = 0;
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$drbd_rrd = get_rrd_path($device, "app-drbd-".$app['app_instance'].".rrd");
if (rrd_is_file($drbd_rrd))
{
$rrd_filename = $drbd_rrd;
}
$ds_in = "dr";
$ds_out = "dw";
$leg_in = "Read";
$leg_out = "Written";
$multiplier = "1024";
$format = "bytes";
include($config['html_dir']."/includes/graphs/generic_data.inc.php");
// EOF

View File

@ -0,0 +1,32 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = 0;
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$drbd_rrd = get_rrd_path($device, "app-drbd-".$app['app_instance'].".rrd");
if (rrd_is_file($drbd_rrd))
{
$rrd_filename = $drbd_rrd;
}
$ds_in = "nr";
$ds_out = "ns";
$multiplier = "1024";
include($config['html_dir']."/includes/graphs/generic_data.inc.php");
// EOF

View File

@ -0,0 +1,48 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$rrd_filename = get_rrd_path($device, "app-drbd-".$app['app_instance'].".rrd");
$array = array(
'lo' => 'Local I/O',
'pe' => 'Pending',
'ua' => 'UnAcked',
'ap' => 'App Pending',
);
$i = 0;
if (rrd_is_file($rrd_filename))
{
foreach ($array as $ds => $data)
{
$rrd_list[$i]['filename'] = $rrd_filename;
if (is_array($data))
{
$rrd_list[$i]['descr'] = $data['descr'];
} else {
$rrd_list[$i]['descr'] = $data;
}
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else { echo("file missing: $rrd_filename"); }
$colours = "mixed";
$nototal = 0;
$unit_text = "";
include($config['html_dir']."/includes/graphs/generic_multi_simplex_separated.inc.php");
// EOF

View File

@ -0,0 +1,39 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
$scale_min = 0;
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$drbd_rrd = get_rrd_path($device, "app-drbd-".$app['app_instance'].".rrd");
if (rrd_is_file($drbd_rrd))
{
$rrd_filename = $drbd_rrd;
}
$ds = "oos";
$colour_area = "CDEB8B";
$colour_line = "006600";
$colour_area_max = "FFEE99";
$graph_max = 1;
$multiplier = 1000;
$unit_text = "Bytes";
include($config['html_dir']."/includes/graphs/generic_simplex.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Current Requests";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-as.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Current Requests";
$rrd_list[0]['ds'] = "currentrequests";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Ping Commands Pending";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-as.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Ping Commands Pending";
$rrd_list[0]['ds'] = "pingcommandspending";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Sync Commands Pending";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-as.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Sync Commands Pending";
$rrd_list[0]['ds'] = "synccommandspending";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Total Error Responses";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-auto.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Total Error Responses";
$rrd_list[0]['ds'] = "errorresponses";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Total Requests";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-auto.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Total Requests";
$rrd_list[0]['ds'] = "totalrequests";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Count";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-is.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Active Connection Count";
$rrd_list[0]['ds'] = "activeconcount";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Failed Requests";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-is.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Failed RPC Requests (Server Busy)";
$rrd_list[0]['ds'] = "clientrpcfailbusy";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,37 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "Requests";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-is.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "RPC Requests";
$rrd_list[0]['ds'] = "rpcrequests";
$rrd_list[1]['filename'] = $rrd_filename;
$rrd_list[1]['descr'] = "RPC Average Latency";
$rrd_list[1]['ds'] = "rpcavglatency";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "User Count";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-is.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "Current User Count";
$rrd_list[0]['ds'] = "usercount";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

View File

@ -0,0 +1,33 @@
<?php
/**
* Observium
*
* This file is part of Observium.
*
* @package observium
* @subpackage graphs
* @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
*
*/
include_once($config['html_dir']."/includes/graphs/common.inc.php");
$colours = "mixed";
$nototal = 1;
$unit_text = "ms";
$rrd_filename = get_rrd_path($device, "wmi-app-exchange-mailbox.rrd");
if (rrd_is_file($rrd_filename))
{
$rrd_list[0]['filename'] = $rrd_filename;
$rrd_list[0]['descr'] = "RPC Average Latency";
$rrd_list[0]['ds'] = "rpcavglatency";
} else {
echo("file missing: $rrd_filename");
}
include($config['html_dir']."/includes/graphs/generic_multi_line.inc.php");
// EOF

Some files were not shown because too many files have changed in this diff Show More