From 61c89794e46dd05c1d04e12986f144868029f061 Mon Sep 17 00:00:00 2001 From: Tony Murray Date: Thu, 29 Apr 2021 22:42:18 -0500 Subject: [PATCH] Remove debug globals (#12811) * Remove $debug global and $vdebug global makes these variables more accessible and protects from collisions. * the on boot set sends application as the first parameter, just handle that * Relocate other debug related functions * Log debug to stdout * Wrong output * remove stupid constants * Fix lint and style issues --- LibreNMS/Authentication/RadiusAuthorizer.php | 5 +- LibreNMS/Config.php | 7 +- LibreNMS/Data/Store/Rrd.php | 4 +- LibreNMS/Util/Debug.php | 137 ++++++++++++++++++ LibreNMS/Util/Laravel.php | 54 ------- LibreNMS/Util/ModuleTestHelper.php | 39 +++-- alerts.php | 3 +- app/Console/Kernel.php | 6 +- app/Http/Controllers/DeviceController.php | 3 +- app/Http/Controllers/LegacyController.php | 3 +- app/Jobs/PingCheck.php | 17 +-- app/Providers/LegacyUserProvider.php | 5 +- check-services.php | 3 +- config/logging.php | 2 +- daily.php | 3 +- discovery.php | 9 +- html/ajax_form.php | 4 +- html/ajax_list.php | 4 +- html/ajax_listports.php | 5 +- html/ajax_ossuggest.php | 4 +- html/ajax_output.php | 4 +- html/ajax_search.php | 4 +- html/ajax_table.php | 4 +- html/csv.php | 5 +- html/graph.php | 5 +- html/network-map.php | 3 +- html/pdf.php | 3 +- includes/common.php | 33 +---- includes/discovery/cisco-vrf-lite.inc.php | 4 +- includes/functions.php | 43 +----- includes/helpers.php | 47 +----- includes/html/functions.inc.php | 5 +- includes/html/graphs/graph.inc.php | 2 +- .../html/graphs/macaccounting/auth.inc.php | 2 +- includes/init.php | 3 +- includes/polling/ports.inc.php | 5 +- includes/snmp.inc.php | 5 +- ping.php | 9 +- poll-billing.php | 3 +- poller.php | 6 +- routes/console.php | 3 +- scripts/auth_test.php | 3 +- scripts/collect-port-polling.php | 7 +- scripts/collect-snmp-data.php | 3 +- scripts/new-os.php | 3 +- scripts/save-test-data.php | 6 +- scripts/test-alert.php | 5 +- scripts/test-template.php | 3 +- snmptrap.php | 5 +- tests/OSDiscoveryTest.php | 6 +- tests/OSModulesTest.php | 9 +- 51 files changed, 287 insertions(+), 278 deletions(-) create mode 100644 LibreNMS/Util/Debug.php diff --git a/LibreNMS/Authentication/RadiusAuthorizer.php b/LibreNMS/Authentication/RadiusAuthorizer.php index e74d7586e4..05aa23d30b 100644 --- a/LibreNMS/Authentication/RadiusAuthorizer.php +++ b/LibreNMS/Authentication/RadiusAuthorizer.php @@ -5,6 +5,7 @@ namespace LibreNMS\Authentication; use Dapphp\Radius\Radius; use LibreNMS\Config; use LibreNMS\Exceptions\AuthenticationException; +use LibreNMS\Util\Debug; class RadiusAuthorizer extends MysqlAuthorizer { @@ -22,13 +23,11 @@ class RadiusAuthorizer extends MysqlAuthorizer public function authenticate($credentials) { - global $debug; - if (empty($credentials['username'])) { throw new AuthenticationException('Username is required'); } - if ($debug) { + if (Debug::isEnabled()) { $this->radius->setDebug(true); } diff --git a/LibreNMS/Config.php b/LibreNMS/Config.php index 3c08b9d6be..fd06fcdf19 100644 --- a/LibreNMS/Config.php +++ b/LibreNMS/Config.php @@ -30,6 +30,7 @@ use Illuminate\Database\QueryException; use Illuminate\Support\Arr; use Illuminate\Support\Str; use LibreNMS\DB\Eloquent; +use LibreNMS\Util\Debug; use Log; class Config @@ -259,8 +260,7 @@ class Config if (class_exists(Log::class)) { Log::error($e); } - global $debug; - if ($debug) { + if (Debug::isEnabled()) { echo $e; } @@ -485,8 +485,7 @@ class Config private static function deprecatedVariable($old, $new) { if (self::has($old)) { - global $debug; - if ($debug) { + if (Debug::isEnabled()) { echo "Copied deprecated config $old to $new\n"; } self::set($new, self::get($old)); diff --git a/LibreNMS/Data/Store/Rrd.php b/LibreNMS/Data/Store/Rrd.php index e30d2be823..3cf829b990 100644 --- a/LibreNMS/Data/Store/Rrd.php +++ b/LibreNMS/Data/Store/Rrd.php @@ -29,6 +29,7 @@ use LibreNMS\Config; use LibreNMS\Data\Measure\Measurement; use LibreNMS\Exceptions\FileExistsException; use LibreNMS\Proc; +use LibreNMS\Util\Debug; use LibreNMS\Util\Rewrite; use Log; @@ -356,7 +357,6 @@ class Rrd extends BaseDatastore */ private function command($command, $filename, $options) { - global $vdebug; $stat = Measurement::start($this->coalesceStatisticType($command)); $output = null; @@ -391,7 +391,7 @@ class Rrd extends BaseDatastore Log::error('rrdtool could not start'); } - if ($vdebug) { + if (Debug::isVerbose()) { echo 'RRDtool Output: '; echo $output[0]; echo $output[1]; diff --git a/LibreNMS/Util/Debug.php b/LibreNMS/Util/Debug.php new file mode 100644 index 0000000000..5623c7fbf8 --- /dev/null +++ b/LibreNMS/Util/Debug.php @@ -0,0 +1,137 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2021 Tony Murray + * @author Tony Murray + */ + +namespace LibreNMS\Util; + +use App; +use Illuminate\Database\Events\QueryExecuted; +use LibreNMS\DB\Eloquent; +use Log; + +class Debug +{ + private static $debug = false; + private static $verbose = false; + + public static function set($debug = true, bool $silence = false): bool + { + self::$debug = (bool) $debug; + + restore_error_handler(); // disable Laravel error handler + + if (self::$debug) { + ini_set('display_errors', '1'); + ini_set('display_startup_errors', '1'); + ini_set('log_errors', '0'); + error_reporting(E_ALL & ~E_NOTICE); + + self::enableCliDebugOutput(); + self::enableQueryDebug(); + } else { + ini_set('display_errors', '0'); + ini_set('display_startup_errors', '0'); + ini_set('log_errors', '1'); + error_reporting($silence ? 0 : E_ERROR); + + self::disableCliDebugOutput(); + self::disableQueryDebug(); + } + + return self::$debug; + } + + /** + * Set debug without configuring error reporting. + */ + public static function setOnly(bool $debug = true): bool + { + return self::$debug = $debug; + } + + public static function setVerbose(bool $verbose = true): void + { + self::$verbose = $verbose; + } + + public static function isEnabled(): bool + { + return self::$debug; + } + + public static function isVerbose(): bool + { + return self::$verbose; + } + + public static function disableQueryDebug() + { + $db = Eloquent::DB(); + + if ($db) { + // remove all query executed event handlers + $db->getEventDispatcher()->flush('Illuminate\Database\Events\QueryExecuted'); + } + } + + public static function enableCliDebugOutput() + { + if (Laravel::isBooted() && App::runningInConsole()) { + Log::setDefaultDriver('console'); + } + } + + public static function disableCliDebugOutput() + { + if (Laravel::isBooted()) { + Log::setDefaultDriver('stack'); + } + } + + public static function enableQueryDebug() + { + static $sql_debug_enabled; + $db = Eloquent::DB(); + + if ($db && ! $sql_debug_enabled) { + $db->listen(function (QueryExecuted $query) { + // collect bindings and make them a little more readable + $bindings = collect($query->bindings)->map(function ($item) { + if ($item instanceof \Carbon\Carbon) { + return $item->toDateTimeString(); + } + + return $item; + })->toJson(); + + if (Laravel::isBooted()) { + Log::debug("SQL[%Y{$query->sql} %y$bindings%n {$query->time}ms] \n", ['color' => true]); + } else { + c_echo("SQL[%Y{$query->sql} %y$bindings%n {$query->time}ms] \n"); + } + }); + $sql_debug_enabled = true; + } + } +} diff --git a/LibreNMS/Util/Laravel.php b/LibreNMS/Util/Laravel.php index 7eaacadfd2..c6cac57013 100644 --- a/LibreNMS/Util/Laravel.php +++ b/LibreNMS/Util/Laravel.php @@ -24,10 +24,6 @@ namespace LibreNMS\Util; -use App; -use Illuminate\Database\Events\QueryExecuted; -use LibreNMS\DB\Eloquent; -use Log; use Symfony\Component\HttpFoundation\HeaderBag; class Laravel @@ -77,56 +73,6 @@ class Laravel return function_exists('app') && ! empty(app()->isAlias('Illuminate\Foundation\Application')) && app()->isBooted(); } - public static function enableQueryDebug() - { - static $sql_debug_enabled; - $db = Eloquent::DB(); - - if ($db && ! $sql_debug_enabled) { - $db->listen(function (QueryExecuted $query) { - // collect bindings and make them a little more readable - $bindings = collect($query->bindings)->map(function ($item) { - if ($item instanceof \Carbon\Carbon) { - return $item->toDateTimeString(); - } - - return $item; - })->toJson(); - - if (self::isBooted()) { - Log::debug("SQL[%Y{$query->sql} %y$bindings%n {$query->time}ms] \n", ['color' => true]); - } else { - c_echo("SQL[%Y{$query->sql} %y$bindings%n {$query->time}ms] \n"); - } - }); - $sql_debug_enabled = true; - } - } - - public static function disableQueryDebug() - { - $db = Eloquent::DB(); - - if ($db) { - // remove all query executed event handlers - $db->getEventDispatcher()->flush('Illuminate\Database\Events\QueryExecuted'); - } - } - - public static function enableCliDebugOutput() - { - if (self::isBooted() && App::runningInConsole()) { - Log::setDefaultDriver('console'); - } - } - - public static function disableCliDebugOutput() - { - if (self::isBooted()) { - Log::setDefaultDriver('stack'); - } - } - /** * Add prefix and strip .php to make the url helper work in non-laravel php scripts * diff --git a/LibreNMS/Util/ModuleTestHelper.php b/LibreNMS/Util/ModuleTestHelper.php index 2477bab870..edceecb35e 100644 --- a/LibreNMS/Util/ModuleTestHelper.php +++ b/LibreNMS/Util/ModuleTestHelper.php @@ -181,21 +181,21 @@ class ModuleTestHelper private function collectOids($device_id) { - global $debug, $vdebug, $device; + global $device; $device = device_by_id_cache($device_id); DeviceCache::setPrimary($device_id); // Run discovery ob_start(); - $save_debug = $debug; - $save_vedbug = $vdebug; - $debug = true; - $vdebug = false; + $save_debug = Debug::isEnabled(); + $save_vedbug = Debug::isEnabled(); + Debug::set(); + Debug::setVerbose(); discover_device($device, $this->parseArgs('discovery')); poll_device($device, $this->parseArgs('poller')); - $debug = $save_debug; - $vdebug = $save_vedbug; + Debug::set($save_debug); + Debug::setVerbose($save_vedbug); $collection_output = ob_get_contents(); ob_end_clean(); @@ -518,7 +518,7 @@ class ModuleTestHelper */ public function generateTestData(Snmpsim $snmpsim, $no_save = false) { - global $device, $debug, $vdebug; + global $device; Config::set('rrd.enable', false); // disable rrd if (! is_file($this->snmprec_file)) { @@ -552,11 +552,11 @@ class ModuleTestHelper $data = []; // array to hold dumped data // Run discovery - $save_debug = $debug; - $save_vedbug = $vdebug; + $save_debug = Debug::isEnabled(); + $save_vedbug = Debug::isVerbose(); if ($this->quiet) { - $debug = true; - $vdebug = true; + Debug::setOnly(); + Debug::setVerbose(); } ob_start(); @@ -564,8 +564,8 @@ class ModuleTestHelper $this->discovery_output = ob_get_contents(); if ($this->quiet) { - $debug = $save_debug; - $vdebug = $save_vedbug; + Debug::setOnly($save_debug); + Debug::setVerbose($save_vedbug); } else { ob_flush(); } @@ -583,8 +583,8 @@ class ModuleTestHelper // Run the poller if ($this->quiet) { - $debug = true; - $vdebug = true; + Debug::setOnly(); + Debug::setVerbose(); } ob_start(); @@ -592,8 +592,8 @@ class ModuleTestHelper $this->poller_output = ob_get_contents(); if ($this->quiet) { - $debug = $save_debug; - $vdebug = $save_vedbug; + Debug::setOnly($save_debug); + Debug::setVerbose($save_vedbug); } else { ob_flush(); } @@ -608,8 +608,7 @@ class ModuleTestHelper // Remove the test device, we don't need the debug from this if ($device['hostname'] == $snmpsim->getIp()) { - global $debug; - $debug = false; + Debug::set(false); delete_device($device['device_id']); } diff --git a/alerts.php b/alerts.php index 272735cbf3..e495d8fb6c 100755 --- a/alerts.php +++ b/alerts.php @@ -28,13 +28,14 @@ */ use LibreNMS\Alert\RunAlerts; +use LibreNMS\Util\Debug; $init_modules = ['alerts', 'laravel']; require __DIR__ . '/includes/init.php'; $options = getopt('d::'); -if (set_debug(isset($options['d']))) { +if (Debug::set(isset($options['d']))) { echo "DEBUG!\n"; } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 31e9d4b70d..1e41087464 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -4,6 +4,7 @@ namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; +use LibreNMS\Util\Debug; use LibreNMS\Util\Version; class Kernel extends ConsoleKernel @@ -63,10 +64,9 @@ class Kernel extends ConsoleKernel // intercept input and check for debug if ($input->hasParameterOption(['-d', '--debug', '-vv', '-vvv'], true)) { if ($input->hasParameterOption(['-vvv'], true)) { - global $vdebug; - $vdebug = true; + Debug::setVerbose(); } - $this->app->booted('set_debug'); + $this->app->booted('\LibreNMS\Util\Debug::set'); } return parent::handle($input, $output); diff --git a/app/Http/Controllers/DeviceController.php b/app/Http/Controllers/DeviceController.php index 90f5725288..001cd2511f 100644 --- a/app/Http/Controllers/DeviceController.php +++ b/app/Http/Controllers/DeviceController.php @@ -11,6 +11,7 @@ use Illuminate\Http\Request; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Auth; use LibreNMS\Config; +use LibreNMS\Util\Debug; use LibreNMS\Util\Graph; use LibreNMS\Util\Url; @@ -110,7 +111,7 @@ class DeviceController extends Controller { ob_start(); $device = $device->toArray(); - set_debug(false); + Debug::set(false); chdir(base_path()); $init_modules = ['web', 'auth']; require base_path('/includes/init.php'); diff --git a/app/Http/Controllers/LegacyController.php b/app/Http/Controllers/LegacyController.php index 6f85d4b5a8..d7b5d5725a 100644 --- a/app/Http/Controllers/LegacyController.php +++ b/app/Http/Controllers/LegacyController.php @@ -8,6 +8,7 @@ use Illuminate\Http\Request; use Illuminate\Support\Arr; use Illuminate\Support\Str; use LibreNMS\Config; +use LibreNMS\Util\Debug; class LegacyController extends Controller { @@ -20,7 +21,7 @@ class LegacyController extends Controller $init_modules = ['web', 'auth']; require base_path('/includes/init.php'); - set_debug(Str::contains($request->path(), 'debug')); + Debug::set(Str::contains($request->path(), 'debug')); ob_start(); // protect against bad plugins that output during start \LibreNMS\Plugins::start(); diff --git a/app/Jobs/PingCheck.php b/app/Jobs/PingCheck.php index 80c3a124d6..3940dd90ac 100644 --- a/app/Jobs/PingCheck.php +++ b/app/Jobs/PingCheck.php @@ -36,6 +36,7 @@ use Illuminate\Support\Collection; use LibreNMS\Alert\AlertRules; use LibreNMS\Config; use LibreNMS\RRD\RrdDefinition; +use LibreNMS\Util\Debug; use Log; use Symfony\Component\Process\Process; @@ -151,8 +152,6 @@ class PingCheck implements ShouldQueue return $this->devices; } - global $vdebug; - /** @var Builder $query */ $query = Device::canPing() ->select(['devices.device_id', 'hostname', 'overwrite_ip', 'status', 'status_reason', 'last_ping', 'last_ping_timetaken', 'max_depth']) @@ -174,7 +173,7 @@ class PingCheck implements ShouldQueue $this->current_tier = 1; $this->current = $this->tiered->get($this->current_tier, collect()); - if ($vdebug) { + if (Debug::isVerbose()) { $this->tiered->each(function (Collection $tier, $index) { echo "Tier $index (" . $tier->count() . '): '; echo $tier->implode('hostname', ', '); @@ -191,8 +190,6 @@ class PingCheck implements ShouldQueue */ private function processTier() { - global $vdebug; - if ($this->current->isNotEmpty()) { return; } @@ -204,7 +201,7 @@ class PingCheck implements ShouldQueue return; } - if ($vdebug) { + if (Debug::isVerbose()) { echo "Out of devices at this tier, moving to tier $this->current_tier\n"; } @@ -227,9 +224,7 @@ class PingCheck implements ShouldQueue */ private function recordData(array $data) { - global $vdebug; - - if ($vdebug) { + if (Debug::isVerbose()) { echo "Attempting to record data for {$data['hostname']}... "; } @@ -238,7 +233,7 @@ class PingCheck implements ShouldQueue // process the data if this is a standalone device or in the current tier if ($device->max_depth === 0 || $this->current->has($device->hostname)) { - if ($vdebug) { + if (Debug::isVerbose()) { echo "Success\n"; } @@ -269,7 +264,7 @@ class PingCheck implements ShouldQueue $this->complete($device->hostname); d_echo("Recorded data for $device->hostname (tier $device->max_depth)\n"); } else { - if ($vdebug) { + if (Debug::isVerbose()) { echo "Deferred\n"; } diff --git a/app/Providers/LegacyUserProvider.php b/app/Providers/LegacyUserProvider.php index 5ce97e74d8..4ffa367ccf 100644 --- a/app/Providers/LegacyUserProvider.php +++ b/app/Providers/LegacyUserProvider.php @@ -30,6 +30,7 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use LibreNMS\Authentication\LegacyAuth; use LibreNMS\Exceptions\AuthenticationException; +use LibreNMS\Util\Debug; use Log; use Request; use Session; @@ -131,10 +132,8 @@ class LegacyUserProvider implements UserProvider return true; } catch (AuthenticationException $ae) { - global $debug; - $auth_message = $ae->getMessage(); - if ($debug) { + if (Debug::isEnabled()) { $auth_message .= '
' . $ae->getFile() . ': ' . $ae->getLine(); } \Toastr::error($auth_message); diff --git a/check-services.php b/check-services.php index 585c277425..48ab904d84 100755 --- a/check-services.php +++ b/check-services.php @@ -14,12 +14,13 @@ */ use LibreNMS\Data\Store\Datastore; +use LibreNMS\Util\Debug; $init_modules = []; require __DIR__ . '/includes/init.php'; $options = getopt('drfpgh:'); -if (set_debug(isset($options['d']))) { +if (Debug::set(isset($options['d']))) { echo "DEBUG!\n"; } diff --git a/config/logging.php b/config/logging.php index 6d391592f9..0dcc9edada 100644 --- a/config/logging.php +++ b/config/logging.php @@ -51,7 +51,7 @@ return [ 'console' => [ 'driver' => 'stack', - 'channels' => ['single', 'stderr'], + 'channels' => ['single', 'stdout'], 'ignore_exceptions' => false, ], diff --git a/daily.php b/daily.php index cfc2e7bedc..09c2fe6c99 100644 --- a/daily.php +++ b/daily.php @@ -11,6 +11,7 @@ use App\Models\DeviceGroup; use Illuminate\Database\Eloquent\Collection; use LibreNMS\Alert\AlertDB; use LibreNMS\Config; +use LibreNMS\Util\Debug; use LibreNMS\Validations\Php; $init_modules = ['alerts']; @@ -21,7 +22,7 @@ $options = getopt('df:o:t:r:'); if (isset($options['d'])) { echo "DEBUG\n"; - $debug = true; + Debug::set(); } if ($options['f'] === 'update') { diff --git a/discovery.php b/discovery.php index b6e8141d25..de4222ceea 100755 --- a/discovery.php +++ b/discovery.php @@ -8,6 +8,9 @@ * * @copyright (C) 2006 - 2012 Adam Armstrong */ + +use LibreNMS\Util\Debug; + $init_modules = ['discovery']; require __DIR__ . '/includes/init.php'; @@ -59,7 +62,7 @@ if (isset($options['i']) && $options['i'] && isset($options['n'])) { $doing = $options['n'] . '/' . $options['i']; } -if (set_debug(isset($options['d'])) || isset($options['v'])) { +if (Debug::set(isset($options['d']), false) || isset($options['v'])) { $versions = version_info(); echo <<. */ +use LibreNMS\Util\Debug; + $init_modules = ['web', 'auth']; require realpath(__DIR__ . '/..') . '/includes/init.php'; @@ -22,7 +24,7 @@ if (! Auth::check()) { exit('Unauthorized'); } -set_debug($_REQUEST['debug']); +Debug::set($_REQUEST['debug']); /** * Levenshtein Sort diff --git a/html/ajax_output.php b/html/ajax_output.php index 705d697c7f..ae10961617 100644 --- a/html/ajax_output.php +++ b/html/ajax_output.php @@ -12,6 +12,8 @@ * the source code distribution for details. */ +use LibreNMS\Util\Debug; + session_start(); session_write_close(); if (isset($_SESSION['stage']) && $_SESSION['stage'] == 2) { @@ -26,7 +28,7 @@ if (isset($_SESSION['stage']) && $_SESSION['stage'] == 2) { } } -set_debug($_REQUEST['debug']); +Debug::set($_REQUEST['debug']); $id = basename($_REQUEST['id']); if ($id && is_file(\LibreNMS\Config::get('install_dir') . "/includes/html/output/$id.inc.php")) { diff --git a/html/ajax_search.php b/html/ajax_search.php index c7a8b6da14..94445c589a 100644 --- a/html/ajax_search.php +++ b/html/ajax_search.php @@ -1,5 +1,7 @@ '; printf('Runtime %.3fs', microtime(true) - $start); echo '
'; diff --git a/html/network-map.php b/html/network-map.php index 18f4a9bc05..4d98044176 100644 --- a/html/network-map.php +++ b/html/network-map.php @@ -9,6 +9,7 @@ */ use LibreNMS\Config; +use LibreNMS\Util\Debug; $links = 1; @@ -21,7 +22,7 @@ if (! Auth::check()) { $options = getopt('d::'); -if (set_debug(isset($options['d']))) { +if (Debug::set(isset($options['d']), false)) { echo "DEBUG!\n"; } diff --git a/html/pdf.php b/html/pdf.php index 94ed8c7573..b510cdc45f 100644 --- a/html/pdf.php +++ b/html/pdf.php @@ -13,6 +13,7 @@ */ use LibreNMS\Config; +use LibreNMS\Util\Debug; $init_modules = ['web', 'auth']; require realpath(__DIR__ . '/..') . '/includes/init.php'; @@ -21,7 +22,7 @@ if (! Auth::check()) { exit('Unauthorized'); } -set_debug(strpos($_SERVER['PATH_INFO'], 'debug')); +Debug::set(strpos($_SERVER['PATH_INFO'], 'debug')); $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); diff --git a/includes/common.php b/includes/common.php index c169cd74f8..edef9abfa3 100644 --- a/includes/common.php +++ b/includes/common.php @@ -19,9 +19,9 @@ use LibreNMS\Config; use LibreNMS\Enum\Alert; use LibreNMS\Exceptions\InvalidIpException; +use LibreNMS\Util\Debug; use LibreNMS\Util\Git; use LibreNMS\Util\IP; -use LibreNMS\Util\Laravel; use Symfony\Component\Process\Process; function generate_priority_status($priority) @@ -67,14 +67,12 @@ function graylog_severity_label($severity) */ function external_exec($command) { - global $debug, $vdebug; - $device = DeviceCache::getPrimary(); $proc = new Process($command); $proc->setTimeout(Config::get('snmp.exec_timeout', 1200)); - if ($debug && ! $vdebug) { + if (Debug::isEnabled() && ! Debug::isVerbose()) { $patterns = [ '/-c\' \'[\S]+\'/', '/-u\' \'[\S]+\'/', @@ -98,7 +96,7 @@ function external_exec($command) $debug_command = preg_replace($patterns, $replacements, $proc->getCommandLine()); c_echo('SNMP[%c' . $debug_command . "%n]\n"); - } elseif ($vdebug) { + } elseif (Debug::isVerbose()) { c_echo('SNMP[%c' . $proc->getCommandLine() . "%n]\n"); } @@ -115,11 +113,11 @@ function external_exec($command) d_echo($proc->getErrorOutput()); } - if ($debug && ! $vdebug) { + if (Debug::isEnabled() && ! Debug::isVerbose()) { $ip_regex = '/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/'; $debug_output = preg_replace($ip_regex, '*', $output); d_echo($debug_output . PHP_EOL); - } elseif ($vdebug) { + } elseif (Debug::isVerbose()) { d_echo($output . PHP_EOL); } d_echo($proc->getErrorOutput()); @@ -427,27 +425,6 @@ function del_dev_attrib($device, $attrib_type) return DeviceCache::get((int) $device['device_id'])->forgetAttrib($attrib_type); } -/* - * convenience function - please use this instead of 'if ($debug) { echo ...; }' - */ -if (! function_exists('d_echo')) { - //TODO remove this after installs have updated, leaving it for for transition - function d_echo($text, $no_debug_text = null) - { - global $debug; - - if (Laravel::isBooted()) { - \Log::debug(is_string($text) ? rtrim($text) : $text); - } elseif ($debug) { - print_r($text); - } - - if (! $debug && $no_debug_text) { - echo "$no_debug_text"; - } - } -} - /** * Output using console color if possible * https://github.com/pear/Console_Color2/blob/master/examples/documentation diff --git a/includes/discovery/cisco-vrf-lite.inc.php b/includes/discovery/cisco-vrf-lite.inc.php index 2b0b3a79ab..6c935cd4fd 100644 --- a/includes/discovery/cisco-vrf-lite.inc.php +++ b/includes/discovery/cisco-vrf-lite.inc.php @@ -14,8 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -global $debug; - // This one only will work with the CISCO-CONTEXT-MAPPING-MIB V2 of cisco use LibreNMS\Config; @@ -62,7 +60,7 @@ if (Config::get('enable_vrf_lite_cisco')) { unset($listIntance); foreach ((array) $tableVrf as $context => $vrf) { - if ($debug) { + if (\LibreNMS\Util\Debug::isEnabled()) { echo "\n[DEBUG]\nRelation:t" . $context . 't' . $vrf['intance'] . 't' . $vrf['vrf'] . "\n[/DEBUG]\n"; } diff --git a/includes/functions.php b/includes/functions.php index f24a5249fd..ccf3bb0095 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -19,49 +19,12 @@ use LibreNMS\Exceptions\InvalidPortAssocModeException; use LibreNMS\Exceptions\SnmpVersionUnsupportedException; use LibreNMS\Fping; use LibreNMS\Modules\Core; +use LibreNMS\Util\Debug; use LibreNMS\Util\IPv4; use LibreNMS\Util\IPv6; use PHPMailer\PHPMailer\PHPMailer; use Symfony\Component\Process\Process; -if (! function_exists('set_debug')) { - /** - * Set debugging output - * - * @param bool $state If debug is enabled or not - * @param bool $silence When not debugging, silence every php error - * @return bool - */ - function set_debug($state = true, $silence = false) - { - global $debug; - - $debug = $state; // set to global - - restore_error_handler(); // disable Laravel error handler - - if (isset($debug) && $debug) { - ini_set('display_errors', 1); - ini_set('display_startup_errors', 1); - ini_set('log_errors', 0); - error_reporting(E_ALL & ~E_NOTICE); - - \LibreNMS\Util\Laravel::enableCliDebugOutput(); - \LibreNMS\Util\Laravel::enableQueryDebug(); - } else { - ini_set('display_errors', 0); - ini_set('display_startup_errors', 0); - ini_set('log_errors', 1); - error_reporting($silence ? 0 : E_ERROR); - - \LibreNMS\Util\Laravel::disableCliDebugOutput(); - \LibreNMS\Util\Laravel::disableQueryDebug(); - } - - return $debug; - } -}//end set_debug() - function array_sort_by_column($array, $on, $order = SORT_ASC) { $new_array = []; @@ -333,8 +296,6 @@ function device_discovery_trigger($id) function delete_device($id) { - global $debug; - if (isCli() === false) { ignore_user_abort(true); set_time_limit(0); @@ -377,7 +338,7 @@ function delete_device($id) foreach (dbFetch('SELECT TABLE_NAME FROM information_schema.columns WHERE table_schema = ? AND column_name = ?', [$db_name, $field]) as $table) { $table = $table['TABLE_NAME']; $entries = (int) dbDelete($table, "`$field` = ?", [$id]); - if ($entries > 0 && $debug === true) { + if ($entries > 0 && Debug::isEnabled()) { $ret .= "$field@$table = #$entries\n"; } } diff --git a/includes/helpers.php b/includes/helpers.php index b14f30869d..2d01431025 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -22,11 +22,12 @@ * @author Tony Murray */ +use LibreNMS\Util\Debug; use LibreNMS\Util\Laravel; if (! function_exists('d_echo')) { /** - * Legacy convenience function - please use this instead of 'if ($debug) { echo ...; }' + * Legacy convenience function - please use this instead of 'if (Debug::isEnabled()) { echo ...; }' * Use Log directly in pure Laravel code! * * @param string|array $text The error message or array to print @@ -34,58 +35,18 @@ if (! function_exists('d_echo')) { */ function d_echo($text, $no_debug_text = null) { - global $debug; - if (Laravel::isBooted()) { \Log::debug(is_string($text) ? rtrim($text) : $text); - } elseif ($debug) { + } elseif (Debug::isEnabled()) { print_r($text); } - if (! $debug && $no_debug_text) { + if (! Debug::isEnabled() && $no_debug_text) { echo "$no_debug_text"; } } } -if (! function_exists('set_debug')) { - /** - * Set debugging output - * - * @param bool $state If debug is enabled or not - * @param bool $silence When not debugging, silence every php error - * @return bool - */ - function set_debug($state = true, $silence = false) - { - global $debug; - - $debug = $state; // set to global - - restore_error_handler(); // disable Laravel error handler - - if ($debug) { - ini_set('display_errors', 1); - ini_set('display_startup_errors', 1); - ini_set('log_errors', 0); - error_reporting(E_ALL & ~E_NOTICE); - - \LibreNMS\Util\Laravel::enableCliDebugOutput(); - \LibreNMS\Util\Laravel::enableQueryDebug(); - } else { - ini_set('display_errors', 0); - ini_set('display_startup_errors', 0); - ini_set('log_errors', 1); - error_reporting($silence ? 0 : E_ERROR); - - \LibreNMS\Util\Laravel::disableCliDebugOutput(); - \LibreNMS\Util\Laravel::disableQueryDebug(); - } - - return $debug; - } -} - if (! function_exists('array_pairs')) { /** * Get all consecutive pairs of values in an array. diff --git a/includes/html/functions.inc.php b/includes/html/functions.inc.php index 460dd6283d..7c755886af 100644 --- a/includes/html/functions.inc.php +++ b/includes/html/functions.inc.php @@ -11,6 +11,7 @@ */ use LibreNMS\Config; +use LibreNMS\Util\Debug; use LibreNMS\Util\Number; use LibreNMS\Util\Rewrite; @@ -462,9 +463,9 @@ function generate_port_image($args) */ function graph_error($text, $color = [128, 0, 0]) { - global $vars, $debug; + global $vars; - if (! $debug) { + if (! Debug::isEnabled()) { set_image_type(); } diff --git a/includes/html/graphs/graph.inc.php b/includes/html/graphs/graph.inc.php index ad8d5911c8..3ca8e51422 100644 --- a/includes/html/graphs/graph.inc.php +++ b/includes/html/graphs/graph.inc.php @@ -81,7 +81,7 @@ if ($error_msg) { Rrd::graph($graphfile, $rrd_options); d_echo($rrd_cmd); if (is_file($graphfile)) { - if (! $debug) { + if (! \LibreNMS\Util\Debug::isEnabled()) { set_image_type(); if ($output === 'base64') { $imagedata = file_get_contents($graphfile); diff --git a/includes/html/graphs/macaccounting/auth.inc.php b/includes/html/graphs/macaccounting/auth.inc.php index fadadd11e4..21ad028f09 100644 --- a/includes/html/graphs/macaccounting/auth.inc.php +++ b/includes/html/graphs/macaccounting/auth.inc.php @@ -3,7 +3,7 @@ if (is_numeric($vars['id'])) { $acc = dbFetchRow('SELECT * FROM `mac_accounting` AS M, `ports` AS I, `devices` AS D WHERE M.ma_id = ? AND I.port_id = M.port_id AND I.device_id = D.device_id', [$vars['id']]); - if ($debug) { + if (\LibreNMS\Util\Debug::isEnabled()) { echo '
';
         print_r($acc);
         echo '
'; diff --git a/includes/init.php b/includes/init.php index 1d5d22068f..92f9e26e60 100644 --- a/includes/init.php +++ b/includes/init.php @@ -28,6 +28,7 @@ use LibreNMS\Authentication\LegacyAuth; use LibreNMS\Config; +use LibreNMS\Util\Debug; global $vars, $console_color; @@ -90,7 +91,7 @@ if (module_selected('web', $init_modules)) { \LibreNMS\Util\Laravel::bootCli(); } -set_debug(false); // disable debug initially (hides legacy errors too) +Debug::set(false); // disable debug initially (hides legacy errors too) if (! module_selected('nodb', $init_modules)) { \LibreNMS\DB\Eloquent::boot(); diff --git a/includes/polling/ports.inc.php b/includes/polling/ports.inc.php index 08cb9c850b..6112091422 100644 --- a/includes/polling/ports.inc.php +++ b/includes/polling/ports.inc.php @@ -4,6 +4,7 @@ use Illuminate\Support\Str; use LibreNMS\Config; use LibreNMS\RRD\RrdDefinition; +use LibreNMS\Util\Debug; use LibreNMS\Util\Number; $data_oids = [ @@ -664,7 +665,7 @@ foreach ($ports as $port) { if ($port[$oid] != $this_port[$oid] && ! isset($this_port[$oid])) { $port['update'][$oid] = ['NULL']; log_event($oid . ': ' . $port[$oid] . ' -> NULL', $device, 'interface', 4, $port['port_id']); - if ($debug) { + if (Debug::isEnabled()) { d_echo($oid . ': ' . $port[$oid] . ' -> NULL '); } else { echo $oid . ' '; @@ -692,7 +693,7 @@ foreach ($ports as $port) { } log_event($oid . ': ' . $port[$oid] . ' -> ' . $this_port[$oid], $device, 'interface', 3, $port['port_id']); - if ($debug) { + if (Debug::isEnabled()) { d_echo($oid . ': ' . $port[$oid] . ' -> ' . $this_port[$oid] . ' '); } else { echo $oid . ' '; diff --git a/includes/snmp.inc.php b/includes/snmp.inc.php index 979b09b967..58c2907952 100644 --- a/includes/snmp.inc.php +++ b/includes/snmp.inc.php @@ -18,6 +18,7 @@ use App\Models\Device; use Illuminate\Support\Str; use LibreNMS\Config; +use LibreNMS\Util\Debug; use Symfony\Component\Process\Exception\ProcessTimedOutException; function string_to_oid($string) @@ -707,8 +708,6 @@ function snmpwalk_cache_twopart_oid($device, $oid, $array, $mib = 0, $mibdir = n function snmpwalk_cache_threepart_oid($device, $oid, $array, $mib = 0) { - global $debug; - $cmd = gen_snmpwalk_cmd($device, $oid, '-OQUs', $mib); $data = trim(external_exec($cmd)); @@ -719,7 +718,7 @@ function snmpwalk_cache_threepart_oid($device, $oid, $array, $mib = 0) $value = str_replace('"', '', $value); [$oid, $first, $second, $third] = explode('.', $oid); - if ($debug) { + if (Debug::isEnabled()) { echo "$entry || $oid || $first || $second || $third\n"; } diff --git a/ping.php b/ping.php index 6d8b1b87c5..4d9d4ac0f0 100755 --- a/ping.php +++ b/ping.php @@ -3,6 +3,7 @@ use App\Jobs\PingCheck; use LibreNMS\Data\Store\Datastore; +use LibreNMS\Util\Debug; $init_modules = ['alerts', 'laravel', 'nodb']; require __DIR__ . '/includes/init.php'; @@ -21,12 +22,8 @@ END; exit; } -set_debug(isset($options['d'])); - -if (isset($options['v'])) { - global $vdebug; - $vdebug = true; -} +Debug::set(isset($options['d'])); +Debug::setVerbose(isset($options['v'])); Datastore::init($options); diff --git a/poll-billing.php b/poll-billing.php index 026cddd632..c9946cdb13 100755 --- a/poll-billing.php +++ b/poll-billing.php @@ -12,6 +12,7 @@ */ use LibreNMS\Data\Store\Datastore; +use LibreNMS\Util\Debug; $init_modules = []; require __DIR__ . '/includes/init.php'; @@ -23,7 +24,7 @@ if (isset($argv[1]) && is_numeric($argv[1])) { $options = getopt('db:'); } -set_debug(isset($options['d'])); +Debug::set(isset($options['d'])); Datastore::init(); // Wait for schema update, as running during update can break update diff --git a/poller.php b/poller.php index 6ce44017d8..82346cfd9d 100755 --- a/poller.php +++ b/poller.php @@ -27,6 +27,7 @@ use LibreNMS\Alert\AlertRules; use LibreNMS\Config; use LibreNMS\Data\Store\Datastore; +use LibreNMS\Util\Debug; $init_modules = ['polling', 'alerts', 'laravel']; require __DIR__ . '/includes/init.php'; @@ -94,7 +95,7 @@ if (empty($where)) { exit; } -if (set_debug(isset($options['d'])) || isset($options['v'])) { +if (Debug::set(isset($options['d']), false) || isset($options['v'])) { $versions = version_info(); echo <<getOutput()->getVerbosity()) >= 128) { - set_debug(); + Debug::set(); if ($verbosity >= 256) { global $verbose; $verbose = true; diff --git a/scripts/auth_test.php b/scripts/auth_test.php index 8eccf5b3e6..4817ce9e73 100755 --- a/scripts/auth_test.php +++ b/scripts/auth_test.php @@ -4,6 +4,7 @@ use Illuminate\Support\Str; use LibreNMS\Authentication\LegacyAuth; use LibreNMS\Config; +use LibreNMS\Util\Debug; $options = getopt('u:rldvh'); if (isset($options['h']) || (! isset($options['l']) && ! isset($options['u']))) { @@ -17,7 +18,7 @@ if (isset($options['h']) || (! isset($options['l']) && ! isset($options['u']))) } if (isset($options['d'])) { - $debug = true; + Debug::set(); } $init_modules = []; diff --git a/scripts/collect-port-polling.php b/scripts/collect-port-polling.php index a227565a1c..00808cbe35 100755 --- a/scripts/collect-port-polling.php +++ b/scripts/collect-port-polling.php @@ -3,6 +3,7 @@ use Illuminate\Support\Str; use LibreNMS\Config; +use LibreNMS\Util\Debug; $install_dir = realpath(__DIR__ . '/..'); chdir($install_dir); @@ -23,7 +24,7 @@ function print_help() } if (isset($options['d'])) { - $debug = true; + Debug::set(); } if (isset($options['help'])) { @@ -61,7 +62,7 @@ echo 'Full Polling: '; Config::set('polling.selected_ports', false); foreach ($devices as $index => $device) { echo $device['device_id'] . ' '; - if (! $debug) { + if (! Debug::isEnabled()) { ob_start(); } @@ -76,7 +77,7 @@ Config::set('polling.selected_ports', true); echo 'Selective Polling: '; foreach ($devices as $index => $device) { echo $device['device_id'] . ' '; - if (! $debug) { + if (! Debug::isEnabled()) { ob_start(); } diff --git a/scripts/collect-snmp-data.php b/scripts/collect-snmp-data.php index f0e924c60e..4efc661f72 100755 --- a/scripts/collect-snmp-data.php +++ b/scripts/collect-snmp-data.php @@ -3,6 +3,7 @@ use Illuminate\Support\Str; use LibreNMS\Exceptions\InvalidModuleException; +use LibreNMS\Util\Debug; use LibreNMS\Util\ModuleTestHelper; use LibreNMS\Util\Snmpsim; @@ -96,7 +97,7 @@ Examples: exit; } -$debug = (isset($options['d']) || isset($options['debug'])); +Debug::set(isset($options['d']) || isset($options['debug'])); if (isset($options['m'])) { $modules_input = $options['m']; diff --git a/scripts/new-os.php b/scripts/new-os.php index 8f58076e38..bbc28c6926 100755 --- a/scripts/new-os.php +++ b/scripts/new-os.php @@ -3,6 +3,7 @@ use LibreNMS\Config; use LibreNMS\Modules\Core; +use LibreNMS\Util\Debug; $init_modules = ['']; require __DIR__ . '/../includes/init.php'; @@ -12,7 +13,7 @@ $options = getopt('h:o:t:v:d::'); if ($options['h'] && $options['o'] && $options['t'] && $options['v']) { $type = $options['t']; $vendor = $options['v']; - set_debug(isset($options['d'])); + Debug::set(isset($options['d'])); $device_id = ctype_digit($options['h']) ? $options['h'] : getidbyname($options['h']); $device = device_by_id_cache($device_id); diff --git a/scripts/save-test-data.php b/scripts/save-test-data.php index 481c3ce7c5..9ab32cc686 100755 --- a/scripts/save-test-data.php +++ b/scripts/save-test-data.php @@ -2,6 +2,7 @@ genDevice($community)); $output = ob_get_contents(); diff --git a/tests/OSModulesTest.php b/tests/OSModulesTest.php index 0beffeb705..a4943d9713 100644 --- a/tests/OSModulesTest.php +++ b/tests/OSModulesTest.php @@ -30,6 +30,7 @@ use LibreNMS\Config; use LibreNMS\Exceptions\FileNotFoundException; use LibreNMS\Exceptions\InvalidModuleException; use LibreNMS\Fping; +use LibreNMS\Util\Debug; use LibreNMS\Util\ModuleTestHelper; class OSModulesTest extends DBTestCase @@ -89,7 +90,7 @@ class OSModulesTest extends DBTestCase $this->stubClasses(); try { - set_debug(false); // avoid all undefined index errors in the legacy code + Debug::set(false); // avoid all undefined index errors in the legacy code $helper = new ModuleTestHelper($modules, $os, $variant); $helper->setQuiet(); @@ -107,7 +108,7 @@ class OSModulesTest extends DBTestCase } // output all discovery and poller output if debug mode is enabled for phpunit - $debug = in_array('--debug', $_SERVER['argv'], true); + $phpunit_debug = in_array('--debug', $_SERVER['argv'], true); foreach ($modules as $module) { $expected = $expected_data[$module]['discovery'] ?? []; @@ -117,7 +118,7 @@ class OSModulesTest extends DBTestCase $actual, "OS $os: Discovered $module data does not match that found in $filename\n" . print_r(array_diff($expected, $actual), true) - . $helper->getDiscoveryOutput($debug ? null : $module) + . $helper->getDiscoveryOutput($phpunit_debug ? null : $module) . "\nOS $os: Discovered $module data does not match that found in $filename" ); @@ -137,7 +138,7 @@ class OSModulesTest extends DBTestCase $actual, "OS $os: Polled $module data does not match that found in $filename\n" . print_r(array_diff($expected, $actual), true) - . $helper->getPollerOutput($debug ? null : $module) + . $helper->getPollerOutput($phpunit_debug ? null : $module) . "\nOS $os: Polled $module data does not match that found in $filename" ); }