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


PHP Scalr::GenerateRandomKey方法代码示例

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


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

示例1: xSaveAction

 public function xSaveAction($url, $endpointId = null)
 {
     if (!$endpointId) {
         $endpoint = new WebhookEndpoint();
         $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT;
         $endpoint->accountId = $this->getEnvironment()->clientId;
         $endpoint->envId = $this->getEnvironmentId();
         $endpoint->securityKey = Scalr::GenerateRandomKey(64);
     } else {
         $endpoint = WebhookEndpoint::findPk($endpointId);
         if ($endpoint->envId != $this->getEnvironmentId() || $endpoint->accountId != $this->getEnvironment()->clientId) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint');
         }
     }
     foreach (WebhookEndpoint::findByUrl($url) as $ep) {
         if ($ep->endpointId != $endpoint->endpointId && $ep->envId == $this->getEnvironmentId()) {
             $this->request->addValidationErrors('url', 'Endpoint url must be unique within environment');
             break;
         }
     }
     if ($this->request->isValid()) {
         if ($endpoint->url != $url) {
             $endpoint->isValid = false;
             $endpoint->url = $url;
         }
         ////temporarily disable url validation per Igor`s request(see also webhooks/endpoints/view.js)
         $endpoint->isValid = true;
         $endpoint->save();
         $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey)));
     } else {
         $this->response->data($this->request->getValidationErrors());
         $this->response->failure();
     }
 }
开发者ID:rickb838,项目名称:scalr,代码行数:34,代码来源:Endpoints.php

示例2: init

 /**
  * Initializes ReportPayloadEntity object
  *
  * @param  array                $data    Data array of params for uuid (Notification type, subject type, subject id)
  * @param  array                $payload Payload
  * @param  string|DateTime|null $start   optional Start date of the report (Y-m-d)
  * @return ReportPayloadEntity  Returns  ReportPayloadEntity object
  */
 public static function init(array $data, $payload, $start = null)
 {
     $obj = new self();
     $obj->created = $start instanceof DateTime ? clone $start : new DateTime($start ?: "now", new DateTimeZone('UTC'));
     $dataToHash = implode('|', $data) . '|' . $obj->created->format('Y-m-d');
     $obj->uuid = $obj->type('uuid')->toPhp(substr(hash('sha1', $dataToHash, true), 0, 16));
     $obj->secret = $obj->type('secret')->toPhp(hash('sha1', \Scalr::GenerateRandomKey(40), true));
     $baseUrl = rtrim(\Scalr::getContainer()->config('scalr.endpoint.scheme') . "://" . \Scalr::getContainer()->config('scalr.endpoint.host'), '/');
     $payload['reportUrl'] = $baseUrl . '#/public/report?uuid=' . $obj->uuid . '&secretHash=' . bin2hex((string) $obj->secret);
     $obj->payload = json_encode($payload);
     return $obj;
 }
开发者ID:mheydt,项目名称:scalr,代码行数:20,代码来源:ReportPayloadEntity.php

示例3: xSaveAction

 /**
  * @param string $url
  * @param string $endpointId
  * @throws Exception
  */
 public function xSaveAction($url, $endpointId = null)
 {
     if (!$endpointId) {
         $endpoint = new WebhookEndpoint();
         $endpoint->setScope($this->request->getScope(), $this->user->getAccountId(), $this->getEnvironmentId(true));
         $endpoint->securityKey = Scalr::GenerateRandomKey(64);
     } else {
         $endpoint = WebhookEndpoint::findPk($endpointId);
         if (!$this->canEditEndpoint($endpoint)) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint at this scope');
         }
     }
     $validator = new Validator();
     $validator->validate($url, 'url', Validator::URL);
     //check url unique within current level
     $criteria = [];
     $criteria[] = ['url' => $url];
     if ($endpoint->endpointId) {
         $criteria[] = ['endpointId' => ['$ne' => $endpoint->endpointId]];
     }
     switch ($this->request->getScope()) {
         case WebhookEndpoint::SCOPE_ENVIRONMENT:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_ENVIRONMENT];
             $criteria[] = ['envId' => $endpoint->envId];
             $criteria[] = ['accountId' => $endpoint->accountId];
             break;
         case WebhookEndpoint::SCOPE_ACCOUNT:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_ACCOUNT];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $endpoint->accountId];
             break;
         case WebhookEndpoint::SCOPE_SCALR:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_SCALR];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (WebhookEndpoint::findOne($criteria)) {
         $validator->addError('url', 'Endpoint url must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($endpoint->url != $url) {
         $endpoint->isValid = false;
         $endpoint->url = $url;
     }
     ////temporarily disable url validation per Igor`s request(see also webhooks/endpoints/view.js)
     $endpoint->isValid = true;
     $endpoint->save();
     $this->response->success('Endpoint successfully saved');
     $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey, 'scope' => $endpoint->getScope())));
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:58,代码来源:Endpoints.php

