Skip to content

Commit

Permalink
Remove legacy addhost code (librenms#15376)
Browse files Browse the repository at this point in the history
* Remove legacy addhost code
Update webui addhost
Update device snmp settings page
Update discovery protocols device discovery (no longer force full new device discovery in process)

* remove baseline exceptions

* Apply fixes from StyleCI

---------

Co-authored-by: StyleCI Bot <[email protected]>
  • Loading branch information
murrant and StyleCIBot authored Oct 8, 2023
1 parent 685d11d commit c87c6e8
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 526 deletions.
37 changes: 24 additions & 13 deletions includes/discovery/functions.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* See COPYING for more details.
*/

use App\Models\Eventlog;
use App\Models\Ipv6Address;
use App\Models\Ipv6Network;
use App\Models\Port;
Expand All @@ -26,7 +27,16 @@
use LibreNMS\Util\IPv6;
use LibreNMS\Util\UserFuncHelper;

function discover_new_device($hostname, $device = [], $method = '', $interface = '')
/**
* @param string $hostname
* @param array $device
* @param string $method name of process discoverying this device
* @param array|null $interface Interface this device was discovered on
* @return false|int
*
* @throws InvalidIpException
*/
function discover_new_device($hostname, $device, $method, $interface = null)
{
d_echo("discovering $hostname\n");

Expand Down Expand Up @@ -77,25 +87,26 @@ function discover_new_device($hostname, $device = [], $method = '', $interface =
}

try {
$remote_device_id = addHost($hostname, '', '161', 'udp', $device['poller_group']); // discover with actual poller group
$remote_device = device_by_id_cache($remote_device_id, 1);
echo '+[' . $remote_device['hostname'] . '(' . $remote_device['device_id'] . ')]';
discover_device($remote_device);
device_by_id_cache($remote_device_id, 1);
$remote_device = new \App\Models\Device([
'hostname' => $hostname,
'poller_group' => $device['poller_group'],
]);
$result = \App\Actions\Device\ValidateDeviceAndCreate($remote_device)->execute();

if ($result) {
echo '+[' . $remote_device->hostname . '(' . $remote_device->device_id . ')]';

if ($remote_device_id && is_array($device) && ! empty($method)) {
$extra_log = is_array($interface) ? ' (port ' . cleanPort($interface)['label'] . ') ' : '';
Eventlog::log('Device ' . $remote_device->hostname . " ($ip) $extra_log autodiscovered through $method on " . $device['hostname'], $device['device_id'], 'discovery', Severity::Ok);

log_event('Device ' . $remote_device['hostname'] . " ($ip) $extra_log autodiscovered through $method on " . $device['hostname'], $remote_device_id, 'discovery', 1);
} else {
log_event("$method discovery of " . $remote_device['hostname'] . " ($ip) failed - Check ping and SNMP access", $device['device_id'], 'discovery', 5);
return $remote_device->device_id;
}

return $remote_device_id;
Eventlog::log("$method discovery of " . $remote_device->hostname . " ($ip) failed - Check ping and SNMP access", $device['device_id'], 'discovery', Severity::Error);
} catch (HostExistsException $e) {
// already have this device
} catch (Exception $e) {
log_event("$method discovery of " . $hostname . " ($ip) failed - " . $e->getMessage(), $device['device_id'], 'discovery', 5);
Eventlog::log("$method discovery of " . $hostname . " ($ip) failed - " . $e->getMessage(), $device['device_id'], 'discovery', Severity::Error);
}

return false;
Expand Down Expand Up @@ -153,7 +164,7 @@ function discover_device(&$device, $force_module = false)
} catch (Throwable $e) {
// isolate module exceptions so they don't disrupt the polling process
Log::error("%rError discovering $module module for {$device['hostname']}.%n $e", ['color' => true]);
\App\Models\Eventlog::log("Error discovering $module module. Check log file for more details.", $device['device_id'], 'discovery', Severity::Error);
Eventlog::log("Error discovering $module module. Check log file for more details.", $device['device_id'], 'discovery', Severity::Error);
report($e);

// Re-throw exception if we're in CI
Expand Down
253 changes: 0 additions & 253 deletions includes/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,7 @@
use App\Models\Device;
use Illuminate\Support\Str;
use LibreNMS\Config;
use LibreNMS\Enum\PortAssociationMode;
use LibreNMS\Enum\Severity;
use LibreNMS\Exceptions\HostExistsException;
use LibreNMS\Exceptions\HostIpExistsException;
use LibreNMS\Exceptions\HostnameExistsException;
use LibreNMS\Exceptions\HostSysnameExistsException;
use LibreNMS\Exceptions\HostUnreachableException;
use LibreNMS\Exceptions\HostUnreachablePingException;
use LibreNMS\Exceptions\HostUnreachableSnmpException;
use LibreNMS\Exceptions\InvalidPortAssocModeException;
use LibreNMS\Exceptions\SnmpVersionUnsupportedException;
use LibreNMS\Modules\Core;

/**
* Parse cli discovery or poller modules and set config for this run
Expand Down Expand Up @@ -164,248 +153,6 @@ function delete_device($id)
return "Failed to remove device $device->hostname";
}

/**
* Add a device to LibreNMS
*
* @param string $host dns name or ip address
* @param string $snmp_version If this is empty, try v2c,v3,v1. Otherwise, use this specific version.
* @param int $port the port to connect to for snmp
* @param string $transport udp or tcp
* @param string $poller_group the poller group this device will belong to
* @param bool $force_add add even if the device isn't reachable
* @param string $port_assoc_mode snmp field to use to determine unique ports
* @param array $additional an array with additional parameters to take into consideration when adding devices
* @return int returns the device_id of the added device
*
* @throws HostExistsException This hostname already exists
* @throws HostIpExistsException We already have a host with this IP
* @throws HostUnreachableException We could not reach this device is some way
* @throws HostUnreachablePingException We could not ping the device
* @throws InvalidPortAssocModeException The given port association mode was invalid
* @throws SnmpVersionUnsupportedException The given snmp version was invalid
*/
function addHost($host, $snmp_version = '', $port = 161, $transport = 'udp', $poller_group = '0', $force_add = false, $port_assoc_mode = 'ifIndex', $additional = [])
{
// Test Database Exists
if (host_exists($host)) {
throw new HostnameExistsException($host);
}

// Valid port assoc mode
if (! in_array($port_assoc_mode, PortAssociationMode::getModes())) {
throw new InvalidPortAssocModeException("Invalid port association_mode '$port_assoc_mode'. Valid modes are: " . join(', ', PortAssociationMode::getModes()));
}

// check if we have the host by IP
$overwrite_ip = null;
if (! empty($additional['overwrite_ip'])) {
$overwrite_ip = $additional['overwrite_ip'];
$ip = $overwrite_ip;
} elseif (Config::get('addhost_alwayscheckip') === true) {
$ip = gethostbyname($host);
} else {
$ip = $host;
}
if ($force_add !== true && $existing = Device::findByIp($ip)) {
throw new HostIpExistsException($host, $existing->hostname, $ip);
}

// Test reachability
if (! $force_add) {
if (! (new \LibreNMS\Polling\ConnectivityHelper(new Device(['hostname' => $ip])))->isPingable()->success()) {
throw new HostUnreachablePingException($host);
}
}

// if $snmpver isn't set, try each version of snmp
if (empty($snmp_version)) {
$snmpvers = Config::get('snmp.version');
} else {
$snmpvers = [$snmp_version];
}

if (isset($additional['snmp_disable']) && $additional['snmp_disable'] == 1) {
return createHost($host, '', $snmp_version, $port, $transport, [], $poller_group, 1, true, $overwrite_ip, $additional);
}
$host_unreachable_exception = new HostUnreachableSnmpException($host);
// try different snmp variables to add the device
foreach ($snmpvers as $snmpver) {
if ($snmpver === 'v3') {
// Try each set of parameters from config
foreach (Config::get('snmp.v3') as $v3) {
$device = deviceArray($host, null, $snmpver, $port, $transport, $v3, $port_assoc_mode, $overwrite_ip);
if ($force_add === true || isSNMPable($device)) {
return createHost($host, null, $snmpver, $port, $transport, $v3, $poller_group, $port_assoc_mode, $force_add, $overwrite_ip);
} else {
$host_unreachable_exception->addReason($snmpver, $v3['authname'] . '/' . $v3['authlevel']);
}
}
} elseif ($snmpver === 'v2c' || $snmpver === 'v1') {
// try each community from config
foreach (Config::get('snmp.community') as $community) {
$device = deviceArray($host, $community, $snmpver, $port, $transport, null, $port_assoc_mode, $overwrite_ip);

if ($force_add === true || isSNMPable($device)) {
return createHost($host, $community, $snmpver, $port, $transport, [], $poller_group, $port_assoc_mode, $force_add, $overwrite_ip);
} else {
$host_unreachable_exception->addReason($snmpver, $community);
}
}
} else {
throw new SnmpVersionUnsupportedException($snmpver);
}
}
if (isset($additional['ping_fallback']) && $additional['ping_fallback'] == 1) {
$additional['snmp_disable'] = 1;
$additional['os'] = 'ping';

return createHost($host, '', $snmp_version, $port, $transport, [], $poller_group, 1, true, $overwrite_ip, $additional);
}
throw $host_unreachable_exception;
}

function deviceArray($host, $community, $snmpver, $port = 161, $transport = 'udp', $v3 = [], $port_assoc_mode = 'ifIndex', $overwrite_ip = null)
{
$device = [];
$device['hostname'] = $host;
$device['overwrite_ip'] = $overwrite_ip;
$device['port'] = $port;
$device['transport'] = $transport;

/* Get port_assoc_mode id if neccessary
* We can work with names of IDs here */
if (! is_int($port_assoc_mode)) {
$port_assoc_mode = PortAssociationMode::getId($port_assoc_mode);
}
$device['port_association_mode'] = $port_assoc_mode;

$device['snmpver'] = $snmpver;
if ($snmpver === 'v2c' or $snmpver === 'v1') {
$device['community'] = $community;
} elseif ($snmpver === 'v3') {
$device['authlevel'] = $v3['authlevel'];
$device['authname'] = $v3['authname'];
$device['authpass'] = $v3['authpass'];
$device['authalgo'] = $v3['authalgo'];
$device['cryptopass'] = $v3['cryptopass'];
$device['cryptoalgo'] = $v3['cryptoalgo'];
}

return $device;
}//end deviceArray()

function isSNMPable($device)
{
$pos = snmp_check($device);
if ($pos === true) {
return true;
} else {
$pos = snmp_get($device, 'sysObjectID.0', '-Oqv', 'SNMPv2-MIB');
if ($pos === '' || $pos === false) {
return false;
} else {
return true;
}
}
}

function getpollergroup($poller_group = '0')
{
//Is poller group an integer
if (is_int($poller_group) || ctype_digit($poller_group)) {
return $poller_group;
} else {
//Check if it contains a comma
if (strpos($poller_group, ',') !== false) {
//If it has a comma use the first element as the poller group
$poller_group_array = explode(',', $poller_group);

return getpollergroup($poller_group_array[0]);
} else {
if (Config::get('distributed_poller_group')) {
//If not use the poller's group from the config
return getpollergroup(Config::get('distributed_poller_group'));
} else {
//If all else fails use default
return '0';
}
}
}
}

/**
* Add a host to the database
*
* @param string $host The IP or hostname to add
* @param string $community The snmp community
* @param string $snmpver snmp version: v1 | v2c | v3
* @param int $port SNMP port number
* @param string $transport SNMP transport: udp | udp6 | udp | tcp6
* @param array $v3 SNMPv3 settings required array keys: authlevel, authname, authpass, authalgo, cryptopass, cryptoalgo
* @param int $poller_group distributed poller group to assign this host to
* @param string $port_assoc_mode field to use to identify ports: ifIndex, ifName, ifDescr, ifAlias
* @param bool $force_add Do not detect the host os
* @param array $additional an array with additional parameters to take into consideration when adding devices
* @return int the id of the added host
*
* @throws HostExistsException Throws this exception if the host already exists
* @throws Exception Throws this exception if insertion into the database fails
*/
function createHost(
$host,
$community,
$snmpver,
$port = 161,
$transport = 'udp',
$v3 = [],
$poller_group = 0,
$port_assoc_mode = 'ifIndex',
$force_add = false,
$overwrite_ip = null,
$additional = []
) {
$host = trim(strtolower($host));

$poller_group = getpollergroup($poller_group);

/* Get port_assoc_mode id if necessary
* We can work with names of IDs here */
if (! is_int($port_assoc_mode)) {
$port_assoc_mode = PortAssociationMode::getId($port_assoc_mode);
}

$device = new Device(array_merge([
'hostname' => $host,
'overwrite_ip' => $overwrite_ip,
'sysName' => $additional['sysName'] ?? $host,
'os' => $additional['os'] ?? 'generic',
'hardware' => $additional['hardware'] ?? null,
'community' => $community,
'port' => $port,
'transport' => $transport,
'status' => '1',
'snmpver' => $snmpver,
'poller_group' => $poller_group,
'status_reason' => '',
'port_association_mode' => $port_assoc_mode,
'snmp_disable' => $additional['snmp_disable'] ?? 0,
], $v3));

if ($force_add !== true) {
$device->os = Core::detectOS($device);

$device->sysName = SnmpQuery::device($device)->get('SNMPv2-MIB::sysName.0')->value();
if (host_exists($host, $device->sysName)) {
throw new HostSysnameExistsException($host, $device->sysName);
}
}
if ($device->save()) {
return $device->device_id;
}

throw new \Exception('Failed to add host to the database, please run ./validate.php');
}

function isDomainResolves($domain)
{
if (gethostbyname($domain) != $domain) {
Expand Down
Loading

0 comments on commit c87c6e8

Please sign in to comment.