Kaynağa Gözat

- draft 2.5.3

root 1 yıl önce
ebeveyn
işleme
ed8fab5a94

+ 95 - 0
html/admin/customers/building.php

@@ -0,0 +1,95 @@
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
+
+if (isset($_POST["remove"])) {
+    $fid = $_POST["f_id"];
+    foreach ($fid as $key => $val) {
+        if (isset($val) and $val > 1) {
+            LOG_INFO($db_link,'Remove building id: '.$val);
+            delete_record($db_link, "building", "id=" . $val);
+        }
+    }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+}
+
+if (isset($_POST['save'])) {
+    $len = is_array($_POST['r_id']) ? count($_POST['r_id']) : 0;
+    for ($i = 0; $i < $len; $i ++) {
+        $save_id = intval($_POST['save'][$i]);
+        if ($save_id == 0) {
+            continue;
+        }
+        $len_all = is_array($_POST['r_id']) ? count($_POST['r_id']) : 0;
+        for ($j = 0; $j < $len_all; $j ++) {
+            if (intval($_POST['r_id'][$j]) != $save_id) {
+                continue;
+            }
+            $value = $_POST['f_building_name'][$j];
+            $value_comment = $_POST['f_building_comment'][$j];
+            if (isset($value)) {
+                $new['name'] = $value;
+                $new['comment'] = $value_comment;
+                LOG_INFO($db_link,"Change building id='{$save_id}': name=".$value." comment=".$value_comment);
+                update_record($db_link, "building", "id='{$save_id}'", $new);
+            }
+        }
+    }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+}
+
+if (isset($_POST["create"])) {
+    $building_name = $_POST["new_building"];
+    if (isset($building_name)) {
+        $new['name'] = $building_name;
+        LOG_INFO($db_link,'Add building $building_name');
+        insert_record($db_link, "building", $new);
+    }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+}
+
+unset($_POST);
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+print_control_submenu($page_url);
+?>
+<div id="cont">
+<form name="def" action="building.php" method="post">
+<table class="data">
+<tr align="center">
+<td><input type="checkbox" onClick="checkAll(this.checked);"></td>
+<td><b>id</b></td>
+<td><b><?php echo WEB_cell_name; ?></b></td>
+<td><b><?php echo WEB_cell_comment; ?></b></td>
+<td>
+<input type="submit" onclick="return confirm('<?php print WEB_btn_delete; ?>?')" name="remove" value="<?php print WEB_btn_remove; ?>">
+</td>
+</tr>
+<?php
+$t_building = get_records($db_link,'building','TRUE ORDER BY id');
+foreach ($t_building as $row) {
+    print "<tr align=center>\n";
+    print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$row['id']}'></td>\n";
+    print "<td class=\"data\"><input type=\"hidden\" name='r_id[]' value='{$row['id']}'>{$row['id']}</td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_building_name[]' value='{$row['name']}'></td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_building_comment[]' value='{$row['comment']}'></td>\n";
+    print "<td class=\"data\"><button name='save[]' value='{$row['id']}'>".WEB_btn_save."</button></td>\n";
+    print "</tr>\n";
+}
+?>
+</table>
+<table>
+<tr>
+<td><input type=text name=new_building value="Unknown"></td>
+<td>
+<input type="submit" name="create" value="<?php print WEB_btn_add; ?>">
+</td>
+<td align="right"></td>
+</tr>
+</table>
+</form>
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

+ 160 - 0
html/admin/customers/devmodels.php

@@ -0,0 +1,160 @@
+<?php
+
+$default_displayed=25;
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/vendorfilter.php");
+
+if (isset($_POST['save'])) {
+    $saved = array();
+    //button save
+    $len = is_array($_POST['save']) ? count($_POST['save']) : 0;
+    for ($i = 0; $i < $len; $i ++) {
+        $save_id = intval($_POST['save'][$i]);
+        if ($save_id == 0) { continue;  }
+        array_push($saved,$save_id);
+        }
+    //select box
+    $len = is_array($_POST['f_id']) ? count($_POST['f_id']) : 0;
+    if ($len>0) {
+        for ($i = 0; $i < $len; $i ++) {
+            $save_id = intval($_POST['f_id'][$i]);
+            if ($save_id == 0) { continue; }
+            if (!in_array($save_id, $saved)) { array_push($saved,$save_id); }
+            }
+        }
+    //save changes
+    $len = is_array($saved) ? count($saved) : 0;
+    for ($i = 0; $i < $len; $i ++) {
+        $save_id = intval($saved[$i]);
+        if ($save_id == 0) { continue;  }
+        $len_all = is_array($_POST['r_id']) ? count($_POST['r_id']) : 0;
+        for ($j = 0; $j < $len_all; $j ++) {
+            if (intval($_POST['r_id'][$j]) != $save_id) { continue; }
+            if ($save_id>=10000) {
+                $new['vendor_id'] = $_POST['f_vendor'][$j];
+	            $new['model_name'] = $_POST['f_name'][$j];
+	        }
+            $new['nagios_template'] = $_POST['f_nagios'][$j];
+            update_record($db_link, "device_models", "id='{$save_id}'", $new);
+            }
+        }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+    }
+
+if (isset($_POST['remove'])) {
+        $saved = array();
+        //button save
+        $len = is_array($_POST['save']) ? count($_POST['save']) : 0;
+        for ($i = 0; $i < $len; $i ++) {
+            $save_id = intval($_POST['save'][$i]);
+            if ($save_id == 0) { continue;  }
+            array_push($saved,$save_id);
+            }
+        //select box
+        $len = is_array($_POST['f_id']) ? count($_POST['f_id']) : 0;
+        if ($len>0) {
+            for ($i = 0; $i < $len; $i ++) {
+                $save_id = intval($_POST['f_id'][$i]);
+                if ($save_id == 0) { continue; }
+                if (!in_array($save_id, $saved)) { array_push($saved,$save_id); }
+                }
+            }
+        //save changes
+        $len = is_array($saved) ? count($saved) : 0;
+        for ($i = 0; $i < $len; $i ++) {
+            $save_id = intval($saved[$i]);
+            if ($save_id == 0) { continue;  }
+            $len_all = is_array($_POST['r_id']) ? count($_POST['r_id']) : 0;
+            for ($j = 0; $j < $len_all; $j ++) {
+                if (intval($_POST['r_id'][$j]) != $save_id) { continue; }
+                if ($save_id>=10000) { 
+                    delete_record($db_link, "device_models", "id='{$save_id}'");
+                    run_sql($db_link,"UPDATE devices set device_model_id=NULL WHERE device_model_id=".$save_id);
+                    }
+                }
+            }
+        header("Location: " . $_SERVER["REQUEST_URI"]);
+        exit;
+        }
+
+if (isset($_POST["create"])) {
+    $model_name = $_POST["new_model"];
+    if (isset($model_name)) {
+	$max_record = get_record_sql($db_link,"SELECT MAX(id) as max_id FROM device_models");
+	if (!isset($max_record) or $max_record['max_id']<10000) { $next_id = 10000; } else { $next_id = $max_record['max_id'] + 1; }
+        $new['vendor_id']=1;
+        $new['id'] = $next_id;
+        if (isset($f_vendor_select) and $f_vendor_select>1) { $new['vendor_id']=$f_vendor_select; }
+        $new['model_name'] = $model_name;
+        insert_record($db_link, "device_models", $new);
+        }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+    }
+
+unset($_POST);
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+print_control_submenu($page_url);
+
+?>
+<div id="cont">
+<br>
+<form name="def" action="devmodels.php" method="post">
+
+<table class="data">
+<tr>
+<td><b><?php echo WEB_list_models; ?></b></td>
+<td><?php print_vendor_select($db_link,'vendor_select',$f_vendor_select); ?></td>
+<td><?php print WEB_rows_at_page."&nbsp:";print_row_at_pages('rows',$displayed); ?></td>
+<td><input type="submit" name="OK" value="<?php print WEB_btn_show; ?>"></td>
+</tr>
+</table>
+
+<?php
+$v_filter='';
+if (!empty($f_vendor_select)) { $v_filter = "WHERE vendor_id=".$f_vendor_select; }
+
+$countSQL="SELECT Count(*) FROM device_models $v_filter";
+$res = mysqli_query($db_link, $countSQL);
+$count_records = mysqli_fetch_array($res);
+$total=ceil($count_records[0]/$displayed);
+if ($page>$total) { $page=$total; }
+if ($page<1) { $page=1; }
+$start = ($page * $displayed) - $displayed;
+print_navigation($page_url,$page,$displayed,$count_records[0],$total);
+?>
+<br>
+<table class="data">
+<tr align="center">
+<td><input type="checkbox" onClick="checkAll(this.checked);"></td>
+<td><b>Id</b></td>
+<td><b><?php echo WEB_model_vendor; ?></b></td>
+<td><b><?php echo WEB_cell_name; ?></b></td>
+<td><b><?php echo WEB_nagios_template; ?></b></td>
+<td><input type="submit" name='save' value="<?php echo WEB_btn_save; ?>"></td>
+<td><input type="submit" name='remove' value="<?php echo WEB_btn_delete; ?>"></td>
+</tr>
+<?php
+$t_ou = get_records_sql($db_link,'SELECT * FROM device_models '.$v_filter." ORDER BY vendor_id, model_name LIMIT $start,$displayed");
+foreach ($t_ou as $row) {
+    print "<tr align=center>\n";
+    print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$row['id']}'></td>\n";
+    print "<td class=\"data\"><input type=\"hidden\" name='r_id[]' value='{$row['id']}'>{$row['id']}</td>\n";
+    print "<td class=\"data\" width=150>"; print_vendor_set($db_link,'f_vendor[]',$row['vendor_id']); print "</td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_name[]' value='{$row['model_name']}'></td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_nagios[]' value='{$row['nagios_template']}'></td>\n";
+    print "<td class=\"data\"></td>\n";
+    print "<td class=\"data\"></td>\n";
+    print "</tr>\n";
+}
+?>
+</table>
+<div><input type=text name=new_model value="Unknown">
+<input type="submit" name="create" value="<?php echo WEB_btn_add; ?>">
+</div>
+</form>
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

