function RestartMySQL() { mysql_admin_mysql(1, "Restarting MySQL service...", null, __FILE__, __LINE__); system("/etc/init.d/mysql restart --force --framework=" . __FILE__); echo "Type Enter key to exit.\n"; $answer = trim(strtolower(fgets(STDIN))); menu(); }
function mysqld_perso_save() { $datas = base64_decode($_GET["mysqld-perso-save"]); @file_put_contents("/etc/artica-postfix/my.cnf.mysqld", trim($datas)); $unix = new unix(); $nohup = $unix->find_program("nohup"); mysql_admin_mysql(1, "Restarting MySQL service...", null, __FILE__, __LINE__); $cmd = trim("{$nohup} /etc/init.d/mysql restart --framework=" . __FILE__ . " >/dev/null 2>&1 &"); shell_exec($cmd); writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__); }
function clean_squid_stats_dbs() { $sock = new sockets(); $DisableArticaProxyStatistics = $sock->GET_INFO("DisableArticaProxyStatistics"); $CleanArticaSquidDatabases = $sock->GET_INFO("CleanArticaSquidDatabases"); if (!is_numeric($DisableArticaProxyStatistics)) { $DisableArticaProxyStatistics = 0; } if (!is_numeric($CleanArticaSquidDatabases)) { $CleanArticaSquidDatabases = 0; } if (!$GLOBALS["FORCE"]) { if ($CleanArticaSquidDatabases == 0) { echo "Option is not activated...\n"; return; } } $q = new mysql_squid_builder(); $tables = $q->LIST_TABLES_DAYS(); $rows = 0; $count_tables = 0; while (list($num, $table) = each($tables)) { $rows = $rows + $q->COUNT_ROWS($table); if ($GLOBALS["VERBOSE"]) { echo " Delete table {$table} {$rows} rows \n"; } $count_tables++; $q->DELETE_TABLE($table); } $tables = $q->LIST_TABLES_DAYS_BLOCKED(); while (list($num, $table) = each($tables)) { $rows = $rows + $q->COUNT_ROWS($table); if ($GLOBALS["VERBOSE"]) { echo " Delete table {$table} {$rows} rows \n"; } $count_tables++; $q->DELETE_TABLE($table); } $tables = $q->LIST_TABLES_MEMBERS(); while (list($num, $table) = each($tables)) { $rows = $rows + $q->COUNT_ROWS($table); if ($GLOBALS["VERBOSE"]) { echo " Delete table {$table} {$rows} rows \n"; } $count_tables++; $q->DELETE_TABLE($table); } $tables = $q->LIST_TABLES_MONTH(); while (list($num, $table) = each($tables)) { $rows = $rows + $q->COUNT_ROWS($table); if ($GLOBALS["VERBOSE"]) { echo " Delete table {$table} {$rows} rows \n"; } $count_tables++; $q->DELETE_TABLE($table); } $tables = $q->LIST_TABLES_WEEKS(); while (list($num, $table) = each($tables)) { $rows = $rows + $q->COUNT_ROWS($table); if ($GLOBALS["VERBOSE"]) { echo " Delete table {$table} {$rows} rows \n"; } $count_tables++; $q->DELETE_TABLE($table); } $q = new mysql_catz(); $tables = $q->LIST_TABLES_CATEGORIES(); while (list($num, $table) = each($tables)) { $rows = $rows + $q->COUNT_ROWS($table); if ($GLOBALS["VERBOSE"]) { echo " Delete table {$table} {$rows} rows \n"; } $count_tables++; $q->DELETE_TABLE($table); } $q = new mysql(); if ($q->DATABASE_EXISTS("catz")) { $q->DELETE_DATABASE("catz"); } if ($count_tables > 0) { mysql_admin_mysql(1, "Restarting MySQL service...", null, __FILE__, __LINE__); shell_exec("/etc/init.d/mysql restart"); } $sock->TOP_NOTIFY("{$count_tables} statistics tables as been deleted with {$rows} rows", "info"); //print_r($tables); }
function backup($ID) { $date_start = time(); $sock = new sockets(); $q = new mysql(); $unix = new unix(); $users = new usersMenus(); $GLOBALS["RESOURCE_MOUNTED"] = true; $sql = "SELECT * FROM backup_schedules WHERE ID='{$ID}'"; if ($GLOBALS["VERBOSE"]) { backup_events($ID, "initialization", "{$sql}", __LINE__); } $mount_path = "/opt/artica/mounts/backup/{$ID}"; if (!$q->TABLE_EXISTS("backup_storages", "artica_backup", true)) { $q->BuildTables(); if (!$q->TABLE_EXISTS("backup_storages", "artica_backup", true)) { backup_events($ID, "initialization", "ERROR, backup_storages, no such table", __LINE__); return; } } $servername = $users->fqdn; $servername = str_replace('.(none)', "", $servername); $servername = str_replace(')', "", $servername); $servername = str_replace('(', "", $servername); $GLOBALS["MYSERVERNAME"] = $servername; $ExecBackupDeadAfterH = $sock->GET_INFO("ExecBackupDeadAfterH"); if (!is_numeric($ExecBackupDeadAfterH)) { $ExecBackupDeadAfterH = 2; } if ($ExecBackupDeadAfterH < 2) { $ExecBackupDeadAfterH = 2; } $ExecBackupDeadAfterH = $ExecBackupDeadAfterH * 60; $ligne = @mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup")); if (!$q->ok) { send_email_events("Backup Task {$ID}:: Mysql database error !", "Aborting backup\n{$q->mysql_error}", "backup"); backup_events($ID, "initialization", "ERROR, Mysql database error\n{$q->mysql_error}", __LINE__); return false; } if (!$GLOBALS["ONNLY_MOUNT"]) { $pid = $ligne["pid"]; if ($unix->process_exists($pid)) { $time = $unix->PROCCESS_TIME_MIN($pid); if ($time > $ExecBackupDeadAfterH) { send_email_events("Backup Task {$ID}:: Already instance {$pid} running since {$time}Mn", "The old process was killed and a new backup task will be performed\nstatus:\n\n{$unix->proc_status}", "backup"); } else { send_email_events("Backup Task {$ID}:: Already instance {$pid} running since {$time}Mn", "Aborting backup\n{$unix->proc_status}", "backup"); backup_events($ID, "initialization", "ERROR, Already instance {$pid} running since {$time}Mn", $unix->proc_status); return false; } } } $sql = "UPDATE backup_schedules set pid='" . getmypid() . "' WHERE ID='{$ID}'"; $q->QUERY_SQL($sql, "artica_backup"); $ressources = unserialize(base64_decode($ligne["datasbackup"])); if (count($ressources) == 0) { backup_events($ID, "initialization", "ERROR,No source specified"); send_email_events("Backup Task {$ID}:: No source specified", "Aborting backup", "backup"); return false; } if ($ressources["OPTIONS"]["STOP_IMAP"] == 1) { $GLOBALS["NO_STOP_CYRUS"] = " --no-cyrus-stop"; } $backup = new backup_protocols(); $resource_type = $ligne["resource_type"]; $pattern = $ligne["pattern"]; $first_ressource = $backup->extractFirsRessource($ligne["pattern"]); $container = $ligne["container"]; backup_events($ID, "initialization", "resource: {$resource_type} -> {$first_ressource}", __LINE__); if ($resource_type == null) { backup_events($ID, "initialization", "ERROR,No resource specified"); send_email_events("Backup Task {$ID}:: No resource specified !", "Aborting backup", "backup"); return false; } if ($resource_type == "smb") { $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $mounted_path_sep = "/"; if (!mount_smb($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_smb()", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to mount", "Aborting backup", "backup"); return false; } $GLOBALS["PCOPY"] = true; } if ($resource_type == "ssh") { $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $mounted_path_sep = "/"; if (!mount_ssh($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_ssh()", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to mount to remote ssh service", "Aborting backup", "backup"); return false; } $GLOBALS["PCOPY"] = true; } if ($resource_type == "usb") { $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $mounted_path_sep = "/"; if (!mount_usb($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_usb()", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to mount", "Aborting backup", "backup"); return false; } backup_events($ID, "initialization", "INFO, using external device trough USB", __LINE__); $GLOBALS["PCOPY"] = true; } if ($resource_type == "rsync") { $mounted_path_sep = null; $mount_path = null; $GLOBALS["RESOURCE_MOUNTED"] = false; $GLOBALS["USE_RSYNC"] = true; $GLOBALS["NO_UMOUNT"] = true; $GLOBALS["CAN_CLEAN_CONTAINERS"] = false; if (!mount_rsync($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to connect"); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to connect", "Aborting backup", "backup"); return false; } else { backup_events($ID, "initialization", "INFO,{$first_ressource} connect success"); } } if ($resource_type == "automount") { $mounted_path_sep = "/"; $mount_path = $first_ressource; $GLOBALS["RESOURCE_MOUNTED"] = false; $GLOBALS["USE_RSYNC"] = true; $GLOBALS["NO_UMOUNT"] = true; $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $GLOBALS["MOUNTED_PATH_FINAL"] = $first_ressource; CheckCommandLineCopy(); if (!mount_automount($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to connect"); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to connect", "Aborting backup", "backup"); return false; } backup_events($ID, "initialization", "INFO,{$first_ressource} connect success"); $GLOBALS["PCOPY"] = true; } if ($resource_type == "local") { $mounted_path_sep = "/"; $mount_path = $first_ressource; $GLOBALS["RESOURCE_MOUNTED"] = false; $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $GLOBALS["USE_RSYNC"] = true; $GLOBALS["NO_UMOUNT"] = true; $GLOBALS["MOUNTED_PATH_FINAL"] = $first_ressource; CheckCommandLineCopy(); if (!is_dir($first_ressource)) { backup_events($ID, "initialization", "{$first_ressource} directory doesn't exsits, create it..", __LINE__); @mkdir($first_ressource, 0755, true); } if (!is_dir($first_ressource)) { backup_events($ID, "initialization", "{$first_ressource} no such directory permission denied", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} no such directory", "Aborting backup", "backup"); return false; } backup_events($ID, "initialization", "INFO,{$first_ressource} success"); $GLOBALS["PCOPY"] = true; } if ($GLOBALS["ONLY_TESTS"]) { if ($GLOBALS["RESOURCE_MOUNTED"]) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path}", __FUNCTION__, __FILE__, __LINE__); exec("umount -l {$mount_path}"); } writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: terminated...", __FUNCTION__, __FILE__, __LINE__); return; } if ($GLOBALS["ONNLY_MOUNT"]) { return $mount_path; } if ($container == "daily") { backup_events($ID, "initialization", "INFO, Daily container", __LINE__); $DirectoryContainer = "backup." . date('Y-m-d') . "/{$servername}"; $GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"] = $DirectoryContainer; $mount_path_final = $mount_path . $mounted_path_sep . $DirectoryContainer; } else { backup_events($ID, "initialization", "INFO, Weekly container", __LINE__); $DirectoryContainer = "backup." . date('Y-W') . "/{$servername}"; $GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"] = $DirectoryContainer; $mount_path_final = $mount_path . $mounted_path_sep . $DirectoryContainer; } if ($GLOBALS["DEBUG"]) { $cmd_verb = " --verbose"; writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: Verbose mode detected", __FUNCTION__, __FILE__, __LINE__); } @mkdir($mount_path_final, 0755, true); if (!$GLOBALS["NO_STANDARD_BACKUP"]) { $GLOBALS["MOUNTED_PATH_FINAL"] = $mount_path_final; $WhatToBackup_ar = null; $BACKUP_WWW_ALREADY_DONE = array(); $BACKUP_WEBGET_ALREADY_DONE = array(); $BACKUP_INSTANCES_ALREADY_DONE = array(); while (list($num, $WhatToBackup) = each($ressources)) { if (is_array($WhatToBackup)) { $WhatToBackup_ar = implode(",", $WhatToBackup); backup_events($ID, "initialization", "INFO, WhatToBackup Array = {$WhatToBackup_ar}", __LINE__); continue; } if ($WhatToBackup == "all") { backup_events($ID, "initialization", "INFO, Backup starting Running macro all cyrus, mysql, LDAP, Artica...", __LINE__); send_email_events("Backup Task {$ID}:: Backup starting Running macro all ", "Backup is running", "backup"); if ($users->cyrus_imapd_installed) { backup_events($ID, "initialization", "INFO, cyrus-imapd mailboxes processing"); backup_cyrus($ID); } backup_events($ID, "initialization", "INFO, LDAP Database processing", __LINE__); backup_ldap($ID); backup_events($ID, "initialization", "INFO, MySQL Database processing", __LINE__); backup_mysql($ID, 0); backup_events($ID, "initialization", "INFO, Restarting MySQL service...", __LINE__); mysql_admin_mysql(0, "Restarting mysql service.", null, __FILE__, __LINE__); shell_exec("/etc/init.d/mysql restart"); backup_events($ID, "initialization", "INFO, Artica settings processing", __LINE__); backup_artica($ID); if ($users->ZARAFA_INSTALLED) { if ($sock->GET_INFO("ZarafaStoreOutside") == 1) { backup_events($ID, "initialization", "INFO, Zarafa external attachments processing..."); backup_ZarafaOutside($ID); } } backup_events($ID, "initialization", "continue to next process", __LINE__); continue; } if (preg_match("#MYSQLINSTANCE:([0-9]+)#", $WhatToBackup, $re)) { $instance_id = $re[1]; backup_events($ID, "initialization", "INFO, Backup starting backup MySQL instance Number:{$instance_id}", __LINE__); if ($instance_id > 0) { if (!isset($BACKUP_INSTANCES_ALREADY_DONE[$instance_id])) { backup_mysql($ID, $instance_id); $BACKUP_INSTANCES_ALREADY_DONE[$instance_id] = true; } } continue; } if (preg_match("#FREEWEB:(.+)#", $WhatToBackup, $re)) { $sitename = $re[1]; backup_events($ID, "initialization", "INFO, Backup starting backup Website {$sitename}", __LINE__); if (!isset($BACKUP_WWW_ALREADY_DONE[$sitename])) { backup_freewebs($ID, $sitename); $BACKUP_INSTANCES_ALREADY_DONE[$sitename] = true; } continue; } if (preg_match("#WEBGET:(.+)#", $WhatToBackup, $re)) { if (!isset($BACKUP_WEBGET_ALREADY_DONE[$re[1]])) { $arr = unserialize(base64_decode($re[1])); if (!is_array($arr)) { backup_events($ID, "initialization", "ERROR, WEBGET `{$re[1]}` is not an array...", __LINE__); continue; } backup_events($ID, "initialization", "INFO, Backup remote Artica FreeWebs Website {$arr["RemoteArticaSite"]} from source {$arr["RemoteArticaServer"]}", __LINE__); backup_webget($ID, $arr); } continue; } backup_events($ID, "initialization", "INFO, `{$WhatToBackup}` could not understood", __LINE__); } } $sql = "SELECT * FROM backup_folders WHERE taskid={$ID}"; $results = $q->QUERY_SQL($sql, "artica_backup"); if (!$q->ok) { if (strpos($q->mysql_error, "gone away")) { backup_events($ID, "personal", "ERROR, mysql {$q->mysql_error} Restarting MySQL server (Patch p.20130807)", __LINE__); mysql_admin_mysql(0, "Restarting mysql service.", $q->mysql_error, __FILE__, __LINE__); shell_exec("/etc/init.d/mysql restart"); $q = new mysql(); $results = $q->QUERY_SQL($sql, "artica_backup"); } } if (!$q->ok) { backup_events($ID, "personal", "ERROR, mysql {$q->mysql_error}", __LINE__); return; } while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) { $dd1 = time(); if ($ligne["recursive"] == 1) { $recursive = " --recursive"; } else { $recursive = null; } $path = trim(base64_decode($ligne["path"])); if (!is_dir($path)) { backup_events($ID, "personal", "ERROR, [{$path}] no such file or directory", __LINE__); continue; } backup_events($ID, "personal", "INFO, Backup starting for {$path}", __LINE__); send_email_events("Backup Task {$ID}:: Backup starting {$path}", "Backup is running for path {$path}", "backup"); backup_mkdir($path); $results = backup_copy($path, $path, $ID); $calculate = distanceOfTimeInWords($dd1, time()); backup_events($ID, "personal", "INFO, Backup finish for {$path}\n{$results} {$calculate}", __LINE__); } writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: Calculate directory size on {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); $du = $unix->find_program("du"); $dut1 = time(); $nice = $unix->EXEC_NICE(); $cmd = "{$nice}{$du} -s {$mount_path_final}"; exec($cmd, $du_results); $calculate = distanceOfTimeInWords($dut1, time()); $BackupSize = 0; if (preg_match("#^([0-9]+)\\s+#", @implode("", $du_results), $re)) { $BackupSize = $re[1]; backup_events($ID, "initialization", "INFO, backup size {$BackupSize} bytes time:{$calculate}", __LINE__); } if ($GLOBALS["CAN_CLEAN_CONTAINERS"]) { backup_events($ID, "initialization", "INFO, cleaning containers....", __LINE__); CleanContainers($ID, $mount_path_final); } else { backup_events($ID, "initialization", "INFO, cannot clean containers, check protocols....", __LINE__); } $GLOBAL["BACKUP_MEMORY_SQL"]["mount_path_final"] = $mount_path_final; $zmd5 = md5("{$GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"]}{$GLOBALS["MYSERVERNAME"]}"); $cnx_params = addslashes(base64_encode(serialize($GLOBAL["BACKUP_MEMORY_SQL"]))); $sql = "INSERT IGNORE INTO backup_storages (`taskid`,`size`,`cnx_params`,`zmd5`) VALUES('{$ID}','{$BackupSize}','{$cnx_params}','{$zmd5}')"; $q->QUERY_SQL($sql, "artica_backup"); $sql = "UPDATE backup_storages SET `size`='{$BackupSize}' WHERE `zmd5`='{$zmd5}'"; $q->QUERY_SQL($sql, "artica_backup"); if (!$q->ok) { backup_events($ID, "initialization", "ERROR, {$q->mysql_error}", __LINE__); } if (!$GLOBALS["NO_UMOUNT"]) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); if (preg_match("#^\\/opt\\/artica\\/mounts\\/backup\\/[0-9]+(.+)#", $mount_path_final, $re)) { $mount_path_final = str_replace($re[1], "", $mount_path_final); writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:translated to {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); } backup_events($ID, "initialization", "INFO, umount {$mount_path_final}", __LINE__); writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); exec("umount -l {$mount_path_final} 2>&1", $resultsUmount); if (count($resultsUmount) > 0) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount : ----- \n" . @implode("\n", $resultsUmount) . "\n", __FUNCTION__, __FILE__, __LINE__); } } $date_end = time(); $calculate = distanceOfTimeInWords($date_start, $date_end); backup_events($ID, "TIME", "INFO, Time: {$calculate} ({$mount_path_final})", __LINE__); backup_events($ID, "initialization", "INFO, Backup task terminated", __LINE__); send_email_events("Backup Task {$ID}:: Backup stopping", "Backup is stopped", "backup"); shell_exec(LOCATE_PHP5_BIN2() . " " . dirname(__FILE__) . "/exec.cleanfiles.php"); }
function SERVICE_START($nochecks = false, $nopid = false) { $unix = new unix(); $sock = new sockets(); $kill = $unix->find_program("kill"); if (!$nopid) { $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pid = @file_get_contents($pidfile); if ($unix->process_exists($pid, basename(__FILE__))) { $time = $unix->PROCCESS_TIME_MIN($pid); echo "Starting......: " . date("H:i:s") . " MySQL this script is already executed PID: {$pid} since {$time}Mn\n"; if ($time < 5) { if (!$GLOBALS["FORCE"]) { return; } } unix_system_kill_force($pid); } @file_put_contents($pidfile, getmypid()); } if (is_file("/etc/artica-postfix/mysql.stop")) { echo "Starting......: " . date("H:i:s") . " MySQL locked, exiting\n"; return; } $PID_NUM = PID_NUM(); if ($unix->process_exists($PID_NUM)) { $timemin = $unix->PROCCESS_TIME_MIN($PID_NUM); echo "Starting......: " . date("H:i:s") . " MySQL already running PID \"{$PID_NUM}\" since {$timemin}Mn\n"; return; } $mysql_install_db = $unix->find_program('mysql_install_db'); $mysqlbin = $unix->LOCATE_mysqld_bin(); $php5 = $unix->LOCATE_PHP5_BIN(); $nohup = $unix->find_program("nohup"); if (!is_file($mysqlbin)) { echo "Starting......: " . date("H:i:s") . " MySQL is not installed, abort\n"; return; } $EnableMysqlFeatures = $sock->GET_INFO('EnableMysqlFeatures'); $MysqlBinAllAdresses = $sock->GET_INFO('MysqlBinAllAdresses'); $MySQLTMPMEMSIZE = $sock->GET_INFO('MySQLTMPMEMSIZE'); $MysqlTooManyConnections = $sock->GET_INFO("MysqlTooManyConnections"); $MysqlRemoveidbLogs = $sock->GET_INFO("MysqlRemoveidbLogs"); $innodb_force_recovery = $sock->GET_INFO("innodb_force_recovery"); if (!is_numeric($innodb_force_recovery)) { $innodb_force_recovery = 0; } if (!is_numeric($MysqlRemoveidbLogs)) { $MysqlRemoveidbLogs = 0; } if (!is_numeric($MysqlBinAllAdresses)) { $MysqlBinAllAdresses = 0; } if (!is_numeric($MySQLTMPMEMSIZE)) { $MySQLTMPMEMSIZE = 0; } if (!is_numeric($MysqlTooManyConnections)) { $MysqlTooManyConnections = 0; } if (!is_numeric($EnableMysqlFeatures)) { $EnableMysqlFeatures = 1; } $MySqlTmpDir = $sock->GET_INFO('MySQLTMPDIR'); $MySQLLOgErrorPath = $sock->GET_INFO('MySQLLOgErrorPath'); $datadir = $unix->MYSQL_DATA_DIR(); $EnableMysqlLog = $sock->GET_INFO("EnableMysqlLog"); if (!is_numeric($EnableMysqlLog)) { $EnableMysqlLog = 0; } if ($datadir == null) { $datadir = '/var/lib/mysql'; } if ($MySqlTmpDir == '/tmp') { $MySqlTmpDir = null; } if ($MySQLLOgErrorPath == null) { $MySQLLOgErrorPath = $datadir . '/mysqld.err'; } if ($MysqlTooManyConnections == 1) { echo "Starting......: " . date("H:i:s") . " MySQL MysqlTooManyConnections=1, abort\n"; return; } if (isset($GLOBALS["RECOVERY"])) { $innodb_force_recovery = $GLOBALS["RECOVERY"]; } if (strlen($MySqlTmpDir) > 3) { echo "Starting......: " . date("H:i:s") . " MySQL tempdir : {$MySqlTmpDir}\n"; shell_exec("{$php5} /usr/share/artica-postfix/exec.mysql.build.php --tmpfs"); $MySqlTmpDir = str_replace("//", "/", $MySqlTmpDir); if (!is_dir($MySqlTmpDir)) { @mkdir($MySqlTmpDir, 0755, true); $unix->chown_func("mysql", "mysql", $MySqlTmpDir); } $MySqlTmpDirCMD = " --tmpdir={$MySqlTmpDir}"; } if ($EnableMysqlFeatures == 0) { echo "Starting......: " . date("H:i:s") . " MySQL is disabled by \"EnableMysqlFeatures\"...\n"; return; } $pid_file = "/var/run/mysqld/mysqld.pid"; $socket = "/var/run/mysqld/mysqld.sock"; $mysql_user = "******"; @mkdir("/var/run/mysqld", 0755, true); @mkdir("/var/log/mysql", 0755, true); @mkdir($datadir, 0755, true); $dirs = $unix->dirdir("/var/lib/mysql"); while (list($num, $directory) = each($dirs)) { echo "Starting......: " . date("H:i:s") . " MySQL, apply permissions on " . basename($directory) . "\n"; $unix->chown_func("mysql", "mysql", "{$directory}/*"); } $bind_address = ' --bind-address=127.0.0.1'; $bind_address2 = "127.0.0.1"; if ($MysqlBinAllAdresses == 1) { $bind_address2 = 'All (0.0.0.0)'; $bind_address = ' --bind-address=0.0.0.0'; } echo "Starting......: " . date("H:i:s") . " MySQL Pid path.......:{$pid_file}\n"; echo "Starting......: " . date("H:i:s") . " datadir..............:{$datadir}\n"; echo "Starting......: " . date("H:i:s") . " Log error............:{$MySQLLOgErrorPath}\n"; echo "Starting......: " . date("H:i:s") . " socket...............:{$socket}\n"; echo "Starting......: " . date("H:i:s") . " user.................:{$mysql_user}\n"; echo "Starting......: " . date("H:i:s") . " LOGS ENABLED.........:{$EnableMysqlLog}\n"; echo "Starting......: " . date("H:i:s") . " Daemon...............:{$mysqlbin}\n"; echo "Starting......: " . date("H:i:s") . " Bind address.........:{$bind_address2}\n"; echo "Starting......: " . date("H:i:s") . " Temp Dir.............:{$MySqlTmpDir}\n"; echo "Starting......: " . date("H:i:s") . " innodb_force_recovery:{$innodb_force_recovery}\n"; mysql_admin_mysql(1, "Starting MySQL service...", null, __FILE__, __LINE__); echo "Starting......: " . date("H:i:s") . " Settings permissions..\n"; @mkdir("/var/run/mysqld", 0755, true); $unix->chown_func($mysql_user, $mysql_user, "/var/run/mysqld"); $unix->chown_func($mysql_user, $mysql_user, "/var/log/mysql"); $unix->chown_func($mysql_user, $mysql_user, $datadir); $unix->chown_func($mysql_user, $mysql_user, "{$datadir}/*"); if ($unix->is_socket("/var/run/mysqld/mysqld.sock")) { @unlink("/var/run/mysqld/mysqld.sock"); } if (is_file('/var/run/mysqld/mysqld.err')) { @unlink('/var/run/mysqld/mysqld.err'); } if (is_file("/var/run/mysqld/mysqld.pid")) { $unix->chown_func($mysql_user, $mysql_user, "/var/run/mysqld/mysqld.pid"); } if ($MysqlRemoveidbLogs == 1) { shell_exec('/bin/mv /var/lib/mysql/ib_logfile* /tmp/'); $sock->SET_INFO('MysqlRemoveidbLogs', '0'); } $logpathstring = " --log-error={$MySQLLOgErrorPath}"; if ($EnableMysqlLog == 1) { $logpathstring = " --log=/var/log/mysql.log --log-slow-queries=/var/log/mysql-slow-queries.log --log-error={$MySQLLOgErrorPath} --log-warnings"; } $toTouch[] = "/var/log/mysql-slow-queries.log"; $toTouch[] = "/var/log/mysql.error"; $toTouch[] = "/var/log/mysql.log"; $toTouch[] = "/var/log/mysql.warn"; while (list($num, $filename) = each($toTouch)) { if (!is_file($filename)) { @file_put_contents($filename, "#\n"); } $unix->chown_func($mysql_user, $mysql_user, $filename); } echo "Starting......: " . date("H:i:s") . " MySQL Checking : {$datadir}/mysql/host.frm\n"; if (!is_file("{$datadir}/mysql/host.frm")) { if (is_file($mysql_install_db)) { echo "Starting......: " . date("H:i:s") . " MySQL Installing default databases\n"; shell_exec("{$mysql_install_db} --datadir=\"{$datadir}\""); } } else { echo "Starting......: " . date("H:i:s") . " MySQL Checking : {$datadir}/mysql/host.frm OK\n"; } $cmd2 = array(); $MEMORY = $unix->MEM_TOTAL_INSTALLEE(); $AsCategoriesAppliance = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/AsCategoriesAppliance")); if ($AsCategoriesAppliance == 1) { $MEMORY = 620288; } if ($MEMORY < 624288) { $GetStartedValues = GetStartedValues(); echo "Starting......: " . date("H:i:s") . " MySQL Warning memory did not respond to pre-requesites, tuning to lower memory\n"; if ($GetStartedValues["--key-buffer-size"]) { $cmd2[] = "--key-buffer-size=8M"; } if ($GetStartedValues["--max-allowed-packet"]) { $cmd2[] = "--max-allowed-packet=4M"; } if ($GetStartedValues["--table-cache"]) { $cmd2[] = "--table-cache=4"; } if ($GetStartedValues["--sort-buffer-size"]) { $cmd2[] = "--sort-buffer-size=64k"; } if ($GetStartedValues["--read-buffer-size"]) { $cmd2[] = "--read-buffer-size=256k"; } if ($GetStartedValues["--read-rnd-buffer-size"]) { $cmd2[] = "--read-rnd-buffer-size=128k"; } if ($GetStartedValues["--net-buffer-length"]) { $cmd2[] = "--net-buffer-length=2k"; } if ($GetStartedValues["--thread-stack"]) { $cmd2[] = "--thread-stack=192k"; } if ($GetStartedValues["--thread-cache-size"]) { $cmd2[] = "--thread-cache-size=128"; } if ($GetStartedValues["--thread-concurrency"]) { $cmd2[] = "--thread-concurrency=10"; } if ($GetStartedValues["--default-storage-engine"]) { $cmd2[] = "--default-storage-engine=MyISAM"; } if ($GetStartedValues["--default-tmp-storage-engine"]) { $cmd2[] = "--default-tmp-storage-engine=MyISAM"; } if ($GetStartedValues["--tmp-table-size"]) { $cmd2[] = "--tmp-table-size=16M"; } if ($GetStartedValues["--table-cache"]) { $cmd2[] = "--table-cache=64"; } if ($GetStartedValues["--query-cache-limit"]) { $cmd2[] = "--query-cache-limit=4M"; } if ($GetStartedValues["--query-cache-size"]) { $cmd2[] = "--query-cache-size=32M"; } if ($GetStartedValues["--max-connections"]) { $cmd2[] = "--max-connections=50"; } if (is_file("/etc/artica-postfix/WORDPRESS_APPLIANCE")) { $cmd2[] = "--innodb=OFF"; } echo "Starting......: " . date("H:i:s") . " MySQL " . count($cmd2) . " forced option(s)\n"; } if (is_file($MySQLLOgErrorPath)) { @unlink($MySQLLOgErrorPath); } $cmds[] = $mysqlbin; if ($MEMORY < 624288) { $cmds[] = "--no-defaults --user=mysql"; } $cmds[] = "--pid-file=/var/run/mysqld/mysqld.pid"; $cmds[] = trim($logpathstring); $cmds[] = trim($MySqlTmpDirCMD); $cmds[] = "--socket={$socket}"; $cmds[] = "--datadir=\"{$datadir}\""; if (count($cmd2) == 0) { if ($innodb_force_recovery > 0) { $cmds[] = "--innodb-force-recovery={$innodb_force_recovery}"; } } if (count($cmd2) > 0) { $cmds[] = @implode(" ", $cmd2); } $cmds[] = ">/dev/null 2>&1 &"; if (is_file('/usr/sbin/aa-complain')) { echo "Starting......: " . date("H:i:s") . " Mysql Adding mysql in apparamor complain mode...\n"; shell_exec("/usr/sbin/aa-complain {$mysqlbin} >/dev/null 2>&1"); } $cmd = @implode(" ", $cmds); while (list($num, $ligne) = each($cmds)) { echo "Starting......: " . date("H:i:s") . " MySQL Option: {$ligne}\n"; } echo "Starting......: " . date("H:i:s") . " MySQL Starting daemon, please wait\n"; writelogs("Starting MySQL {$cmd}", __FUNCTION__, __FILE__, __LINE__); shell_exec($cmd); $count = 0; sleep(2); for ($i = 0; $i < 6; $i++) { $pid = PID_NUM(); if ($unix->process_exists($pid, $mysqlbin)) { echo "Starting......: " . date("H:i:s") . " MySQL Checks daemon running...\n"; break; } echo "Starting......: " . date("H:i:s") . " MySQL Checks daemon, please wait ({$i}/6)\n"; sleep(1); } $pid = PID_NUM(); if (!$unix->process_exists($pid)) { echo "Starting......: " . date("H:i:s") . " MySQL failed\n"; echo "Starting......: " . date("H:i:s") . " {$cmd}\n"; system_admin_events("Failed to start MySQL server", __FUNCTION__, __FILE__, __LINE__, "services"); $php5 = $unix->LOCATE_PHP5_BIN(); shell_exec("{$nohup} {$php5} /usr/share/artica-postfix/exec.mysql.build.php >/dev/null 2>&1 &"); } else { for ($i = 0; $i < 4; $i++) { echo "Starting......: " . date("H:i:s") . " MySQL Checks mysqld.sock waiting {$i}/3\n"; if ($unix->is_socket("/var/run/mysqld/mysqld.sock")) { break; } sleep(1); } if (!$unix->is_socket("/var/run/mysqld/mysqld.sock")) { mysql_admin_mysql(0, "Failed to start MySQL Server /var/run/mysqld/mysqld.sock no such socket after 4 seconds", null, __FILE__, __LINE__); echo "Starting......: " . date("H:i:s") . " MySQL Checks mysqld.sock failed...\n"; } mysql_admin_mysql(1, "Success to start MySQL Server with new pid {$pid}", null, __FILE__, __LINE__); echo "Starting......: " . date("H:i:s") . " MySQL Success pid {$pid}\n"; $q = new mysql_squid_builder(); $q->MEMORY_TABLES_RESTORE(); } }
public function QUERY_SQL($sql, $database = null, $called = null, $unbuffered = false) { $TableDropped_blacklist["ufdb_smtp"] = true; $database = trim($database); if ($database == "artica_backup") { $database = $this->database; } if ($database == "artica_events") { $database = $this->database; } if ($database == "ocsweb") { $database = $this->database; } if ($database == "postfixlog") { $database = $this->database; } if ($database == "powerdns") { $database = $this->database; } if ($database == "zarafa") { $database = $this->database; } if ($database == "syslogstore") { $database = $this->database; } if ($database == "metaclient") { $database = $this->database; } if ($database == null) { $database = $this->database; } $this->last_id = 0; $this->sql = $sql; $CLASS = __CLASS__; $FUNCTION = __FUNCTION__; $FILENAME = basename(__FILE__); $LOGPRF = "{$FILENAME}::{$CLASS}/{$FUNCTION}"; $this->ok = false; if (isset($GLOBALS["HOTSPOT_DEBUG"])) { if ($GLOBALS["HOTSPOT_DEBUG"]) { if (function_exists("wifidog_logs")) { wifidog_logs("{$sql}", __FUNCTION__, __LINE__); } } } $sql = trim($sql); if ($called == null) { if (function_exists("debug_backtrace")) { $trace = @debug_backtrace(); if (isset($trace[1])) { $called = "called by " . basename($trace[1]["file"]) . " {$trace[1]["function"]}() line {$trace[1]["line"]}"; } } } if (preg_match("#delete.*?webfilter_members#i", $sql)) { $this->ToSyslog("FATAL!! CHATEAU-THIERRY {$sql} {$called}"); } if ($GLOBALS["DEBUG_SQL"]) { echo "this->BD_CONNECT\n"; } @mysql_close($this->mysql_connection); if (!$this->BD_CONNECT(false, $called)) { if ($GLOBALS["VERBOSE"]) { echo "Unable to BD_CONNECT class mysql/QUERY_SQL\n"; } if (function_exists("system_admin_events")) { $trace = @debug_backtrace(); if (isset($trace[1])) { $called = "called by " . basename($trace[1]["file"]) . " {$trace[1]["function"]}() line {$trace[1]["line"]}"; } system_admin_events("MySQL error DB:\"{$database}\" Error, unable to connect to MySQL server, request failed\n{$called}", __FUNCTION__, __FILE__, __LINE__, "mysql-error"); } $this->writeLogs("QUERY_SQL:" . __LINE__ . ": DB:\"{$database}\" Error, unable to connect to MySQL server, request failed", __CLASS__ . '/' . __FUNCTION__, __LINE__); $this->ok = false; $this->mysql_error = $this->BD_CONNECT_ERROR . " Error, unable to connect to MySQL server"; $this->ToSyslog($this->mysql_error); return false; } if (preg_match("#DROP TABLE\\s+(.+)\$#i", $sql, $re)) { $TableDropped = $re[1]; if (!isset($TableDropped_blacklist[$TableDropped])) { if (function_exists("system_admin_events")) { $trace = @debug_backtrace(); if (isset($trace[1])) { $called = "called by " . basename($trace[1]["file"]) . " {$trace[1]["function"]}() line {$trace[1]["line"]}"; } system_admin_events("MySQL table {$database}/{$TableDropped} was deleted {$called}", __FUNCTION__, __FILE__, __LINE__, "mysql-delete"); } } } if ($GLOBALS["DEBUG_SQL"]) { echo "mysql_select_db()\n"; } if ($GLOBALS['VERBOSE']) { $ok = mysql_select_db($database, $this->mysql_connection); } else { $ok = @mysql_select_db($database, $this->mysql_connection); } if (!$ok) { $errnum = @mysql_errno($this->mysql_connection); $des = @mysql_error($this->mysql_connection); if (!is_numeric($errnum)) { if ($GLOBALS["VERBOSE"]) { echo "{$LOGPRF} mysql_select_db/{$this->database}/" . __LINE__ . " [FAILED] error {$errnum} {$des} -> RESTART !!\n"; } @mysql_close($this->mysql_connection); $this->mysql_connection = false; $this->BD_CONNECT(false, $called); $ok = @mysql_select_db($this->database, $this->mysql_connection); if (!$ok) { if ($GLOBALS["VERBOSE"]) { echo "{$LOGPRF} mysql_select_db/{$this->database}/" . __LINE__ . " [FAILED] -> SECOND TIME !!\n"; } if (function_exists("mysql_admin_mysql")) { mysql_admin_mysql(0, "FATAL MySQL error Connection failed to MySQL database", $sql . "\n{$this->mysql_error}", __FILE__, __LINE__); } $this->ok = false; return false; } } } if (!$ok) { $errnum = @mysql_errno($this->mysql_connection); $des = @mysql_error($this->mysql_connection); if ($GLOBALS["VERBOSE"]) { echo "{$LOGPRF} mysql_select_db/{$this->database}/" . __LINE__ . " [FAILED] N.{$errnum} DESC:{$des} mysql/QUERY_SQL\n"; } if ($GLOBALS["VERBOSE"]) { echo "mysql -u {$this->mysql_admin} -p{$this->mysql_password} -h {$this->mysql_server} -P {$this->mysql_port} -A {$this->database}\n"; } $this->mysql_errornum = $errnum; $this->mysql_error = $des; $time = date('h:i:s'); $this->writeLogs("{$LOGPRF} Line:" . __LINE__ . ":mysql_select_db DB:\"{$database}\" Error Number ({$errnum}) ({$des}) config:{$this->mysql_server}:{$this->mysql_port}@{$this->mysql_admin} ({$called})", __CLASS__ . '/' . __FUNCTION__, __LINE__); $this->mysql_error = "{$LOGPRF} Line:" . __LINE__ . ": mysql_select_db:: Error {$errnum} ({$des}) config:{$this->mysql_server}:{$this->mysql_port}@{$this->mysql_admin} line:" . __LINE__; $this->ok = false; $this->ToSyslog($this->mysql_error); $this->ToSyslog($sql); @mysql_close($this->mysql_connection); $this->mysql_connection = false; if (function_exists("mysql_admin_mysql")) { mysql_admin_mysql(0, "FATAL MySQL error Error Number ({$errnum}) ({$des})", $sql . "\n{$this->mysql_error}", __FILE__, __LINE__); } return null; } $mysql_unbuffered_query_log = null; if (preg_match("#^(UPDATE|DELETE)#i", $sql)) { $mysql_unbuffered_query_log = "mysql_unbuffered_query"; if ($GLOBALS["DEBUG_SQL"]) { echo "mysql_unbuffered_query()\n"; } $results = @mysql_unbuffered_query($sql, $this->mysql_connection); } else { if ($unbuffered) { $mysql_unbuffered_query_log = "mysql_unbuffered_query"; if ($GLOBALS["DEBUG_SQL"]) { echo "mysql_unbuffered_query()\n"; } $results = @mysql_unbuffered_query($sql, $this->mysql_connection); } else { $mysql_unbuffered_query_log = "mysql_query"; if ($GLOBALS["DEBUG_SQL"]) { echo "mysql_query()\n"; } $results = @mysql_query($sql, $this->mysql_connection); $this->last_id = @mysql_insert_id($this->mysql_connection); } } if (!$results) { $errnum = @mysql_errno($this->mysql_connection); $des = @mysql_error($this->mysql_connection); if (preg_match('#Duplicate entry#', $des)) { $this->writeLogs("QUERY_SQL:" . __LINE__ . ": DB:\"{$database}\" Error {$errnum} {$des} line:" . __LINE__, __CLASS__ . '/' . __FUNCTION__, __FILE__, __LINE__); $this->writeLogs("QUERY_SQL:" . __LINE__ . ": DB:\"{$database}\" " . substr($sql, 0, 255) . "...line:" . __LINE__, __CLASS__ . '/' . __FUNCTION__, __FILE__, __LINE__); $this->writelogs($sql, __CLASS__ . '/' . __FUNCTION__, __FILE__); $this->ok = true; @mysql_close($this->mysql_connection); $this->mysql_connection = false; return true; } $this->mysql_errornum = $errnum; $this->mysql_error = "QUERY_SQL:" . __LINE__ . ": {$mysql_unbuffered_query_log}:: {$called} Error {$errnum} ({$des}) config:{$this->mysql_server}:{$this->mysql_port}@{$this->mysql_admin} line:" . __LINE__; if (isset($GLOBALS["HOTSPOT_DEBUG"])) { if ($GLOBALS["HOTSPOT_DEBUG"]) { if (function_exists("wifidog_logs")) { wifidog_logs("{$this->mysql_error}", __FUNCTION__, __LINE__); } } } $this->ToSyslog($this->mysql_error); $sql = str_replace("\n", " ", $sql); $sql = str_replace("\t", " ", $sql); $sql = str_replace(" ", " ", $sql); $this->ToSyslog($sql); if (preg_match("#Table\\s+'(.+?)'.*?is marked as crashed#", $des, $re)) { if (class_exists("sockets")) { $sock = new sockets(); $ARRAY["DB"] = $database; $ARRAY["TABLE"] = $re[1]; $data = urlencode(base64_encode(serialize($ARRAY))); $sock->getFrameWork("squid.php?mysql-crash={$data}"); } } if ($GLOBALS["VERBOSE"]) { echo "{$LOGPRF} {$mysql_unbuffered_query_log}/" . __LINE__ . " [FAILED] N.{$errnum} DESC:{$des} {$called}\n"; } if ($GLOBALS["VERBOSE"]) { echo "{$LOGPRF} {$mysql_unbuffered_query_log}" . __LINE__ . " [FAILED] {$sql}\n"; } if (function_exists("mysql_admin_mysql")) { mysql_admin_mysql(0, "FATAL MySQL error Error Number ({$errnum}) ({$des})", $sql . "\n{$this->mysql_error}", __FILE__, __LINE__); } @mysql_free_result($this->mysql_connection); @mysql_close($this->mysql_connection); $this->mysql_connection = false; $this->ok = false; return null; } if ($GLOBALS["DEBUG_SQL"]) { echo "SUCCESS\n"; } $this->ok = true; if ($this->last_id == 0) { $this->last_id = @mysql_insert_id($this->mysql_connection); } $result_return = $results; @mysql_free_result($this->mysql_connection); @mysql_close($this->mysql_connection); $this->mysql_connection = false; return $result_return; }
function RestartMysqlDaemon() { $unix = new unix(); $php5 = $unix->LOCATE_PHP5_BIN(); $cmd = trim("{$php5} /usr/share/artica-postfix/exec.mysql.build.php \"" . $unix->MYSQL_MYCNF_PATH() . "\" >/dev/null 2>&1"); writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__); shell_exec($cmd); $nohup = $unix->find_program("nohup"); mysql_admin_mysql(1, "Restarting MySQL service...", null, __FILE__, __LINE__); $cmd = trim("{$nohup} /etc/init.d/mysql restart --force --framework=" . __FILE__ . " >/dev/null 2>&1 &"); writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__); shell_exec($cmd); }
<?php $GLOBALS["SCHEDULE_ID"] = 0; if (preg_match("#schedule-id=([0-9]+)#", implode(" ", $argv), $re)) { $GLOBALS["SCHEDULE_ID"] = $re[1]; } include_once dirname(__FILE__) . '/ressources/class.templates.inc'; include_once dirname(__FILE__) . '/ressources/class.ini.inc'; include_once dirname(__FILE__) . '/ressources/class.users.menus.inc'; include_once dirname(__FILE__) . '/ressources/class.mysql-server.inc'; include_once dirname(__FILE__) . '/ressources/class.mysql.inc'; include_once dirname(__FILE__) . '/ressources/class.mysql-multi.inc'; include_once dirname(__FILE__) . "/framework/class.unix.inc"; include_once dirname(__FILE__) . "/framework/frame.class.inc"; include_once dirname(__FILE__) . '/ressources/class.os.system.inc'; $pidfile = "/etc/artica-postfix/" . basename(__FILE__) . ".pid"; $pid = @file_get_contents($pidfile); $unix = new unix(); if ($unix->process_exists($pid, basename(__FILE__))) { system_admin_events("Starting......: " . date("H:i:s") . "Already executed PID {$pid}...", __FUNCTION__, __FILE__, __LINE__, "mysql"); die; } @file_put_contents($pidfile, getmypid()); $t = time(); $unix = new unix(); $unix->ToSyslog("Restarting MySQL service"); mysql_admin_mysql(1, "Restarting MySQL service...", null, __FILE__, __LINE__); exec("/etc/init.d/mysql restart --framework=" . __FILE__ . " 2>&1", $results); $took = $unix->distanceOfTimeInWords($t, time()); system_admin_events("Restarting MySQL service done took {$took}:\n" . @implode("\n", $results), __FUNCTION__, __FILE__, __LINE__, "mysql");
function check_crashed_squid() { $FILE_LOG = "/opt/squidsql/error.log"; $DB_PATH = "/opt/squidsql/data"; // /etc/artica-postfix/pids/exec.mysqld.crash.php.check_crashed_squid.time $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidTime = "/etc/artica-postfix/pids/exec.mysqld.crash.php.check_crashed_squid.time"; if ($GLOBALS["VERBOSE"]) { echo "pidTime: {$pidTime}\n"; } $unix = new unix(); $pid = $unix->get_pid_from_file($pidfile); $sock = new sockets(); if ($unix->process_exists($pid, basename(__FILE__))) { $pidTime = $unix->PROCCESS_TIME_MIN($pid); if ($pidTime > 120) { $kill = $unix->find_program("kill"); unix_system_kill_force($pid); die; } return; } @file_put_contents($pidfile, getmypid()); $Time = $unix->file_time_min($pidTime); if (!$GLOBALS["VERBOSE"]) { if ($Time < 120) { return; } } @unlink($pidTime); @file_put_contents($pidTime, time()); $q = new mysql_squid_builder(); $sql = "SELECT table_name as c FROM information_schema.tables WHERE table_schema = 'squidlogs' AND table_name LIKE '%_blocked'"; $results = $q->QUERY_SQL($sql, "artica_events"); while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) { if (!preg_match("#^[0-9]+_", $ligne["c"])) { continue; } $q->QUERY_SQL("DROP TABLE {$ligne["c"]}"); } if (!is_file($FILE_LOG)) { return; } $myisamchk = $unix->find_program("myisamchk"); $echo = $unix->find_program("echo"); if (!is_file($myisamchk)) { return; } $f = explode("\n", @file_get_contents($FILE_LOG)); $GLOBALS["CRASHED"] = array(); $PATHS = array(); while (list($num, $line) = each($f)) { $line = trim($line); if ($line == null) { continue; } if (preg_match("#Aborted connection [0-9]+#", $line)) { continue; } if (preg_match("#Got an error from thread_id#", $line)) { continue; } if (preg_match("#MySQL thread id [0-9]+#", $line)) { continue; } if (preg_match("#ERROR.*?Table.*?\\/(.+?)\\/(.*?)'\\s+is marked as crashed#", $line, $re)) { $md5 = md5("{$re[1]}{$re[2]}"); if (!isset($arrayCheckNot[$md5])) { mysql_admin_mysql(1, "{$re[1]}/{$re[2]} Incorrect key file for table [action=repair]", @implode("\n", $xxx)); $GLOBALS["CRASHED"][$re[1]][] = $re[2]; $GLOBALS["CRASHED_LOGS"][] = "Detected: {$line}"; $arrayCheckNot[$md5] = true; } continue; } if (preg_match("#Incorrect key file for table './(.+?)\\/(.+?)\\.MYI'; try to repair it#", $line, $re)) { $md5 = md5("{$re[1]}{$re[2]}"); if (!isset($arrayCheckNot[$md5])) { mysql_admin_mysql(1, "{$re[1]}/{$re[2]} Incorrect key file for table [action=repair]", @implode("\n", $xxx)); $GLOBALS["CRASHED"][$re[1]][] = $re[2]; $GLOBALS["CRASHED_LOGS"][] = "Detected: {$line}"; $arrayCheckNot[$md5] = true; } continue; } if (preg_match("#Got error 127 when reading table './(.+?)\\/(.+?)'#", $line, $re)) { $md5 = md5("{$re[1]}{$re[2]}"); if (!isset($arrayCheckNot[$md5])) { mysql_admin_mysql(1, "{$re[1]}/{$re[2]} Got error 127 when reading table [action=repair]", @implode("\n", $xxx)); $GLOBALS["CRASHED"][$re[1]][] = $re[2]; $GLOBALS["CRASHED_LOGS"][] = "Detected: {$line}"; $arrayCheckNot[$md5] = true; } continue; } if ($GLOBALS["VERBOSE"]) { echo $line . " no match\n"; } } if (count($GLOBALS["CRASHED"]) == 0) { return; } while (list($database, $tables) = each($GLOBALS["CRASHED"])) { while (list($a, $table) = each($tables)) { $path = "{$DB_PATH}/{$database}/{$table}.MYI"; if (is_file("{$DB_PATH}/{$database}/{$table}.TMD")) { @copy("{$DB_PATH}/{$database}/{$table}.TMD", "/var/lib/mysql/{$database}/{$table}." . time() . ".TMD"); @unlink("{$DB_PATH}/{$database}/{$table}.TMD"); } $arrayCheck[$table] = true; $PATHS[$path] = true; } } while (list($filepath, $none) = each($PATHS)) { $t = time(); $cmd = "{$myisamchk} -f -r {$filepath} 2>&1"; if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } $results = array(); exec("{$cmd}", $results); $Took = $unix->distanceOfTimeInWords($t, time()); mysql_admin_mysql(1, basename($filepath) . " repair report, took {$Took}", @implode("\n", $results)); system_admin_events(basename($filepath) . " repair report, took {$Took}", @implode("\n", $results), __FILE__, __LINE__, "mysql"); } $mysqlcheck = $unix->find_program("mysqlcheck"); $q = new mysql_squid_builder(); while (list($tablename, $none) = each($arrayCheck)) { shell_exec("{$mysqlcheck} --auto-repair {$q->MYSQL_CMDLINES} squidlogs {$tablename}"); } shell_exec("{$echo} \"\" >{$FILE_LOG}"); }
function start_watchdog() { if ($GLOBALS["VERBOSE"]) { $GLOBALS["FORCE"] = true; } $pidtime = "/etc/artica-postfix/pids/exec.squid.watchdog.php.start_watchdog.time"; $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidtimeNTP = "/etc/artica-postfix/pids/exec.squid.watchdog.php.start_watchdog.ntp.time"; $unix = new unix(); $pid = $unix->get_pid_from_file($pidFile); if ($unix->process_exists($pid)) { $pptime = $unix->PROCCESS_TIME_MIN($pid, 10); if ($GLOBALS["VERBOSE"]) { echo "Process already running PID {$pid} since {$pptime}Mn\n"; } return; } @file_put_contents($pidFile, getmypid()); $time = $unix->file_time_min($pidtime); $sock = new sockets(); $nohup = $unix->find_program("nohup"); $php = $unix->LOCATE_PHP5_BIN(); $NtpdateAD = intval($sock->GET_INFO("NtpdateAD")); $EnableFailover = $sock->GET_INFO("EnableFailover"); $GLOBALS["EnableFailover"] = $sock->GET_INFO("EnableFailover"); $SQUIDEnable = trim($sock->GET_INFO("SQUIDEnable")); if (!is_numeric($SQUIDEnable)) { $SQUIDEnable = 1; } if (!is_numeric($EnableFailover)) { $EnableFailover = 1; } if (!is_file("/usr/share/squid3/icons/silk/bigshield-256.png")) { @copy("/usr/share/artica-postfix/img/bigshield-256.png", "/usr/share/squid3/icons/silk/bigshield-256.png"); } if (!is_file("/usr/share/squid3/icons/silk/logo-artica-64.png")) { @copy("/usr/share/artica-postfix/img/logo-artica-64.png", "/usr/share/squid3/icons/silk/logo-artica-64.png"); } $articafiles[] = "exec.logfile_daemon.php"; $articafiles[] = "external_acl_squid_ldap.php"; $articafiles[] = "external_acl_dynamic.php"; $articafiles[] = "external_acl_quota.php"; $articafiles[] = "external_acl_basic_auth.php"; $articafiles[] = "external_acl_squid.php"; $articafiles[] = "external_acl_restrict_access.php"; while (list($num, $filename) = each($articafiles)) { $filepath = "/usr/share/artica-postfix/{$filename}"; @chmod($filepath, 0755); @chown($filepath, "squid"); @chgrp($filepath, "squid"); } @unlink($pidtime); @file_put_contents($pidtime, time()); if ($SQUIDEnable == 0) { die; } ALL_STATUS(true); $MonitConfig = unserialize(base64_decode($sock->GET_INFO("SquidWatchdogMonitConfig"))); $MonitConfig["EnableFailover"] = $EnableFailover; $MonitConfig = watchdog_config_default($MonitConfig); $unix->chmod_func(0755, "/etc/artica-postfix/settings/Daemons/*"); @mkdir("{$GLOBALS["ARTICALOGDIR"]}/squid/mysql-failed", 0755, true); $unix->chown_func("squid", "squid", "{$GLOBALS["ARTICALOGDIR"]}/squid/mysql-failed"); if (!$GLOBALS["VERBOSE"]) { if ($time < $MonitConfig["MIN_INTERVAL"]) { return; } } $STAMP_MAX_RESTART_TIME = $unix->file_time_min($GLOBALS["STAMP_MAX_RESTART"]); if ($STAMP_MAX_RESTART_TIME > 60) { @unlink($GLOBALS["STAMP_MAX_RESTART"]); } //Events("Start: ". basename($pidtime).":{$time}Mn / {$MonitConfig["MIN_INTERVAL"]}Mn STAMP_MAX_RESTART_TIME={$STAMP_MAX_RESTART_TIME}Mn"); if (!is_file("/etc/artica-postfix/SQUID_TEMPLATE_DONE")) { mysql_admin_mysql(1, "SQUID_TEMPLATE_DONE: No such file, launch build template action...", null, __FILE__, __LINE__); shell_exec("{$nohup} {$php} " . dirname(__FILE__) . "/exec.squid.php --tpl-save >/dev/null 2>&1 &"); } $GLOBALS["ALL_SCORES"] = 0; $pid = SQUID_PID(); $processtime = $unix->PROCCESS_TIME_MIN($pid); if (!$GLOBALS["FORCE"]) { if ($processtime < 2) { return; } } CHECK_STREAMCACHE(); CACHE_DIR_SIZE_CACHES(); verify_var_log(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after START"; CHECK_SARG(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after CHECK_SARG();"; Checks_mgrinfos($MonitConfig, true); ntlmauthenticator(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after ntlmauthenticator()"; CheckOldCachesLog(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after CheckOldCachesLog()"; DeletedCaches(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after DeletedCaches()"; caches_center(true); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after caches_center()"; squid_stores_status(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after squid_stores_status()"; squid_mem_status(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after squid_mem_status()"; squid_memory_monitor(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after squid_memory_monitor()"; caches_size(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after caches_size()"; if ($MonitConfig["watchdog"] == 0) { if ($GLOBALS["VERBOSE"]) { echo "Watchdog is disabled...\n"; } counters(true); return; } if ($processtime < 5) { return; } if ($GLOBALS["VERBOSE"]) { echo "Check DefaultRoute\n"; } DefaultRoute(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after DefaultRoute()"; if ($GLOBALS["VERBOSE"]) { echo "Check UFDB\n"; } CheckUFDBGuardLocalThreads(); CheckUFDBGuardConfig(); CheckUFDBGuardPort(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after CheckUFDBGuardConfig()"; if ($GLOBALS["VERBOSE"]) { echo "PING_GATEWAY()\n"; } PING_GATEWAY(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after PING_GATEWAY()"; if ($GLOBALS["VERBOSE"]) { echo "SwapWatchdog()\n"; } SwapWatchdog(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after SwapWatchdog()"; if ($GLOBALS["VERBOSE"]) { echo "Checks_Winbindd()\n"; } Checks_Winbindd(); if ($GLOBALS["VERBOSE"]) { echo "CheckStoreDirs()\n"; } $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after Checks_Winbindd()"; CheckStoreDirs(); if ($GLOBALS["VERBOSE"]) { echo "MemBoosters()\n"; } $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after CheckStoreDirs()"; MemBoosters(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after MemBoosters()"; if ($GLOBALS["VERBOSE"]) { echo "SwapCache()\n"; } SwapCache($MonitConfig); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after SwapCache()"; MaxSystemLoad($MonitConfig); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after MaxSystemLoad()"; if ($GLOBALS["VERBOSE"]) { echo "CheckAvailableSize()\n"; } CheckAvailableSize(); $GLOBALS["ALL_SCORES_WHY"][] = "score: {$GLOBALS["ALL_SCORES"]} after CheckAvailableSize()"; FailOverCheck(); DNSCACHE(); cache_center_status(); if ($GLOBALS["VERBOSE"]) { echo "counters()\n"; } counters(true); if ($NtpdateAD == 1) { $pidtimeNTPT = $unix->file_time_min($pidtimeNTP); if ($pidtimeNTPT > 120) { if ($GLOBALS["VERBOSE"]) { echo "/usr/share/artica-postfix/exec.kerbauth.php --ntpdate\n"; } shell_exec("{$nohup} {$php} /usr/share/artica-postfix/exec.kerbauth.php --ntpdate >/dev/null 2>&1 &"); @unlink($pidtimeNTP); @file_put_contents($pidtimeNTP, time()); } } }
function remove_database() { $q = new mysql(); $unix = new unix(); $sock = new sockets(); $ZarafaDedicateMySQLServer = $sock->GET_INFO("ZarafaDedicateMySQLServer"); if (!is_numeric($ZarafaDedicateMySQLServer)) { $ZarafaDedicateMySQLServer = 0; } if ($ZarafaDedicateMySQLServer == 1) { shell_exec($unix->LOCATE_PHP5_BIN() . " /usr/share/artica-postfix/exec.zarafa-db.php --remove-database"); return; } $MYSQL_DATA_DIR = $unix->MYSQL_DATA_DIR(); $q->DELETE_DATABASE("zarafa"); if (!$q->ok) { echo "Error while removing zarafa database...{$q->mysql_error}\n"; return; } if (!is_dir($MYSQL_DATA_DIR)) { echo "Failed to locate {$MYSQL_DATA_DIR}\n"; return; } if (is_file("/etc/artica-postfix/ZARFA_FIRST_INSTALL")) { @unlink("/etc/artica-postfix/ZARFA_FIRST_INSTALL"); } $kill = $unix->find_program("kill"); $pidof = $unix->find_program("pidof"); $zarafa_server = $unix->find_program("zarafa-server"); shell_exec("{$kill} -9 `{$pidof} {$zarafa_server}` >/dev/null 2>&1"); echo "Starting zarafa..............: remove {$MYSQL_DATA_DIR}/ib_logfile*\n"; shell_exec("/bin/rm -f {$MYSQL_DATA_DIR}/ib_logfile*"); shell_exec("/bin/rm -f {$MYSQL_DATA_DIR}/ibdata*"); echo "Starting zarafa..............: remove {$MYSQL_DATA_DIR}/zarafa*\n"; shell_exec("/bin/rm -rf {$MYSQL_DATA_DIR}/zarafa"); echo "Starting zarafa..............: restart MySQL\n"; mysql_admin_mysql(1, "Restarting MySQL service...", null, __FILE__, __LINE__); shell_exec("/etc/init.d/mysql restart --force --framework=" . __FILE__ . " >/tmp/zarafa_removedb 2>&1"); echo "Starting zarafa..............: restart Zarafa server\n"; shell_exec("/etc/init.d/zarafa-server restart >>/tmp/zarafa_removedb 2>&1"); $unix->send_email_events("Success removing zarafa databases", "removed {$MYSQL_DATA_DIR}/ib_logfile*\nremoved {$MYSQL_DATA_DIR}/ibdata*\nremoved {$MYSQL_DATA_DIR}/zarafa\n\n" . @file_get_contents("/tmp/zarafa_removedb"), "mailbox"); }
function mysql_server() { if (!$GLOBALS["CLASS_USERS"]->mysql_installed) { return; } $master_pid = mysql_server_pid(); $mysqlversion = mysqld_version(); $l[] = "[ARTICA_MYSQL]"; $l[] = "service_name=APP_MYSQL_ARTICA"; $l[] = "master_version={$mysqlversion}"; $l[] = "service_cmd=/etc/init.d/mysql"; $l[] = "service_disabled=1"; $l[] = "watchdog_features=1"; $l[] = "family=system"; $status = $GLOBALS["CLASS_UNIX"]->PROCESS_STATUS($master_pid); events("mysqld status = {$status}", __FUNCTION__, __LINE__); shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --watch --framework=" . __FILE__ . " >/dev/null 2>&1 &"); $GLOBALS["CLASS_UNIX"]->chown_func("mysql", "mysql", "/var/run/mysqld"); $GLOBALS["CLASS_UNIX"]->chown_func("mysql", "mysql", "/var/log/mysql"); @chmod("/var/run/mysqld", 0777); if (!$GLOBALS["CLASS_UNIX"]->process_exists($master_pid)) { events("mysqld not running....", __FUNCTION__, __LINE__); if (!$GLOBALS["DISABLE_WATCHDOG"]) { exec("{$GLOBALS["TAILBIN"]} -n 120 /var/lib/mysql/mysqld.err 2>&1", $tailR); $GLOBALS["CLASS_UNIX"]->send_email_events("MySQL not running, starting MySQL service and repair", @implode("\n", $GLOBALS["MYSQL_WATCHOG_EVENTS"]) . "\n" . @implode("\n", $tailR), "system"); if ($GLOBALS["SQUID_INSTALLED"]) { squid_admin_mysql(0, "MySQL not running, starting MySQL service and repair", @implode("\n", $GLOBALS["MYSQL_WATCHOG_EVENTS"]) . "\n" . @implode("\n", $tailR), __FILE__, __LINE__); } shell_exec2("{$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.initd-mysql.php >/dev/null 2>&1"); shell_exec2("{$GLOBALS["nohup"]} /etc/init.d/mysql start >/dev/null 2>&1 &"); shell_exec2("{$GLOBALS["nohup"]} /usr/share/artica-postfix/exec.exec.mysqld.crash.php --crashed --force >/dev/null 2>&1 &"); } $l[] = ""; return implode("\n", $l); return; } else { events("mysqld running -> exec.rrd.php --mysql ....", __FUNCTION__, __LINE__); shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.rrd.php --mysql >/dev/null 2>&1 &"); events("mysqld running -> mysql_watchdog() ....", __FUNCTION__, __LINE__); mysql_watchdog(); } $l[] = "running=1"; $l[] = GetMemoriesOf($master_pid); $l[] = ""; $AS_CGROUP = false; if ($GLOBALS["CLASS_SOCKETS"]->EnableIntelCeleron == 1) { $AS_CGROUP = true; } if ($AS_CGROUP) { events("mysqld cgroup must be enabled ....", __FUNCTION__, __LINE__); $cgroups = new status_cgroups(); $limit = $cgroups->GetLimit($master_pid); if ($cgroups->GetLimit($master_pid) == "unlimited") { $cgroups->set_limit("mysql", $master_pid); } } if (!$GLOBALS["DISABLE_WATCHDOG"]) { mysqld_init_fix(); } exec("{$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.build.php --multi-status 2>&1", $result1s); $l[] = "" . @implode("\n", $result1s); shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --engines --framework=" . __FILE__ . " >/dev/null 2>&1 &"); if (!$GLOBALS["DISABLE_WATCHDOG"]) { if (!$GLOBALS["CLASS_UNIX"]->is_socket("/var/run/mysqld/mysqld.sock")) { $xxx = array(); exec("/usr/bin/stat /var/run/mysqld/mysqld.sock 2>&1", $xxx); mysql_admin_mysql(0, "/var/run/mysqld/mysqld.sock no such socket [action=restart]", @implode("\n", $xxx)); shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --restart --socketfailed --framework=" . __FILE__ . " >/dev/null 2>&1 &"); } $DisableMessaging = intval($GLOBALS["CLASS_SOCKETS"]->GET_INFO("DisableMessaging")); if ($DisableMessaging == 0) { $dir = "/var/lib/mysql/postfixlog"; $unix = new unix(); $countDefiles = $GLOBALS["CLASS_UNIX"]->COUNT_FILES($dir) / 2; if ($countDefiles > 500) { shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.postfix.miltergrey.stats.php >/dev/null 2>&1 &"); } } } $CacheSchedules = $GLOBALS["CLASS_UNIX"]->file_time_min("/etc/artica-postfix/pids/exec.mysqld.crash.php.check_crashed.time"); events("exec.mysqld.crash.php.check_crashed.time = {$CacheSchedules}/240Min", __FUNCTION__, __LINE__); if ($CacheSchedules > 240) { if (!system_is_overloaded()) { $cmd = trim("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysqld.crash.php --crashed >/dev/null 2>&1 &"); if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } shell_exec2($cmd); } } $CacheSchedules = $GLOBALS["CLASS_UNIX"]->file_time_min("/etc/artica-postfix/pids/exec.mysql.start.php.test_sockets.time"); events("exec.mysql.start.php.test_sockets.time = {$CacheSchedules}/15Min", __FUNCTION__, __LINE__); if ($CacheSchedules > 15) { $cmd = trim("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --test-sock >/dev/null 2>&1 &"); if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } shell_exec2($cmd); } return implode("\n", $l); return; }
function check_crashed_squid() { $FILE_LOG = "/opt/squidsql/error.log"; $DB_PATH = "/opt/squidsql/data"; // /etc/artica-postfix/pids/exec.mysqld.crash.php.check_crashed_squid.time $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; if ($GLOBALS["VERBOSE"]) { echo "pidTime: {$pidTime}\n"; } $unix = new unix(); $pid = $unix->get_pid_from_file($pidfile); $sock = new sockets(); if ($unix->process_exists($pid, basename(__FILE__))) { $pidTime = $unix->PROCCESS_TIME_MIN($pid); if ($pidTime > 120) { $kill = $unix->find_program("kill"); unix_system_kill_force($pid); die; } return; } @file_put_contents($pidfile, getmypid()); $Time = $unix->file_time_min($pidTime); if (!$GLOBALS["VERBOSE"]) { if ($Time < 240) { return; } } if (!is_file($FILE_LOG)) { return; } $myisamchk = $unix->find_program("myisamchk"); $echo = $unix->find_program("echo"); if (!is_file($myisamchk)) { return; } $f = explode("\n", @file_get_contents($FILE_LOG)); $GLOBALS["CRASHED"] = array(); $PATHS = array(); while (list($num, $line) = each($f)) { if (preg_match("#Aborted connection [0-9]+#", $line)) { continue; } if (preg_match("#Got an error from thread_id#", $line)) { continue; } if (preg_match("#MySQL thread id [0-9]+#", $line)) { continue; } if (preg_match("#ERROR.*?Table.*?\\/(.+?)\\/(.*?)'\\s+is marked as crashed#", $line, $re)) { $GLOBALS["CRASHED"][$re[1]][] = $re[2]; continue; } if (preg_match("#Incorrect key file for table './(.+?)\\/(.+?)\\.MYI'; try to repair it#", $line, $re)) { mysql_admin_mysql(1, "{$re[1]}/{$re[2]} Incorrect key file for table [action=repair]", @implode("\n", $xxx)); $GLOBALS["CRASHED"][$re[1]][] = $re[2]; continue; } if (preg_match("#Got error 127 when reading table './(.+?)\\/(.+?)'#", $line, $re)) { mysql_admin_mysql(1, "{$re[1]}/{$re[2]} Got error 127 when reading table [action=repair]", @implode("\n", $xxx)); $GLOBALS["CRASHED"][$re[1]][] = $re[2]; continue; } if ($GLOBALS["VERBOSE"]) { echo $line . " no match\n"; } } if (count($GLOBALS["CRASHED"]) == 0) { return; } while (list($database, $tables) = each($GLOBALS["CRASHED"])) { while (list($a, $table) = each($tables)) { $path = "{$DB_PATH}/{$database}/{$table}.MYI"; if (is_file("{$DB_PATH}/{$database}/{$table}.TMD")) { @copy("{$DB_PATH}/{$database}/{$table}.TMD", "/var/lib/mysql/{$database}/{$table}." . time() . ".TMD"); @unlink("{$DB_PATH}/{$database}/{$table}.TMD"); } $PATHS[$path] = true; } } while (list($filepath, $none) = each($PATHS)) { $t = time(); $cmd = "{$myisamchk} -f -r {$filepath} 2>&1"; if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } $results = array(); exec("{$cmd}", $results); $Took = $unix->distanceOfTimeInWords($t, time()); mysql_admin_mysql(1, basename($filepath) . " repair report, took {$Took}", @implode("\n", $results)); system_admin_events(basename($filepath) . " repair report, took {$Took}", @implode("\n", $results), __FILE__, __LINE__, "mysql"); } shell_exec("{$echo} \"\" >{$FILE_LOG}"); }
function mysql_server() { if (!$GLOBALS["CLASS_USERS"]->mysql_installed) { return; } $program_path = $GLOBALS["CLASS_UNIX"]->find_program("mysqld"); if ($program_path == null) { if (is_file("/usr/sbin/mysqld")) { $program_path = "/usr/sbin/mysqld"; } } $pid_path = GetVersionOf("mysql-pid"); if ($pid_path == null) { if ($GLOBALS["VERBOSE"]) { echo "Pid path is null -> PIDOF({$program_path})"; } $master_pid = $GLOBALS["CLASS_UNIX"]->PIDOF($program_path); } else { $master_pid = trim(@file_get_contents($pid_path)); } if (!$GLOBALS["CLASS_UNIX"]->process_exists($master_pid)) { if ($GLOBALS["VERBOSE"]) { echo "Pid {$master_pid} not in memory -> PIDOF({$program_path})\n"; } $master_pid = $GLOBALS["CLASS_UNIX"]->PIDOF($program_path); } $mysqlversion = mysqld_version(); $l[] = "[ARTICA_MYSQL]"; $l[] = "service_name=APP_MYSQL_ARTICA"; $l[] = "master_version={$mysqlversion}"; $l[] = "service_cmd=/etc/init.d/mysql"; $l[] = "service_disabled=1"; $l[] = "pid_path={$pid_path}"; $l[] = "bin_path={$program_path}"; $l[] = "watchdog_features=1"; $l[] = "family=system"; $status = $GLOBALS["CLASS_UNIX"]->PROCESS_STATUS($master_pid); if ($GLOBALS["VERBOSE"]) { echo "Mysqld status = {$status}\n"; print_r($status); } shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --watch --framework=" . __FILE__ . " >/dev/null 2>&1 &"); $GLOBALS["CLASS_UNIX"]->chown_func("mysql", "mysql", "/var/run/mysqld"); $GLOBALS["CLASS_UNIX"]->chown_func("mysql", "mysql", "/var/log/mysql"); if (!$GLOBALS["CLASS_UNIX"]->process_exists($master_pid)) { if (!$GLOBALS["DISABLE_WATCHDOG"]) { $GLOBALS["CLASS_UNIX"]->send_email_events("MySQL not running, starting MySQL service", null, "system"); if ($GLOBALS["SQUID_INSTALLED"]) { squid_admin_mysql(0, "MySQL not running, starting MySQL service", null, __FILE__, __LINE__); } shell_exec2("{$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.initd-mysql.php >/dev/null 2>&1"); shell_exec2("{$GLOBALS["nohup"]} /etc/init.d/mysql start >/dev/null 2>&1 &"); } $l[] = ""; return implode("\n", $l); return; } else { shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.rrd.php --mysql >/dev/null 2>&1 &"); mysql_watchdog(); } $l[] = "running=1"; $l[] = GetMemoriesOf($master_pid); $l[] = ""; if (!$GLOBALS["DISABLE_WATCHDOG"]) { mysqld_init_fix(); } exec("{$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.build.php --multi-status 2>&1", $result1s); $l[] = "" . @implode("\n", $result1s); shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --engines --framework=" . __FILE__ . " >/dev/null 2>&1 &"); if (!$GLOBALS["DISABLE_WATCHDOG"]) { if (!$GLOBALS["CLASS_UNIX"]->is_socket("/var/run/mysqld/mysqld.sock")) { $xxx = array(); exec("/usr/bin/stat /var/run/mysqld/mysqld.sock 2>&1", $xxx); mysql_admin_mysql(0, "/var/run/mysqld/mysqld.sock no such socket [action=restart]", @implode("\n", $xxx)); shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --restart --socketfailed --framework=" . __FILE__ . " >/dev/null 2>&1 &"); } $DisableMessaging = intval($GLOBALS["CLASS_SOCKETS"]->GET_INFO("DisableMessaging")); if ($DisableMessaging == 0) { $dir = "/var/lib/mysql/postfixlog"; $unix = new unix(); $countDefiles = $GLOBALS["CLASS_UNIX"]->COUNT_FILES($dir) / 2; if ($countDefiles > 500) { shell_exec2("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.postfix.miltergrey.stats.php >/dev/null 2>&1 &"); } } } $CacheSchedules = $GLOBALS["CLASS_UNIX"]->file_time_min("/etc/artica-postfix/pids/exec.mysqld.crash.php.check_crashed.time"); if ($CacheSchedules > 240) { if (!system_is_overloaded()) { $cmd = trim("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysqld.crash.php --crashed >/dev/null 2>&1 &"); if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } shell_exec2($cmd); } } $CacheSchedules = $GLOBALS["CLASS_UNIX"]->file_time_min("/etc/artica-postfix/pids/exec.mysql.start.php.test_sockets.time"); if ($CacheSchedules > 15) { $cmd = trim("{$GLOBALS["nohup"]} {$GLOBALS["NICE"]} {$GLOBALS["PHP5"]} /usr/share/artica-postfix/exec.mysql.start.php --test-sock >/dev/null 2>&1 &"); if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } shell_exec2($cmd); } return implode("\n", $l); return; }