getDb() публичный статический Метод

Gets an ADO Database Connection as singleton
public static getDb ( boolean $forceNewConnection = null ) : ADODB_mysqli
$forceNewConnection boolean optional Force new connection. (false by default)
Результат ADODB_mysqli
Пример #1
0
 public function __call($method, $args)
 {
     // If observer enabled
     if (!$this->Config || $this->Config->GetFieldByName("IsEnabled")->Value == 0) {
         return;
     }
     $enabled = $this->Config->GetFieldByName("{$method}Notify");
     if (!$enabled || $enabled->Value == 0) {
         return;
     }
     $DB = \Scalr::getDb();
     // Event name
     $name = substr($method, 2);
     // Event message
     $message = $DB->GetOne("SELECT message FROM events WHERE event_id = ? LIMIT 1", array($args[0]->GetEventID()));
     $farm_name = $DB->GetOne("SELECT name FROM farms WHERE id=? LIMIT 1", array($args[0]->GetFarmID()));
     // Set subject
     if (!$farm_name) {
         $this->Mailer->setSubject("{$name} event notification (FarmID: {$args[0]->GetFarmID()})");
     } else {
         $this->Mailer->setSubject("{$name} event notification (FarmID: {$args[0]->GetFarmID()} FarmName: {$farm_name})");
     }
     // Set body
     $this->Mailer->setMessage($message);
     // Send mail
     try {
         $res = $this->Mailer->send();
     } catch (\Exception $e) {
         $res = false;
     }
     if (!$res) {
         Logger::getLogger(__CLASS__)->info("Mail sent to '{$this->Config->GetFieldByName("EventMailTo")->Value}'. Result: {$res}");
     }
 }
 public function StartThread($farminfo)
 {
     $db = \Scalr::getDb();
     $DBFarm = DBFarm::LoadByID($farminfo['id']);
     foreach ($DBFarm->GetFarmRoles() as $DBFarmRole) {
         foreach ($DBFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, SERVER_STATUS::PENDING, SERVER_STATUS::TROUBLESHOOTING)), array()) as $DBServer) {
             $launchTime = strtotime($DBServer->dateAdded);
             $lastCheckTime = (int) $DBServer->GetProperty(SERVER_PROPERTIES::STATISTICS_LAST_CHECK_TS);
             if (!$lastCheckTime) {
                 $lastCheckTime = $launchTime;
             }
             $period = round((time() - $lastCheckTime) / 60);
             $maxMinutes = date("j") * 24 * 60 - date("H") * 60;
             if ($period > $maxMinutes) {
                 $period = $maxMinutes;
             }
             $serverType = $DBServer->GetFlavor();
             if (!$serverType) {
                 continue;
             }
             $db->Execute("INSERT INTO servers_stats SET\n                    `usage` = ?,\n                    `instance_type` = ?,\n                    `env_id` = ?,\n                    `month` = ?,\n                    `year` = ?,\n                    `farm_id` = ?,\n                    `cloud_location` = ?\n                ON DUPLICATE KEY UPDATE `usage` = `usage` + ?\n                ", array($period, $serverType, $DBServer->envId, date("m"), date("Y"), $DBServer->farmId, $DBServer->GetCloudLocation(), $period));
             $DBServer->SetProperty(SERVER_PROPERTIES::STATISTICS_LAST_CHECK_TS, time());
         }
         //for each items
     }
 }
