Beispiel #1
0
 public function xInitiateImportAction()
 {
     $this->request->defineParams(array('platform', 'cloudLocation', 'cloudServerId', 'roleName'));
     $validator = new Scalr_Validator();
     if ($validator->validateNotEmpty($this->getParam('roleName')) !== true) {
         $err['roleName'] = 'Role name cannot be empty';
     }
     if (strlen($this->getParam('roleName')) < 3) {
         $err['roleName'] = _("Role name should be greater than 3 chars");
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         $err['roleName'] = _("Role name is incorrect");
     }
     if ($this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?) LIMIT 1", array($this->getParam('roleName'), $this->getEnvironmentId()))) {
         $err['roleName'] = 'Selected role name is already used. Please select another one.';
     }
     $cryptoKey = Scalr::GenerateRandomKey(40);
     $creInfo = new ServerCreateInfo($this->getParam('platform'), null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME => $this->getParam('roleName'), SERVER_PROPERTIES::SZR_KEY => $cryptoKey, SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.14.0", SERVER_PROPERTIES::SZR_IMPORTING_VERSION => 2, SERVER_PROPERTIES::SZR_IMPORTING_STEP => 1, SERVER_PROPERTIES::LAUNCHED_BY_ID => $this->user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $this->user->getEmail()));
     $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
     if ($this->getParam('platform') == SERVER_PLATFORMS::EC2) {
         $client = $this->environment->aws($this->getParam('cloudLocation'))->ec2;
         $r = $client->instance->describe($this->getParam('cloudServerId'));
         $instance = $r->get(0)->instancesSet->get(0);
         $creInfo->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $this->getParam('cloudLocation'), EC2_SERVER_PROPERTIES::INSTANCE_ID => $this->getParam('cloudServerId'), EC2_SERVER_PROPERTIES::AMIID => $instance->imageId, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
     } else {
         if ($this->getParam('platform') == SERVER_PLATFORMS::GCE) {
             $gce = $platform->getClient($this->environment, $this->getParam('cloudLocation'));
             $result = $gce->instances->get($this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::PROJECT_ID), $this->getParam('cloudLocation'), $this->getParam('cloudServerId'));
             $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_ID => $result->id, GCE_SERVER_PROPERTIES::SERVER_NAME => $this->getParam('cloudServerId'), GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation')));
         } else {
             if (PlatformFactory::isOpenstack($this->getParam('platform'))) {
                 $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation'), OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $this->getParam('cloudServerId')));
             } else {
                 if (PlatformFactory::isCloudstack($this->getParam('platform'))) {
                     $creInfo->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation'), CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $this->getParam('cloudServerId')));
                 }
             }
         }
     }
     $dbServer = DBServer::Create($creInfo, true);
     $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
     $ips = $platform->GetServerIPAddresses($dbServer);
     $dbServer->localIp = $ips['localIp'];
     $dbServer->remoteIp = $ips['remoteIp'];
     $dbServer->Save();
     $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'serverId' => $dbServer->serverId));
 }
