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
This commit is contained in:
Tony Murray 2021-04-29 22:42:18 -05:00 committed by GitHub
parent 2cdd762656
commit 61c89794e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 287 additions and 278 deletions

View File

@ -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);
}

View File

@ -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));

View File

@ -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];

137
LibreNMS/Util/Debug.php Normal file
View File

@ -0,0 +1,137 @@
<?php
/*
* Debug.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 2021 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
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;
}
}
}

View File

@ -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
*

View File

@ -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']);
}

View File

@ -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";
}

View File

@ -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);

View File

@ -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');

View File

@ -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();

View File

@ -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";
}

View File

@ -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 .= '<br /> ' . $ae->getFile() . ': ' . $ae->getLine();
}
\Toastr::error($auth_message);

View File

@ -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";
}

View File

@ -51,7 +51,7 @@ return [
'console' => [
'driver' => 'stack',
'channels' => ['single', 'stderr'],
'channels' => ['single', 'stdout'],
'ignore_exceptions' => false,
],

View File

@ -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') {

View File

@ -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 <<<EOH
===================================
@ -75,9 +78,7 @@ SNMP: {$versions['netsnmp_ver']}
EOH;
echo "DEBUG!\n";
if (isset($options['v'])) {
$vdebug = true;
}
Debug::setVerbose(isset($options['v']));
\LibreNMS\Util\OS::updateCache(true); // Force update of OS Cache
}

View File

@ -12,6 +12,8 @@
* the source code distribution for details.
*/
use LibreNMS\Util\Debug;
$init_modules = ['web', 'auth', 'alerts'];
require realpath(__DIR__ . '/..') . '/includes/init.php';
@ -19,7 +21,7 @@ if (! Auth::check()) {
exit('Unauthorized');
}
set_debug(isset($_REQUEST['debug']) ? $_REQUEST['debug'] : false);
Debug::set(isset($_REQUEST['debug']) ? $_REQUEST['debug'] : false);
if (preg_match('/^[a-zA-Z0-9\-]+$/', $_POST['type']) == 1) {
if (file_exists('includes/html/forms/' . $_POST['type'] . '.inc.php')) {

View File

@ -13,6 +13,8 @@
* the source code distribution for details.
*/
use LibreNMS\Util\Debug;
$init_modules = ['web', 'auth'];
require realpath(__DIR__ . '/..') . '/includes/init.php';
@ -20,7 +22,7 @@ if (! Auth::check()) {
exit('Unauthorized');
}
set_debug($_REQUEST['debug']);
Debug::set($_REQUEST['debug']);
$type = basename($_REQUEST['type']);

View File

@ -7,6 +7,9 @@
*
* @copyright (C) 2006 - 2012 Adam Armstrong
*/
use LibreNMS\Util\Debug;
$init_modules = ['web', 'auth'];
require realpath(__DIR__ . '/..') . '/includes/init.php';
@ -14,7 +17,7 @@ if (! Auth::check()) {
exit('Unauthorized');
}
set_debug($_REQUEST['debug']);
Debug::set($_REQUEST['debug']);
if (is_numeric($_GET['device_id'])) {
foreach (dbFetch('SELECT * FROM ports WHERE device_id = ?', [$_GET['device_id']]) as $interface) {

View File

@ -15,6 +15,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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

View File

@ -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")) {

View File

@ -1,5 +1,7 @@
<?php
use LibreNMS\Util\Debug;
$init_modules = ['web', 'auth'];
require realpath(__DIR__ . '/..') . '/includes/init.php';
@ -7,7 +9,7 @@ if (! Auth::check()) {
exit('Unauthorized');
}
set_debug($_REQUEST['debug']);
Debug::set($_REQUEST['debug']);
$device = [];
$ports = [];

View File

@ -12,6 +12,8 @@
* the source code distribution for details.
*/
use LibreNMS\Util\Debug;
$init_modules = ['web', 'auth'];
require realpath(__DIR__ . '/..') . '/includes/init.php';
@ -19,7 +21,7 @@ if (! Auth::check()) {
exit('Unauthorized');
}
set_debug($_REQUEST['debug']);
Debug::set($_REQUEST['debug']);
$current = $_REQUEST['current'];
settype($current, 'integer');

View File

@ -13,6 +13,7 @@
*/
use LibreNMS\Config;
use LibreNMS\Util\Debug;
$init_modules = ['web', 'auth'];
require realpath(__DIR__ . '/..') . '/includes/init.php';
@ -21,11 +22,11 @@ if (! Auth::check()) {
exit('Unauthorized');
}
set_debug(strpos($_SERVER['PATH_INFO'], 'debug'));
Debug::set(strpos($_SERVER['PATH_INFO'], 'debug'));
$report = basename($vars['report']);
if ($report && file_exists(Config::get('install_dir') . "/includes/html/reports/$report.csv.inc.php")) {
if ($debug === false) {
if (! Debug::isEnabled()) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $report . '-' . date('Ymd') . '.csv"');
}

View File

@ -8,6 +8,7 @@
*/
use LibreNMS\Data\Store\Datastore;
use LibreNMS\Util\Debug;
$start = microtime(true);
@ -22,13 +23,13 @@ if (! Auth::check()) {
}
}
set_debug(isset($_GET['debug']));
Debug::set(isset($_GET['debug']));
require \LibreNMS\Config::get('install_dir') . '/includes/html/graphs/graph.inc.php';
Datastore::terminate();
if ($debug) {
if (Debug::isEnabled()) {
echo '<br />';
printf('Runtime %.3fs', microtime(true) - $start);
echo '<br />';

View File

@ -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";
}

View File

@ -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);

View File

@ -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

View File

@ -14,8 +14,6 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. */
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";
}

View File

@ -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";
}
}

