monitoring.module in Monitoring 7
Same filename and directory in other branches
Monitoring bootstrap file.
File
monitoring.moduleView source
<?php
/**
* @file
* Monitoring bootstrap file.
*/
use Drupal\monitoring\Sensor\NonExistingSensorException;
use Drupal\monitoring\Sensor\SensorInfo;
use Drupal\monitoring\Result\SensorResultInterface;
use Drupal\monitoring\Sensor\SensorManager;
use Drupal\monitoring\SensorRunner;
/**
* Returns an instance of the sensor manager.
*
* @return \Drupal\monitoring\Sensor\SensorManager
* The sensor manager.
*/
function monitoring_sensor_manager() {
$sensor_manager =& drupal_static(__FUNCTION__);
if (!$sensor_manager) {
$sensor_manager = new SensorManager();
}
return $sensor_manager;
}
/**
* Returns monitoring sensor info.
*
* @return \Drupal\monitoring\Sensor\SensorInfo[]
* List of SensorInfo instances.
*
* @throws \Drupal\monitoring\Sensor\NonExistingSensorException
* In case a sensor name is provided, which does not exists.
*
* @see \Drupal\monitoring\Sensor\SensorManager
*/
function monitoring_sensor_info() {
return monitoring_sensor_manager()
->getSensorInfo();
}
/**
* Menu load function to load a sensor info object.
*
* @param string $sensor_name
* Sensor name.
*
* @return \Drupal\monitoring\Sensor\SensorInfo
* A SensorInfo instance.
*/
function monitoring_sensor_info_load($sensor_name) {
try {
return monitoring_sensor_manager()
->getSensorInfoByName($sensor_name);
} catch (NonExistingSensorException $e) {
// Return FALSE if a sensor does not exist, this will lead to a page not
// found response.
return FALSE;
}
}
/**
* Gets sensor info grouped by categories.
*
* @param bool $enabled
* Sensor isEnabled flag.
*
* @return \Drupal\monitoring\Sensor\SensorInfo[]
* Sensor info.
*/
function monitoring_sensor_info_by_categories($enabled = TRUE) {
return monitoring_sensor_manager()
->getSensorInfoByCategories($enabled);
}
/**
* The sensor runner function.
*
* Note that in case there is a cached result for given sensor name, the sensor
* will not run and the cached result will be returned.
*
* @param string $sensor_name
* The name of the sensor that is to be run.
* @param bool $force_run
* Set to TRUE to force the run. Defaults to FALSE.
* @param bool $verbose
* (optional) Set to TRUE to enable verbose execution, defaults to FALSE.
*
* @return SensorResultInterface
* A single result object.
*
* @throws \Drupal\monitoring\Sensor\NonExistingSensorException
* Thrown if the requested sensor does not exist.
* @throws \Drupal\monitoring\Sensor\DisabledSensorException
* Thrown if any of the passed sensor names is not enabled.
*/
function monitoring_sensor_run($sensor_name, $force_run = FALSE, $verbose = FALSE) {
$results = monitoring_sensor_run_multiple(array(
$sensor_name,
), $force_run, $verbose);
return reset($results);
}
/**
* Runs sensors.
*
* @param array $sensor_names
* Sensor names to run.
* @param bool $force_run
* Flag to force run.
* @param bool $verbose
* (optional) Set to TRUE to enable verbose execution, defaults to FALSE.
*
* @return \Drupal\monitoring\Result\SensorResultInterface[]
* List of result objects.
*
* @throws \Drupal\monitoring\Sensor\NonExistingSensorException
* Thrown if the requested sensor does not exist.
* @throws \Drupal\monitoring\Sensor\DisabledSensorException
* Thrown if any of the passed sensor names is not enabled.
*
* @see \Drupal\monitoring\Sensor\SensorManager
* @see \Drupal\monitoring\SensorRunner
*/
function monitoring_sensor_run_multiple($sensor_names = array(), $force_run = FALSE, $verbose = FALSE) {
$sensors_info = array();
if (empty($sensor_names)) {
foreach (monitoring_sensor_manager()
->getEnabledSensorInfo() as $sensor_name => $sensor_info) {
$sensors_info[$sensor_name] = $sensor_info;
}
}
else {
foreach ($sensor_names as $sensor_name) {
$sensors_info[$sensor_name] = monitoring_sensor_manager()
->getSensorInfoByName($sensor_name);
}
}
$runner = new SensorRunner($sensors_info);
$runner
->verbose($verbose);
$runner
->forceRun($force_run);
$results = $runner
->runSensors();
return $results;
}
/**
* Implements hook_entity_info().
*/
function monitoring_entity_info() {
$info['monitoring_sensor_result'] = array(
'label' => t('Monitoring sensor result'),
'module' => 'monitoring',
'controller class' => 'Drupal\\monitoring\\Controller\\SensorResultController',
'metadata controller class' => 'Drupal\\monitoring\\Controller\\SensorResultMetadataController',
'views controller class' => 'Drupal\\monitoring\\Controller\\SensorResultViewsController',
'entity class' => 'Drupal\\monitoring\\Entity\\SensorResultEntity',
'base table' => 'monitoring_sensor_result',
'uri callback' => 'entity_class_uri',
'label callback' => 'entity_class_label',
'entity keys' => array(
'id' => 'record_id',
),
);
return $info;
}
/**
* Implements hook_views_api().
*/
function monitoring_views_api() {
return array(
'api' => 3,
);
}
/**
* Implements hook_preprocess_HOOK().
*
* Display a view as a table style.
*/
function monitoring_preprocess_views_view_table(&$vars) {
// We want to alter only the monitoring sensor results view.
if ($vars['view']->name != 'monitoring_sensor_results') {
return;
}
$vars['classes_array'][] = 'monitoring-severity-colors';
foreach ($vars['rows'] as $num => $row) {
if (isset($vars['result'][$num]->monitoring_sensor_result_sensor_status)) {
$vars['row_classes'][$num][] = 'monitoring-' . strtolower($vars['result'][$num]->monitoring_sensor_result_sensor_status);
}
}
drupal_add_css(drupal_get_path('module', 'monitoring') . '/monitoring.css');
}
/**
* Implements hook_menu().
*/
function monitoring_menu() {
$items['admin/config/system/monitoring'] = array(
'title' => 'Monitoring',
'description' => 'Manage sensors, configure enabled monitoring products.',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'monitoring_config_sensors_overview_form',
),
'access arguments' => array(
'administer monitoring',
),
'file' => 'monitoring.admin.inc',
);
$items['admin/config/system/monitoring/sensors'] = array(
'title' => 'Sensors',
'description' => 'Configure all available sensors',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/config/system/monitoring/settings'] = array(
'title' => 'Monitoring settings',
'description' => 'Configure monitoring behaviour',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'monitoring_settings_form',
),
'access arguments' => array(
'administer monitoring',
),
'file' => 'monitoring.admin.inc',
'weight' => -9,
'type' => MENU_LOCAL_TASK,
);
$items['admin/config/system/monitoring/sensors/%monitoring_sensor_info'] = array(
'title callback' => 'monitoring_sensor_action_title',
'title arguments' => array(
'settings',
5,
),
'description' => 'Monitoring sensor configuration',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'monitoring_sensor_settings_form',
5,
),
'access arguments' => array(
'administer monitoring',
),
'file' => 'monitoring.admin.inc',
'type' => MENU_VISIBLE_IN_BREADCRUMB,
'weight' => -10,
);
$items['admin/reports/monitoring'] = array(
'title' => 'Monitoring',
'description' => 'View sensor results and logs.',
'page callback' => 'monitoring_reports_sensors_overview',
'access arguments' => array(
'monitoring reports',
),
'file' => 'monitoring.admin.inc',
);
$items['admin/reports/monitoring/sensors'] = array(
'title' => 'Sensors',
'description' => 'Overview of all enabled monitoring sensors.',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/reports/monitoring/sensors/%monitoring_sensor_info'] = array(
'title callback' => 'monitoring_sensor_action_title',
'title arguments' => array(
'details',
4,
),
'description' => 'Details',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'monitoring_sensor_details',
4,
),
'access arguments' => array(
'monitoring reports',
),
'file' => 'monitoring.admin.inc',
);
$items['admin/reports/monitoring/sensors/%monitoring_sensor_info/details'] = array(
'title' => 'Details',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -16,
);
$items['monitoring/sensors/force'] = array(
'title' => 'Force run all sensors',
'page callback' => 'monitoring_force_execution',
'access arguments' => array(
'monitoring force run',
),
'file' => 'monitoring.admin.inc',
);
return $items;
}
/**
* Sensor pages title callback.
*
* @param string $action
* View/page action.
* @param \Drupal\monitoring\Sensor\SensorInfo $sensor_info
* Sensor info.
*
* @return string
* Title.
*/
function monitoring_sensor_action_title($action, SensorInfo $sensor_info) {
$placeholders = array(
'@category' => $sensor_info
->getCategory(),
'@label' => $sensor_info
->getLabel(),
);
switch ($action) {
case 'settings':
return t('@label settings (@category)', $placeholders);
case 'details':
case 'log':
return t('@label (@category)', $placeholders);
}
return '';
}
/**
* Implements hook_permission().
*/
function monitoring_permission() {
return array(
'administer monitoring' => array(
'title' => t('Administer monitoring'),
),
'monitoring reports' => array(
'title' => t('View monitoring reports'),
),
'monitoring verbose' => array(
'title' => t('Display verbose monitoring sensor info'),
),
'monitoring force run' => array(
'title' => t('Force run monitoring sensor execution'),
),
);
}
/**
* Implements hook_services_resources().
*
* Offer services resources:
* - sensor-info: Available sensors info
* - sensor-result: Available sensor results
*/
function monitoring_services_resources() {
$resources = array();
$resources['sensor-info']['operations'] = array(
'index' => array(
'file' => array(
'type' => 'inc',
'module' => 'monitoring',
'name' => 'monitoring.services',
),
'help' => t('Available sensors info'),
'callback' => 'monitoring_services_sensors_info',
'access callback' => 'user_access',
'access arguments' => array(
'monitoring reports',
),
),
'retrieve' => array(
'file' => array(
'type' => 'inc',
'module' => 'monitoring',
'name' => 'monitoring.services',
),
'help' => t('Specific sensor info'),
'callback' => 'monitoring_services_sensor_info',
'access callback' => 'user_access',
'access arguments' => array(
'monitoring reports',
),
'args' => array(
array(
'name' => 'sensor_name',
'optional' => FALSE,
'source' => array(
'path' => 0,
),
'type' => 'string',
'description' => 'Sensor name.',
),
),
),
);
$resources['sensor-result']['operations'] = array(
'index' => array(
'file' => array(
'type' => 'inc',
'module' => 'monitoring',
'name' => 'monitoring.services',
),
'help' => t('Available sensor results'),
'callback' => 'monitoring_services_sensors_results',
'access callback' => 'user_access',
'access arguments' => array(
'monitoring reports',
),
'args' => array(
array(
'name' => 'expand',
'type' => 'string',
'description' => t('Additional sensor result data to expand. I.e. expand=sensor_info'),
'source' => array(
'param' => 'expand',
),
'optional' => TRUE,
),
),
),
'retrieve' => array(
'file' => array(
'type' => 'inc',
'module' => 'monitoring',
'name' => 'monitoring.services',
),
'help' => t('Specific sensor result'),
'callback' => 'monitoring_services_sensor_result',
'access callback' => 'user_access',
'access arguments' => array(
'monitoring reports',
),
'args' => array(
array(
'name' => 'sensor_name',
'optional' => FALSE,
'source' => array(
'path' => 0,
),
'type' => 'string',
'description' => 'Sensor name.',
),
array(
'name' => 'expand',
'type' => 'string',
'description' => t('Additional sensor result data to expand. I.e. expand=sensor_info'),
'source' => array(
'param' => 'expand',
),
'optional' => TRUE,
),
),
),
);
return $resources;
}
/**
* Saves sensor settings.
*
* @param string $sensor_name
* Sensor name.
* @param array $values
* Settings to be saved.
*/
function monitoring_sensor_settings_save($sensor_name, $values) {
variable_set(monitoring_sensor_settings_key($sensor_name), $values);
// After settings save reset the cache.
monitoring_sensor_manager()
->resetCache();
// Changed settings might affect the sensor result.
SensorRunner::resetCache(array(
$sensor_name,
));
}
/**
* Gets sensor settings.
*
* @param string $sensor_name
* Sensor name.
*
* @return array
* Sensor saved settings.
*/
function monitoring_sensor_settings_get($sensor_name) {
return variable_get(monitoring_sensor_settings_key($sensor_name), array());
}
/**
* Build the sensor settings key.
*
* @param string $sensor_name
* Sensor name.
*
* @return string
* Sensor settings key.
*/
function monitoring_sensor_settings_key($sensor_name) {
return 'monitoring_' . $sensor_name . '_settings';
}
/**
* Saves the sensor result.
*
* @param SensorResultInterface $result
* Sensor call result.
*
* @return \Drupal\monitoring\Entity\SensorResultEntity
* Sensor result entity.
*/
function monitoring_sensor_result_save(SensorResultInterface $result) {
$values = array(
'sensor_name' => $result
->getSensorName(),
'sensor_status' => $result
->getStatus(),
'sensor_message' => $result
->getMessage(),
'sensor_value' => $result
->getValue(),
'timestamp' => $result
->getTimestamp(),
'execution_time' => $result
->getExecutionTime(),
);
$result_entity = entity_create('monitoring_sensor_result', $values);
entity_save('monitoring_sensor_result', $result_entity);
return $result_entity;
}
/**
* Gets last sensor result.
*
* @param string $sensor_name
* The name of the sensor.
*
* @return \Drupal\monitoring\Entity\SensorResultEntity|null
* A SensorResultEntity representing the last sensor result.
*/
function monitoring_sensor_result_last($sensor_name) {
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'monitoring_sensor_result');
$query
->propertyCondition('sensor_name', $sensor_name);
$query
->propertyOrderBy('timestamp', 'DESC');
$query
->range(0, 1);
$result = $query
->execute();
if (isset($result['monitoring_sensor_result'])) {
$row = array_shift($result['monitoring_sensor_result']);
return entity_load_single('monitoring_sensor_result', $row->record_id);
}
return NULL;
}
/**
* Implements hook_views_pre_render().
*
* Alters the views page title.
*/
function monitoring_views_pre_render(View &$view) {
if ($view->name == 'monitoring_sensor_results' && !empty($view->args)) {
$view->build_info['title'] = monitoring_sensor_action_title('log', monitoring_sensor_info_load($view->args[0]));
}
}
/**
* Implements hook_theme().
*/
function monitoring_theme() {
return array(
'monitoring_config_box' => array(
'variables' => array(
'title' => NULL,
'description' => NULL,
'code' => NULL,
'code_height' => NULL,
),
),
'monitoring_overview_summary' => array(
'variables' => array(
'status_overview' => array(),
'total_execution_time' => NULL,
'non_cached_execution_time' => NULL,
'oldest_sensor_label' => NULL,
'oldest_sensor_category' => NULL,
'oldest_sensor_called_before' => NULL,
),
),
);
}
/**
* Monitoring config code box theme.
*
* @param array $variables
* Theme variables.
*
* @return string
* Formatted output.
*/
function theme_monitoring_config_box($variables) {
$output = '';
if (!empty($variables['title'])) {
$output .= '<h3>' . check_plain($variables['title']) . '</h3>';
}
if (!empty($variables['description'])) {
$output .= '<p>' . check_plain($variables['description']) . '</p>';
}
if (!empty($variables['code'])) {
$variables['code_height'] = !empty($variables['code_height']) ? $variables['code_height'] : '100';
$output .= '<pre style="border:1px solid silver;padding:4px;height:' . $variables['code_height'] . 'px;overflow:auto;">' . check_plain($variables['code']) . '</pre>';
}
return $output;
}
/**
* Get config code with dynamic variables.
*
* @param string $module
* Module name.
* @param string $type
* Config type.
* @param array $variables
* Dynamic values.
*
* @return string
* Config code.
*/
function monitoring_config_code($module, $type, $variables = array()) {
$code = file_get_contents(drupal_get_path('module', $module) . '/config_tpl/' . $type . '.txt');
return format_string($code, $variables);
}
/**
* Monitoring overview page summary.
*
* @param array $variables
* Theme variables.
*
* @return string
* Formatted output.
*/
function theme_monitoring_overview_summary($variables) {
$output = '<div class="monitoring-overview-summary">';
$output .= t('<span class="monitoring-summary-time">Request execution time: <strong>@time_non_cachedms</strong> (including cached <strong>@time_totalms</strong>)</span>, <span class="monitoring-summary-ok"> </span> @ok OK, <span class="monitoring-summary-info"> </span> @info Info, <span class="monitoring-summary-warning"> </span> @warning Warning, <span class="monitoring-summary-critical"> </span> @critical Critical, <span class="monitoring-summary-unknown"> </span> @unknown Unknown', array(
'@time_total' => $variables['total_execution_time'],
'@time_non_cached' => $variables['non_cached_execution_time'],
'@ok' => $variables['status_overview'][SensorResultInterface::STATUS_OK],
'@info' => $variables['status_overview'][SensorResultInterface::STATUS_INFO],
'@warning' => $variables['status_overview'][SensorResultInterface::STATUS_WARNING],
'@critical' => $variables['status_overview'][SensorResultInterface::STATUS_CRITICAL],
'@unknown' => $variables['status_overview'][SensorResultInterface::STATUS_UNKNOWN],
));
$output .= '</div>';
if (user_access('monitoring force run')) {
$output .= '<div class="monitoring-overview-summary-actions-right">' . l(t('Force execute all'), 'monitoring/sensors/force') . '</div>';
}
if (!empty($variables['oldest_sensor_label'])) {
$output .= '<div class="monitoring-overview-summary-actions-right">' . t('Sensor %sensor (%category) cached before %before.', array(
'%sensor' => $variables['oldest_sensor_label'],
'%before' => $variables['oldest_sensor_called_before'],
'%category' => $variables['oldest_sensor_category'],
)) . '</div>';
}
else {
$output .= '<div class="monitoring-overview-summary-actions-right">' . t('No sensor cached.') . '</div>';
}
return $output;
}
/**
* Gets current site host.
*
* @return string
* Site url.
*/
function monitoring_host() {
global $base_url;
return preg_replace('/^http(s)?:\\/\\//', '', $base_url);
}
/**
* Gets host key.
*
* @return string
* Host key.
*/
function monitoring_host_key() {
return str_replace('.', '_', monitoring_host());
}
/**
* Submit callback to clear the disappeared sensors list.
*
* @see \Drupal\monitoring\Sensor\Sensors\SensorDisappearedSensors::settingsForm()
*/
function monitoring_clear_missing_sensor_submit($form, &$form_state) {
$available_sensors = array();
foreach (monitoring_sensor_info() as $key => $info) {
$available_sensors[$key] = array(
'name' => $key,
'label' => $info
->getLabel(),
'enabled' => $info
->isEnabled(),
);
}
variable_set('monitoring_available_sensors', $available_sensors);
drupal_set_message(t('All missing sensors have been cleared.'));
}
/**
* Implements hook_modules_enabled().
*
* Enabling modules can change the available sensors, reset the cache to make
* sure that the list is up to date.
*/
function monitoring_modules_enabled($modules) {
monitoring_sensor_manager()
->resetCache();
}
/**
* Implements hook_modules_disabled().
*
* Disabling modules can change the available sensors, reset the cache to make
* sure that the list is up to date.
*/
function monitoring_modules_disabled($modules) {
//
monitoring_sensor_manager()
->resetCache();
}
/**
* Gets available value types definitions.
*
* @return array
* Value type definitions, consisting of a label and an optional
* formatter_callback.
*/
function monitoring_value_types() {
// @todo Allow extension of those types throgh a hook or plugin system.
return array(
'time_interval' => array(
'label' => 'Seconds',
'formatter_callback' => 'monitoring_value_label_callback_interval',
),
'bool' => array(
'label' => 'Status',
'formatter_callback' => 'monitoring_value_label_callback_bool',
),
'commerce_currency' => array(
'label' => 'Commerce currency',
'formatter_callback' => 'monitoring_value_label_callback_commerce_currency',
),
);
}
/**
* Formatter for time interval value.
*
* @param \Drupal\monitoring\Result\SensorResultInterface $result
* Result object for which to get the formatted value.
*
* @return string
* Formatted time interval.
*
* @see format_interval()
*/
function monitoring_value_label_callback_interval(SensorResultInterface $result) {
return format_interval($result
->getValue());
}
/**
* Formatter for boolean value (TRUE, FALSE).
*
* @param \Drupal\monitoring\Result\SensorResultInterface $result
* Result object for which to get the formatted value.
*
* @return string
* TRUE or FALSE strings.
*/
function monitoring_value_label_callback_bool(SensorResultInterface $result) {
return $result
->getValue() ? 'TRUE' : 'FALSE';
}
/**
* Formatter for commerce currency amount value.
*
* @param \Drupal\monitoring\Result\SensorResultInterface $result
* Result object for which to get the formatted value.
*
* @return string
* Formatted amount.
*
* @see commerce_default_currency()
* @see commerce_currency_format()
*/
function monitoring_value_label_callback_commerce_currency(SensorResultInterface $result) {
if (module_exists('commerce')) {
$currency = $result
->getSensorInfo()
->getSetting('currency_code');
if (empty($currency)) {
$currency = commerce_default_currency();
}
// commerce_currency_format() uses @placeholders and runs the price through
// check_plain(), that can cause double encoding, so decode entities again.
return html_entity_decode(commerce_currency_format($result
->getValue(), $currency, NULL, FALSE), ENT_QUOTES);
}
return $result
->getValue();
}