-
Notifications
You must be signed in to change notification settings - Fork 9
/
functions.php
2146 lines (1748 loc) · 74.5 KB
/
functions.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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/ |
+-------------------------------------------------------------------------+
*/
function gexport_calc_next_start($export, $start_time = 0) {
if ($start_time == 0) $start_time = time();
$poller_interval = read_config_option('poller_interval');
if ($export['export_timing'] == 'periodic') {
$now = date('Y-m-d H:i:00', time());
$next_run = strtotime($now) + $export['export_skip'] * $poller_interval;
$next_start = date('Y-m-d H:i:s', $next_run);
} else {
switch($export['export_timing']) {
case 'hourly':
$next_start = date('Y-m-d H:' . $export['export_hourly'] . ':00', $start_time);
$now_time = strtotime(date('Y-m-d H:i:00', $start_time));
$next_run = strtotime($next_start);
if ($next_run <= $now_time) {
$next_run += 3600;
}
$next_start = date('Y-m-d H:i:00', $next_run);
break;
case 'daily':
$next_start = date('Y-m-d ' . $export['export_daily'] . ':00', $start_time);
$now_time = strtotime(date('Y-m-d H:i:00', $start_time));
$next_run = strtotime($next_start);
if ($next_run <= $now_time) {
$next_run += 86400;
}
$next_start = date('Y-m-d H:i:00', $next_run);
break;
}
}
return $next_start;
}
/* graph_export - a function that determines, for each export definition
if it's time to run or not. this function is currently single threaded
and some thought should be given to making multi-threaded.
@arg $id - the id of the export to check, '0' for all export definitions.
@arg $force - force the export to run no regardless of it's timing settings. */
function graph_export($id = 0, $force = false) {
global $debug, $start;
/* take time to log performance data */
$start = microtime(true);
$start_time = time();
$poller_interval = read_config_option('poller_interval');
$runnow = false;
$sql_where = '';
$started_exports = 0;
if ($force) {
export_debug('This is a forced run');
}
/* force run */
if ($id > 0) {
$sql_where = ' AND id=' . $id;
}
$exports = db_fetch_assoc('SELECT *
FROM graph_exports
WHERE enabled="on"' . $sql_where);
if (cacti_sizeof($exports)) {
foreach($exports as $export) {
export_debug("Checking export '" . $export['name'] . "' to determine if it's time to run.");
/* insert poller stats into the settings table */
db_execute_prepared('UPDATE graph_exports
SET last_checked = NOW()
WHERE id = ?',
array($export['id']));
$runnow = false;
if (!$force) {
if (strtotime($export['next_start']) < $start_time) {
$runnow = true;
$next_start = gexport_calc_next_start($export);
db_execute_prepared('UPDATE graph_exports
SET next_start = ? WHERE id = ?',
array($next_start, $export['id']));
}
} else {
$runnow = true;
}
if ($runnow) {
$started_exports++;
export_debug('Running Export for id ' . $export['id']);
run_export($export);
}
}
}
$end = microtime(true);
$export_stats = sprintf('Time:%01.2f Exports:%s Exported:%s', $end - $start, cacti_sizeof($exports), $started_exports);
cacti_log('MASTER STATS: ' . $export_stats, true, 'EXPORT');
}
/* run_export - a function the pre-processes the export structure and
then executes the required functions to export graphs, html and
config, to sanitize directories, and transfer data to the remote
host(s).
@arg $export - the export item structure. */
function run_export(&$export) {
global $config, $export_path;
$exported = 0;
if (!empty($export['export_pid'])) {
export_warn('Previous run of the following Graph Export ended in an unclean state Export:' . $export['name']);
if (posix_kill($export['export_pid'], 0) !== false) {
export_warn('Can not start the following Graph Export:' . $export['name'] . ' is still running');
return;
}
}
db_execute_prepared('UPDATE graph_exports
SET export_pid = ?, status = 1, last_started=NOW()
WHERE id = ?',
array(getmypid(), $export['id']));
switch ($export['export_type']) {
case 'local':
export_debug("Export Type is 'local'");
$export_path = $export['export_directory'];
$exported = exporter($export, $export_path);
break;
case 'sftp':
export_debug("Export Type is 'sftp_php'");
if (!function_exists('ftp_ssl_connect')) {
export_fatal($export, 'Secure FTP Function does not exist. Export can not continue.');
}
case 'ftp':
export_debug("Export Type is 'ftp'");
/* set the temp directory */
if (strlen($export['export_temp_directory']) == 0) {
$stExportDir = getenv('TEMP') . '/cacti-ftp-temp-' . $export['id'];
} else {
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\r") . '/cacti-ftp-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_pre_ftp_upload($export, $stExportDir);
export_log('Using PHP built-in FTP functions.');
export_ftp_php_execute($export, $stExportDir);
export_post_ftp_upload($export, $stExportDir);
break;
case 'ftp_nc':
export_debug("Export Type is 'ftp_nc'");
if (strstr(PHP_OS, 'WIN')) export_fatal($export, 'ncftpput only available in unix environment! Export can not continue.');
/* set the temp directory */
if (trim($export['export_temp_directory']) == '') {
if ($config['cacti_server_os'] == 'win32') {
$stExportDir = getenv('TEMP') . '/cacti-ftp-temp-' . $export['id'];
} else {
$stExportDir = '/tmp/cacti-ftp-temp-' . $export['id'];
}
} else {
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\r") . '/cacti-ftp-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_pre_ftp_upload($export, $stExportDir);
export_log('Using ncftpput.');
export_ftp_ncftpput_execute($export, $stExportDir);
export_post_ftp_upload($export, $stExportDir);
break;
case 'rsync':
export_debug("Export Type is 'rsync'");
/* set the temp directory */
if (trim($export['export_temp_directory']) == '') {
if ($config['cacti_server_os'] == 'win32') {
$stExportDir = getenv('TEMP') . '/cacti-rsync-temp-' . $export['id'];
} else {
$stExportDir = '/tmp/cacti-rsync-temp-' . $export['id'];
}
} else {
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\t") . '/cacti-rsync-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_rsync_execute($export, $stExportDir);
break;
case 'scp':
export_debug("Export Type is 'scp'");
/* set the temp directory */
if (trim($export['export_temp_directory']) == '') {
if ($config['cacti_server_os'] == 'win32') {
$stExportDir = getenv('TEMP') . '/cacti-scp-temp-' . $export['id'];
} else {
$stExportDir = '/tmp/cacti-scp-temp-' . $export['id'];
}
} else {
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\r") . '/cacti-scp-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_scp_execute($export, $stExportDir);
break;
default:
export_fatal($export, 'Export method not specified. Exporting can not continue. Please set method properly in Cacti configuration.');
}
db_execute_prepared('UPDATE graph_exports SET export_pid = 0 WHERE id = ?', array($export['id']));
config_export_stats($export, $exported);
}
function export_rsync_execute(&$export, $stExportDir) {
$keyopt = '';
$user = $export['export_user'];
$port = $export['export_port'];
$host = $export['export_host'];
$output = array();
$prune = '';
$retvar = 0;
if ($export['export_private_key_path'] != '') {
if (file_exists($export['export_private_key_path'])) {
if (is_readable($export['export_private_key_path'])) {
$keyopt = ' -e \'ssh -i "' . $export['export_private_key_path'] . '"\'';
} else {
export_fatal($export, 'ssh Private Key file is not readable.');
}
} else {
export_fatal($export, 'ssh Private Key file does not exist.');
}
}
if (preg_match('~^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$~', $host) != 1 && gethostbyname($host) == $host) {
export_fatal($export, "Hostname '" . $host . "' can not be resolved to an IP Address.");
}
if ($port != '') {
if (!is_numeric($port)) {
export_fatal($export, "SSH port '" . $port . "' must be numeric.");
} else {
$keyopt .= " -e 'ssh -p " . $port . "'";
}
} elseif ($keyopt != '') {
$keyopt .= " ";
}
if ($export['export_sanitize_remote'] == 'on') {
$prune = '--delete-delay --prune-empty-dirs';
}
exec('rsync -q ' . $export['export_args'] . ' ' . $prune . $keyopt . ' ' . $stExportDir . '/. ' . ($user != '' ? "$user@":'') . $host . ':' . $export['export_directory'] . ' 2>&1', $output, $retvar);
if ($retvar != 0) {
$retvar_message = export_rsync_get_message($retvar);
export_note('RSYNC OUTPUT: \'' . trim(implode(',',$output)) . '\'');
export_fatal($export, "RSYNC FAILED! Return Code was '$retvar' with message '" . $retvar_message . "'");
}
}
function export_rsync_get_message($error_code) {
switch ($error_code) {
case 0: return __('Success','gexport');
case 1: return __('Syntax or usage error','gexport');
case 2: return __('Protocol incompatibility','gexport');
case 3: return __('Errors selecting input/output files, dirs','gexport');
case 4: return __('Requested action not supported: an attempt was made to manipulate 64-bit files on a platform that cannot support them; or an option was specified that is supported by the client and not by the server.','gexport');
case 5: return __('Error starting client-server protocol','gexport');
case 6: return __('Daemon unable to append to log-file','gexport');
case 10: return __('Error in socket I/O','gexport');
case 11: return __('Error in file I/O','gexport');
case 12: return __('Error in rsync protocol data stream','gexport');
case 13: return __('Errors with program diagnostics','gexport');
case 14: return __('Error in IPC code','gexport');
case 20: return __('Received SIGUSR1 or SIGINT','gexport');
case 21: return __('Some error returned by waitpid()','gexport');
case 22: return __('Error allocating core memory buffers','gexport');
case 23: return __('Partial transfer due to error','gexport');
case 24: return __('Partial transfer due to vanished source files','gexport');
case 25: return __('The --max-delete limit stopped deletions','gexport');
case 30: return __('Timeout in data send/receive','gexport');
case 35: return __('Timeout waiting for daemon connection','gexport');
default:
return __('Unknown error ','gexport') . $error_code;
}
}
function export_scp_execute(&$export, $stExportDir) {
$keyopt = '';
$user = $export['export_user'];
$port = $export['export_port'];
$host = $export['export_host'];
$output = array();
$retvar = 0;
if ($export['export_private_key_path'] != '') {
if (file_exists($export['export_private_key_path'])) {
if (is_readable($export['export_private_key_path'])) {
$keyopt = ' -i "' . $export['export_private_key_path'] . '"';
} else {
export_fatal($export, 'ssh Private Key file is not readable.');
}
} else {
export_fatal($export, 'ssh Private Key file does not exist.');
}
}
if (preg_match('~^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$~', $host) != 1 && gethostbyname($host) == $host) {
export_fatal($export, "Hostname '" . $host . "' can not be resolved to an IP Address.");
}
if ($port != '' && !is_numeric($port)) {
export_fatal($export, "SCP port '" . $port . "' must be numeric.");
}
exec('scp ' . $export['export_args'] . ' ' . $keyopt . ($port != '' ? ' -P ' . "$port ":"") . $stExportDir . '/. ' . ($user != '' ? "$user@":'') . $host . ':' . $export['export_directory'] . ' 2>&1', $output, $retvar);
if ($retvar != 0) {
$retvar_message = export_rsync_get_message($retvar);
export_note('SCP OUTPUT: \'' . trim(implode(',',$output)) . '\'');
export_fatal($export, "SCP FAILED! Return Code was '$retvar' with message '" . $retvar_message . "'");
}
}
function export_scp_get_message($error_code) {
switch ($error_code) {
case 0: return __("Operation was successful");
case 1: return __("General error in file copy");
case 2: return __("Destination is not directory, but it should be");
case 3: return __("Maximum symlink level exceeded");
case 4: return __("Connecting to host failed.");
case 5: return __("Connection broken");
case 6: return __("File does not exist");
case 7: return __("No permission to access file.");
case 8: return __("General error in sftp protocol");
case 9: return __("File transfer protocol mismatch");
case 10: return __("No file matches a given criteria");
case 65: return __("Host not allowed to connect");
case 66: return __("General error in ssh protocol");
case 67: return __("Key exchange failed");
case 68: return __("Reserved");
case 69: return __("MAC error");
case 70: return __("Compression error");
case 71: return __("Service not available");
case 72: return __("Protocol version not supported");
case 73: return __("Host key not verifiable");
case 74: return __("Connection failed");
case 75: return __("Disconnected by application");
case 76: return __("Too many connections");
case 77: return __("Authentication cancelled by user");
case 78: return __("No more authentication methods available");
case 79: return __("Invalid user name");
default:
return __('Unknown error ','gexport') . $error_code;
}
}
/* exporter - a wrapper function that reduces clutter in the run_export
function.
@arg $export - the export item structure.
@arg $export_path - the location to storage export output. */
function exporter(&$export, $export_path) {
global $config;
$root_path = $config['base_path'];
$exported = 0;
create_export_directory_structure($export, $root_path, $export_path);
$exported = export_graphs($export, $export_path);
tree_site_export($export, $export_path);
return $exported;
}
/* config_export_stats - a function to export stats to the Cacti system for information
and possible graphing. It uses a global variable to get the start time of the
export process.
@arg $export - the export item structure
@arg $exported - the number of graphs exported. */
function config_export_stats(&$export, $exported) {
global $start;
/* take time to log performance data */
$end = microtime(true);
$export_stats = sprintf(
'ExportID:%s (%s) ExportDate:%s ExportDuration:%01.2f TotalGraphsExported:%s MaximumThreads: %s',
$export['id'], $export['name'], date('Y-m-d_G:i:s'), $end - $start, $exported, $export['export_threads']);
cacti_log('STATS: ' . $export_stats, true, 'EXPORT');
/* insert poller stats into the settings table */
db_execute_prepared('UPDATE graph_exports
SET last_runtime = ?, total_graphs = ?, last_ended=NOW(), status=0
WHERE id = ?',
array($end - $start, $exported, $export['id']));
db_execute_prepared(sprintf("REPLACE INTO settings (name,value) values ('stats_export_%s', ?)", $export['id']), array($export_stats));
}
/* export_fatal - a simple export logging function that indicates a
fatal condition for developers and users.
@arg $export - the export item structure
@arg $stMessage - the debug message. */
function export_fatal(&$export, $stMessage) {
export_recordlog('FATAL ERROR: ' . $stMessage, POLLER_VERBOSITY_NONE);
/* insert poller stats into the settings table */
db_execute_prepared('UPDATE graph_exports
SET last_error = ?, last_ended=NOW(), last_errored=NOW(), status=2
WHERE id = ?',
array($stMessage, $export['id']));
exit;
}
/* export_warn - a simple export logging function that indicates a
warning condition for developers and users
@arg $stMessage - the message */
function export_warn($stMessage) {
export_recordlog($stMessage, POLLER_VERBOSITY_MEDIUM);
}
/* export_note - a simple export logging function */
function export_note($stMessage) {
export_recordlog($stMessage, POLLER_VERBOSITY_NONE);
}
/* export_log - a simple export logging function that also logs to stdout
for developers.
@arg $stMessage - the debug message. */
function export_log($stMessage) {
export_recordlog($stMessage, POLLER_VERBOSITY_HIGH);
}
/* export_debug - a common cli debug level output for developers.
@arg $stMessage - the debug message. */
function export_debug($stMessage) {
export_recordlog($stMessage, POLLER_VERBOSITY_DEBUG);
}
/* export_recordlog - a common logging function to output to the
cacti log file and screen. Default is to use debug mode unless
the @loglevel is overridden or the global debug flag is set
@message - the message to record
@loglevel - the cacti loggiing level to use which affects both
screen and log file output */
function export_recordlog($message, $loglevel = POLLER_VERBOSITY_DEBUG) {
global $debug;
if ($debug) {
$loglevel = POLLER_VERBOSITY_NONE;
$message = 'MEMUSE: ' . number_format_i18n(memory_get_usage()) . ', MESSAGE: ' . rtrim($message);
}
$message = 'PID: ' . getmypid() . ' ' . rtrim($message);
cacti_log($message, true, 'EXPORT', $loglevel);
}
/* export_pre_ftp_upload - this function creates a global variable
of your pre-checked ftp credentials and settings that will be used
for the actual ftp transfer.
@arg $export - the export item structure */
function export_pre_ftp_upload(&$export) {
global $config, $aFtpExport;
$aFtpExport['server'] = $export['export_host'];
if (empty($aFtpExport['server'])) {
export_fatal($export, 'FTP Hostname is not expected to be blank!');
}
$aFtpExport['remotedir'] = $export['export_directory'];
if (empty($aFtpExport['remotedir'])) {
export_fatal($export, 'FTP Remote export path is not expected to be blank!');
}
$aFtpExport['port'] = $export['export_port'];
$aFtpExport['port'] = empty($aFtpExport['port']) ? '21' : $aFtpExport['port'];
$aFtpExport['username'] = $export['export_user'];
$aFtpExport['password'] = $export['export_password'];
if (empty($aFtpExport['username'])) {
$aFtpExport['username'] = 'Anonymous';
$aFtpExport['password'] = '';
export_log('Using Anonymous transfer method.');
}
if ($export['export_passive'] == 'on') {
$aFtpExport['passive'] = true;
export_log('Using passive transfer method.');
} else {
$aFtpExport['passive'] = false;
export_log('Using active transfer method.');
}
}
/* check_cacti_paths - this function is looking for bad export paths that
can potentially get the user in trouble. We avoid paths that can
get erased by accident.
@arg $export - the export item structure
@arg $export_path - the directory holding the export contents. */
function check_cacti_paths(&$export, $export_path) {
global $config;
$root_path = $config['base_path'];
/* check for bad directories within the cacti path */
if (strcasecmp($root_path, $export_path) < 0) {
$cacti_system_paths = array(
'include',
'lib',
'install',
'rra',
'log',
'scripts',
'plugins',
'images',
'resource');
foreach($cacti_system_paths as $cacti_system_path) {
if (substr_count(strtolower($export_path), strtolower($cacti_system_path)) > 0) {
export_fatal($export, "Export path '" . $export_path . "' is potentially within a Cacti system path '" . $cacti_system_path . "'. Can not continue.");
}
}
}
/* can not be the web root */
if ((strcasecmp($root_path, $export_path) == 0) &&
(read_config_option('export_type') == 'local')) {
export_fatal($export, "Export path '" . $export_path . "' is the Cacti web root. Can not continue.");
}
/* can not be a parent of the Cacti web root */
if (strncasecmp($root_path, $export_path, strlen($export_path))== 0) {
export_fatal($export, "Export path '" . $export_path . "' is a parent folder from the Cacti web root. Can not continue.");
}
}
function check_system_paths(&$export, $export_path) {
/* don't allow to export to system paths */
$system_paths = array(
'/boot',
'/lib',
'/usr',
'/usr/bin',
'/bin',
'/sbin',
'/usr/sbin',
'/usr/lib',
'/var/lib',
'/var/log',
'/root',
'/etc',
'windows',
'winnt',
'program files');
foreach($system_paths as $system_path) {
if (substr($system_path, 0, 1) == '/') {
if ($system_path == substr($export_path, 0, strlen($system_path))) {
export_fatal($export, "Export path '" . $export_path . "' is within a system path '" . $system_path . "'. Can not continue.");
}
} elseif (substr_count(strtolower($export_path), strtolower($system_path)) > 0) {
export_fatal($export, "Export path '" . $export_path . "' is within a system path '" . $system_path . "'. Can not continue.");
}
}
}
/* export_graphs - this function exports all the graphs and some html for
mgtg view data. these are all the graphs that are in scope for the export
be it a tree export, or a site export.
@arg $export - the export item structure
@arg $export_path - the directory holding the export contents. */
function export_graphs(&$export, $export_path) {
global $config;
/* check for bad directories */
check_cacti_paths($export, $export_path);
check_system_paths($export, $export_path);
if (strlen($export_path) < 3) {
export_fatal($export, "Export path is not long enough ! Export can not continue. ");
}
/* if the path is not a directory, don't continue */
clearstatcache();
if (!is_dir($export_path)) {
if (!mkdir($export_path)) {
export_fatal($export, "Unable to create path '" . $export_path . "'! Export can not continue.");
}
} else {
if ($export['export_clear'] == 'on') {
delTree($export_path, true);
}
}
clearstatcache();
if (!is_dir($export_path . '/graphs')) {
if (!mkdir($export_path . '/graphs')) {
export_fatal($export, "Unable to create path '" . $export_path . "/graphs'! Export can not continue.");
}
}
clearstatcache();
if (!is_writable($export_path)) {
export_fatal($export, "Unable to write to path '" . $export_path . "'! Export can not continue.");
}
clearstatcache();
if (!is_writable($export_path . '/graphs')) {
export_fatal($export, "Unable to write to path '" . $export_path . "/graphs'! Export can not continue.");
}
/* blank paths are not good */
if (strlen($export_path) == 0) {
export_fatal($export, 'Export path is null! Export can not continue.');
}
export_log('Running graph export');
$user = $export['export_effective_user'];
$trees = $export['graph_tree'];
$sites = $export['graph_site'];
$export_id = $export['id'];
$ntree = array();
$graphs = array();
$ngraph = array();
$limit = 1000;
$sql_where = '';
$hosts = '';
$total_rows = 0;
$exported = 0;
$metadata = array();
if ($user == 0) {
$user = -1;
}
export_debug('Export presentation is ' . $export['export_presentation']);
if ($export['export_presentation'] == 'tree') {
if ($trees != '0') {
$sql_where = 'gt.id IN(' . $trees . ')';
}
$trees = get_allowed_trees(false, false, $sql_where, 'name', '', $total_rows, $user);
export_debug('There are ' . cacti_sizeof($trees) . ' trees to export');
if (cacti_sizeof($trees)) {
foreach($trees as $tree) {
$ntree[] = $tree['id'];
export_debug('Tree \'' . $tree['name'] . '\' with id \'' . $tree['id'] . '\' is allowed');
}
}
if (cacti_sizeof($ntree)) {
$graphs = array_rekey(
db_fetch_assoc('SELECT DISTINCT local_graph_id
FROM graph_tree_items
WHERE local_graph_id > 0
AND graph_tree_id IN(' . implode(', ', $ntree) . ')'),
'local_graph_id', 'local_graph_id'
);
if (cacti_sizeof($graphs)) {
foreach($graphs as $local_graph_id) {
if (is_graph_allowed($local_graph_id, $user)) {
$ngraph[$local_graph_id] = $local_graph_id;
}
}
}
export_debug('There are ' . cacti_sizeof($graphs) . ' graphs not in hosts to export for all trees');
$hosts = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id)
FROM graph_tree_items
WHERE graph_tree_id IN(?)',
array(implode(', ', $ntree)));
export_debug('There are ' . cacti_sizeof(explode(',',$hosts)) . ' hosts to export for all trees');
if ($hosts != '') {
$sql_where = 'gl.host_id IN(' . $hosts . ')';
$graphs = get_allowed_graphs($sql_where, 'gtg.title_cache', '', $total_rows, $user);
if (cacti_sizeof($graphs)) {
foreach($graphs as $graph) {
if (is_graph_allowed($graph['local_graph_id'], $user)) {
$ngraph[$graph['local_graph_id']] = $graph['local_graph_id'];
}
}
}
}
export_debug('There are ' . cacti_sizeof($ngraph) . ' total graphs to export for all trees');
}
} else {
if ($sites != '0' && $sites != '') {
$hosts = db_fetch_cell('SELECT GROUP_CONCAT(id) FROM host WHERE site_id IN(' . $sites . ')');
} elseif ($sites == '0') {
$hosts = db_fetch_cell('SELECT GROUP_CONCAT(id) FROM host WHERE site_id > 0');
}
if ($hosts != '') {
$sql_where = 'gl.host_id IN(' . $hosts . ')';
}
$graphs = get_allowed_graphs($sql_where, 'gtg.title_cache', '', $total_rows, $user);
if (cacti_sizeof($graphs)) {
foreach($graphs as $graph) {
if (is_graph_allowed($graph['local_graph_id'], $user)) {
$ngraph[$graph['local_graph_id']] = $graph['local_graph_id'];
}
}
}
}
if (cacti_sizeof($ngraph)) {
if ($export['export_threads'] > 0) {
export_graph_clear_tasks();
}
foreach($ngraph as $local_graph_id) {
if ($export['export_threads'] > 0) {
export_graph_prepare_task($export_id, $user, $export_path, $local_graph_id);
} else {
export_graph_files($export, $user, $export_path, $local_graph_id);
}
$exported++;
if ($exported >= $export['graph_max'] && $export['graph_max'] > 0) {
db_execute_prepared('UPDATE graph_exports
SET last_error="WARNING: Max number of Graphs ' . $export['graph_max'] . ' reached",
last_errored=NOW()
WHERE id = ?',
array($export['id']));
break;
}
}
if ($export['export_threads'] > 0) {
export_graph_monitor_tasks($export);
}
}
return $exported;
}
function delTree($dir, $skip = false) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return ($skip ? 0 : rmdir($dir));
}
function export_is_task_running($pid) {
return posix_kill($pid, 0);
}
function export_graph_monitor_tasks($export) {
global $debug;
$max_threads = $export['export_threads'];
$script_file = dirname(__FILE__) .'/poller_export.php';
$script_php = read_config_option('path_php_binary');
$spawn_time = new DateTime();
while (true) {
$expire_time = new DateTime();
$expire_time->modify('-30 seconds');
$pids_left = db_fetch_cell('SELECT COUNT(*)
FROM graph_exports_tasks
WHERE status IN (0,1)');
//printf("%s: Found %s pids, spawn %s, expire %s\n", (new DateTime())->format('H:i:s'), $pids_left, $spawn_time->format('H:i:s'), $expire_time->format('H:i:s'));
if ($pids_left == 0) break;
if ($spawn_time < $expire_time) {
//printf("%s: Running failure checks\n", (new DateTime())->format('H:i:s'));
$pids_fail = db_fetch_cell_prepared('SELECT COUNT(*)
FROM graph_exports_tasks
WHERE status < 2
AND start_time != 0
AND start_time < ?',
array($expire_time->getTimestamp()));
if ($pids_fail > 0) {
db_execute_prepared('UPDATE graph_exports_tasks
SET status = 3
WHERE status = 1
AND start_time != 0
AND start_time < ?',
array($expire_time->getTimestamp()));
}
}
$pids_running = array_rekey(
db_fetch_assoc('SELECT DISTINCT id, pid
FROM graph_exports_tasks
WHERE status = 1'),
'id', 'pid'
);
$thread_run = cacti_sizeof($pids_running);
$thread_adj = $thread_run;
if ($thread_adj > 0 && $spawn_time < $expire_time) {
//printf("%s: Running adjustments checks\n", (new DateTime())->format('H:i:s'));
foreach ($pids_running as $id => $pid) {
if ($pid != 0 && !export_is_task_running($pid)) {
export_debug('TASKS Pid ' . $pid .' is not running, adjusting');
db_execute_prepared('UPDATE graph_exports_tasks
SET status = 4
WHERE status = 1
AND id = ?
AND pid = ?',
array($id, $pid));
$thread_adj--;
}
}
}
export_debug('TASKS ' . $thread_run . ' Database, ' . $thread_adj . ' Active');
if ($thread_adj < $max_threads) {
$wanted_count = $max_threads - $thread_adj;
//printf("%s: Spawning threads %s of %s\n", (new DateTime())->format('H:i:s'), $wanted_count, $max_threads);
$tasks = db_fetch_assoc('SELECT DISTINCT *
FROM graph_exports_tasks
WHERE status = 0
LIMIT ' . $wanted_count);
export_debug('TASKS ' . $wanted_count . ' available, ' . cacti_sizeof($tasks) . ' found');
if (cacti_sizeof($tasks) > 0) {
$spawn_time = new DateTime();
foreach ($tasks as $task) {
db_execute_prepared('UPDATE graph_exports_tasks
SET status = 1, start_time = ?
WHERE id = ?',
array(time(), $task['id']));
export_debug('TASKS Spawning task ' . $task['id'] . ' for Export[' . $task['export_id'] . '], Graph[' . $task['local_graph_id'] .']');
exec_background($script_php, '-q ' . $script_file . ' --thread=' . $task['id']);
}
}
}
sleep(2);
}
}
function export_graph_clear_tasks() {
db_execute('TRUNCATE TABLE graph_exports_tasks');
}
function export_graph_prepare_task($export_id, $user, $folder, $local_graph_id) {
export_debug('TASKS Preparing task for Export[' . $export_id . '], Graph[' . $local_graph_id .']');
// MJV: Do something here
db_execute_prepared('INSERT INTO graph_exports_tasks (export_id, local_graph_id, user, folder)
VALUES (?, ?, ?, ?)', array($export_id, $local_graph_id, $user, $folder));
}
function export_graph_start_task($task_id) {
$start = microtime(true);
$exports = 0;
$task = db_fetch_row_prepared('SELECT * FROM graph_exports_tasks
WHERE id = ?',
array($task_id));
if (!sizeof($task)) {
export_warn('TASKS Launched ' . $task_id . ' - Invalid ID, Aborting');
} else {
db_execute_prepared('UPDATE graph_exports_tasks
SET pid = ?
WHERE id = ?',
array(getmypid(), $task['id']));
export_debug('TASKS Launched ' . $task['id'] . ', exporting graph ' . $task['local_graph_id'] . ' as user \'' . $task['user'] . '\'');
$export = db_fetch_row_prepared('SELECT * FROM graph_exports
WHERE id = ?',
array($task['export_id']));
$exports = export_graph_files($export, $task['user'], $task['folder'], $task['local_graph_id']);
db_execute_prepared('UPDATE graph_exports_tasks
SET status = 2
WHERE id = ?',
array($task['id']));
}
$end = microtime(true);
$export_stats = sprintf('Time:%01.2f Exports:%s', $end - $start, $exports);
export_debug('THREAD STATS: ' . $export_stats);
}
/* export_graph_files - this function exports the actual files for a given graph
@arg $export - the export item structure
@arg $export_path - the directory holding the export contents. */
function export_graph_files($export, $user, $export_path, $local_graph_id) {
if ($user == 0) {
$user = -1;
}
/* open a pipe to rrdtool for writing */
$rrdtool_pipe = rrd_init();
export_debug('Exporting Graph ID: ' . $local_graph_id);
check_remove($export_path . '/graph_' . $local_graph_id . '.html');
if ($export['export_thumbs'] == 'on') {
/* settings for preview graphs */
$graph_data_array['export_filename'] = $export_path . '/graphs/thumb_' . $local_graph_id . '.png';
$graph_data_array['graph_height'] = $export['graph_height'];
$graph_data_array['graph_width'] = $export['graph_width'];
$graph_data_array['graph_nolegend'] = true;
$graph_data_array['export'] = true;
$graph_data_array['graph_theme'] = $export['export_theme'];
$graph_data_array['image_format'] = 'png';
export_log("Creating Graph Thumbnail '" . $graph_data_array['export_filename'] . "'");
check_remove($graph_data_array['export_filename']);
rrdtool_function_graph($local_graph_id, 0, $graph_data_array, $rrdtool_pipe, $metadata, $user);
unset($graph_data_array);
}
/* settings for preview graphs */
$graph_data_array['export_filename'] = $export_path . '/graphs/graph_' . $local_graph_id . '.png';
$graph_data_array['export'] = true;
$graph_data_array['graph_theme'] = $export['export_theme'];
$graph_data_array['image_format'] = 'png';