View File

@ -22,11 +22,12 @@
* @author Tony Murray <murraytony@gmail.com>
*/
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.

View File

@ -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();
}

View File

@ -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);

View File

@ -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 '<pre>';
print_r($acc);
echo '</pre>';

View File

@ -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();

View File

@ -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 . ' ';

View File

@ -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";
}

View File

@ -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);

View File

@ -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

View File

@ -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 <<<EOH
===================================
@ -111,14 +112,13 @@ EOH;
echo "DEBUG!\n";
if (isset($options['v'])) {
$vdebug = true;
Debug::setVerbose();
}
\LibreNMS\Util\OS::updateCache(true); // Force update of OS Cache
}
// If we've specified modules with -m, use them
$module_override = parse_modules('poller', $options);
set_debug($debug);
$datastore = Datastore::init($options);

View File

@ -13,6 +13,7 @@
use App\Models\Device;
use LibreNMS\Exceptions\HostUnreachableException;
use LibreNMS\Util\Debug;
use Symfony\Component\Process\Process;
Artisan::command('device:rename
@ -107,7 +108,7 @@ Artisan::command('device:add
include base_path('includes/init.php');
if (($verbosity = $this->getOutput()->getVerbosity()) >= 128) {
set_debug();
Debug::set();
if ($verbosity >= 256) {
global $verbose;
$verbose = true;

View File

@ -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 = [];

View File

@ -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();
}

View File

@ -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'];

View File

@ -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);

View File

@ -2,6 +2,7 @@
<?php
use LibreNMS\Exceptions\InvalidModuleException;
use LibreNMS\Util\Debug;
use LibreNMS\Util\ModuleTestHelper;
use LibreNMS\Util\Snmpsim;
@ -27,8 +28,9 @@ $options = getopt(
$init_modules = ['discovery', 'polling'];
require $install_dir . '/includes/init.php';
$debug = (isset($options['d']) || isset($options['debug']));
$vdebug = $debug;
Debug::setVerbose(
Debug::set(isset($options['d']) || isset($options['debug']))
);
if (isset($options['snmpsim'])) {
$snmpsim = new Snmpsim();

View File

@ -2,6 +2,7 @@
<?php
use LibreNMS\Alert\RunAlerts;
use LibreNMS\Util\Debug;
$init_modules = ['alerts', 'laravel'];
require __DIR__ . '/../includes/init.php';
@ -9,7 +10,7 @@ require __DIR__ . '/../includes/init.php';
$options = getopt('t:h:r:p:s:d::');
if (isset($options['r']) && isset($options['h'])) {
set_debug(isset($options['d']));
Debug::set(isset($options['d']));
$runAlerts = new RunAlerts();
$rule_id = (int) $options['r'];
@ -33,7 +34,7 @@ Usage:
-r Is the Rule ID.
-h Is the device ID or hostname
-d Debug
Example:
./scripts/test-alert.php -r 4 -d -h localhost

View File

@ -7,11 +7,12 @@ require __DIR__ . '/../includes/init.php';
use LibreNMS\Alert\AlertData;
use LibreNMS\Alert\RunAlerts;
use LibreNMS\Alert\Template;
use LibreNMS\Util\Debug;
$options = getopt('t:h:r:p:s:d::');
if (isset($options['t']) && isset($options['h']) && isset($options['r'])) {
set_debug(isset($options['d']));
Debug::set(isset($options['d']));
$runAlerts = new RunAlerts();
$template_id = $options['t'];

View File

@ -10,12 +10,15 @@
* @copyright (C) 2018 LibreNMS
* Adapted from old snmptrap.php handler
*/
use LibreNMS\Util\Debug;
$init_modules = [];
require __DIR__ . '/includes/init.php';
$options = getopt('d::');
if (set_debug(isset($options['d']))) {
if (Debug::set(isset($options['d']))) {
echo "DEBUG!\n";
}

View File

@ -27,6 +27,7 @@ namespace LibreNMS\Tests;
use Illuminate\Support\Str;
use LibreNMS\Config;
use LibreNMS\Modules\Core;
use LibreNMS\Util\Debug;
use LibreNMS\Util\OS;
class OSDiscoveryTest extends TestCase
@ -102,9 +103,8 @@ class OSDiscoveryTest extends TestCase
private function checkOS($expected_os, $filename = null)
{
$community = $filename ?: $expected_os;
global $debug, $vdebug;
$debug = true;
$vdebug = true;
Debug::set();
Debug::setVerbose();
ob_start();
$os = Core::detectOS($this->genDevice($community));
$output = ob_get_contents();

View File

@ -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"
);
}