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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
|
#!/usr/bin/env php
<?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/ |
+-------------------------------------------------------------------------+
*/
require(__DIR__ . '/../site/include/cli_check.php');
chdir('..');
if ($config['poller_id'] > 1) {
print "FATAL: This utility is designed for the main Data Collector only" . PHP_EOL;
exit(1);
}
/* process calling arguments */
$parms = $_SERVER['argv'];
array_shift($parms);
$upgrade = false;
$create = false;
$loadopt = false;
$report = false;
$repair = false;
$altersopt = false;
if (cacti_sizeof($parms)) {
$shortopts = 'VvHh';
$longopts = array(
'create',
'load',
'report',
'upgrade',
'repair',
'alters',
'version',
'help'
);
$options = getopt($shortopts, $longopts);
foreach($options as $arg => $value) {
switch($arg) {
case 'create':
$create = true;
break;
case 'load':
$loadopt = true;
break;
case 'report':
$report = true;
break;
case 'repair':
$repair = true;
break;
case 'alters':
$altersopt = true;
break;
case 'upgrade':
$upgrade = true;
break;
case 'version':
case 'V':
case 'v':
display_version();
exit(0);
case 'help':
case 'H':
case 'h':
display_help();
exit(0);
default:
print "ERROR: Invalid Argument: ($arg)" . PHP_EOL . PHP_EOL;
display_help();
exit(1);
}
}
$db_version = db_fetch_cell('SELECT cacti FROM version');
if ($db_version != CACTI_VERSION && !$upgrade) {
$upgrade_required = true;
} else {
$upgrade_required = false;
}
if ($upgrade_required) {
print 'WARNING: Cacti must be upgraded first. Use the --upgrade option to perform that upgrade' . PHP_EOL;
exit(1);
} elseif ($db_version != CACTI_VERSION && $upgrade) {
upgrade_database();
}
if ($repair) {
repair_database();
} elseif ($create) {
create_tables();
} elseif ($report) {
report_audit_results();
} elseif ($altersopt) {
repair_database(false);
} elseif ($loadopt) {
load_audit_database();
} else {
display_help();
}
exit(0);
} else {
display_help();
exit(1);
}
function upgrade_database() {
global $config;
$start = microtime(true);
cacti_log('NOTE: Upgrading Cacti, this will take a few minutes.', true, 'UPGRADE');
$return_var = 0;
$output = array();
exec('php ' . $config['base_path'] . '/cli/upgrade_database.php --debug', $output, $return_var);
$end = microtime(true);
if ($return_var == 0) {
cacti_log(sprintf('NOTE: Cacti Upgrade succeeded in %.2f seconds', $end - $start), true, 'UPGRADE');
} else {
cacti_log('WARNING: Cacti Upgrade Encountered Errors. Messages below. Details are below, but also in Cacti upgrade log.', true, 'UPGRADE');
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
print implode(PHP_EOL, $output) . PHP_EOL;
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
}
$pistart = microtime(true);
// Upgrade plugins now
$plugins = glob($config['base_path'] . '/plugins/*', GLOB_ONLYDIR);
// Do syslog and thold first if found
$preorder[] = $config['base_path'] . '/plugins/thold';
$preorder[] = $config['base_path'] . '/plugins/syslog';
foreach($plugins as $p) {
if (strpos($p, 'thold') !== false) {
// Skip, upgrading this first
} elseif (strpos($p, 'syslog') !== false) {
// Skip, upgrading this second
} else {
$preorder[] = $p;
}
}
$plugins = $preorder;
if (cacti_sizeof($plugins)) {
if (!defined('IN_PLUGIN_INSTALL')) {
define('IN_PLUGIN_INSTALL', 1);
}
foreach($plugins as $plugin) {
$parts = explode('/', $plugin);
$pname = end($parts);
$ufunc1 = 'plugin_' . $pname . '_upgrade';
$ufunc2 = $pname . '_upgrade_database';
$ufunc3 = $pname . '_setup_table_new';
if (!plugin_installed($pname)) {
cacti_log("NOTE: Plugin $pname is not installed, skipping.", true, 'UPGRADE');
continue;
}
if (file_exists($plugin . '/INFO')) {
// See if the plugin requires upgrading
$info = parse_ini_file($plugin . '/INFO', true);
$version = $info['info']['version'];
$old = db_fetch_cell_prepared('SELECT version
FROM plugin_config
WHERE directory = ?',
array($pname));
if ($version != $old) {
if (file_exists($plugin . '/setup.php')) {
include_once($plugin . '/setup.php');
if (file_exists($plugin . '/includes/database.php')) {
include_once($plugin . '/includes/database.php');
}
// Always run the new function if it's there
// Some plugins don't upgrade in the proper way
if (function_exists($ufunc3)) {
cacti_log("NOTE: Running Plugin $pname install function due to some plugins not upgrading properly.", true, 'UPGRADE');
$ufunc3(true);
}
if (function_exists($ufunc2)) {
cacti_log("NOTE: Upgrading Plugin $pname from $old to $version using alternate upgrade path.", true, 'UPGRADE');
$ufunc2(true);
} elseif (function_exists($ufunc1)) {
cacti_log("NOTE: Upgrading Plugin $pname from $old to $version using standard upgrade path.", true, 'UPGRADE');
$ufunc1;
} else {
cacti_log("WARNING: Plugin $pname lacks an upgrade function.", true, 'UPGRADE');
}
if (file_exists($plugin . '/database_upgrade.php')) {
cacti_log("NOTE: Upgrading Plugin $pname from $old to $version using upgrade script.", true, 'UPGRADE');
$return_var = 0;
$output = array();
exec('php ' . $config['base_path'] . '/plugins/' . $pname . '/database_upgrade.php --type=large --force-ver=' . $old, $output, $return_var);
if ($return_var == 0) {
print implode(PHP_EOL, $output) . PHP_EOL;
cacti_log("NOTE: Cacti Plugin $pname Upgrade Succeeded.", true, 'UPGRADE');
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
print implode(PHP_EOL, $output) . PHP_EOL;
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
} else {
cacti_log("WARNING: Cacti Plugin $pname Upgrade Encountered Errors.", true, 'UPGRADE');
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
print implode(PHP_EOL, $output) . PHP_EOL;
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
}
}
} else {
cacti_log("WARNING: Plugin $pname lacks a setup file.", true, 'UPGRADE');
}
} else {
cacti_log("NOTE: Plugin $pname Does not Require Upgrade", true, 'UPGRADE');
}
} else {
cacti_log("WARNING: Plugin $pname lacks an INFO file. Can not upgrade!", true, 'UPGRADE');
}
}
}
// Unregister plugins that no longer exist
// We keep legacy tables due to potential
// issues.
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
cacti_log('NOTE: Pruning invalid and deprecated plugins while preserving tables', true, 'UPGRADE');
$plugins = db_fetch_assoc('SELECT directory FROM plugin_config');
if (cacti_sizeof($plugins)) {
foreach($plugins as $p) {
$pname = $p['directory'];
if (!file_exists($config['base_path'] . '/plugins/' . $pname . '/INFO')) {
if (file_exists($config['base_path'] . '/plugins/' . $pname . '/setup.php')) {
cacti_log("NOTE: Uninstalling Plugin $pname which is not supported. Preserving tables.", true, 'UPGRADE');
api_plugin_uninstall($pname, false);
} else {
cacti_log("NOTE: Uninstalling Plugin $pname which is not supported and setup.php not found. Preserving tables.", true, 'UPGRADE');
db_execute_prepared('DELETE FROM plugin_config WHERE directory = ?', array($pname));
db_execute_prepared('DELETE FROM plugin_db_changes WHERE plugin = ?', array($pname));
db_execute_prepared('DELETE FROM plugin_hooks WHERE name = ?', array($pname));
db_execute_prepared('DELETE FROM plugin_realms WHERE plugin = ?', array($pname));
}
}
}
}
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
$end = microtime(true);
cacti_log(sprintf('NOTE: Cacti Plugin Upgrades completed in %.2f seconds', $end - $pistart), true, 'UPGRADE');
cacti_log(sprintf('NOTE: Audit Upgrade completed in %.2f seconds.', $end - $start), true, 'UPGRADE');
}
function plugin_installed($plugin) {
$installed = db_fetch_cell_prepared('SELECT COUNT(*)
FROM plugin_config
WHERE directory = ?
AND status = 1',
array($plugin));
return $installed ? true:false;
}
function repair_database($run = true) {
global $altersopt, $database_default;
$alters = report_audit_results(false);
$good = 0;
$bad = 0;
if (cacti_sizeof($alters)) {
foreach($alters as $table => $changes) {
$tblinfo = db_fetch_row_prepared('SELECT ENGINE, SUBSTRING_INDEX(TABLE_COLLATION, "_", 1) AS COLLATION
FROM information_schema.tables
WHERE TABLE_SCHEMA = ?
AND TABLE_NAME = ?',
array($database_default, $table));
if (isset($tblinfo['COLLATION'])) {
$collation = $tblinfo['COLLATION'];
} else {
$collation = 'utf8mb4';
}
if ($tblinfo['ENGINE'] == 'MyISAM') {
$suffix = ",\n ENGINE=InnoDB ROW_FORMAT=Dynamic CHARSET=" . $collation;
} else {
$suffix = ",\n ROW_FORMAT=Dynamic CHARSET=" . $collation;
}
$sql = 'ALTER TABLE `' . $table . "`\n " . implode(",\n ", $changes) . $suffix . ';';
if ($run) {
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
print 'Executing Alter for Table : ' . $table;
$result = db_execute($sql);
if ($result) {
$good++;
print ' - Success' . PHP_EOL;
} else {
$bad++;
print ' - Failed' . PHP_EOL;
print $sql . PHP_EOL;
}
} else {
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
print '-- Proposed Alter for Table : ' . $table . PHP_EOL . PHP_EOL;
print $sql . PHP_EOL . PHP_EOL;
}
}
}
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
if ($bad == 0 && $good == 0) {
print ($altersopt ? '-- ' : '') . 'Repair Completed! No changes performed.' . PHP_EOL;
} elseif ($bad) {
print 'Repair Completed! ' . $good . ' Alters succeeded and ' . $bad . ' failed!' . PHP_EOL;
} else {
print 'Repair Completed! All ' . $good . ' Alters succeeded!' . PHP_EOL;
}
}
function report_audit_results($output = true) {
global $database_default, $altersopt;
$db_name = 'Tables_in_' . $database_default;
create_tables();
$tables = db_fetch_assoc('SHOW TABLES');
$alters = array();
$cols = array(
'table_type' => 'Type',
'table_null' => 'Null',
'table_key' => 'Key',
'table_default' => 'Default',
'table_extra' => 'Extra'
);
$idxs = array(
'idx_non_unique' => 'Non_unique',
'idx_key_name' => 'Key_name',
'idx_seq_in_index' => 'Seq_in_index',
'idx_column_name' => 'Column_name',
'idx_packed' => 'Packed',
'idx_comment' => 'Comment'
);
if (cacti_sizeof($tables)) {
foreach($tables as $table) {
$alter_cmds = array();
$table_name = $table[$db_name];
$status = db_fetch_row('SHOW TABLE STATUS LIKE "' . $table_name . '"');
if ($status['Collation'] == 'utf8mb4_unicode_ci' || $status['Collation'] == 'utf8_general_ci') {
$collation = 'utf8';
} else {
$collation = 'latin';
}
if ($output) {
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
printf('Checking Table: %-45s', '\'' . $table_name . '\'');
} else {
printf(($altersopt ? '-- ' : '') . 'Scanning Table: %-45s', '\'' . $table_name . '\'');
}
$table_exists = db_fetch_cell_prepared('SELECT COUNT(*)
FROM table_columns
WHERE table_name = ?',
array($table_name));
if (!$table_exists) {
$plugin_table = db_fetch_row_prepared('SELECT *
FROM plugin_db_changes
WHERE `table` = ?
AND method = ?',
array($table_name, 'create'));
if (!cacti_sizeof($plugin_table)) {
if ($output) {
print ' - Does not Exist. Possible Plugin' . PHP_EOL;
continue;
}
}
if ($output) {
print ' - Plugin Detected' . PHP_EOL;
continue;
} else {
print ' - Completed' . PHP_EOL;
}
} elseif (!$output) {
print ' - Completed' . PHP_EOL;
}
/* Column scanning comes in two parts. In the first part, we
* scan the columns in the current database to the saved schema
* In the second pass, we look for the columns from the saved
* schema to look for missing ones.
*/
$i = 1;
$errors = 0;
$warnings = 0;
$col_added = array();
$col_alter = array();
$columns = db_fetch_assoc('SHOW COLUMNS IN ' . $table_name);
$exists = db_fetch_cell_prepared('SELECT COUNT(*) FROM table_columns
WHERE table_name = ?',
array($table_name));
if ($exists) {
if (cacti_sizeof($columns)) {
foreach($columns as $c) {
$sequence_off = false;
$dbc = db_fetch_row_prepared('SELECT *
FROM table_columns
WHERE table_name = ?
AND table_field = ?',
array($table_name, $c['Field']));
if (!cacti_sizeof($dbc)) {
$plugin_column = db_fetch_row_prepared('SELECT *
FROM plugin_db_changes
WHERE `table` = ?
AND `column` = ?
AND method = ?',
array($table_name, $c['Field'], 'addcolumn'));
if (!cacti_sizeof($plugin_column)) {
if ($output) {
print PHP_EOL . 'WARNING Col: \'' . $c['Field'] . '\', does not exist in default Cacti. Plugin possible';
}
$warnings++;
}
} else {
foreach($cols as $dbcol => $col) {
if ($col == 'Type' && $dbc[$dbcol] == 'text') {
if ($collation == 'latin') {
$dbc[$dbcol] = 'mediumtext';
}
}
/* work around MariaDB compatibility issue */
$c[$col] = ! $c[$col] ?: str_replace('current_timestamp()', 'CURRENT_TIMESTAMP', $c[$col]);
$dbc[$dbcol] = ! $dbc[$dbcol] ?: str_replace('current_timestamp()', 'CURRENT_TIMESTAMP',$dbc[$dbcol]);
/* work around MySQL 8.x simplified int columns */
if (strpos($dbc[$dbcol], 'int(') !== false) {
// Get the integer first
$parts = explode('(', $dbc[$dbcol]);
$adbccol = $parts[0];
// Get attributes next
$parts = explode(' ', $parts[1], 2);
if (isset($parts[1])) {
$adbccol .= ' ' . $parts[1];
}
$adbccol = trim($adbccol);
} else {
$adbccol = $dbc[$dbcol];
}
/* Work Around for MySQL 8 */
$c[$col] = trim(str_replace('DEFAULT_GENERATED', '', $c[$col]));
if (($c[$col] != $dbc[$dbcol] && $c[$col] != $adbccol) && $c[$col] != 'mediumtext') {
if ($output) {
if ($col != 'Key') {
print PHP_EOL . 'ERROR Col: \'' . $c['Field'] . '\', Attribute \'' . $col . '\' invalid. Should be: \'' . $dbc[$dbcol] . '\', Is: \'' . $c[$col] . '\'';
}
}
if (array_search($dbc['table_field'], $col_alter) === false) {
$alter_cmds[] = make_column_alter($table_name, $dbc);
$col_alter[] = $dbc['table_field'];
$errors++;
}
}
}
}
$i++;
}
}
/* In this pass, we will gather the default schema and look for
* missing information.
*/
$db_columns = db_fetch_assoc_prepared('SELECT *
FROM table_columns
WHERE table_name = ?',
array($table_name));
if (cacti_sizeof($db_columns)) {
foreach($db_columns as $dbc) {
if (!db_column_exists($table_name, $dbc['table_field'])) {
if (array_search($dbc['table_field'], $col_added) === false) {
if ($output) {
print PHP_EOL . 'WARNING Col: \'' . $dbc['table_field'] . '\' is missing from \'' . $table_name . '\'';
}
$alter_cmds[] = make_column_add($table_name, $dbc);
$col_added[] = $dbc['table_field'];
$errors++;
}
}
}
}
/* Index scanning comes in two parts. In the first part, we
* scan the indexes in the current database to the saved schema
* In the second pass, we look for the indexes from the saved
* schema to look for missing ones.
*/
$indexes = db_fetch_assoc('SHOW INDEXES IN ' . $table_name);
$idx_added = array();
$idx_dropped = array();
if (cacti_sizeof($indexes)) {
foreach($indexes as $i) {
$key_exists = db_fetch_cell_prepared('SELECT COUNT(*)
FROM table_indexes
WHERE idx_table_name = ?
AND idx_key_name = ?',
array($i['Table'], $i['Key_name']));
$dbc = db_fetch_row_prepared('SELECT *
FROM table_indexes
WHERE idx_table_name = ?
AND idx_key_name = ?
AND idx_seq_in_index = ?
AND idx_column_name = ?
ORDER BY idx_seq_in_index',
array($i['Table'], $i['Key_name'], $i['Seq_in_index'], $i['Column_name']));
if (!cacti_sizeof($dbc)) {
if ($key_exists) {
// Ignore till Phase II
} elseif (array_search($i['Key_name'], $idx_dropped) === false) {
// Primary keys come in Phase II
if ($i['Key_name'] != 'PRIMARY') {
if ($output) {
print PHP_EOL . 'WARNING Index: \'' . $i['Key_name'] . '\', does not exist in default Cacti. Dropping.';
}
$alter_cmds[] = 'DROP INDEX ' . $i['Key_name'];
$idx_dropped[] = $i['Key_name'];
$errors++;
}
}
} else {
foreach($idxs as $dbidx => $idx) {
if ($i[$idx] != $dbc[$dbidx]) {
// Primary keys come in Phase II
if ($i['Key_name'] != 'PRIMARY') {
if (array_search($i['Key_name'], $idx_added) === false) {
if ($output) {
print PHP_EOL . 'ERROR Index: \'' . $i['Key_name'] . '\', Attribute \'' . $idx . '\' invalid. Should be: \'' . $dbc[$dbidx] . '\', Is: \'' . $i[$idx] . '\'';
}
$alter_cmds = array_merge($alter_cmds, make_index_alter($table_name, $i['Key_name']));
$idx_added[] = $i['Key_name'];
$errors++;
}
}
}
}
}
}
}
/* check for missing indexes and add them */
$db_indexes = db_fetch_assoc_prepared('SELECT *
FROM table_indexes
WHERE idx_table_name = ?',
array($table_name));
if (cacti_sizeof($db_indexes)) {
foreach($db_indexes as $i) {
if (!db_index_exists($table_name, $i['idx_key_name'])) {
if (array_search($i['idx_key_name'], $idx_added) === false) {
if ($output) {
print PHP_EOL . 'ERROR Index: \'' . $i['idx_key_name'] . '\', is missing from \'' . $table_name . '\'';;
}
$alter_cmds = array_merge($alter_cmds, make_index_alter($table_name, $i['idx_key_name']));
$idx_added[] = $i['idx_key_name'];
$errors++;
}
} else {
$prop_seq = db_fetch_cell_prepared('SELECT COUNT(*)
FROM table_indexes
WHERE idx_table_name = ?
AND idx_key_name = ?',
array($table_name, $i['idx_key_name']));
$curr_seq = get_sequence_count($table_name, $i['idx_key_name']);
$curr_column_seq = get_column_sequence_number($table_name, $i['idx_key_name'], $i['idx_column_name']);
//print PHP_EOL . "Prop Seq:" . $prop_seq . ", Curr Seq:" . $curr_seq . PHP_EOL;
if ($curr_seq != $prop_seq || $curr_column_seq != $i['idx_seq_in_index']) {
if (array_search($i['idx_key_name'], $idx_dropped) === false) {
if ($output) {
if ($curr_seq != $prop_seq) {
print PHP_EOL . 'WARNING Index: \'' . $i['idx_key_name'] . '\', has differing number of columns. Dropping.';
}
if ($curr_column_seq != $i['idx_seq_in_index']) {
print PHP_EOL . 'WARNING Index: \'' . $i['idx_key_name'] . '\', has resequenced columns. Dropping.';
}
}
$alter_cmds = array_merge($alter_cmds, make_index_alter($table_name, $i['idx_key_name']));
$idx_added[] = $i['idx_key_name'];
$idx_dropped[] = $i['idx_key_name'];
$errors++;
}
}
}
}
}
if ($output) {
if ($errors || $warnings) {
print PHP_EOL . PHP_EOL . 'ERRORS: ' . $errors . ', WARNINGS: ' . $warnings . PHP_EOL;
} else {
print ' - Clean' . PHP_EOL;
}
}
if (cacti_sizeof($alter_cmds)) {
$alters[$table_name] = $alter_cmds;
}
}
}
}
if ($output) {
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
if (cacti_sizeof($alters)) {
print 'ERRORS are fixable using the --repair option. WARNINGS will not be repaired' . PHP_EOL;
print 'due to ambiguous use of the column.' . PHP_EOL;
} else {
print 'Audit was clean, no errors or warnings' . PHP_EOL;
}
print '---------------------------------------------------------------------------------------------' . PHP_EOL;
}
return $alters;
}
function make_column_props(&$dbc) {
$alter_cmd = '';
if (isset($dbc['table_default'])) {
$dbc['table_default'] = str_replace('current_timestamp()', 'CURRENT_TIMESTAMP', $dbc['table_default']);
}
if (isset($dbc['table_extra'])) {
$dbc['table_extra'] = str_replace('current_timestamp()', 'CURRENT_TIMESTAMP', $dbc['table_extra']);
$dbc['table_extra'] = trim(str_replace('DEFAULT_GENERATED', '', $dbc['table_extra']));
}
if ($dbc['table_null'] == 'YES') {
if ($dbc['table_default'] == 'NULL') {
// Ignore
} elseif ($dbc['table_default'] === NULL) {
// Ignore
} elseif ($dbc['table_default'] === '') {
// Ignore
} else {
$alter_cmd .= ' DEFAULT "' . $dbc['table_default'] . '"';
}
} elseif ($dbc['table_default'] !== 'NULL' && $dbc['table_default'] !== NULL) {
if ($dbc['table_default'] == 'CURRENT_TIMESTAMP') {
$alter_cmd .= ' DEFAULT CURRENT_TIMESTAMP';
} elseif ($dbc['table_extra'] != 'auto_increment') {
if (strpos($dbc['table_type'], 'int(') !== false && $dbc['table_default'] == '') {
$alter_cmd .= ' DEFAULT "0"';
} else {
$alter_cmd .= ' DEFAULT \'' . $dbc['table_default'] . '\'';
}
}
}
if ($dbc['table_extra'] != '') {
$alter_cmd .= ' ' . $dbc['table_extra'];
}
return $alter_cmd;
}
function make_column_alter($table, $dbc) {
$alter_cmd = 'MODIFY COLUMN `' . $dbc['table_field'] . '` ' .
$dbc['table_type'] . ($dbc['table_null'] == 'NO' ? ' NOT NULL':'');
$alter_cmd .= make_column_props($dbc);
return $alter_cmd;
}
function make_column_add($table, $dbc) {
$after = get_previous_column($table, $dbc['table_field']);
if ($after != 'first') {
$after = 'AFTER `' . $after . '`';
}
$alter_cmd = 'ADD COLUMN `' . $dbc['table_field'] . '` ' .
$dbc['table_type'] . ($dbc['table_null'] == 'NO' ? ' NOT NULL':'');
$alter_cmd .= make_column_props($dbc);
$alter_cmd .= ' ' . $after;
return $alter_cmd;
}
function get_previous_column($table, $column) {
$sequence = db_fetch_cell_prepared('SELECT table_sequence
FROM table_columns
WHERE table_name = ?
AND table_field = ?',
array($table, $column));
if (!empty($sequence)) {
if ($sequence == 1) {
return 'first';
} else {
$previous = db_fetch_cell_prepared('SELECT table_field
FROM table_columns
WHERE table_name = ?
AND table_sequence = ?',
array($table, $sequence - 1));
return $previous;
}
}
}
function make_index_alter($table, $key) {
$alter_cmds = array();
$alter_cmd = '';
$primary_dropped = false;
$parts = db_fetch_assoc_prepared('SELECT *
FROM table_indexes
WHERE idx_table_name = ?
AND idx_key_name = ?
ORDER BY idx_seq_in_index',
array($table, $key));
$sequence_cnt = get_sequence_count($table, $key);
//print PHP_EOL . "NOTE: INDEX KEY is $key, Baseline Sequence: " . cacti_sizeof($parts) . ", Actual Sequence: $sequence_cnt" . PHP_EOL;
if ($sequence_cnt != cacti_sizeof($parts) && $sequence_cnt > 0) {
if ($key == 'PRIMARY') {
$primary_dropped = true;
$alter_cmd .= "DROP PRIMARY KEY,\n ";
} else {
$alter_cmd .= "DROP INDEX `" . $key . "`,\n ";
}
} elseif (db_index_exists($table, $key)) {
if ($key == 'PRIMARY') {
$primary_dropped = true;
$alter_cmd .= "DROP PRIMARY KEY,\n ";
} else {
$alter_cmd .= "DROP INDEX `" . $key . "`,\n ";
}
}
if (cacti_sizeof($parts)) {
$i = 0;
foreach($parts as $p) {
if ($i == 0 && $p['idx_key_name'] == 'PRIMARY') {
if ($primary_dropped == false) {
$alter_cmd .= "DROP PRIMARY KEY,\n ";
}
$alter_cmd .= 'ADD PRIMARY KEY (';
} elseif ($i == 0) {
if ($p['idx_non_unique'] == 1) {
$alter_cmd .= 'ADD INDEX `' . $key . '` (';
} else {
$alter_cmd .= 'ADD UNIQUE INDEX `' . $key . '` (';
}
}
$alter_cmd .= ($i > 0 ? ',':'') . '`' . $p['idx_column_name'] . '`';
$i++;
}
$alter_cmd .= ') USING ' . $p['idx_index_type'];
$alter_cmds[] = $alter_cmd;
}
return $alter_cmds;
}
function get_sequence_count($table, $index) {
$indexes = db_fetch_assoc("SHOW INDEXES IN $table");
$sequence_cnt = 0;
if (cacti_sizeof($indexes)) {
foreach($indexes as $i) {
if ($index == $i['Key_name']) {
$sequence_cnt++;
}
}
}
return $sequence_cnt;
}
function get_column_sequence_number($table, $index, $column) {
$indexes = db_fetch_assoc("SHOW INDEXES IN $table");
if (cacti_sizeof($indexes)) {
foreach($indexes as $i) {
$sequence = $i['Seq_in_index'];
if ($i['Key_name'] == $index) {
if ($i['Column_name'] == $column) {
return $sequence;
}
}
}
}
return -1;
}
function create_tables($load = true) {
global $config, $database_default, $database_username, $database_password, $database_port, $database_hostname;
global $altersopt;
db_execute("CREATE TABLE IF NOT EXISTS table_columns (
table_name varchar(50) NOT NULL,
table_sequence int(10) unsigned NOT NULL,
table_field varchar(50) NOT NULL,
table_type varchar(50) default NULL,
table_null varchar(10) default NULL,
table_key varchar(4) default NULL,
table_default varchar(50) default NULL,
table_extra varchar(128) default NULL,
PRIMARY KEY (table_name, table_sequence, table_field))
ENGINE=InnoDB
COMMENT='Holds Default Cacti Table Definitions'");
$exists_columns = db_table_exists('table_columns');
if (!$exists_columns) {
print "Failed to create 'table_columns'";
exit;
}
db_execute("CREATE TABLE IF NOT EXISTS table_indexes (
idx_table_name varchar(50) NOT NULL,
idx_non_unique int(10) unsigned default NULL,
idx_key_name varchar(128) NOT NULL,
idx_seq_in_index int(10) unsigned NOT NULL,
idx_column_name varchar(50) NOT NULL,
idx_collation varchar(10) default NULL,
idx_cardinality int(10) unsigned default NULL,
idx_sub_part varchar(50) default NULL,
idx_packed varchar(128) default NULL,
idx_null varchar(10) default NULL,
idx_index_type varchar(20) default NULL,
idx_comment varchar(128) default NULL,
PRIMARY KEY (idx_table_name, idx_key_name, idx_seq_in_index, idx_column_name))
ENGINE=InnoDB
COMMENT='Holds Default Cacti Index Definitions'");
$exists_indexes = db_table_exists('table_indexes');
if (!$exists_indexes) {
print "Failed to create 'table_indexes'";
exit;
}
if ($load) {
db_execute('TRUNCATE table_columns');
db_execute('TRUNCATE table_indexes');
$output = array();
$error = 0;
if (file_exists($config['base_path'] . '/docs/audit_schema.sql')) {
exec('mysql' .
' -u' . cacti_escapeshellarg($database_username) .
' -p' . cacti_escapeshellarg($database_password) .
' -h' . cacti_escapeshellarg($database_hostname) .
' -P' . cacti_escapeshellarg($database_port) .
' ' . $database_default .
' < ' . $config['base_path'] . '/docs/audit_schema.sql', $output, $error);
if ($error == 0) {
print ($altersopt ? '-- ' : '') . 'SUCCESS: Loaded the Audit Schema' . PHP_EOL;
} else {
print 'FATAL: Failed Load the Audit Schema' . PHP_EOL;
print 'ERROR: ' . implode(",\n ", $output) . PHP_EOL;
}
} else {
print 'FATAL: Failed to find Audit Schema' . PHP_EOL;
}
}
}
function load_audit_database() {
global $config, $database_default, $database_username, $database_password;
$db_name = 'Tables_in_' . $database_default;
create_tables(false);
db_execute('TRUNCATE table_columns');
db_execute('TRUNCATE table_indexes');
$tables = db_fetch_assoc('SHOW TABLES');
if (cacti_sizeof($tables)) {
foreach($tables as $table) {
$table_name = $table[$db_name];
$columns = db_fetch_assoc('SHOW COLUMNS IN ' . $table_name);
$indexes = db_fetch_assoc('SHOW INDEXES IN ' . $table_name);
print 'Importing Table: ' . $table_name;
$i = 1;
if (cacti_sizeof($columns)) {
foreach($columns as $c) {
db_execute_prepared('INSERT INTO table_columns
(table_name, table_sequence, table_field, table_type, table_null, table_key, table_default, table_extra)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
array(
$table_name,
$i,
$c['Field'],
$c['Type'],
$c['Null'],
$c['Key'],
$c['Default'],
$c['Extra']
)
);
$i++;
}
}
print ' - Done' . PHP_EOL;
if (cacti_sizeof($indexes)) {
foreach($indexes as $i) {
db_execute_prepared('INSERT INTO table_indexes
(idx_table_name, idx_non_unique, idx_key_name, idx_seq_in_index, idx_column_name,
idx_collation, idx_cardinality, idx_sub_part, idx_packed, idx_null, idx_index_type, idx_comment)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
array(
$i['Table'],
$i['Non_unique'],
$i['Key_name'],
$i['Seq_in_index'],
$i['Column_name'],
$i['Collation'],
$i['Cardinality'],
$i['Sub_part'],
$i['Packed'],
$i['Null'],
$i['Index_type'],
$i['Comment']
)
);
}
}
}
}
if (is_dir($config['base_path'] . '/docs')) {
print PHP_EOL . 'Exporting Table Audit Table Creation Logic to ' . $config['base_path'] . '/docs/audit_schema.sql' . PHP_EOL;
$retval = db_dump_data($database_default, 'table_columns table_indexes', array(), $config['base_path'] . '/docs/audit_schema.sql');
if ($retval) {
print 'Finished Creating Audit Schema with ERROR' . PHP_EOL . PHP_EOL;
} else {
print 'Finished Creating Audit Schema' . PHP_EOL . PHP_EOL;
}
} else {
print PHP_EOL . 'FATAL: Docs directory does not exist!' . PHP_EOL . PHP_EOL;
}
}
/* display_version - displays version information */
function display_version() {
$version = get_cacti_cli_version();
print "Cacti Database Audit Utility, Version $version, " . COPYRIGHT_YEARS . PHP_EOL;
}
function display_help() {
display_version();
print PHP_EOL . 'usage: audit_database.php --report | --repair [ --upgrade ]' . PHP_EOL . PHP_EOL;
print 'Cacti utility for auditing and correcting your Cacti database. This utility can' . PHP_EOL;
print 'will scan your Cacti database and report any problems in the schema that it finds.' . PHP_EOL . PHP_EOL;
print 'Options:' . PHP_EOL;
print ' --report - Report on any issues found in the audit of the database' . PHP_EOL;
print ' --repair - Repair any issues found during the audit of the database' . PHP_EOL;
print ' --upgrade - Upgrade the Cacti database before running' . PHP_EOL . PHP_EOL;
print 'Developer Options:' . PHP_EOL;
print ' --create - Initialize or Re-initialize the Audit Schema tables.' . PHP_EOL;
print ' --load - Take a pristine Cacti install and create Audit Schema and file.' . PHP_EOL;
print ' --alters - Print out all the alter commands vs. executing for debugging.' . PHP_EOL . PHP_EOL;
}
|