Device-Groups Draft

This commit is contained in:
f0o
2015-04-03 18:22:29 +00:00
parent 1a8c76268c
commit ba99eb25a2
20 changed files with 952 additions and 2 deletions

View File

@ -29,7 +29,22 @@ if (isset($_REQUEST['search']))
{
$found = 0;
if($_REQUEST['type'] == 'device') {
if( $_REQUEST['type'] == 'group' ) {
include_once('../includes/device-groups.inc.php');
foreach( dbFetchRows("SELECT name FROM device_groups WHERE name LIKE '%".$search."%'") as $group ) {
if( $_REQUEST['map'] ) {
$results[] = array('name'=>'g:'.$group['name']);
} else {
$results[] = array('name'=>$group['name']);
}
}
die(json_encode($results));
} elseif( $_REQUEST['type'] == 'alert-rules' ) {
foreach( dbFetchRows("SELECT name FROM alert_rules WHERE name LIKE '%".$search."%'") as $rules ) {
$results[] = array('name'=>$rules['name']);
}
die(json_encode($results));
} elseif($_REQUEST['type'] == 'device') {
// Device search
$results = dbFetchRows("SELECT * FROM `devices` WHERE `hostname` LIKE '%" . $search . "%' OR `location` LIKE '%" . $search . "%' ORDER BY hostname LIMIT 8");

View File

@ -55,6 +55,15 @@ if(empty($rule)) {
} else {
if( dbInsert(array('device_id'=>$device_id,'rule'=>$rule,'severity'=>mres($_POST['severity']),'extra'=>$extra_json,'name'=>$name),'alert_rules') ) {
$update_message = "Added Rule: <i>$name: $rule</i>";
if( is_array($_POST['maps']) ) {
foreach( $_POST['maps'] as $target ) {
$_POST['rule'] = $name;
$_POST['target'] = $target;
$_POST['map_id'] = '';
include('forms/create-map-item.inc.php');
unset($ret,$target,$raw,$rule,$msg,$map_id);
}
}
} else {
$update_message = "ERROR: Failed to add Rule: <i>".$rule."</i>";
}

View File

@ -0,0 +1,52 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
$pattern = $_POST['patterns'];
$group_id = $_POST['group_id'];
$name = mres($_POST['name']);
$desc = mres($_POST['desc']);
if( is_array($pattern) ) {
$pattern = implode(" ", $pattern);
$pattern = rtrim($pattern,'&&');
$pattern = rtrim($pattern,'||');
} elseif( !empty($_POST['pattern']) && !empty($_POST['condition']) && !empty($_POST['value']) ) {
$pattern = '%'.$_POST['pattern'].' '.$_POST['condition'].' ';
if( is_numeric($_POST['value']) ) {
$pattern .= $_POST['value'];
} else {
$pattern .= '"'.$_POST['value'].'"';
}
}
if(empty($pattern)) {
$update_message = "ERROR: No group was generated";
} elseif(is_numeric($group_id) && $group_id > 0) {
if(dbUpdate(array('pattern' => $pattern,'name'=>$name,'desc'=>$desc), 'device_groups', 'id=?',array($group_id)) >= 0) {
$update_message = "Edited Group: <i>$name: $pattern</i>";
} else {
$update_message = "ERROR: Failed to edit Group: <i>".$pattern."</i>";
}
} else {
if( dbInsert(array('pattern'=>$pattern,'name'=>$name,'desc'=>$desc),'device_groups') ) {
$update_message = "Added Group: <i>$name: $pattern</i>";
} else {
$update_message = "ERROR: Failed to add Group: <i>".$pattern."</i>";
}
}
echo $update_message;

View File

@ -0,0 +1,59 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
$rule = mres($_POST['rule']);
$target = mres($_POST['target']);
$map_id = mres($_POST['map_id']);
$ret = array();
if( empty($rule) || empty($target) ) {
$ret[] = "ERROR: No map was generated";
} else {
$raw = $rule;
$rule = dbFetchCell('SELECT id FROM alert_rules WHERE name = ?',array($rule));
if( !is_numeric($target) && $target[0] != "g" ) {
array_unshift($ret, "ERROR: Could not find rule for '".$raw."'");
} else {
$raw = $target;
if( $target[0].$target[1] == "g:" ) {
$target = "g".dbFetchCell('SELECT id FROM device_groups WHERE name = ?',array(substr($target,2)));
} else {
$target = dbFetchCell('SELECT device_id FROM devices WHERE hostname = ?',array($target));
}
if( !is_numeric($target) && $target[0] != "g" ) {
array_unshift($ret, "ERROR: Could not find entry for '".$raw."'");
} else {
if(is_numeric($map_id) && $map_id > 0) {
if(dbUpdate(array('rule' => $rule,'target'=>$target), 'alert_map', 'id=?',array($map_id)) >= 0) {
$ret[] = "Edited Map: <i>".$map_id.": ".$rule." = ".$target."</i>";
} else {
array_unshift($ret,"ERROR: Failed to edit Map: <i>".$map_id.": ".$rule." = ".$target."</i>");
}
} else {
if( dbInsert(array('rule'=>$rule,'target'=>$target),'alert_map') ) {
$ret[] = "Added Map: <i>".$rule." = ".$target."</i>";
} else {
array_unshift($ret,"ERROR: Failed to add Map: <i>".$rule." = ".$target."</i>");
}
}
}
}
}
foreach( $ret as $msg ) {
echo $msg."<br/>";
}

View File

@ -0,0 +1,31 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['map_id'])) {
echo('ERROR: No map selected');
exit;
} else {
if(dbDelete('alert_map', "`id` = ?", array($_POST['map_id']))) {
echo('Map has been deleted.');
exit;
} else {
echo('ERROR: Map has not been deleted.');
exit;
}
}

View File

@ -0,0 +1,31 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
if(!is_numeric($_POST['group_id'])) {
echo('ERROR: No group selected');
exit;
} else {
if(dbDelete('device_groups', "`id` = ?", array($_POST['group_id']))) {
echo('group has been deleted.');
exit;
} else {
echo('ERROR: group has not been deleted.');
exit;
}
}

View File

@ -0,0 +1,30 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
$map_id = $_POST['map_id'];
if(is_numeric($map_id) && $map_id > 0) {
$map = dbFetchRow("SELECT alert_rules.name,alert_map.target FROM alert_map,alert_rules WHERE alert_map.rule=alert_rules.id && alert_map.id = ?",array($map_id));
if( $map['target'][0] == "g" ) {
$map['target'] = 'g:'.dbFetchCell("SELECT name FROM device_groups WHERE id = ?",array(substr($map['target'],1)));
} else {
$map['target'] = dbFetchCell("SELECT hostname FROM devices WHERE device_id = ?",array($map['target']));
}
$output = array('rule'=>$map['name'],'target'=>$map['target']);
echo _json_encode($output);
}

View File

@ -0,0 +1,28 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
$group_id = $_POST['group_id'];
if(is_numeric($group_id) && $group_id > 0) {
$group = dbFetchRow("SELECT * FROM `device_groups` WHERE `id` = ? LIMIT 1",array($group_id));
$group_split = preg_split('/([a-zA-Z0-9_\-\.\=\%\<\>\ \"\'\!\~\(\)\*\/\@]+[&&\|\|]+)/',$group['pattern'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$count = count($group_split) - 1;
$group_split[$count] = $group_split[$count].' &&';
$output = array('name'=>$group['name'],'desc'=>$group['desc'],'pattern'=>$group_split);
echo _json_encode($output);
}

View File

@ -0,0 +1,70 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
?>
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="Delete" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h5 class="modal-title" id="Delete">Confirm Delete</h5>
</div>
<div class="modal-body">
<p>If you would like to remove the alert map then please click Delete.</p>
</div>
<div class="modal-footer">
<form role="form" class="remove_token_form">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger danger" id="alert-map-removal" data-target="alert-map-removal">Delete</button>
<input type="hidden" name="map_id" id="map_id" value="">
<input type="hidden" name="confirm" id="confirm" value="yes">
</form>
</div>
</div>
</div>
</div>
<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
event.preventDefault();
map_id = $(e.relatedTarget).data('map_id');
$("#map_id").val(map_id);
});
$('#alert-map-removal').click('', function(event) {
event.preventDefault();
var map_id = $("#map_id").val();
$.ajax({
type: 'POST',
url: '/ajax_form.php',
data: { type: "delete-alert-map", map_id: map_id },
dataType: "html",
success: function(msg) {
if(msg.indexOf("ERROR:") <= -1) {
$("#row_"+map_id).remove();
}
$("#message").html('<div class="alert alert-info">'+msg+'</div>');
$("#confirm-delete").modal('hide');
},
error: function() {
$("#message").html('<div class="alert alert-info">The alert map could not be deleted.</div>');
$("#confirm-delete").modal('hide');
}
});
});
</script>

View File

@ -0,0 +1,70 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() === false) {
die('ERROR: You need to be admin');
}
?>
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="Delete" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h5 class="modal-title" id="Delete">Confirm Delete</h5>
</div>
<div class="modal-body">
<p>If you would like to remove the device group then please click Delete.</p>
</div>
<div class="modal-footer">
<form role="form" class="remove_token_form">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger danger" id="device-group-removal" data-target="device-group-removal">Delete</button>
<input type="hidden" name="group_id" id="group_id" value="">
<input type="hidden" name="confirm" id="confirm" value="yes">
</form>
</div>
</div>
</div>
</div>
<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
event.preventDefault();
group_id = $(e.relatedTarget).data('group_id');
$("#group_id").val(group_id);
});
$('#device-group-removal').click('', function(event) {
event.preventDefault();
var group_id = $("#group_id").val();
$.ajax({
type: 'POST',
url: '/ajax_form.php',
data: { type: "delete-device-group", group_id: group_id },
dataType: "html",
success: function(msg) {
if(msg.indexOf("ERROR:") <= -1) {
$("#row_"+group_id).remove();
}
$("#message").html('<div class="alert alert-info">'+msg+'</div>');
$("#confirm-delete").modal('hide');
},
error: function() {
$("#message").html('<div class="alert alert-info">The device group could not be deleted.</div>');
$("#confirm-delete").modal('hide');
}
});
});
</script>