Пример #3
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::enqueue()
  */
 public function enqueue()
 {
     $queue = new ArrayObject([]);
     $db = \Scalr::getDb();
     $this->log('INFO', "Fetching farms...");
     $farms = [];
     $rs = $db->Execute("\n            SELECT env_id, value FROM governance\n            WHERE enabled = 1 AND name = ?\n        ", [Scalr_Governance::GENERAL_LEASE]);
     while ($env = $rs->FetchRow()) {
         $env['value'] = json_decode($env['value'], true);
         $period = 0;
         if (is_array($env['value']['notifications'])) {
             foreach ($env['value']['notifications'] as $notif) {
                 if ($notif['period'] > $period) {
                     $period = $notif['period'];
                 }
             }
             $dt = new DateTime();
             $dt->add(new DateInterval('P' . $period . 'D'));
             $fs = $db->GetAll("\n                    SELECT fs.farmid, f.status\n                    FROM farm_settings fs\n                    JOIN farms f ON f.id = fs.farmid\n                    WHERE fs.name = ? AND f.status = ? AND f.env_id = ? AND fs.value < ? AND fs.value != ''\n                ", [Entity\FarmSetting::LEASE_TERMINATE_DATE, FARM_STATUS::RUNNING, $env['env_id'], $dt->format('Y-m-d H:i:s')]);
             foreach ($fs as $f) {
                 if (!isset($farms[$f['farmid']])) {
                     $farms[$f['farmid']] = true;
                     $obj = new stdClass();
                     $obj->farmId = $f['farmid'];
                     $queue->append($obj);
                 }
             }
         }
     }
     $cnt = count($farms);
     $this->log('INFO', "%d lease task%s %s found", $cnt, $cnt != 1 ? 's' : '', $cnt != 1 ? 'were' : 'was');
     return $queue;
 }
Пример #4
0
 /**
  * @test
  * @dataProvider providerDiffFiles
  */
 public function testDiff(SplFileObject $source, SplFileObject $target, $testSourceSchema, $testTargetSchema)
 {
     $connection = \Scalr::getDb();
     try {
         if (!@$connection->Execute("SELECT 1;")) {
             $this->markTestSkipped("No DB connection!");
         }
     } catch (Exception $e) {
         $this->markTestSkipped("No DB connection!");
     }
     try {
         $connection->Execute("SET FOREIGN_KEY_CHECKS=0;");
         $this->createTestSchema($source, $connection, $testSourceSchema);
         $this->createTestSchema($target, $connection, $testTargetSchema);
         $diff = new Diff(new FileStream("ddl://localhost/{$testSourceSchema}"), new FileStream("ddl://localhost/{$testTargetSchema}"));
         $statements = $diff->diff();
         $connection->Execute("USE {$testTargetSchema};");
         foreach ($statements as $statement) {
             $connection->Execute($statement);
         }
         $diff = new Diff(new FileStream("ddl://localhost/{$testSourceSchema}"), new FileStream("ddl://localhost/{$testTargetSchema}"));
         $statements = $diff->diff();
         $this->assertEquals("", implode("\n", $statements));
     } catch (ADODB_Exception $adoe) {
         $this->markTestSkipped($adoe->getMessage());
     } catch (Exception $e) {
         $this->fail($e->getMessage($e->getMessage()));
     }
     $connection->Execute("DROP DATABASE IF EXISTS `{$testSourceSchema}`");
     $connection->Execute("DROP DATABASE IF EXISTS `{$testTargetSchema}`");
 }
Пример #5
0
 public function __call($method, $args)
 {
     // If observer enabled
     if (!$this->Config || $this->Config->GetFieldByName("IsEnabled")->Value == 0) {
         return;
     }
     $url = $this->Config->GetFieldByName("{$method}NotifyURL");
     if (!$url || $url->Value == '') {
         return;
     }
     $DB = \Scalr::getDb();
     // Event message
     $message = urlencode($DB->GetOne("SELECT message FROM events WHERE event_id = ? LIMIT 1", array($args[0]->GetEventID())));
     $ch = @curl_init();
     // set URL and other appropriate options
     @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
     @curl_setopt($ch, CURLOPT_URL, $url->Value);
     @curl_setopt($ch, CURLOPT_HEADER, false);
     @curl_setopt($ch, CURLOPT_POST, true);
     @curl_setopt($ch, CURLOPT_POSTFIELDS, "event={$method}&message={$message}");
     // grab URL and pass it to the browser
     @curl_exec($ch);
     $error = curl_error();
     if ($error) {
         Logger::getLogger(__CLASS__)->error($error);
     }
     // close cURL resource, and free up system resources
     @curl_close($ch);
 }
Пример #6
0
 public static function doJob($job)
 {
     $db = \Scalr::getDb();
     $messageSerializer = new Scalr_Messaging_XmlSerializer();
     $message = $db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($job->workload()));
     try {
         if ($message['handle_attempts'] >= 3) {
             $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
         } else {
             try {
                 $DBServer = DBServer::LoadByID($message['server_id']);
             } catch (Exception $e) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
                 return;
             }
             if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) {
                 // Only 0.2-68 or greater version support this feature.
                 if ($DBServer->IsSupported("0.2-68")) {
                     $msg = $messageSerializer->unserialize($message['message']);
                     $DBServer->SendMessage($msg);
                 } else {
                     $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::UNSUPPORTED, $message['id']));
                 }
             } elseif (in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
             }
         }
     } catch (Exception $e) {
         //var_dump($e->getMessage());
     }
 }
