Inheritance: extends Scalr_Model
Example #1
0
 public function onFarmSave(DBFarm $dbFarm, DBFarmRole $dbFarmRole)
 {
     try {
         $account = Scalr_Account::init()->loadById($dbFarm->ClientID);
         if (!$account->isFeatureEnabled(Scalr_Limits::FEATURE_CHEF)) {
             $dbFarmRole->ClearSettings("chef.");
             return false;
         }
         $db = Core::GetDBInstance();
         $runListId = $dbFarmRole->GetSetting(self::ROLE_CHEF_RUNLIST_ID);
         $attributes = $dbFarmRole->GetSetting(self::ROLE_CHEF_ATTRIBUTES);
         $checksum = $dbFarmRole->GetSetting(self::ROLE_CHEF_CHECKSUM);
         $chefRoleName = $dbFarmRole->GetSetting(self::ROLE_CHEF_ROLE_NAME);
         $chefServerId = $dbFarmRole->GetSetting(self::ROLE_CHEF_SERVER_ID);
         // Need to remove chef role if chef was disabled for current farmrole
         if (!$runListId && $chefRoleName) {
             $this->removeChefRole($chefServerId, $chefRoleName);
             $dbFarmRole->ClearSettings("chef.");
             return true;
         }
         if ($runListId) {
             $runListInfo = $this->db->GetRow("SELECT chef_server_id, runlist FROM services_chef_runlists WHERE id=?", array($runListId));
             $newChefServerId = $runListInfo['chef_server_id'];
             if ($newChefServerId != $chefServerId && $chefServerId) {
                 // Remove role from old server
                 $this->removeChefRole($chefServerId, $chefRoleName);
                 $createNew = true;
             }
             if (!$chefServerId) {
                 $createNew = true;
             }
             $chefServerInfo = $this->db->GetRow("SELECT * FROM services_chef_servers WHERE id=?", array($runListInfo['chef_server_id']));
             $chefServerInfo['auth_key'] = $this->getCrypto()->decrypt($chefServerInfo['auth_key'], $this->cryptoKey);
             $chefClient = Scalr_Service_Chef_Client::getChef($chefServerInfo['url'], $chefServerInfo['username'], trim($chefServerInfo['auth_key']));
             $roleName = "scalr-{$dbFarmRole->ID}";
             $setSettings = false;
             if ($createNew) {
                 $chefClient->createRole($roleName, $roleName, json_decode($runListInfo['runlist']), json_decode($attributes), $runListInfo['chef_environment']);
                 $setSettings = true;
             } else {
                 if ($dbFarmRole->GetSetting(self::ROLE_CHEF_CHECKSUM) != md5("{$runListInfo['runlist']}.{$attributes}")) {
                     $chefClient->updateRole($roleName, $roleName, json_decode($runListInfo['runlist']), json_decode($attributes), $runListInfo['chef_environment']);
                     $setSettings = true;
                 }
             }
             if ($setSettings) {
                 $dbFarmRole->SetSetting(self::ROLE_CHEF_ROLE_NAME, $roleName);
                 $dbFarmRole->SetSetting(self::ROLE_CHEF_SERVER_ID, $runListInfo['chef_server_id']);
                 $dbFarmRole->SetSetting(self::ROLE_CHEF_CHECKSUM, md5("{$runListInfo['runlist']}.{$attributes}"));
             }
         }
     } catch (Exception $e) {
         throw new Exception("Chef settings error: {$e->getMessage()} ({$e->getTraceAsString()})");
     }
 }
Example #2
0
 protected function getUserInfoByAccountId($accountId)
 {
     if (!isset($this->accountsCache[$accountId])) {
         if ($accountId) {
             try {
                 $acc = new \Scalr_Account();
                 $acc->loadById($accountId);
                 $this->accountsCache[$accountId] = array('id' => $acc->getOwner()->id, 'email' => $acc->getOwner()->getEmail());
             } catch (\Exception $e) {
                 $this->console->error($e->getMessage());
                 return array('id' => 0, 'email' => '');
             }
         } else {
             $user = new \Scalr_Account_User();
             $user->loadByEmail('admin', 0);
             $this->accountsCache[$accountId] = array('id' => $user->id, 'email' => $user->getEmail());
         }
     }
     return $this->accountsCache[$accountId];
 }
Example #3
0
 /**
  * @test
  */
 public function testXListAccountsAction()
 {
     $res = $this->request('/admin/accounts/xListAccounts');
     $this->assertResponseDataHasKeys(array('id' => $this->logicalNot($this->isEmpty()), 'name' => $this->isType('string'), 'dtadded', 'status', 'ownerEmail' => $this->matchesRegularExpression('/^.+@[\\.\\w\\d]+$/'), 'isTrial', 'envs' => $this->matchesRegularExpression('/^\\d+$/'), 'limitEnvs', 'farms' => $this->matchesRegularExpression('/^\\d+$/'), 'limitFarms', 'users' => $this->matchesRegularExpression('/^\\d+$/'), 'limitUsers', 'servers' => $this->matchesRegularExpression('/^\\d+$/'), 'limitServers', 'dnsZones' => $this->matchesRegularExpression('/^\\d+$/')), $res, true);
     foreach ($res['data'] as $v) {
         if ($v['name'] == $this->getCreatedAccountName()) {
             try {
                 //Tries to remove previously created account
                 $acc = \Scalr_Account::init()->loadById($v['id']);
                 $acc->delete();
             } catch (\Exception $e) {
             }
         }
     }
 }
Example #4
0
 public function Run()
 {
     $container = Scalr::getContainer();
     $db = $container->adodb;
     $time = microtime(true);
     $farms = $db->Execute("SELECT id, created_by_id, created_by_email, clientid FROM farms");
     while ($farm = $farms->FetchRow()) {
         if (!$farm['created_by_email'] && !$farm['created_by_id']) {
             $accountOwner = Scalr_Account::init()->loadById($farm['clientid'])->getOwner();
             $db->Execute("UPDATE farms SET created_by_id = ?, created_by_email = ? WHERE id = ?", array($accountOwner->id, $accountOwner->getEmail(), $farm['id']));
         }
     }
     print "Done.\n";
     $t = round(microtime(true) - $time, 2);
     printf("Upgrade process took %0.2f seconds\n\n", $t);
 }
 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()));
     }
 }
Example #6
0
 /**
  * Return account's hash. It's used for reseting keepSession on a whole account
  *
  * @param   int     $userId
  * @return  string
  */
 protected static function getAccountHash($userId)
 {
     $db = \Scalr::getDb();
     $hash = $db->GetOne("\n            SELECT `value`\n            FROM client_settings\n            JOIN account_users ON account_users.account_id = client_settings.clientid\n            WHERE `key` = ? AND account_users.id = ?\n            LIMIT 1\n        ", array(Scalr_Account::SETTING_AUTH_HASH, $userId));
     if (!$hash) {
         $accountId = $db->GetOne('SELECT account_id FROM account_users WHERE id = ? LIMIT 1', array($userId));
         if ($accountId) {
             $hash = CryptoTool::sault();
             $acc = new Scalr_Account();
             $acc->loadById($accountId);
             $acc->setSetting(Scalr_Account::SETTING_AUTH_HASH, $hash);
         }
     }
     return $hash;
 }
Example #7
0
 /**
  * 
  * @param ServerCreateInfo $ServerCreateInfo
  * @return DBServer
  */
 public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false)
 {
     $db = Core::GetDBInstance();
     if (!$DBServer && $ServerCreateInfo) {
         $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME));
         $DBServer = DBServer::Create($ServerCreateInfo, false, true);
     } elseif (!$DBServer && !$ServerCreateInfo) {
         // incorrect arguments
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server"));
         return null;
     }
     if ($delayed) {
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->Save();
         return $DBServer;
     }
     try {
         $account = Scalr_Account::init()->loadById($DBServer->clientId);
         $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1);
         PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer);
         $DBServer->status = SERVER_STATUS::PENDING;
         $DBServer->Save();
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage())));
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, $e->getMessage());
         $DBServer->Save();
     }
     if ($DBServer->status == SERVER_STATUS::PENDING) {
         Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer));
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "");
         $db->Execute("UPDATE servers_history SET\r\n\t\t\t\t\t`dtlaunched` = NOW(),\r\n\t\t\t\t\t`cloud_server_id` = ?,\r\n\t\t\t\t\t`type` = ?\r\n\t\t\t\t\tWHERE server_id = ?\r\n\t\t\t\t", array($DBServer->GetCloudServerID(), $DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_TYPE), $DBServer->serverId));
     }
     return $DBServer;
 }
