Inheritance: extends Scalr_Model
Exemplo n.º 1
0
 public function OnStartForking()
 {
     // start cron, which runs scripts by it's schedule queue
     try {
         $db = \Scalr::getDb();
         // set status to "finished" for active tasks, which ended or executed once
         $db->Execute("UPDATE scheduler SET `status` = ? WHERE\n                `status` = ? AND (\n                    CONVERT_TZ(`end_time`,'SYSTEM',`timezone`) < CONVERT_TZ(NOW(),'SYSTEM',`timezone`) OR\n                    (CONVERT_TZ(`last_start_time`,'SYSTEM',`timezone`) < CONVERT_TZ(NOW(),'SYSTEM',`timezone`) AND `restart_every` = 0)\n                )", array(Scalr_SchedulerTask::STATUS_FINISHED, Scalr_SchedulerTask::STATUS_ACTIVE));
         // get active tasks: first run (condition and last_start_time is null), others (condition and last_start_time + interval * 0.9 < now())
         $taskList = $db->GetAll("SELECT *\n                FROM scheduler\n                WHERE\n                    `status` = ? AND\n                    (`end_time` IS NULL OR CONVERT_TZ(`end_time`,'SYSTEM',`timezone`) > CONVERT_TZ(NOW(),'SYSTEM',`timezone`)) AND\n                    (`start_time` IS NULL OR CONVERT_TZ(`start_time`,'SYSTEM',`timezone`) <= CONVERT_TZ(NOW(),'SYSTEM',`timezone`)) AND\n                    (\n                        `last_start_time` IS NULL OR\n                        `last_start_time` IS NOT NULL AND `start_time` IS NULL AND (CONVERT_TZ(last_start_time + INTERVAL restart_every MINUTE, 'SYSTEM', `timezone`) < CONVERT_TZ(NOW(),'SYSTEM',`timezone`)) OR\n                        `last_start_time` IS NOT NULL AND `start_time` IS NOT NULL AND (CONVERT_TZ(last_start_time + INTERVAL (restart_every * 0.9) MINUTE, 'SYSTEM', `timezone`) < CONVERT_TZ(NOW(),'SYSTEM',`timezone`))\n                    )\n                ORDER BY IF (last_start_time, last_start_time, start_time), order_index ASC\n            ", array(Scalr_SchedulerTask::STATUS_ACTIVE));
         if (!$taskList) {
             $this->Logger->info(_("There is no tasks to execute in scheduler table"));
             exit;
         }
         foreach ($taskList as $task) {
             // check account status (active or inactive)
             try {
                 if (Scalr_Account::init()->loadById($task['account_id'])->status != Scalr_Account::STATUS_ACTIVE) {
                     continue;
                 }
             } catch (Exception $e) {
                 $this->Logger->info("Invalid scheduler task #{$task['id']}: {$e->getMessage()}");
             }
             if ($task['last_start_time'] && $task['start_time']) {
                 // try to auto-align time to start time
                 $startTime = new DateTime($task['start_time']);
                 $startTime->setTimezone(new DateTimeZone($task['timezone']));
                 $currentTime = new DateTime('now', new DateTimeZone($task['timezone']));
                 $offset = $startTime->getOffset() - $currentTime->getOffset();
                 $num = ($currentTime->getTimestamp() - $startTime->getTimestamp() - $offset) / ($task['restart_every'] * 60);
                 // num should be less than 0.5
                 if (floor($num) != round($num, 0, PHP_ROUND_HALF_UP)) {
                     continue;
                 }
             }
             $taskObj = new Scalr_SchedulerTask();
             $taskObj->loadById($task['id']);
             if ($taskObj->execute()) {
                 // convert_tz
                 $taskObj->updateLastStartTime();
                 $this->Logger->info(sprintf("Task {$taskObj->id} successfully sent"));
             }
         }
     } catch (Exception $e) {
         $this->Logger->warn(sprintf("Can't execute task {$task['id']}. Error message: %s", $e->getMessage()));
     }
 }