Beispiel #2
0
 /**
  *
  * @param ServerCreateInfo $serverCreateInfo
  * @param bool $isImport
  * @return DBServer
  */
 public static function Create(ServerCreateInfo $creInfo, $isImport = false, $setPendingStatus = false)
 {
     $db = \Scalr::getDb();
     $startWithLetter = in_array($creInfo->platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::GCE));
     if ($isImport) {
         $startWithLetter = true;
     }
     $server_id = Scalr::GenerateUID(false, $startWithLetter);
     $status = !$isImport ? SERVER_STATUS::PENDING_LAUNCH : SERVER_STATUS::IMPORTING;
     if ($setPendingStatus) {
         $status = SERVER_STATUS::PENDING;
     }
     // Assigns Farm index to the server
     if (!$isImport) {
         // This query select the least lower vacant Farm index from the available.
         // If there are no available indexes the query returns NULL so we need cast result to integer
         // to make sure it will use Farm index equal to 1 in this case.
         // We ingore terminated and pending terminating instances to release their indexes.
         $farmIndex = 1 + intval($db->GetOne("\n                SELECT s.farm_index\n                FROM servers s\n                WHERE s.farm_id = ? AND s.status NOT IN (?, ?)\n                AND NOT EXISTS (SELECT 1 FROM servers WHERE farm_id = s.farm_id AND farm_index = s.farm_index + 1 AND status NOT IN (?, ?))\n                ORDER BY s.farm_index\n                LIMIT 1\n            ", [$creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE]));
     } else {
         // Default Farm index value is considered to equal 1
         $farmIndex = 1;
     }
     // IF no index defined
     if (!$creInfo->index && !$isImport) {
         $indexes = $db->GetAll("SELECT `index` FROM servers WHERE farm_roleid = ? AND status NOT IN (?, ?)", [$creInfo->dbFarmRole->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE]);
         $usedIndexes = [];
         if (!empty($indexes)) {
             foreach ($indexes as $index) {
                 $usedIndexes[$index['index']] = true;
             }
         }
         for ($i = 1;; $i++) {
             if (!isset($usedIndexes[$i])) {
                 $creInfo->index = $i;
                 break;
             }
         }
     } elseif ($isImport) {
         $creInfo->index = 0;
     }
     $client_id = $creInfo->clientId ? $creInfo->clientId : $creInfo->dbFarmRole->GetFarmObject()->ClientID;
     $instanceTypeName = null;
     $instanceTypeId = $creInfo->dbFarmRole ? $creInfo->dbFarmRole->getInstanceType() : null;
     if (in_array($creInfo->platform, [SERVER_PLATFORMS::EC2, SERVER_PLATFORMS::GCE])) {
         $instanceTypeName = $instanceTypeId;
     }
     $db->Execute("\n            INSERT INTO servers\n            SET `server_id` = ?,\n                `farm_id` = ?,\n                `env_id` = ?,\n                `farm_roleid` = ?,\n                `client_id` = ?,\n                `platform` = ?,\n                `status` = ?,\n                `remote_ip` = ?,\n                `local_ip` = ?,\n                `dtadded` = NOW(),\n                `index` = ?,\n                `farm_index` = ?,\n                `cloud_location` = ?,\n                `type` = ?,\n                `instance_type_name`= ?\n        ", [$server_id, $creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, $creInfo->envId, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->ID : 0, $client_id, $creInfo->platform, $status, $creInfo->remoteIp, $creInfo->localIp, $creInfo->index, $farmIndex, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->CloudLocation : null, $instanceTypeId, $instanceTypeName]);
     $DBServer = DBServer::LoadByID($server_id);
     $DBServer->SetProperties($creInfo->GetProperties());
     $DBServer->setOsType($DBServer->osType);
     try {
         if ($DBServer->farmRoleId) {
             $db->Execute("\n                    INSERT INTO servers_launch_timelog\n                    SET `server_id` = ?,\n                        `os_family` = ?,\n                        `os_version` = ?,\n                        `cloud` = ?,\n                        `cloud_location` = ?,\n                        `server_type` = ?,\n                        `behaviors` = ?,\n                        `ts_created` = ?\n                ", [$server_id, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->family, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->version, $DBServer->platform, $DBServer->cloudLocation, $DBServer->getType(), implode(",", $DBServer->GetFarmRoleObject()->GetRoleObject()->getBehaviors()), time()]);
         }
     } catch (Exception $e) {
     }
     return $DBServer;
 }
Beispiel #3
0
 /**
  * @param   string      $platform
  * @param   string      $cloudLocation
  * @param   string      $cloudServerId
  * @param   string      $name
  * @param   bool        $createImage
  * @throws  Exception
  */
 public function xInitiateImportAction($platform, $cloudLocation, $cloudServerId, $name, $createImage = false)
 {
     if (!Role::isValidName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
     }
     if (!$createImage && Role::isNameUsed($name, $this->user->getAccountId(), $this->getEnvironmentId())) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $cryptoKey = Scalr::GenerateRandomKey(40);
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME => $name, SERVER_PROPERTIES::SZR_IMPORTING_OBJECT => $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE, SERVER_PROPERTIES::SZR_KEY => $cryptoKey, SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.14.0", SERVER_PROPERTIES::SZR_IMPORTING_VERSION => 2, SERVER_PROPERTIES::SZR_IMPORTING_STEP => 1, SERVER_PROPERTIES::LAUNCHED_BY_ID => $this->user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $this->user->getEmail()));
     $platformObj = PlatformFactory::NewPlatform($platform);
     $availZone = null;
     $osType = '';
     if ($platform == SERVER_PLATFORMS::EC2) {
         $client = $this->environment->aws($cloudLocation)->ec2;
         $r = $client->instance->describe($cloudServerId);
         $instance = $r->get(0)->instancesSet->get(0);
         $availZone = $instance->placement->availabilityZone;
         $osType = $instance->platform == 'windows' ? 'windows' : 'linux';
         $creInfo->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $cloudLocation, EC2_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EC2_SERVER_PROPERTIES::AMIID => $instance->imageId, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
     } else {
         if ($platform == SERVER_PLATFORMS::GCE) {
             $gce = $platformObj->getClient($this->environment);
             $result = $gce->instances->get($this->environment->keychain(SERVER_PLATFORMS::GCE)->properties[CloudCredentialsProperty::GCE_PROJECT_ID], $cloudLocation, $cloudServerId);
             $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_NAME => $cloudServerId, GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation));
         } else {
             if ($platform == SERVER_PLATFORMS::AZURE) {
                 //$this->getEnvironment()->azure()->compute->virtualMachine->getInstanceViewInfo()
                 // $r->properties->osProfile->linuxConfiguration != NULL
             } else {
                 if (PlatformFactory::isOpenstack($platform)) {
                     $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                 } else {
                     if (PlatformFactory::isCloudstack($platform)) {
                         $creInfo->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                     }
                 }
             }
         }
     }
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->osType = $osType;
     $ips = $platformObj->GetServerIPAddresses($dbServer);
     $dbServer->localIp = $ips['localIp'];
     $dbServer->remoteIp = $ips['remoteIp'];
     $dbServer->cloudLocation = $cloudLocation;
     if ($platform == SERVER_PLATFORMS::GCE) {
         $dbServer->cloudLocationZone = $cloudLocation;
     } else {
         $dbServer->cloudLocationZone = $availZone;
     }
     $dbServer->Save();
     $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'installCommand' => $this->getInstallCmd($dbServer), 'osType' => $dbServer->osType, 'serverId' => $dbServer->serverId));
 }
