Skip to content

Commit fc5e69f

Browse files
lafCopilot
andauthored
Refactor some general scripts to stop using dbFacile (librenms#18542)
* Refactor some general scripts to stop using dbFacile * CI fix * Update check-services.php Co-authored-by: Copilot <[email protected]> * Update scripts/collect-port-polling.php Co-authored-by: Copilot <[email protected]> * Update daily.php Co-authored-by: Copilot <[email protected]> * Some updates to queries * CI fix * Update includes/services.inc.php Co-authored-by: Copilot <[email protected]> * Updated to use Eloquent * Updates from feedback * CI fixes --------- Co-authored-by: Copilot <[email protected]>
1 parent 4d05f06 commit fc5e69f

File tree

7 files changed

+47
-207
lines changed

7 files changed

+47
-207
lines changed

check-services.php

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
*/
1515

1616
use App\Facades\LibrenmsConfig;
17+
use App\Models\Device;
1718
use LibreNMS\Data\Store\Datastore;
1819
use LibreNMS\Enum\Severity;
1920
use LibreNMS\Util\Debug;
@@ -33,19 +34,19 @@
3334
echo "Starting service polling run:\n\n";
3435
$polled_services = 0;
3536

36-
$where = '';
37-
$params = [];
37+
$query = Device::query()->select('devices.*', 'services.*')
38+
->join('services', 'devices.device_id', '=', 'services.device_id')
39+
->where('devices.disabled', 0)
40+
->orderBy('devices.device_id', 'DESC');
41+
3842
if (isset($options['h'])) {
3943
if (is_numeric($options['h'])) {
40-
$where = 'AND `S`.`device_id` = ?';
41-
$params[] = (int) $options['h'];
44+
$query->where('services.device_id', $options['h']);
4245
} else {
4346
if (preg_match('/\*/', $options['h'])) {
44-
$where = "AND `hostname` LIKE '?'";
45-
$params[] = str_replace('*', '%', $options['h']);
47+
$query->where('devices.hostname', 'like', str_replace('*', '%', $options['h']));
4648
} else {
47-
$where = "AND `hostname` = '?'";
48-
$params[] = $options['h'];
49+
$query->where('devices.hostname', $options['h']);
4950
}
5051
}
5152
} else {
@@ -58,16 +59,13 @@
5859
}
5960
}
6061

61-
$sql = 'SELECT D.*,S.*,attrib_value FROM `devices` AS D'
62-
. ' INNER JOIN `services` AS S ON S.device_id = D.device_id AND D.disabled = 0 ' . $where
63-
. ' LEFT JOIN `devices_attribs` as A ON D.device_id = A.device_id AND A.attrib_type = "override_icmp_disable"'
64-
. ' ORDER by D.device_id DESC;';
62+
$services = $query->get();
6563