Example #8
0
 /**
  * Launches server
  *
  * @param   \ServerCreateInfo       $ServerCreateInfo optional The server create info
  * @param   \DBServer               $DBServer         optional The DBServer object
  * @param   bool                    $delayed          optional
  * @param   integer|array            $reason           optional
  * @param   \Scalr_Account_User|int $user             optional The Scalr_Account_User object or its unique identifier
  * @return  DBServer|null           Returns the DBServer object on cussess or null otherwise
  */
 public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = 0, $user = null)
 {
     $db = self::getDb();
     $farm = null;
     //Ensures handling identifier of the user instead of the object
     if ($user !== null && !$user instanceof \Scalr_Account_User) {
         try {
             $user = Scalr_Account_User::init()->loadById(intval($user));
         } catch (\Exception $e) {
         }
     }
     if (!$DBServer && $ServerCreateInfo) {
         $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME));
         $DBServer = DBServer::Create($ServerCreateInfo, false, true);
     } elseif (!$DBServer && !$ServerCreateInfo) {
         // incorrect arguments
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server"));
         return null;
     }
     $propsToSet = array();
     if ($user instanceof \Scalr_Account_User) {
         $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_ID] = $user->id;
         $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_EMAIL] = $user->getEmail();
     }
     //We should keep role_id and farm_role_id in server properties to use in cost analytics
     if (!empty($DBServer->farmRoleId)) {
         $propsToSet[SERVER_PROPERTIES::FARM_ROLE_ID] = $DBServer->farmRoleId;
         $propsToSet[SERVER_PROPERTIES::ROLE_ID] = $DBServer->farmRoleId ? $DBServer->GetFarmRoleObject()->RoleID : 0;
     }
     try {
         // Ensures the farm object will be fetched as correctly as possible
         $farm = $DBServer->farmId ? $DBServer->GetFarmObject() : null;
         $farmRole = $DBServer->farmRoleId ? $DBServer->GetFarmRoleObject() : null;
         if (!$farmRole instanceof DBFarmRole) {
             $farmRole = null;
         } else {
             if (!$farm instanceof DBFarm) {
                 // Gets farm through FarmRole object in this case
                 $farm = $farmRole->GetFarmObject();
             }
         }
         if ($farm instanceof DBFarm) {
             $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_ID] = $farm->createdByUserId;
             $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_EMAIL] = $farm->createdByUserEmail;
             $projectId = $farm->GetSetting(DBFarm::SETTING_PROJECT_ID);
             if (!empty($projectId)) {
                 try {
                     $projectEntity = ProjectEntity::findPk($projectId);
                     if ($projectEntity instanceof ProjectEntity) {
                         /* @var $projectEntity ProjectEntity */
                         $ccId = $projectEntity->ccId;
                     } else {
                         $projectId = null;
                     }
                 } catch (Exception $e) {
                     $projectId = null;
                 }
             }
             $propsToSet[SERVER_PROPERTIES::FARM_PROJECT_ID] = $projectId;
         }
         if ($farmRole instanceof DBFarmRole) {
             $propsToSet[SERVER_PROPERTIES::INFO_INSTANCE_TYPE_NAME] = $farmRole->GetSetting(DBFarmRole::SETTING_INFO_INSTANCE_TYPE_NAME);
         }
         if (!empty($ccId)) {
             $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $ccId;
         } elseif ($DBServer->envId && ($environment = $DBServer->GetEnvironmentObject()) instanceof Scalr_Environment) {
             $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $environment->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID);
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Could not load related object for recently created server %s. It says: %s", $DBServer->serverId, $e->getMessage()));
     }
     if (!empty($propsToSet)) {
         $DBServer->SetProperties($propsToSet);
     }
     $fnGetReason = function ($reasonId) {
         $args = func_get_args();
         $args[0] = DBServer::getLaunchReason($reasonId);
         return [call_user_func_array('sprintf', $args), $reasonId];
     };
     if ($delayed) {
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
         $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_REASON => $reasonMsg, SERVER_PROPERTIES::LAUNCH_REASON_ID => $reasonId]);
         $DBServer->Save();
         return $DBServer;
     }
     if ($ServerCreateInfo && $ServerCreateInfo->roleId) {
         $dbRole = DBRole::loadById($ServerCreateInfo->roleId);
         if ($dbRole->generation == 1) {
             $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
             $DBServer->Save();
             $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ERROR => "ami-scripts servers no longer supported", SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]);
             return $DBServer;
         }
     }
     // Limit amount of pending servers
     if ($DBServer->isOpenstack()) {
         $config = \Scalr::getContainer()->config;
         if ($config->defined("scalr.{$DBServer->platform}.pending_servers_limit")) {
             $pendingServersLimit = $config->get("scalr.{$DBServer->platform}.pending_servers_limit");
             $pendingServers = $db->GetOne("SELECT COUNT(*) FROM servers WHERE platform=? AND status=? AND server_id != ?", array($DBServer->platform, SERVER_STATUS::PENDING, $DBServer->serverId));
             if ($pendingServers >= $pendingServersLimit) {
                 Logger::getLogger("SERVER_LAUNCH")->warn("{$pendingServers} servers in PENDING state on {$DBServer->platform}. Limit is: {$pendingServersLimit}. Waiting.");
                 $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
                 $DBServer->Save();
                 $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]);
                 return $DBServer;
             } else {
                 Logger::getLogger("SERVER_LAUNCH")->warn("{$pendingServers} servers in PENDING state on {$DBServer->platform}. Limit is: {$pendingServersLimit}. Launching server.");
             }
         }
     }
     try {
         $account = Scalr_Account::init()->loadById($DBServer->clientId);
         $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1);
         PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer);
         $DBServer->status = SERVER_STATUS::PENDING;
         $DBServer->Save();
         try {
             if ($reason) {
                 list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
             } else {
                 $reasonMsg = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON);
                 $reasonId = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON_ID);
             }
             $DBServer->getServerHistory()->markAsLaunched($reasonMsg, $reasonId);
             $DBServer->updateTimelog('ts_launched');
             if ($DBServer->imageId) {
                 //Update Image last used date
                 $image = Image::findOne([['id' => $DBServer->imageId], ['envId' => $DBServer->envId], ['platform' => $DBServer->platform], ['cloudLocation' => $DBServer->cloudLocation]]);
                 if (!$image) {
                     $image = Image::findOne([['id' => $DBServer->imageId], ['envId' => NULL], ['platform' => $DBServer->platform], ['cloudLocation' => $DBServer->cloudLocation]]);
                 }
                 if ($image) {
                     $image->dtLastUsed = new DateTime();
                     $image->save();
                 }
                 //Update Role last used date
                 if ($DBServer->farmRoleId) {
                     $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
                     $dbRole->dtLastUsed = date("Y-m-d H:i:s");
                     $dbRole->save();
                 }
             }
         } catch (Exception $e) {
             Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}"));
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage()), $DBServer->serverId));
         $existingLaunchError = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ERROR);
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ERROR => $e->getMessage(), SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]);
         $DBServer->Save();
         if ($DBServer->farmId && !$existingLaunchError) {
             Scalr::FireEvent($DBServer->farmId, new InstanceLaunchFailedEvent($DBServer, $e->getMessage()));
         }
     }
     if ($DBServer->status == SERVER_STATUS::PENDING) {
         Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer));
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "");
     }
     return $DBServer;
 }
Example #9
0
 public function xLoginAsAction()
 {
     if ($this->getParam('accountId')) {
         $account = new Scalr_Account();
         $account->loadById($this->getParam('accountId'));
         $user = $account->getOwner();
     } else {
         $user = new Scalr_Account_User();
         $user->loadById($this->getParam('userId'));
     }
     Scalr_Session::create($user->getId(), true);
     $this->response->success();
 }
Example #10
0
 /**
  * @param  int     $accountId
  * @param  RawData $password
  * @param  RawData $currentPassword
  * @throws Exception
  */
 public function xSaveOwnerPasswordAction($accountId, RawData $password, RawData $currentPassword)
 {
     $account = new Scalr_Account();
     $account->loadById($accountId);
     $password = (string) $password;
     $validator = new Validator();
     $validator->addErrorIf(!$this->user->checkPassword($currentPassword), "currentPassword", "Invalid password");
     $validator->validate($password, "password", Validator::PASSWORD, ['admin']);
     if ($validator->isValid($this->response)) {
         $user = $account->getOwner();
         $user->updatePassword($password);
         $user->save();
         // Send notification E-mail
         $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{administratorFullName}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $user->getEmail(), $user->fullname);
         $this->response->success('Password successfully updated');
     }
 }
Example #11
0
 /**
  * Launches server
  *
  * @param   \ServerCreateInfo       $ServerCreateInfo optional The server create info
  * @param   \DBServer               $DBServer         optional The DBServer object
  * @param   bool                    $delayed          optional
  * @param   integer|array            $reason           optional
  * @param   \Scalr_Account_User|int $user             optional The Scalr_Account_User object or its unique identifier
  * @return  DBServer|null           Returns the DBServer object on cussess or null otherwise
  */
 public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = 0, $user = null)
 {
     $db = self::getDb();
     $farm = null;
     //Ensures handling identifier of the user instead of the object
     if ($user !== null && !$user instanceof \Scalr_Account_User) {
         try {
             $user = Scalr_Account_User::init()->loadById(intval($user));
         } catch (\Exception $e) {
         }
     }
     if (!$DBServer && $ServerCreateInfo) {
         $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME));
         $DBServer = DBServer::Create($ServerCreateInfo, false, true);
     } elseif (!$DBServer && !$ServerCreateInfo) {
         // incorrect arguments
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server"));
         return null;
     }
     $propsToSet = array();
     if ($user instanceof \Scalr_Account_User) {
         $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_ID] = $user->id;
         $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_EMAIL] = $user->getEmail();
     }
     try {
         if ($DBServer->farmId && ($farm = $DBServer->GetFarmObject()) instanceof DBFarm) {
             $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_ID] = $farm->createdByUserId;
             $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_EMAIL] = $farm->createdByUserEmail;
             $propsToSet[SERVER_PROPERTIES::FARM_PROJECT_ID] = $farm->GetSetting(DBFarm::SETTING_PROJECT_ID);
         }
         if ($DBServer->envId && ($environment = $DBServer->GetEnvironmentObject()) instanceof Scalr_Environment) {
             $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $environment->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID);
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Could not load related object for recently created server %s. It says: %s", $DBServer->serverId, $e->getMessage()));
     }
     if (!empty($propsToSet)) {
         $DBServer->SetProperties($propsToSet);
     }
     $fnGetReason = function ($reasonId) {
         $args = func_get_args();
         $args[0] = DBServer::getLaunchReason($reasonId);
         return [call_user_func_array('sprintf', $args), $reasonId];
     };
     if ($delayed) {
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
         $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_REASON => $reasonMsg, SERVER_PROPERTIES::LAUNCH_REASON_ID => $reasonId]);
         $DBServer->Save();
         return $DBServer;
     }
     if ($ServerCreateInfo && $ServerCreateInfo->roleId) {
         $dbRole = DBRole::loadById($ServerCreateInfo->roleId);
         if ($dbRole->generation == 1) {
             $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
             $DBServer->Save();
             $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "ami-scripts servers no longer supported");
             return $DBServer;
         }
     }
     try {
         $account = Scalr_Account::init()->loadById($DBServer->clientId);
         $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1);
         PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer);
         $DBServer->status = SERVER_STATUS::PENDING;
         $DBServer->Save();
         try {
             if ($reason) {
                 list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
             } else {
                 $reasonMsg = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON);
                 $reasonId = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON_ID);
             }
             $DBServer->getServerHistory()->markAsLaunched($reasonMsg, $reasonId);
             $DBServer->updateTimelog('ts_launched');
         } catch (Exception $e) {
             Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}"));
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage())));
         $existingLaunchError = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ERROR);
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, $e->getMessage());
         $DBServer->Save();
         if ($DBServer->farmId && !$existingLaunchError) {
             Scalr::FireEvent($DBServer->farmId, new InstanceLaunchFailedEvent($DBServer, $e->getMessage()));
         }
     }
     if ($DBServer->status == SERVER_STATUS::PENDING) {
         Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer));
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "");
     }
     return $DBServer;
 }
Example #12
0
 /**
  * @param int $accountId
  * @param RawData $password
  * @param RawData $cpassword
  * @param RawData $currentPassword
  * @throws Exception
  */
 public function xSaveOwnerPasswordAction($accountId, $password, $cpassword, $currentPassword)
 {
     $account = new Scalr_Account();
     $account->loadById($accountId);
     $validator = new Validator();
     $validator->addErrorIf(!$this->user->checkPassword($currentPassword), ['currentPassword'], 'Invalid password');
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     if ($validator->isValid($this->response)) {
         $user = $account->getOwner();
         $user->updatePassword($password);
         $user->save();
         // Send notification E-mail
         $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{administratorFullName}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $user->getEmail(), $user->fullname);
         $this->response->success('Password successfully updated');
     }
 }