Beispiel #4
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;
 }
Beispiel #5
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;
 }
Beispiel #6
0
 /**
  *
  * @param ServerCreateInfo $serverCreateInfo
  * @param bool $isImport
  * @return DBServer
  */
 public static function Create(ServerCreateInfo $creInfo, $isImport = false, $setPendingStatus = false)
 {
     $db = \Scalr::getDb();
     $startWithLetter = in_array($creInfo->platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::GCE));
     if ($isImport) {
         $startWithLetter = true;
     }
     $server_id = Scalr::GenerateUID(false, $startWithLetter);
     $status = !$isImport ? SERVER_STATUS::PENDING_LAUNCH : SERVER_STATUS::IMPORTING;
     if ($setPendingStatus) {
         $status = SERVER_STATUS::PENDING;
     }
     // IF no index defined
     if (!$creInfo->index && !$isImport) {
         $indexes = $db->GetAll("\n                SELECT `index` FROM servers\n                WHERE farm_roleid=?\n                AND status NOT IN (?,?,?)\n            ", array($creInfo->dbFarmRole->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TROUBLESHOOTING));
         $used_indexes = array();
         if (count($indexes) > 0) {
             foreach ($indexes as $index) {
                 $used_indexes[$index['index']] = true;
             }
         }
         for ($i = 1;; $i++) {
             if (!$used_indexes[$i]) {
                 $creInfo->index = $i;
                 break;
             }
         }
     } elseif ($isImport) {
         $creInfo->index = 0;
     }
     $client_id = $creInfo->clientId ? $creInfo->clientId : $creInfo->dbFarmRole->GetFarmObject()->ClientID;
     $db->Execute("\n            INSERT INTO servers SET\n            `server_id`     = ?,\n            `farm_id`       = ?,\n            `env_id`        = ?,\n            `farm_roleid`   = ?,\n            `client_id`     = ?,\n            `platform`      = ?,\n            `status`        = ?,\n            `remote_ip`     = ?,\n            `local_ip`      = ?,\n            `dtadded`       = NOW(),\n            `index`         = ?\n        ", array($server_id, $creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, $creInfo->envId, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->ID : 0, $client_id, $creInfo->platform, $status, $creInfo->remoteIp, $creInfo->localIp, $creInfo->index));
     $DBServer = DBServer::LoadByID($server_id);
     $DBServer->SetProperties($creInfo->GetProperties());
     $DBServer->setOsType($DBServer->osType);
     try {
         if ($DBServer->farmRoleId) {
             $db->Execute("INSERT INTO servers_launch_timelog SET\n                    `server_id`     = ?,\n                    `os_family`     = ?,\n                    `os_version`    = ?,\n                    `cloud`         = ?,\n                    `cloud_location`    = ?,\n                    `server_type`       = ?,\n                    `behaviors`     = ?,\n                    `ts_created`    = ?\n                ", array($server_id, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->family, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->version, $DBServer->platform, $DBServer->cloudLocation, $DBServer->GetFlavor(), implode(",", $DBServer->GetFarmRoleObject()->GetRoleObject()->getBehaviors()), time()));
         }
     } catch (Exception $e) {
     }
     return $DBServer;
 }