Exemplo n.º 2
0
 public function xDeleteAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_GENERAL_SCHEDULERTASKS, Acl::PERM_GENERAL_SCHEDULERTASKS_MANAGE);
     $this->request->defineParams(array('tasks' => array('type' => 'json')));
     $processed = [];
     foreach ($this->getParam('tasks') as $taskId) {
         $task = Scalr_SchedulerTask::init()->loadById($taskId);
         $this->user->getPermissions()->validate($task);
         $task->delete();
         $processed[] = $task->id;
     }
     $this->response->success("Selected task(s) successfully removed");
     $this->response->data(['processed' => $processed]);
 }
Exemplo n.º 3
0
 public function xTransferAction()
 {
     foreach ($this->db->GetAll('SELECT * FROM scheduler_tasks WHERE client_id = ?', array($this->user->getAccountId())) as $taskOld) {
         $task = Scalr_SchedulerTask::init();
         $task->name = $taskOld['task_name'];
         $task->type = $taskOld['task_type'];
         $task->targetId = $taskOld['target_id'];
         $task->targetType = $taskOld['target_type'];
         $task->timezone = $taskOld['timezone'];
         $timezone = new DateTimeZone($taskOld['timezone']);
         $startTm = new DateTime($taskOld['start_time_date']);
         $endTm = new DateTime($taskOld['end_time_date']);
         $lastStartTm = new DateTime($taskOld['last_start_time']);
         // old time in timezone (from record) to server time (timezone leave for UI)
         Scalr_Util_DateTime::convertDateTime($startTm, null, $timezone);
         Scalr_Util_DateTime::convertDateTime($endTm, null, $timezone);
         Scalr_Util_DateTime::convertDateTime($lastStartTm, null, $timezone);
         $task->startTime = $startTm->format('Y-m-d H:i:s');
         $task->endTime = $endTm->format('Y-m-d H:i:s');
         $task->lastStartTime = $taskOld['last_start_time'] ? $lastStartTm->format('Y-m-d H:i:s') : NULL;
         switch ($taskOld['target_type']) {
             case SCRIPTING_TARGET::FARM:
                 try {
                     $DBFarm = DBFarm::LoadByID($taskOld['target_id']);
                 } catch (Exception $e) {
                     continue 2;
                 }
                 break;
             case SCRIPTING_TARGET::ROLE:
                 try {
                     $DBFarmRole = DBFarmRole::LoadByID($taskOld['target_id']);
                     $a = $DBFarmRole->GetRoleObject()->name;
                     $a = $DBFarmRole->FarmID;
                     $a = $DBFarmRole->GetFarmObject()->Name;
                 } catch (Exception $e) {
                     continue 2;
                 }
                 break;
             case SCRIPTING_TARGET::INSTANCE:
                 $serverArgs = explode(':', $taskOld['target_id']);
                 try {
                     $DBServer = DBServer::LoadByFarmRoleIDAndIndex($serverArgs[0], $serverArgs[1]);
                     $a = "({$DBServer->remoteIp})";
                     $DBFarmRole = $DBServer->GetFarmRoleObject();
                     $a = $DBServer->farmId;
                     $a = $DBFarmRole->GetFarmObject()->Name;
                     $a = $DBServer->farmRoleId;
                     $a = $DBFarmRole->GetRoleObject()->name;
                 } catch (Exception $e) {
                     continue 2;
                 }
                 break;
         }
         $config = unserialize($taskOld['task_config']);
         $r = array();
         switch ($task->type) {
             case Scalr_SchedulerTask::SCRIPT_EXEC:
                 $r['scriptId'] = (string) $config['script_id'];
                 unset($config['script_id']);
                 $r['scriptIsSync'] = (string) $config['issync'];
                 unset($config['issync']);
                 $r['scriptTimeout'] = (string) $config['timeout'];
                 unset($config['timeout']);
                 $r['scriptVersion'] = (string) $config['revision'];
                 unset($config['revision']);
                 $r['scriptOptions'] = $config;
                 break;
             case Scalr_SchedulerTask::LAUNCH_FARM:
                 break;
             case Scalr_SchedulerTask::TERMINATE_FARM:
                 $r['deleteDNSZones'] = $config['deleteDNS'];
                 $r['deleteCloudObjects'] = $config['keep_elastic_ips'] == '1' || $config['keep_ebs'] == '1' ? NULL : '1';
                 break;
         }
         $task->config = $r;
         $task->restartEvery = $taskOld['restart_every'];
         $task->orderIndex = $taskOld['order_index'];
         $task->status = $taskOld['status'];
         $task->accountId = $taskOld['client_id'];
         $task->envId = $taskOld['env_id'];
         $task->save();
     }
     $this->db->Execute('DELETE FROM scheduler_tasks WHERE client_id = ?', array($this->user->getAccountId()));
     $this->response->success('All tasks transfered successfully');
 }
