forked from Cacti/cacti
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rrdcleaner.php
630 lines (526 loc) · 19.5 KB
/
rrdcleaner.php
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2024 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/ |
+-------------------------------------------------------------------------+
*/
include_once('./include/auth.php');
include_once(CACTI_PATH_LIBRARY . '/functions.php');
include_once(CACTI_PATH_LIBRARY . '/rrd.php');
$ds_actions = array(
1 => __x('dropdown action', 'Delete'),
3 => __x('dropdown action', 'Archive')
);
$rra_path = CACTI_PATH_RRA . '/';
/* set default action */
set_default_action();
if (isset_request_var('rescan')) {
set_request_var('action', 'restart');
}
switch (get_request_var('action')) {
case 'actions':
top_header();
do_rrd();
/* show current table again */
list_rrd();
bottom_footer();
break;
case 'restart':
top_header();
/* fill files name table */
rrdclean_fill_table();
list_rrd();
bottom_footer();
break;
case 'remall':
case 'arcall':
top_header();
/* fill files name table */
remove_all_rrds();
list_rrd();
bottom_footer();
break;
default:
top_header();
/* fill files name table */
list_rrd();
bottom_footer();
break;
}
/*
* Fill RRDCleaner's table
*/
function rrdclean_fill_table() {
global $config, $rra_path;
/* suppress warnings */
error_reporting(0);
/* install the rrdclean error handler */
set_error_handler('rrdclean_error_handler');
/* delete old file names table */
rrdclean_truncate_tables();
get_files();
clearstatcache();
/* restore original error handler */
restore_error_handler();
}
/*
* Determine the last time the rrdcleaner table was updated
*/
function rrdcleaner_lastupdate() {
$status = db_fetch_row("SHOW TABLE STATUS LIKE 'data_source_purge_temp'");
if (cacti_sizeof($status)) {
return $status['Update_time'];
}
}
/*
* Delete RRDCleaner's intermediate tables
*/
function rrdclean_truncate_tables() {
global $config;
/* suppress warnings */
error_reporting(0);
/* install the rrdclean error handler */
set_error_handler('rrdclean_error_handler');
$sql = 'TRUNCATE TABLE `data_source_purge_temp`';
db_execute($sql);
/* clear old data_source_purge_action table */
$sql = 'TRUNCATE TABLE `data_source_purge_action`';
db_execute($sql);
/* restore original error handler */
restore_error_handler();
}
/*
* PHP Error Handler
*/
function rrdclean_error_handler($errno, $errmsg, $filename, $linenum, $vars = array()) {
global $debug;
if ($debug) {
/* define all error types */
$errortype = array(
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
# E_STRICT => 'Runtime Notice',
# E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
/* create an error string for the log */
$err = "ERRNO:'" . $errno . "' TYPE:'" . $errortype[$errno] .
"' MESSAGE:'" . $errmsg . "' IN FILE:'" . $filename .
"' LINE NO:'" . $linenum . "'";
/* let's ignore some lesser issues */
if (substr_count($errmsg, 'date_default_timezone')) {
return;
}
if (substr_count($errmsg, 'Only variables')) {
return;
}
print('PROGERR: ' . $err . "\n"); # print_r($vars); print('</pre>');
}
return;
}
/*
* Find all unused files from Cacti tables
* and get file system information for them
*/
function get_files() {
global $config, $rra_path;
/* suppress warnings */
error_reporting(0);
/* install the rrdclean error handler */
set_error_handler('rrdclean_error_handler');
$files_unused = array();
$arc_path = read_config_option('rrd_archive');
if (substr_count($arc_path, $rra_path)) {
$archive = true;
$arcbase = basename($arc_path);
} else {
$archive = false;
$arcbase = '';
}
/* insert the files into the table from cacti */
db_execute("INSERT INTO data_source_purge_temp
(local_data_id, data_template_id, name_cache, name, in_cacti)
SELECT local_data_id, data_template_id, name_cache, replace(data_source_path, '<path_rra>/', '') AS file, '1' AS in_cacti
FROM data_template_data
WHERE local_data_id>0
ON DUPLICATE KEY UPDATE local_data_id=VALUES(local_data_id)");
$size = 0;
$sql = array();
if (read_config_option('storage_location')) {
$rrdtool_pipe = rrd_init();
rrdtool_execute('setcnn timeout off', false, RRDTOOL_OUTPUT_NULL, $rrdtool_pipe, $logopt = 'POLLER');
$scan = rrdtool_execute('rrd-list', false, RRDTOOL_OUTPUT_STDOUT, $rrdtool_pipe, $logopt = 'POLLER');
rrd_close($rrdtool_pipe);
if ($scan) {
$files = explode("\r\n", $scan);
foreach ($files as $file) {
list($pathname, $size, $mtime) = explode(',', $file);
$sql[] = "('" . str_replace($rra_path, '', $pathname) . "', " . $size . ", '" . date('Y-m-d H:i:s', $mtime) . "',0)";
$size++;
if ($size == 400) {
db_execute('INSERT INTO data_source_purge_temp
(name, size, last_mod, in_cacti)
VALUES ' . implode(',', $sql) . '
ON DUPLICATE KEY UPDATE size=VALUES(size), last_mod=VALUES(last_mod)');
$size = 0;
$sql = array();
}
}
}
} else {
$dir_iterator = new RecursiveDirectoryIterator($rra_path);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
if (substr($file->getPathname(), -3) == 'rrd' && !($archive && strstr($file->getPathname(), $arcbase . '/') !== false)) {
$sql[] = "('" . str_replace($rra_path, '', $file->getPathname()) . "', " . $file->getSize() . ", '" . date('Y-m-d H:i:s', $file->getMTime()) . "',0)";
$size++;
if ($size == 400) {
db_execute('INSERT INTO data_source_purge_temp
(name, size, last_mod, in_cacti)
VALUES ' . implode(',', $sql) . '
ON DUPLICATE KEY UPDATE size=VALUES(size), last_mod=VALUES(last_mod)');
$size = 0;
$sql = array();
}
}
}
}
if ($size > 0) {
db_execute('INSERT INTO data_source_purge_temp
(name, size, last_mod, in_cacti)
VALUES ' . implode(',', $sql) . '
ON DUPLICATE KEY UPDATE size=VALUES(size), last_mod=VALUES(last_mod)');
}
/* restore original error handler */
restore_error_handler();
}
/*
* Display all rrd file entries
*/
function list_rrd() {
global $config, $item_rows, $ds_actions, $rra_path;
/* suppress warnings */
error_reporting(0);
/* install the rrdclean error handler */
set_error_handler('rrdclean_error_handler');
/* ================= input validation and session storage ================= */
$filters = array(
'rows' => array(
'filter' => FILTER_VALIDATE_INT,
'pageset' => true,
'default' => '-1'
),
'page' => array(
'filter' => FILTER_VALIDATE_INT,
'default' => '1'
),
'filter' => array(
'filter' => FILTER_DEFAULT,
'pageset' => true,
'default' => ''
),
'sort_column' => array(
'filter' => FILTER_CALLBACK,
'default' => 'name',
'options' => array('options' => 'sanitize_search_string')
),
'sort_direction' => array(
'filter' => FILTER_CALLBACK,
'default' => 'ASC',
'options' => array('options' => 'sanitize_search_string')
),
'age' => array(
'filter' => FILTER_VALIDATE_INT,
'pageset' => true,
'default' => '0'
)
);
validate_store_request_vars($filters, 'sess_rrdc');
/* ================= input validation and session storage ================= */
if (get_request_var('rows') == '-1') {
$rows = read_config_option('num_rows_table');
} else {
$rows = get_request_var('rows');
}
html_start_box(__('RRD Cleaner'), '100%', '', '3', 'center', '');
filter();
html_end_box();
$sql_where = 'WHERE in_cacti=0';
/* form the 'where' clause for our main sql query */
if (get_request_var('filter') != '') {
$sql_where .= ' AND (
rc.name LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . '
OR rc.name_cache LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . '
OR dt.name LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ')';
}
$secsback = get_request_var('age');
if (get_request_var('age') == 0) {
$sql_where .= " AND last_mod>='" . date('Y-m-d H:i:s', time() - (86400 * 7)) . "'";
} else {
$sql_where .= " AND last_mod<='" . date('Y-m-d H:i:s', (time() - $secsback)) . "'";
}
$total_rows = db_fetch_cell("SELECT COUNT(rc.name)
FROM data_source_purge_temp AS rc
LEFT JOIN data_template AS dt
ON dt.id = rc.data_template_id
$sql_where");
$total_size = db_fetch_cell("SELECT ROUND(SUM(size),2)
FROM data_source_purge_temp AS rc
LEFT JOIN data_template AS dt
ON dt.id = rc.data_template_id
$sql_where");
$sql_order = get_order_string();
$sql_limit = ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows;
$file_list = db_fetch_assoc("SELECT rc.id, rc.name, rc.last_mod, rc.size,
rc.name_cache, rc.local_data_id, rc.data_template_id, dt.name AS data_template_name
FROM data_source_purge_temp AS rc
LEFT JOIN data_template AS dt
ON dt.id = rc.data_template_id
$sql_where
$sql_order
$sql_limit");
$nav = html_nav_bar(CACTI_PATH_URL . 'rrdcleaner.php?filter' . get_request_var('filter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 8, __('RRD Files'), 'page', 'main');
form_start('rrdcleaner.php');
print $nav;
html_start_box('', '100%', '', '3', 'center', '');
$display_text = array(
'name' => array(__('RRD File Name'), 'ASC'),
'name_cache' => array(__('DS Name'), 'ASC'),
'local_data_id' => array(__('DS ID'), 'ASC'),
'data_template_id' => array(__('Template ID'), 'ASC'),
'data_template_name' => array(__('Template'), 'ASC'),
'last_mod' => array(__('Last Modified'), 'DESC'),
'size' => array(__('Size [KB]'), 'DESC')
);
html_header_sort_checkbox($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false);
if (cacti_sizeof($file_list)) {
foreach ($file_list as $file) {
$data_template_name = ((empty($file['data_template_name'])) ? '<em>None</em>' : $file['data_template_name']);
form_alternate_row('line' . $file['id'], true);
form_selectable_cell(filter_value($file['name'], get_request_var('filter')), $file['id']);
form_selectable_cell(filter_value($file['name_cache'], get_request_var('filter'), CACTI_PATH_URL . 'data_sources.php?action=ds_edit&id=' . $file['local_data_id']), $file['id']);
form_selectable_cell($file['local_data_id'] > 0 ? $file['local_data_id'] : '<i>' . __('Deleted') . '</i>', $file['id']);
form_selectable_cell($file['data_template_id'] > 0 ? $file['data_template_id'] : '<i>' . __('Deleted') . '</i>', $file['id']);
form_selectable_cell(filter_value($file['data_template_name'], get_request_var('filter')), $file['id']);
form_selectable_cell($file['last_mod'], $file['id']);
form_selectable_cell(round($file['size'] / 1024, 2), $file['id']);
form_checkbox_cell($file['id'], $file['id']);
form_end_row();
}
} else {
print '<tr><td><em>' . __('No unused RRD Files') . "</em></td></tr>\n";
}
html_end_box(false);
if (cacti_sizeof($file_list)) {
print $nav;
}
rrdcleaner_legend($total_size);
draw_actions_dropdown($ds_actions);
form_end();
/* restore original error handler */
restore_error_handler();
}
function rrdcleaner_legend($total_size) {
html_start_box('', '100%', '', '3', 'center', '');
print '<tr>';
print '<td><b>' . __('Total Size [MB]:') . '</b> ' . round($total_size / 1024 / 1024, 2) . '</td>';
print '</tr><tr>';
print '<td><b>' . __('Last Scan:') . '</b> ' . rrdcleaner_lastupdate() . '</td>';
print '</tr>';
html_end_box(false);
}
function remove_all_rrds() {
global $config, $rra_path;
/* suppress warnings */
error_reporting(0);
/* install the rrdclean error handler */
set_error_handler('rrdclean_error_handler');
$action = get_nfilter_request_var('raction');
/* add to data_source_purge_action table */
db_execute_prepared('INSERT INTO data_source_purge_action
(name, local_data_id, action)
SELECT name, local_data_id, ? AS action
FROM data_source_purge_temp
WHERE in_cacti = 0
ON DUPLICATE KEY UPDATE action = VALUES(action)', array($action));
/* remove the entries from the data_source_purge_temp location */
db_execute('DELETE FROM data_source_purge_temp WHERE in_cacti = 0');
/* restore original error handler */
restore_error_handler();
}
/*
* Read all checked list items and put them into
* a temporary table for the poller
*/
function do_rrd() {
global $config, $rra_path;
/* suppress warnings */
error_reporting(0);
/* install the rrdclean error handler */
set_error_handler('rrdclean_error_handler');
foreach ($_POST as $var => $val) {
if (preg_match('/^chk_(.*)$/', $var, $matches)) {
/* recreate the file name */
$unused_file = db_fetch_row_prepared('SELECT id, name, local_data_id
FROM data_source_purge_temp
WHERE id = ?', array($matches[1]));
/* add to data_source_purge_action table */
$sql = 'INSERT INTO data_source_purge_action
(name, local_data_id, action)
VALUES(?, ?, ?)
ON DUPLICATE KEY UPDATE local_data_id = VALUES(local_data_id)';
db_execute_prepared($sql, array($unused_file['name'], $unused_file['local_data_id'], get_nfilter_request_var('drp_action')));
/* drop from data_source_purge table */
db_execute_prepared('DELETE FROM data_source_purge_temp WHERE id = ?', array($matches[1]));
}
}
/* restore original error handler */
restore_error_handler();
}
function filter() {
global $item_rows;
?>
<tr class='even'>
<td>
<form id='form_rrdclean' method='get' action='rrdcleaner.php'>
<table class='filterTable'>
<tr>
<td>
<?php print __('Search'); ?>
</td>
<td>
<input type='text' class='ui-state-default ui-corner-all' id='filter' size='25' value='<?php print html_escape_request_var('filter'); ?>'>
</td>
<td>
<?php print __('Time Since Update'); ?>
</td>
<td>
<select id='age' onChange='refreshForm()'>
<option value='0' <?php print(get_request_var('age') == '0' ? ' selected' : ''); ?>>< <?php print __('%d Week', 1); ?></option>
<option value='604800' <?php print(get_request_var('age') == '604800' ? ' selected' : ''); ?>>> <?php print __('%d Week', 1); ?></option>
<option value='1209600' <?php print(get_request_var('age') == '1209600' ? ' selected' : ''); ?>>> <?php print __('%d Weeks', 2); ?></option>
<option value='1814400' <?php print(get_request_var('age') == '1814400' ? ' selected' : ''); ?>>> <?php print __('%d Weeks', 3); ?></option>
<option value='2628000' <?php print(get_request_var('age') == '2628000' ? ' selected' : ''); ?>>> <?php print __('%d Month', 1); ?></option>
<option value='5256000' <?php print(get_request_var('age') == '5256000' ? ' selected' : ''); ?>>> <?php print __('%d Months', 2); ?></option>
<option value='10512000' <?php print(get_request_var('age') == '10512000' ? ' selected' : ''); ?>>> <?php print __('%d Months', 4); ?></option>
<option value='15768000' <?php print(get_request_var('age') == '15768000' ? ' selected' : ''); ?>>> <?php print __('%d Months', 6); ?></option>
<option value='31536000' <?php print(get_request_var('age') == '31536000' ? ' selected' : ''); ?>>> <?php print __('%d Year', 1); ?></option>
</select>
</td>
<td>
<?php print __('RRDfiles'); ?>
</td>
<td>
<select id='rows'>
<option value='-1' <?php print(get_request_var('rows') == '-1' ? ' selected>' : '>') . __('Default'); ?></option>
<?php
if (cacti_sizeof($item_rows)) {
foreach ($item_rows as $key => $value) {
print '<option value="' . $key . '"';
if (get_request_var('rows') == $key) {
print ' selected';
}
print '>' . $value . "</option>\n";
}
}
?>
</select>
</td>
<td>
<span>
<input type='submit' class='ui-button ui-corner-all ui-widget' id='go' value='<?php print __x('filter: use', 'Go'); ?>'>
<input type='button' class='ui-button ui-corner-all ui-widget' id='clear' value='<?php print __x('filter: reset', 'Clear'); ?>'>
<input type='button' class='ui-button ui-corner-all ui-widget' id='rescan' value='<?php print __esc('Rescan'); ?>' name='rescan'>
</span>
</td>
<td>
<span>
<input type='button' class='ui-button ui-corner-all ui-widget' id='remall' value='<?php print __esc('Delete All'); ?>' title='<?php print __esc('Delete All Unknown RRDfiles'); ?>'>
<input type='button' class='ui-button ui-corner-all ui-widget' id='arcall' value='<?php print __esc('Archive All'); ?>' title='<?php print __esc('Archive All Unknown RRDfiles'); ?>'>
</span>
</td>
<td id='text'></td>
</tr>
</table>
</form>
<script type="text/javascript">
function refreshForm() {
strURL = 'rrdcleaner.php';
'?filter=' + $('#filter').val() +
'&age=' + $('#age').val() +
'&rows=' + $('#rows').val();
loadUrl({
url: strURL
})
}
function finishFinalize(options, data) {
$('#text').text('Finished').fadeOut(2000);
}
$(function() {
$('#form_rrdclean').submit(function() {
refreshForm();
return false;
});
$('#rows').change(function() {
refreshForm();
});
$('#clear').click(function() {
loadUrl({
url: 'rrdcleaner.php?clear=1',
})
});
$('#rescan').click(function() {
$('#text').text('Rebuilding RRDfile Listing');
pulsate('#text');
loadUrl({
url: 'rrdcleaner.php?rescan=1&clear=1',
funcEnd: 'finishFinalize',
});
});
$('#arcall').click(function() {
$('#text').text('Scheduling Archiving of All Unknowns');
pulsate('#text');
loadUrl({
url: 'rrdcleaner.php?action=arcall&raction=3&clear=1',
funcEnd: 'finishFinalize',
});
});
$('#remall').click(function() {
$('#text').text('Scheduling Purging of All Unknowns');
pulsate('#text');
loadUrl({
url: 'rrdcleaner.php?action=remall&raction=1&clear=1',
funcEnd: 'finishFinalize',
});
});
});
</script>
</td>
</tr>
<?php
}