Beispiel #7
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;
 }
Beispiel #8
0
 public function xBuildAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     $this->request->defineParams(array('platform' => array('type' => 'string'), 'architecture' => array('type' => 'string'), 'behaviors' => array('type' => 'json'), 'roleName' => array('type' => 'string'), 'imageId' => array('type' => 'string'), 'location' => array('type' => 'string'), 'advanced' => array('type' => 'json'), 'chef' => array('type' => 'json')));
     if (strlen($this->getParam('roleName')) < 3) {
         throw new Exception(_("Role name should be greater than 3 chars"));
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         throw new Exception(_("Role name is incorrect"));
     }
     $chkRoleId = $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?) LIMIT 1", array($this->getParam('roleName'), $this->getEnvironmentId()));
     if ($chkRoleId) {
         if (!$this->db->GetOne("SELECT id FROM roles_queue WHERE role_id=? LIMIT 1", array($chkRoleId))) {
             throw new Exception('Selected role name is already used. Please select another one.');
         }
     }
     $imageId = $this->getParam('imageId');
     $advanced = $this->getParam('advanced');
     $chef = $this->getParam('chef');
     $behaviours = implode(",", array_values($this->getParam('behaviors')));
     // Create server
     $creInfo = new ServerCreateInfo($this->getParam('platform'), null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_IMPORTING_IMAGE_ID => $imageId, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.13.0", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => "mysql", SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $advanced['scalrbranch'], SERVER_PROPERTIES::ARCHITECTURE => $this->getParam('architecture'), SERVER_PROPERTIES::SZR_IMPORTING_LEAVE_ON_FAIL => $advanced['dontterminatefailed'] == 'on' ? 1 : 0, SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID => $chef['chef.server'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT => $chef['chef.environment'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME => $chef['chef.role']));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $this->getParam('cloud_location');
     $launchOptions->architecture = $this->getParam('architecture');
     $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
     switch ($this->getParam('platform')) {
         case SERVER_PLATFORMS::ECS:
             $launchOptions->serverType = 10;
             break;
         case SERVER_PLATFORMS::IDCF:
             $launchOptions->serverType = 24;
             break;
         case SERVER_PLATFORMS::RACKSPACE:
             if ($this->getParam('osfamily') == 'ubuntu') {
                 $launchOptions->serverType = 1;
             } else {
                 $launchOptions->serverType = 3;
             }
             break;
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_UK:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($this->getParam('hvm') == 1) {
                 $launchOptions->serverType = 'm3.xlarge';
                 $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
             } else {
                 if ($this->getParam('osfamily') == 'oel') {
                     $launchOptions->serverType = 'm1.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($this->getParam('osfamily') == 'rhel') {
                     $launchOptions->serverType = 'm1.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($this->getParam('osfamily') == 'scientific') {
                     $launchOptions->serverType = 'm1.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $launchOptions->serverType = 'm1.small';
                 }
             }
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
         case SERVER_PLATFORMS::GCE:
             $launchOptions->serverType = 'n1-standard-1';
             $locations = array_keys($platform->getLocations());
             $launchOptions->cloudLocation = $locations[0];
             $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::GCE_STORAGE;
             break;
     }
     if ($advanced['servertype']) {
         $launchOptions->serverType = $advanced['servertype'];
     }
     if ($advanced['availzone']) {
         $launchOptions->availZone = $advanced['availzone'];
     }
     if ($advanced['region']) {
         $launchOptions->cloudLocation = $advanced['region'];
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     if ($bundleType) {
         $bundleTask->bundleType = $bundleType;
     }
     $bundleTask->createdById = $this->user->id;
     $bundleTask->createdByEmail = $this->user->getEmail();
     $bundleTask->osFamily = $this->getParam('osfamily');
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         $platform->LaunchServer($dbServer, $launchOptions);
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('serverId' => $dbServer->serverId, 'bundleTaskId' => $bundleTask->id));
 }
