当前位置: 首页>>代码示例>>PHP>>正文


PHP ADODB_mysqli::GetOne方法代码示例

本文整理汇总了PHP中ADODB_mysqli::GetOne方法的典型用法代码示例。如果您正苦于以下问题:PHP ADODB_mysqli::GetOne方法的具体用法?PHP ADODB_mysqli::GetOne怎么用?PHP ADODB_mysqli::GetOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ADODB_mysqli的用法示例。


在下文中一共展示了ADODB_mysqli::GetOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: checkPermission

 /**
  * Checks if user has permissions to project in environment or account scope
  *
  * @param string $projectId     Identifier of the project
  * @param array $criteria       ['envId' => '', 'clientid' => '']
  * @return bool|mixed
  */
 public function checkPermission($projectId, array $criteria)
 {
     $and = '';
     foreach ($criteria as $name => $value) {
         $field = 'f.' . \Scalr::decamelize($name);
         $and .= " AND " . $field . "=" . $this->db->escape($value);
     }
     $projectEntity = new ProjectEntity();
     $projectId = $projectEntity->type('projectId')->toDb($projectId);
     $where = " WHERE p.project_id = UNHEX('" . $projectId . "') AND EXISTS (\n                SELECT * FROM farms f\n                LEFT JOIN farm_settings fs ON f.id = fs.farmid\n                WHERE fs.name = '" . Entity\FarmSetting::PROJECT_ID . "'\n                AND REPLACE(fs.value, '-', '') = HEX(p.project_id)\n                {$and})";
     $sql = "SELECT " . $projectEntity->fields('p') . "\n                FROM " . $projectEntity->table('p') . $where;
     return $this->db->GetOne($sql);
 }
开发者ID:mheydt,项目名称:scalr,代码行数:20,代码来源:Projects.php

示例2: isConnectionAlive

 /**
  * Checks whether current connection is alive
  *
  * @param   ADODB_mysqli  $conn
  * @return  bool Returns true on success or false otherwise
  */
 private static function isConnectionAlive($conn)
 {
     $alive = true;
     if (!empty($conn->_connectionID) && method_exists($conn->_connectionID, 'ping')) {
         $alive = (bool) @$conn->_connectionID->ping();
     } else {
         try {
             $conn->GetOne('SELECT 1');
         } catch (\ADODB_Exception $e) {
             if (stristr($e->getMessage(), 'has gone away') !== false) {
                 $alive = false;
             }
         }
     }
     return $alive;
 }
开发者ID:recipe,项目名称:scalr,代码行数:22,代码来源:ConnectionPool.php

示例3: bindContact

 /**
  * @param Scalr_Service_ZohoCrm_Entity_Contact $contact
  * @param Client $client
  * @return void
  */
 private function bindContact($contact, $client)
 {
     list($contact->firstName, $contact->lastName) = explode(" ", $client->Fullname, 2);
     if (!$contact->lastName) {
         $contact->lastName = $contact->firstName;
         unset($contact->firstName);
     }
     $contact->email = $client->Email;
     $contact->phone = $client->Phone;
     $contact->fax = $client->Fax;
     $contact->mailingStreet = $client->Address1;
     $contact->mailingCity = $client->City;
     $contact->mailingState = $client->State;
     $contact->mailingCode = $client->ZipCode;
     if ($client->Country) {
         $contact->mailingCountry = $this->db->GetOne("\n                SELECT name FROM countries WHERE code = ?\n                LIMIT 1\n            ", array($client->Country));
     }
     $adPagesVisited = $client->GetSettingValue(CLIENT_SETTINGS::AD_PAGES_VISITED);
     $adCompaign = $client->GetSettingValue(CLIENT_SETTINGS::AD_COMPAIGN);
     if ($adPagesVisited) {
         $contact->leadSource = 'Adwords';
         $contact->setProperty(Scalr_Integration_ZohoCrm_CustomFields::CONTACT_AD_PAGES_VISITED, (int) $adPagesVisited);
         $contact->setProperty(Scalr_Integration_ZohoCrm_CustomFields::CONTACT_AD_VALUE_TRACK, $client->GetSettingValue(CLIENT_SETTINGS::AD_VALUE_TRACK));
         $client->ClearSettings('adwords%');
     } elseif ($adCompaign) {
         $contact->leadSource = $adCompaign;
     } else {
         $packageId = $client->GetSettingValue(CLIENT_SETTINGS::BILLING_PACKAGE);
         if (!$packageId || $packageId == 4) {
             $contact->leadSource = "Development edition";
         } else {
             $contact->leadSource = "Production edition";
         }
     }
     $unsubscrDate = $client->GetSettingValue(CLIENT_SETTINGS::ZOHOCRM_UNSUBSCR_DATE);
     $contact->setProperty(Scalr_Integration_ZohoCrm_CustomFields::CONTACT_UNSUBSCRIBED_ACCOUNT, (bool) $unsubscrDate);
     $contact->setProperty(Scalr_Integration_ZohoCrm_CustomFields::CONTACT_DATE_UNSUBSCRIBED, $unsubscrDate ? $unsubscrDate : null);
 }
开发者ID:recipe,项目名称:scalr,代码行数:43,代码来源:DefaultMediator.php