Пример #7
0
 /**
  * Constructor
  *
  * @param unknown_type $queue_name
  */
 public function __construct($queue_name)
 {
     $this->QueueName = $queue_name;
     $this->DB = \Scalr::getDb();
     $this->ReflectionTask = new ReflectionClass("Task");
     $this->LastTaskID = 0;
 }
Пример #8
0
 function __construct($zohoCrm)
 {
     $this->zohoCrm = $zohoCrm;
     $this->db = \Scalr::getDb();
     $this->zohoMappings = new Scalr_Integration_ZohoCrm_CustomFields();
     $this->logger = Logger::getLogger(__CLASS__);
 }
Пример #9
0
 /**
  * Setup db connection.
  * Based on defined options, this method connects to db defined in {@link $dsn}
  * and creates a {@link $table} table if {@link $createTable} is true.
  * @return boolean true if all ok.
  */
 function activateOptions()
 {
     $this->db = \Scalr::getDb();
     $this->layout = LoggerReflectionUtils::createObject('LoggerPatternLayoutScalr');
     $this->layout->setConversionPattern($this->getSql());
     $this->canAppend = true;
 }
Пример #10
0
 public function __construct($id = null)
 {
     $this->id = $id;
     $this->container = \Scalr::getContainer();
     $this->db = \Scalr::getDb();
     $this->dbMessageKeyNotFound = get_class($this) . " " . $this->dbMessageKeyNotFound;
 }
Пример #11
0
 public function __construct($envId, $scope = Scalr_Scripting_GlobalVariables::SCOPE_ENVIRONMENT)
 {
     $this->crypto = new Scalr_Util_CryptoTool(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB, @mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), @mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB));
     $this->cryptoKey = @file_get_contents(APPPATH . "/etc/.cryptokey");
     $this->envId = $envId;
     $this->scope = $scope;
     $this->db = \Scalr::getDb();
 }
Пример #12
0
 /**
  * Recrypt
  *
  * @param string     $scheme    Database scheme
  * @param CryptoTool $source    Current encryption
  * @param CryptoTool $target    New encryption
  * @param Console    $console   Console handler
  */
 public function __construct($scheme, CryptoTool $source, CryptoTool $target, Console $console)
 {
     $this->db = \Scalr::getDb();
     $this->scheme = $scheme;
     $this->source = $source;
     $this->target = $target;
     $this->console = $console;
 }
Пример #13
0
 public function __construct()
 {
     $this->request = Scalr_UI_Request::getInstance();
     $this->response = Scalr_UI_Response::getInstance();
     $this->user = $this->request->getUser();
     $this->environment = $this->request->getEnvironment();
     $this->container = Scalr::getContainer();
     $this->db = Scalr::getDb();
 }
Пример #14
0
 /**
  * @param int $accountId
  * @param int $envId
  * @param string $scope
  */
 public function __construct($accountId = 0, $envId = 0, $scope = Scalr_Scripting_GlobalVariables::SCOPE_SCALR)
 {
     $this->crypto = \Scalr::getContainer()->crypto;
     $this->accountId = $accountId;
     $this->envId = $envId;
     $this->scope = $scope;
     $this->listScopes = [self::SCOPE_SCALR, self::SCOPE_ACCOUNT, self::SCOPE_ENVIRONMENT, self::SCOPE_ROLE, self::SCOPE_FARM, self::SCOPE_FARMROLE, self::SCOPE_SERVER];
     $this->db = \Scalr::getDb();
 }
Пример #15
0
 /**
  * @return DBEBSVolume
  * @param string $volumeId
  */
 public static function loadByVolumeId($volumeId)
 {
     $db = \Scalr::getDb();
     $ebs_info = $db->GetRow("SELECT id FROM ec2_ebs WHERE volume_id = ? LIMIT 1", array($volumeId));
     if (!$ebs_info) {
         throw new Exception(sprintf(_("EBS volume ID#%s not found in database"), $volumeId));
     }
     return self::loadById($ebs_info['id']);
 }