Beispiel #9
0
 public function xBuildAction()
 {
     $this->request->defineParams(array('platform' => array('type' => 'string'), 'architecture' => array('type' => 'string'), 'behaviors' => array('type' => 'json'), 'roleName' => array('type' => 'string'), 'imageId' => array('type' => 'string'), 'location' => array('type' => 'string'), 'mysqlServerType' => array('type' => 'string'), 'devScalarizrBranch' => array('type' => 'string')));
     if (strlen($this->getParam('roleName')) < 3) {
         throw new Exception(_("Role name should be greater than 3 chars"));
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         throw new Exception(_("Role name is incorrect"));
     }
     $chkRoleId = $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?)", array($this->getParam('roleName'), $this->getEnvironmentId()));
     if ($chkRoleId) {
         if (!$this->db->GetOne("SELECT id FROM roles_queue WHERE role_id=?", array($chkRoleId))) {
             throw new Exception('Selected role name is already used. Please select another one.');
         }
     }
     $imageId = $this->getParam('imageId');
     if ($this->getParam('platform') == SERVER_PLATFORMS::RACKSPACE) {
         $imageId = str_replace('lon', '', $imageId);
     }
     $behaviours = implode(",", array_values($this->getParam('behaviors')));
     // Create server
     $creInfo = new ServerCreateInfo($this->getParam('platform'), null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.6", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => $this->getParam('mysqlServerType'), SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $this->getParam('devScalarizrBranch')));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $this->getParam('location');
     $launchOptions->architecture = $this->getParam('architecture');
     switch ($this->getParam('platform')) {
         case SERVER_PLATFORMS::RACKSPACE:
             $launchOptions->serverType = 1;
             break;
         case SERVER_PLATFORMS::EC2:
             $launchOptions->serverType = 'm1.small';
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
     }
     if ($this->getParam('serverType')) {
         $launchOptions->serverType = $this->getParam('serverType');
     }
     if ($this->getParam('availZone')) {
         $launchOptions->availZone = $this->getParam('availZone');
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         PlatformFactory::NewPlatform($this->getParam('platform'))->LaunchServer($dbServer, $launchOptions);
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('bundleTaskId' => $bundleTask->id));
 }
Beispiel #10
0
 public function xImportStartAction()
 {
     $validator = new Validator();
     if ($validator->IsDomain($this->getParam('remoteIp'))) {
         $remoteIp = @gethostbyname($this->getParam('remoteIp'));
     } else {
         $remoteIp = $this->getParam('remoteIp');
     }
     if (!$validator->IsIPAddress($remoteIp, _("Server IP address"))) {
         $err['remoteIp'] = 'Server IP address is incorrect';
     }
     if (!$validator->IsNotEmpty($this->getParam('roleName'))) {
         $err['roleName'] = 'Role name cannot be empty';
     }
     if (strlen($this->getParam('roleName')) < 3) {
         $err['roleName'] = _("Role name should be greater than 3 chars");
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         $err['roleName'] = _("Role name is incorrect");
     }
     if ($this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?)", array($this->getParam('roleName'), $this->getEnvironmentId()))) {
         $err['roleName'] = 'Selected role name is already used. Please select another one.';
     }
     if ($this->getParam('add2farm')) {
     }
     // Find server in the database
     $existingServer = $this->db->GetRow("SELECT * FROM servers WHERE remote_ip = ?", array($remoteIp));
     if ($existingServer["client_id"] == $this->user->getAccountId()) {
         $err['remoteIp'] = sprintf(_("Server %s is already in Scalr with a server_id: %s"), $remoteIp, $existingServer["server_id"]);
     } else {
         if ($existingServer) {
             $err['remoteIp'] = sprintf(_("Server with selected IP address cannot be imported"));
         }
     }
     if (count($err) == 0) {
         $cryptoKey = Scalr::GenerateRandomKey(40);
         $creInfo = new ServerCreateInfo($this->getParam('platform'), null, 0, 0);
         $creInfo->clientId = $this->user->getAccountId();
         $creInfo->envId = $this->getEnvironmentId();
         $creInfo->farmId = (int) $this->getParam('farmId');
         $creInfo->remoteIp = $remoteIp;
         $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME => $this->getParam('roleName'), SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $this->getParam('behavior'), SERVER_PROPERTIES::SZR_KEY => $cryptoKey, SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.7-1", SERVER_PROPERTIES::SZR_IMPORTING_OS_FAMILY => $this->getParam('os')));
         if ($this->getParam('platform') == SERVER_PLATFORMS::EUCALYPTUS) {
             $creInfo->SetProperties(array(EUCA_SERVER_PROPERTIES::REGION => $this->getParam('cloudLocation')));
         }
         if ($this->getParam('platform') == SERVER_PLATFORMS::RACKSPACE) {
             $creInfo->SetProperties(array(RACKSPACE_SERVER_PROPERTIES::DATACENTER => $this->getParam('cloudLocation')));
         }
         if ($this->getParam('platform') == SERVER_PLATFORMS::OPENSTACK) {
             $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation')));
         }
         if ($this->getParam('platform') == SERVER_PLATFORMS::NIMBULA) {
             $creInfo->SetProperties(array(NIMBULA_SERVER_PROPERTIES::CLOUD_LOCATION => 'nimbula-default'));
         }
         $dbServer = DBServer::Create($creInfo, true);
         $this->response->data(array('serverId' => $dbServer->serverId));
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => $err));
     }
 }