示例4: xInitiateImportAction

 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));
 }
开发者ID:recipe,项目名称:scalr,代码行数:51,代码来源:Import.php

示例5: xInitiateImportAction

 /**
  * @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));
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:57,代码来源:Import.php

示例6: run1

 /**
  * Performs upgrade literally for the stage ONE.
  *
  * Implementation of this method performs update steps needs to be taken
  * to accomplish upgrade successfully.
  *
  * If there are any error during an execution of this scenario it must
  * throw an exception.
  *
  * @param   int  $stage  optional The stage number
  * @throws  \Exception
  */
 protected function run1($stage)
 {
     $observers = $this->db->Execute("SELECT * FROM farm_event_observers WHERE event_observer_name = 'MailEventObserver'");
     while ($observer = $observers->FetchRow()) {
         $dbFarm = \DBFarm::LoadByID($observer['farmid']);
         // Create endpoint
         $endpointId = $this->db->GetOne("SELECT endpoint_id FROM webhook_endpoints WHERE env_id = ? AND url = ?", array($dbFarm->EnvID, 'SCALR_MAIL_SERVICE'));
         if ($endpointId) {
             $endpoint = WebhookEndpoint::findPk(bin2hex($endpointId));
         } else {
             $endpoint = new WebhookEndpoint();
             $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT;
             $endpoint->accountId = $dbFarm->ClientID;
             $endpoint->envId = $dbFarm->EnvID;
             $endpoint->securityKey = \Scalr::GenerateRandomKey(64);
             $endpoint->isValid = true;
             $endpoint->url = "SCALR_MAIL_SERVICE";
             $endpoint->save();
         }
         //Create webhook configuration
         $webhook = new WebhookConfig();
         $webhook->level = WebhookConfig::LEVEL_ENVIRONMENT;
         $webhook->accountId = $dbFarm->ClientID;
         $webhook->envId = $dbFarm->EnvID;
         $webhook->name = "MailEventObserver(FarmID: {$dbFarm->ID})";
         $webhook->postData = $this->db->GetOne("SELECT value FROM farm_event_observers_config WHERE `key` = ? AND observerid = ?", array('EventMailTo', $observer['id']));
         $webhook->save();
         //save endpoints
         $configEndpoint = new WebhookConfigEndpoint();
         $configEndpoint->webhookId = $webhook->webhookId;
         $configEndpoint->setEndpoint($endpoint);
         $configEndpoint->save();
         //save events
         $dbEvents = $this->db->Execute("SELECT * FROM farm_event_observers_config WHERE `key` LIKE '%Notify' AND observerid = ?", array($observer['id']));
         while ($info = $dbEvents->FetchRow()) {
             preg_match('/On([A-Za-z0-9]+)Notify/si', $info['key'], $matches);
             $configEvent = new WebhookConfigEvent();
             $configEvent->webhookId = $webhook->webhookId;
             $configEvent->eventType = $matches[1];
             $configEvent->save();
         }
         //save farms
         $configFarm = new WebhookConfigFarm();
         $configFarm->webhookId = $webhook->webhookId;
         $configFarm->farmId = $dbFarm->ID;
         $configFarm->save();
     }
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:60,代码来源:Update20140320035714.php

示例7: create

 public static function create($name)
 {
     $account = Scalr_UI_Request::getInstance()->getUser()->getAccount();
     $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
     $db = Core::GetDBInstance();
     $dbFarm = new self();
     $dbFarm->Status = FARM_STATUS::TERMINATED;
     $dbFarm->ClientID = $account->id;
     $dbFarm->EnvID = Scalr_UI_Request::getInstance()->getEnvironment()->id;
     $dbFarm->Name = $name;
     $dbFarm->RolesLaunchOrder = 0;
     $dbFarm->Comments = "";
     $dbFarm->save();
     $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     return $dbFarm;
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:16,代码来源:class.DBFarm.php

示例8: create

 /**
  * Initializes a new farm
  *
  * TODO: Rewrite this terrible code.
  *
  * @param   string             $name  The name of the farm
  * @param   Scalr_Account_User $user  The user
  * @param   int                $envId The identifier of the environment
  * @return  DBFarm
  */
 public static function create($name, Scalr_Account_User $user, $envId)
 {
     $account = $user->getAccount();
     $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
     $dbFarm = new self();
     $dbFarm->Status = FARM_STATUS::TERMINATED;
     $dbFarm->ClientID = $account->id;
     $dbFarm->EnvID = $envId;
     $dbFarm->createdByUserId = $user->getId();
     $dbFarm->createdByUserEmail = $user->getEmail();
     $dbFarm->changedByUserId = $user->getId();
     $dbFarm->changedTime = microtime();
     $dbFarm->Name = $name;
     $dbFarm->RolesLaunchOrder = 0;
     $dbFarm->Comments = "";
     $dbFarm->save();
     $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     return $dbFarm;
 }
开发者ID:rickb838,项目名称:scalr,代码行数:29,代码来源:class.DBFarm.php

示例9: providerTestCrypto

 /**
  * Data provider for testCrypto()
  */
 public function providerTestCrypto()
 {
     self::initCrypto();
     $cases = array();
     // this cases doesn't work similar in python decrypt as php
     /* TODO: fix
        $cases[] = array("\n");
        $cases[] = array("abracadabra\n");
        $cases[] = array(" ");
        $cases[] = array(" \n");
        $cases[] = array("abracadabra \n");
        $cases[] = array(" abracadabra \n");
        $cases[] = array("\t\n");
        $cases[] = array(" foo ");
        */
     // depends on block size (extended test = 256, short = 32)
     for ($i = 1; $i <= 32; $i++) {
         $cases[] = array(\Scalr::GenerateRandomKey($i));
     }
     return $cases;
 }
开发者ID:rickb838,项目名称:scalr,代码行数:24,代码来源:CryptoToolTest.php

示例10: save

 /**
  * {@inheritdoc}
  * @see AbstractEntity::save()
  */
 public function save()
 {
     $this->changed = microtime();
     if (empty($this->id)) {
         $this->createdById = $this->changedById;
         $this->added = new DateTime();
         $this->status = FARM_STATUS::TERMINATED;
         if (empty($this->settings[FarmSetting::TIMEZONE])) {
             $this->settings[FarmSetting::TIMEZONE] = date_default_timezone_get();
         }
         $this->settings[FarmSetting::CRYPTO_KEY] = \Scalr::GenerateRandomKey(40);
         /* @var $governance Governance */
         $governance = Governance::findPk($this->envId, Governance::CATEGORY_GENERAL, Governance::GENERAL_LEASE);
         if (!empty($governance) && $governance->enabled) {
             $this->settings[FarmSetting::LEASE_STATUS] = 'Active';
         }
         //TODO: unused field
         $this->region = Aws::REGION_US_EAST_1;
     }
     parent::save();
     if (!empty($this->_settings)) {
         $this->_settings->save();
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:28,代码来源:Farm.php

示例11: import

 /**
  * {@inheritdoc}
  * @see ServerImportInterface::import()
  */
 public function import($instanceId, $tags = [])
 {
     $instances = PlatformFactory::NewPlatform($this->farmRole->platform)->getOrphanedServers($this->farmRole->getFarm()->getEnvironment(), $this->farmRole->cloudLocation, [$instanceId]);
     if (count($instances) != 1) {
         throw new ValidationErrorException("Instance was not found");
     }
     $this->orphaned = $instances[0];
     $this->tags = $tags;
     $this->validate();
     $farm = $this->farmRole->getFarm();
     $server = $this->server = new Entity\Server();
     try {
         $server->serverId = \Scalr::GenerateUID(false);
         // DBServer::Create, startWithLetter
         $server->platform = $this->farmRole->platform;
         $server->cloudLocation = $this->farmRole->cloudLocation;
         $server->accountId = $farm->accountId;
         $server->envId = $farm->envId;
         $server->farmId = $farm->id;
         $server->farmRoleId = $this->farmRole->id;
         $server->imageId = $this->orphaned->imageId;
         $server->status = Entity\Server::STATUS_RUNNING;
         $server->type = $this->orphaned->instanceType;
         $server->remoteIp = $this->orphaned->publicIp;
         $server->localIp = $this->orphaned->privateIp;
         $server->added = new DateTime();
         $server->initialized = new DateTime();
         // initialized is used in billing, so we set current time as start point
         $server->scalarized = 0;
         $server->setFreeFarmIndex();
         $server->setFreeFarmRoleIndex();
         $server->properties[Entity\Server::SZR_KEY] = \Scalr::GenerateRandomKey(40);
         $server->properties[Entity\Server::SZR_KEY_TYPE] = SZR_KEY_TYPE::ONE_TIME;
         $server->properties[Entity\Server::SZR_VESION] = '';
         $server->properties[Entity\Server::LAUNCHED_BY_ID] = $this->user->id;
         $server->properties[Entity\Server::LAUNCHED_BY_EMAIL] = $this->user->email;
         $server->properties[Entity\Server::LAUNCH_REASON_ID] = DBServer::LAUNCH_REASON_IMPORT;
         $server->properties[Entity\Server::LAUNCH_REASON] = DBServer::getLaunchReason(DBServer::LAUNCH_REASON_IMPORT);
         $server->properties[Entity\Server::FARM_ROLE_ID] = $this->farmRole->id;
         $server->properties[Entity\Server::ROLE_ID] = $this->farmRole->roleId;
         $server->properties[Entity\Server::FARM_CREATED_BY_ID] = $farm->ownerId ?: $farm->settings[Entity\FarmSetting::CREATED_BY_ID];
         $server->properties[Entity\Server::FARM_CREATED_BY_EMAIL] = $farm->ownerId ? Entity\Account\User::findPk($farm->ownerId)->email : $farm->settings[Entity\FarmSetting::CREATED_BY_EMAIL];
         // projectId, ccId
         $projectId = $farm->settings[Entity\FarmSetting::PROJECT_ID];
         $ccId = null;
         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;
             }
         }
         $server->properties[Entity\Server::FARM_PROJECT_ID] = $projectId;
         if (empty($ccId)) {
             $ccId = Entity\Account\Environment::findPk($farm->envId)->getProperty(Entity\Account\EnvironmentProperty::SETTING_CC_ID);
         }
         $server->properties[Entity\Server::ENV_CC_ID] = $ccId;
         if (!empty($server->getImage())) {
             $server->getImage()->update(['dtLastUsed' => new DateTime()]);
         }
         if (!empty($this->farmRole->getRole())) {
             $this->farmRole->getRole()->update(['lastUsed' => new DateTime()]);
         }
         $this->importServer();
         $server->save();
         $server->setTimeLog('ts_created');
         $server->setTimeLog('ts_launched', time());
         $history = $server->getHistory();
         $history->markAsLaunched($server->properties[Entity\Server::LAUNCH_REASON], $server->properties[Entity\Server::LAUNCH_REASON_ID]);
         $history->update(['cloudServerId' => $this->orphaned->cloudServerId, 'scuCollecting' => 1]);
         $this->applyTags();
         return $server;
     } catch (Exception $e) {
         if (!empty($server->serverId)) {
             // cleanup
             $server->deleteBy([['serverId' => $server->serverId]]);
             Entity\ServerProperty::deleteBy([['serverId' => $server->serverId]]);
             Entity\Server\History::deletePk($server->serverId);
             $this->db->Execute("DELETE FROM `servers_launch_timelog` WHERE server_id = ?", [$server->serverId]);
         }
         throw new ServerImportException(sprintf("Server create was failed with error: %s", $e->getMessage()), $e->getCode(), $e);
     }
 }
开发者ID:scalr,项目名称:scalr,代码行数:93,代码来源:AbstractServerImport.php

示例12: xBuildAction

 public function xBuildAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'), 'launch' => array('type' => 'bool')));
     if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) {
         if ($this->errors['error_count'] != 0) {
             $this->response->failure();
             $this->response->data(array('errors' => $this->errors));
             return;
         }
     }
     $farm = $this->getParam('farm');
     $client = Client::Load($this->user->getAccountId());
     if ($this->getParam('farmId')) {
         $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
         $this->user->getPermissions()->validate($dbFarm);
         $this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE);
         $dbFarm->isLocked();
         if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) {
             $userName = 'Someone';
             $changed = explode(' ', $this->getParam('changed'));
             $changedTime = intval($changed[1]);
             try {
                 $user = new Scalr_Account_User();
                 $user->loadById($dbFarm->changedByUserId);
                 $userName = $user->getEmail();
             } catch (Exception $e) {
             }
             $this->response->failure();
             $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime))));
             return;
         }
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
         $bNew = false;
     } else {
         $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
         $dbFarm = new DBFarm();
         $dbFarm->ClientID = $this->user->getAccountId();
         $dbFarm->EnvID = $this->getEnvironmentId();
         $dbFarm->Status = FARM_STATUS::TERMINATED;
         $dbFarm->createdByUserId = $this->user->getId();
         $dbFarm->createdByUserEmail = $this->user->getEmail();
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
         $bNew = true;
     }
     if ($this->getParam('farm')) {
         $dbFarm->Name = $this->request->stripValue($farm['name']);
         $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder'];
         $dbFarm->Comments = $this->request->stripValue($farm['description']);
     }
     if (empty($dbFarm->Name)) {
         throw new Exception(_("Farm name required"));
     }
     if ($bNew) {
         $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL;
     } else {
         if ($dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP)) {
             if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->createdByUserId) {
                 $user = (new Scalr_Account_User())->loadById($farm['owner']);
                 $dbFarm->createdByUserId = $user->getId();
                 $dbFarm->createdByUserEmail = $user->getEmail();
                 // TODO: move to subclass \Farm\Setting\OwnerHistory
                 $history = unserialize($dbFarm->GetSetting(DBFarm::SETTING_OWNER_HISTORY));
                 if (!is_array($history)) {
                     $history = [];
                 }
                 $history[] = ['newId' => $user->getId(), 'newEmail' => $user->getEmail(), 'changedById' => $this->user->getId(), 'changedByEmail' => $this->user->getEmail(), 'dt' => date('Y-m-d H:i:s')];
                 $dbFarm->SetSetting(DBFarm::SETTING_OWNER_HISTORY, serialize($history));
             }
             $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL;
         }
     }
     $dbFarm->save();
     $governance = new Scalr_Governance($this->getEnvironmentId());
     if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
         // for created farm
     }
     if (isset($farm['variables'])) {
         $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true);
     }
     if (!$farm['timezone']) {
         $farm['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']);
     $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $farm[DBFarm::SETTING_SZR_UPD_REPOSITORY]);
     $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $farm[DBFarm::SETTING_SZR_UPD_SCHEDULE]);
     if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) {
         $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     }
     if ($this->getContainer()->analytics->enabled) {
         //Cost analytics project must be set for the Farm object
         $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null);
     }
     $virtualFarmRoles = array();
//.........这里部分代码省略.........
开发者ID:sacredwebsite,项目名称:scalr,代码行数:101,代码来源:Builder.php

示例13: xBuildAction

 /**
  * @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']) {
//.........这里部分代码省略.........
开发者ID:scalr,项目名称:scalr,代码行数:101,代码来源:Roles.php

示例14: xInitiateImportAction

 /**
  * @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));
 }
开发者ID:scalr,项目名称:scalr,代码行数:69,代码来源:Import.php

示例15: GenerateAPIKeys

 public static function GenerateAPIKeys()
 {
     $key = Scalr::GenerateRandomKey();
     $sault = abs(crc32($key));
     $keyid = dechex($sault) . dechex(time());
     $ScalrKey = $key;
     $ScalrKeyID = $keyid;
     return array("id" => $ScalrKeyID, "key" => $ScalrKey);
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:9,代码来源:Scalr.php


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