Пример #16
0
 /**
  * @param int $accountId
  * @param int $envId
  * @param string $scope
  */
 public function __construct($accountId = 0, $envId = 0, $scope = ScopeInterface::SCOPE_SCALR)
 {
     $this->crypto = \Scalr::getContainer()->crypto;
     $this->accountId = $accountId;
     $this->envId = $envId;
     $this->scope = $scope;
     $this->listScopes = [ScopeInterface::SCOPE_SCALR, ScopeInterface::SCOPE_ACCOUNT, ScopeInterface::SCOPE_ENVIRONMENT, ScopeInterface::SCOPE_ROLE, ScopeInterface::SCOPE_FARM, ScopeInterface::SCOPE_FARMROLE, ScopeInterface::SCOPE_SERVER];
     $this->db = \Scalr::getDb();
 }
Пример #17
0
 public function __construct(DBServer $DBServer)
 {
     parent::__construct();
     $this->DBServer = $DBServer;
     $r_server = \Scalr::getDb()->GetRow("SELECT server_id FROM servers WHERE replace_server_id=? LIMIT 1", array($DBServer->serverId));
     if ($r_server) {
         $this->replacementDBServer = DBServer::LoadByID($r_server['server_id']);
     }
 }
Пример #18
0
 /**
  * Load Client Object by E-mail
  * @param string $email
  * @return Client $Client
  */
 public static function LoadByEmail($email)
 {
     $db = \Scalr::getDb();
     $clientid = $db->GetOne("SELECT id FROM clients WHERE email=? LIMIT 1", array($email));
     if (!$clientid) {
         throw new Exception(sprintf(_("Client with email=%s not found in database"), $email));
     }
     return self::Load($clientid);
 }
