Checks whether current install is hosted scalr
public static isHostedScalr ( ) : boolean | ||
return | boolean | Returns true if current install is a hosted Scalr |
public function aboutAction() { $key = "short"; if (!Scalr::isHostedScalr() || $this->user->isScalrAdmin() || $this->request->getHeaderVar('Interface-Beta')) { $key = $this->user->isScalrAdmin() || $this->request->getHeaderVar('Interface-Beta') ? "beta" : "full"; } $this->response->page('ui/core/about.js', Scalr::getContainer()->version($key)); }
public function aboutAction() { $data = array('version' => @file_get_contents(APPPATH . '/etc/version')); if (!Scalr::isHostedScalr() || $this->user->isScalrAdmin() || $this->request->getHeaderVar('Interface-Beta')) { $manifest = @file_get_contents(APPPATH . '/../manifest.json'); if ($manifest) { $info = @json_decode($manifest, true); if ($info) { if (stristr($info['edition'], 'ee')) { $data['edition'] = 'Enterprise Edition'; } else { $data['edition'] = 'Open Source Edition'; } $data['gitFullHash'] = $info['full_revision']; $data['gitDate'] = $info['date']; $data['gitRevision'] = $info['revision']; } } if (!$data['edition']) { @exec("git show --format='%h|%ci|%H' HEAD", $output); $info = @explode("|", $output[0]); $data['gitRevision'] = trim($info[0]); $data['gitDate'] = trim($info[1]); $data['gitFullHash'] = trim($info[2]); @exec("git remote -v", $output2); if (stristr($output2[0], 'int-scalr')) { $data['edition'] = 'Enterprise Edition'; } else { $data['edition'] = 'Open Source Edition'; } } if ($this->user->isScalrAdmin() || $this->request->getHeaderVar('Interface-Beta')) { @exec("git rev-parse --abbrev-ref HEAD", $branch); $data['branch'] = trim($branch[0]); } $data['id'] = SCALR_ID; } $this->response->page('ui/core/about.js', $data); }
/** * Associates cost analytics project with the farm * * It does not perform any actions if cost analytics is disabled * * @param ProjectEntity|string $project The project entity or its identifier * @param bool $ignoreAutomatic optional Should it ignore auto assignment of the default project * @return string Returns identifier of the associated project * @throws InvalidArgumentException * @throws AnalyticsException */ public function setProject($project, $ignoreAutomatic = false) { if (Scalr::getContainer()->analytics->enabled) { if ($project instanceof ProjectEntity) { $projectId = $project->projectId; } else { $projectId = $project; unset($project); } $analytics = Scalr::getContainer()->analytics; if (!$ignoreAutomatic && Scalr::isHostedScalr() && !Scalr::isAllowedAnalyticsOnHostedScalrAccount($this->ClientID)) { //Overrides project with automatic one $projectId = $analytics->usage->autoProject($this->EnvID, $this->ID); } else { if (!empty($projectId)) { //Validates specified project's identifier if (!preg_match('/^[[:xdigit:]-]{36}$/', $projectId)) { throw new InvalidArgumentException(sprintf("Identifier of the cost analytics Project must have valid UUID format. '%s' given.", strip_tags($projectId))); } $project = isset($project) ? $project : $analytics->projects->get($projectId); if (!$project) { throw new AnalyticsException(sprintf("Could not find Project with specified identifier %s.", strip_tags($projectId))); } else { if ($project->ccId !== $this->GetEnvironmentObject()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) { throw new AnalyticsException(sprintf("Invalid project identifier. Parent Cost center of the Project should correspond to the Environment's cost center.")); } } } else { $projectId = null; } } //Sets project to the farm object only if it has been provided if (isset($projectId)) { $project = isset($project) ? $project : $analytics->projects->get($projectId); $oldProjectId = $this->GetSetting(DBFarm::SETTING_PROJECT_ID); $this->SetSetting(DBFarm::SETTING_PROJECT_ID, $project->projectId); //Server property SERVER_PROPERTIES::FARM_PROJECT_ID should be updated //for all running servers associated with the farm. $this->DB->Execute("\n INSERT `server_properties` (`server_id`, `name`, `value`)\n SELECT s.`server_id`, ? AS `name`, ? AS `value`\n FROM `servers` s\n WHERE s.`farm_id` = ?\n ON DUPLICATE KEY UPDATE `value` = ?\n ", [SERVER_PROPERTIES::FARM_PROJECT_ID, $project->projectId, $this->ID, $project->projectId]); //Cost centre should correspond to Project's CC $this->DB->Execute("\n INSERT `server_properties` (`server_id`, `name`, `value`)\n SELECT s.`server_id`, ? AS `name`, ? AS `value`\n FROM `servers` s\n WHERE s.`farm_id` = ?\n ON DUPLICATE KEY UPDATE `value` = ?\n ", [SERVER_PROPERTIES::ENV_CC_ID, $project->ccId, $this->ID, $project->ccId]); if (empty($oldProjectId)) { $analytics->events->fireAssignProjectEvent($this, $project->projectId); } elseif ($oldProjectId !== $projectId) { $analytics->events->fireReplaceProjectEvent($this, $project->projectId, $oldProjectId); } } } return $projectId; }
private function saveAzure() { if (Scalr::isHostedScalr() && !$this->request->getHeaderVar('Interface-Beta')) { $this->response->failure('Azure support available only for Scalr Enterprise Edition.'); return; } $enabled = false; $currentCloudCredentials = $this->env->keychain(SERVER_PLATFORMS::AZURE); if (empty($currentCloudCredentials->id)) { $currentCloudCredentials = $this->makeCloudCredentials(SERVER_PLATFORMS::AZURE, [], Entity\CloudCredentials::STATUS_DISABLED); } /* @var $ccProps Scalr\Model\Collections\SettingsCollection */ $ccProps = $currentCloudCredentials->properties; if ($this->getParam('azure.is_enabled')) { $enabled = true; $tenantName = $this->checkVar(Entity\CloudCredentialsProperty::AZURE_TENANT_NAME, 'string', "Azure Tenant name is required", SERVER_PLATFORMS::AZURE); $ccProps->saveSettings([Entity\CloudCredentialsProperty::AZURE_AUTH_STEP => 0]); if (!count($this->checkVarError)) { $oldTenantName = $ccProps[Entity\CloudCredentialsProperty::AZURE_TENANT_NAME]; $ccProps->saveSettings([Entity\CloudCredentialsProperty::AZURE_TENANT_NAME => $tenantName]); $azure = $this->env->azure(); $ccProps->saveSettings([Entity\CloudCredentialsProperty::AZURE_AUTH_STEP => 1]); $authorizationCode = $ccProps[Entity\CloudCredentialsProperty::AZURE_AUTH_CODE]; $accessToken = $ccProps[Entity\CloudCredentialsProperty::AZURE_ACCESS_TOKEN]; if (empty($authorizationCode) && empty($accessToken) || $oldTenantName != $ccProps[Entity\CloudCredentialsProperty::AZURE_TENANT_NAME]) { $ccProps->saveSettings([Entity\CloudCredentialsProperty::AZURE_AUTH_CODE => false, Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID => false]); $location = $azure->getAuthorizationCodeLocation(); $this->response->data(['authLocation' => $location]); return; } $ccProps->saveSettings([Entity\CloudCredentialsProperty::AZURE_AUTH_STEP => 0]); $subscriptionId = trim($this->checkVar(Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID, 'string', "Azure Subscription id is required", SERVER_PLATFORMS::AZURE)); $params[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID] = $subscriptionId; if (!count($this->checkVarError)) { $oldSubscriptionId = $ccProps[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID]; if ($subscriptionId != $oldSubscriptionId) { $azure->getClientToken(); $objectId = $azure->getAppObjectId(); $params[Entity\CloudCredentialsProperty::AZURE_CLIENT_OBJECT_ID] = $objectId; $contributorRoleId = $azure->getContributorRoleId($subscriptionId); $params[Entity\CloudCredentialsProperty::AZURE_CONTRIBUTOR_ID] = $contributorRoleId; $roleAssignment = $azure->getContributorRoleAssignmentInfo($subscriptionId, $objectId, $contributorRoleId); if (empty($roleAssignment)) { $roleAssignmentId = \Scalr::GenerateUID(); $azure->assignContributorRoleToApp($subscriptionId, $roleAssignmentId, $objectId, $contributorRoleId); } else { $roleAssignmentId = $roleAssignment->name; } $params[Entity\CloudCredentialsProperty::AZURE_ROLE_ASSIGNMENT_ID] = $roleAssignmentId; $ccProps->saveSettings([Entity\CloudCredentialsProperty::AZURE_CLIENT_TOKEN => false, Entity\CloudCredentialsProperty::AZURE_CLIENT_TOKEN_EXPIRE => false]); $azure->getClientToken(Azure::URL_CORE_WINDOWS); $ccProps->saveSettings($params); $providersList = $azure->getProvidersList($subscriptionId); $requiredProviders = ProviderData::getRequiredProviders(); foreach ($providersList as $providerData) { /* @var $providerData ProviderData */ if (in_array($providerData->namespace, $requiredProviders) && $providerData->registrationState == ProviderData::REGISTRATION_STATE_NOT_REGISTERED) { $registerResponse = $azure->registerSubscription($subscriptionId, $providerData->namespace); } } if (!empty($registerResponse)) { do { sleep(5); $provider = $azure->getLocationsList($registerResponse->namespace); } while ($provider->registrationState != ProviderData::REGISTRATION_STATE_REGISTERED); } } $ccProps[Entity\CloudCredentialsProperty::AZURE_AUTH_STEP] = 3; } else { $this->response->failure(); $this->response->data(['errors' => $this->checkVarError]); return; } } else { $this->response->failure(); $this->response->data(['errors' => $this->checkVarError]); return; } } $this->db->BeginTrans(); try { $this->env->enablePlatform(SERVER_PLATFORMS::AZURE, $enabled); if ($enabled) { $currentCloudCredentials->status = Entity\CloudCredentials::STATUS_ENABLED; $currentCloudCredentials->save(); } if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) { $this->user->getAccount()->setSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED, time()); } $this->response->success('Environment saved'); $this->response->data(['enabled' => $enabled]); } catch (Exception $e) { $this->db->RollbackTrans(); throw new Exception(_("Failed to save Azure settings: {$e->getMessage()}")); } $this->db->CommitTrans(); }
public function getBaseConfiguration(DBServer $dbServer, $isHostInit = false, $onlyBase = false) { $configuration = new stdClass(); $dbFarmRole = $dbServer->GetFarmRoleObject(); //Storage if (!$onlyBase) { try { if ($dbFarmRole) { $storage = new FarmRoleStorage($dbFarmRole); $volumes = $storage->getVolumesConfigs($dbServer, $isHostInit); if (!empty($volumes)) { $configuration->volumes = $volumes; } } } catch (Exception $e) { $this->logger->error(new FarmLogMessage($dbServer->farmId, "Cannot init storage: {$e->getMessage()}")); } } // Base try { if ($dbFarmRole) { $scriptingLogTimeout = $dbFarmRole->GetSetting(self::ROLE_BASE_KEEP_SCRIPTING_LOGS_TIME); if (!$scriptingLogTimeout) { $scriptingLogTimeout = 3600; } $configuration->base = new stdClass(); $configuration->base->keepScriptingLogsTime = $scriptingLogTimeout; $configuration->base->abortInitOnScriptFail = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_ABORT_INIT_ON_SCRIPT_FAIL); $configuration->base->disableFirewallManagement = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_DISABLE_FIREWALL_MANAGEMENT); $configuration->base->rebootAfterHostinitPhase = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_REBOOT_AFTER_HOSTINIT_PHASE); $configuration->base->resumeStrategy = PlatformFactory::NewPlatform($dbFarmRole->Platform)->getResumeStrategy(); //Dev falgs for our if (Scalr::isHostedScalr() && $dbServer->envId == 3414) { $configuration->base->unionScriptExecutor = 1; } $governance = new Scalr_Governance($dbFarmRole->GetFarmObject()->EnvID); if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT)) { $hostNameFormat = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT); } else { $hostNameFormat = $dbFarmRole->GetSetting(self::ROLE_BASE_HOSTNAME_FORMAT); } $configuration->base->hostname = !empty($hostNameFormat) ? $dbServer->applyGlobalVarsToValue($hostNameFormat) : ''; if ($configuration->base->hostname != '') { $dbServer->SetProperty(self::SERVER_BASE_HOSTNAME, $configuration->base->hostname); } $apiPort = null; $messagingPort = null; if (!PlatformFactory::isCloudstack($dbFarmRole->Platform)) { $apiPort = $dbFarmRole->GetSetting(self::ROLE_BASE_API_PORT); $messagingPort = $dbFarmRole->GetSetting(self::ROLE_BASE_MESSAGING_PORT); } $configuration->base->apiPort = $apiPort ? $apiPort : 8010; $configuration->base->messagingPort = $messagingPort ? $messagingPort : 8013; } //Update settings $updateSettings = $dbServer->getScalarizrRepository(); $configuration->base->update = new stdClass(); foreach ($updateSettings as $k => $v) { $configuration->base->update->{$k} = $v; } } catch (Exception $e) { } return $configuration; }
private function getCostCenters($requiredCcIds = []) { $ccs = []; if ($this->getContainer()->analytics->enabled) { foreach ($this->getContainer()->analytics->ccs->all(true) as $ccEntity) { /* @var $ccEntity \Scalr\Stats\CostAnalytics\Entity\CostCentreEntity */ $isRequiredCcId = in_array($ccEntity->ccId, $requiredCcIds); if (!$isRequiredCcId && ($ccEntity->archived || Scalr::isHostedScalr())) { continue; } $cc = get_object_vars($ccEntity); $cc['envs'] = \Scalr::getDb()->GetAll("\n SELECT e.id, e.name FROM client_environments e\n JOIN client_environment_properties ep ON ep.env_id = e.id\n WHERE ep.name = ? AND ep.value = ?\n ", [\Scalr_Environment::SETTING_CC_ID, strtolower($ccEntity->ccId)]); $ccs[] = $cc; } } return $ccs; }
protected function run1($stage) { $analytics = \Scalr::getContainer()->analytics; if (!\Scalr::isHostedScalr()) { $this->console->warning("Terminating as this upgrade script is only for Hosted Scalr installation."); return; } $this->console->out("Creates default Cost Center for an each Account"); $rs = $this->db->Execute("SELECT id FROM `clients`"); while ($rec = $rs->FetchRow()) { try { $account = Scalr_Account::init()->loadById($rec['id']); } catch (Exception $e) { continue; } $this->console->out("Processing %s (%d) account...", $account->name, $account->id); //Whether the Account already has account level Cost Center assigned to it $ccs = $account->getCostCenters()->filterByAccountId($account->id); if (count($ccs) > 0) { //We assume that the account has already been initialized continue; } try { //Gets account owner user to be CC Lead $owner = $account->getOwner(); } catch (Exception $e) { continue; } //Creates default Cost Center and Project $cc = $analytics->usage->createHostedScalrAccountCostCenter($account, $owner); //Associates default CC with the account $accountCc = new AccountCostCenterEntity($account->id, $cc->ccId); $accountCc->save(); //Gets project entity /* @var $project ProjectEntity */ $project = $cc->getProjects()[0]; foreach ($this->db->GetAll("SELECT id FROM client_environments WHERE client_id = ?", [$account->id]) as $row) { try { $environment = Scalr_Environment::init()->loadById($row['id']); } catch (Exception $e) { continue; } $this->console->out("- Environment: %s (%d) CC: %s", $environment->name, $environment->id, $cc->ccId); //Creates association $environment->setPlatformConfig([Scalr_Environment::SETTING_CC_ID => $cc->ccId]); foreach ($this->db->GetAll("SELECT id FROM farms WHERE env_id = ?", [$environment->id]) as $r) { try { $farm = DBFarm::LoadByID($r['id']); } catch (Exception $e) { continue; } $this->console->out("- - Farm: %s (%d) Project: %s", $farm->Name, $farm->ID, $project->projectId); //Associates farm with default Project $farm->SetSetting(Entity\FarmSetting::PROJECT_ID, $project->projectId); unset($farm); } $this->console->out("- Updating server properties for environment %s (%d)", $environment->name, $environment->id); $this->db->Execute("\n INSERT `server_properties` (`server_id`, `name`, `value`)\n SELECT s.`server_id`, ?, ? FROM `servers` s WHERE s.env_id = ?\n ON DUPLICATE KEY UPDATE `value` = ?\n ", [SERVER_PROPERTIES::FARM_PROJECT_ID, $project->projectId, $environment->id, $project->projectId]); $this->db->Execute("\n INSERT `server_properties` (`server_id`, `name`, `value`)\n SELECT s.`server_id`, ?, ? FROM `servers` s WHERE s.env_id = ?\n ON DUPLICATE KEY UPDATE `value` = ?\n ", [SERVER_PROPERTIES::ENV_CC_ID, $cc->ccId, $environment->id, $cc->ccId]); unset($environment); } unset($ccs); unset($owner); unset($account); } }
public function getContext() { $data = array(); if ($this->user) { $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => $this->getEnvironment() ? $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS) : '', 'type' => $this->user->getType()); $envVars = json_decode($data['user']['envVars'], true); $betaMode = $envVars && $envVars['beta'] == 1; if (!$this->user->isAdmin()) { $data['farms'] = $this->db->getAll('SELECT id, name FROM farms WHERE env_id = ? ORDER BY name', array($this->getEnvironmentId())); if ($this->user->getAccountId() != 0) { $data['flags'] = $this->user->getAccount()->getFeaturesList(); $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false; } else { $data['flags'] = array(); } $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled'); $data['flags']['featureUsersPermissions'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_USERS_PERMISSIONS); $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url'); $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url'); if ($data['flags']['supportUrl'] == '/core/support') { $data['flags']['supportUrl'] .= '?X-Requested-Token=' . Scalr_Session::getInstance()->getToken(); } $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true); if ($this->user->isAccountOwner()) { if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) { if (count($this->environment->getEnabledPlatforms()) == 0) { $data['flags']['needEnvConfig'] = Scalr_Environment::init()->loadDefault($this->user->getAccountId())->id; } } } $data['environments'] = $this->user->getEnvironments(); if ($this->getEnvironment() && $this->user->isTeamOwner()) { $data['user']['isTeamOwner'] = true; } } $data['platforms'] = array(); $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds'); foreach (SERVER_PLATFORMS::getList() as $platform => $platformName) { if (!in_array($platform, $allowedClouds) || $platform == SERVER_PLATFORMS::UCLOUD && !$this->request->getHeaderVar('Interface-Beta')) { continue; } $data['platforms'][$platform] = array('public' => PlatformFactory::isPublic($platform), 'enabled' => $this->user->isAdmin() ? true : !!$this->environment->isPlatformEnabled($platform), 'name' => $platformName); if (!$this->user->isAdmin()) { if ($platform == SERVER_PLATFORMS::EC2 && $this->environment->status == Scalr_Environment::STATUS_INACTIVE && $this->environment->getPlatformConfigValue('system.auto-disable-reason')) { $data['platforms'][$platform]['config'] = array('autoDisabled' => true); } if (PlatformFactory::isOpenstack($platform) && $data['platforms'][$platform]['enabled']) { $data['platforms'][$platform]['config'] = array(OpenstackPlatformModule::EXT_SECURITYGROUPS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_SECURITYGROUPS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_LBAAS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_LBAAS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_FLOATING_IPS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_FLOATING_IPS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_CINDER_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_CINDER_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_SWIFT_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_SWIFT_ENABLED, $this->getEnvironment(), false)); } } } $data['flags']['uiStorageTime'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME); $data['flags']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); $data['flags']['allowManageAnalytics'] = (bool) Scalr::isAllowedAnalyticsOnHostedScalrAccount($this->environment->clientId); } if ($this->user) { $data['tags'] = Tag::getAll($this->user->getAccountId()); } $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode'); $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken(); $data['flags']['hostedScalr'] = (bool) Scalr::isHostedScalr(); $data['flags']['analyticsEnabled'] = $this->getContainer()->analytics->enabled; return $data; }
/** * Gets the list of the cost centres * * @return array Returns the list of the cost centres */ private function getNodesList($period, $ccId = null, $query = null) { $nodes = array(); $isHostedScalr = \Scalr::isHostedScalr(); if (!$ccId) { $criteria = null; if ($query) { $criteria = array('name' => array('$like' => array('%' . $query . '%'))); foreach (ProjectEntity::find($criteria) as $item) { /* @var $item ProjectEntity */ if (!isset($nodes[$item->ccId])) { $costCenter = $this->getContainer()->analytics->ccs->get($item->ccId); if ($isHostedScalr && $costCenter === null) { continue; } $nodes[$item->ccId] = $this->getCostCenterData($costCenter, $period); $nodes[$item->ccId]['nodes'] = array(); } $nodes[$item->ccId]['nodes'][] = $this->getProjectData($item, $period); } foreach (CostCentreEntity::find($criteria) as $item) { /* @var $item CostCentreEntity */ if (!isset($nodes[$item->ccId])) { $nodes[$item->ccId] = $this->getCostCenterData($item, $period); } $nodes[$item->ccId]['nodes'] = array(); foreach (ProjectEntity::findByCcId($item->ccId) as $projectItem) { $nodes[$item->ccId]['nodes'][] = $this->getProjectData($projectItem, $period); } } } else { foreach (CostCentreEntity::all() as $item) { /* @var $item CostCentreEntity */ $nodes[$item->ccId] = $this->getCostCenterData($item, $period); } } } else { $cc = $this->getContainer()->analytics->ccs->get($ccId); if ($cc instanceof CostCentreEntity) { foreach ($cc->getProjects() as $item) { $nodes[$item->projectId] = $this->getProjectData($item, $period); } } } return array_values($nodes); }
/** * @param int $farmId optional * @param int $roleId optional * @param string $scalrPageHash optional * @param string $scalrPageUiHash optional * @throws Scalr_Exception_InsufficientPermissions */ public function xGetFarmAction($farmId = null, $roleId = null, $scalrPageHash = null, $scalrPageUiHash = null) { if ($scalrPageHash && $scalrPageHash != $this->calcFarmDesignerHash()) { $this->response->data(['scalrPageHashMismatch' => true]); return; } if ($scalrPageUiHash && $scalrPageUiHash != $this->response->pageUiHash()) { $this->response->data(['scalrPageUiHashMismatch' => true]); return; } $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true)); unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]); unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]); unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]); //platforms list $platforms = self::loadController('Platforms')->getEnabledPlatforms(); if (empty($platforms)) { throw new Exception('Before building new farm you need to configure environment and setup cloud credentials'); } $moduleParams['categories'] = self::loadController('Roles')->listRoleCategories(true, true); $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2); if ($moduleParams['farmVpcEc2Enabled']) { $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false); } if ($farmId) { $this->request->checkPermissions(DBFarm::LoadByID($farmId)->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE); $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms'); $moduleParams['farm'] = $c->getFarm2($farmId); } else { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); // TODO: remove hack, do better $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM); $moduleParams['farmVariables'] = $vars->getValues(); } $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'scripting', 'ec2', 'openstack', 'gce', 'azure', 'security', 'devel', 'storage', 'variables', 'advanced', 'chef'); //deprecated tabs if (\Scalr::config('scalr.ui.show_deprecated_features')) { $moduleParams['tabs'][] = 'ebs'; } $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter'); $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->keychain(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => file_get_contents(APPPATH . '/templates/services/nginx/server_section.tpl'), 'server_section_ssl' => file_get_contents(APPPATH . '/templates/services/nginx/server_section_ssl.tpl'))); $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy'); $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo'); if (Scalr::isHostedScalr()) { $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = ['latest' => Utils::getScalarizrUpdateRepoTitle('latest')]; if ($this->user->getAccount()->priority == 100) { $moduleParams['tabParams']['scalr.scalarizr_update.repos']['stable'] = Utils::getScalarizrUpdateRepoTitle('stable'); } } else { $repos = array_keys(\Scalr::config('scalr.scalarizr_update.repos')); $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_combine($repos, $repos); } $moduleParams['tabParams']['scalr.scalarizr_update.devel_repos'] = is_array(\Scalr::config('scalr.scalarizr_update.devel_repos')) ? array_keys(\Scalr::config('scalr.scalarizr_update.devel_repos')) : []; $moduleParams['tabParams']['scalr.aws.ec2.limits.security_groups_per_instance'] = \Scalr::config('scalr.aws.ec2.limits.security_groups_per_instance'); $moduleParams['metrics'] = Entity\ScalingMetric::getList($this->getEnvironmentId()); $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones(); $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE); if ($moduleParams['farm']['farm']['ownerEditable']) { $moduleParams['usersList'] = []; foreach (Entity\Account\User::findByAccountId($this->user->getAccountId()) as $user) { $moduleParams['usersList'][] = ['id' => $user->id, 'email' => $user->email]; } } $defaultFarmRoleSecurityGroups = array('default'); if (\Scalr::config('scalr.aws.security_group_name')) { $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name'); } $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups), 'base.abort_init_on_script_fail' => \Scalr::config('scalr.system.scripting.default_abort_init_on_script_fail') ? 1 : 0, 'base.disable_firewall_management' => \Scalr::config('scalr.system.default_disable_firewall_management') ? 1 : 0); //cost analytics if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) { $farmCostData = $this->getFarmCostData($farmId); $moduleParams['analytics'] = $farmCostData['analytics']; if ($farmId) { $moduleParams['farm']['farm']['projectId'] = $farmCostData['projectId']; $moduleParams['analytics']['farmCostMetering'] = $farmCostData['farmCostMetering']; } } $moduleParams['farmLaunchPermission'] = $farmId ? $moduleParams['farm']['farm']['launchPermission'] : $this->request->isAllowed([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS], Acl::PERM_FARMS_LAUNCH_TERMINATE); $this->response->data($moduleParams); }
/** * @param DBServer $dbServer * @param bool $cached check only cached information * @param int $timeout * @return array|null */ public function getServerStatus(DBServer $dbServer, $cached = true, $timeout = 0) { if ($dbServer->status == SERVER_STATUS::RUNNING && ($dbServer->IsSupported('0.8') && $dbServer->osType == 'linux' || $dbServer->IsSupported('0.19') && $dbServer->osType == 'windows')) { if ($cached && !$dbServer->IsSupported('2.7.7')) { return ['status' => 'statusNoCache', 'error' => "<span style='color:gray;'>Scalarizr is checking actual status</span>"]; } try { $scalarizr = $dbServer->scalarizrUpdateClient->getStatus($cached); try { if ($dbServer->farmRoleId != 0) { $scheduledOn = $dbServer->GetFarmRoleObject()->GetSetting('scheduled_on'); } } catch (Exception $e) { } $nextUpdate = null; if ($scalarizr->candidate && $scalarizr->installed != $scalarizr->candidate) { $nextUpdate = ['candidate' => htmlspecialchars($scalarizr->candidate), 'scheduledOn' => $scheduledOn ? Scalr_Util_DateTime::convertTzFromUTC($scheduledOn) : null]; } return ['status' => htmlspecialchars($scalarizr->service_status), 'version' => htmlspecialchars($scalarizr->installed), 'candidate' => htmlspecialchars($scalarizr->candidate), 'repository' => Scalr::isHostedScalr() ? Utils::getScalarizrUpdateRepoTitle($scalarizr->repository) : ucfirst(htmlspecialchars($scalarizr->repository)), 'lastUpdate' => ['date' => $scalarizr->executed_at ? Scalr_Util_DateTime::convertTzFromUTC($scalarizr->executed_at) : "", 'error' => nl2br(htmlspecialchars($scalarizr->error))], 'nextUpdate' => $nextUpdate, 'fullInfo' => $scalarizr]; } catch (Exception $e) { if (stristr($e->getMessage(), "Method not found")) { return ['status' => 'statusNotAvailable', 'error' => "<span style='color:red;'>Scalarizr status is not available, because scalr-upd-client installed on this server is too old.</span>"]; } else { return ['status' => 'statusNotAvailable', 'error' => "<span style='color:red;'>Scalarizr status is not available: {$e->getMessage()}</span>"]; } } } }
/** * @param int $uiStorageTime optional * @return array */ public function getContext($uiStorageTime = 0) { $data = array(); if ($this->user) { $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => '', 'type' => $this->user->getType(), 'settings' => [Scalr_Account_User::SETTING_UI_TIMEZONE => $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE), UserSetting::NAME_UI_ANNOUNCEMENT_TIME => $this->getUser()->getSetting(UserSetting::NAME_UI_ANNOUNCEMENT_TIME)]); if ($this->getEnvironment()) { $data['user']['envVars'] = $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS); } else { if ($this->user->getAccountId()) { $data['user']['envVars'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_UI_VARS); } } if ($uiStorageTime > 0 && $uiStorageTime < $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME) && !Scalr_Session::getInstance()->isVirtual()) { $data['user']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); } $envVars = json_decode($data['user']['envVars'], true); $betaMode = $envVars && $envVars['beta'] == 1; if (!$this->user->isAdmin()) { $data['flags'] = []; if ($this->user->getAccountId() != 0) { $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false; } $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled'); $data['flags']['showDeprecatedFeatures'] = \Scalr::config('scalr.ui.show_deprecated_features'); $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true); if (!$this->user->isAccountOwner()) { $data['user']['accountOwnerName'] = $this->user->getAccount()->getOwner()->getEmail(); } $data['environments'] = $this->user->getEnvironments(); if ($this->user->isAccountOwner()) { if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) { $data['flags']['needEnvConfig'] = true; } } if ($this->request->getScope() == 'environment') { $sql = "SELECT id, name FROM farms f WHERE env_id = ? AND " . $this->request->getFarmSqlQuery(); $args = [$this->getEnvironmentId()]; $sql .= " ORDER BY name"; $data['farms'] = $this->db->getAll($sql, $args); if ($this->getEnvironment() && $this->user->isTeamOwner()) { $data['user']['isTeamOwner'] = true; } } } $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url'); $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url'); if ($data['flags']['supportUrl'] == '/core/support') { if ($this->user->isAdmin()) { unset($data['flags']['supportUrl']); } else { $data['flags']['supportUrl'] .= '?X-Requested-Token=' . Scalr_Session::getInstance()->getToken(); } } //OS $data['os'] = []; foreach (Os::find() as $os) { /* @var $os Os */ $data['os'][] = ['id' => $os->id, 'family' => $os->family, 'name' => $os->name, 'generation' => $os->generation, 'version' => $os->version, 'status' => $os->status]; } $data['defaults'] = (new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(true), ScopeInterface::SCOPE_ENVIRONMENT))->getUiDefaults(); $data['platforms'] = []; $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds'); if ($this->user->getAccountId() == 263) { array_push($allowedClouds, SERVER_PLATFORMS::VERIZON); } $platforms = SERVER_PLATFORMS::getList(); if (!($this->request->getHeaderVar('Interface-Beta') || $betaMode)) { $platforms = array_intersect_key($platforms, array_flip($allowedClouds)); } $environment = $this->getEnvironment(); if (!empty($environment)) { $cloudsCredentials = $environment->cloudCredentialsList(array_keys($platforms)); } foreach ($platforms as $platform => $platformName) { if (!in_array($platform, $allowedClouds) && !$this->request->getHeaderVar('Interface-Beta') && !$betaMode) { continue; } $data['platforms'][$platform] = array('public' => PlatformFactory::isPublic($platform), 'enabled' => $this->user->isAdmin() || $this->request->getScope() != 'environment' ? true : isset($cloudsCredentials[$platform]) && $cloudsCredentials[$platform]->isEnabled(), 'name' => $platformName); if (!($this->user->isAdmin() || $this->request->getScope() != 'environment')) { if ($platform == SERVER_PLATFORMS::EC2 && $this->environment->status == Scalr_Environment::STATUS_INACTIVE && $this->environment->getPlatformConfigValue('system.auto-disable-reason')) { $data['platforms'][$platform]['config'] = array('autoDisabled' => true); } if (PlatformFactory::isOpenstack($platform) && $data['platforms'][$platform]['enabled']) { $ccProps = $cloudsCredentials[$platform]->properties; $data['platforms'][$platform]['config'] = [CloudCredentialsProperty::OPENSTACK_EXT_SECURITYGROUPS_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_SECURITYGROUPS_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_LBAAS_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_LBAAS_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_FLOATING_IPS_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_FLOATING_IPS_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_CINDER_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_CINDER_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_SWIFT_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_SWIFT_ENABLED]]; } } } $data['flags']['uiStorageTime'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME); $data['flags']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); $data['flags']['allowManageAnalytics'] = $this->user->getAccountId() && Scalr::isAllowedAnalyticsOnHostedScalrAccount($this->user->getAccountId()); $data['flags']['hostedScalr'] = (bool) Scalr::isHostedScalr(); $data['flags']['analyticsEnabled'] = $this->getContainer()->analytics->enabled; $data['flags']['apiEnabled'] = (bool) \Scalr::config('scalr.system.api.enabled'); $data['flags']['dnsGlobalEnabled'] = (bool) \Scalr::config('scalr.dns.global.enabled'); $data['flags']['allowBetaEbsTypes'] = SCALR_ID == 'gdp-aws-east'; $data['scope'] = $this->request->getScope(); if ($this->request->getScope() == 'environment') { $governance = new Scalr_Governance($this->getEnvironmentId()); $data['governance'] = $governance->getValues(true); } } if ($this->user) { $data['tags'] = Tag::getAll($this->user->getAccountId()); } $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode'); $data['flags']['recaptchaPublicKey'] = $this->getContainer()->config->get('scalr.ui.recaptcha.public_key'); $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken(); $data['flags']['loginWarning'] = $this->getContainer()->config->get('scalr.ui.login_warning'); return $data; }
public function getContext($uiStorageTime = 0) { $data = array(); if ($this->user) { $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => $this->getEnvironment() ? $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS) : '', 'type' => $this->user->getType(), 'settings' => [Scalr_Account_User::VAR_SSH_CONSOLE_LAUNCHER => $this->user->getVar(Scalr_Account_User::VAR_SSH_CONSOLE_LAUNCHER)]); if ($uiStorageTime > 0 && $uiStorageTime < $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME) && !Scalr_Session::getInstance()->isVirtual()) { $data['user']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); } $envVars = json_decode($data['user']['envVars'], true); $betaMode = $envVars && $envVars['beta'] == 1; if (!$this->user->isAdmin()) { $data['flags'] = []; if ($this->user->getAccountId() != 0) { $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false; } $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled'); $data['flags']['showDeprecatedFeatures'] = \Scalr::config('scalr.ui.show_deprecated_features'); $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url'); $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url'); if ($data['flags']['supportUrl'] == '/core/support') { $data['flags']['supportUrl'] .= '?X-Requested-Token=' . Scalr_Session::getInstance()->getToken(); } $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true); if (!$this->user->isAccountOwner()) { $data['user']['accountOwnerName'] = $this->user->getAccount()->getOwner()->getEmail(); } $data['environments'] = $this->user->getEnvironments(); if ($this->user->isAccountOwner()) { if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) { $data['flags']['needEnvConfig'] = true; } } if ($this->request->getScope() == 'environment') { $sql = 'SELECT id, name FROM farms WHERE env_id = ?'; $args = [$this->getEnvironmentId()]; list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args); $sql .= ' ORDER BY name'; $data['farms'] = $this->db->getAll($sql, $args); if ($this->getEnvironment() && $this->user->isTeamOwner()) { $data['user']['isTeamOwner'] = true; } } } //OS $data['os'] = []; foreach (Os::find([['status' => Os::STATUS_ACTIVE]]) as $os) { /* @var $os Os */ $data['os'][] = ['id' => $os->id, 'family' => $os->family, 'name' => $os->name, 'generation' => $os->generation, 'version' => $os->version]; } $data['platforms'] = []; $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds'); foreach (SERVER_PLATFORMS::getList() as $platform => $platformName) { if ($this->user->getAccountId() == 263) { array_push($allowedClouds, SERVER_PLATFORMS::VERIZON); } if (!in_array($platform, $allowedClouds) && !$this->request->getHeaderVar('Interface-Beta')) { continue; } $data['platforms'][$platform] = array('public' => PlatformFactory::isPublic($platform), 'enabled' => $this->user->isAdmin() || $this->request->getScope() != 'environment' ? true : !!$this->environment->isPlatformEnabled($platform), 'name' => $platformName); if (!($this->user->isAdmin() || $this->request->getScope() != 'environment')) { if ($platform == SERVER_PLATFORMS::EC2 && $this->environment->status == Scalr_Environment::STATUS_INACTIVE && $this->environment->getPlatformConfigValue('system.auto-disable-reason')) { $data['platforms'][$platform]['config'] = array('autoDisabled' => true); } if (PlatformFactory::isOpenstack($platform) && $data['platforms'][$platform]['enabled']) { $data['platforms'][$platform]['config'] = array(OpenstackPlatformModule::EXT_SECURITYGROUPS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_SECURITYGROUPS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_LBAAS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_LBAAS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_FLOATING_IPS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_FLOATING_IPS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_CINDER_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_CINDER_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_SWIFT_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_SWIFT_ENABLED, $this->getEnvironment(), false)); } } } $data['flags']['uiStorageTime'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME); $data['flags']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); $data['flags']['allowManageAnalytics'] = (bool) Scalr::isAllowedAnalyticsOnHostedScalrAccount($this->environment->clientId); $data['scope'] = $this->request->getScope(); if ($this->request->getScope() == 'environment') { $governance = new Scalr_Governance($this->getEnvironmentId()); $data['governance'] = $governance->getValues(true); } } if ($this->user) { $data['tags'] = Tag::getAll($this->user->getAccountId()); } $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode'); $data['flags']['recaptchaPublicKey'] = $this->getContainer()->config->get('scalr.ui.recaptcha.public_key'); $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken(); $data['flags']['hostedScalr'] = (bool) Scalr::isHostedScalr(); $data['flags']['analyticsEnabled'] = $this->getContainer()->analytics->enabled; $data['flags']['apiEnabled'] = (bool) \Scalr::config('scalr.system.api.enabled'); return $data; }