Example #13
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Pcntl\ProcessInterface::OnEndForking()
  */
 public function OnEndForking()
 {
     $db = \Scalr::getDb();
     \Scalr::getContainer()->logger(__CLASS__)->warn("OnEndForking: start");
     $list = $db->GetAll("\n            SELECT farm_roleid\n            FROM farm_role_settings\n            WHERE name=? AND value='1'\n        ", array(Scalr_Db_Msr::DATA_STORAGE_EBS_ENABLE_ROTATION));
     foreach ($list as $list_item) {
         try {
             $DBFarmRole = DBFarmRole::LoadByID($list_item['farm_roleid']);
         } catch (Exception $e) {
             continue;
         }
         try {
             $DBFarm = $DBFarmRole->GetFarmObject();
         } catch (Exception $e) {
             continue;
         }
         if ($DBFarm->Status == FARM_STATUS::RUNNING) {
             $old_snapshots = $db->GetAll("\n                    SELECT id FROM storage_snapshots\n                    WHERE farm_roleid=?\n                    AND `type`='ebs'\n                    ORDER BY dtcreated ASC\n                ", array($DBFarmRole->ID));
             $r = (int) $DBFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EBS_ROTATE);
             if (count($old_snapshots) > $r && $r > 0) {
                 try {
                     $aws = $DBFarm->GetEnvironmentObject()->aws($DBFarmRole);
                     while (count($old_snapshots) > $r) {
                         $snapinfo = array_shift($old_snapshots);
                         try {
                             $aws->ec2->snapshot->delete($snapinfo['id']);
                             $this->deleteStorageSnapshot($snapinfo['id']);
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "does not exist")) {
                                 $this->deleteStorageSnapshot($snapinfo['id']);
                             } else {
                                 throw $e;
                             }
                         }
                     }
                     //Releases memory
                     $DBFarm->GetEnvironmentObject()->getContainer()->release('aws');
                     unset($aws);
                 } catch (Exception $e) {
                     $this->logger->warn(sprintf(_("Cannot delete old snapshot ({$snapinfo['id']}): %s"), $e->getMessage()));
                 }
             }
         }
     }
     \Scalr::getContainer()->logger(__CLASS__)->warn("OnEndForking: rotate mysql snapshots");
     // Rotate MySQL master snapshots.
     $list = $db->GetAll("\n            SELECT farm_roleid\n            FROM farm_role_settings\n            WHERE name=? AND value='1'\n        ", [Entity\FarmRoleSetting::MYSQL_EBS_SNAPS_ROTATION_ENABLED]);
     foreach ($list as $list_item) {
         try {
             $DBFarmRole = DBFarmRole::LoadByID($list_item['farm_roleid']);
         } catch (Exception $e) {
             continue;
         }
         try {
             $DBFarm = $DBFarmRole->GetFarmObject();
         } catch (Exception $e) {
             continue;
         }
         if ($DBFarm->Status == FARM_STATUS::RUNNING) {
             $old_snapshots = $db->GetAll("\n                    SELECT * FROM storage_snapshots\n                    WHERE ismysql='1'\n                    AND farm_roleid=?\n                    AND `type`='ebs'\n                    ORDER BY dtcreated ASC\n                ", [$DBFarmRole->ID]);
             if (count($old_snapshots) > $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_EBS_SNAPS_ROTATE)) {
                 try {
                     $aws = $DBFarm->GetEnvironmentObject()->aws($DBFarmRole);
                     while (count($old_snapshots) > $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_EBS_SNAPS_ROTATE)) {
                         $snapinfo = array_shift($old_snapshots);
                         try {
                             $aws->ec2->snapshot->delete($snapinfo['id']);
                             $this->deleteEbsSnapshotInfo($snapinfo['id']);
                             $this->deleteStorageSnapshot($snapinfo['id']);
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "does not exist")) {
                                 $this->deleteEbsSnapshotInfo($snapinfo['id']);
                                 $this->deleteStorageSnapshot($snapinfo['id']);
                             } else {
                                 throw $e;
                             }
                         }
                     }
                     $DBFarm->GetEnvironmentObject()->getContainer()->release('aws');
                     unset($aws);
                 } catch (Exception $e) {
                     $this->logger->warn(sprintf(_("Cannot delete old snapshots snapshotid:%s. %s"), isset($snapinfo['id']) ? $snapinfo['id'] : 'null', $e->getMessage()));
                 }
             }
         }
     }
     \Scalr::getContainer()->logger(__CLASS__)->warn("OnEndForking: auto-snapshot volumes");
     // Auto - snapshotting
     $snapshots_settings = $db->Execute("\n            SELECT * FROM autosnap_settings\n            WHERE (`dtlastsnapshot` < NOW() - INTERVAL `period` HOUR OR `dtlastsnapshot` IS NULL)\n            AND objectid != '0' AND object_type = ?", array(AUTOSNAPSHOT_TYPE::EBSSnap));
     \Scalr::getContainer()->logger(__CLASS__)->warn(sprintf("OnEndForking: found %s volumes", $snapshots_settings->RecordCount()));
     while ($snapshot_settings = $snapshots_settings->FetchRow()) {
         try {
             $environment = Scalr_Environment::init()->loadById($snapshot_settings['env_id']);
             $account = Scalr_Account::init()->loadById($environment->clientId);
             if ($account->status != Scalr_Account::STATUS_ACTIVE) {
                 continue;
             }
             $aws = $environment->aws($snapshot_settings['region']);
             // Check volume
             try {
                 $volume = $aws->ec2->volume->describe($snapshot_settings['objectid'])->get(0);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "does not exist")) {
                     $db->Execute("DELETE FROM autosnap_settings WHERE id=?", array($snapshot_settings['id']));
                 }
                 throw $e;
             }
             $description = "Auto snapshot created by Scalr";
             if (true) {
                 $info = $db->GetRow("\n                        SELECT * FROM ec2_ebs WHERE volume_id=? LIMIT 1\n                    ", array($snapshot_settings['objectid']));
                 $farmName = false;
                 $roleName = false;
                 $serverIndex = false;
                 if ($info) {
                     try {
                         $farmName = DBFarm::LoadByID($info['farm_id'])->Name;
                         $roleName = DBFarmRole::LoadByID($info['farm_roleid'])->GetRoleObject()->name;
                         $serverIndex = $info['server_index'];
                     } catch (Exception $e) {
                     }
                 }
                 if ($farmName) {
                     $description = sprintf("Auto snapshot created by Scalr: %s -> %s #%s", $farmName, $roleName, $serverIndex);
                 }
             }
             //Creates a new snapshot
             $snapshot = $aws->ec2->snapshot->create($snapshot_settings['objectid'], $description);
             if (!empty($volume->tagSet) && $volume->tagSet->count()) {
                 try {
                     //We need to do sleep due to eventual consistency on EC2
                     sleep(2);
                     //Set tags (copy them from the original EBS volume)
                     $snapshot->createTags($volume->tagSet);
                 } catch (Exception $e) {
                     //We want to hear from the cases when it cannot set tag to snapshot
                     trigger_error(sprintf("Could not set tag to snapshot: %s", $e->getMessage()), E_USER_WARNING);
                 }
             }
             $db->Execute("\n                    UPDATE autosnap_settings SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?\n                ", [$snapshot->snapshotId, $snapshot_settings['id']]);
             $db->Execute("\n                    INSERT INTO ebs_snaps_info SET snapid=?, comment=?, dtcreated=NOW(), region=?, autosnapshotid=?\n                ", [$snapshot->snapshotId, _("Auto-snapshot"), $snapshot_settings['region'], $snapshot_settings['id']]);
             // Remove old snapshots
             if ($snapshot_settings['rotate'] != 0) {
                 $old_snapshots = $db->GetAll("\n                        SELECT * FROM ebs_snaps_info\n                        WHERE autosnapshotid=?\n                        ORDER BY id ASC\n                    ", [$snapshot_settings['id']]);
                 if (count($old_snapshots) > $snapshot_settings['rotate']) {
                     try {
                         while (count($old_snapshots) > $snapshot_settings['rotate']) {
                             $snapinfo = array_shift($old_snapshots);
                             try {
                                 $aws->ec2->snapshot->delete($snapinfo['snapid']);
                                 $this->deleteEbsSnapshotInfo($snapinfo['id']);
                             } catch (Exception $e) {
                                 if (stristr($e->getMessage(), "does not exist")) {
                                     $this->deleteEbsSnapshotInfo($snapinfo['id']);
                                 }
                                 throw $e;
                             }
                         }
                     } catch (Exception $e) {
                         $this->logger->error(sprintf(_("Cannot delete old snapshots for volume %s. %s"), $snapshot_settings['objectid'], $e->getMessage()));
                     }
                 }
             }
             $environment->getContainer()->release('aws');
             unset($aws);
         } catch (Exception $e) {
             $this->logger->warn(sprintf(_("Cannot create snapshot for volume %s. %s"), $snapshot_settings['objectid'], $e->getMessage()));
         }
     }
 }
Example #14
0
 public function loginAsOwnerAction()
 {
     $account = Scalr_Account::init()->loadById($this->getParam(self::CALL_PARAM_NAME));
     $owner = $account->getOwner();
     Scalr_Session::create($owner->getId());
     UI::Redirect("/#/dashboard");
 }
Example #15
0
 /**
  * Launches server
  *
  * @param   \ServerCreateInfo       $ServerCreateInfo optional The server create info
  * @param   \DBServer               $DBServer         optional The DBServer object
  * @param   bool                    $delayed          optional
  * @param   string                  $reason           optional
  * @param   \Scalr_Account_User|int $user             optional The Scalr_Account_User object or its unique identifier
  * @return  DBServer|null           Returns the DBServer object on cussess or null otherwise
  */
 public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = "", $user = null)
 {
     $db = self::getDb();
     //Ensures handling identifier of the user instead of the object
     if ($user !== null && !$user instanceof \Scalr_Account_User) {
         try {
             $user = Scalr_Account_User::init()->loadById(intval($user));
         } catch (\Exception $e) {
         }
     }
     if (!$DBServer && $ServerCreateInfo) {
         $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME));
         $DBServer = DBServer::Create($ServerCreateInfo, false, true);
     } elseif (!$DBServer && !$ServerCreateInfo) {
         // incorrect arguments
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server"));
         return null;
     }
     if ($user instanceof \Scalr_Account_User) {
         $DBServer->SetProperties(array(SERVER_PROPERTIES::LAUNCHED_BY_ID => $user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $user->getEmail()));
     }
     if ($delayed) {
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_REASON, $reason);
         $DBServer->Save();
         return $DBServer;
     }
     if ($ServerCreateInfo && $ServerCreateInfo->roleId) {
         $dbRole = DBRole::loadById($ServerCreateInfo->roleId);
         if ($dbRole->generation == 1) {
             $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
             $DBServer->Save();
             $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "ami-scripts servers no longer supported");
             return $DBServer;
         }
     }
     try {
         $account = Scalr_Account::init()->loadById($DBServer->clientId);
         $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1);
         PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer);
         $DBServer->status = SERVER_STATUS::PENDING;
         $DBServer->Save();
         try {
             if (!$reason) {
                 $reason = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON);
             }
             $DBServer->getServerHistory()->markAsLaunched($reason);
         } catch (Exception $e) {
             Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}"));
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage())));
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, $e->getMessage());
         $DBServer->Save();
     }
     if ($DBServer->status == SERVER_STATUS::PENDING) {
         Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer));
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "");
     }
     return $DBServer;
 }