Beispiel #11
0
 /**
  * @param   string      $platform
  * @param   string      $architecture
  * @param   JsonData    $behaviors
  * @param   string      $name
  * @param   bool        $createImage
  * @param   string      $imageId
  * @param   string      $cloudLocation
  * @param   string      $osId
  * @param   integer     $hvm
  * @param   JsonData    $advanced
  * @param   JsonData    $chef
  * @throws  Exception
  */
 public function xBuildAction($platform, $architecture, JsonData $behaviors, $name = '', $createImage = false, $imageId, $cloudLocation, $osId, $hvm = 0, JsonData $advanced, JsonData $chef)
 {
     $this->request->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_BUILD);
     if (!Role::isValidName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
     }
     if (!$createImage && Role::isNameUsed($name, $this->user->getAccountId(), $this->getEnvironmentId())) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $behaviours = implode(",", array_values($behaviors->getArrayCopy()));
     $os = Os::findPk($osId);
     if (!$os) {
         throw new Exception('Operating system not found.');
     }
     // Create server
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_IMPORTING_IMAGE_ID => $imageId, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.13.0", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => "mysql", SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $advanced['scalrbranch'], SERVER_PROPERTIES::ARCHITECTURE => $architecture, SERVER_PROPERTIES::SZR_IMPORTING_LEAVE_ON_FAIL => $advanced['dontterminatefailed'] == 'on' ? 1 : 0, SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID => $chef['chef.server'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT => $chef['chef.environment'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME => $chef['chef.role']));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->imageId = $imageId;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $cloudLocation;
     $launchOptions->architecture = $architecture;
     $platformObj = PlatformFactory::NewPlatform($platform);
     switch ($platform) {
         case SERVER_PLATFORMS::IDCF:
             $launchOptions->serverType = 24;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_UK:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($cloudLocation == Aws::REGION_AP_NORTHEAST_2) {
                 if ($hvm == 1 || $this->isHvmBundleTypeOs($os)) {
                     $launchOptions->serverType = 't2.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 }
             } else {
                 if ($hvm == 1) {
                     $launchOptions->serverType = "m3.xlarge";
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $launchOptions->serverType = "m3.large";
                     if ($this->isHvmBundleTypeOs($os)) {
                         $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                     }
                     if ($os->family == 'oel' && $os->generation == '5') {
                         $launchOptions->serverType = "m1.large";
                     }
                 }
             }
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
         case SERVER_PLATFORMS::GCE:
             $launchOptions->serverType = 'n1-standard-1';
             $location = null;
             $locations = array_keys($platformObj->getLocations($this->environment));
             while (count($locations) != 0) {
                 $location = array_shift($locations);
                 if (strstr($location, "us-")) {
                     break;
                 }
             }
             $launchOptions->cloudLocation = $locations[0];
             $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::GCE_STORAGE;
             break;
     }
     if ($advanced['servertype']) {
         $launchOptions->serverType = $advanced['servertype'];
     }
     if ($advanced['availzone']) {
         $launchOptions->availZone = $advanced['availzone'];
     }
     if ($advanced['region']) {
         $launchOptions->cloudLocation = $advanced['region'];
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $name, SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     if ($bundleType) {
         $bundleTask->bundleType = $bundleType;
     }
     $bundleTask->createdById = $this->user->id;
     $bundleTask->createdByEmail = $this->user->getEmail();
     $bundleTask->osFamily = $os->family;
     $bundleTask->object = $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE;
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         $platformObj->LaunchServer($dbServer, $launchOptions);
         $dbServer->Save();
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('serverId' => $dbServer->serverId, 'bundleTaskId' => $bundleTask->id));
 }