66-
foreach (dbFetchRows($sql, $params) as $service) {
64+
foreach ($services as $service) {
6765
// Run the polling function if service is enabled and the associated device is up, "Disable ICMP Test" option is not enabled,
6866
// or service hostname/ip is different from associated device
6967
if (! $service['service_disabled'] && ($service['status'] == 1 || ($service['status'] == 0 && $service['status_reason'] === 'snmp') ||
70-
$service['attrib_value'] === 'true' || (! is_null($service['service_ip']) && $service['service_ip'] !== $service['hostname'] &&
68+
$service->getAttrib('override_icmp_disable') === 'true' || (! is_null($service['service_ip']) && $service['service_ip'] !== $service['hostname'] &&
7169
$service['service_ip'] !== inet6_ntop($service['ip'])))) {
7270
poll_service($service);
7371
$polled_services++;

daily.php

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
*/
88

99
use App\Facades\LibrenmsConfig;
10+
use App\Models\AlertRule;
1011
use App\Models\Device;
1112
use App\Models\DeviceGroup;
1213
use Illuminate\Database\Eloquent\Collection;
@@ -264,15 +265,11 @@
264265
$lock = Cache::lock('refresh_alert_rules', 86000);
265266
if ($lock->get()) {
266267
echo 'Refreshing alert rules queries' . PHP_EOL;
267-
$rules = dbFetchRows('SELECT `id`, `builder`, `extra` FROM `alert_rules`');
268+
$rules = AlertRule::query()->select(['id', 'builder', 'extra'])->get();
268269
foreach ($rules as $rule) {
269-
$rule_options = json_decode($rule['extra'], true);
270-
if ($rule_options['options']['override_query'] !== 'on' && $rule_options['options']['override_query'] !== true) {
271-
$data['query'] = QueryBuilderParser::fromJson($rule['builder'])->toSql();
272-
if (! empty($data['query'])) {
273-
dbUpdate($data, 'alert_rules', 'id=?', [$rule['id']]);
274-
unset($data);
275-
}
270+
if (($rule->extra['options']['override_query'] ?? false) !== 'on' && ($rule->extra['options']['override_query'] ?? false) !== true) {
271+
$rule->query = QueryBuilderParser::fromJson($rule->builder)->toSql();
272+
$rule->save();
276273
}
277274
}
278275
$lock->release();

dist-pollers.php

Lines changed: 0 additions & 57 deletions
This file was deleted.

includes/services.inc.php

Lines changed: 11 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -2,44 +2,13 @@
22

33
use App\Facades\LibrenmsConfig;
44
use App\Models\Eventlog;
5+
use App\Models\Service;
56
use LibreNMS\Alert\AlertRules;
67
use LibreNMS\Enum\Severity;
78
use LibreNMS\RRD\RrdDefinition;
89
use LibreNMS\Util\Clean;
910
use LibreNMS\Util\IP;
1011

11-
function get_service_status($device = null)
12-
{
13-
$sql_query = 'SELECT service_status, count(service_status) as count FROM services WHERE';
14-
$sql_param = [];
15-
$add = 0;
16-
17-
if (! is_null($device)) {
18-
// Add a device filter to the SQL query.
19-
$sql_query .= ' `device_id` = ?';
20-
$sql_param[] = $device;
21-
$add++;
22-
}
23-
24-
if ($add == 0) {
25-
// No filters, remove " WHERE" -6
26-
$sql_query = substr($sql_query, 0, strlen($sql_query) - 6);
27-
}
28-
$sql_query .= ' GROUP BY service_status';
29-
30-
// $service is not null, get only what we want.
31-
$result = dbFetchRows($sql_query, $sql_param);
32-
33-
// Set our defaults to 0
34-
$service_count = [0 => 0, 1 => 0, 2 => 0];
35-
// Rebuild the array in a more convenient method
36-
foreach ($result as $v) {
37-
$service_count[$v['service_status']] = $v['count'];
38-
}
39-
40-
return $service_count;
41-
}
42-
4312
function add_service($device, $type, $desc, $ip = '', $param = '', $ignore = 0, $disabled = 0, $template_id = '', $name = '')
4413
{
4514
$device = DeviceCache::get(is_array($device) ? $device['device_id'] : $device);
@@ -48,45 +17,25 @@ function add_service($device, $type, $desc, $ip = '', $param = '', $ignore = 0,
4817
$ip = $device->pollerTarget();
4918
}
5019

51-
$insert = ['device_id' => $device->device_id, 'service_ip' => $ip, 'service_type' => $type, 'service_changed' => ['UNIX_TIMESTAMP(NOW())'], 'service_desc' => $desc, 'service_param' => $param, 'service_ignore' => $ignore, 'service_status' => 3, 'service_message' => 'Service not yet checked', 'service_ds' => '{}', 'service_disabled' => $disabled, 'service_template_id' => $template_id, 'service_name' => $name];
20+
$insert = ['device_id' => $device->device_id, 'service_ip' => $ip, 'service_type' => $type, 'service_desc' => $desc, 'service_param' => $param, 'service_ignore' => $ignore, 'service_status' => 3, 'service_message' => 'Service not yet checked', 'service_ds' => '{}', 'service_disabled' => $disabled, 'service_template_id' => $template_id, 'service_name' => $name];
5221

53-
return dbInsert($insert, 'services');
22+
return Service::create($insert);
5423
}
5524

5625
function service_get($device = null, $service = null)
5726
{
58-
$sql_query = 'SELECT `service_id`,`device_id`,`service_ip`,`service_type`,`service_desc`,`service_param`,`service_ignore`,`service_status`,`service_changed`,`service_message`,`service_disabled`,`service_ds`,`service_template_id`,`service_name` FROM `services` WHERE';
59-
$sql_param = [];
60-
$add = 0;
61-
62-
d_echo('SQL Query: ' . $sql_query);
6327
if (! is_null($service)) {
6428
// Add a service filter to the SQL query.
65-
$sql_query .= ' `service_id` = ? AND';
66-
$sql_param[] = $service;
67-
$add++;
68-
}
69-
if (! is_null($device)) {
70-
// Add a device filter to the SQL query.
71-
$sql_query .= ' `device_id` = ? AND';
72-
$sql_param[] = $device;
73-
$add++;
74-
}
75-
76-
if ($add == 0) {
77-
// No filters, remove " WHERE" -6
78-
$sql_query = substr($sql_query, 0, strlen($sql_query) - 6);
29+
$services = Service::query()->where('service_id', $service)->get();
30+
} elseif (! is_null($device)) {
31+
$services = Service::query()->where('device_id', $device)->get();
7932
} else {
80-
// We have filters, remove " AND" -4
81-
$sql_query = substr($sql_query, 0, strlen($sql_query) - 4);
33+
$services = Service::query()->get();
8234
}
83-
d_echo('SQL Query: ' . $sql_query);
8435

85-
// $service is not null, get only what we want.
86-
$services = dbFetchRows($sql_query, $sql_param);
8736
d_echo('Service Array: ' . print_r($services, true) . "\n");
8837

89-
return $services;
38+
return $services->toArray();
9039
}
9140

9241
function edit_service($update = [], $service = null)
@@ -95,7 +44,7 @@ function edit_service($update = [], $service = null)
9544
return false;
9645
}
9746

98-
return dbUpdate($update, 'services', '`service_id`=?', [$service]);
47+
return Service::query()->where('service_id', $service)->update($update);
9948
}
10049

10150
function delete_service($service = null)
@@ -104,12 +53,12 @@ function delete_service($service = null)
10453
return false;
10554
}
10655

107-
return dbDelete('services', '`service_id` = ?', [$service]);
56+
return Service::query()->where('service_id', $service)->delete();
10857
}
10958

11059
function discover_service($device, $service)
11160
{
112-
if (! dbFetchCell('SELECT COUNT(service_id) FROM `services` WHERE `service_type`= ? AND `device_id` = ?', [$service, $device['device_id']])) {
61+
if (Service::query()->where('service_type', $service)->where('device_id', $device['device_id'])->doesntExist()) {
11362
add_service($device, $service, "$service Monitoring (Auto Discovered)", null, null, 0, 0, 0, "AUTO: $service");
11463
Eventlog::log('Autodiscovered service: type ' . $service, $device['device_id'], 'service', Severity::Info);
11564
echo '+';

phpstan-baseline-deprecated.neon

Lines changed: 0 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -10386,51 +10386,6 @@ parameters:
1038610386
count: 2
1038710387
path: includes/polling/unix-agent/munin-plugins.inc.php
1038810388

10389-
-
10390-
message: '''
10391-
#^Call to deprecated function dbDelete\(\)\:
10392-
Please use Eloquent instead; https\://laravel\.com/docs/eloquent\#deleting\-models$#
10393-
'''
10394-
identifier: function.deprecated
10395-
count: 1
10396-
path: includes/services.inc.php
10397-
10398-
-
10399-
message: '''
10400-
#^Call to deprecated function dbFetchCell\(\)\:
10401-
Please use Eloquent instead; https\://laravel\.com/docs/eloquent$#
10402-
'''
10403-
identifier: function.deprecated
10404-
count: 1
10405-
path: includes/services.inc.php
10406-
10407-
-
10408-
message: '''
10409-
#^Call to deprecated function dbFetchRows\(\)\:
10410-
Please use Eloquent instead; https\://laravel\.com/docs/eloquent$#
10411-
'''
10412-
identifier: function.deprecated
10413-
count: 2
10414-
path: includes/services.inc.php
10415-
10416-
-
10417-
message: '''
10418-
#^Call to deprecated function dbInsert\(\)\:
10419-
Please use Eloquent instead; https\://laravel\.com/docs/eloquent\#inserting\-and\-updating\-models$#
10420-
'''
10421-
identifier: function.deprecated
10422-
count: 1
10423-
path: includes/services.inc.php
10424-
10425-
-
10426-
message: '''
10427-
#^Call to deprecated function dbUpdate\(\)\:
10428-
Please use Eloquent instead; https\://laravel\.com/docs/eloquent\#inserting\-and\-updating\-models$#
10429-
'''
10430-
identifier: function.deprecated
10431-
count: 1
10432-
path: includes/services.inc.php
10433-
1043410389
-
1043510390
message: '''
1043610391
#^Call to deprecated function dbFetchCell\(\)\:

scripts/collect-port-polling.php

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
<?php
33

44
use App\Facades\LibrenmsConfig;
5+
use App\Models\Device;
56
use Illuminate\Support\Str;
67
use LibreNMS\Util\Debug;
78
use LibreNMS\Util\Number;
@@ -35,23 +36,25 @@ function print_help()
3536
exit(0);
3637
}
3738

38-
$where = '';
39-
$params = [];
39+
$devices = Device::query()->isActive()->orderBy('hostname', 'ASC');
4040
if (isset($options['h'])) {
4141
if (is_numeric($options['h'])) {
42-
$where = 'AND `device_id` = ?';
43-
$params = [$options['h']];
42+
$devices->where('device_id', $options['h']);
4443
} elseif (Str::contains($options['h'], ',')) {
4544
$device_ids = array_map(trim(...), explode(',', $options['h']));
4645
$device_ids = array_filter($device_ids, is_numeric(...));
47-
$where = 'AND `device_id` in ' . dbGenPlaceholders(count($device_ids));
48-
$params = $device_ids;
46+
$devices->whereIn('device_id', $device_ids);
4947
} else {
50-
$where = 'AND `hostname` LIKE ?';
51-
$params = [str_replace('*', '%', $options['h'])];
48+
$devices->where('hostname', 'like', str_replace('*', '%', $options['h']));
5249
}
5350
}
54-
$devices = dbFetchRows("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY `hostname` ASC", $params);
51+
52+
$devices = $devices->withCount([
53+
'ports',
54+
'ports as inactive_count' => fn ($q) => $q->where('deleted', 1)->orWhere('ifAdminStatus', '!=', 'up')->orWhere('disabled', 1),
55+
]);
56+
57+
$devices = $devices->get()->toArray();
5558

5659
if (isset($options['e'])) {
5760
if (! is_numeric($options['e']) || $options['e'] < 0) {
@@ -95,14 +98,7 @@ function print_help()
9598
$inactive_sql = "`deleted` = 1 OR `ifAdminStatus` != 'up' OR `disabled` = 1";
9699
$set_count = 0;
97100
foreach ($devices as &$device) {
98-
$count = dbFetchCell('SELECT COUNT(*) FROM `ports` WHERE `device_id`=?', [$device['device_id']]);
99-
$inactive = dbFetchCell(
100-
"SELECT COUNT(*) FROM `ports` WHERE `device_id`=? AND ($inactive_sql)",
101-
[$device['device_id']]
102-
);
103-
104-
$device['port_count'] = $count;
105-
$device['inactive_ratio'] = ($inactive == 0 ? 0 : ($inactive / $count));
101+
$device['inactive_ratio'] = ($device['inactive_count'] == 0 ? 0 : ($device['inactive_count'] / $device['ports_count']));
106102
$device['diff_sec'] = $device['selective_time_sec'] - $device['full_time_sec'];
107103
$device['diff_perc'] = Number::calculatePercent($device['diff_sec'], $device['full_time_sec']);
108104

0 commit comments

Comments
 (0)