Example #16
0
 /**
  * @param string $name
  * @param string $org
  * @param $email
  * @param $password
  * @param string $agreeTerms
  * @param string $newBilling
  * @param string $country
  * @param string $phone
  * @param string $lastname
  * @param string $firstname
  * @param string $v
  * @param string $numServers
  */
 public function xCreateAccountAction($name = '', $org = '', $email, $password = '', $agreeTerms = '', $newBilling = '', $country = '', $phone = '', $lastname = '', $firstname = '', $v = '', $numServers = '')
 {
     if (!\Scalr::config('scalr.billing.enabled')) {
         exit;
     }
     $Validator = new Scalr_Validator();
     if ($v == 2) {
         if (!$firstname) {
             $err['firstname'] = _("First name required");
         }
         if (!$lastname) {
             $err['lastname'] = _("Last name required");
         }
         //if (!$org)
         //    $err['org'] = _("Organization required");
         $name = $firstname . " " . $lastname;
     } else {
         if (!$name) {
             $err['name'] = _("Account name required");
         }
     }
     if (!$password) {
         $password = $this->getCrypto()->sault(10);
     }
     if ($Validator->validateEmail($email, null, true) !== true) {
         $err['email'] = _("Invalid E-mail address");
     }
     if (strlen($password) < 6) {
         $err['password'] = _("Password should be longer than 6 chars");
     }
     // Check email
     $DBEmailCheck = $this->db->GetOne("SELECT COUNT(*) FROM account_users WHERE email=?", array($email));
     if ($DBEmailCheck > 0) {
         $err['email'] = _("E-mail already exists in database");
     }
     if (!$agreeTerms) {
         $err['agreeTerms'] = _("You need to agree with terms and conditions");
     }
     if (count($err) == 0) {
         $account = Scalr_Account::init();
         $account->name = $org ? $org : $name;
         $account->status = Scalr_Account::STATUS_ACTIVE;
         $account->save();
         $account->createEnvironment("Environment 1");
         $account->initializeAcl();
         $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
         $user->fullname = $name;
         $user->save();
         if ($v == 2) {
             $user->setSetting('website.phone', $phone);
             $user->setSetting('website.country', $country);
             $user->setSetting('website.num_servers', $numServers);
         }
         /**
          * Limits
          */
         $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host');
         try {
             $billing = new Scalr_Billing();
             $billing->loadByAccount($account);
             $billing->createSubscription(Scalr_Billing::PAY_AS_YOU_GO, "", "", "", "");
             /*******************/
         } catch (Exception $e) {
             $account->delete();
             header("Location: {$url}/order/?error={$e->getMessage()}");
             exit;
         }
         if ($_COOKIE['__utmz']) {
             $gaParser = new Scalr_Service_GoogleAnalytics_Parser();
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_CONTENT] = $gaParser->campaignContent;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_MEDIUM] = $gaParser->campaignMedium;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_NAME] = $gaParser->campaignName;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_SOURCE] = $gaParser->campaignSource;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_TERM] = $gaParser->campaignTerm;
             $clientSettings[CLIENT_SETTINGS::GA_FIRST_VISIT] = $gaParser->firstVisit;
             $clientSettings[CLIENT_SETTINGS::GA_PREVIOUS_VISIT] = $gaParser->previousVisit;
             $clientSettings[CLIENT_SETTINGS::GA_TIMES_VISITED] = $gaParser->timesVisited;
         }
         $clientSettings[CLIENT_SETTINGS::RSS_LOGIN] = $email;
         $clientSettings[CLIENT_SETTINGS::RSS_PASSWORD] = $this->getCrypto()->sault(10);
         foreach ($clientSettings as $k => $v) {
             $account->setSetting($k, $v);
         }
         try {
             $this->db->Execute("INSERT INTO default_records SELECT null, '{$account->id}', rtype, ttl, rpriority, rvalue, rkey FROM default_records WHERE clientid='0'");
         } catch (Exception $e) {
         }
         $clientinfo = array('fullname' => $name, 'firstname' => $firstname ? $firstname : $name, 'email' => $email, 'password' => $password);
         //Sends welcome email
         $this->getContainer()->mailer->setFrom('*****@*****.**', 'Scalr')->setHtml()->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/welcome.html.php', array('firstName' => htmlspecialchars($clientinfo['firstname']), 'password' => htmlspecialchars($clientinfo['password']), "siteUrl" => htmlspecialchars($url), "wikiUrl" => htmlspecialchars(\Scalr::config('scalr.ui.wiki_url')), "supportUrl" => htmlspecialchars(\Scalr::config('scalr.ui.support_url')), "isUrl" => preg_match('/^http(s?):\\/\\//i', \Scalr::config('scalr.ui.support_url'))), $email);
         $user->getAccount()->setSetting(Scalr_Account::SETTING_IS_TRIAL, 1);
         //AutoLogin
         $user->updateLastLogin();
         Scalr_Session::create($user->getId());
         Scalr_Session::keepSession();
         $this->response->setRedirect("{$url}/thanks.html");
     } else {
         $errors = array_values($err);
         $error = $errors[0];
         $this->response->setRedirect("{$url}/order/?error={$error}");
     }
 }
Example #17
0
 private function cleanup()
 {
     // Check that time has come to cleanup dead servers
     $doCleanup = false;
     sem_acquire($this->cleanupSem);
     try {
         if (time() - (int) $this->lastCleanup->get(0) >= $this->cleanupInterval) {
             $doCleanup = true;
             $this->lastCleanup->put(0, time());
         }
     } catch (Exception $e) {
         sem_release($this->cleanupSem);
     }
     sem_release($this->cleanupSem);
     if ($doCleanup) {
         $this->logger->info("Cleanup dead servers");
         try {
             $terminated_servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status=? AND (UNIX_TIMESTAMP(dtshutdownscheduled)+3600 < UNIX_TIMESTAMP(NOW()) OR dtshutdownscheduled IS NULL)", array(SERVER_STATUS::TERMINATED));
             foreach ($terminated_servers as $ts) {
                 DBServer::LoadByID($ts['server_id'])->Remove();
             }
             $p_terminated_servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status=? AND role_id='0' AND farm_id IS NULL", array(SERVER_STATUS::PENDING_TERMINATE));
             foreach ($p_terminated_servers as $ts) {
                 DBServer::LoadByID($ts['server_id'])->Remove();
             }
             $importing_servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN(?,?) AND UNIX_TIMESTAMP(dtadded)+86400 < UNIX_TIMESTAMP(NOW())", array(SERVER_STATUS::IMPORTING, SERVER_STATUS::TEMPORARY));
             foreach ($importing_servers as $ts) {
                 DBServer::LoadByID($ts['server_id'])->Remove();
             }
             $pending_launch_servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status=?", array(SERVER_STATUS::PENDING_LAUNCH));
             try {
                 foreach ($pending_launch_servers as $ts) {
                     $DBServer = DBServer::LoadByID($ts['server_id']);
                     $account = Scalr_Account::init()->loadById($DBServer->clientId);
                     if ($account->status == Scalr_Account::STATUS_ACTIVE) {
                         Scalr::LaunchServer(null, $DBServer);
                     }
                 }
             } catch (Exception $e) {
                 Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Can't load server with ID #'%s'", $ts['server_id'], $e->getMessage()));
             }
         } catch (Exception $e) {
             $this->logger->fatal("Poller::cleanup failed: {$e->getMessage()}");
         }
     }
 }