Beispiel #12
0
 /**
  *
  * @param ServerCreateInfo $serverCreateInfo
  * @param bool $isImport
  * @return DBServer
  */
 public static function Create(ServerCreateInfo $creInfo, $isImport = false, $setPendingStatus = false)
 {
     $db = \Scalr::getDb();
     $startWithLetter = in_array($creInfo->platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::UCLOUD, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::GCE));
     if ($isImport) {
         $startWithLetter = true;
     }
     $server_id = Scalr::GenerateUID(false, $startWithLetter);
     $status = !$isImport ? SERVER_STATUS::PENDING_LAUNCH : SERVER_STATUS::IMPORTING;
     if ($setPendingStatus) {
         $status = SERVER_STATUS::PENDING;
     }
     // IF no index defined
     if (!$creInfo->index && !$isImport) {
         $indexes = $db->GetAll("SELECT `index` FROM servers WHERE farm_roleid=? AND status NOT IN (?,?,?)", array($creInfo->dbFarmRole->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TROUBLESHOOTING));
         $used_indexes = array();
         if (count($indexes) > 0) {
             foreach ($indexes as $index) {
                 $used_indexes[$index['index']] = true;
             }
         }
         for ($i = 1;; $i++) {
             if (!$used_indexes[$i]) {
                 $creInfo->index = $i;
                 break;
             }
         }
     } elseif ($isImport) {
         $creInfo->index = 0;
     }
     $client_id = $creInfo->clientId ? $creInfo->clientId : $creInfo->dbFarmRole->GetFarmObject()->ClientID;
     $db->Execute("INSERT INTO servers SET\n            `server_id`\t\t= ?,\n            `farm_id`\t\t= ?,\n            `role_id`\t\t= ?,\n            `env_id`\t\t= ?,\n            `farm_roleid`\t= ?,\n            `client_id`\t\t= ?,\n            `platform`\t\t= ?,\n            `status`\t\t= ?,\n            `remote_ip`\t\t= ?,\n            `local_ip`\t\t= ?,\n            `dtadded`\t\t= NOW(),\n            `index`\t\t\t= ?\n        ", array($server_id, $creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, $creInfo->roleId, $creInfo->envId, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->ID : 0, $client_id, $creInfo->platform, $status, $creInfo->remoteIp, $creInfo->localIp, $creInfo->index));
     $DBServer = DBServer::LoadByID($server_id);
     $DBServer->SetProperties($creInfo->GetProperties());
     return $DBServer;
 }
Beispiel #13
0
 /**
  * @param   string      $platform
  * @param   string      $architecture
  * @param   JsonData    $behaviors
  * @param   string      $name
  * @param   bool        $createImage
  * @param   string      $imageId
  * @param   string      $cloudLocation
  * @param   string      $osId
  * @param   integer     $hvm
  * @param   JsonData    $advanced
  * @param   JsonData    $chef
  * @throws  Exception
  */
 public function xBuildAction($platform, $architecture, JsonData $behaviors, $name = '', $createImage = false, $imageId, $cloudLocation, $osId, $hvm = 0, JsonData $advanced, JsonData $chef)
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     if (!\Scalr\Model\Entity\Role::validateName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage && $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id IS NULL OR env_id = ?) LIMIT 1", array($name, $this->getEnvironmentId()))) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $behaviours = implode(",", array_values($behaviors->getArrayCopy()));
     $os = Os::findPk($osId);
     if (!$os) {
         throw new Exception('Operating system not found.');
     }
     // Create server
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_IMPORTING_IMAGE_ID => $imageId, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.13.0", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => "mysql", SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $advanced['scalrbranch'], SERVER_PROPERTIES::ARCHITECTURE => $architecture, SERVER_PROPERTIES::SZR_IMPORTING_LEAVE_ON_FAIL => $advanced['dontterminatefailed'] == 'on' ? 1 : 0, SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID => $chef['chef.server'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT => $chef['chef.environment'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME => $chef['chef.role']));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->imageId = $imageId;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $cloudLocation;
     $launchOptions->architecture = $architecture;
     $platformObj = PlatformFactory::NewPlatform($platform);
     switch ($platform) {
         case SERVER_PLATFORMS::ECS:
             $launchOptions->serverType = 10;
             if ($cloudLocation == 'all') {
                 $locations = array_keys($platformObj->getLocations($this->environment));
                 $launchOptions->cloudLocation = $locations[0];
             }
             //Network here:
             $osClient = $platformObj->getOsClient($this->environment, $launchOptions->cloudLocation);
             $networks = $osClient->network->listNetworks();
             $tenantId = $osClient->getConfig()->getAuthToken()->getTenantId();
             foreach ($networks as $network) {
                 if ($network->status == 'ACTIVE') {
                     if ($network->{"router:external"} != true) {
                         if ($tenantId == $network->tenant_id) {
                             $launchOptions->networks = array($network->id);
                             break;
                         }
                     }
                 }
             }
             break;
         case SERVER_PLATFORMS::IDCF:
             $launchOptions->serverType = 24;
             break;
         case SERVER_PLATFORMS::RACKSPACE:
             if ($os->family == 'ubuntu') {
                 $launchOptions->serverType = 1;
             } else {
                 $launchOptions->serverType = 3;
             }
             break;
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_UK:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($hvm == 1) {
                 $launchOptions->serverType = 'm3.xlarge';
                 $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
             } else {
                 if ($os->family == 'oel') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'rhel') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'scientific') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'debian' && $os->generation == '8') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'centos' && $os->generation == '7') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $launchOptions->serverType = 'm3.large';
                 }
             }
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
         case SERVER_PLATFORMS::GCE:
             $launchOptions->serverType = 'n1-standard-1';
             $location = null;
             $locations = array_keys($platformObj->getLocations($this->environment));
             while (count($locations) != 0) {
                 $location = array_shift($locations);
                 if (strstr($location, "us-")) {
                     break;
                 }
             }
             $launchOptions->cloudLocation = $locations[0];
             $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::GCE_STORAGE;
             break;
     }
     if ($advanced['servertype']) {
         $launchOptions->serverType = $advanced['servertype'];
     }
     if ($advanced['availzone']) {
         $launchOptions->availZone = $advanced['availzone'];
     }
     if ($advanced['region']) {
         $launchOptions->cloudLocation = $advanced['region'];
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $name, SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     if ($bundleType) {
         $bundleTask->bundleType = $bundleType;
     }
     $bundleTask->createdById = $this->user->id;
     $bundleTask->createdByEmail = $this->user->getEmail();
     $bundleTask->osFamily = $os->family;
     $bundleTask->object = $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE;
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         $platformObj->LaunchServer($dbServer, $launchOptions);
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('serverId' => $dbServer->serverId, 'bundleTaskId' => $bundleTask->id));
 }