Пример #19
0
 /**
  * Auto-snapshoting
  * {@inheritdoc}
  * @see \Scalr\System\Pcntl\ProcessInterface::OnStartForking()
  */
 public function OnStartForking()
 {
     $db = \Scalr::getDb();
     // selects rows where the snapshot's time has come to create new snapshot.
     $resultset = $db->Execute("\n            SELECT * FROM autosnap_settings\n            WHERE (`dtlastsnapshot` < NOW() - INTERVAL `period` HOUR OR `dtlastsnapshot` IS NULL)\n            AND objectid != '0'\n            AND object_type = ?\n        ", array(AUTOSNAPSHOT_TYPE::RDSSnap));
     while ($snapshotsSettings = $resultset->FetchRow()) {
         try {
             $environment = Scalr_Environment::init()->loadById($snapshotsSettings['env_id']);
             $aws = $environment->aws($snapshotsSettings['region']);
             // Check instance. If instance wasn't found then delete current recrod from settings table
             try {
                 $aws->rds->dbInstance->describe($snapshotsSettings['objectid']);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid") || stristr($e->getMessage(), "security token included in the request is invalid")) {
                     $db->Execute("\n                            DELETE FROM autosnap_settings WHERE id = ?\n                        ", array($snapshotsSettings['id']));
                 }
                 $this->Logger->error(sprintf(_("RDS instance %s was not found. " . "Auto-snapshot settings for this instance will be deleted. %s."), $snapshotsSettings['objectid'], $e->getMessage()));
                 throw $e;
             }
             // snapshot random unique name
             $snapshotId = "scalr-auto-" . dechex(microtime(true) * 10000) . rand(0, 9);
             try {
                 // Create new snapshot
                 $aws->rds->dbSnapshot->create($snapshotsSettings['objectid'], $snapshotId);
                 // update last snapshot creation date in settings
                 $db->Execute("\n                        UPDATE autosnap_settings\n                        SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?\n                    ", array($snapshotId, $snapshotsSettings['id']));
                 // create new snapshot record in DB
                 $db->Execute("\n                        INSERT INTO rds_snaps_info\n                        SET snapid = ?,\n                            comment = ?,\n                            dtcreated = NOW(),\n                            region = ?,\n                            autosnapshotid = ?\n                    ", array($snapshotId, _("Auto snapshot"), $snapshotsSettings['region'], $snapshotsSettings['id']));
             } catch (Exception $e) {
                 $this->Logger->warn(sprintf(_("Could not create RDS snapshot: %s."), $e->getMessage()));
             }
             // Remove old snapshots
             if ($snapshotsSettings['rotate'] != 0) {
                 $oldSnapshots = $db->GetAll("\n                        SELECT * FROM rds_snaps_info\n                        WHERE autosnapshotid = ?\n                        ORDER BY id ASC\n                    ", array($snapshotsSettings['id']));
                 if (count($oldSnapshots) > $snapshotsSettings['rotate']) {
                     while (count($oldSnapshots) > $snapshotsSettings['rotate']) {
                         // takes the oldest snapshot ...
                         $deletingSnapshot = array_shift($oldSnapshots);
                         try {
                             // and deletes it from amazon and from DB
                             $aws->rds->dbSnapshot->delete($deletingSnapshot['snapid']);
                             $db->Execute("\n                                    DELETE FROM rds_snaps_info WHERE id = ?\n                                ", array($deletingSnapshot['id']));
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid")) {
                                 $db->Execute("\n                                        DELETE FROM rds_snaps_info WHERE id = ?\n                                    ", array($deletingSnapshot['id']));
                             }
                             $this->Logger->error(sprintf(_("DBsnapshot %s for RDS instance %s was not found and cannot be deleted . %s."), $deletingSnapshot['snapid'], $snapshotsSettings['objectid'], $e->getMessage()));
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             $this->Logger->warn(sprintf(_("Cannot create snapshot for RDS Instance %s. %s"), $snapshotsSettings['objectid'], $e->getMessage()));
         }
     }
 }
Пример #20
0
 /**
  * @param $configId
  * @param $serverIndex
  * @return bool|Scalr\Farm\Role\FarmRoleStorageDevice
  */
 public static function getByConfigIdAndIndex($configId, $serverIndex)
 {
     $db = \Scalr::getDb();
     $id = $db->GetOne("SELECT storage_id FROM farm_role_storage_devices WHERE storage_config_id = ? AND server_index = ? AND status = ? LIMIT 1", array($configId, $serverIndex, self::STATUS_ACTIVE));
     if (!$id) {
         return false;
     }
     $device = new self();
     return $device->loadById($id);
 }
Пример #21
0
 /**
  * @param int $accountId
  * @param int $envId
  * @param string $scope
  */
 public function __construct($accountId = 0, $envId = 0, $scope = Scalr_Scripting_GlobalVariables::SCOPE_SCALR)
 {
     $this->crypto = new Scalr_Util_CryptoTool(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB, @mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), @mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB));
     $this->cryptoKey = @file_get_contents(APPPATH . "/etc/.cryptokey");
     $this->accountId = $accountId;
     $this->envId = $envId;
     $this->scope = $scope;
     $this->listScopes = [self::SCOPE_SCALR, self::SCOPE_ACCOUNT, self::SCOPE_ENVIRONMENT, self::SCOPE_ROLE, self::SCOPE_FARM, self::SCOPE_FARMROLE, self::SCOPE_SERVER];
     $this->db = \Scalr::getDb();
 }
Пример #22
0
 public function OnStartForking()
 {
     $db = \Scalr::getDb();
     // Get pid of running daemon
     $pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid");
     $this->Logger->info("Current daemon process PID: {$pid}");
     // Check is daemon already running or not
     if ($pid) {
         $Shell = new Scalr_System_Shell();
         // Set terminal width
         putenv("COLUMNS=400");
         // Execute command
         $ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent");
         $this->Logger->info("Shell->queryRaw(): {$ps}");
         if ($ps) {
             // daemon already running
             $this->Logger->info("Daemon running. All ok!");
             return true;
         }
     }
     $rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'");
     while ($row = $rows->FetchRow()) {
         $history = WebhookHistory::findPk(bin2hex($row['history_id']));
         if (!$history) {
             continue;
         }
         $endpoint = WebhookEndpoint::findPk($history->endpointId);
         $request = new HttpRequest();
         $request->setMethod(HTTP_METH_POST);
         if ($endpoint->url == 'SCALR_MAIL_SERVICE') {
             $request->setUrl('https://my.scalr.com/webhook_mail.php');
         } else {
             $request->setUrl($endpoint->url);
         }
         $request->setOptions(array('timeout' => 3, 'connecttimeout' => 3));
         $dt = new DateTime('now', new DateTimeZone("UTC"));
         $timestamp = $dt->format("D, d M Y H:i:s e");
         $canonical_string = $history->payload . $timestamp;
         $signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey);
         $request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json'));
         $request->setBody($history->payload);
         try {
             $request->send();
             $history->responseCode = $request->getResponseCode();
             if ($request->getResponseCode() <= 205) {
                 $history->status = WebhookHistory::STATUS_COMPLETE;
             } else {
                 $history->status = WebhookHistory::STATUS_FAILED;
             }
         } catch (Exception $e) {
             $history->status = WebhookHistory::STATUS_FAILED;
         }
         $history->save();
     }
 }