Example #18
0
 /**
  * @param string  $name
  * @param string  $org
  * @param string  $email
  * @param RawData $password
  * @param string  $agreeTerms
  * @param string  $newBilling
  * @param string  $country
  * @param string  $phone
  * @param string  $lastname
  * @param string  $firstname
  * @param string  $v
  * @param string  $numServers
  */
 public function xCreateAccountAction($name = '', $org = '', $email = '', RawData $password = null, $agreeTerms = '', $newBilling = '', $country = '', $phone = '', $lastname = '', $firstname = '', $v = '', $numServers = '', $beta = 0)
 {
     if (!\Scalr::config('scalr.billing.enabled')) {
         header("HTTP/1.0 403 Forbidden");
         exit;
     }
     $validator = new Validator();
     if ($v == 2) {
         $validator->validate($firstname, "firstname", Validator::NOEMPTY, [], "First name is required");
         $validator->validate($lastname, "lastname", Validator::NOEMPTY, [], "Last name is required");
         $name = $firstname . " " . $lastname;
     } else {
         $validator->validate($name, "name", Validator::NOEMPTY, [], "Account name is required");
     }
     if ($password == '') {
         $password = \Scalr::GenerateSecurePassword(User::PASSWORD_ADMIN_LENGTH);
     }
     $validator->validate($email, "email", Validator::EMAIL);
     $validator->validate($password, "password", Validator::PASSWORD, ['admin']);
     $validator->addErrorIf($this->db->GetOne("SELECT EXISTS(SELECT * FROM account_users WHERE email = ?)", [$email]), "email", "E-mail already exists in the database");
     $validator->validate($agreeTerms, "agreeTerms", Validator::NOEMPTY, [], "You haven't accepted terms and conditions");
     $errors = $validator->getErrors(true);
     if (empty($errors)) {
         $account = Scalr_Account::init();
         $account->name = $org ? $org : $name;
         $account->status = Scalr_Account::STATUS_ACTIVE;
         $account->save();
         $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
         $user->fullname = $name;
         $user->save();
         if ($this->getContainer()->analytics->enabled) {
             $analytics = $this->getContainer()->analytics;
             //Default Cost Center should be assigned
             $cc = $analytics->ccs->get($analytics->usage->autoCostCentre());
             //Assigns account with Cost Center
             $accountCcEntity = new AccountCostCenterEntity($account->id, $cc->ccId);
             $accountCcEntity->save();
         }
         //Creates Environment. It will be associated with the Cost Center itself.
         $account->createEnvironment("Environment 1");
         $account->initializeAcl();
         if ($v == 2) {
             $user->setSetting('website.phone', $phone);
             $user->setSetting('website.country', $country);
             $user->setSetting('website.num_servers', $numServers);
         }
         /**
          * Limits
          */
         $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host');
         try {
             $billing = new Scalr_Billing();
             $billing->loadByAccount($account);
             $billing->createSubscription(Scalr_Billing::PAY_AS_YOU_GO, "", "", "", "");
         } catch (Exception $e) {
             $account->delete();
             header("Location: {$url}/order/?error={$e->getMessage()}");
             exit;
         }
         if ($_COOKIE['__utmz']) {
             $gaParser = new Scalr_Service_GoogleAnalytics_Parser();
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_CONTENT] = $gaParser->campaignContent;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_MEDIUM] = $gaParser->campaignMedium;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_NAME] = $gaParser->campaignName;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_SOURCE] = $gaParser->campaignSource;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_TERM] = $gaParser->campaignTerm;
             $clientSettings[CLIENT_SETTINGS::GA_FIRST_VISIT] = $gaParser->firstVisit;
             $clientSettings[CLIENT_SETTINGS::GA_PREVIOUS_VISIT] = $gaParser->previousVisit;
             $clientSettings[CLIENT_SETTINGS::GA_TIMES_VISITED] = $gaParser->timesVisited;
         }
         if (!empty($clientSettings)) {
             foreach ($clientSettings as $k => $v) {
                 $account->setSetting($k, $v);
             }
         }
         try {
             $this->db->Execute("\n                    INSERT INTO default_records\n                    SELECT null, '{$account->id}', rtype, ttl, rpriority, rvalue, rkey\n                    FROM default_records\n                    WHERE clientid='0'\n                ");
         } catch (Exception $e) {
         }
         $clientinfo = array('fullname' => $name, 'firstname' => $firstname ? $firstname : $name, 'email' => $email, 'password' => $password);
         //Sends welcome email
         $this->getContainer()->mailer->setFrom('*****@*****.**', 'Scalr')->setHtml()->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/welcome.html.php', array('firstName' => htmlspecialchars($clientinfo['firstname']), 'password' => htmlspecialchars($clientinfo['password']), "siteUrl" => htmlspecialchars($url), "wikiUrl" => htmlspecialchars(\Scalr::config('scalr.ui.wiki_url')), "supportUrl" => htmlspecialchars(\Scalr::config('scalr.ui.support_url')), "isUrl" => preg_match('/^http(s?):\\/\\//i', \Scalr::config('scalr.ui.support_url'))), $email);
         $user->getAccount()->setSetting(Scalr_Account::SETTING_IS_TRIAL, 1);
         //AutoLogin
         $user->updateLastLogin();
         Scalr_Session::create($user->getId());
         Scalr_Session::keepSession();
         if ($beta != 1) {
             $this->response->setRedirect("{$url}/thanks.html");
         } else {
             $this->response->data(array('accountId' => $user->getAccountId()));
         }
     } else {
         if ($beta == 1) {
             header("HTTP/1.0 400 Bad request");
             print json_encode($errors);
             exit;
         } else {
             $error = array_values($errors)[0];
             $this->response->setRedirect("{$url}/order/?error={$error}");
         }
     }
 }
 public function OnStartForking()
 {
     // start cron, which runs scripts by it's schedule queue
     try {
         $db = Core::GetDBInstance(null, true);
         // set status to "finished" for active tasks, which ended or executed once
         $info = $db->Execute("UPDATE scheduler SET `status` = ? WHERE\r\n\t\t\t\t`status` = ? AND (`end_time` < NOW() OR (`last_start_time` < NOW() AND `restart_every` = 0))", 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 *\r\n\t\t\t\tFROM scheduler\r\n\t\t\t\tWHERE `status` = ? AND (`end_time` > NOW() OR `end_time` IS NULL) AND (`start_time` <= NOW() OR `start_time` IS NULL) AND (\r\n\t\t\t\t\t`last_start_time` IS NULL OR\r\n\t\t\t\t\t`last_start_time` IS NOT NULL AND (last_start_time + INTERVAL (restart_every * 0.9 * 60) SECOND < NOW())\r\n\t\t\t\t)\r\n\t\t\t\tORDER BY IF (last_start_time, last_start_time, start_time), order_index ASC\r\n\t\t\t", 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()}");
             }
             // check time
             $lastStartTime = $task['last_start_time'] ? strtotime($task['last_start_time']) : NULL;
             if ($lastStartTime) {
                 if ($task['start_time'] == NULL) {
                     // disallow execute earlier
                     if ($lastStartTime + $task['restart_every'] * 60 > time()) {
                         continue;
                     }
                 } else {
                     // try to auto-align time to start time
                     $startTime = strtotime($task['start_time']);
                     $num = (time() - $startTime) / ($task['restart_every'] * 60);
                     /*file_put_contents("test.txt", print_r($task['name'], true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(date('r', $lastStartTime), true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(date('r'), true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r($num, true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(floor($num), true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(round($num, 0, PHP_ROUND_HALF_UP), true), FILE_APPEND);
                     		file_put_contents("test.txt", "\n", FILE_APPEND);*/
                     // num sholud be less than 0.5
                     if (floor($num) != round($num, 0, PHP_ROUND_HALF_UP)) {
                         continue;
                     }
                 }
             }
             // Terminate, Launch farm  or execute script
             $farmRoleNotFound = false;
             switch ($task['type']) {
                 case Scalr_SchedulerTask::LAUNCH_FARM:
                     try {
                         $farmId = $task['target_id'];
                         $DBFarm = DBFarm::LoadByID($farmId);
                         if ($DBFarm->Status == FARM_STATUS::TERMINATED) {
                             // launch farm
                             Scalr::FireEvent($farmId, new FarmLaunchedEvent(true));
                             $this->Logger->info(sprintf("Farm #{$farmId} successfully launched"));
                         } elseif ($DBFarm->Status == FARM_STATUS::RUNNING) {
                             // farm is running
                             $this->Logger->info(sprintf("Farm #{$farmId} is already running"));
                         } else {
                             // farm can't be launched
                             $this->Logger->info(sprintf("Farm #{$farmId} can't be launched because of it's status: {$DBFarm->Status}"));
                         }
                     } catch (Exception $e) {
                         // farm  not found
                         $farmRoleNotFound = true;
                         $this->Logger->info(sprintf("Farm #{$farmId} was not found and can't be launched"));
                     }
                     break;
                 case SCHEDULE_TASK_TYPE::TERMINATE_FARM:
                     try {
                         // get config settings
                         $farmId = $task['target_id'];
                         $config = unserialize($task['config']);
                         $deleteDNSZones = (int) $config['deleteDNSZones'];
                         $deleteCloudObjects = (int) $config['deleteCloudObjects'];
                         $keepCloudObjects = $deleteCloudObjects == 1 ? 0 : 1;
                         $DBFarm = DBFarm::LoadByID($farmId);
                         if ($DBFarm->Status == FARM_STATUS::RUNNING) {
                             // terminate farm
                             $event = new FarmTerminatedEvent($deleteDNSZones, $keepCloudObjects, false, $keepCloudObjects);
                             Scalr::FireEvent($farmId, $event);
                             $this->Logger->info(sprintf("Farm successfully terminated"));
                         } else {
                             $this->Logger->info(sprintf("Farm #{$farmId} can't be terminated because of it's status"));
                         }
                     } catch (Exception $e) {
                         // role not found
                         $farmRoleNotFound = true;
                         $this->Logger->info(sprintf("Farm #{$farmId} was not found and can't be terminated"));
                     }
                     break;
                 case SCHEDULE_TASK_TYPE::SCRIPT_EXEC:
                     // generate event name
                     $eventName = Scalr_Scripting_Manager::generateEventName('CustomEvent');
                     $instances = array();
                     try {
                         // get variables for SQL INSERT or UPDATE
                         $config = unserialize($task['config']);
                         if (!$config['scriptId']) {
                             throw new Exception(_("Script %s is not existed"), $config['scriptId']);
                         }
                         // check avaliable script version
                         if (!$db->GetOne("SELECT id FROM script_revisions WHERE scriptid = ? AND revision = ? AND approval_state = ?", array($config['scriptId'], $config['scriptVersion'], APPROVAL_STATE::APPROVED))) {
                             throw new Exception(_("Selected version is not approved or no longer available"));
                         }
                         // get executing object by target_type variable
                         switch ($task['target_type']) {
                             case SCRIPTING_TARGET::FARM:
                                 $DBFarm = DBFarm::LoadByID($task['target_id']);
                                 $farmId = $DBFarm->ID;
                                 $farmRoleId = null;
                                 $servers = $db->GetAll("SELECT * FROM servers WHERE `status` IN (?,?) AND farm_id = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId));
                                 break;
                             case SCRIPTING_TARGET::ROLE:
                                 $farmRoleId = $task['target_id'];
                                 $DBFarmRole = DBFarmRole::LoadByID($farmRoleId);
                                 $farmId = $DBFarmRole->GetFarmObject()->ID;
                                 $servers = $db->GetAll("SELECT * FROM servers WHERE `status` IN (?,?) AND farm_roleid = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId));
                                 break;
                             case SCRIPTING_TARGET::INSTANCE:
                                 $instanceArgs = explode(":", $task['target_id']);
                                 $farmRoleId = $instanceArgs[0];
                                 $DBFarmRole = DBFarmRole::LoadByID($farmRoleId);
                                 // target for instance looks like  "farm_roleid:index"
                                 // script gets farmid conformed to the roleid and index
                                 $servers = $db->GetAll("SELECT * FROM servers WHERE `status` IN (?,?) AND farm_roleid = ? AND `index` = ? ", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId, $instanceArgs[1]));
                                 $farmId = $servers[0]["farm_id"];
                                 break;
                         }
                         if ($servers) {
                             $db->Execute("INSERT INTO farm_role_scripts SET\r\n\t\t\t\t\t\t\t\t\tscriptid\t= ?,\r\n\t\t\t\t\t\t\t\t\tfarmid\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tfarm_roleid\t= ?,\r\n\t\t\t\t\t\t\t\t\tparams\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tevent_name\t= ?,\r\n\t\t\t\t\t\t\t\t\ttarget\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tversion\t\t= ?,\r\n\t\t\t\t\t\t\t\t\ttimeout\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tissync\t\t= ?,\r\n\t\t\t\t\t\t\t\t\torder_index = ?,\r\n\t\t\t\t\t\t\t\t\tismenuitem\t= ?,\r\n\t\t\t\t\t\t\t\t\t`debug`\t\t= ?\r\n\t\t\t\t\t\t\t\t", array($config['scriptId'], $farmId, $farmRoleId, serialize($config['scriptOptions']), $eventName, $task['target_type'], $config['scriptVersion'], $config['scriptTimeout'], $config['scriptIsSync'], $task["order_index"], 0, 'scheduler2'));
                             $farmRoleScriptId = $db->Insert_ID();
                             // send message to start executing task (starts script)
                             foreach ($servers as $server) {
                                 $DBServer = DBServer::LoadByID($server['server_id']);
                                 $msg = new Scalr_Messaging_Msg_ExecScript($eventName);
                                 $msg->meta[Scalr_Messaging_MsgMeta::EVENT_ID] = "FRSID-{$farmRoleScriptId}";
                                 $msg = Scalr_Scripting_Manager::extendMessage($msg, $DBServer);
                                 $DBServer->SendMessage($msg);
                             }
                         }
                     } catch (Exception $e) {
                         // farm or role not found.
                         $farmRoleNotFound = true;
                         $this->Logger->warn(sprintf("Farm, role or instances were not found, script can't be executed"));
                     }
                     break;
             }
             if ($farmRoleNotFound) {
                 // delete task if farm or role not found.
                 //$db->Execute("DELETE FROM scheduler  WHERE id = ?", array($task['id']));
                 //$this->Logger->warn(sprintf("Task {$task['id']} was deleted, because of the farm or role was not found"));
             } else {
                 $db->Execute("UPDATE  scheduler SET last_start_time = NOW() WHERE id = ?", array($task['id']));
                 $this->Logger->info(sprintf("Task {$task['id']} successfully sent"));
             }
         }
     } catch (Exception $e) {
         $this->Logger->warn(sprintf("Can't execute task {$task['id']}. Error message: %s", $e->getMessage()));
     }
 }