Exemplo n.º 4
0
 public function xDeleteAction()
 {
     $this->request->defineParams(array('tasks' => array('type' => 'json')));
     foreach ($this->getParam('tasks') as $taskId) {
         $task = Scalr_SchedulerTask::init()->loadById($taskId);
         $this->user->getPermissions()->validate($task);
         $task->delete();
     }
     $this->response->success("Selected task(s) successfully removed");
 }
Exemplo n.º 5
0
 function Run()
 {
     global $db;
     $time = microtime(true);
     $db->Execute("\r\n\t\t\t\tCREATE TABLE IF NOT EXISTS `scheduler` (\r\n\t\t\t\t  `id` int(11) NOT NULL AUTO_INCREMENT,\r\n\t\t\t\t  `name` varchar(255) DEFAULT NULL,\r\n\t\t\t\t  `type` varchar(255) DEFAULT NULL,\r\n\t\t\t\t  `target_id` varchar(255) DEFAULT NULL COMMENT 'id of farm, farm_role or farm_role:index from other tables',\r\n\t\t\t\t  `target_type` varchar(255) DEFAULT NULL COMMENT 'farm, role or instance type',\r\n\t\t\t\t  `start_time` datetime DEFAULT NULL COMMENT 'start task''s time',\r\n\t\t\t\t  `end_time` datetime DEFAULT NULL COMMENT 'end task by this time',\r\n\t\t\t\t  `last_start_time` datetime DEFAULT NULL COMMENT 'the last time task was started',\r\n\t\t\t\t  `restart_every` int(11) DEFAULT '0' COMMENT 'restart task every N minutes',\r\n\t\t\t\t  `config` text COMMENT 'arguments for action',\r\n\t\t\t\t  `order_index` int(11) DEFAULT NULL COMMENT 'task order',\r\n\t\t\t\t  `timezone` varchar(100) DEFAULT NULL,\r\n\t\t\t\t  `status` varchar(11) DEFAULT NULL COMMENT 'active, suspended, finished',\r\n\t\t\t\t  `account_id` int(11) DEFAULT NULL COMMENT 'Task belongs to selected account',\r\n\t\t\t\t  `env_id` int(11) DEFAULT NULL,\r\n\t\t\t\t  PRIMARY KEY (`id`),\r\n\t\t\t\t  KEY `index` (`name`,`type`,`start_time`,`end_time`,`last_start_time`,`restart_every`,`order_index`,`status`,`account_id`,`env_id`)\r\n\t\t\t\t) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;\r\n\t\t\t");
     $cnt = 0;
     foreach ($db->GetAll('SELECT * FROM scheduler_tasks') as $taskOld) {
         $task = Scalr_SchedulerTask::init();
         $task->name = $taskOld['task_name'];
         $task->type = $taskOld['task_type'];
         $task->targetId = $taskOld['target_id'];
         $task->targetType = $taskOld['target_type'];
         $task->timezone = $taskOld['timezone'];
         $timezone = new DateTimeZone($taskOld['timezone']);
         $startTm = new DateTime($taskOld['start_time_date']);
         $endTm = new DateTime($taskOld['end_time_date']);
         $lastStartTm = new DateTime($taskOld['last_start_time']);
         // old time in timezone (from record) to server time (timezone leave for UI)
         Scalr_Util_DateTime::convertDateTime($startTm, null, $timezone);
         Scalr_Util_DateTime::convertDateTime($endTm, null, $timezone);
         Scalr_Util_DateTime::convertDateTime($lastStartTm, null, $timezone);
         $task->startTime = $startTm->format('Y-m-d H:i:s');
         $task->endTime = $endTm->format('Y-m-d H:i:s');
         $task->lastStartTime = $taskOld['last_start_time'] ? $lastStartTm->format('Y-m-d H:i:s') : NULL;
         switch ($taskOld['target_type']) {
             case SCRIPTING_TARGET::FARM:
                 try {
                     $DBFarm = DBFarm::LoadByID($taskOld['target_id']);
                 } catch (Exception $e) {
                     continue 2;
                 }
                 break;
             case SCRIPTING_TARGET::ROLE:
                 try {
                     $DBFarmRole = DBFarmRole::LoadByID($taskOld['target_id']);
                     $a = $DBFarmRole->GetRoleObject()->name;
                     $a = $DBFarmRole->FarmID;
                     $a = $DBFarmRole->GetFarmObject()->Name;
                 } catch (Exception $e) {
                     continue 2;
                 }
                 break;
             case SCRIPTING_TARGET::INSTANCE:
                 $serverArgs = explode(':', $taskOld['target_id']);
                 try {
                     $DBServer = DBServer::LoadByFarmRoleIDAndIndex($serverArgs[0], $serverArgs[1]);
                     $a = "({$DBServer->remoteIp})";
                     $DBFarmRole = $DBServer->GetFarmRoleObject();
                     $a = $DBServer->farmId;
                     $a = $DBFarmRole->GetFarmObject()->Name;
                     $a = $DBServer->farmRoleId;
                     $a = $DBFarmRole->GetRoleObject()->name;
                 } catch (Exception $e) {
                     continue 2;
                 }
                 break;
         }
         $config = unserialize($taskOld['task_config']);
         $r = array();
         switch ($task->type) {
             case Scalr_SchedulerTask::SCRIPT_EXEC:
                 $r['scriptId'] = (string) $config['script_id'];
                 unset($config['script_id']);
                 $r['scriptIsSync'] = (string) $config['issync'];
                 unset($config['issync']);
                 $r['scriptTimeout'] = (string) $config['timeout'];
                 unset($config['timeout']);
                 $r['scriptVersion'] = (string) $config['revision'];
                 unset($config['revision']);
                 $r['scriptOptions'] = $config;
                 break;
             case Scalr_SchedulerTask::LAUNCH_FARM:
                 break;
             case Scalr_SchedulerTask::TERMINATE_FARM:
                 $r['deleteDNSZones'] = $config['deleteDNS'];
                 $r['deleteCloudObjects'] = $config['keep_elastic_ips'] == '1' || $config['keep_ebs'] == '1' ? NULL : '1';
                 break;
         }
         $task->config = $r;
         $task->restartEvery = $taskOld['restart_every'];
         $task->orderIndex = $taskOld['order_index'];
         $task->status = $taskOld['status'];
         $task->accountId = $taskOld['client_id'];
         $task->envId = $taskOld['env_id'];
         $task->save();
     }
     print "Done.\n";
     $t = round(microtime(true) - $time, 2);
     print "Upgrade process took {$t} seconds\n\n\n";
 }