+ 115 - 0
html/admin/customers/devvendors.php

@@ -0,0 +1,115 @@
+<?php
+
+$default_displayed=25;
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
+
+if (isset($_POST['save'])) {
+    $saved = array();
+    //button save
+    $len = is_array($_POST['save']) ? count($_POST['save']) : 0;
+    for ($i = 0; $i < $len; $i ++) {
+        $save_id = intval($_POST['save'][$i]);
+        if ($save_id == 0) { continue;  }
+        if ($save_id<10000) { continue; }
+        array_push($saved,$save_id);
+        }
+    //select box
+    $len = is_array($_POST['f_id']) ? count($_POST['f_id']) : 0;
+    if ($len>0) {
+        for ($i = 0; $i < $len; $i ++) {
+            $save_id = intval($_POST['f_id'][$i]);
+            if ($save_id == 0) { continue; }
+            if ($save_id<10000) { continue; }
+            if (!in_array($save_id, $saved)) { array_push($saved,$save_id); }
+            }
+        }
+    //save changes
+    $len = is_array($saved) ? count($saved) : 0;
+    for ($i = 0; $i < $len; $i ++) {
+        $save_id = intval($saved[$i]);
+        if ($save_id == 0) { continue;  }
+        if ($save_id<10000) { continue; }
+        $len_all = is_array($_POST['r_id']) ? count($_POST['r_id']) : 0;
+        for ($j = 0; $j < $len_all; $j ++) {
+            if (intval($_POST['r_id'][$j]) != $save_id) { continue; }
+            $new['name'] = $_POST['f_name'][$j];
+            update_record($db_link, "vendors", "id='{$save_id}'", $new);
+            }
+        }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+    }
+
+if (isset($_POST["create"])) {
+    $vendor_name = $_POST["new_vendor"];
+    if (isset($vendor_name)) {
+	$max_record = get_record_sql($db_link,"SELECT MAX(id) as max_id FROM vendors");
+	if (!isset($max_record) or $max_record['max_id']<10000) { $next_id = 10000; } else { $next_id = $max_record['max_id'] + 1; }
+        $new['id'] = $next_id;
+        $new['name'] = $vendor_name;
+        insert_record($db_link, "vendors", $new);
+        }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    exit;
+    }
+
+unset($_POST);
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+print_control_submenu($page_url);
+
+?>
+<div id="cont">
+<br>
+
+<form name="def" action="devvendors.php" method="post">
+
+<table class="data">
+<tr>
+<td><b><?php print WEB_list_vendors; ?></b></td>
+<td><?php print WEB_rows_at_page."&nbsp:";print_row_at_pages('rows',$displayed); ?></td>
+<td><input type="submit" name="OK" value="<?php print WEB_btn_show; ?>"></td>
+</tr>
+</table>
+
+<?php
+$countSQL="SELECT Count(*) FROM vendors";
+$res = mysqli_query($db_link, $countSQL);
+$count_records = mysqli_fetch_array($res);
+$total=ceil($count_records[0]/$displayed);
+if ($page>$total) { $page=$total; }
+if ($page<1) { $page=1; }
+$start = ($page * $displayed) - $displayed;
+print_navigation($page_url,$page,$displayed,$count_records[0],$total);
+
+?>
+<table class="data">
+<tr align="center">
+<td><input type="checkbox" onClick="checkAll(this.checked);"></td>
+<td><b>Id</b></td>
+<td><b><?php echo WEB_model_vendor; ?></b></td>
+<td><input type="submit" name='save' value="<?php echo WEB_btn_save; ?>"></td>
+</tr>
+<?php
+$t_ou = get_records_sql($db_link,"SELECT * FROM vendors ORDER BY name LIMIT $start,$displayed");
+foreach ($t_ou as $row) {
+    print "<tr align=center>\n";
+    print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$row['id']}'></td>\n";
+    print "<td class=\"data\"><input type=\"hidden\" name='r_id[]' value='{$row['id']}'>{$row['id']}</td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_name[]' value='{$row['name']}'></td>\n";
+    print "<td class=\"data\"></td>\n";
+    print "</tr>\n";
+}
+?>
+</table>
+<table>
+<tr>
+<td><input type=text name=new_vendor value="Unknown"></td>
+<td><input type="submit" name="create" value="<?php echo WEB_btn_add; ?>"></td>
+<td align="right"></td>
+</tr>
+</table>
+</form>
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

+ 1 - 3
html/inc/common.php