示例4: buildResponseFromSql

 protected function buildResponseFromSql($sql, $filterFields = array(), $groupSQL = "", $simpleQuery = true, $noLimit = false)
 {
     $this->request->defineParams(array('start' => array('type' => 'int', 'default' => 0), 'limit' => array('type' => 'int', 'default' => 20)));
     if (is_array($groupSQL)) {
         return $this->buildResponseFromSql2($sql, $filterFields, $groupSQL, is_array($simpleQuery) ? $simpleQuery : array(), $noLimit);
     }
     if ($this->getParam('query') && count($filterFields) > 0) {
         $filter = $this->db->qstr('%' . trim($this->getParam('query')) . '%');
         foreach ($filterFields as $field) {
             if ($simpleQuery) {
                 $likes[] = "`{$field}` LIKE {$filter}";
             } else {
                 $likes[] = "{$field} LIKE {$filter}";
             }
         }
         $sql .= " AND (";
         $sql .= implode(" OR ", $likes);
         $sql .= ")";
     }
     if ($groupSQL) {
         $sql .= "{$groupSQL}";
     }
     if (!$noLimit) {
         $response['total'] = $this->db->GetOne('SELECT COUNT(*) FROM (' . $sql . ') c_sub');
     }
     // @TODO replace with simple code (legacy code)
     $s = $this->getParam('sort');
     if (!is_array($s)) {
         $s = json_decode($this->getParam('sort'), true);
     }
     if (is_array($s)) {
         $sorts = array();
         if (count($s) && (!isset($s[0]) || !is_array($s[0]))) {
             $s = array($s);
         }
         foreach ($s as $param) {
             $sort = preg_replace("/[^A-Za-z0-9_]+/", "", $param['property']);
             $dir = in_array(strtolower($param['direction']), array('asc', 'desc')) ? $param['direction'] : 'ASC';
             if ($sort && $dir) {
                 $sorts[] = "`{$sort}` {$dir}";
             }
         }
         if (count($sorts) > 0) {
             $sql .= " ORDER BY " . implode($sorts, ',');
         }
     } else {
         if ($this->getParam('sort')) {
             $sort = preg_replace("/[^A-Za-z0-9_]+/", "", $this->getParam('sort'));
             $dir = in_array(strtolower($this->getParam('dir')), array('asc', 'desc')) ? $this->getParam('dir') : 'ASC';
             $sql .= " ORDER BY `{$sort}` {$dir}";
         }
     }
     if (!$noLimit) {
         $start = intval($this->getParam('start'));
         if ($start > $response["total"]) {
             $start = 0;
         }
         $limit = intval($this->getParam('limit'));
         $sql .= " LIMIT {$start}, {$limit}";
     }
     //$response['sql'] = $sql;
     $response["success"] = true;
     $response["data"] = $this->db->GetAll($sql);
     return $response;
 }
开发者ID:recipe,项目名称:scalr,代码行数:65,代码来源:Controller.php

示例5: setUserRoles

 /**
  * Set roles for specified user for specified team.
  *
  * @param   int        $teamId       The identifier of the team
  * @param   int        $userId       The identifier of the user
  * @param   array      $accountRoles The list of the identifiers of the roles of account level
  * @param   int        $accountId    optional The identifier of the account
  */
 public function setUserRoles($teamId, $userId, $accountRoles, $accountId = null)
 {
     $accountId = intval($accountId);
     //Verify that team and user are from the same acount
     if (!empty($accountId)) {
         $check = $this->db->GetOne("\n                SELECT 1 FROM account_users WHERE id = ? AND account_id = ? LIMIT 1\n            ", array($userId, $accountId)) && $this->db->GetOne("\n                SELECT 1 FROM account_teams WHERE id = ? AND account_id = ? LIMIT 1\n            ", array($teamId, $accountId));
         if (!$check) {
             throw new Exception\AclException(sprintf('Cannot find the team "%d" or user "%d" in the account "%d"', $teamId, $userId, $accountId));
         }
     } else {
         //Retrieves identifier of the account
         $accountId = $this->db->GetOne("\n                SELECT u.account_id\n                FROM account_users u\n                JOIN account_teams t ON t.account_id = u.account_id\n                WHERE u.user_id = ? AND t.team_id = ?\n                LIMIT 1\n            ", array($userId, $accountId));
         if (!$accountId) {
             throw new Exception\AclException(sprintf('Cannot find the team "%d" or user "%d" in the account "%d"', $teamId, $userId, $accountId));
         }
     }
     $teamUserId = $this->db->GetOne("\n           SELECT tu.id\n           FROM `account_team_users` tu\n           WHERE tu.`team_id` = ? AND tu.`user_id` = ?\n           LIMIT 1\n        ", array($teamId, $userId));
     if (empty($teamUserId)) {
         $this->db->Execute("\n                INSERT IGNORE `account_team_users`\n                SET team_id = ?,\n                    user_id = ?\n            ", array($teamId, $userId));
         $teamUserId = $this->db->Insert_ID();
     } else {
         //Removes previous relations
         $this->db->Execute("\n                DELETE FROM `account_team_user_acls` WHERE account_team_user_id = ?\n            ", array($teamUserId));
     }
     if ($c = count($accountRoles)) {
         //Creates new relations
         $this->db->Execute("\n                INSERT IGNORE `account_team_user_acls` (account_team_user_id, account_role_id)\n                SELECT ?, r.account_role_id\n                FROM `acl_account_roles` r\n                WHERE r.account_id = ?\n                AND r.account_role_id IN (" . rtrim(str_repeat("?,", $c), ',') . ")\n            ", array_merge(array($teamUserId, $accountId), array_values($accountRoles)));
     }
 }