Пример #23
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::enqueue()
  */
 public function enqueue()
 {
     $queue = new ArrayObject([]);
     $db = \Scalr::getDb();
     // set status to "finished" for active tasks, which ended or executed once
     $db->Execute("\n            UPDATE scheduler\n            SET `status` = ?\n            WHERE `status` = ?\n            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            )\n        ", [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("\n            SELECT *\n            FROM scheduler\n            WHERE `status` = ?\n            AND (`end_time` IS NULL OR CONVERT_TZ(`end_time`,'SYSTEM',`timezone`) > CONVERT_TZ(NOW(),'SYSTEM',`timezone`))\n            AND (`start_time` IS NULL OR CONVERT_TZ(`start_time`,'SYSTEM',`timezone`) <= CONVERT_TZ(NOW(),'SYSTEM',`timezone`))\n            AND (`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) ASC\n        ", [Scalr_SchedulerTask::STATUS_ACTIVE]);
     if (!$taskList) {
         $this->getLogger()->info("There are no tasks to execute in scheduler table.");
         return $queue;
     }
     $this->getLogger()->info("Found %d tasks", count($taskList));
     foreach ($taskList as $task) {
         try {
             // check account status (active or inactive)
             if (Scalr_Account::init()->loadById($task['account_id'])->status != Scalr_Account::STATUS_ACTIVE) {
                 continue;
             }
         } catch (Exception $e) {
             $this->getLogger()->info("Scheduler task #%s could not start: %s", $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);
             $numFloor = floor($num);
             // we check tasks which are longer than hour
             if ($task['restart_every'] > 55) {
                 // check how much intervals were missed
                 $lastStartTime = new DateTime($task['last_start_time']);
                 $lastStartTime->setTimezone(new DateTimeZone($task['timezone']));
                 if (($currentTime->getTimestamp() - $lastStartTime->getTimestamp() - ($lastStartTime->getOffset() - $currentTime->getOffset())) / ($task['restart_every'] * 60) > 2) {
                     // we missed one extra (or more) interval, so let's check if currentTime is synchronized with startTime
                     if ($num - $numFloor > 0.1) {
                         $this->getLogger()->debug(sprintf('Delay task (missed interval): %s, num: %f', $task['name'], $num));
                         continue;
                     }
                 }
             }
             // because of timezone's transitions
             // num should be less than 0.5 (because of interval * 0.9 in SQL query)
             if ($numFloor != round($num, 0, PHP_ROUND_HALF_UP)) {
                 $this->getLogger()->debug(sprintf('Delay task (interval): %s, Offset: %d, num: %f, floor: %f, round: %f', $task['name'], $offset, $num, floor($num), round($num, 0, PHP_ROUND_HALF_UP)));
                 continue;
             }
         }
         $this->log('DEBUG', "Adding task %s to queue", $task['id']);
         $queue->append($task['id']);
     }
     return $queue;
 }
Пример #24
0
 protected function addIndex($table, $key = 'dtadded')
 {
     $db = \Scalr::getDb();
     $idxName = 'idx_' . $key;
     $row = $db->GetRow("SHOW INDEXES FROM `" . $table . "` WHERE `key_name` = ?", array($idxName));
     if (!empty($row)) {
         print "Nothing to do. Index {$idxName} does exist in {$table}.\n";
     } else {
         $db->Execute("ALTER TABLE `" . $table . "` ADD INDEX `" . $idxName . "` (`" . $key . "`)");
     }
 }
Пример #25
0
 /**
  * Prepares client to enqueue
  *
  * @throws Exception
  */
 public function prepare()
 {
     if (empty($this->db)) {
         $this->db = \Scalr::getDb();
     }
     if (empty($this->params)) {
         $this->prepareTemporary($this->parseIntervals($this->config()->intervals_attempts));
     }
     if (empty($this->stmt)) {
         $this->prepareStatement();
     }
 }
Пример #26
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::enqueue()
  */
 public function enqueue()
 {
     $plt = [];
     $args = [date("Y-m-d H:00:00"), Server::STATUS_RUNNING];
     foreach (array_keys(\SERVER_PLATFORMS::GetList()) as $platform) {
         $plt[] = "SELECT CONVERT(? USING latin1) AS `platform`";
         $args[] = $platform;
     }
     $args[] = Server::INFO_INSTANCE_VCPUS;
     \Scalr::getDb()->Execute("\n            INSERT IGNORE INTO platform_usage (`time`, `platform`, `value`)\n            SELECT ? AS `time`, p.`platform`, SUM(IF(s.status = ?, IFNULL(sp.`value`, 0), 0))\n            FROM (" . implode(" UNION ALL ", $plt) . ") AS p\n            LEFT JOIN servers AS s ON p.platform = s.platform\n            LEFT JOIN server_properties AS sp ON s.server_id = sp.server_id AND sp.`name` = ?\n            GROUP BY p.`platform`\n            ", $args);
     return new ArrayObject([]);
 }
Пример #27
0
 /**
  * @test
  * @functional
  */
 public function testFunctional()
 {
     $db = \Scalr::getDb();
     $entity = new TableEntity();
     $schema = $db->GetOne("SELECT DATABASE()");
     $tableInfo = $entity->findOne([['tableSchema' => $schema]]);
     $this->assertInstanceOf('Scalr\\Model\\Entity\\InformationSchema\\TableEntity', $tableInfo);
     /* @var $tableInfo TableEntity */
     $this->assertNotEmpty($tableInfo->engine);
     $this->assertNotEmpty($tableInfo->tableName);
     $this->assertNotEmpty($tableInfo->createTime);
     $this->assertInstanceOf('DateTime', $tableInfo->createTime);
 }
Пример #28
0
 /**
  * @param \DBFarmRole $farmRole
  * @return FarmRoleStorageConfig[]
  */
 public static function getByFarmRole(\DBFarmRole $farmRole)
 {
     $db = \Scalr::getDb();
     $configs = array();
     $ids = $db->GetCol('SELECT id FROM farm_role_storage_config WHERE farm_role_id = ?', array($farmRole->ID));
     foreach ($ids as $id) {
         $config = new FarmRoleStorageConfig($farmRole);
         if ($config->loadById($id)) {
             $configs[] = $config;
         }
     }
     return $configs;
 }
Пример #29
0
 /**
  * Constructor
  * @param $DBFarmRole
  * @return void
  */
 function __construct(DBFarmRole $DBFarmRole)
 {
     $this->db = \Scalr::getDb();
     $this->dbFarmRole = $DBFarmRole;
     $this->logger = Logger::getLogger(__CLASS__);
     $role_metrics = $this->db->Execute("SELECT id, metric_id FROM farm_role_scaling_metrics WHERE farm_roleid = ?", array($this->dbFarmRole->ID));
     $this->farmRoleMetrics = array();
     while ($role_metric = $role_metrics->FetchRow()) {
         if ($role_metric['metric_id']) {
             $this->farmRoleMetrics[$role_metric['metric_id']] = Scalr_Model::init(Scalr_Model::SCALING_FARM_ROLE_METRIC)->loadById($role_metric['id']);
         }
     }
 }
Пример #30
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::getLocations()
  */
 public function getLocations(\Scalr_Environment $environment = null)
 {
     if ($environment === null) {
         return array();
     }
     $db = \Scalr::getDb();
     $locations = $db->GetAll("SELECT DISTINCT(`group`) as `name` FROM client_environment_properties WHERE `name` = ? AND env_id = ?", array(self::API_KEY, $environment->id));
     $retval = array();
     foreach ($locations as $location) {
         $retval[$location['name']] = "Rackspace / {$location['name']}";
     }
     return $retval;
 }