protected function run1($stage) { $envIds = $this->db->Execute("SELECT `id` FROM `client_environments`"); $platformVariables = static::getCloudsCredentialProperties(); foreach ($envIds as $row) { $environment = \Scalr_Environment::init()->loadById($row['id']); $platforms = []; foreach (array_keys(SERVER_PLATFORMS::getList()) as $platform) { if ($environment->getPlatformConfigValue($platform . '.is_enabled', false)) { $platforms[] = $platform; } } foreach ($platforms as $platform) { try { switch ($platform) { case SERVER_PLATFORMS::RACKSPACE: foreach (['rs-ORD1', 'rs-LONx'] as $location) { $cloudCredentials = new Entity\CloudCredentials(); $cloudCredentials->accountId = $environment->getAccountId(); $cloudCredentials->envId = $environment->id; $cloudCredentials->cloud = "{$location}.{$platform}"; $cloudCredentials->name = "{$environment->id}-{$environment->getAccountId()}-{$cloudCredentials->cloud}-" . \Scalr::GenerateUID(true); foreach ($platformVariables[$platform] as $name => $newName) { $value = $environment->getPlatformConfigValue($name, true, $location); if ($value === null) { $value = false; } $cloudCredentials->properties[$newName] = $value; } $cloudCredentials->save(); $cloudCredentials->bindToEnvironment($environment); } break; default: $cloudCredentials = new Entity\CloudCredentials(); $cloudCredentials->accountId = $environment->getAccountId(); $cloudCredentials->envId = $environment->id; $cloudCredentials->cloud = $platform; $cloudCredentials->name = "{$environment->id}-{$environment->getAccountId()}-{$platform}-" . \Scalr::GenerateUID(true); $cloudCredentials->status = Entity\CloudCredentials::STATUS_ENABLED; foreach ($platformVariables[$platform] as $name => $newName) { $value = $environment->getPlatformConfigValue($name); if ($value === null) { $value = false; } $cloudCredentials->properties[$newName] = $value; } $cloudCredentials->save(); $cloudCredentials->bindToEnvironment($environment); break; } } catch (Exception $e) { $this->console->error(get_class($e) . " in {$e->getFile()} on line {$e->getLine()}: " . $e->getMessage()); error_log(get_class($e) . " in {$e->getFile()} at line {$e->getLine()}: {$e->getMessage()}\n{$e->getTraceAsString()}"); } } } }
/** * Gets CloudCredentials entity * * @param string $cloudCredentialsId Unique identifier of the CloudCredentials * * @return Entity\CloudCredentials * * @throws ApiErrorException */ public function getCloudCredentials($cloudCredentialsId) { /* @var $cloudCredentials Entity\CloudCredentials */ $cloudCredentials = Entity\CloudCredentials::findPk($cloudCredentialsId); if (empty($cloudCredentials)) { throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Cloud Credentials either does not exist or is not owned by you."); } switch ($cloudCredentials->getScope()) { case ScopeInterface::SCOPE_SCALR: break; case ScopeInterface::SCOPE_ACCOUNT: if ($cloudCredentials->accountId != $this->getUser()->getAccountId()) { throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Cloud Credentials either does not exist or is not owned by you."); } break; case ScopeInterface::SCOPE_ENVIRONMENT: if (!($this->getUser()->canManageAcl() || $this->getUser()->hasAccessToEnvironment($cloudCredentials->envId))) { throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "Insufficient permissions"); } } return $cloudCredentials; }
/** * Makes clod credentials entity for specified platform * * @param string $platform Cloud credentials platform * @param array $parameters Array of cloud credentials parameters * @param int $status optional Cloud credentials status * * @return Entity\CloudCredentials Returns new cloud credentials entity * * @throws Exception */ public function makeCloudCredentials($platform, $parameters, $status = Entity\CloudCredentials::STATUS_ENABLED) { $cloudCredentials = new Entity\CloudCredentials(); $cloudCredentials->envId = $this->env->id; $cloudCredentials->accountId = $this->env->getAccountId(); $cloudCredentials->cloud = $platform; $cloudCredentials->name = "{$this->env->id}-{$this->env->getAccountId()}-{$platform}-" . \Scalr::GenerateUID(true); $cloudCredentials->status = $status; try { $this->db->BeginTrans(); $cloudCredentials->save(); $cloudCredentials->properties->saveSettings($parameters); $cloudCredentials->bindToEnvironment($this->env); $this->db->CommitTrans(); } catch (Exception $e) { $this->db->RollbackTrans(); throw $e; } $cloudCredentials->cache($this->env->getContainer()); return $cloudCredentials; }
/** * @param string $cloudCredentialsId * @param bool $modify * * @return Entity\CloudCredentials * @throws ApiErrorException */ public function getCloudCredentials($cloudCredentialsId, $modify = false) { $cloudCredentials = Entity\CloudCredentials::findPk($cloudCredentialsId); if (empty($cloudCredentials) || !$this->hasPermissions($cloudCredentials, $modify)) { throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Cloud Credentials either does not exist or is not owned by you."); } return $cloudCredentials; }
/** * xGetPlatformEndpointsAction * * @param string $platform The cloud platform */ public function xGetPlatformEndpointsAction($platform) { if (PlatformFactory::isOpenstack($platform)) { $key = Entity\CloudCredentialsProperty::OPENSTACK_KEYSTONE_URL; } else { if (PlatformFactory::isCloudstack($platform)) { $key = Entity\CloudCredentialsProperty::CLOUDSTACK_API_URL; } } if (isset($key)) { $pm = PlatformFactory::NewPlatform($platform); $rs = $this->db->Execute("\n SELECT DISTINCT ce.`id`, cecc.`cloud_credentials_id`\n FROM client_environments ce\n JOIN clients c ON c.id = ce.client_id\n JOIN environment_cloud_credentials cecc ON ce.`id` = cecc.`env_id` AND cecc.`cloud` = ?\n JOIN cloud_credentials_properties ccp ON cecc.`cloud_credentials_id` = ccp.`cloud_credentials_id`\n LEFT JOIN client_environment_properties cep ON ce.`id` = cep.`env_id` AND cep.`name` = ?\n WHERE c.status = ? AND ccp.name = ? AND ce.status = ? AND cep.`value` IS NULL OR cep.`value` = ''\n GROUP BY ccp.`value`\n ", [$platform, "{$platform}.suspended", Scalr_Account::STATUS_ACTIVE, $key, Scalr_Environment::STATUS_ACTIVE]); $endpoints = []; $cloudCredsIds = []; $envs = []; while ($rec = $rs->FetchRow()) { $cloudCredsId = $rec['cloud_credentials_id']; $envs[$cloudCredsId] = $rec['id']; $cloudCredsIds[] = $cloudCredsId; } $cloudCredentialsEntity = new Entity\CloudCredentials(); $idFieldType = $cloudCredentialsEntity->getIterator()->getField('id')->getType(); foreach (array_chunk($cloudCredsIds, 128) as $chunk) { /* @var $cloudCredentials Entity\CloudCredentials */ foreach (Entity\CloudCredentials::find([['id' => ['$in' => $chunk]]]) as $cloudCredentials) { $url = $this->getContainer()->analytics->prices->normalizeUrl($cloudCredentials->properties[$key]); if (!array_key_exists($url, $endpoints)) { $endpoints[$url] = array('envId' => $envs[$cloudCredentials->id], 'url' => $url); } } } } else { $endpoints[0] = $platform; } $this->response->data(['data' => array_values($endpoints)]); }
/** * Gets cloud credentials for listed clouds * * @param string[] $clouds optional Clouds list * @param array $credentialsFilter optional Criteria to filter by CloudCredentials properties * @param array $propertiesFilter optional Criteria to filter by CloudCredentialsProperties * * @return EntityIterator|CloudCredentials[] */ public function cloudCredentialsList(array $clouds = null, array $credentialsFilter = [], array $propertiesFilter = []) { if (!is_array($clouds)) { $clouds = (array) $clouds; } $cloudCredentials = new CloudCredentials(); $cloudCredProps = new CloudCredentialsProperty(); $criteria = $credentialsFilter; $from[] = empty($criteria[AbstractEntity::STMT_FROM]) ? " {$cloudCredentials->table()} " : $criteria[AbstractEntity::STMT_FROM]; $where = empty($criteria[AbstractEntity::STMT_WHERE]) ? [] : [$criteria[AbstractEntity::STMT_WHERE]]; $criteria[] = ['accountId' => $this->id]; if (!empty($clouds)) { $clouds = implode(", ", array_map(function ($cloud) use($cloudCredentials) { return $cloudCredentials->qstr('cloud', $cloud); }, $clouds)); $where[] = "{$cloudCredentials->columnCloud()} IN ({$clouds})"; } if (!empty($propertiesFilter)) { foreach ($propertiesFilter as $property => $propCriteria) { $alias = "ccp_" . trim($cloudCredentials->db()->qstr($property), "'"); $from[] = "\n LEFT JOIN {$cloudCredProps->table($alias)} ON\n {$cloudCredentials->columnId()} = {$cloudCredProps->columnCloudCredentialsId($alias)} AND\n {$cloudCredProps->columnName($alias)} = {$cloudCredProps->qstr('name', $property)}\n "; $built = $cloudCredProps->_buildQuery($propCriteria, 'AND', $alias); if (!empty($built['where'])) { $where[] = $built['where']; } } } $criteria[AbstractEntity::STMT_FROM] = implode("\n", $from); if (!empty($where)) { $criteria[AbstractEntity::STMT_WHERE] = "(" . implode(") AND (", $where) . ")"; } return CloudCredentials::find($criteria); }
public function getEnabledPlatforms($cacheResult = false, $clouds = null) { $cloudsList = array_keys(SERVER_PLATFORMS::getList()); if (isset($clouds)) { $cloudsList = array_intersect($cloudsList, (array) $clouds); } return array_values(array_intersect($cloudsList, array_keys($this->cloudCredentialsList($cloudsList, [['status' => ['$in' => Entity\CloudCredentials::getEnabledStatuses()]]], [], $cacheResult)))); }
/** * {@inheritdoc} * @see Scalr_Model::delete() */ public function delete($id = null) { $servers = \DBServer::listByFilter(['clientId' => $this->id]); foreach ($servers as $server) { /* @var $server \DBServer */ $server->Remove(); } try { $this->db->StartTrans(); //TODO: Use models $this->db->Execute("\n DELETE account_team_users FROM account_team_users, account_teams\n WHERE account_teams.account_id = ?\n AND account_team_users.team_id = account_teams.id\n ", array($this->id)); $this->db->Execute("DELETE FROM account_users WHERE account_id=?", array($this->id)); $this->db->Execute("DELETE FROM account_teams WHERE account_id=?", array($this->id)); $this->db->Execute("DELETE FROM account_limits WHERE account_id=?", array($this->id)); /* @var $environment Environment */ foreach (Environment::findByAccountId($this->id) as $environment) { $environment->delete(true); } CloudCredentials::deleteByAccountId($this->id); $this->db->Execute("\n DELETE account_team_user_acls FROM account_team_user_acls, acl_account_roles\n WHERE acl_account_roles.account_id = ?\n AND account_team_user_acls.account_role_id = acl_account_roles.account_role_id\n ", array($this->id)); $this->db->Execute("DELETE FROM acl_account_roles WHERE account_id=?", array($this->id)); $this->db->Execute("DELETE FROM ec2_ebs WHERE client_id=?", array($this->id)); $this->db->Execute("DELETE FROM apache_vhosts WHERE client_id=?", array($this->id)); $this->db->Execute("DELETE FROM scheduler WHERE account_id=?", array($this->id)); foreach ($this->db->Execute("SELECT id FROM farms WHERE clientid=?", [$this->id]) as $farm) { $this->db->Execute("DELETE FROM farms WHERE id=?", array($farm["id"])); $this->db->Execute("DELETE FROM farm_roles WHERE farmid=?", array($farm["id"])); $this->db->Execute("DELETE FROM elastic_ips WHERE farmid=?", array($farm["id"])); } $roles = $this->db->GetAll("SELECT id FROM roles WHERE client_id = '{$this->id}'"); foreach ($roles as $role) { $this->db->Execute("DELETE FROM roles WHERE id = ?", array($role['id'])); $this->db->Execute("DELETE FROM role_behaviors WHERE role_id = ?", array($role['id'])); $this->db->Execute("DELETE FROM role_images WHERE role_id = ?", array($role['id'])); $this->db->Execute("DELETE FROM role_properties WHERE role_id = ?", array($role['id'])); $this->db->Execute("DELETE FROM role_security_rules WHERE role_id = ?", array($role['id'])); } //Removing cost centres and projects which are set up from this account $this->db->Execute("\n DELETE project_properties FROM project_properties, projects\n WHERE projects.project_id = project_properties.project_id\n AND projects.account_id = ?\n ", [$this->id]); $this->db->Execute("DELETE FROM projects WHERE account_id = ?", [$this->id]); $this->db->Execute("\n DELETE cc_properties FROM cc_properties, ccs\n WHERE ccs.cc_id = cc_properties.cc_id\n AND ccs.account_id = ?\n ", [$this->id]); $this->db->Execute("DELETE FROM ccs WHERE account_id = ?", [$this->id]); parent::delete(); ReportEntity::deleteByAccountId($this->id); NotificationEntity::deleteByAccountId($this->id); $this->db->CompleteTrans(); } catch (\Exception $e) { $this->db->RollbackTrans(); throw $e; } }
/** * @param Entity\CloudCredentials $entity * @param Entity\CloudCredentials $prevConfig * * @throws ApiErrorException */ public function validateEntity($entity, $prevConfig = null) { if (empty($entity->name)) { throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Cloud credentials name cannot be empty"); } $criteria = $this->controller->getScopeCriteria(); $criteria[] = ['name' => $entity->name]; $criteria[] = ['id' => ['$ne' => $entity->id]]; /* @var $exists Entity\CloudCredentials */ if ($exists = Entity\CloudCredentials::findOne($criteria)) { throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, "Cloud credentials named '{$entity->name}' already exists in {$exists->getScope()}"); } }
/** * Gets cloud credentials for listed clouds * * @param string[] $clouds optional Clouds list * @param array $credentialsFilter optional Criteria to filter by CloudCredentials properties * @param array $propertiesFilter optional Criteria to filter by CloudCredentialsProperties * @param bool $cacheResult optional Cache result * * @return Entity\CloudCredentials[] */ public function cloudCredentialsList(array $clouds = null, array $credentialsFilter = [], array $propertiesFilter = [], $cacheResult = true) { if (!is_array($clouds)) { $clouds = (array) $clouds; } $cloudCredentials = new Entity\CloudCredentials(); $envCloudCredentials = new Entity\EnvironmentCloudCredentials(); $cloudCredProps = new Entity\CloudCredentialsProperty(); $criteria = array_merge($credentialsFilter, [AbstractEntity::STMT_FROM => $cloudCredentials->table(), AbstractEntity::STMT_WHERE => '']); if (!empty($clouds)) { $criteria[AbstractEntity::STMT_FROM] .= "\n JOIN {$envCloudCredentials->table('cecc')} ON\n {$cloudCredentials->columnId()} = {$envCloudCredentials->columnCloudCredentialsId('cecc')} AND\n {$cloudCredentials->columnCloud()} = {$envCloudCredentials->columnCloud('cecc')}\n "; $clouds = implode(", ", array_map(function ($cloud) use($envCloudCredentials) { return $envCloudCredentials->qstr('cloud', $cloud); }, $clouds)); $criteria[AbstractEntity::STMT_WHERE] = "\n {$envCloudCredentials->columnEnvId('cecc')} = {$envCloudCredentials->qstr('envId', $this->id)} AND\n {$envCloudCredentials->columnCloud('cecc')} IN ({$clouds})\n "; } if (!empty($propertiesFilter)) { foreach ($propertiesFilter as $property => $propCriteria) { $criteria[AbstractEntity::STMT_FROM] .= "\n LEFT JOIN {$cloudCredProps->table('ccp')} ON\n {$cloudCredentials->columnId()} = {$cloudCredProps->columnCloudCredentialsId('ccp')} AND\n {$cloudCredProps->columnName('ccp')} = {$cloudCredProps->qstr('name', $property)}\n "; $conjunction = empty($criteria[AbstractEntity::STMT_WHERE]) ? "" : "AND"; $criteria[AbstractEntity::STMT_WHERE] .= "\n {$conjunction} {$cloudCredProps->_buildQuery($propCriteria, 'AND', 'ccp')}\n "; } } /* @var $cloudsCredentials Entity\CloudCredentials[] */ $cloudsCredentials = Entity\CloudCredentials::find($criteria); $result = []; $cont = \Scalr::getContainer(); foreach ($cloudsCredentials as $cloudCredentials) { $result[$cloudCredentials->cloud] = $cloudCredentials; if ($cacheResult) { $cloudCredentials->bindEnvironment($this->id); $cloudCredentials->cache($cont); } } return $result; }
$envCloudCredentials = new Entity\EnvironmentCloudCredentials(); /* @var $cloudCredentials Entity\CloudCredentials */ $cloudCredentials = Entity\CloudCredentials::findOne([\Scalr\Model\AbstractEntity::STMT_FROM => "{$cloudCredentials->table()} JOIN {$envCloudCredentials->table('cecc')} ON {$cloudCredentials->columnId()} = {$envCloudCredentials->columnCloudCredentialsId('cecc')} AND {$cloudCredentials->columnCloud()} = {$envCloudCredentials->columnCloud('cecc')}", \Scalr\Model\AbstractEntity::STMT_WHERE => "{$envCloudCredentials->columnEnvId('cecc')} = {$envCloudCredentials->qstr('envId', $envId)} AND {$envCloudCredentials->columnCloud('cecc')} = {$envCloudCredentials->qstr('cloud', $cloud)}"]); if (!empty($cloudCredentials)) { $cloudCredId = $cloudCredentials->id; $cloudCredentials->bindEnvironment($envId); return $cloudCredId; } return null; }); } $cloudCredId = $cont->get($envCloudCredId); $contCloudCredId = "cloud_creds.{$cloudCredId}"; if (!$cont->initialized($contCloudCredId)) { $cont->setShared($contCloudCredId, function ($cont) use($envId, $cloud, $cloudCredId, &$cloudCredentials) { if (!(isset($cloudCredentials) || empty($cloudCredentials = Entity\CloudCredentials::findPk($cloudCredId)))) { $cloudCredentials->bindEnvironment($envId); } return $cloudCredentials ?: false; }); } if (empty($cloudCredentials = $cont->get($contCloudCredId))) { $cloudCredentials = new Entity\CloudCredentials(); $cloudCredentials->accountId = empty($cont->environment) || $cont->environment->id != $envId ? \Scalr_Environment::init()->loadById($envId)->getAccountId() : $cont->environment; $cloudCredentials->envId = $envId; $cloudCredentials->cloud = $cloud; } return $cloudCredentials; }); $container->setShared('saml.config', function ($cont) { $settings = $cont->config->get('scalr.connections.saml');
/** * Gets cloud credentials for listed clouds * * @param string[] $clouds optional Clouds list * @param array $credentialsFilter optional Criteria to filter by CloudCredentials properties * @param array $propertiesFilter optional Criteria to filter by CloudCredentialsProperties * @param bool $cacheResult optional Cache result * * @return Entity\CloudCredentials[] */ public function cloudCredentialsList(array $clouds = null, array $credentialsFilter = [], array $propertiesFilter = [], $cacheResult = true) { if (!is_array($clouds)) { $clouds = (array) $clouds; } $cloudCredentials = new Entity\CloudCredentials(); $cloudCredProps = new Entity\CloudCredentialsProperty(); $envCloudCredentials = new Entity\EnvironmentCloudCredentials(); $criteria = $credentialsFilter; $from[] = empty($criteria[AbstractEntity::STMT_FROM]) ? " {$cloudCredentials->table()} " : $criteria[AbstractEntity::STMT_FROM]; $where = empty($criteria[AbstractEntity::STMT_WHERE]) ? [] : [$criteria[AbstractEntity::STMT_WHERE]]; $from[] = "\n JOIN {$envCloudCredentials->table('cecc')} ON\n {$cloudCredentials->columnId()} = {$envCloudCredentials->columnCloudCredentialsId('cecc')} AND\n {$cloudCredentials->columnCloud()} = {$envCloudCredentials->columnCloud('cecc')}\n "; $where[] = "{$envCloudCredentials->columnEnvId('cecc')} = {$envCloudCredentials->qstr('envId', $this->id)}"; if (!empty($clouds)) { $clouds = implode(", ", array_map(function ($cloud) use($cloudCredentials) { return $cloudCredentials->qstr('cloud', $cloud); }, $clouds)); $where[] = "{$cloudCredentials->columnCloud()} IN ({$clouds})"; } if (!empty($propertiesFilter)) { foreach ($propertiesFilter as $property => $propCriteria) { $alias = "ccp_" . trim($cloudCredentials->db()->qstr($property), "'"); $from[] = "\n LEFT JOIN {$cloudCredProps->table($alias)} ON\n {$cloudCredentials->columnId()} = {$cloudCredProps->columnCloudCredentialsId($alias)} AND\n {$cloudCredProps->columnName($alias)} = {$cloudCredProps->qstr('name', $property)}\n "; $built = $cloudCredProps->_buildQuery($propCriteria, 'AND', $alias); if (!empty($built['where'])) { $where[] = $built['where']; } } } $criteria[AbstractEntity::STMT_FROM] = implode("\n", $from); if (!empty($where)) { $criteria[AbstractEntity::STMT_WHERE] = "(" . implode(") AND (", $where) . ")"; } /* @var $cloudsCredentials Entity\CloudCredentials[] */ $cloudsCredentials = Entity\CloudCredentials::find($criteria); $result = []; foreach ($cloudsCredentials as $cloudCredentials) { $result[$cloudCredentials->cloud] = $cloudCredentials; if ($cacheResult) { $cloudCredentials->bindEnvironment($this->id); $cloudCredentials->cache(); } } return $result; }
/** * {@inheritdoc} * @see Scalr_Model::delete() */ public function delete($id = null) { if ($this->db->GetOne("SELECT COUNT(*) FROM farms WHERE env_id = ?", array($this->id))) { throw new Exception("Cannot remove environment. You need to remove all your farms first."); } if ($this->db->GetOne("SELECT COUNT(*) FROM client_environments WHERE client_id = ?", array($this->clientId)) < 2) { throw new Exception('At least one environment should be in account. You cannot remove the last one.'); } parent::delete(); try { $this->db->Execute("DELETE FROM client_environment_properties WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM apache_vhosts WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM autosnap_settings WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM bundle_tasks WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM dns_zones WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM ec2_ebs WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM elastic_ips WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM farms WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM roles WHERE env_id=?", array($this->id)); $servers = \DBServer::listByFilter(['envId' => $this->id]); foreach ($servers as $server) { /* @var $server \DBServer */ $server->Remove(); } Entity\EnvironmentCloudCredentials::deleteByEnvId($this->id); Entity\CloudCredentials::deleteByEnvId($this->id); $this->db->Execute("DELETE FROM `account_team_envs` WHERE env_id = ?", array($this->id)); } catch (Exception $e) { throw new Exception(sprintf(_("Cannot delete record. Error: %s"), $e->getMessage()), $e->getCode()); } }