开发者ID:recipe,项目名称:scalr,代码行数:37,代码来源:Acl.php

示例6: GetSettingValue

 /**
  * Returns client setting value by name
  *
  * @param string $name
  * @return mixed $value
  */
 public function GetSettingValue($name)
 {
     return $this->DB->GetOne("SELECT value FROM client_settings WHERE clientid=? AND `key`=? LIMIT 1", array($this->ID, $name));
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:10,代码来源:class.Client.php

示例7: worker


//.........这里部分代码省略.........
                     } catch (Exception $e) {
                     }
                     if ($bundleTask) {
                         if ($bundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PREPARING) {
                             if ($message->status == 'ok') {
                                 $metaData = array('szr_version' => $message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION], 'os' => $message->os, 'software' => $message->software);
                                 $bundleTask->setMetaData($metaData);
                                 $bundleTask->Save();
                                 PlatformFactory::NewPlatform($bundleTask->platform)->CreateServerSnapshot($bundleTask);
                             } else {
                                 $bundleTask->SnapshotCreationFailed("PrepareBundle procedure failed: {$message->lastError}");
                             }
                         }
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_DeployResult) {
                     try {
                         $deploymentTask = Scalr_Model::init(Scalr_Model::DM_DEPLOYMENT_TASK)->loadById($message->deployTaskId);
                     } catch (Exception $e) {
                     }
                     if ($deploymentTask) {
                         if ($message->status == 'error') {
                             $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_FAILED;
                             $deploymentTask->lastError = $message->lastError;
                         } else {
                             $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_DEPLOYED;
                             $deploymentTask->dtDeployed = date("Y-m-d H:i:s");
                         }
                         $deploymentTask->save();
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_Hello) {
                     $event = $this->onHello($message, $dbserver);
                 } elseif ($message instanceof Scalr_Messaging_Msg_FireEvent) {
                     //Validate event
                     $isEventExist = $this->db->GetOne("\n                            SELECT id FROM event_definitions\n                            WHERE name = ? AND ((env_id = ? AND account_id = ?) OR (env_id IS NULL AND account_id = ?) OR (env_id IS NULL AND account_id IS NULL))\n                            LIMIT 1\n                        ", array($message->eventName, $dbserver->envId, $dbserver->clientId, $dbserver->clientId));
                     if ($isEventExist) {
                         $event = new CustomEvent($dbserver, $message->eventName, (array) $message->params);
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_HostUpdate) {
                     try {
                         $dbFarmRole = $dbserver->GetFarmRoleObject();
                     } catch (Exception $e) {
                     }
                     if ($dbFarmRole instanceof DBFarmRole) {
                         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                             $behavior->handleMessage($message, $dbserver);
                         }
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_MongoDb) {
                     /********* MONGODB *********/
                     try {
                         $dbFarmRole = $dbserver->GetFarmRoleObject();
                     } catch (Exception $e) {
                     }
                     if ($dbFarmRole instanceof DBFarmRole) {
                         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                             $behavior->handleMessage($message, $dbserver);
                         }
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_DbMsr) {
                     /********* DBMSR *********/
                     try {
                         $dbFarmRole = $dbserver->GetFarmRoleObject();
                     } catch (Exception $e) {
                     }
                     if ($dbFarmRole instanceof DBFarmRole) {
                         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
开发者ID:sacredwebsite,项目名称:scalr,代码行数:67,代码来源:ScalarizrMessaging.php

示例8: handleWork

 /**
  * {@inheritdoc}
  * @see Scalr_System_Cronjob_MultiProcess_DefaultWorker::handleWork()
  */
 function handleWork($farmId)
 {
     $this->cleanup();
     $DBFarm = DBFarm::LoadByID($farmId);
     $account = Scalr_Account::init()->loadById($DBFarm->ClientID);
     $payAsYouGoTime = $account->getSetting(Scalr_Account::SETTING_BILLING_PAY_AS_YOU_GO_DATE);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     $this->logger->info("[" . $GLOBALS["SUB_TRANSACTIONID"] . "] Begin polling farm (ID: {$DBFarm->ID}, Name: {$DBFarm->Name}, Status: {$DBFarm->Status})");
     // Collect information from database
     $servers_count = $this->db->GetOne("\n            SELECT COUNT(*) FROM servers WHERE farm_id = ? AND status NOT IN (?,?)\n        ", array($DBFarm->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED));
     $this->logger->info("[FarmID: {$DBFarm->ID}] Found {$servers_count} farm instances in database");
     if ($DBFarm->Status == FARM_STATUS::TERMINATED && $servers_count == 0) {
         return;
     }
     foreach ($DBFarm->GetServersByFilter(array(), array('status' => SERVER_STATUS::PENDING_LAUNCH)) as $DBServer) {
         /** @var DBServer $DBServer */
         try {
             if ($DBServer->cloudLocation) {
                 try {
                     Logger::getLogger(LOG_CATEGORY::FARM)->info(sprintf("Initializing cloud cache: {$DBServer->cloudLocation} ({$DBServer->serverId})"));
                     $p = PlatformFactory::NewPlatform($DBServer->platform);
                     $list = $p->GetServersList($DBServer->GetEnvironmentObject(), $DBServer->cloudLocation);
                 } catch (Exception $e) {
                     Logger::getLogger(LOG_CATEGORY::FARM)->info(sprintf("Initializing cloud cache: FAILED"));
                 }
             }
             if ($DBServer->status != SERVER_STATUS::PENDING && $DBServer->status != SERVER_STATUS::PENDING_TERMINATE) {
                 if (!$p->IsServerExists($DBServer)) {
                     try {
                         $serverInfo = $p->GetServerExtendedInformation($DBServer);
                     } catch (Exception $e) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: %d] Crash check for server '%s' failed: %s", $DBFarm->ID, $DBServer->serverId, $e->getMessage()));
                     }
                     if (!$serverInfo) {
                         if ($p->debugLog) {
                             Logger::getLogger('Openstack')->fatal($p->debugLog);
                         }
                         if (!in_array($DBServer->status, array(SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED))) {
                             if ($DBServer->GetProperty(SERVER_PROPERTIES::CRASHED) == 1) {
                                 if (PlatformFactory::isOpenstack($DBServer->platform)) {
                                     $DBServer->SetProperty(SERVER_PROPERTIES::MISSING, 1);
                                 } else {
                                     $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                                     Scalr::FireEvent($DBFarm->ID, new HostCrashEvent($DBServer));
                                 }
                             } else {
                                 $DBServer->SetProperties([SERVER_PROPERTIES::REBOOTING => 0, SERVER_PROPERTIES::CRASHED => 1, SERVER_PROPERTIES::MISSING => 1]);
                                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' found in database but not found on %s. Crashed.", $DBServer->serverId, $DBServer->platform)));
                             }
                             continue;
                         }
                     } else {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: %d] False-positive crash check: %s (EnvID: %d)", $DBFarm->ID, $DBServer->serverId, $DBServer->envId));
                     }
                 } else {
                     $DBServer->SetProperty(SERVER_PROPERTIES::CRASHED, "0");
                     $DBServer->SetProperty(SERVER_PROPERTIES::MISSING, "0");
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "AWS was not able to validate the provided access credentials") || stristr($e->getMessage(), "Unable to sign AWS API request. Please, check your X.509")) {
                 $env = Scalr_Environment::init()->LoadById($DBFarm->EnvID);
                 $env->status = Scalr_Environment::STATUS_INACTIVE;
                 $env->save();
                 $env->setPlatformConfig(array('system.auto-disable-reason' => $e->getMessage()), false);
                 return;
             }
             if (stristr($e->getMessage(), "Could not connect to host")) {
                 continue;
             }
             print "[0][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             continue;
         }
         /*
         try {
             $realStatus = $DBServer->GetRealStatus()->getName();
             if ($realStatus == 'stopped') {
                 $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, $realStatus);
                 continue;
             } else {
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS) == 'stopped')
                     $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, "");
             }
         } catch (Exception $e) {}
         */
         try {
             if (!in_array($DBServer->status, array(SERVER_STATUS::SUSPENDED, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::PENDING_SUSPEND))) {
                 $openstackErrorState = false;
                 if (PlatformFactory::isOpenstack($DBServer->platform)) {
                     if ($DBServer->GetRealStatus()->getName() === 'ERROR') {
                         $openstackErrorState = true;
                     }
                 }
                 if ($DBServer->GetRealStatus()->isTerminated() || $openstackErrorState) {
                     Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' (Platform: %s) not running (Real state: %s, Scalr status: %s).", $DBServer->serverId, $DBServer->platform, $DBServer->GetRealStatus()->getName(), $DBServer->status)));
//.........这里部分代码省略.........
开发者ID:rickb838,项目名称:scalr,代码行数:101,代码来源:Poller.php

示例9: isLead

 /**
  * Checks if user is the lead of at least one project or cost center
  *
  * @param string $email User's email
  * @return bool Returns true if user is project or cc lead
  */
 public function isLead($email)
 {
     $isLead = $this->db->GetOne("\n            SELECT pp.project_id\n            FROM project_properties pp\n            JOIN projects p ON p.project_id = pp.project_id\n            WHERE pp.name = ?\n            AND pp.value = ?\n            AND p.archived = ?\n\n            UNION\n\n            SELECT cp.cc_id\n            FROM cc_properties cp\n            JOIN ccs c ON c.cc_id = cp.cc_id\n            WHERE cp.name = ?\n            AND cp.value = ?\n            AND c.archived = ?\n        ", [ProjectPropertyEntity::NAME_LEAD_EMAIL, $email, ProjectEntity::NOT_ARCHIVED, CostCentrePropertyEntity::NAME_LEAD_EMAIL, $email, CostCentreEntity::NOT_ARCHIVED]);
     return $isLead ? true : false;
 }
开发者ID:scalr,项目名称:scalr,代码行数:11,代码来源:Usage.php

示例10: handleWork

 function handleWork($farmId)
 {
     $DBFarm = DBFarm::LoadByID($farmId);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     if ($DBFarm->Status != FARM_STATUS::RUNNING) {
         $this->logger->warn("[FarmID: {$DBFarm->ID}] Farm terminated. There is no need to scale it.");
         return;
     }
     foreach ($DBFarm->GetFarmRoles() as $DBFarmRole) {
         for ($i = 0; $i < 10; $i++) {
             if ($DBFarmRole->NewRoleID != '') {
                 $this->logger->warn("[FarmID: {$DBFarm->ID}] Role '{$DBFarmRole->GetRoleObject()->name}' being synchronized. This role will not be scalled.");
                 continue 2;
             }
             if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ENABLED) != '1' && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::VPC_ROUTER)) {
                 $this->logger->info("[FarmID: {$DBFarm->ID}] Scaling disabled for role '{$DBFarmRole->GetRoleObject()->name}'. Skipping...");
                 continue 2;
             }
             // Get polling interval in seconds
             $polling_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_POLLING_INTERVAL) * 60;
             $dt_last_polling = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME);
             if ($dt_last_polling && $dt_last_polling + $polling_interval > time() && $i == 0) {
                 $this->logger->info("Polling interval: every {$polling_interval} seconds");
                 continue;
             }
             // Set Last polling time
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME, time(), DBFarmRole::TYPE_LCL);
             // Get current count of running and pending instances.
             $this->logger->info(sprintf("Processing role '%s'", $DBFarmRole->GetRoleObject()->name));
             $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
             $scalingDecision = $scalingManager->makeScalingDecition();
             if ($scalingDecision == Scalr_Scaling_Decision::STOP_SCALING) {
                 return;
             }
             if ($scalingDecision == Scalr_Scaling_Decision::NOOP) {
                 continue 2;
             } elseif ($scalingDecision == Scalr_Scaling_Decision::DOWNSCALE) {
                 /*
                  Timeout instance's count decrease. Decreases instance�s count after scaling
                  resolution the spare instances are running�g for selected timeout interval
                  from scaling EditOptions
                 */
                 // We have to check timeout limits before new scaling (downscaling) process will be initiated
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_TIMEOUT_ENABLED)) {
                     // if the farm timeout is exceeded
                     // checking timeout interval.
                     $last_down_scale_data_time = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_DATETIME);
                     $timeout_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_TIMEOUT);
                     // check the time interval to continue scaling or cancel it...
                     if (time() - $last_down_scale_data_time < $timeout_interval * 60) {
                         // if the launch time is too small to terminate smth in this role -> go to the next role in foreach()
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Waiting for downscaling timeout on farm %s, role %s", $DBFarm->Name, $DBFarmRole->GetRoleObject()->name)));
                         continue 2;
                     }
                 }
                 // end Timeout instance's count decrease
                 $sort = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_KEEP_OLDEST) == 1 ? 'DESC' : 'ASC';
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status = ? AND farm_roleid=? ORDER BY dtadded {$sort}", array(SERVER_STATUS::RUNNING, $DBFarmRole->ID));
                 $got_valid_instance = false;
                 // Select instance that will be terminated
                 //
                 // * Instances ordered by uptime (oldest wil be choosen)
                 // * Instance cannot be mysql master
                 // * Choose the one that was rebundled recently
                 while (!$got_valid_instance && count($servers) > 0) {
                     $item = array_shift($servers);
                     $DBServer = DBServer::LoadByID($item['server_id']);
                     if ($DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                         $serversCount = count($DBServer->GetFarmRoleObject()->GetServersByFilter(array(), array('status' => array(SERVER_STATUS::TERMINATED, SERVER_STATUS::TROUBLESHOOTING))));
                         if ($DBServer->index == 1 && $serversCount > 1) {
                             continue;
                         }
                     }
                     if ($DBServer->GetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED)) {
                         continue;
                     }
                     // Exclude db master
                     if ($DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) != 1 && $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER) != 1) {
                         // We do not want to delete the most recently synced instance. Because of LA fluctuation.
                         // I.e. LA may skyrocket during sync and drop dramatically after sync.
                         if ($DBServer->dateLastSync != 0) {
                             $chk_sync_time = $this->db->GetOne("\n                                    SELECT server_id FROM servers\n                                    WHERE dtlastsync > {$DBServer->dateLastSync}\n                                    AND farm_roleid='{$DBServer->farmRoleId}'\n                                    AND status NOT IN('" . SERVER_STATUS::TERMINATED . "', '" . SERVER_STATUS::TROUBLESHOOTING . "')\n                                    LIMIT 1\n                                ");
                             if ($chk_sync_time) {
                                 $got_valid_instance = true;
                             }
                         } else {
                             $got_valid_instance = true;
                         }
                     }
                 }
                 if ($DBServer && $got_valid_instance) {
                     $this->logger->info(sprintf("Server '%s' selected for termination...", $DBServer->serverId));
                     $allow_terminate = false;
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $aws = $DBServer->GetEnvironmentObject()->aws($DBServer);
                         // Shutdown an instance just before a full hour running
                         if (!$DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_SCALING_IGNORE_FULL_HOUR)) {
                             $response = $aws->ec2->instance->describe($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID))->get(0);
                             if ($response && count($response->instancesSet)) {
//.........这里部分代码省略.........
开发者ID:recipe,项目名称:scalr,代码行数:101,代码来源:Scaling.php

示例11: handleWork

 /**
  * {@inheritdoc}
  * @see Scalr_System_Cronjob_MultiProcess_DefaultWorker::handleWork()
  */
 function handleWork($serverId)
 {
     $dtNow = new DateTime('now');
     $dbServer = DBServer::LoadByID($serverId);
     if ($dbServer->status != SERVER_STATUS::PENDING_TERMINATE && $dbServer->status != SERVER_STATUS::TERMINATED) {
         return;
     }
     if ($dbServer->status == SERVER_STATUS::TERMINATED || $dbServer->dateShutdownScheduled <= $dtNow->format('Y-m-d H:i:s')) {
         try {
             if ($dbServer->GetCloudServerID()) {
                 $serverHistory = $dbServer->getServerHistory();
                 if (!$dbServer->GetRealStatus()->isTerminated()) {
                     try {
                         if ($dbServer->farmId != 0) {
                             if ($dbServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                                 $serversCount = count($dbServer->GetFarmRoleObject()->GetServersByFilter(array(), array('status' => SERVER_STATUS::TERMINATED)));
                                 if ($dbServer->index == 1 && $serversCount > 1) {
                                     Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($dbServer->GetFarmObject()->ID, sprintf("RabbitMQ role. Main DISK node should be terminated after all other nodes. " . "Waiting... (Platform: %s) (ServerTerminate).", $dbServer->serverId, $dbServer->platform)));
                                     return;
                                 }
                             }
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($dbServer->GetFarmObject()->ID, sprintf("Terminating server '%s' (Platform: %s) (ServerTerminate).", $dbServer->serverId, $dbServer->platform)));
                         }
                     } catch (Exception $e) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->warn($serverId . ": {$e->getMessage()}");
                     }
                     PlatformFactory::NewPlatform($dbServer->platform)->TerminateServer($dbServer);
                     if ($dbServer->farmId) {
                         $wasHostDownFired = $this->db->GetOne("SELECT id FROM events WHERE event_server_id = ? AND type = ?", array($serverId, 'HostDown'));
                         if (!$wasHostDownFired) {
                             Scalr::FireEvent($dbServer->farmId, new HostDownEvent($dbServer));
                         }
                     }
                 } else {
                     if ($dbServer->status == SERVER_STATUS::TERMINATED) {
                         if (!$dbServer->dateShutdownScheduled || time() - strtotime($dbServer->dateShutdownScheduled) > 600) {
                             $serverHistory->setTerminated();
                             $dbServer->Remove();
                         }
                     } else {
                         if ($dbServer->status == SERVER_STATUS::PENDING_TERMINATE) {
                             $dbServer->status = SERVER_STATUS::TERMINATED;
                             $dbServer->Save();
                         }
                     }
                 }
             } else {
                 //$serverHistory->setTerminated(); If there is no cloudserverID we don't need to add this server into server history.
                 $dbServer->Remove();
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "could not be found") || stristr($e->getMessage(), "or entity does not exist or due to incorrect parameter annotation for the field in api cmd class")) {
                 if ($serverHistory) {
                     $serverHistory->setTerminated();
                 }
                 $dbServer->Remove();
             } else {
                 throw $e;
             }
         }
     }
 }
