Files
Tony Murray 0801af7a81 Consolidate and improve snmptranslate usage (#14567)
* Consolidate and improve snmptranslate usage

* Fix style

* lint fixes

* fix typo

* allow multiple mib directories

* Only add mib if it is not already set

* oid first, in case we have key length issues

* if there is a full oid, don't add other mibs

* debug in ci

* more debug in ci

* better debug in ci

* remove debug

* Use numeric index

* revert dlink change

* Don't add -On twice

* unit tests and hopefully better heuristics

* remove dump and add one more set of tests

* style fixes

* handle bad input in old functions

* shortcut whole snmp_translate function
2022-11-07 12:00:47 -06:00

83 lines
2.2 KiB
PHP

<?php
/*
* Snmp.php
*
* -Description-
*
* 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/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2022 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Util;
use Cache;
use LibreNMS\Exceptions\InvalidOidException;
class Oid
{
public static function isNumeric(string $oid): bool
{
return (bool) preg_match('/^[.\d]+$/', $oid);
}
public static function hasNumericRoot(string $oid): bool
{
return (bool) preg_match('/^\.?1/', $oid);
}
public static function hasNumeric(array $oids): bool
{
foreach ($oids as $oid) {
if (self::isNumeric($oid)) {
return true;
}
}
return false;
}
/**
* Converts an oid to numeric and caches the result
*
* @throws \LibreNMS\Exceptions\InvalidOidException
*/
public static function toNumeric(string $oid, string $mib = 'ALL', int $cache = 1800): string
{
if (Oid::isNumeric($oid)) {
return $oid;
}
// we already have a specific mib, don't add a bunch of others
if (str_contains($oid, '::')) {
$mib = null;
}
$key = 'Oid:toNumeric:' . $oid . '/' . $mib;
$numeric_oid = Cache::remember($key, $cache, function () use ($oid, $mib) {
return \SnmpQuery::numeric()->translate($oid, $mib);
});
if (empty($numeric_oid)) {
throw new InvalidOidException("Unable to translate oid $oid");
}
return $numeric_oid;
}
}