Beispiel #14
0
 /**
  * @param   string      $platform
  * @param   string      $cloudLocation
  * @param   string      $cloudServerId
  * @param   string      $name
  * @param   bool        $createImage
  * @throws  Exception
  */
 public function xInitiateImportAction($platform, $cloudLocation, $cloudServerId, $name, $createImage = false)
 {
     if (!Role::validateName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage && $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id IS NULL OR env_id = ?) LIMIT 1", array($name, $this->getEnvironmentId()))) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $cryptoKey = Scalr::GenerateRandomKey(40);
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME => $name, SERVER_PROPERTIES::SZR_IMPORTING_OBJECT => $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE, SERVER_PROPERTIES::SZR_KEY => $cryptoKey, SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.14.0", SERVER_PROPERTIES::SZR_IMPORTING_VERSION => 2, SERVER_PROPERTIES::SZR_IMPORTING_STEP => 1, SERVER_PROPERTIES::LAUNCHED_BY_ID => $this->user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $this->user->getEmail()));
     $platformObj = PlatformFactory::NewPlatform($platform);
     if ($platform == SERVER_PLATFORMS::EC2) {
         $client = $this->environment->aws($cloudLocation)->ec2;
         $r = $client->instance->describe($cloudServerId);
         $instance = $r->get(0)->instancesSet->get(0);
         $creInfo->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $cloudLocation, EC2_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EC2_SERVER_PROPERTIES::AMIID => $instance->imageId, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
     } else {
         if ($platform == SERVER_PLATFORMS::EUCALYPTUS) {
             $client = $this->environment->eucalyptus($cloudLocation)->ec2;
             $r = $client->instance->describe($cloudServerId);
             $instance = $r->get(0)->instancesSet->get(0);
             $creInfo->SetProperties(array(EUCA_SERVER_PROPERTIES::REGION => $cloudLocation, EUCA_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EUCA_SERVER_PROPERTIES::EMIID => $instance->imageId, EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
         } else {
             if ($platform == SERVER_PLATFORMS::GCE) {
                 $gce = $platformObj->getClient($this->environment, $cloudLocation);
                 $result = $gce->instances->get($this->environment->getPlatformConfigValue(GoogleCEPlatformModule::PROJECT_ID), $cloudLocation, $cloudServerId);
                 $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_NAME => $cloudServerId, GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation));
             } else {
                 if (PlatformFactory::isOpenstack($platform)) {
                     $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                 } else {
                     if (PlatformFactory::isCloudstack($platform)) {
                         $creInfo->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                     }
                 }
             }
         }
     }
     $dbServer = DBServer::Create($creInfo, true);
     $ips = $platformObj->GetServerIPAddresses($dbServer);
     $dbServer->localIp = $ips['localIp'];
     $dbServer->remoteIp = $ips['remoteIp'];
     $dbServer->Save();
     $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'serverId' => $dbServer->serverId));
 }
Beispiel #15
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;
 }