Example #20
0
 /**
  * Gets project properties and parameters
  *
  * @param   ProjectEntity    $projectEntity          Project entity
  * @param   string           $calculate     optional Whether response should be adjusted with cost usage data
  * @return  array Returns cost centre properties and parameters
  */
 private function getProjectData(ProjectEntity $projectEntity, $calculate = false)
 {
     $ret = array('ccId' => $projectEntity->ccId, 'ccName' => $projectEntity->getCostCenter() !== null ? $projectEntity->getCostCenter()->name : null, 'projectId' => $projectEntity->projectId, 'name' => $projectEntity->name, 'billingCode' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE), 'description' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_DESCRIPTION), 'leadEmail' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL), 'created' => $projectEntity->created->format('Y-m-d'), 'createdByEmail' => $projectEntity->createdByEmail, 'archived' => $projectEntity->archived, 'shared' => $projectEntity->shared, 'farmsCount' => count($projectEntity->getFarmsList()));
     if (!empty($projectEntity->accountId) && $projectEntity->shared === ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         $ret['accountId'] = $projectEntity->accountId;
         $ret['accountName'] = Scalr_Account::init()->loadById($projectEntity->accountId)->name;
     } elseif (!empty($projectEntity->envId) && $projectEntity->shared === ProjectEntity::SHARED_WITHIN_ENV) {
         $ret['accountId'] = $projectEntity->accountId;
         $ret['accountName'] = Scalr_Account::init()->loadById($projectEntity->accountId)->name;
         $ret['envId'] = $projectEntity->envId;
         $ret['envName'] = Scalr_Environment::init()->loadById($projectEntity->envId)->name;
     }
     if ($calculate) {
         $iterator = ChartPeriodIterator::create('month', gmdate('Y-m-01'), null, 'UTC');
         $usage = $this->getContainer()->analytics->usage->get(['projectId' => $ret['projectId']], $iterator->getStart(), $iterator->getEnd());
         //It calculates usage for previous period same days
         $prevusage = $this->getContainer()->analytics->usage->get(['projectId' => $ret['projectId']], $iterator->getPreviousStart(), $iterator->getPreviousEnd());
         $ret = $this->getWrappedUsageData(['ccId' => $ret['ccId'], 'projectId' => $ret['projectId'], 'iterator' => $iterator, 'usage' => $usage['cost'], 'prevusage' => $prevusage['cost']]) + $ret;
     }
     return $ret;
 }
Example #21
0
 /**
  * {@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)));
                     $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                     $DBServer->SetProperties([SERVER_PROPERTIES::REBOOTING => 0, SERVER_PROPERTIES::RESUMING => 0]);
                     Scalr::FireEvent($DBFarm->ID, new HostDownEvent($DBServer));
                     continue;
                 } elseif ($DBServer->GetRealStatus()->isSuspended()) {
                     // if server was suspended when it was running
                     if ($DBServer->status == SERVER_STATUS::RUNNING) {
                         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->SetProperties([SERVER_PROPERTIES::REBOOTING => 0, SERVER_PROPERTIES::RESUMING => 0, SERVER_PROPERTIES::SUB_STATUS => ""]);
                         $DBServer->remoteIp = "";
                         $DBServer->localIp = "";
                         $DBServer->status = SERVER_STATUS::SUSPENDED;
                         $DBServer->Save();
                         Scalr::FireEvent($DBFarm->ID, new HostDownEvent($DBServer));
                         continue;
                     } else {
                         // If server was suspended during initialization - we do not support this and need to terminate this instance
                         $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                         continue;
                     }
                 }
             }
             if ($DBServer->status != SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->IsRunning()) {
                 if ($DBServer->status == SERVER_STATUS::SUSPENDED) {
                     //TODO: Depends on resume strategy need to set server status
                     // For Openstack we need to re-accociate IPs
                     $DBServer->SetProperty(\SERVER_PROPERTIES::RESUMING, 0);
                     try {
                         if ($DBServer->isOpenstack()) {
                             $this->openstackSetFloatingIp($DBServer);
                         }
                     } catch (Exception $e) {
                         if (!$DBServer->GetProperty(SERVER_PROPERTIES::SZR_IS_INIT_FAILED)) {
                             $DBServer->SetProperties([SERVER_PROPERTIES::SZR_IS_INIT_FAILED => 1, SERVER_PROPERTIES::SZR_IS_INIT_ERROR_MSG => $e->getMessage()]);
                         }
                     }
                     Scalr::FireEvent($DBFarm->ID, new HostUpEvent($DBServer, ""));
                     continue;
                 } elseif (!in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::TROUBLESHOOTING))) {
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         if ($DBServer->status == SERVER_STATUS::PENDING && $DBFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
                             if ($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS) != 'outbound-only') {
                                 $ipAddress = \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::setEipForServer($DBServer);
                                 if ($ipAddress) {
                                     $DBServer->remoteIp = $ipAddress;
                                     $DBServer->Save();
                                 }
                             }
                         }
                     }
                     try {
                         if ($DBServer->isOpenstack()) {
                             $this->openstackSetFloatingIp($DBServer);
                         }
                     } catch (Exception $e) {
                         if (!$DBServer->GetProperty(SERVER_PROPERTIES::SZR_IS_INIT_FAILED)) {
                             $DBServer->SetProperties([SERVER_PROPERTIES::SZR_IS_INIT_FAILED => 1, SERVER_PROPERTIES::SZR_IS_INIT_ERROR_MSG => $e->getMessage()]);
                         }
                     }
                     if ($DBServer->isCloudstack()) {
                         if ($DBServer->status == SERVER_STATUS::PENDING) {
                             $jobId = $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID);
                             try {
                                 $cs = $DBServer->GetEnvironmentObject()->cloudstack($DBServer->platform);
                                 $res = $cs->queryAsyncJobResult($jobId);
                                 if ($res->jobstatus == 1) {
                                     $DBServer->SetProperties([CLOUDSTACK_SERVER_PROPERTIES::TMP_PASSWORD => $res->virtualmachine->password, CLOUDSTACK_SERVER_PROPERTIES::SERVER_NAME => $res->virtualmachine->name]);
                                 }
                                 //TODO: handle failed job: $res->jobresult->jobstatus == 2
                             } catch (Exception $e) {
                                 if ($DBServer->farmId) {
                                     Logger::getLogger("CloudStack")->error(new FarmLogMessage($DBServer->farmId, $e->getMessage()));
                                 }
                             }
                         }
                     }
                     try {
                         $dtadded = strtotime($DBServer->dateAdded);
                         $DBFarmRole = $DBServer->GetFarmRoleObject();
                         $launch_timeout = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) > 0 ? $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) : 900;
                     } catch (Exception $e) {
                         if (stristr($e->getMessage(), "not found")) {
                             $DBServer->terminate(DBServer::TERMINATE_REASON_ROLE_REMOVED);
                         }
                     }
                     $scripting_event = false;
                     if ($DBServer->status == SERVER_STATUS::PENDING) {
                         $event = "hostInit";
                         $scripting_event = EVENT_TYPE::HOST_INIT;
                     } elseif ($DBServer->status == SERVER_STATUS::INIT) {
                         $event = "hostUp";
                         $scripting_event = EVENT_TYPE::HOST_UP;
                     }
                     if ($scripting_event && $dtadded) {
                         $scripting_timeout = (int) $this->db->GetOne("\n                                SELECT sum(timeout)\n                                FROM farm_role_scripts\n                                WHERE event_name=? AND\n                                farm_roleid=? AND issync='1'\n                            ", array($scripting_event, $DBServer->farmRoleId));
                         if ($scripting_timeout) {
                             $launch_timeout = $launch_timeout + $scripting_timeout;
                         }
                         if ($dtadded + $launch_timeout < time() && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //Add entry to farm log
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' did not send '%s' event in %s seconds after launch (Try increasing timeouts in role settings). Considering it broken. Terminating instance.", $DBServer->serverId, $event, $launch_timeout)));
                             try {
                                 $DBServer->terminate(array(DBServer::TERMINATE_REASON_SERVER_DID_NOT_SEND_EVENT, $event, $launch_timeout), false);
                             } catch (Exception $err) {
                                 $this->logger->fatal($err->getMessage());
                             }
                         } elseif ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //DO NOT TERMINATE MONGODB INSTANCES BY TIMEOUT! IT'S NOT SAFE
                             //THINK ABOUT WORKAROUND
                         }
                     }
                     // Is IP address changed?
                     if (!$DBServer->IsRebooting()) {
                         $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                         if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("RemoteIP: %s (%s), LocalIp: %s (%s) (Poller).", $DBServer->remoteIp, $ipaddresses['remoteIp'], $DBServer->localIp, $ipaddresses['localIp'])));
                             Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                         }
                         //TODO: Check health:
                     }
                 }
             } elseif ($DBServer->status == SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->isRunning()) {
                 // Is IP address changed?
                 if (!$DBServer->IsRebooting()) {
                     $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     if ($ipaddresses['remoteIp'] && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp != $ipaddresses['localIp']) {
                         Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                     }
                     if ($payAsYouGoTime) {
                         $initTime = $DBServer->GetProperty(SERVER_PROPERTIES::INITIALIZED_TIME);
                         if ($initTime < $payAsYouGoTime) {
                             $initTime = $payAsYouGoTime;
                         }
                         $runningHours = ceil((time() - $initTime) / 3600);
                         $scuUsed = $runningHours * Scalr_Billing::getSCUByInstanceType($DBServer->GetFlavor(), $DBServer->platform);
                         $this->db->Execute("UPDATE servers_history SET scu_used = ?, scu_updated = 0 WHERE server_id = ?", array($scuUsed, $DBServer->serverId));
                     }
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $env = Scalr_Environment::init()->loadById($DBServer->envId);
                         $ec2 = $env->aws($DBServer->GetCloudLocation())->ec2;
                         //TODO:
                         $time = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED_LAST_CHECK_TIME);
                         if (!$time || time() < $time + 1200) {
                             $isEnabled = $ec2->instance->describeAttribute($DBServer->GetCloudServerID(), InstanceAttributeType::disableApiTermination());
                             $DBServer->SetProperties([EC2_SERVER_PROPERTIES::IS_LOCKED => $isEnabled, EC2_SERVER_PROPERTIES::IS_LOCKED_LAST_CHECK_TIME => time()]);
                         }
                     }
                 } else {
                     //TODO: Check reboot timeout
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "not found")) {
                 print $e->getTraceAsString() . "\n";
             } elseif (stristr($e->getMessage(), "Request limit exceeded")) {
                 sleep(10);
                 print "[1:SLEEP][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             } else {
                 print "[1][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             }
         }
     }
 }
Example #22
0
 /**
  *
  * @return Scalr_Account
  */
 public function getAccount()
 {
     if (!$this->account) {
         $this->account = Scalr_Account::init()->loadById($this->accountId);
     }
     return $this->account;
 }
