Since: 5.11.6 (25.01.2016)
Author: Igor Vodiasov (invar@scalr.com)
Inheritance: extends Scalr\Model\Entity\Setting
Ejemplo n.º 1
0
 /**
  * Gets filter criteria by the setting
  *
  * @param   string  $name                Setting name
  * @param   string  $value      optional Setting value
  * @param   array   $criteria   optional Criteria, if already exists
  *
  * @return  array   Returns extended criteria
  */
 public function getSettingCriteria($name, $value = null, array $criteria = null)
 {
     $serverProperty = new ServerProperty();
     $alias = "sp_" . trim($this->db()->qstr($name), "'");
     $join = "\n            JOIN {$serverProperty->table($alias)} ON {$this->columnServerId()} = {$serverProperty->columnServerId($alias)}\n                AND {$serverProperty->columnName($alias)} = {$serverProperty->qstr('name', $name)}";
     if (isset($criteria[AbstractEntity::STMT_FROM])) {
         $criteria[AbstractEntity::STMT_FROM] .= " {$join}";
     } else {
         $criteria[AbstractEntity::STMT_FROM] = " {$join}";
     }
     if (isset($value)) {
         $where = "{$serverProperty->columnValue($alias)} = {$serverProperty->qstr('value', $value)}";
         if (isset($criteria[AbstractEntity::STMT_WHERE])) {
             $criteria[AbstractEntity::STMT_WHERE] .= " AND ({$where})";
         } else {
             $criteria[AbstractEntity::STMT_WHERE] = $where;
         }
     }
     return $criteria;
 }
Ejemplo n.º 2
0
 /**
  * @test
  * @functional
  */
 public function testComplex()
 {
     /* @var $farm Farm */
     $farm = $this->createTestFarm('server', ['base-ubuntu1404']);
     /* @var $farmRole FarmRole */
     $farmRole = $farm->farmRoles->current();
     $server = null;
     static::toDelete(Farm::class, [$farm->id]);
     $uri = self::getUserApiUrl("/farms/{$farm->id}/actions/launch");
     $this->request($uri, Request::METHOD_POST);
     for ($time = time(), $sleep = 50; time() - $time < 400 && (empty($server) || $server->status != Server::STATUS_RUNNING); $sleep += 50) {
         sleep($sleep);
         $testServers = $this->listServers(['farmId' => $farm->id]);
         if (count($testServers) > 0) {
             $server = reset($testServers);
             /* @var $server Server */
             continue;
         }
     }
     $this->assertNotEmpty($server);
     $this->assertEquals($server->status, 'running');
     $testDescribe = [['farmId' => $farm->id], ['farmRoleId' => $farmRole->id], ['serverId' => 'all']];
     // testing describe and fetch action
     foreach ($testDescribe as $value) {
         $servers = $this->listServers($value);
         $serverAdapter = $this->getAdapter('server');
         $filterable = $serverAdapter->getRules()[ApiEntityAdapter::RULE_TYPE_FILTERABLE];
         foreach ($servers as $server) {
             /* @var $server Server */
             foreach ($filterable as $property) {
                 $filterValue = $server->{$property};
                 $listResult = $this->listServers($value, [$property => $filterValue]);
                 if (!static::isRecursivelyEmpty($filterValue)) {
                     foreach ($listResult as $filtered) {
                         $this->assertEquals($filterValue, $filtered->{$property}, "Property '{$property}' mismatch");
                     }
                 }
             }
             $response = $this->getServer($server->id);
             $this->assertEquals(200, $response->status, $this->printResponseError($response));
             $dbServer = Server::findPk($server->id);
             $this->assertObjectEqualsEntity($response->getBody()->data, $dbServer, $serverAdapter);
         }
     }
     $entity = Server::findPk($server->id);
     /* @var $entity Server */
     $DBServerObject = $entity->__getDBServer();
     $oldModel = DBServer::LoadByID($server->id);
     $this->assertEquals($DBServerObject, $oldModel);
     $serverEntity = (new Server())->__getEntityFromDBServer($oldModel);
     $this->assertEquals($entity, $serverEntity);
     // testing reboot action
     $response = $this->rebootServer($server->id, true);
     $this->assertEquals(200, $response->status, $this->printResponseError($response));
     $data = $response->getBody()->data;
     $this->assertEquals($server->id, $data->id);
     $propertyReboot = ServerProperty::findOne([['serverId' => $server->id], ['name' => SERVER_PROPERTIES::REBOOTING]]);
     /* @var $propertyReboot ServerProperty */
     for ($time = time(), $sleep = 50; time() - $time < 300 && (!$propertyReboot || $propertyReboot->value); $sleep += 50) {
         $propertyReboot = ServerProperty::findOne([['serverId' => $server->id], ['name' => SERVER_PROPERTIES::REBOOTING]]);
     }
     $server = $this->waitForChanges($server->id, Server::STATUS_RUNNING);
     // testing suspend action
     $response = $this->suspendServer($server->id);
     $this->assertEquals(200, $response->status, $this->printResponseError($response));
     $data = $response->getBody()->data;
     $this->assertEquals($server->id, $data->id);
     $this->assertEquals($data->status, 'pending_suspend');
     $server = $this->waitForChanges($server->id, Server::STATUS_SUSPENDED, 600);
     // testing resume action
     $sleep = 0;
     do {
         try {
             $response = $this->resumeServer($server->id);
             if ($response->status == 200) {
                 break;
             }
         } catch (Exception $e) {
             if (strpos($e->getMessage(), "is not in a state from which it can be started") !== false) {
                 $sleep += 60;
                 sleep(60);
             } else {
                 throw $e;
             }
         }
     } while ($sleep < 300);
     $this->assertEquals(200, $response->status, $this->printResponseError($response));
     $data = $response->getBody()->data;
     $this->assertEquals($server->id, $data->id);
     $this->assertEquals($data->status, 'resuming');
     $server = $this->waitForChanges($server->id, Server::STATUS_RUNNING);
 }
Ejemplo n.º 3
0
 /**
  * {@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);
     }
 }