Repository navigation
Expand file tree
/
Copy pathsetup.php
More file actions
591 lines (471 loc) · 18.8 KB
/
Copy pathsetup.php
File metadata and controls
591 lines (471 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
<?php
/*
* SPDX-FileCopyrightText: 2026 Thomas Vincent <thomasvincent@gmail.com>
* SPDX-License-Identifier: GPL-2.0-or-later
*
* This file is part of plugin_gpu, a plugin for Cacti.
* https://github.com/somethingwithproof/plugin_gpu
*
* 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 2 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.
*/
/*
* Cacti includes this file on every request, on whatever PHP version the site
* runs. It must parse on PHP 8.0 (CI lints it there), and nothing under lib/
* is loaded until gpu_boot() has confirmed PHP 8.2 or later (ADR 0006).
* Every hook and lifecycle function therefore starts with that check, so an
* unsupported runtime gets a refusal instead of a parse error that would take
* down the whole Cacti UI.
*/
function gpu_php_supported(): bool {
return version_compare(PHP_VERSION, '8.2.0', '>=');
}
function gpu_boot(): bool {
if (!gpu_php_supported()) {
return false;
}
require_once(__DIR__ . '/include/autoload.php');
return true;
}
/**
* Refuse with a message naming the required version (REQ-COMPAT-002).
*
* Used by the lifecycle functions only. Hook shims return silently instead,
* because they run on every page and a refused plugin must not flood the log.
*/
function gpu_refuse_unsupported(): bool {
if (gpu_php_supported()) {
return false;
}
$message = __('The GPU plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled.', '8.2.0', PHP_VERSION, 'gpu');
cacti_log('ERROR: ' . $message, false, 'GPU');
if (PHP_SAPI === 'cli') {
fwrite(STDERR, $message . PHP_EOL);
} elseif (function_exists('raise_message')) {
raise_message('gpu_php', $message, MESSAGE_LEVEL_ERROR);
}
return true;
}
/**
* @return array<string, string>
*/
function plugin_gpu_version(): array {
$info = parse_ini_file(__DIR__ . '/INFO', true);
if (!is_array($info) || !isset($info['info']) || !is_array($info['info'])) {
return array();
}
$version = array();
foreach ($info['info'] as $key => $value) {
$version[(string) $key] = is_scalar($value) ? (string) $value : '';
}
return $version;
}
function plugin_gpu_install(): void {
if (gpu_refuse_unsupported()) {
return;
}
plugin_gpu_upgrade(true);
}
function plugin_gpu_check_config(): bool {
if (gpu_refuse_unsupported()) {
return false;
}
return plugin_gpu_upgrade(true);
}
/**
* Common start after include/auth.php establishes the user. Recheck the
* realm here because cookie and Basic login restore the user after the
* alternate-realms hook. Disabled plugins and unsupported runtimes refuse.
*/
function gpu_page_start(): bool {
if (gpu_boot() && api_plugin_is_enabled('gpu')) {
if (gpu_page_allowed()) {
return true;
}
http_response_code(403);
return false;
}
top_header();
html_start_box(__('GPU', 'gpu'), '100%', '', '3', 'center', '');
print '<tr><td>' . html_escape(gpu_php_supported() ? __('The GPU plugin is not enabled.', 'gpu') : __('The GPU plugin requires PHP %s or later.', '8.2.0', 'gpu')) . '</td></tr>';
html_end_box();
bottom_footer();
return false;
}
/**
* State-changing actions are accepted only as POST, where csrf-magic checks
* the token (REQ-UI-004). A GET that names one is sent back to the page
* without effect.
*
* @param list<string> $actions
*/
function gpu_require_post(string $page, array $actions): void {
$action = (string) get_nfilter_request_var('action');
if (in_array($action, $actions, true) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: ' . $page);
exit;
}
}
function gpu_settings(): \Somethingwithproof\Gpu\Settings {
return (new \Somethingwithproof\Gpu\SettingsRepository(false))->load();
}
function gpu_nodes(): \Somethingwithproof\Gpu\NodeRepository {
return new \Somethingwithproof\Gpu\NodeRepository(false, new \Somethingwithproof\Gpu\SystemClock());
}
function gpu_gpus(): \Somethingwithproof\Gpu\GpuRepository {
return new \Somethingwithproof\Gpu\GpuRepository(false);
}
function gpu_poller(): \Somethingwithproof\Gpu\Poller {
$clock = new \Somethingwithproof\Gpu\SystemClock();
$gpus = gpu_gpus();
$collections = new \Somethingwithproof\Gpu\CollectionRepository(false);
$retries = (int) read_config_option('snmp_retries');
$collector = new \Somethingwithproof\Gpu\Collector(
new \Somethingwithproof\Gpu\SnmpExtendReader(max(0, $retries)),
new \Somethingwithproof\Gpu\NvidiaSmiParser(),
new \Somethingwithproof\Gpu\Inventory($gpus, new \Somethingwithproof\Gpu\IdentityReconciler(), $clock),
$gpus,
new \Somethingwithproof\Gpu\ObservationRepository(false),
$collections,
new \Somethingwithproof\Gpu\ReindexRepository(false),
new \Somethingwithproof\Gpu\LockRepository(false),
$clock,
);
return new \Somethingwithproof\Gpu\Poller(gpu_nodes(), $collections, $collector, gpu_provisioner(), new \Somethingwithproof\Gpu\ReindexRepository(false), $clock);
}
/**
* The provisioner, with the core libraries its API calls need loaded.
*/
function gpu_provisioner(): \Somethingwithproof\Gpu\Provisioner {
global $config;
foreach (array('api_device', 'data_query', 'template', 'api_graph', 'api_data_source', 'utility', 'poller', 'variables', 'functions') as $library) {
include_once($config['library_path'] . '/' . $library . '.php');
}
return new \Somethingwithproof\Gpu\Provisioner(new \Somethingwithproof\Gpu\CactiObjectRepository(false), new \Somethingwithproof\Gpu\CacheRepository(false), new \Somethingwithproof\Gpu\ReindexRepository(false), new \Somethingwithproof\Gpu\SystemClock());
}
function gpu_templates(): \Somethingwithproof\Gpu\TemplateInstaller {
global $config;
// What core's cli/import_template.php loads for an import: the import
// itself replicates and repairs through poller.php and utility.php.
include_once($config['library_path'] . '/import.php');
include_once($config['library_path'] . '/poller.php');
include_once($config['library_path'] . '/utility.php');
return new \Somethingwithproof\Gpu\TemplateInstaller(new \Somethingwithproof\Gpu\CactiObjectRepository(false), new \Somethingwithproof\Gpu\LockRepository(false), __DIR__, rtrim((string) $config['base_path'], '/'));
}
function gpu_script_server(): \Somethingwithproof\Gpu\ScriptServer {
return new \Somethingwithproof\Gpu\ScriptServer(new \Somethingwithproof\Gpu\CacheRepository(false), new \Somethingwithproof\Gpu\SystemClock(), gpu_settings()->staleAfter);
}
/**
* Bring the schema, hooks, realms, and shipped templates up to the code's version.
*
* Cacti 1.2.31 never calls this itself; check_config and the config_arrays
* hook do. Fresh installs take the same path as upgrades. The version stored
* in plugin_config changes only after every migration has succeeded, so an
* interrupted run is finished by the next one (REQ-LIFE-002).
*
* $grant gives newly registered realms to the current user. Only install and
* check_config pass it: both run from the Plugins page, which needs plugin
* management. A repair triggered from config_arrays can run for anyone who
* opens a plugin page, so it must never grant anything.
*/
function plugin_gpu_upgrade(bool $grant = false): bool {
if (!gpu_boot()) {
return false;
}
$info = plugin_gpu_version();
$schema = new \Somethingwithproof\Gpu\Schema(false);
if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered() && gpu_templates()->installed()) {
return true;
}
if (!$schema->migrate()) {
return false;
}
$schema->trackTables();
gpu_setup_hooks($grant);
// The version is recorded only once the templates are in place, so a
// failed import is retried by the next repair.
if (!gpu_templates()->install()) {
return false;
}
$schema->recordPluginVersion($info['version'], $info['author'], $info['homepage']);
return true;
}
/**
* Register hooks and realms.
*
* Kept procedural and named *_setup_* because api_plugin_register_hook() and
* api_plugin_register_realm() refuse callers whose function name does not
* contain install, upgrade, or setup.
*/
function gpu_setup_hooks(bool $grant = false): void {
global $config;
// Registering a hook replicates plugin config, which needs core lib/poller.php.
if (!function_exists('replicate_out')) {
include_once($config['library_path'] . '/poller.php');
}
// A hook repaired while the plugin is enabled must be active, or core
// never calls it; on install and while disabled, core decides.
$enabled = (new \Somethingwithproof\Gpu\Schema(false))->pluginEnabled();
foreach (\Somethingwithproof\Gpu\Schema::HOOKS as $hook => $function) {
api_plugin_register_hook('gpu', $hook, $function, 'setup.php', $enabled);
}
foreach (\Somethingwithproof\Gpu\Pages::realms() as $realm) {
api_plugin_register_realm('gpu', implode(',', $realm['files']), $realm['name'], $grant && $realm['files'] !== \Somethingwithproof\Gpu\Pages::OPERATOR);
}
}
/**
* Abort an uninstall that was told to keep the tables but could not untrack
* them. Core drops every tracked table once plugin_gpu_uninstall() returns
* and ignores its result, so only stopping the request keeps the tables; the
* plugin then stays installed and the uninstall can be retried. PHP 8.0
* syntax, because the unbooted path uses it too.
*/
function gpu_uninstall_stop(): void {
cacti_log('ERROR: Uninstall stopped: the plugin tables could not be untracked, so Cacti would have dropped the tables it was told to keep', false, 'GPU');
throw new RuntimeException('The GPU plugin uninstall was stopped to keep its tables. See the Cacti log.');
}
/**
* Uninstall never touches a Cacti device, data source, graph, or RRD file,
* and never contacts a GPU node (REQ-LIFE-004, REQ-LIFE-005). Core drops the
* tracked plugin tables afterwards unless the administrator left "Keep
* Plugin Tables on Uninstall" checked, which is the default.
*/
function plugin_gpu_uninstall(): void {
if (!gpu_boot()) {
include_once(__DIR__ . '/include/unbooted-uninstall.php');
gpu_uninstall_unbooted();
return;
}
$schema = new \Somethingwithproof\Gpu\Schema(false);
if (gpu_settings()->keepTablesOnUninstall) {
if (!$schema->untrackTables()) {
gpu_uninstall_stop();
}
\Somethingwithproof\Gpu\Log::info('Uninstall kept the plugin tables as configured');
} else {
$schema->forgetVersion();
}
// REQ-LIFE-004: removing the plugin's own templates and data query XML
// is a separate choice, off by default. It never removes a device, data
// source, graph, or RRD file.
if (gpu_settings()->removeObjectsOnUninstall) {
$report = gpu_templates()->remove(new \Somethingwithproof\Gpu\CactiTemplateRepository(false));
\Somethingwithproof\Gpu\Log::info(sprintf('Uninstall removed %d of the plugin\'s Cacti objects; kept because still in use or changed: %s', count($report['removed']), $report['kept'] === [] ? 'none' : implode(', ', $report['kept'])));
}
}
/**
* Create a Cacti device for a node that has none, through Cacti's own
* api_device_save() with the site's device defaults (ADR 0010). Returns the
* new device id, or 0.
*/
function gpu_create_device(string $description, string $hostname, int $template): int {
global $config;
include_once($config['library_path'] . '/api_device.php');
$availability = (int) read_config_option('availability_method');
$max_oids = (int) read_config_option('max_get_size');
$threads = (int) read_config_option('device_threads');
$id = api_device_save(0, $template, $description, $hostname,
read_config_option('snmp_community'), read_config_option('snmp_version'),
read_config_option('snmp_username'), read_config_option('snmp_password'),
read_config_option('snmp_port'), read_config_option('snmp_timeout'), '',
$availability > 0 ? $availability : 1, read_config_option('ping_method'), read_config_option('ping_port'),
read_config_option('ping_timeout'), read_config_option('ping_retries'), '',
read_config_option('snmp_auth_protocol'), read_config_option('snmp_priv_passphrase'), read_config_option('snmp_priv_protocol'), '', '',
$max_oids > 0 ? $max_oids : 10, $threads > 0 ? $threads : 1, 1, max(0, (int) read_config_option('default_site')));
return is_numeric($id) ? (int) $id : 0;
}
/**
* Remove a device through Cacti's API, which also calls the device_remove
* hooks.
*/
function gpu_remove_device(int $id): bool {
global $config;
include_once($config['library_path'] . '/api_device.php');
api_device_remove($id);
return (new \Somethingwithproof\Gpu\CactiObjectRepository(false))->deviceRemoved($id);
}
/**
* Whether Maint holds a device in maintenance, or null when Maint is not
* enabled. It asks Maint's own check, guarded, because core has no caller
* of the is_device_in_maintenance hook (PLAN, Measurement state).
*/
function gpu_in_maintenance(int $host_id): ?bool {
global $config;
if (!api_plugin_is_enabled('maint') || !is_file($config['base_path'] . '/plugins/maint/functions.php')) {
return null;
}
include_once($config['base_path'] . '/plugins/maint/functions.php');
return function_exists('plugin_maint_check_cacti_host') ? (bool) plugin_maint_check_cacti_host($host_id) : null;
}
/**
* poller_bottom hook: start the collector in the background once the
* poller cycle has finished. The collector reads the GPU nodes; the poller
* itself and the script server input never do (REQ-SS-001).
*/
function gpu_poller_bottom(): void {
global $config;
if (!gpu_boot()) {
return;
}
// Remote data collectors are phase 3; only the main poller collects.
if ((int) $config['poller_id'] !== \Somethingwithproof\Gpu\Poller::MAIN_POLLER) {
return;
}
if (!function_exists('exec_background')) {
include_once($config['library_path'] . '/poller.php');
}
// exec_background() silently does nothing for a binary that does not
// exist, so a bare 'php' fallback would never start the collector.
$php = trim((string) read_config_option('path_php_binary'));
if ($php === '' || !is_file($php) || !is_executable($php)) {
cacti_log('ERROR: The GPU collector was not started because the PHP binary path setting is empty or not an executable file', false, 'GPU');
return;
}
// The one argument is escaped, so no part of it is parsed by a shell.
$args = '-q ' . cacti_escapeshellarg(__DIR__ . '/poller_gpu.php');
exec_background($php, $args);
}
/**
* device_remove hook: Cacti is deleting these devices. Their nodes are
* disabled and keep their GPU records (ADR 0010).
*
* @param mixed $device_ids
* @return mixed
*/
function gpu_device_remove($device_ids) {
if (!gpu_boot() || !is_array($device_ids)) {
return $device_ids;
}
$ids = array();
foreach ($device_ids as $id) {
if (is_numeric($id) && (int) $id > 0) {
$ids[] = (int) $id;
}
}
$disabled = gpu_nodes()->disableForHosts($ids);
if ($disabled > 0) {
\Somethingwithproof\Gpu\Log::info(sprintf('%d GPU nodes disabled because their Cacti devices were deleted', $disabled));
}
return $device_ids;
}
/**
* api_device_new hook: a device was saved. If it is a GPU node, make sure
* a device template change did not detach the GPU data query or change its
* reindex method (ADR 0010).
*
* @param mixed $save
* @return mixed
*/
function gpu_api_device_new($save) {
if (!gpu_boot() || !is_array($save) || !isset($save['id']) || !is_numeric($save['id'])) {
return $save;
}
$node = gpu_nodes()->findByHost((int) $save['id']);
if ($node !== null) {
gpu_provisioner()->attach($node);
}
return $save;
}
function gpu_config_arrays(): void {
global $menu;
if (!gpu_boot()) {
return;
}
foreach (\Somethingwithproof\Gpu\Pages::menu() as $file => $title) {
$menu[__('Management')]['plugins/gpu/' . $file] = $title;
}
// Cacti has not checked the session yet; a repair that keeps failing
// must not rerun, and log, on every anonymous request. A guest visit to
// graph_view.php leaves the guest ID in the session, so exclude it.
$sessionUser = $_SESSION['sess_user_id'] ?? 0;
if (
is_numeric($sessionUser) && (int) $sessionUser > 0
&& in_array(get_current_page(), \Somethingwithproof\Gpu\Pages::upgradeTriggers(), true)
&& (int) $sessionUser !== (int) get_guest_account()
) {
plugin_gpu_upgrade();
}
}
function gpu_config_settings(): void {
global $tabs, $settings;
if (PHP_SAPI !== 'cli' && !api_plugin_user_realm_auth('gpu_nodes.php')) {
return;
}
if (!gpu_boot()) {
return;
}
$tabs['gpu'] = __('GPU', 'gpu');
$settings['gpu'] = \Somethingwithproof\Gpu\Settings::form();
}
/**
* @param array<string, mixed> $nav
* @return array<string, mixed>
*/
function gpu_draw_navigation_text($nav) {
global $current_user;
if (!gpu_boot()) {
return $nav;
}
// Refresh settings after core restores cookie or Basic authentication.
if (get_current_page() === 'settings.php' && (PHP_SAPI === 'cli' || ($current_user['enabled'] ?? '') === 'on')) {
gpu_config_settings();
}
return array_merge($nav, \Somethingwithproof\Gpu\Pages::navigation());
}
/** Resolve role inheritance against Cacti's current user and group grants. */
function gpu_auth_alternate_realms(): void {
global $user_auth_realm_filenames;
static $deferred = array();
foreach ($deferred as $file => $realm) {
$user_auth_realm_filenames[$file] = $realm;
}
$deferred = array();
if (!api_plugin_is_enabled('gpu')) {
return;
}
if (empty($_SESSION['sess_user_id'])) {
// Core restores cookie and Basic authentication after this hook. Only
// these entrypoints defer the realm check to their post-auth guard.
$page = get_current_page();
if (in_array($page, array('gpu_inventory.php', 'gpu_health.php', 'gpu_operator.php'), true) && isset($user_auth_realm_filenames[$page])) {
$deferred[$page] = $user_auth_realm_filenames[$page];
$user_auth_realm_filenames[$page] = -1;
}
return;
}
$operator = 'gpu_operator.php';
$admin = 'gpu_nodes.php';
$files = array('gpu_inventory.php', 'gpu_health.php');
$realm = $user_auth_realm_filenames[$admin] ?? 0;
if ($realm > 0 && is_realm_allowed($realm)) {
$files[] = $operator;
} else {
$realm = $user_auth_realm_filenames[$operator] ?? 0;
if ($realm <= 0 || !is_realm_allowed($realm)) {
return;
}
}
foreach ($files as $file) {
$user_auth_realm_filenames[$file] = $realm;
}
}
/** Recheck the authenticated user before a plugin page reads data or acts. */
function gpu_page_allowed(): bool {
global $current_user;
gpu_auth_alternate_realms();
$userId = $current_user['id'] ?? null;
$sessionId = $_SESSION['sess_user_id'] ?? null;
return (is_int($userId) || (is_string($userId) && ctype_digit($userId)))
&& (is_int($sessionId) || (is_string($sessionId) && ctype_digit($sessionId)))
&& (int) $userId > 0 && (int) $userId === (int) $sessionId
&& api_plugin_is_enabled('gpu')
&& ($current_user['enabled'] ?? '') === 'on'
&& api_plugin_user_realm_auth(get_current_page());
}