Example #23
0
 public function xCreateAccountAction()
 {
     global $Mailer;
     //FIXME:
     if (!class_exists("Scalr_Billing")) {
         exit;
     }
     $this->request->defineParams(array('name', 'org', 'email', 'password', 'agreeTerms', 'newBilling', 'country', 'phone', 'lastname', 'firstname', 'v', 'numServers'));
     $Validator = new Validator();
     if ($this->getParam('v') == 2) {
         if (!$this->getParam('firstname')) {
             $err['firstname'] = _("First name required");
         }
         if (!$this->getParam('lastname')) {
             $err['lastname'] = _("Last name required");
         }
         if (!$this->getParam('org')) {
             $err['org'] = _("Organization required");
         }
         $name = $this->getParam('firstname') . " " . $this->getParam('lastname');
     } else {
         if (!$this->getParam('name')) {
             $err['name'] = _("Account name required");
         }
         $name = $this->getParam("name");
     }
     $password = $this->getParam('password');
     if (!$password) {
         $password = $this->getCrypto()->sault(10);
     }
     if (!$Validator->IsEmail($this->getParam('email'))) {
         $err['email'] = _("Invalid E-mail address");
     }
     if (strlen($password) < 6) {
         $err['password'] = _("Password should be longer than 6 chars");
     }
     // Check email
     $DBEmailCheck = $this->db->GetOne("SELECT COUNT(*) FROM account_users WHERE email=?", array($this->getParam('email')));
     if ($DBEmailCheck > 0) {
         $err['email'] = _("E-mail already exists in database");
     }
     if (!$this->getParam('agreeTerms')) {
         $err['agreeTerms'] = _("You need to agree with terms and conditions");
     }
     if (count($err) == 0) {
         $account = Scalr_Account::init();
         $account->name = $this->getParam("org") ? $this->getParam("org") : $name;
         $account->status = Scalr_Account::STATUS_ACTIVE;
         $account->save();
         $account->createEnvironment("default", true);
         $user = $account->createUser($this->getParam('email'), $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
         $user->fullname = $name;
         $user->save();
         if ($this->getParam('v') == 2) {
             $user->setSetting('website.phone', $this->getParam('phone'));
             $user->setSetting('website.country', $this->getParam('country'));
             $user->setSetting('website.num_servers', $this->getParam('numServers'));
         }
         /**
          * Limits
          */
         try {
             $billing = new Scalr_Billing();
             $billing->loadByAccount($account);
             $billing->createSubscription(Scalr_Billing::PACKAGE_SEED, "", "", "", "");
             /*******************/
         } catch (Exception $e) {
             $account->delete();
             header("Location: https://scalr.net/order/?error={$e->getMessage()}");
             exit;
         }
         if ($_COOKIE['__utmz']) {
             $gaParser = new Scalr_Service_GoogleAnalytics_Parser();
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_CONTENT] = $gaParser->campaignContent;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_MEDIUM] = $gaParser->campaignMedium;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_NAME] = $gaParser->campaignName;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_SOURCE] = $gaParser->campaignSource;
             $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_TERM] = $gaParser->campaignTerm;
             $clientSettings[CLIENT_SETTINGS::GA_FIRST_VISIT] = $gaParser->firstVisit;
             $clientSettings[CLIENT_SETTINGS::GA_PREVIOUS_VISIT] = $gaParser->previousVisit;
             $clientSettings[CLIENT_SETTINGS::GA_TIMES_VISITED] = $gaParser->timesVisited;
         }
         $clientSettings[CLIENT_SETTINGS::RSS_LOGIN] = $this->getParam('email');
         $clientSettings[CLIENT_SETTINGS::RSS_PASSWORD] = $this->getCrypto()->sault(10);
         foreach ($clientSettings as $k => $v) {
             $account->setSetting($k, $v);
         }
         try {
             $this->db->Execute("INSERT INTO default_records SELECT null, '{$account->id}', rtype, ttl, rpriority, rvalue, rkey FROM default_records WHERE clientid='0'");
         } catch (Exception $e) {
         }
         $clientinfo = array('fullname' => $name, 'firstname' => $this->getParam('firstname') ? $this->getParam('firstname') : $name, 'email' => $this->getParam('email'), 'password' => $password);
         $mailer = new PHPMailer();
         $mailer->Subject = 'Welcome to the Scalr revolution!';
         $mailer->From = '*****@*****.**';
         $mailer->FromName = 'Scalr';
         $mailer->AddAddress($this->getParam('email'));
         $mailer->IsHTML(true);
         $mailer->Body = @file_get_contents(dirname(__FILE__) . '/../../../../templates/en_US/emails/welcome.html');
         $mailer->Body = str_replace(array('{{FirstName}}', '{{Password}}'), array($clientinfo['firstname'], $clientinfo['password']), $mailer->Body);
         $mailer->Send();
         /*
         // Send welcome E-mail
         $Mailer->ClearAddresses();
         $Mailer->From 		='*****@*****.**';
         $res = $Mailer->Send("emails/welcome.eml",
         	array("client" => $clientinfo, "site_url" => "http://{$_SERVER['HTTP_HOST']}"),
         	$this->getParam('email'),
         	''
         );
         */
         $user->getAccount()->setSetting(Scalr_Account::SETTING_IS_TRIAL, 1);
         //AutoLogin
         $user->updateLastLogin();
         Scalr_Session::create($user->getId());
         Scalr_Session::keepSession();
         header("Location: http://scalr.net/thanks.html");
     } else {
         $errors = array_values($err);
         $error = $errors[0];
         header("Location: https://scalr.net/order/?error={$error}");
         //$this->response->failure();
         //$this->response->data(array('errors' => $err));
     }
     exit;
 }
Example #24
0
 /**
  * Gets project properties and parameters
  *
  * @param   ProjectEntity    $projectEntity          Project entity
  * @return  array Returns cost centre properties and parameters
  */
 private function getProjectData(ProjectEntity $projectEntity)
 {
     $ret = array('projectId' => $projectEntity->projectId, 'name' => $projectEntity->name, 'ccId' => $projectEntity->ccId, 'ccName' => $projectEntity->getCostCenter() !== null ? $projectEntity->getCostCenter()->name : null, 'billingCode' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE), 'description' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_DESCRIPTION), 'leadEmail' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL), 'created' => $projectEntity->created->format('Y-m-d'), 'createdByEmail' => $projectEntity->createdByEmail, 'archived' => $projectEntity->archived, 'shared' => $projectEntity->shared);
     if (!empty($projectEntity->accountId) && $projectEntity->shared === ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         $ret['accountId'] = $projectEntity->accountId;
         $ret['accountName'] = Scalr_Account::init()->loadById($projectEntity->accountId)->name;
     } elseif (!empty($projectEntity->envId) && $projectEntity->shared === ProjectEntity::SHARED_WITHIN_ENV) {
         $ret['accountId'] = $projectEntity->accountId;
         $ret['accountName'] = Scalr_Account::init()->loadById($projectEntity->accountId)->name;
         $ret['envId'] = $projectEntity->envId;
         $ret['envName'] = \Scalr_Environment::init()->loadById($projectEntity->envId)->name;
     }
     return $ret;
 }
 public function Run()
 {
     $container = Scalr::getContainer();
     $db = $container->adodb;
     $time = microtime(true);
     print "Checking integrity.\n";
     //Check database
     $u20130730 = $db->getOne("SHOW TABLES LIKE 'acl_roles'");
     if ($u20130730 !== 'acl_roles') {
         print "Upgrade terminated. Old database schema. Please run php app/bin/upgrade_20130730.php\n";
         exit;
     }
     $u20130731 = $db->GetCol("SELECT role_id FROM acl_roles WHERE role_id IN (1, 10)");
     if (!in_array(1, $u20130731) || !in_array(10, $u20130731)) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130731.php\n";
         exit;
     }
     $u = $db->getRow("SHOW INDEXES FROM `account_team_envs` WHERE `key_name` = 'fk_account_team_envs_client_environments1'");
     if (!$u) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130802.php\n";
         exit;
     }
     $u = null;
     $res = $db->Execute('DESCRIBE acl_account_roles');
     while ($rec = $res->GetAssoc()) {
         if (isset($rec['color'])) {
             $u = true;
         }
     }
     if (!$u) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130806.php\n";
         exit;
     }
     $u = $db->getRow("SHOW INDEXES FROM `account_team_users` WHERE `key_name` = 'idx_unique'");
     if (!$u) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130807.php\n";
         exit;
     }
     $u = $db->getRow("SHOW INDEXES FROM `account_teams` WHERE `key_name` = 'idx_account_role_id'");
     $u2 = $db->GetOne("SELECT role_id FROM acl_role_resource_permissions WHERE resource_id = 0x106 AND perm_id = 'manage'");
     if (!$u || empty($u2)) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130808_acl.php\n";
         exit;
     }
     $u = $db->getRow("SELECT * FROM `acl_account_role_resources` WHERE resource_id = 0x200");
     if (!empty($u)) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130808_acl2.php\n";
         exit;
     }
     $u = $db->getRow("SELECT * FROM `acl_role_resource_permissions` WHERE perm_id = 'not-owned-farms'");
     if (!$u) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130810.php\n";
         exit;
     }
     $u = $db->getRow("SHOW INDEXES FROM `farms` WHERE `key_name` = 'idx_created_by_id'");
     if (!$u) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130820.php\n";
         exit;
     }
     $u = $db->GetRow("SHOW INDEXES FROM `account_team_envs` WHERE `key_name` = 'idx_unique'");
     if (!$u) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130903.php\n";
         exit;
     }
     $u = $db->GetAssoc('DESCRIBE acl_account_roles');
     if (empty($u['is_automatic'])) {
         print "Upgrade terminated. Please run php app/bin/upgrade_20130916.php\n";
         exit;
     }
     print "Integrity seems to be OK.\n";
     print "Deploying new ACL.\n";
     $i = $db->GetOne("SELECT COUNT(`account_role_id`) AS `cnt` FROM `acl_account_roles`");
     if ($i > 0) {
         printf("Upgrade terminated. There are %d account roles already initialized for this installation.\n", $i);
         exit;
     }
     $counter = 0;
     $acl = \Scalr::getContainer()->acl;
     $rs = $db->Execute("SELECT id FROM `clients` ORDER BY `status`");
     while ($rec = $rs->FetchRow()) {
         $account = \Scalr_Account::init();
         $account->loadById($rec['id']);
         //Creates default account roles
         $roles = $account->initializeAcl();
         /* @var $fullAccessRole \Scalr\Acl\Role\AccountRoleObject */
         $fullAccessRole = $roles['account_role'][$acl::ROLE_ID_FULL_ACCESS];
         //Assigns full access role as default to all defined teams for an each account.
         $db->Execute("\n                UPDATE `account_teams` SET account_role_id = ?\n                WHERE `account_id` = ?\n                AND account_role_id IS NULL\n            ", array($fullAccessRole->getRoleId(), $account->id));
         unset($account);
         unset($fullAccessRole);
         if ($counter % 500 === 0) {
             print '.';
         }
     }
     print "Done.\n";
     $t = round(microtime(true) - $time, 2);
     printf("Upgrade process took %0.2f seconds\n\n", $t);
 }