View File

@ -0,0 +1,127 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() !== false) {
?>
<div class="modal fade bs-example-modal-sm" id="create-map" tabindex="-1" role="dialog" aria-labelledby="Create" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h5 class="modal-title" id="Create">Alert Maps</h5>
</div>
<div class="modal-body">
<form method="post" role="form" id="maps" class="form-horizontal maps-form">
<input type="hidden" name="map_id" id="map_id" value="">
<input type="hidden" name="type" id="type" value="create-map-item">
<div class='form-group'>
<label for='name' class='col-sm-3 control-label'>Rule: </label>
<div class='col-sm-9'>
<input type='text' id='rule' name='rule' class='form-control' maxlength='200'>
</div>
</div>
<div class="form-group">
<label for='target' class='col-sm-3 control-label'>Target: </label>
<div class="col-sm-9">
<input type='text' id='target' name='target' class='form-control' placeholder='Group or Hostname'/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-default btn-sm" type="submit" name="map-submit" id="map-submit" value="save">Save map</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$('#create-map').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var map_id = button.data('map_id');
var modal = $(this)
$('#map_id').val(map_id);
$.ajax({
type: "POST",
url: "/ajax_form.php",
data: { type: "parse-alert-map", map_id: map_id },
dataType: "json",
success: function(output) {
$('#rule').val(output['rule']);
$('#target').val(output['target']);
}
});
});
var cache = {};
$('#rule').typeahead([
{
name: 'map_rules',
remote : '/ajax_search.php?search=%QUERY&type=alert-rules',
template: '{{name}}',
valueKey:"name",
engine: Hogan
}
]);
$('#target').typeahead([
{
name: 'map_devices',
remote : '/ajax_search.php?search=%QUERY&type=device&map=1',
header : '<h5><strong>&nbsp;Devices</strong></h5>',
template: '{{name}}',
valueKey:"name",
engine: Hogan
},
{
name: 'map_groups',
remote : '/ajax_search.php?search=%QUERY&type=group&map=1',
header : '<h5><strong>&nbsp;Groups</strong></h5>',
template: '{{name}}',
valueKey:"name",
engine: Hogan
}
]);
$('#map-submit').click('', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/ajax_form.php",
data: $('form.maps-form').serialize(),
success: function(msg){
$("#message").html('<div class="alert alert-info">'+msg+'</div>');
$("#create-map").modal('hide');
if(msg.indexOf("ERROR:") <= -1) {
setTimeout(function() {
location.reload(1);
}, 1000);
}
},
error: function(){
$("#message").html('<div class="alert alert-info">An error occurred creating this map.</div>');
$("#create-map").modal('hide');
}
});
});
</script>
<?php
}
?>