开发者ID:recipe,项目名称:scalr,代码行数:66,代码来源:ServerTerminate.php

示例12: getTableDefinition

 /**
  * {@inheritdoc}
  * @see \Scalr\Upgrade\UpdateInterface::getTableDefinition()
  */
 public function getTableDefinition($table, $schema = null)
 {
     if (!isset($schema)) {
         $schema = $this->db->GetOne("SELECT DATABASE()");
     }
     $entity = new TableEntity();
     $entity->db = $this->db;
     return $entity->findOne([['tableSchema' => $schema], ['tableName' => $table]]);
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:13,代码来源:AbstractUpdate.php

示例13: onHostDown

 private function onHostDown(\Scalr_Messaging_Msg $message, DBServer $dbserver)
 {
     // If insatnce is already SUSPENDED or TERMINATED it means that hostdown was already processed by CloudPoller
     // and no need to process it again
     if (in_array($dbserver->status, array(\SERVER_STATUS::SUSPENDED, \SERVER_STATUS::TERMINATED))) {
         return true;
     }
     $p = PlatformFactory::NewPlatform($dbserver->platform);
     $status = $p->GetServerRealStatus($dbserver);
     if ($dbserver->isOpenstack()) {
         $status = $p->GetServerRealStatus($dbserver);
         if (stristr($status->getName(), 'REBOOT') || stristr($status->getName(), 'HARD_REBOOT')) {
             //Hard reboot
             $isRebooting = true;
         } elseif ($status->isRunning()) {
             // Soft reboot
             $isRebooting = true;
         } elseif (!$status->isTerminated()) {
             $isStopping = true;
         }
     } elseif ($dbserver->platform == \SERVER_PLATFORMS::GCE) {
         if ($status->getName() == 'STOPPING') {
             // We don't know is this shutdown or stop so let's ignore HostDown
             // and wait for status change
             return false;
         } elseif ($status->getName() == 'RUNNING') {
             $isRebooting = true;
         } elseif ($status->isSuspended() && $dbserver->status != \SERVER_STATUS::PENDING_TERMINATE) {
             $isStopping = true;
         }
     } else {
         if ($status->isRunning()) {
             $isRebooting = true;
         } elseif (!$status->isTerminated()) {
             $isStopping = true;
         }
     }
     if ($isStopping) {
         $event = new HostDownEvent($dbserver);
         $event->isSuspended = true;
     } elseif ($isRebooting) {
         $event = new RebootBeginEvent($dbserver);
     } else {
         if ($dbserver->farmId) {
             $wasHostDownFired = $this->db->GetOne("SELECT id FROM events WHERE event_server_id = ? AND type = ? AND is_suspend = '0'", array($dbserver->serverId, 'HostDown'));
             //TODO:
             if (!$wasHostDownFired) {
                 $event = new HostDownEvent($dbserver);
             }
         }
     }
     return $event;
 }
开发者ID:mheydt,项目名称:scalr,代码行数:53,代码来源:ScalarizrMessaging.php

示例14: worker


//.........这里部分代码省略.........
                  resolution the spare instances are running for selected timeout interval
                  from scaling EditOptions
                 */
                 // We have to check timeout limits before new scaling (downscaling) process will be initiated
                 if ($DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_TIMEOUT_ENABLED)) {
                     // if the farm timeout is exceeded
                     // checking timeout interval.
                     $last_down_scale_data_time = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_DATETIME);
                     $timeout_interval = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_TIMEOUT);
                     // check the time interval to continue scaling or cancel it...
                     if (time() - $last_down_scale_data_time < $timeout_interval * 60) {
                         // if the launch time is too small to terminate smth in this role -> go to the next role in foreach()
                         \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage(!empty($request->farmId) ? $request->farmId : null, sprintf("Waiting for downscaling timeout on farm %s, role %s", !empty($request->farmName) ? $request->farmName : null, !empty($DBFarmRole->Alias) ? $DBFarmRole->Alias : null), null, null, !empty($DBFarmRole->ID) ? $DBFarmRole->ID : null));
                         continue;
                     }
                 }
                 // end Timeout instance's count decrease
                 $sort = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_KEEP_OLDEST) == 1 ? 'DESC' : 'ASC';
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status = ? AND farm_roleid=? ORDER BY dtadded {$sort}", array(SERVER_STATUS::RUNNING, $DBFarmRole->ID));
                 $got_valid_instance = false;
                 $ignoreFullHour = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_IGNORE_FULL_HOUR);
                 $useSafeShutdown = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_SAFE_SHUTDOWN);
                 $isRabbitMQ = $DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ);
                 // Select instance that will be terminated
                 //
                 // Instances ordered by uptime (oldest wil be choosen)
                 // Instance cannot be mysql master
                 // Choose the one that was rebundled recently
                 $DBServer = null;
                 while (!$got_valid_instance && count($servers) > 0) {
                     $item = array_shift($servers);
                     $DBServer = DBServer::LoadByID($item['server_id']);
                     if ($isRabbitMQ) {
                         $serverExists = $this->db->GetOne("\n                            SELECT EXISTS (\n                                SELECT 1 FROM servers\n                                WHERE farm_roleid = ?\n                                AND status NOT IN (?, ?)\n                                AND `index` != ?\n                            )\n                        ", [$DBServer->farmRoleId, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED, 1]);
                         if ($DBServer->index == 1 && $serverExists) {
                             continue;
                         }
                     }
                     if ($DBServer->GetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED)) {
                         continue;
                     }
                     // Exclude db master
                     if ($DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) != 1 && $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER) != 1) {
                         $got_valid_instance = true;
                     }
                     //Check safe shutdown
                     if ($useSafeShutdown == 1) {
                         try {
                             $res = $DBServer->scalarizr->system->callAuthShutdownHook();
                         } catch (Exception $e) {
                             $res = $e->getMessage();
                         }
                         if ($res != '1') {
                             \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBServer->farmId, sprintf("Safe shutdown enabled. Server '%s'. Script returned '%s' skipping it.", $DBServer->serverId, $res), $DBServer->serverId, $DBServer->envId, $DBServer->farmRoleId));
                             $got_valid_instance = false;
                         }
                     }
                 }
                 // end while
                 if ($DBServer !== null && $got_valid_instance) {
                     $this->getLogger()->info(sprintf("Server '%s' selected for termination...", $DBServer->serverId));
                     $allow_terminate = false;
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $aws = $DBServer->GetEnvironmentObject()->aws($DBServer);
                         // Shutdown an instance just before a full hour running
                         if (!$ignoreFullHour) {
开发者ID:scalr,项目名称:scalr,代码行数:67,代码来源:Scaling.php

示例15: handleWork

 function handleWork($farmId)
 {
     $this->cleanup();
     $DBFarm = DBFarm::LoadByID($farmId);
     $account = Scalr_Account::init()->loadById($DBFarm->ClientID);
     $payAsYouGoTime = $account->getSetting(Scalr_Account::SETTING_BILLING_PAY_AS_YOU_GO_DATE);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     $this->logger->info("[" . $GLOBALS["SUB_TRANSACTIONID"] . "] Begin polling farm (ID: {$DBFarm->ID}, Name: {$DBFarm->Name}, Status: {$DBFarm->Status})");
     //
     // Collect information from database
     //
     $servers_count = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id = ? AND status != ?", array($DBFarm->ID, SERVER_STATUS::TERMINATED));
     $this->logger->info("[FarmID: {$DBFarm->ID}] Found {$servers_count} farm instances in database");
     if ($DBFarm->Status == FARM_STATUS::TERMINATED && $servers_count == 0) {
         return;
     }
     foreach ($DBFarm->GetServersByFilter(array(), array('status' => SERVER_STATUS::PENDING_LAUNCH)) as $DBServer) {
         try {
             if ($DBServer->status != SERVER_STATUS::PENDING && $DBServer->status != SERVER_STATUS::PENDING_TERMINATE) {
                 $p = PlatformFactory::NewPlatform($DBServer->platform);
                 if (!$p->IsServerExists($DBServer)) {
                     try {
                         $serverInfo = $p->GetServerExtendedInformation($DBServer);
                     } catch (Exception $e) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: {$DBFarm->ID}] Crash check for server '{$DBServer->serverId}' failed: {$e->getMessage()}"));
                     }
                     if (!$serverInfo) {
                         if ($DBServer->status != SERVER_STATUS::PENDING_TERMINATE && $DBServer->status != SERVER_STATUS::TERMINATED) {
                             if ($DBServer->GetProperty("system.crashed") == 1) {
                                 $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                                 Scalr::FireEvent($DBFarm->ID, new HostCrashEvent($DBServer));
                             } else {
                                 $DBServer->SetProperty(SERVER_PROPERTIES::REBOOTING, 0);
                                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' found in database but not found on {$DBServer->platform}. Crashed.", $DBServer->serverId)));
                                 $DBServer->SetProperty("system.crashed", "1");
                             }
                             continue;
                         }
                     } else {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: {$DBFarm->ID}] False-positive crash check: {$DBServer->serverId}"));
                         if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->fatal(sprintf("[CRASH][FarmID: {$DBFarm->ID}] InstanceID: %s, List: %s", $DBServer->GetCloudServerID(), json_encode($p->instancesListCache)));
                         }
                     }
                 } else {
                     $DBServer->SetProperty("system.crashed", "0");
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "AWS was not able to validate the provided access credentials") || stristr($e->getMessage(), "Unable to sign AWS API request. Please, check your X.509")) {
                 $env = Scalr_Environment::init()->LoadById($DBFarm->EnvID);
                 $env->status = Scalr_Environment::STATUS_INACTIVE;
                 $env->save();
                 $env->setPlatformConfig(array('system.auto-disable-reason' => $e->getMessage()), false);
                 return;
             }
             if (stristr($e->getMessage(), "Could not connect to host")) {
                 continue;
             }
             print "[0][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             continue;
         }
         try {
             $realStatus = $DBServer->GetRealStatus()->getName();
             if ($realStatus == 'stopped') {
                 $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, $realStatus);
                 continue;
             } else {
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS) == 'stopped') {
                     $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, "");
                 }
             }
         } catch (Exception $e) {
         }
         try {
             if (!in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE)) && $DBServer->GetRealStatus()->isTerminated()) {
                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' (Platform: %s) not running (Real state: %s, Scalr status: %s).", $DBServer->serverId, $DBServer->platform, $DBServer->GetRealStatus()->getName(), $DBServer->status)));
                 $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                 $DBServer->SetProperty(SERVER_PROPERTIES::REBOOTING, 0);
                 Scalr::FireEvent($DBFarm->ID, new HostDownEvent($DBServer));
                 continue;
             } elseif ($DBServer->status != SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->IsRunning()) {
                 if ($DBServer->status != SERVER_STATUS::TERMINATED && $DBServer->status != SERVER_STATUS::TROUBLESHOOTING) {
                     /*
                     if ($DBServer->platform == SERVER_PLATFORMS::NIMBULA)
                     {
                         if (!$DBServer->GetProperty(NIMBULA_SERVER_PROPERTIES::USER_DATA_INJECTED))
                         {
                             $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
                     
                             $ssh2Client = new Scalr_Net_Ssh2_Client();
                             $ssh2Client->addPassword(
                                 $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_INIT_ROOT_USER),
                                 $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_INIT_ROOT_PASS)
                             );
                     
                             $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     
                             $port = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT);
//.........这里部分代码省略.........
开发者ID:recipe,项目名称:scalr,代码行数:101,代码来源:Poller.php


注:本文中的ADODB_mysqli::GetOne方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。