Example #26
0
{
    return SERVER_PLATFORMS::ECS . "." . constant('Scalr\\Modules\\Platforms\\Openstack\\OpenstackPlatformModule::' . $name);
}
if (count($err) == 0) {
    if ($_REQUEST['delete']) {
        $user = Scalr_Account_User::init()->loadByEmail($email);
        if (!$user) {
            throw new Exception("User Not Found");
        }
        $account = $user->getAccount();
        $account->delete();
        print json_encode(array('success' => true));
        exit;
    }
    if (!$_REQUEST['update']) {
        $account = Scalr_Account::init();
        $account->name = $name;
        $account->status = Scalr_Account::STATUS_ACTIVE;
        $account->save();
        $env = $account->createEnvironment("Environment 1");
        $envId = $env->id;
        $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER);
        $user->fullname = $name;
        $user->save();
        $clientSettings[CLIENT_SETTINGS::RSS_LOGIN] = $email;
        $clientSettings[CLIENT_SETTINGS::RSS_PASSWORD] = $crypto->sault(10);
        foreach ($clientSettings as $k => $v) {
            $account->setSetting($k, $v);
        }
        try {
            $db->Execute("INSERT INTO default_records SELECT null, '{$account->id}', type, ttl, priority, value, name FROM default_records WHERE clientid='0'");
Example #27
0
 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);
                             if (!$port) $port = 22;
                     
                             try {
                                 $ssh2Client->connect($info['remoteIp'], $port);
                     
                                 foreach ($DBServer->GetCloudUserData() as $k=>$v)
                                     $u_data .= "{$k}={$v};";
                     
                                 $u_data = trim($u_data, ";");
                                 $ssh2Client->sendFile('/etc/scalr/private.d/.user-data', $u_data, "w+", false);
                     
                                 $DBServer->SetProperty(NIMBULA_SERVER_PROPERTIES::USER_DATA_INJECTED, 1);
                             }
                             catch(Exception $e) {
                                 Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBFarm->ID, $e->getMessage()));
                             }
                         }
                     }
                     */
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         if ($DBServer->status == SERVER_STATUS::PENDING && $DBFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
                             if ($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS) != 'outbound-only') {
                                 $ipAddress = Modules_Platforms_Ec2_Helpers_Eip::setEipForServer($DBServer);
                                 if ($ipAddress) {
                                     $DBServer->remoteIp = $ipAddress;
                                     $DBServer->Save();
                                 }
                             }
                         }
                     }
                     if ($DBServer->isOpenstack()) {
                         $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_OPENSTACK_IP_POOL);
                         if (!$DBServer->remoteIp && ($DBServer->status == SERVER_STATUS::PENDING || $DBServer->status == SERVER_STATUS::INIT) && $ipPool) {
                             $osClient = $DBServer->GetEnvironmentObject()->openstack($DBServer->platform, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
                             if ($osClient->hasService('network')) {
                                 $platform = PlatformFactory::NewPlatform($DBServer->platform);
                                 $serverIps = $platform->GetServerIPAddresses($DBServer);
                                 /********* USE Quantum (Neuron) NETWORK *******/
                                 $ips = $osClient->network->floatingIps->list();
                                 //Check free existing IP
                                 $ipAssigned = false;
                                 $ipAddress = false;
                                 $ipId = false;
                                 $ipInfo = false;
                                 foreach ($ips as $ip) {
                                     if ($ip->fixed_ip_address == $serverIps['localIp'] && $ip->port_id) {
                                         $ipAddress = $ip->floating_ip_address;
                                         $ipId = $ip->id;
                                         $ipAssigned = true;
                                         $ipInfo = $ip;
                                         break;
                                     }
                                     /*
                                     if (!$ip->fixed_ip_address && !$ipAddress) {
                                         $ipAddress = $ip->floating_ip_address;
                                         $ipId = $ip->id;
                                         $ipInfo = $ip;
                                     }
                                     */
                                 }
                                 if ($ipInfo) {
                                     Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Found free floating IP: {$ipAddress} for use (" . json_encode($ipInfo) . ")"));
                                 }
                                 if (!$ipAssigned) {
                                     // Get instance port
                                     $ports = $osClient->network->ports->list();
                                     foreach ($ports as $port) {
                                         if ($port->device_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                                             $serverNetworkPort = $port->id;
                                             break;
                                         }
                                     }
                                     if (!$serverNetworkPort) {
                                         Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId, "Unable to identify network port of instance"));
                                     } else {
                                         if (!$ipAddress) {
                                             $publicNetworkId = $ipPool;
                                             /*
                                             $networks = $osClient->network->listNetworks();
                                             foreach ($networks as $network) {
                                                 if ($network->{"router:external"} == true) {
                                                     $publicNetworkId = $network->id;
                                                 }
                                             }
                                             
                                             if (!$publicNetworkId) {
                                                 Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId,
                                                                                                     "Unable to identify public network to allocate"
                                                                                                 ));
                                             } else {
                                             */
                                             $ip = $osClient->network->floatingIps->create($publicNetworkId, $serverNetworkPort);
                                             $ipAddress = $ip->floating_ip_address;
                                             $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->floating_ip_address, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                             Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Allocated new IP {$ipAddress} for port: {$serverNetworkPort}"));
                                             //}
                                         } else {
                                             /*
                                             Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId,
                                               "Updating IP {$ipAddress} ({$ipId}) with port: {$serverNetworkPort}"
                                             ));
                                             $osClient->network->floatingIps->update($ipId, $serverNetworkPort);
                                             */
                                         }
                                     }
                                 } else {
                                     Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "IP: {$ipAddress} already assigned"));
                                 }
                             } else {
                                 /********* USE NOVA NETWORK *******/
                                 //Check free existing IP
                                 $ipAssigned = false;
                                 $ipAddress = false;
                                 $ips = $osClient->servers->floatingIps->list($ipPool);
                                 foreach ($ips as $ip) {
                                     //if (!$ip->instance_id) {
                                     //	$ipAddress = $ip->ip;
                                     //}
                                     if ($ip->instance_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                                         $ipAddress = $ip->ip;
                                         $ipAssigned = true;
                                     }
                                 }
                                 //If no free IP allocate new from pool
                                 if (!$ipAddress) {
                                     $ip = $osClient->servers->floatingIps->create($ipPool);
                                     $ipAddress = $ip->ip;
                                     $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->ip, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                 }
                                 if (!$ipAssigned) {
                                     //Associate floating IP with Instance
                                     $osClient->servers->addFloatingIp($DBServer->GetCloudServerID(), $ipAddress);
                                 }
                             }
                             if ($ipAddress) {
                                 $DBServer->remoteIp = $ipAddress;
                                 $DBServer->Save();
                                 $DBServer->SetProperty(SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, null);
                             }
                         }
                     }
                     if ($DBServer->isCloudstack()) {
                         if ($DBServer->status == SERVER_STATUS::PENDING) {
                             $jobId = $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID);
                             try {
                                 $platform = PlatformFactory::NewPlatform($DBServer->platform);
                                 $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $DBServer->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $DBServer->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $DBServer->GetEnvironmentObject()), $DBServer->platform);
                                 $res = $cs->queryAsyncJobResult($jobId);
                                 if ($res->jobresult->jobstatus == 1) {
                                     $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::TMP_PASSWORD, $res->jobresult->virtualmachine->password);
                                     $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_NAME, $res->jobresult->virtualmachine->name);
                                 }
                                 //TODO: handle failed job: $res->jobresult->jobstatus == 2
                             } catch (Exception $e) {
                                 if ($DBServer->farmId) {
                                     Logger::getLogger("CloudStack")->error(new FarmLogMessage($DBServer->farmId, $e->getMessage()));
                                 }
                             }
                         }
                     }
                     try {
                         $dtadded = strtotime($DBServer->dateAdded);
                         $DBFarmRole = $DBServer->GetFarmRoleObject();
                         $launch_timeout = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) > 0 ? $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) : 900;
                     } catch (Exception $e) {
                         if (stristr($e->getMessage(), "not found")) {
                             $DBServer->terminate('FARM_ROLE_NOT_FOUND');
                         }
                     }
                     $scripting_event = false;
                     if ($DBServer->status == SERVER_STATUS::PENDING) {
                         $event = "hostInit";
                         $scripting_event = EVENT_TYPE::HOST_INIT;
                     } elseif ($DBServer->status == SERVER_STATUS::INIT) {
                         $event = "hostUp";
                         $scripting_event = EVENT_TYPE::HOST_UP;
                     }
                     if ($scripting_event && $dtadded) {
                         $scripting_timeout = (int) $this->db->GetOne("\n                                SELECT sum(timeout)\n                                FROM farm_role_scripts\n                                WHERE event_name=? AND\n                                farm_roleid=? AND issync='1'\n                            ", array($scripting_event, $DBServer->farmRoleId));
                         if ($scripting_timeout) {
                             $launch_timeout = $launch_timeout + $scripting_timeout;
                         }
                         if ($dtadded + $launch_timeout < time() && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //Add entry to farm log
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' did not send '%s' event in %s seconds after launch (Try increasing timeouts in role settings). Considering it broken. Terminating instance.", $DBServer->serverId, $event, $launch_timeout)));
                             try {
                                 $DBServer->terminate(array('SERVER_DID_NOT_SEND_EVENT', $event, $launch_timeout), false);
                             } catch (Exception $err) {
                                 $this->logger->fatal($err->getMessage());
                             }
                         } elseif ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //DO NOT TERMINATE MONGODB INSTANCES BY TIMEOUT! IT'S NOT SAFE
                             //THINK ABOUT WORKAROUND
                         }
                     }
                     // Is IP address changed?
                     if (!$DBServer->IsRebooting()) {
                         $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                         if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("RemoteIP: %s (%s), LocalIp: %s (%s) (Poller).", $DBServer->remoteIp, $ipaddresses['remoteIp'], $DBServer->localIp, $ipaddresses['localIp'])));
                             Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                         }
                         //TODO: Check health:
                     }
                 }
             } elseif ($DBServer->status == SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->isRunning()) {
                 // Is IP address changed?
                 if (!$DBServer->IsRebooting()) {
                     $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                         Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                     }
                     if ($payAsYouGoTime) {
                         $initTime = $DBServer->GetProperty(SERVER_PROPERTIES::INITIALIZED_TIME);
                         if ($initTime < $payAsYouGoTime) {
                             $initTime = $payAsYouGoTime;
                         }
                         $runningHours = ceil((time() - $initTime) / 3600);
                         $scuUsed = $runningHours * Scalr_Billing::getSCUByInstanceType($DBServer->GetFlavor());
                         $this->db->Execute("UPDATE servers_history SET scu_used = ?, scu_updated = 0 WHERE server_id = ?", array($scuUsed, $DBServer->serverId));
                     }
                     //Update GCE ServerID
                     if ($DBServer->platform == SERVER_PLATFORMS::GCE) {
                         if ($DBServer->GetProperty(GCE_SERVER_PROPERTIES::SERVER_ID) == $DBServer->serverId) {
                             $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerExtendedInformation($DBServer);
                             $DBServer->SetProperty(GCE_SERVER_PROPERTIES::SERVER_ID, $info['Cloud Server ID']);
                         }
                     }
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $env = Scalr_Environment::init()->loadById($DBServer->envId);
                         $ec2 = $env->aws($DBServer->GetCloudLocation())->ec2;
                         //TODO:
                         $isEnabled = $ec2->instance->describeAttribute($DBServer->GetCloudServerID(), InstanceAttributeType::disableApiTermination());
                         $DBServer->SetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED, $isEnabled);
                     }
                 } else {
                     //TODO: Check reboot timeout
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "not found")) {
                 print $e->getTraceAsString() . "\n";
             } else {
                 print "[1][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             }
         }
     }
 }