Repository navigation
Expand file tree
/
Copy paththold_process.php
More file actions
439 lines (358 loc) · 12.5 KB
/
Copy paththold_process.php
File metadata and controls
439 lines (358 loc) · 12.5 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
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| 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: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 100);
}
chdir(__DIR__);
chdir('../../');
require_once('./include/cli_check.php');
require_once($config['base_path'] . '/lib/rrd.php');
// thold_mail() calls get_timespan() for alerts with a <GRAPH> tag.
require_once($config['base_path'] . '/lib/time.php');
require($config['base_path'] . '/plugins/thold/includes/arrays.php');
require_once($config['base_path'] . '/plugins/thold/includes/functions.php');
require_once($config['library_path'] . '/snmp.php');
// install signal handlers for Linux/UNIX only
if (function_exists('pcntl_signal')) {
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
}
// help with microtime(true)
// ini_set('precision', 16);
// process calling arguments
$parms = $_SERVER['argv'];
array_shift($parms);
$thread = false;
$debug = false;
global $thread, $cnn_id;
if (sizeof($parms)) {
foreach ($parms as $parameter) {
if (strpos($parameter, '=')) {
[$arg, $value] = explode('=', $parameter);
} else {
$arg = $parameter;
$value = '';
}
switch ($arg) {
case '-d':
case '--debug':
$debug = true;
break;
case '--thread':
$thread = $value;
if (!is_numeric($thread) || $thread <= 0) {
print 'FATAL: The Thread ID must be numeric and greater than 0.' . PHP_EOL;
display_help();
exit(1);
}
break;
case '-v':
case '--version':
case '-V':
display_version();
exit;
case '--help':
case '-h':
case '-H':
display_help();
exit;
default:
print 'ERROR: Invalid Parameter ' . $parameter . "\n\n";
display_help();
}
}
}
// Record start time for the pid's processing
$start = microtime(true);
if ($thread === false) {
print 'FATAL: The Thread ID must be numeric and greater than 0.' . PHP_EOL;
display_help();
exit(1);
}
$timeout = 99999999;
if (!register_process_start('thold', 'child', $thread, $timeout)) {
$pid = db_fetch_cell_prepared('SELECT pid
FROM processes
WHERE tasktype = "thold"
AND taskname = "child"
AND taskid = ?',
[$thread]);
if ($config['cacti_server_os'] == 'unix') {
if (function_exists('posix_getpgid')) {
$running = posix_getpgid($pid);
} elseif (function_exists('posix_kill')) {
$running = posix_kill($pid, 0);
}
if ($running) {
exit(1);
} else {
unregister_process('thold', 'child', $thread);
register_process_start('thold', 'child', $thread, $timeout);
}
}
}
db_close($cnn_id);
$cnn_id = thold_db_reconnect($cnn_id);
while (true) {
if (thold_db_connection()) {
// Prime the 'thold_daemon_debug' value
$daemon_debug = read_config_option('thold_daemon_debug', true);
// Fix issues with microtime skew
usleep(1);
$start_time = time();
$after_id = 0;
$batches = 0;
/**
* Walk this thread's queue in bounded batches, so a backlog costs time
* rather than memory. Each batch reads the queued samples, checks each
* threshold once, and deletes the rows it read.
*/
while (cacti_sizeof($ids = thold_daemon_queue_batch_ids($thread, $start_time, $after_id))) {
$after_id = end($ids);
$batches++;
$tholds = thold_daemon_queue_samples($ids, $start_time);
thold_daemon_debug(sprintf('Found %u queued samples for %u Thresholds to check for current values.', cacti_sizeof($tholds), cacti_sizeof($ids)), $thread);
$rrd_reindexed = [];
$rrd_time_reindexed = [];
thold_daemon_debug('Getting current values and normalizing multi-item Data Sources for Thresholds', $thread);
/**
* One transaction per batch: each sample is an UPDATE, and as an
* autocommit each one waited for its own log flush. If the worker
* dies mid-batch the samples roll back and, as the queue rows are
* deleted only after the commit, the next cycle reads them again.
*/
db_execute('START TRANSACTION');
foreach ($tholds as $thold_data) {
$item = [];
if (substr($thold_data['rrd_reindexed'], 0, 1) == 'a') {
$rrd_reindexed[$thold_data['local_data_id']] = cacti_unserialize($thold_data['rrd_reindexed']);
} else {
$rrd_reindexed[$thold_data['local_data_id']] = json_decode($thold_data['rrd_reindexed'], true);
}
$rrd_time_reindexed[$thold_data['local_data_id']] = $thold_data['rrd_time_reindexed'];
$currenttime = 0;
$currentval = thold_get_currentval($thold_data, $rrd_reindexed, $rrd_time_reindexed, $item, $currenttime);
switch ($thold_data['data_type']) {
case 0:
break;
case 1:
if ($thold_data['cdef'] > 0) {
$currentval = thold_build_cdef($thold_data['cdef'], $currentval, $thold_data['local_data_id'], $thold_data['data_template_rrd_id']);
}
break;
case 2:
if ($thold_data['percent_ds'] != '') {
$currentval = thold_calculate_percent($thold_data, $currentval, $rrd_reindexed);
}
break;
case 3:
if ($thold_data['expression'] != '') {
$currentval = thold_calculate_expression($thold_data, $currentval, $rrd_reindexed, $rrd_time_reindexed);
}
break;
case 4:
if ($thold_data['upper_ds'] != '') {
$currentval = thold_calculate_lower_upper($thold_data, $currentval, $rrd_reindexed);
}
break;
}
if (is_numeric($currentval)) {
$currentval = round($currentval, 4);
} else {
$currentval = '';
}
thold_daemon_debug(sprintf('Checked Name:%s, Graph:%s, Value:%s, Time:%s', $thold_data['thold_name'], $thold_data['local_graph_id'], $currentval, $currenttime), $thread);
if (!thold_daemon_persist_sample($thold_data, $item, $currentval, $currenttime)) {
thold_cacti_log(sprintf('WARNING: Failed to persist threshold sample for ID %s.', $thold_data['thold_id']), $thread);
}
}
db_execute('COMMIT');
$tholds = thold_daemon_queue_checks($thread, $ids);
$total_tholds = cacti_sizeof($tholds);
thold_daemon_debug(sprintf('Found %u Thresholds to check for breech.', $total_tholds), $thread);
if ($total_tholds) {
foreach ($tholds as $thold) {
thold_check_threshold($thold);
db_execute_prepared('UPDATE thold_data
SET tcheck = 0
WHERE id = ?',
[$thold['id']]
);
}
}
if (!thold_daemon_queue_delete($ids, $start_time)) {
thold_cacti_log('WARNING: Failed to remove processed rows from the Threshold Daemon queue.', $thread);
}
unset($tholds, $rrd_reindexed, $rrd_time_reindexed);
}
if ($batches > 0) {
thold_daemon_debug(sprintf('Processed %u batches, peak memory %u bytes.', $batches, memory_get_peak_usage(true)), $thread);
} else {
sleep(5);
$cnn_id = thold_db_reconnect($cnn_id);
heartbeat_process('thold', 'child', $thread);
}
} else {
thold_daemon_debug('WARNING: Thold Database Connection Down. Sleeping 60 Seconds', $thread);
sleep(60);
}
}
/**
* sig_handler - provides a generic means to catch exceptions to the Cacti log.
*
* @param $signo - (int) the signal that was thrown by the interface.
*
* @returns - null
*/
function sig_handler($signo) {
global $thread;
switch ($signo) {
case SIGTERM:
case SIGINT:
thold_cacti_log('WARNING: Thold Daemon Child Process with PID[' . getmypid() . '] terminated by user', $thread);
unregister_process('thold', 'child', $thread);
exit;
break;
default:
// ignore all other signals
}
}
/**
* Logs a debug message from a worker thread to the Cacti log, only
* when global debug mode or the thold_daemon_debug setting is enabled.
*
* @param string $message The message to log.
* @param mixed $thread The worker thread identifier, passed through
* to thold_cacti_log() for log-line context.
*
* @return void
*
* @global bool $debug Whether debug output is enabled.
*/
function thold_daemon_debug($message, $thread) {
global $debug;
$daemon_debug = read_config_option('thold_daemon_debug');
if ($debug || $daemon_debug) {
thold_cacti_log($message, $thread);
}
}
/**
* Checks whether the current database connection handle is a live,
* usable connection by attempting a trivial query against it, ignoring
* any resulting error via a temporary error handler swap.
*
* @return bool True if the connection is a valid object and the test
* query succeeds, false otherwise.
*
* @global object $cnn_id The current database connection handle.
*/
function thold_db_connection() {
global $cnn_id;
if (is_object($cnn_id)) {
// Avoid showing errors
restore_error_handler();
set_error_handler('thold_error_handler');
$cacti_version = db_fetch_cell('SELECT cacti FROM version');
// Restore Cacti's Error handler
restore_error_handler();
set_error_handler('CactiErrorHandler');
return is_null($cacti_version) ? false : true;
}
return false;
}
/**
* Re-establishes a fresh database connection for a worker process,
* closing the given (presumably stale/dead) connection handle first if
* it's a valid object, then reloading Cacti's config.php to obtain
* current connection credentials and reconnecting.
*
* @param object|null $cnn_id The existing (possibly stale) database
* connection handle to close before
* reconnecting (default null).
*
* @return object|resource The new database connection handle.
*/
function thold_db_reconnect($cnn_id = null) {
chdir(__DIR__);
include('../../include/config.php');
if (is_object($cnn_id)) {
db_close($cnn_id);
}
// Avoid showing errors
restore_error_handler();
set_error_handler('thold_error_handler');
// Connect to the database server
$cnn_id = db_connect_real($database_hostname, $database_username, $database_password, $database_default, $database_type, $database_port, $database_ssl);
// Restore Cacti's Error handler
restore_error_handler();
set_error_handler('CactiErrorHandler');
return $cnn_id;
}
/**
* Prints a timestamped debug message directly to stdout when global
* debug mode is enabled.
*
* @param string $string The message to print.
*
* @return void
*
* @global bool $debug Whether debug output is enabled.
*/
function thold_cli_debug($string) {
global $debug;
if ($debug) {
$output = date('Y-m-d H:i:s') . ' DEBUG: ' . trim($string);
print $output . PHP_EOL;
}
}
/**
* Prints this script's name, version, and copyright banner to stdout.
*
* @return void
*
* @global array $config Cacti global configuration array; used to
* locate setup.php when plugin_thold_version()
* isn't already loaded.
*/
function display_version() {
global $config;
if (!function_exists('plugin_thold_version')) {
include_once($config['base_path'] . '/plugins/thold/setup.php');
}
$info = plugin_thold_version();
print 'Threshold Processor, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL;
}
/**
* Prints this script's version banner followed by its command-line
* usage instructions to stdout.
*
* @return void
*/
function display_help() {
display_version();
print PHP_EOL . 'usage: thold_process.php --thread=N [--debug]' . PHP_EOL . PHP_EOL;
print 'The main Threshold Processor for the Thold Plugin.' . PHP_EOL;
}