View File

@ -108,6 +108,22 @@ if(is_admin() !== false) {
<input type='text' id='name' name='name' class='form-control' maxlength='200'>
</div>
</div>
<div id="preseed-maps">
<div class="form-group">
<label for='map-stub' class='col-sm-3 control-label'>Map To: </label>
<div class="col-sm-5">
<input type='text' id='map-stub' name='map-stub' class='form-control'/>
</div>
<div class="col-sm-3">
<button class="btn btn-primary btn-sm" type="button" name="add-map" id="add-map" value="Add">Add</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span id="map-tags"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-default btn-sm" type="submit" name="rule-submit" id="rule-submit" value="save">Save Rule</button>
@ -126,6 +142,12 @@ $("[name='invert']").bootstrapSwitch('offColor','danger');
$('#create-alert').on('hide.bs.modal', function (event) {
$('#response').data('tagmanager').empty();
$('#map-tags').data('tagmanager').empty();
});
$('#add-map').click('',function (event) {
$('#map-tags').data('tagmanager').populate([ $('#map-stub').val() ]);
$('#map-stub').val('');
});
$('#create-alert').on('show.bs.modal', function (event) {
@ -140,6 +162,16 @@ $('#create-alert').on('show.bs.modal', function (event) {
strategy: 'array',
tagFieldName: 'rules[]'
});
$('#map-tags').tagmanager({
strategy: 'array',
tagFieldName: 'maps[]',
initialCap: false
});
if( $('#alert_id').val() == '' ) {
$('#preseed-maps').show();
} else {
$('#preseed-maps').hide();
}
$.ajax({
type: "POST",
url: "/ajax_form.php",
@ -183,6 +215,24 @@ $('#suggest').typeahead([
engine: Hogan
}
]);
$('#map-stub').typeahead([
{
name: 'map_devices',
remote : '/ajax_search.php?search=%QUERY&type=device&map=1',
header : '<h5><strong>&nbsp;Devices</strong></h5>',
template: '{{name}}',
valueKey:"name",
engine: Hogan
},
{
name: 'map_groups',
remote : '/ajax_search.php?search=%QUERY&type=group&map=1',
header : '<h5><strong>&nbsp;Groups</strong></h5>',
template: '{{name}}',
valueKey:"name",
engine: Hogan
}
]);
$('#and, #or').click('', function(e) {
e.preventDefault();

View File

@ -0,0 +1,189 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if(is_admin() !== false) {
?>
<div class="modal fade bs-example-modal-sm" id="create-group" tabindex="-1" role="dialog" aria-labelledby="Create" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h5 class="modal-title" id="Create">Device Groups</h5>
</div>
<div class="modal-body">
<form method="post" role="form" id="group" class="form-horizontal group-form">
<div class='form-group'>
<label for='name' class='col-sm-3 control-label'>Name: </label>
<div class='col-sm-9'>
<input type='text' id='name' name='name' class='form-control' maxlength='200'>
</div>
</div>
<div class='form-group'>
<label for='desc' class='col-sm-3 control-label'>Description: </label>
<div class='col-sm-9'>
<input type='text' id='desc' name='desc' class='form-control' maxlength='200'>
</div>
</div>
<input type="hidden" name="group_id" id="group_id" value="">
<input type="hidden" name="type" id="type" value="create-device-group">
<div class="form-group">
<label for='pattern' class='col-sm-3 control-label'>Pattern: </label>
<div class="col-sm-5">
<input type='text' id='suggest' name='pattern' class='form-control' placeholder='I.e: devices.status'/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<p>Start typing for suggestions, use '.' for indepth selection</p>
</div>
</div>
<div class="form-group">
<label for='condition' class='col-sm-3 control-label'>Condition: </label>
<div class="col-sm-5">
<select id='condition' name='condition' placeholder='Condition' class='form-control'>
<option value='='>Equals</option>
<option value='!='>Not Equals</option>
<option value='~'>Like</option>
<option value='!~'>Not Like</option>
<option value='>'>Larger than</option>
<option value='>='>Larger than or Equals</option>
<option value='<'>Smaller than</option>
<option value='<='>Smaller than or Equals</option>
</select>
</div>
</div>
<div class="form-group">
<label for='value' class='col-sm-3 control-label'>Value: </label>
<div class="col-sm-5">
<input type='text' id='value' name='value' class='form-control'/>
</div>
</div>
<div class="form-group">
<label for='group-glue' class='col-sm-3 control-label'>Connection: </label>
<div class="col-sm-5">
<button class="btn btn-default btn-sm" type="submit" name="group-glue" value="&&" id="and" name="and">And</button>
<button class="btn btn-default btn-sm" type="submit" name="group-glue" value="||" id="or" name="or">Or</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span id="response"></span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-default btn-sm" type="submit" name="group-submit" id="group-submit" value="save">Save Group</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$('#create-group').on('hide.bs.modal', function (event) {
$('#response').data('tagmanager').empty();
$('#name').val('');
$('#desc').val('');
});
$('#create-group').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var group_id = button.data('group_id');
var modal = $(this)
$('#group_id').val(group_id);
$('#tagmanager').tagmanager();
$('#response').tagmanager({
strategy: 'array',
tagFieldName: 'patterns[]'
});
$.ajax({
type: "POST",
url: "/ajax_form.php",
data: { type: "parse-device-group", group_id: group_id },
dataType: "json",
success: function(output) {
var arr = [];
$.each ( output['pattern'], function( key, value ) {
arr.push(value);
});
$('#response').data('tagmanager').populate(arr);
$('#name').val(output['name']);
$('#desc').val(output['desc']);
}
});
});
var cache = {};
$('#suggest').typeahead([
{
name: 'suggestion',
remote : '/ajax_rulesuggest.php?device_id=-1&term=%QUERY',
template: '{{name}}',
valueKey:"name",
engine: Hogan
}
]);
$('#and, #or').click('', function(e) {
e.preventDefault();
var entity = $('#suggest').val();
var condition = $('#condition').val();
var value = $('#value').val();
var glue = $(this).val();
if(entity != '' && condition != '') {
$('#response').tagmanager({
strategy: 'array',
tagFieldName: 'patterns[]'
});
if(entity.indexOf("%") >= 0) {
$('#response').data('tagmanager').populate([ entity+' '+condition+' '+value+' '+glue ]);
} else {
$('#response').data('tagmanager').populate([ '%'+entity+' '+condition+' "'+value+'" '+glue ]);
}
}
});
$('#group-submit').click('', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/ajax_form.php",
data: $('form.group-form').serialize(),
success: function(msg){
$("#message").html('<div class="alert alert-info">'+msg+'</div>');
$("#create-group").modal('hide');
if(msg.indexOf("ERROR:") <= -1) {
$('#response').data('tagmanager').empty();
setTimeout(function() {
location.reload(1);
}, 1000);
}
},
error: function(){
$("#message").html('<div class="alert alert-info">An error occurred creating this group.</div>');
$("#create-group").modal('hide');
}
});
});
</script>
<?php
}
?>