@@ -2090,7 +2090,7 @@ return $rule_id;
 function allow_update($table, $action = 'update', $field = '')
 {
 //always allow modification for tables
-    if (preg_match('/(variables|dns_cache|syslog|sessions)/i', $table)) { return 1; }
+    if (preg_match('/(variables|dns_cache|syslog|sessions|dns_queue|User_auth_alias)/i', $table)) { return 1; }
 
     if (isset($_SESSION['login'])) {
         $work_user = $_SESSION['login'];
@@ -2110,8 +2110,6 @@ function allow_update($table, $action = 'update', $field = '')
     if ($user_level == 3) { return 0; }
 
 //allow tables for Operator
-    if (preg_match('/(dns_queue|User_auth_alias)/i', $table)) { return 1; }
-
     if ($action == 'update') {
         $operator_acl = [
             'User_auth'=> [

+ 291 - 0
scripts/eyelib/nagios.pm

@@ -0,0 +1,291 @@
+package eyelib::nagios;
+
+#use v5.28;
+use utf8;
+use open ":encoding(utf8)";
+use strict;
+use English;
+use FindBin '$Bin';
+use lib "/opt/Eye/scripts";
+use base 'Exporter';
+use vars qw(@EXPORT @ISA);
+use eyelib::config;
+use eyelib::main;
+use eyelib::mysql;
+use Time::Local;
+use Data::Dumper;
+
+@ISA = qw(Exporter);
+@EXPORT = qw(
+nagios_send_command
+nagios_host_svc_disable
+nagios_host_svc_enable
+print_nagios_cfg
+@cfg_dirs
+);
+
+BEGIN
+{
+
+#---------------------------------------------------------------------------------
+
+sub nagios_send_command {
+my $command = shift;
+next if (!$command);
+if (!-e $config_ref{nagios_cmd}) { die("Command socket $config_ref{nagios_cmd} not found!"); }
+log_info("Send command: $command to $config_ref{nagios_cmd}");
+open(FH, ">> $config_ref{nagios_cmd}");
+print FH "$command\n";
+close(FH);
+}
+
+#---------------------------------------------------------------------------------
+
+sub nagios_host_svc_disable {
+my $hostname = shift;
+my $full = shift || 0;
+my $utime = timelocal(localtime());
+my $cmd = "[$utime] DISABLE_HOST_SVC_CHECKS;$hostname";
+#dont run!!!
+#check nagios option work?
+#nagios_send_command($cmd);
+if ($full) {
+    $cmd = "[$utime] DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST;$hostname";
+    nagios_send_command($cmd);
+    }
+$cmd = "[$utime] DISABLE_HOST_SVC_NOTIFICATIONS;$hostname";
+nagios_send_command($cmd);
+}
+
+#---------------------------------------------------------------------------------
+
+sub nagios_host_svc_enable {
+my $hostname = shift;
+my $full = shift || 0;
+my $utime = timelocal(localtime());
+my $cmd = "[$utime] ENABLE_HOST_SVC_CHECKS;$hostname";
+nagios_send_command($cmd);
+if ($full) {
+    $cmd = "[$utime] ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST;$hostname";
+    nagios_send_command($cmd);
+    }
+$cmd = "[$utime] ENABLE_HOST_SVC_NOTIFICATIONS;$hostname";
+nagios_send_command($cmd);
+}
+
+#---------------------------------------------------------------------------------
+
+sub read_host_template {
+my $device = shift;
+my $template_file = shift;
+my $result;
+my @custom_cfg=();
+if (-e $template_file) { @custom_cfg = read_file($template_file); } else { return; }
+if (@custom_cfg and scalar(@custom_cfg)) {
+    foreach my $row (@custom_cfg) {
+	next if (!$row);
+        $row=~s/\%HOSTNAME\%/$device->{name}/;
+        $row=~s/\%HOST\%/$device->{name}/;
+	$row=~s/\%HOSTIP\%/$device->{ip}/;
+	$row=~s/\%HOST_IP\%/$device->{ip}/;
+	$row=~s/\%COMMUNITY\%/$device->{community}/ if ($device->{community});
+	$row=~s/\%RW_COMMUNITY\%/$device->{rw_community}/ if ($device->{rw_community});
+	$row=~s/\%SNMP_VERSION\%/$device->{snmp_version}/ if ($device->{snmp_version});
+	$row=~s/\%MODEL\%/$device->{device_model}->{model_name}/ if ($device->{device_model}->{model_name});
+        push(@{$result->{template}},$row);
+	if ($row=~/\s+service_description\s+(.*)$/i) { $result->{services}->{$1}=1; }
+	}
+    }
+return $result;
+}
+
+sub print_single_host {
+my $device = shift;
+my $host_template = 'generic-host';
+my $default_service="local-service";
+
+my $ping_enable = $device->{ou}->{nagios_ping};
+if ($device->{ou}->{nagios_host_use}) { $host_template=$device->{ou}->{nagios_host_use}; }
+if ($device->{ou}->{nagios_default_service}) { $default_service=$device->{ou}->{nagios_default_service}; }
+
+my $cfg_file = $device->{ou}->{nagios_dir}."/".$device->{name}.".cfg";
+open(FH, "> $cfg_file");
+print(FH "define host{\n");
+print(FH "       use                     $host_template\n");
+print(FH "       host_name               $device->{name}\n");
+print(FH "       alias                   $device->{name}\n");
+print(FH "       address                 $device->{ip}\n");
+print(FH "       _ID			 $device->{auth_id}\n"); 
+print(FH "       _TYPE			 user\n");
+if ($device->{device_model}) {
+	print(FH "       notes		$device->{device_model}->{model_name}\n"); 
+	}
+if ($device->{parent_name}) {
+        print(FH "       parents                    $device->{parent_name}\n");
+        }
+print(FH "       notes_url       ".$config_ref{stat_url}."/admin/users/editauth.php?id=".$device->{auth_id}."\n");
+print(FH "       }\n\n");
+
+if ($ping_enable) {
+	print(FH "define service{\n");
+	print(FH "       use                    ping-service\n");
+	print(FH "       host_name              $device->{name}\n");
+	print(FH "       service_description    ping $device->{name}\n");
+	print(FH "       check_command          check_ping_icmp!100.0,20%!500.0,60%\n");
+	print(FH "       }\n");
+	print(FH "\n");
+    }
+if ($device->{parent_name} and $device->{link_check} and $device->{parent_snmp_version}) {
+	#port status
+        print(FH "define service{\n");
+        print(FH "       use                        $default_service\n");
+        print(FH "       host_name                  $device->{parent_name}\n");
+        print(FH "       service_description port $device->{parent_port} - $device->{name}\n");
+        print(FH "       check_command              check_ifoperstatus!$device->{parent_port_snmp_index}!$device->{parent_community}\n");
+        print(FH "       }\n");
+        print(FH "\n");
+        #crc
+        print(FH "define service{\n");
+        print(FH "       use                        service-snmp-crc\n");
+        print(FH "       host_name                  $device->{parent_name}\n");
+        print(FH "       service_description port $device->{parent_port} - $device->{name} CRC Errors\n");
+        print(FH "       check_command              check_snmp_switch_crc!$device->{parent_community}!$device->{parent_port_snmp_index}\n");
+        print(FH "       }\n\n");
+    }
+close(FH);
+return $cfg_file;
+}
+#---------------------------------------------------------------------------------
+
+sub print_nagios_cfg {
+
+my $device = shift;
+return if (!$device);
+my $device_id = $device->{device_id};
+my $custom_cfg;
+my $device_custom_cfg = $config_ref{nagios_dir}."/custom-cfg/".$device->{name}.".cfg";
+if (-e $device_custom_cfg) { $custom_cfg = read_host_template($device,$device_custom_cfg); }
+$device_custom_cfg = $config_ref{nagios_dir}."/custom-cfg/".$device_id.".cfg";
+if (-e $device_custom_cfg) { $custom_cfg = read_host_template($device,$device_custom_cfg); }
+my $default_service="local-service";
+
+if (!$device->{ou}->{nagios_dir}) { print Dumper($device); }
+
+my $cfg_file = $device->{ou}->{nagios_dir}."/".$device->{name}.".cfg";
+
+if ($custom_cfg->{template}) {
+    open(FH, "> $cfg_file");
+    my @custom_cfg = @{$custom_cfg->{template}};
+    if (@custom_cfg and scalar(@custom_cfg)) {
+	foreach my $row (@custom_cfg) {
+	    next if (!$row);
+            print(FH $row."\n");
+	    }
+	}
+    close(FH);
+    return;
+    }
+
+#switch | router
+if (in_array([0,1,2],$device->{type})) {
+    open(FH, "> $cfg_file");
+    my $device_template = 'switches';
+    if ($device->{type} eq 2) {  $device_template='routers'; }
+    print(FH "define  host {\n");
+    print(FH "       use                     $device_template\n");
+    print(FH "       host_name               $device->{name}\n");
+    print(FH "       alias                   $device->{name}\n");
+    print(FH "       address                 $device->{ip}\n");
+    print(FH "       _ID                     $device->{device_id}\n");
+    print(FH "       _TYPE                   device\n");
+    if ($device->{device_model}) {
+	print(FH "       notes		$device->{device_model}->{model_name}\n");
+	}
+    if ($device->{parent_name}) {
+        print(FH "       parents                    $device->{parent_name}\n");
+        }
+    print(FH "       notes_url       ".$config_ref{stat_url}."/admin/devices/editdevice.php?id=$device->{device_id}\n");
+    print(FH "       }\n\n");
+    #ping
+    print(FH "define service{\n");
+    print(FH "        use                             ping-service         ; Name of service template to use\n");
+    print(FH "        host_name                       $device->{name}\n");
+    print(FH "        service_description             ping $device->{name}\n");
+    print(FH "        check_command                   check_ping_icmp!100.0,20%!500.0,60%\n");
+    print(FH "        }\n");
+    #uptime
+    if ($device->{snmp_version}) {
+        print(FH "define service{\n");
+	print(FH "        use                             $default_service\n");
+        print(FH "        host_name                       $device->{name}\n");
+	print(FH "        service_description             Uptime\n");
+        print(FH "        check_command                   check_snmp_uptime!$device->{community}!161!$device->{snmp_version}\n");
+	print(FH "        }\n");
+        print(FH "\n");
+        #uplink
+        if (exists $device->{uplink}) {
+	    print(FH "define service{\n");
+    	    print(FH "       use                        service-snmp-crc\n");
+            print(FH "       host_name                  $device->{name}\n");
+            my $port_description = $device->{parent_name};
+            my $conn = $device->{uplink};
+            print(FH "       service_description port $conn->{port} - $port_description CRC Errors\n");
+            print(FH "       check_command              check_snmp_switch_crc!$device->{community}!$conn->{snmp_index}\n");
+            print(FH "       }\n\n");
+    	    }
+	foreach my $conn (@{$device->{downlinks}}) {
+	    #id,port,snmp_index,comment
+	    print(FH "define service{\n");
+    	    print(FH "       use                        $default_service\n");
+            print(FH "       host_name                  $device->{name}\n");
+            my $port_description=translit($conn->{comment});
+            if ($conn->{target_port_id}) { $port_description = $conn->{downlink_name}; }
+            print(FH "       service_description port $conn->{port} - $port_description \n");
+            print(FH "       check_command              check_ifoperstatus!$conn->{snmp_index}!$device->{community}\n");
+            print(FH "       }\n\n");
+            #src
+	    print(FH "define service{\n");
+    	    print(FH "       use                        service-snmp-crc\n");
+            print(FH "       host_name                  $device->{name}\n");
+            my $port_description=translit($conn->{comment});
+            if ($conn->{target_port_id}) { $port_description = $conn->{downlink_name}; }
+            print(FH "       service_description port $conn->{port} - $port_description CRC Errors\n");
+            print(FH "       check_command              check_snmp_switch_crc!$device->{community}!$conn->{snmp_index}\n");
+            print(FH "       }\n\n");
+            #band
+	    print(FH "define service{\n");
+    	    print(FH "       use                        service-snmp-bandwidth\n");
+            print(FH "       host_name                  $device->{name}\n");
+            my $port_description=translit($conn->{comment});
+            if ($conn->{target_port_id}) { $port_description = $conn->{downlink_name}; }
+            print(FH "       service_description port $conn->{port} - $port_description bandwidth usage\n");
+            print(FH "       check_command              check_snmp_bandwidth!$device->{community}!$conn->{snmp_index}\n");
+            print(FH "       }\n\n");
+	    }
+	}
+    close FH;
+    }
+
+#auth record
+if ($device->{type} eq 3) {
+    my $cfg_file = print_single_host($device);
+    open(FH, ">> $cfg_file");
+    my $dev_cfg;
+    if ($device->{device_model} and $device->{device_model}->{nagios_template}) { $dev_cfg = read_host_template($device,$config_ref{nagios_dir}.'/gen_template/'.$device->{device_model}->{nagios_template}); }
+    if ($dev_cfg and $dev_cfg->{template}) {
+	    my @dev_cfg = @{$dev_cfg->{template}};
+	    if (@dev_cfg and scalar(@dev_cfg)) {
+		foreach my $row (@dev_cfg) {
+		    next if (!$row);
+    		    print(FH $row."\n");
+		    }
+		}
+        }
+    close FH;
+    }
+}
+
+#---------------------------------------------------------------------------------
+
+1;
+}

+ 260 - 0
scripts/gen_nagios_config.pl

@@ -0,0 +1,260 @@
+#!/usr/bin/perl
+
+use utf8;
+use open ":encoding(utf8)";
+use FindBin '$Bin';
+use lib "/opt/Eye/scripts";
+use DBI;
+use File::Basename;
+use File::Find;
+use File::stat qw(:FIELDS);
+use File::Spec::Functions;
+use Sys::Hostname;
+use DirHandle;
+use Time::localtime;
+use Fcntl;
+use Tie::File;
+use Data::Dumper;
+use Net::Ping;
+use eyelib::config;
+use eyelib::main;
+use eyelib::nagios;
+use eyelib::mysql;
+use Fcntl qw(:flock);
+
+open(SELF,"<",$0) or die "Cannot open $0 - $!";
+flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
+
+my %devices;
+my %auths;
+
+my %dependency;
+
+my $nagios_devices = "/etc/snmp/devices.cfg";
+
+my @OU_list = get_records_sql($dbh,"SELECT * FROM OU");
+my %ou;
+my @cfg_dirs = ();
+foreach my $row (@OU_list) {
+next if (!$row->{nagios_dir});
+if ($row->{nagios_dir}!~/^$config_ref{nagios_dir}/) { $row->{nagios_dir}=$config_ref{nagios_dir}.'/'.$row->{nagios_dir}; }
+$row->{nagios_dir}=~s/\/$//;
+$ou{$row->{id}}=$row;
+push(@cfg_dirs,$row->{nagios_dir});
+}
+
+@cfg_dirs = uniq(@cfg_dirs);
+
+my @Model_list = get_records_sql($dbh,"SELECT * FROM device_models");
+my %models;
+foreach my $row (@Model_list) {
+$models{$row->{id}}=$row;
+}
+
+#switches & routers only
+my @netdev_list=get_records_sql($dbh,'SELECT * FROM devices WHERE deleted=0 and nagios=1 and device_type<=2');
+
+##################################### Netdevices analyze ################################################
+if (scalar(@netdev_list)>0) {
+    foreach my $router (@netdev_list) {
+        next if (!$router);
+        my $ip = $router->{'ip'};
+        $ip =~s/\/\d+$//g;
+        my $device_id = 'netdev_'.$router->{'id'};
+        $devices{$device_id}{ip}=$ip;
+        $devices{$device_id}{community}=$router->{'community'} || $config_ref{snmp_default_community};
+        $devices{$device_id}{description}=translit($router->{'comment'});
+        $devices{$device_id}{name} = $router->{'device_name'};
+        $devices{$device_id}{device_model_id} = $router->{'device_model_id'};
+        if ($router->{'device_model_id'}) { $devices{$device_id}{device_model} = $models{$router->{'device_model_id'}};  }
+        $devices{$device_id}{device_id} = $router->{'id'};
+        $devices{$device_id}{snmp_version} = $router->{'snmp_version'} || $config_ref{snmp_default_version};
+        if ($devices{$device_id}{snmp_version} eq '2') { $devices{$device_id}{snmp_version}='2c'; }
+        $devices{$device_id}{vendor_id} = $router->{'vendor_id'};
+        $devices{$device_id}{ou_id} = 0;
+        #1 - switch; 2 - router; 3 - auth
+        #NOT DEVICE TYPE IN DB!!!
+        $devices{$device_id}{type}='1';
+        $devices{$device_id}{ou_id}='7';
+        if ($router->{'device_type'} eq 2) {
+            $devices{$device_id}{type}='2'; 
+            $devices{$device_id}{ou_id}='10';
+            }
+	if ($router->{'user_id'}) {
+            #get user
+	    my $login = get_record_sql($dbh,"SELECT * FROM User_list WHERE id=".$router->{'user_id'});
+	    if ($login and $login->{ou_id} and $ou{$login->{ou_id}}->{nagios_dir}) { $devices{$device_id}{ou_id} = $login->{ou_id}; }
+            }
+        $devices{$device_id}{ou}=$ou{$devices{$device_id}{ou_id}};
+
+        if (!$devices{$device_id}{ou}->{nagios_dir}) {
+    	    if ($devices{$device_id}{type} eq '1') { $devices{$device_id}{ou}->{nagios_dir}='switches'; }
+    	    if ($devices{$device_id}{type} eq '2') { $devices{$device_id}{ou}->{nagios_dir}='routers'; }
+    	    }
+
+	$devices{$device_id}{snmp_version}=$router->{'snmp_version'} || $config_ref{snmp_default_version};
+	$devices{$device_id}{community}=$router->{'community'} || $config_ref{snmp_default_community};
+        $devices{$device_id}{rw_community}=$router->{'rw_community'} || $config_ref{snmp_default_community};
+        $devices{$device_id}{fdb_snmp_index}=$router->{'fdb_snmp_index'};
+        $devices{$device_id}{user_id}=$router->{'user_id'};
+        #get uplinks
+        my $uplink_port = get_record_sql($dbh,"SELECT * FROM device_ports WHERE uplink=1 AND device_id=".$devices{$device_id}{device_id}." AND target_port_id>0 ORDER BY port DESC");
+        if ($uplink_port and $uplink_port->{target_port_id}) {
+            my $parent_uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{target_port_id}." ORDER BY id DESC");
+            if ($parent_uplink and $parent_uplink->{device_id}) {
+        	my $uplink_device = get_record_sql($dbh,"SELECT * FROM devices WHERE id=".$parent_uplink->{device_id}." AND nagios=1 AND deleted=0");
+        	if ($uplink_device) {
+        	    $devices{$device_id}{parent}='netdev_'.$uplink_device->{'id'}; 
+        	    $devices{$device_id}{parent_name}=$uplink_device->{'device_name'};
+        	    }
+        	}
+            my $uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{id}." ORDER BY id DESC");
+    	    $devices{$device_id}{parent_downlink}=$parent_uplink;
+    	    $devices{$device_id}{uplink}=$uplink;
+            }
+        #downlinks
+        my @downlinks = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=".$devices{$device_id}{device_id}." and target_port_id>0 and uplink=0");
+        foreach my $downlink_port (@downlinks) {
+    	    my $downlink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$downlink_port->{target_port_id});
+    	    if ($downlink) {
+    		my $downlink_device = get_record_sql($dbh,"SELECT * FROM devices WHERE id=".$downlink->{device_id});
+    		if ($downlink_device) { $downlink_port->{downlink_name}=$downlink_device->{device_name}; }
+		}
+	    #id,port,snmp_index
+            push(@{$devices{$device_id}{downlinks}},$downlink_port);
+    	    }
+	#custom ports
+        my @custom_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=".$devices{$device_id}{device_id}." and target_port_id=0 and uplink=0 and nagios=1");
+        foreach my $downlink_port (@custom_ports) {
+            #id,port,snmp_index,comment
+	    push(@{$devices{$device_id}{downlinks}},$downlink_port);
+    	    }
+        }
+    }
+
+my @auth_list=get_records_sql($dbh,'SELECT * FROM User_auth WHERE deleted=0 and nagios=1');
+
+##################################### User auth analyze ################################################
+
+if (scalar(@auth_list)>0) {
+    foreach my $auth (@auth_list) {
+        next if (!$auth);
+        my $ip = $auth->{'ip'};
+        $ip =~s/\/\d+$//g;
+
+        #skip doubles
+        my $device_id = 'auth_'.$auth->{'id'};
+        next if ($devices{$device_id});
+
+	#skip user device with few ip
+        my $auth_count = get_count_records($dbh,"User_auth","user_id=".$auth->{'user_id'}." AND deleted=0");
+        next if ($auth_count>1);
+
+	#skip switches and routers
+        my $auth_device = get_record_sql($dbh,"SELECT * FROM devices WHERE user_id=".$auth->{'user_id'});
+	next if ($auth_device and $auth_device->{device_type}<=2);
+
+	#snmp parameters
+	if ($auth_device) {
+		$devices{$device_id}{snmp_version}=$auth_device->{snmp_version};
+		$devices{$device_id}{community}=$auth_device->{community};
+		$devices{$device_id}{rw_community}=$auth_device->{rw_community};
+		$devices{$device_id}{name}=$auth_device->{device_name};
+		} else {
+		$devices{$device_id}{snmp_version}=$config_ref{snmp_default_version};
+		$devices{$device_id}{community}=$config_ref{snmp_default_community};
+		$devices{$device_id}{rw_community}=$config_ref{snmp_default_community};
+		}
+
+        $devices{$device_id}{ip}=$ip;
+
+        #get user
+        my $login = get_record_sql($dbh,"SELECT * FROM User_list WHERE id=".$auth->{'user_id'});
+    
+        $devices{$device_id}{user_login} = $login->{login};
+        $devices{$device_id}{user_fio} = $login->{fio};
+        $devices{$device_id}{ou_id} = 0;
+	if ($login and $login->{ou_id} and $ou{$login->{ou_id}}->{nagios_dir}) { $devices{$device_id}{ou_id} = $login->{ou_id}; }
+        $devices{$device_id}{ou}=$ou{$devices{$device_id}{ou_id}};
+        
+        $devices{$device_id}{device_model_id} = $auth_device->{'device_model_id'};
+        if ($auth_device->{'device_model_id'}) { $devices{$device_id}{device_model} = $models{$auth_device->{'device_model_id'}}; }
+        
+	#name
+        if (!$devices{$device_id}{name} and $auth->{dns_name}) { $devices{$device_id}{name} = $auth->{dns_name}; }
+        if (!$devices{$device_id}{name}) {
+    	    if ($login->{login}) {
+    		$devices{$device_id}{name} = translit($login->{login});
+    		$devices{$device_id}{name}=~s/\(/-/g;
+    		$devices{$device_id}{name}=~s/\)/-/g;
+    		$devices{$device_id}{name}=~s/--/-/g;
+    		} else {
+    		$devices{$device_id}{name} = "auth_id_".$auth->{id};
+    		}
+    	    }
+        $devices{$device_id}{description}=translit($auth->{'comments'}) || $devices{$device_id}{name};
+        $devices{$device_id}{auth_id} = $auth->{'id'};
+        $devices{$device_id}{nagios_handler} = $auth->{'nagios_handler'};
+        $devices{$device_id}{link_check} = $auth->{'link_check'};
+        $devices{$device_id}{type}='3';
+        $devices{$device_id}{user_id}=$auth->{'user_id'};
+        #get uplinks
+        my $uplink_port = get_record_sql($dbh,"SELECT * FROM connections WHERE auth_id=".$auth->{'id'});
+        if ($uplink_port and $uplink_port->{port_id}) {
+            my $uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{port_id});
+            if ($uplink and $uplink->{device_id} and $devices{'netdev_'.$uplink->{'device_id'}}) {
+        	$devices{$device_id}{parent}='netdev_'.$uplink->{'device_id'};
+                $devices{$device_id}{parent_port} = $uplink->{port};
+	        $devices{$device_id}{parent_port_snmp_index} = $uplink->{snmp_index};
+        	$devices{$device_id}{parent_name}=$devices{$devices{$device_id}{parent}}->{'name'};
+        	$devices{$device_id}{parent_snmp_version}=$devices{$devices{$device_id}{parent}}->{'snmp_version'};
+        	$devices{$device_id}{parent_community}=$devices{$devices{$device_id}{parent}}->{'community'};
+        	}
+            }
+        }
+    }
+
+foreach my $dir (@cfg_dirs) {
+    next if ($dir eq '/');
+    next if ($dir eq '/etc');
+    next if ($dir eq $config_ref{nagios_dir});
+    mkdir $dir unless (-d $dir);
+    unlink glob "$dir/*.cfg";
+}
+
+##################################### Switches config ################################################
+
+write_to_file($nagios_devices,"#lisf of device for nagios",0);
+
+foreach my $device_id (keys %devices) {
+my $device = $devices{$device_id};
+next if (!$device->{ip});
+if ($device->{parent_name}) { push(@{$dependency{$device->{parent_name}}},$device->{name}); }
+print_nagios_cfg($device);
+write_to_file($nagios_devices,'$devices{"'.$device->{'ip'}.'"}{"hostname"}="'.$device->{'name'}.'";',1);
+}
+
+####################### Dependency ###########################
+
+open(FH,">",$config_ref{nagios_dir}."/dependency/dep_hosts.cfg");
+foreach my $device_name (keys %dependency) {
+my @dep_list=@{$dependency{$device_name}};
+if (@dep_list and scalar(@dep_list)) {
+    my $dep_hosts;
+    foreach my $dep_host (@dep_list) {
+	next if (!$dep_host);
+	$dep_hosts = $dep_hosts.",".$dep_host;
+	}
+    next if (!$dep_hosts);
+    $dep_hosts=~s/^,//;
+    print(FH "define hostdependency {\n");
+    print(FH "       host_name			$device_name\n");
+    print(FH "       dependent_host_name	$dep_hosts\n");
+    print(FH "       execution_failure_criteria      n,u\n");
+    print(FH "       notification_failure_criteria   d,u\n");
+    print(FH "       }\n");
+    }
+}
+close(FH);
+
+exit

+ 205 - 0
scripts/hmonitor.pl

@@ -0,0 +1,205 @@
+#!/usr/bin/perl
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+use FindBin '$Bin';
+use utf8;
+use open ":encoding(utf8)";
+use lib "/opt/Eye/scripts";
+use strict;
+use Time::Local;
+use FileHandle;
+use eyelib::config;
+use eyelib::mysql;
+use eyelib::main;
+use eyelib::nagios;
+use Data::Dumper;
+use Time::Local;
+use Date::Parse;
+use Getopt::Long;
+use Proc::Daemon;
+use Cwd;
+use File::Tail;
+
+my $pf = '/run/hmonitor/hmonitor.pid';
+
+my $daemon = Proc::Daemon->new(
+        pid_file => $pf,
+        work_dir => $HOME_DIR
+);
+
+# are you running?  Returns 0 if not.
+my $pid = $daemon->Status($pf);
+
+my $daemonize = 1;
+
+GetOptions(
+    'daemon!' => \$daemonize,
+    "help"    => \&usage,
+    "reload"  => \&reload,
+    "restart" => \&restart,
+    "start"   => \&run,
+    "status"  => \&status,
+    "stop"    => \&stop
+) or &usage;
+
+exit(0);
+
+sub stop {
+        if ($pid) {
+                print "Stopping pid $pid...";
+                if ($daemon->Kill_Daemon($pf)) {
+                        print "Successfully stopped.\n";
+                } else {
+                        print "Could not find $pid.  Was it running?\n";
+                }
+         } else {
+                print "Not running, nothing to stop.\n";
+         }
+}
+
+sub status {
+        if ($pid) {
+                print "Running with pid $pid.\n";
+        } else {
+                print "Not running.\n";
+        }
+}
+
+sub run {
+if (!$pid) {
+    print "Starting...";
+    if ($daemonize) {
+        # when Init happens, everything under it runs in the child process.
+        # this is important when dealing with file handles, due to the fact
+        # Proc::Daemon shuts down all open file handles when Init happens.
+        # Keep this in mind when laying out your program, particularly if
+        # you use filehandles.
+        $daemon->Init;
+        }
+
+setpriority(0,0,19);
+
+while(1) {
+eval {
+
+my $hdb = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS");
+if ( !defined $hdb ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
+
+#parse log
+my $nagios_log=File::Tail->new(name=>$config_ref{nagios_event_socket},maxinterval=>5,interval=>1,ignore_nonexistant=>1) || die "$config_ref{nagios_event_socket} not found!";
+
+#truncate current log file
+truncate $config_ref{nagios_event_socket}, 0;
+
+while (my $logline=$nagios_log->read) {
+
+next unless defined $logline;
+chomp($logline);
+
+log_debug("GET:".$logline);
+
+my ($date,$hoststate,$hoststatetype,$hostname,$hostip,$hostid,$hosttype,$svc_control)= split (/\|/, $logline);
+next if (!$hostip);
+
+if (time()-$last_refresh_config>=60) { init_option($hdb); }
+
+if (!$svc_control) { $svc_control=0; }
+
+if ($hoststate=~/UNREACHABLE/i) { $hoststate='DOWN'; }
+
+my $old_state = 'HARDDOWN';
+
+my $device;
+my $auth;
+my $login;
+my $nagios_handler;
+
+if (!$hostid or $hostid !~ /^[0-9]/) {
+    $auth = get_record_sql($hdb,'SELECT * FROM User_auth WHERE deleted=0 AND ip="'.$hostip.'"');
+    next if (!$auth);
+    $hostid = $auth->{id};
+    $login = get_record_sql($hdb,'SELECT * FROM User_list WHERE id='.$auth->{user_id});
+    $device = get_record_sql($hdb,'SELECT * FROM devices WHERE user_id='.$auth->{user_id});
+    if ($auth->{nagios_status}) { $old_state = $auth->{nagios_status}; }
+    db_log_verbose($hdb,"Manual host: $hostname [$hostip] => $hoststate, old: $old_state");
+    } else {
+    if ($hosttype=~/device/i) {
+        $device = get_record_sql($hdb,'SELECT * FROM devices WHERE id='.$hostid);
+        $login = get_record_sql($hdb,'SELECT * FROM User_list WHERE id='.$device->{user_id});
+        $auth = get_record_sql($hdb,'SELECT * FROM User_auth WHERE user_id='.$device->{user_id}.' AND deleted=0 AND ip="'.$hostip.'"');
+        if ($device->{nagios_status}) { $old_state = $device->{nagios_status}; }
+        } else {
+        $auth = get_record_sql($hdb,'SELECT * FROM User_auth WHERE id='.$hostid);
+        $login = get_record_sql($hdb,'SELECT * FROM User_list WHERE id='.$auth->{user_id});
+        $device = get_record_sql($hdb,'SELECT * FROM devices WHERE user_id='.$auth->{user_id});
+        if ($auth->{nagios_status}) { $old_state = $auth->{nagios_status}; }
+        }
+    }
+
+if ($auth and $auth->{nagios_handler}) { $nagios_handler=$auth->{nagios_handler}; }
+
+db_log_debug($hdb,"Get old for $hostname [$hostip] id: $hostid type: $hosttype => state: $old_state");
+if ($hoststate eq "DOWN") { $hoststate=$hoststatetype.$hoststate; }
+db_log_debug($hdb,"Now for $hostname [$hostip] id: $hostid type: $hosttype => state: $hoststate");
+
+if ($hoststate ne $old_state) {
+    #disable child
+    my $full_action = ($svc_control eq 2);
+    #Change device state
+    db_log_verbose($hdb,"Host changed! $hostname [$hostip] => $hoststate, old: $old_state");
+    my $ip_aton=StrToIp($hostip);
+    if ($device->{id}) { do_sql($hdb,'UPDATE devices SET nagios_status="'.$hoststate.'" WHERE id='.$device->{id}); }
+    if ($auth->{id}) { do_sql($hdb,'UPDATE User_auth SET nagios_status="'.$hoststate.'" WHERE id='.$auth->{id}); }
+    if ($hoststate=~/UP/i) {
+        nagios_host_svc_enable($hostname,1);
+        db_log_debug($hdb,"Enable notifications for host $hostname [$hostip] id: $hostid services");
+        }
+    if ($hoststate=~/SOFTDOWN/i) {
+        if ($svc_control) {
+            nagios_host_svc_disable($hostname,$full_action);
+            db_log_debug($hdb,"Disable notifications for host $hostname [$hostip] id: $hostid services");
+            }
+        }
+    if ($hoststate=~/HARDDOWN/i) {
+        if ($svc_control) {
+            nagios_host_svc_disable($hostname,$full_action);
+            db_log_debug($hdb,"Disable notifications for host $hostname [$hostip] id: $hostid services");
+            }
+        if ($nagios_handler) {
+            db_log_info($hdb,"Event handler $nagios_handler for $hostname [$hostip] => $hoststate found!");
+            if ($nagios_handler=~/restart-port/i) {
+                    my $run_cmd = $HOME_DIR."/restart_port_snmp.pl $hostip & ";
+                    db_log_info($hdb,"Nagios eventhandler restart-port started for ip: $hostip");
+                    db_log_info($hdb,"Run handler: $run_cmd");
+                    system($run_cmd);
+                    }
+            } else {
+            db_log_debug($hdb,"Event handler for $hostname [$hostip] => $hoststate not found.");
+            }
+        }
+    }
+}
+};
+if ($@) { log_error("Exception found: $@"); sleep(60); }
+}
+    } else {
+        log_error("Already Running with pid $pid");
+    }
+}
+
+sub usage {
+    print "usage: hmonitor.pl (start|stop|status|restart)\n";
+    exit(0);
+}
+
+sub reload {
+    print "reload process not implemented.\n";
+}
+
+sub restart {
+    stop;
+    run;
+}

+ 158 - 0
scripts/import-system-dev.pl

@@ -0,0 +1,158 @@
+#!/usr/bin/perl
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+#Обновляем БД устрйств
+
+use FindBin '$Bin';
+use lib "$Bin/";
+use Data::Dumper;
+use Rstat::config;
+use Rstat::main;
+use Rstat::mysql;
+use Rstat::net_utils;
+use strict;
+use warnings;
+
+
+print "Stage 0: Read system devices\n";
+
+my @user_devices=();
+
+if (-e "system-devs.csv") {
+    my @nSQL=read_file("system-devs.csv");
+    foreach my $row (@nSQL) {
+        my ($dev_id,$dev_model,$dev_vendor) = split(/;/,$row);
+        my $device;
+        $device->{id}=$dev_id;
+        $device->{model_name}=$dev_model;
+        $device->{vendor_id}=$dev_vendor;
+        push(@user_devices,$device);
+        }
+    }
+
+print "Stage 1: Read system vendors\n";
+
+my @user_vendors=();
+if (-e "system-vendors.csv") {
+    my @nSQL=read_file("system-vendors.csv");
+    foreach my $row (@nSQL) {
+        my ($vendor_id,$vendor_name) = split(/;/,$row);
+        my $vendor;
+        $vendor->{id}=$vendor_id;
+        $vendor->{name}=$vendor_name;
+        push(@user_vendors,$vendor);
+        }
+    }
+print "Done!\n";
+
+my %vendor_migration;
+
+print "Import Vendors\n";
+foreach my $vendor (@user_vendors) {
+#seach exists vendor created by user
+my $vendor_exist = get_record_sql($dbh,"SELECT * FROM vendors WHERE id>=10000 and LOWER(name)='".lc(trim($vendor->{name}))."'");
+print "Check: $vendor->{name} id: $vendor->{id} ...";
+if ($vendor_exist) {
+    if ($vendor_exist->{id} == $vendor->{id}) { print "OK\n"; next; }
+    print " created by user. Switch to system pool.";
+    do_sql($dbh,"UPDATE vendors SET id=".$vendor->{id}." WHERE id=".$vendor_exist->{id});
+    do_sql($dbh,"UPDATE device_models SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
+    do_sql($dbh,"UPDATE devices SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
+    print " Migrated.\n";
+    next;
+    }
+#check system pool
+$vendor_exist = get_record_sql($dbh,"SELECT * FROM vendors WHERE id<10000 and LOWER(name)='".lc(trim($vendor->{name}))."'");
+if ($vendor_exist) {
+    if ($vendor_exist->{id} == $vendor->{id}) { print "OK\n"; next ; }
+    print "Warning! System vendor mismatch! ";
+    my $vendor2 = get_record_sql($dbh,"SELECT * FROM vendors WHERE id=$vendor->{id}");
+    if ($vendor2) {
+        print "Found another vendor with this id =>".$vendor2->{name};
+        my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM vendors");
+        my $new_vendor_id = $last_id->{'last'}+1;
+        if ($new_vendor_id <=10000 ) { $new_vendor_id = 10001; }
+        print " Move vendor $vendor2->{name} to user custom block. Run script again\n";
+        do_sql($dbh,"UPDATE vendors SET id=".$new_vendor_id." WHERE id=".$vendor2->{id});
+        do_sql($dbh,"UPDATE device_models SET vendor_id=".$new_vendor_id." WHERE vendor_id=".$vendor2->{id});
+        next;
+        }
+    do_sql($dbh,"UPDATE vendors SET id=".$vendor->{id}." WHERE id=".$vendor_exist->{id});
+    do_sql($dbh,"UPDATE device_models SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
+    do_sql($dbh,"UPDATE devices SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
+    print "Fixed.\n";
+    next;
+    }
+#check another record with this id
+my $vendor2 = get_record_sql($dbh,"SELECT * FROM vendors WHERE id=$vendor->{id}");
+if ($vendor2) {
+    print "Found another vendor with this id =>".$vendor2->{name};
+    my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM vendors");
+    my $new_vendor_id = $last_id->{'last'}+1;
+    if ($new_vendor_id <=10000 ) { $new_vendor_id = 10001; }
+    print " Move vendor $vendor2->{name} to user custom block. Run script again\n";
+    do_sql($dbh,"UPDATE vendors SET id=".$new_vendor_id." WHERE id=".$vendor2->{id});
+    do_sql($dbh,"UPDATE device_models SET vendor_id=".$new_vendor_id." WHERE vendor_id=".$vendor2->{id});
+    next;
+    }
+insert_record($dbh,"vendors",$vendor);
+print " Imported.\n";
+}
+print "Done!\n";
+
+print "Import devices\n";
+
+foreach my $device (@user_devices) {
+#seach exists device created by user
+print "Check id: $device->{id} name: $device->{model_name}..";
+my $device_exist = get_record_sql($dbh,"SELECT * FROM device_models WHERE id>=10000 AND vendor_id=".$device->{vendor_id}." AND LOWER(model_name)='".lc(trim($device->{model_name}))."'");
+if ($device_exist) {
+    if ($device_exist->{id} == $device->{id}) { print "OK\n"; next; }
+    do_sql($dbh,"UPDATE device_models SET id=".$device->{id}." WHERE id=".$device_exist->{id});
+    do_sql($dbh,"UPDATE devices SET device_model_id=".$device->{id}." WHERE device_model_id=".$device_exist->{id});
+    print "Migrated\n";
+    next;
+    }
+#system model table
+$device_exist = get_record_sql($dbh,"SELECT * FROM device_models WHERE id<10000 AND vendor_id=".$device->{vendor_id}." AND LOWER(model_name)='".lc(trim($device->{model_name}))."'");
+if ($device_exist) {
+    if ($device_exist->{id} == $device->{id}) { print "OK\n"; next; }
+    print "Warning! System device model mismatch! ";
+    my $device2 = get_record_sql($dbh,"SELECT * FROM device_models WHERE id=".$device->{id});
+    if ($device2) {
+        print "Found another device model with this id =>".$device2->{model_name};
+        my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM device_models");
+        my $new_model_id = $last_id->{'last'}+1;
+        if ($new_model_id <=10000 ) { $new_model_id = 10001; }
+        print " Move device model $device2->{model_name} to user custom block. Run script again\n";
+        do_sql($dbh,"UPDATE device_models SET id=".$new_model_id." WHERE id=".$device2->{id});
+        do_sql($dbh,"UPDATE devices SET device_model_id=".$new_model_id." WHERE device_model_id=".$device2->{id});
+        next;
+        }
+    do_sql($dbh,"UPDATE device_models SET id=".$device->{id}." WHERE id=".$device_exist->{id});
+    do_sql($dbh,"UPDATE devices SET device_model_id=".$device->{id}." WHERE device_model_id=".$device_exist->{id});
+    print "Migrated\n";
+    next;
+    }
+#check another record with this id
+my $device2 = get_record_sql($dbh,"SELECT * FROM device_models WHERE id=".$device->{id});
+if ($device2) {
+    print "Found another device model with this id =>".$device2->{model_name};
+    my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM device_models");
+    my $new_model_id = $last_id->{'last'}+1;
+    if ($new_model_id <=10000 ) { $new_model_id = 10001; }
+    print " Move device model $device2->{model_name} to user custom block. Run script again\n";
+    do_sql($dbh,"UPDATE device_models SET id=".$new_model_id." WHERE id=".$device2->{id});
+    do_sql($dbh,"UPDATE devices SET device_model_id=".$new_model_id." WHERE device_model_id=".$device2->{id});
+    next;
+    }
+insert_record($dbh,"device_models",$device);
+print " Imported.\n";
+}
+
+print "Done!\n";
+
+exit;

+ 10 - 0
scripts/restart_nagios

@@ -0,0 +1,10 @@
+#!/bin/bash
+
+/opt/Eye/scripts/gen_nagios_config.pl
+[ $? -ne 0 ] && exit
+
+/opt/Eye/scripts/sync_mikrotik_poe_monitor.pl
+
+/usr/bin/systemctl reload nagios4 >/dev/null 2>&1
+
+exit

+ 129 - 0
scripts/restart_port_snmp.pl

@@ -0,0 +1,129 @@
+#!/usr/bin/perl
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+use FindBin '$Bin';
+use lib "$Bin/";
+use strict;
+use Time::Local;
+use FileHandle;
+use Data::Dumper;
+use eyelib::config;
+use eyelib::main;
+use eyelib::net_utils;
+use eyelib::mysql;
+use eyelib::snmp;
+use Net::SNMP qw(:snmp);
+
+my $pethPsePortAdminEnable ='.1.3.6.1.2.1.105.1.1.1.3.1.';
+
+my $huawei_poe_oid         ='.1.3.6.1.4.1.2011.5.25.195.3.1.3.';
+my $allied_poe_oid         ='.1.3.6.1.2.1.105.1.1.1.3.1.';
+my $hp_poe_oid             ='.1.3.6.1.2.1.105.1.1.1.3.1.';
+my $netgear_poe_oid        ='.1.3.6.1.4.1.4526.11.15.1.1.1.6.1.';
+my $mikrotik_poe_oid       ='.1.3.6.1.4.1.14988.1.1.15.1.1.3.';
+
+my $admin_status_oid       ='.1.3.6.1.2.1.2.2.1.7.';
+
+#wait for up interface
+my $sleep_time = 15;
+
+$|=1;
+
+exit if (!$ARGV[0]);
+
+my $HOST_IP = $ARGV[0];
+
+my $IP_ATON=StrToIp($HOST_IP);
+
+my $auth_id = get_id_record($dbh,'User_auth',"deleted=0 and ip_int='".$IP_ATON."'");
+if (!$auth_id) { db_log_error("Record with ip $HOST_IP not found! Bye."); exit; }
+
+my $ip;
+my $model;
+my $port;
+my $snmp_index;
+my $community;
+my $snmp_version;
+
+my $d_sql="SELECT D.ip, D.device_name, D.vendor_id, D.device_model_id, DP.port, DP.snmp_index, D.rw_community, D.snmp_version  FROM devices AS D, device_ports AS DP, connections AS C WHERE D.snmp_version>0 and D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id=$auth_id AND DP.uplink=0";
+
+my $dev_port = get_record_sql($dbh,$d_sql);
+
+if (!$dev_port) { db_log_error($dbh,"Connection for $HOST_IP not found! Bye."); exit; }
+
+my $ip=$dev_port->{ip};
+my $model=$dev_port->{device_model_id};
+my $port=$dev_port->{port};
+my $vendor_id = $dev_port->{vendor_id};
+my $snmp_index=$dev_port->{snmp_index};
+my $community=$dev_port->{rw_community};
+my $snmp_version=$dev_port->{snmp_version};
+my $device_name = $dev_port->{device_name};
+
+db_log_warning($dbh,"Restart $HOST_IP at $device_name ($model $ip) [$port] request found. Try.");
+
+my $poe_oid;
+my $admin_oid;
+
+my $poe_enabled_value = 1;
+my $poe_disabled_value = 2;
+
+my $ret;
+
+#################### PORT STATE ###################
+
+#default
+$admin_oid=$admin_status_oid.$port;
+
+##################### POE #########################
+
+#default
+$poe_oid=$pethPsePortAdminEnable.$snmp_index;
+
+#Huawei
+if ($vendor_id eq 3) {
+    $poe_oid=$huawei_poe_oid.$snmp_index;
+    }
+
+#NetGear
+if ($vendor_id eq 10) {
+    $poe_oid=$netgear_poe_oid.$snmp_index;
+    }
+
+##################### Action ########################
+
+db_log_debug($dbh,"POE oid: $poe_oid");
+db_log_debug($dbh,"Admin oid: $admin_oid");
+
+if ($poe_oid) {
+    $ret=snmp_set_int($ip,$poe_oid,$poe_disabled_value,$community,161,$snmp_version);
+    db_log_info($dbh,"Try disable POE at port $port.");
+    db_log_debug($dbh,"Send to oid: $poe_oid value: $poe_disabled_value");
+    }
+
+if ($admin_oid) {
+    $ret=snmp_set_int($ip,$admin_oid,$poe_disabled_value,$community,161,$snmp_version); 
+    db_log_info($dbh,"Try shutdown port $port.");
+    db_log_debug($dbh,"Send to oid: $admin_oid value: $poe_disabled_value");
+    }
+
+sleep($sleep_time);
+
+if ($admin_oid) {
+    $ret=snmp_set_int($ip,$admin_oid,$poe_enabled_value,$community,161,$snmp_version);
+    db_log_info($dbh,"Enable POE at port $port.");
+    db_log_debug($dbh,"Send to oid: $admin_oid value: $poe_enabled_value");
+    }
+
+if ($poe_oid) {
+    $ret=snmp_set_int($ip,$poe_oid,$poe_enabled_value,$community,161,$snmp_version); 
+    db_log_info($dbh,"Up port $port.");
+    db_log_debug($dbh,"Send to oid: $poe_oid value: $poe_enabled_value");
+    }
+
+db_log_info($dbh,'Done!');
+
+exit;

+ 114 - 0
scripts/sync_mikrotik_poe_monitor.pl

@@ -0,0 +1,114 @@
+#!/usr/bin/perl -w
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+use FindBin '$Bin';
+use lib "$Bin/";
+use strict;
+use Time::Local;
+use FileHandle;
+use Data::Dumper;
+use eyelib::config;
+use eyelib::main;
+use eyelib::cmd;
+use Net::Patricia;
+use Date::Parse;
+use eyelib::net_utils;
+use eyelib::mysql;
+use DBI;
+use utf8;
+use Fcntl qw(:flock);
+
+open(SELF,"<",$0) or die "Cannot open $0 - $!";
+flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
+
+#exit;
+#$debug = 1;
+
+$|=1;
+
+if (IsNotRun($SPID)) { Add_PID($SPID); }  else { die "Warning!!! $SPID already runnning!\n"; }
+
+my @poe_mikrotik = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 and device_model_id=12");
+
+foreach my $device (@poe_mikrotik) {
+next if (!$device);
+my $switch_name=$device->{device_name};
+my $switch_ip=$device->{ip};
+
+my @cmd_list=();
+
+my @auth_list = get_records_sql($dbh,"SELECT DP.port,AU.ip FROM `device_ports` AS DP, `User_auth` as AU, `connections` as C WHERE DP.id=C.port_id and C.auth_id=AU.id and AU.deleted=0 and AU.link_check=1 and AU.nagios=1 and C.device_id=".$device->{id}."");
+
+my %work_list;
+foreach my $auth (@auth_list) {
+next if (!$auth);
+$work_list{'ether'.$auth->{port}}=$auth->{ip};
+}
+
+$device = netdev_set_auth($device);
+$device->{login}.='+ct400w';
+
+db_log_verbose($dbh,"Sync link monitor at $switch_name [".$switch_ip."] started.");
+
+my $t = netdev_login($device);
+
+#/interface ethernet terse
+#/interface ethernet set [ find default-name=ether1 ] loop-protect=on power-cycle-ping-address=192.168.22.51 power-cycle-ping-enabled=yes power-cycle-ping-timeout=3m speed=100Mbps
+#/interface ethernet set [ find default-name=ether2 ] loop-protect=on speed=100Mbps
+
+#fetch current
+my @current_monitor=netdev_cmd($device,$t,'ssh','/interface ethernet export terse',1);
+@current_monitor=grep(/power/,@current_monitor);
+
+my %current_list;
+foreach my $poe (@current_monitor) {
+next if (!$poe);
+my $port_name;
+my $ping_enabled=0;
+my $ping_address;
+my @words=split(/ /,$poe);
+    foreach my $item (@words) {
+    if ($item=~/(ether\d{1,2})/) { $port_name=$1; }
+    if ($item=~/power-cycle-ping-address=(.*)/) { $ping_address=$1; }
+    if ($item=~/power-cycle-ping-enabled=yes/) { $ping_enabled=1; }
+    }
+next if (!$ping_enabled);
+next if (!$port_name or !$ping_address);
+$current_list{$port_name}=$ping_address;
+}
+
+foreach my $current_port (keys %current_list) {
+if (defined $work_list{$current_port}) {
+    if ($work_list{$current_port} ne $current_list{$current_port}) {
+        db_log_info($dbh,"Change settings poe monitor at $switch_name [$current_port] to ip: $work_list{$current_port}");
+	push(@cmd_list,'/interface ethernet set [ find default-name='.$current_port.' ] power-cycle-ping-address='.$work_list{$current_port}.' power-cycle-ping-enabled=yes power-cycle-ping-timeout=3m'); 
+	}
+    } else {
+    db_log_info($dbh,"Disable poe monitor at $switch_name [$current_port]");
+    push(@cmd_list,'/interface ethernet set [ find default-name='.$current_port.' ] power-cycle-ping-enabled=no');
+    }
+}
+
+foreach my $work_port (keys %work_list) {
+if (!defined $current_list{$work_port}) {
+    db_log_info($dbh,"Enable poe monitor at $switch_name [$work_port] for $work_list{$work_port}");
+    push(@cmd_list,'/interface ethernet set [ find default-name='.$work_port.' ] power-cycle-ping-address='.$work_list{$work_port}.' power-cycle-ping-enabled=yes power-cycle-ping-timeout=3m');
+    }
+}
+
+if (scalar(@cmd_list)) {
+    netdev_cmd($device,$t,'ssh',\@cmd_list,1);
+    if ($debug) { foreach my $cmd (@cmd_list) { db_log_debug($dbh,"$cmd"); } }
+    }
+
+db_log_verbose($dbh,"Sync link monitor at $switch_name [".$switch_ip."] stopped.");
+}
+
+$dbh->disconnect();
+
+if (IsMyPID($SPID)) { Remove_PID($SPID); };
+
+do_exit 0;

+ 9 - 0
scripts/updates/2-5-3/mysql-acl.sql

@@ -0,0 +1,9 @@
+CREATE TABLE `acl` (`id` int(11) NOT NULL,`name` varchar(30) NOT NULL,`description.english` varchar(250) NOT NULL,`description.russian` varchar(250) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+INSERT INTO `acl` VALUES(1, 'Full access', 'Full access', 'Полный доступ');
+INSERT INTO `acl` VALUES(2, 'Operator', 'Editing parameters that are not related to access rights', 'Редактирование параметров, не связанных с правами доступа');
+INSERT INTO `acl` VALUES(3, 'View only', 'View only', 'Только просмотр');
+ALTER TABLE `Customers` CHANGE `readonly` `rights` TINYINT(1) NOT NULL DEFAULT '3';
+UPDATE `Customers` set rights=3 WHERE rights=1;
+UPDATE `Customers` set rights=1 WHERE rights=0;
+ALTER TABLE `acl`  ADD PRIMARY KEY (`id`);
+ALTER TABLE `acl`  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

+ 1 - 0
scripts/updates/2-5-3/version.sql

@@ -0,0 +1 @@
+REPLACE INTO `version` (`version`) VALUES ('2.5.3');