View File

@ -60,6 +60,7 @@ if (isset($config['site_style']) && ($config['site_style'] == 'dark' || $config[
if ($_SESSION['userlevel'] >= '10') {
?>
<li><a href="<?php echo(generate_url(array('page'=>'alert-rules'))); ?>"><i class="fa fa-tasks fa-fw fa-lg"></i> Alert Rules</a></li>
<li><a href="<?php echo(generate_url(array('page'=>'alert-map'))); ?>"><i class="fa fa-link fa-fw fa-lg"></i> Alert Map</a></li>
<li><a href="<?php echo(generate_url(array('page'=>'templates'))); ?>"><i class="fa fa-sitemap fa-fw fa-lg"></i> Alert Templates</a></li>
<?php
}
@ -97,6 +98,13 @@ foreach (dbFetchRows('SELECT `type`,COUNT(`type`) AS total_type FROM `devices` A
}
echo(' <li><a href="devices/type=' . $devtype['type'] . '/"><i class="fa fa-angle-double-right fa-fw fa-lg"></i> ' . ucfirst($devtype['type']) . '</a></li>');
}
require_once('../includes/device-groups.inc.php');
foreach( GetDeviceGroups() as $group ) {
echo '<li><a href="'.generate_url(array('page'=>'devices','group'=>$group['id'])).'" alt="'.$group['desc'].'"><i class="fa fa-th fa-fw fa-lg"></i> '.ucfirst($group['name']).'</a></li>';
}
unset($group);
echo ('</ul>
</li>');
@ -125,6 +133,7 @@ if ($config['show_locations'])
}
echo('
<li role="presentation" class="divider"></li>
<li><a href="'.generate_url(array('page'=>'device-groups')).'"><i class="fa fa-th fa-fw fa-lg"></i> Manage Groups</a></li>
<li><a href="addhost/"><i class="fa fa-desktop fa-col-success fa-fw fa-lg"></i> Add Device</a></li>
<li><a href="delhost/"><i class="fa fa-desktop fa-col-info fa-fw fa-lg"></i> Delete Device</a></li>');
}

View File

@ -0,0 +1,30 @@
<?php
require_once('includes/modal/new_alert_map.inc.php');
require_once('includes/modal/delete_alert_map.inc.php');
$no_refresh = TRUE;
echo '<div class="row"><div class="col-sm-12"><span id="message"></span></div></div>';
echo '<div class="table-responsive">';
echo '<table class="table table-condensed table-hover"><thead><tr>';
echo '<th>Rule</th><th>Target</th><th>Actions</th>';
echo '</tr></thead><tbody>';
foreach( dbFetchRows('SELECT alert_map.target,alert_map.id,alert_rules.name FROM alert_map,alert_rules WHERE alert_map.rule=alert_rules.id ORDER BY alert_map.rule ASC') as $link ) {
if( $link['target'][0] == "g" ) {
$link['target'] = substr($link['target'],1);
$link['target'] = '<a href="'.generate_url(array('page'=>'devices','group'=>$link['target'])).'">'.ucfirst(dbFetchCell('SELECT name FROM device_groups WHERE id = ?',array($link['target']))).'</a>';
} elseif( is_numeric($link['target']) ) {
$link['target'] = '<a href="'.generate_url(array('page'=>'device','device'=>$link['target'])).'">'.dbFetchCell('SELECT hostname FROM devices WHERE device_id = ?',array($link['target'])).'</a>';
}
echo '<tr id="row_'.$link['id'].'">';
echo '<td>'.$link['name'].'</td>';
echo '<td>'.$link['target'].'</td>';
echo '<td>';
echo "<button type='button' class='btn btn-primary btn-sm' aria-label='Edit' data-toggle='modal' data-target='#create-map' data-map_id='".$link['id']."' name='edit-alert-map'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button> ";
echo "<button type='button' class='btn btn-danger btn-sm' aria-label='Delete' data-toggle='modal' data-target='#confirm-delete' data-map_id='".$link['id']."' name='delete-alert-map'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>";
echo '</td>';
echo '</tr>';
}
echo '</tbody></table></div>';
echo "<button type='button' class='btn btn-primary btn-sm' aria-label='Add' data-toggle='modal' data-target='#create-map' data-map_id='' name='create-alert-map'>Create new Map</button> ";
?>

View File

@ -0,0 +1,25 @@
<?php
require_once('includes/modal/new_device_group.inc.php');
require_once('includes/modal/delete_device_group.inc.php');
$no_refresh = TRUE;
echo '<div class="row"><div class="col-sm-12"><span id="message"></span></div></div>';
echo '<div class="table-responsive">';
echo '<table class="table table-condensed table-hover"><thead><tr>';
echo '<th>Name</th><th>Description</th><th>Pattern</th><th>Actions</th>';
echo '</tr></thead><tbody>';
foreach( GetDeviceGroups() as $group ) {
echo '<tr id="row_'.$group['id'].'">';
echo '<td>'.$group['name'].'</td>';
echo '<td>'.$group['desc'].'</td>';
echo '<td>'.$group['pattern'].'</td>';
echo '<td>';
echo "<button type='button' class='btn btn-primary btn-sm' aria-label='Edit' data-toggle='modal' data-target='#create-group' data-group_id='".$group['id']."' name='edit-device-group'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button> ";
echo "<button type='button' class='btn btn-danger btn-sm' aria-label='Delete' data-toggle='modal' data-target='#confirm-delete' data-group_id='".$group['id']."' name='delete-device-group'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>";
echo '</td>';
echo '</tr>';
}
echo '</tbody></table></div>';
echo "<button type='button' class='btn btn-primary btn-sm' aria-label='Add' data-toggle='modal' data-target='#create-group' data-group_id='' name='create-device-group'>Create new Group</button> ";
?>

View File

@ -37,6 +37,16 @@ if (!empty($vars['disabled'])) { $where .= " AND disabled= ?"; $sql_param[]
if (!empty($vars['ignore'])) { $where .= " AND `ignore`= ?"; $sql_param[] = $vars['ignore']; }
if (!empty($vars['location']) && $vars['location'] == "Unset") { $location_filter = ''; }
if (!empty($vars['location'])) { $location_filter = $vars['location']; }
if( !empty($vars['group']) ) {
require_once('../includes/device-groups.inc.php');
$where .= " AND ( ";
foreach( GetDevicesFromGroup($vars['group']) as $dev ) {
$where .= "device_id = ? OR ";
$sql_param[] = $dev['device_id'];
}
$where = substr($where, 0, strlen($where)-3);
$where .= " )";
}
$pagetitle[] = "Devices";

View File

@ -22,6 +22,8 @@
* @subpackage Alerts
*/
include_once('includes/device-groups.inc.php');
/**
* Generate SQL from Rule
* @param string $rule Rule to generate SQL for
@ -52,6 +54,21 @@ function GenSQL($rule) {
return $sql;
}
/**
* Get Alert-Rules for Devices
* @param int $device Device-ID
* @return array
*/
function GetRules($device) {
$groups = GetGroupsFromDevice($device);
$params = array($device,$device);
$where = "";
foreach( $groups as $group ) {
$where .= " || alert_map.target = ?";
$params[] = 'g'.$group;
}
return dbFetchRows('SELECT alert_rules.* FROM alert_rules,alert_map WHERE (alert_rules.device_id = -1 || alert_rules.device_id = ? ) || ( alert_rules.id=alert_map.rule && ( alert_map.target = ? '.$where.' ) )',$params);
}
/**
* Run all rules for a device
@ -64,7 +81,7 @@ function RunRules($device) {
if( $chk['id'] > 0 ) {
return false;
}
foreach( dbFetchRows("SELECT * FROM alert_rules WHERE alert_rules.disabled = 0 && ( alert_rules.device_id = -1 || alert_rules.device_id = ? ) ORDER BY device_id,id",array($device)) as $rule ) {
foreach( GetRules($device) as $rule ) {
echo " #".$rule['id'].":";
$inv = json_decode($rule['extra'],true);
if( isset($inv['invert']) ) {

View File

@ -0,0 +1,95 @@
<?php
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.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, either version 3 of the License, or
* (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>. */
/**
* Device-Grouping
* @author Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
* @license GPL
* @package LibreNMS
* @subpackage Devices
*/
/**
* Generate SQL from Group-Pattern
* @param string $pattern Pattern to generate SQL for
* @return string
*/
function GenGroupSQL($pattern) {
$tmp = explode(" ",$pattern);
$tables = array();
foreach( $tmp as $opt ) {
if( strstr($opt,'%') && strstr($opt,'.') ) {
$tmpp = explode(".",$opt,2);
$tmpp[0] = str_replace("%","",$tmpp[0]);
$tables[] = mres(str_replace("(","",$tmpp[0]));
$pattern = str_replace($opt,$tmpp[0].'.'.$tmpp[1],$pattern);
}
}
$tables = array_keys(array_flip($tables));
$x = sizeof($tables);
$i = 0;
$join = "";
while( $i < $x ) {
if( isset($tables[$i+1]) ) {
$join .= $tables[$i].".device_id = ".$tables[$i+1].".device_id && ";
}
$i++;
}
$sql = "SELECT ".str_replace("(","",$tables[0]).".device_id FROM ".implode(",",$tables)." WHERE (".str_replace(array("%","@","!~","~"),array("","%","NOT LIKE","LIKE"),$pattern).")";
return $sql;
}
/**
* Get all devices of Group
* @param int $group_id Group-ID
* @return string
*/
function GetDevicesFromGroup($group_id) {
$pattern = dbFetchCell("SELECT pattern FROM device_groups WHERE id = ?",array($group_id));
if( !empty($pattern) ) {
return dbFetchRows(GenGroupSQL($pattern));
}
return false;
}
/**
* Get all Device-Groups
* @return array
*/
function GetDeviceGroups() {
return dbFetchRows("SELECT * FROM device_groups");
}
/**
* Get all groups of Device
* @param int $device Device-ID
* @return array
*/
function GetGroupsFromDevice($device) {
$ret = array();
foreach( GetDeviceGroups() as $group ) {
foreach( GetDevicesFromGroup($group['id']) as $dev ) {
if( $dev['device_id'] == $device ) {
if( !in_array($group['id'],$ret) ) {
$ret[] = $group['id'];
}
continue 2;
}
}
}
return $ret;
}
?>

3
sql-schema/045.sql Normal file
View File

@ -0,0 +1,3 @@
CREATE TABLE IF NOT EXISTS `device_groups` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '', `desc` varchar(255) NOT NULL DEFAULT '', `pattern` varchar(255) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`)) ENGINE=InnoDB DEFAULT;
CREATE TABLE IF NOT EXISTS `alert_map` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rule` int(11) NOT NULL DEFAULT '0', `target` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT;
ALTER TABLE `alert_rules` ADD UNIQUE (`name`);