config() public static method

Gets config value
public static config ( string $name ) : mixed
$name string An option name
return mixed Returns configuration value for the specified key
Example #1
0
 public function defaultAction()
 {
     if ($this->user->getType() == Scalr_Account_User::TYPE_SCALR_ADMIN) {
         $this->response->page('ui/dashboard/admin.js');
     } else {
         if ($this->user->getType() == Scalr_Account_User::TYPE_FIN_ADMIN) {
             self::loadController('Dashboard', 'Scalr_UI_Controller_Admin_Analytics')->defaultAction();
         } else {
             $loadJs = array('ui/dashboard/columns.js');
             $scope = $this->request->getScope();
             $cloudynEnabled = \Scalr::config('scalr.cloudyn.master_email') ? true : false;
             $billingEnabled = \Scalr::config('scalr.billing.enabled') ? true : false;
             $panel = $this->user->getDashboard($this->getEnvironmentId(true));
             if (empty($panel['configuration'])) {
                 // default configurations
                 $client = Client::Load($this->user->getAccountId());
                 if ($client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
                     // old customer
                     if ($scope == 'account') {
                         $panel['configuration'] = array(array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))), array(array('name' => 'dashboard.environments')));
                         if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) {
                             array_unshift($panel['configuration'], array(array('name' => 'dashboard.billing')));
                         }
                     } else {
                         $panel['configuration'] = array(array(array('name' => 'dashboard.status'), array('name' => 'dashboard.addfarm')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))), array(array('name' => 'dashboard.lasterrors', 'params' => array('errorCount' => 10))));
                     }
                 } else {
                     if ($scope == 'account') {
                         // new customer
                         $panel['configuration'] = array(array(array('name' => 'dashboard.newuser')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))));
                         if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) {
                             array_unshift($panel['configuration'][1], array('name' => 'dashboard.billing'));
                         }
                     } else {
                         // new customer
                         $panel['configuration'] = array(array(array('name' => 'dashboard.addfarm')), array(array('name' => 'dashboard.newuser')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))));
                     }
                 }
                 $this->user->setDashboard($this->getEnvironmentId(true), $panel);
                 $panel = $this->user->getDashboard($this->getEnvironmentId(true));
             }
             // section for adding required widgets
             if ($scope == 'environment') {
                 if ($cloudynEnabled && !in_array('cloudynInstalled', $panel['flags']) && !in_array('dashboard.cloudyn', $panel['widgets']) && !!$this->environment->isPlatformEnabled(SERVER_PLATFORMS::EC2)) {
                     if (!isset($panel['configuration'][0])) {
                         $panel['configuration'][0] = array();
                     }
                     array_unshift($panel['configuration'][0], array('name' => 'dashboard.cloudyn'));
                     $panel['flags'][] = 'cloudynInstalled';
                     $this->user->setDashboard($this->getEnvironmentId(), $panel);
                     $panel = $this->user->getDashboard($this->getEnvironmentId());
                 }
             }
             $panel = $this->fillDash($panel);
             $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
             $monitoringUrl = "{$conf['scheme']}://{$conf['host']}:{$conf['port']}";
             $this->response->page('ui/dashboard/view.js', array('panel' => $panel, 'flags' => array('cloudynEnabled' => $cloudynEnabled, 'billingEnabled' => $billingEnabled), 'params' => array('monitoringUrl' => $monitoringUrl)), $loadJs, array('ui/dashboard/view.css', 'ui/analytics/analytics.css'));
         }
     }
 }
 public function ListGlobalVariables()
 {
     $ResponseDOMDocument = $this->CreateResponse();
     $configNode = $ResponseDOMDocument->createElement("variables");
     $globalVariables = new Scalr_Scripting_GlobalVariables($this->DBServer->envId, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     $vars = $globalVariables->listVariables($this->DBServer->roleId, $this->DBServer->farmId, $this->DBServer->farmRoleId);
     foreach ($vars as $key => $value) {
         $settingNode = $ResponseDOMDocument->createElement("variable", $value);
         $settingNode->setAttribute("name", $key);
         $configNode->appendChild($settingNode);
     }
     $formats = \Scalr::config("scalr.system.global_variables.format");
     foreach ($this->DBServer->GetScriptingVars() as $name => $value) {
         $name = "SCALR_" . strtoupper($name);
         $value = trim($value);
         if (isset($formats[$name])) {
             $value = @sprintf($formats[$name], $value);
         }
         $settingNode = $ResponseDOMDocument->createElement("variable", $value);
         $settingNode->setAttribute("name", $name);
         $configNode->appendChild($settingNode);
     }
     $ResponseDOMDocument->documentElement->appendChild($configNode);
     return $ResponseDOMDocument;
 }
Example #3
0
 public static function setupScalrAgent(\DBServer $dbServer)
 {
     $baseurl = \Scalr::config('scalr.endpoint.scheme') . "://" . \Scalr::config('scalr.endpoint.host');
     $env = $dbServer->GetEnvironmentObject();
     $azure = $env->azure();
     $branch = $dbServer->getScalarizrRepository()['repository'];
     $develRepos = \Scalr::getContainer()->config->get('scalr.scalarizr_update.devel_repos');
     $scmBranch = $dbServer->GetFarmRoleObject()->GetSetting('user-data.scm_branch');
     if ($scmBranch != '' && $develRepos) {
         $branch = $dbServer->GetFarmRoleObject()->GetSetting('base.devel_repository');
         $scmBranch = "{$scmBranch}/";
     } else {
         $scmBranch = '';
     }
     if ($dbServer->osType == 'linux') {
         $extensionProperties = new ResourceExtensionProperties('Microsoft.OSTCExtensions', 'CustomScriptForLinux', '1.2');
         $extensionProperties->setSettings(['commandToExecute' => "bash -c 'curl -k -L \"{$baseurl}/public/linux/{$branch}/azure/{$scmBranch}install_scalarizr.sh\" | bash && service scalr-upd-client start'"]);
     } else {
         $extensionProperties = new ResourceExtensionProperties('Microsoft.Compute', 'CustomScriptExtension', '1.4');
         $extensionProperties->setSettings(["commandToExecute" => "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex ((new-object net.webclient).DownloadString('{$baseurl}/public/windows/{$branch}/{$scmBranch}install_scalarizr.ps1')); start-service ScalrUpdClient\""]);
     }
     $createExtension = new CreateResourceExtension('scalarizr', $dbServer->cloudLocation, $extensionProperties);
     try {
         $response = $azure->compute->resourceExtension->create($env->keychain(SERVER_PLATFORMS::AZURE)->properties[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID], $dbServer->GetProperty(\AZURE_SERVER_PROPERTIES::RESOURCE_GROUP), $dbServer->GetProperty(\AZURE_SERVER_PROPERTIES::SERVER_NAME), $createExtension);
         \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->info(new \FarmLogMessage($dbServer, sprintf(_("Created azure resource extension to install and launch scalr agent"))));
         $dbServer->SetProperty(\AZURE_SERVER_PROPERTIES::SZR_EXTENSION_DEPLOYED, 1);
     } catch (\Exception $e) {
         \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->fatal(new \FarmLogMessage($dbServer, sprintf(_("Unable to create azure resource extension to install and launch scalr agent: %s"), $e->getMessage())));
     }
 }
Example #4
0
 public function xRequestResultAction()
 {
     $this->request->defineParams(array('requests' => array('type' => 'json'), 'decision'));
     if (!in_array($this->getParam('decision'), array(FarmLease::STATUS_APPROVE, FarmLease::STATUS_DECLINE))) {
         throw new Scalr_Exception_Core('Wrong status');
     }
     foreach ($this->getParam('requests') as $id) {
         $req = $this->db->GetRow('SELECT * FROM farm_lease_requests WHERE id = ? LIMIT 1', array($id));
         if ($req) {
             $dbFarm = DBFarm::LoadByID($req['farm_id']);
             $this->user->getPermissions()->validate($dbFarm);
             $this->db->Execute('UPDATE farm_lease_requests SET status = ?, answer_comment = ?, answer_user_id = ? WHERE id = ?', array($this->getParam('decision'), $this->getParam('comment'), $this->user->getId(), $id));
             try {
                 $mailer = Scalr::getContainer()->mailer;
                 if ($dbFarm->ownerId) {
                     $user = Entity\Account\User::findPk($dbFarm->ownerId);
                     if (\Scalr::config('scalr.auth_mode') == 'ldap') {
                         $email = $user->getSetting(Entity\Account\User\UserSetting::NAME_LDAP_EMAIL);
                         if (!$email) {
                             $email = $user->email;
                         }
                     } else {
                         $email = $user->email;
                     }
                     $mailer->addTo($email);
                 } else {
                     $mailer = null;
                 }
             } catch (Exception $e) {
                 $mailer = null;
             }
             if ($this->getParam('decision') == FarmLease::STATUS_APPROVE) {
                 if ($req['request_days'] > 0) {
                     $dt = $dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE);
                     $dt = new DateTime($dt);
                     $dt->add(new DateInterval('P' . $req['request_days'] . 'D'));
                     $dbFarm->SetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'));
                     $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, null);
                     if ($mailer) {
                         $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_approve.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{date}}' => $dt->format('M j, Y'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id));
                     }
                 } else {
                     $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, '');
                     $dbFarm->SetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE, '');
                     $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, '');
                     if ($mailer) {
                         $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_forever.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id));
                     }
                 }
             } else {
                 $dt = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE));
                 SettingEntity::increase(SettingEntity::LEASE_DECLINED_REQUEST);
                 if ($mailer) {
                     $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_decline.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{date}}' => $dt->format('M j, Y'), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id));
                 }
             }
         }
     }
     $this->response->success();
 }
Example #5
0
 /**
  * @functional
  */
 public function testUser()
 {
     $userId = \Scalr::config('scalr.phpunit.userid');
     $envId = \Scalr::config('scalr.phpunit.envid');
     if (empty($userId) || empty($envId)) {
         $this->markTestSkipped("This test requires valid database connection so it's considered to be functional.");
     }
     /* @var $user User */
     $user = User::findOne([['id' => $userId]]);
     $this->assertInstanceOf('Scalr\\Model\\Entity\\Account\\User', $user);
     $email = $user->getSetting(UserSetting::NAME_GRAVATAR_EMAIL);
     $this->assertNotEmpty($email);
     $environment = Environment::findPk($envId);
     $this->assertInstanceOf('Scalr\\Model\\Entity\\Account\\Environment', $environment);
     $entityIterator = User::result(User::RESULT_ENTITY_ITERATOR)->find(null, null, null, 10);
     $this->assertInstanceOf('Scalr\\Model\\Collections\\EntityIterator', $entityIterator);
     $this->assertNotEmpty($entityIterator->count());
     $this->assertNotEmpty($entityIterator->getArrayCopy());
     foreach ($entityIterator->filterByType(User::TYPE_ACCOUNT_OWNER) as $item) {
         $this->assertEquals(User::TYPE_ACCOUNT_OWNER, $item->type);
     }
     foreach (User::result(User::RESULT_ENTITY_ITERATOR)->findByType(User::TYPE_SCALR_ADMIN) as $item) {
         $this->assertEquals(User::TYPE_SCALR_ADMIN, $item->type);
     }
     $arrayCollection = User::result(User::RESULT_ENTITY_COLLECTION)->find(null, null, null, 10);
     $this->assertInstanceOf('Scalr\\Model\\Collections\\ArrayCollection', $arrayCollection);
     $this->assertNotEmpty($arrayCollection->count());
     $this->assertNotEmpty($arrayCollection->getArrayCopy());
     $rs = User::result(User::RESULT_RAW)->find(null, null, null, 10);
     $this->assertInstanceOf('ADORecordSet', $rs);
     foreach ($rs as $item) {
         $this->assertNotEmpty($item);
         $this->assertInternalType('array', $item);
     }
 }
Example #6
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     if (self::isSkippedFunctionalTest(self::TEST_TYPE_UI)) {
         return;
     }
     $db = \Scalr::getDb();
     self::deleteTestVariables();
     $envId = \Scalr::config('scalr.phpunit.envid');
     if (!$envId) {
         return;
     }
     $env = \Scalr_Environment::init()->loadById($envId);
     self::$vars[ScopeInterface::SCOPE_SCALR] = new Scalr_Scripting_GlobalVariables();
     self::$vars[ScopeInterface::SCOPE_ACCOUNT] = new Scalr_Scripting_GlobalVariables($env->clientId, 0, ScopeInterface::SCOPE_ACCOUNT);
     self::$vars[ScopeInterface::SCOPE_ENVIRONMENT] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_ENVIRONMENT);
     self::$args[ScopeInterface::SCOPE_SCALR] = self::$args[ScopeInterface::SCOPE_ACCOUNT] = self::$args[ScopeInterface::SCOPE_ENVIRONMENT] = [0, 0, 0, ''];
     /* @var $farm Farm */
     $farm = Farm::findOne([['envId' => $env->id]]);
     if ($farm) {
         self::$vars[ScopeInterface::SCOPE_FARM] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_FARM);
         self::$args[ScopeInterface::SCOPE_FARM] = [0, $farm->id, 0, ''];
         /* @var $farmRole FarmRole */
         $farmRole = FarmRole::findOne([['farmId' => $farm->id]]);
         if ($farmRole) {
             self::$vars[ScopeInterface::SCOPE_ROLE] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_ROLE);
             self::$args[ScopeInterface::SCOPE_ROLE] = [$farmRole->roleId, 0, 0, ''];
             self::$vars[ScopeInterface::SCOPE_FARMROLE] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_FARMROLE);
             self::$args[ScopeInterface::SCOPE_FARMROLE] = [$farmRole->roleId, $farm->id, $farmRole->id, ''];
         }
     }
 }
Example #7
0
 /**
  * Constructor. Instantiates ApiLogger, prepares backend
  *
  * @param ApiLoggerConfiguration $config  Api logger config object
  */
 public function __construct($config)
 {
     parent::__construct(\Scalr::config('scalr.logger.api'));
     $this->ipAddress = $config->ipAddress;
     $this->requestId = $config->requestId;
     $this->requestType = $config->requestType;
 }
Example #8
0
 /**
  * Provider of the instances for the functional tests
  */
 public function providerRs()
 {
     $data = \Scalr::config('scalr.phpunit.cloudstack.platforms');
     if (empty($data) || !is_array($data)) {
         return array(array(self::EMPTY_CONFIG, 'jp-east-t1v', '2530', '24'));
     }
     return $data;
 }
Example #9
0
 /**
  * Provider of the instances for the functional tests
  */
 public function providerRs()
 {
     $data = \Scalr::config('scalr.phpunit.openstack.platforms');
     if (empty($data) || !is_array($data)) {
         return array(array(self::EMPTY_CONFIG, 'DFW', '3afe97b2-26dc-49c5-a2cc-a2fc8d80c001'));
     }
     return $data;
 }
Example #10
0
 /**
  * Provider of the instances for the functional tests
  */
 public function providerRs()
 {
     $data = \Scalr::config('scalr.phpunit.openstack.platforms');
     if (empty($data) || !is_array($data)) {
         return array(array(SERVER_PLATFORMS::RACKSPACENG_US, 'DFW', '3afe97b2-26dc-49c5-a2cc-a2fc8d80c001'));
     }
     return $data;
 }
Example #11
0
 /**
  * {@inheritdoc}
  * @see PHPUnit_Framework_TestCase::setUp()
  */
 protected function setUp()
 {
     parent::setUp();
     $this->container = \Scalr::getContainer();
     $this->environment = new \Scalr_Environment();
     if (!$this->isSkipFunctionalTests()) {
         $this->environment->loadById(\Scalr::config('scalr.phpunit.envid'));
         $this->container->environment = $this->environment;
     }
 }
Example #12
0
 /**
  * Returns true if functional tests should be skipped.
  *
  * @param   string $type  optional The type of the test ui, api, cloud-dependent.
  *          If option is not provided it will try to resolve static::TEST_TYPE constant
  *
  * @return  bool Returns true if functional tests should be skipped.
  */
 public static function isSkippedFunctionalTest($type = null)
 {
     $type = $type ?: static::TEST_TYPE;
     $value = \Scalr::config('scalr.phpunit.functional_tests');
     if (!is_array($value)) {
         return !$value;
     }
     //It silently skips test with undefined type.
     return $type ? !in_array($type, $value) : true;
 }
Example #13
0
 /**
  * @test
  * @functional
  */
 public function testFunctionalServiceActions()
 {
     $cy = new Cloudyn('', '', \Scalr::config('scalr.cloudyn.environment'));
     $version = $cy->getVersion();
     $this->assertNotEmpty($version);
     $res = $cy->checkStatus();
     $this->assertTrue($res);
     $countries = $cy->countries();
     $this->assertArrayHasKey('US', $countries);
 }
Example #14
0
 /**
  * {@inheritdoc}
  * @see Scalr_Role_Behavior::getConfiguration()
  */
 public function getConfiguration(DBServer $dbServer)
 {
     $router = new stdClass();
     // Set scalr address
     $router->scalrAddr = \Scalr::config('scalr.endpoint.scheme') . "://" . \Scalr::config('scalr.endpoint.host');
     // Set scalr IPs whitelist
     $router->whitelist = \Scalr::config('scalr.aws.ip_pool');
     // Set CIDR
     $router->cidr = '10.0.0.0/8';
     return $router;
 }
Example #15
0
 /**
  * Constructor. Instantiates AuditLogger, prepares backend
  *
  * @param AuditLoggerConfiguration $config  Audit logger config data
  */
 public function __construct(AuditLoggerConfiguration $config)
 {
     parent::__construct(\Scalr::config('scalr.logger.audit'));
     $this->user = $config->user;
     $this->accountId = $config->accountId;
     $this->envId = $config->envId;
     $this->remoteAddr = $config->remoteAddr;
     $this->ruid = $config->ruid;
     $this->requestType = $config->requestType;
     $this->systemTask = $config->systemTask;
 }
Example #16
0
 /**
  * Creates new http Request object
  *
  * @return Request Returns new http Request object
  */
 protected function createHttpRequest()
 {
     $req = new Request();
     $req->setOptions(array('redirect' => 10, 'verifypeer' => false, 'verifyhost' => false, 'timeout' => \Scalr::config('scalr.openstack.api_client.timeout'), 'connecttimeout' => 30, 'cookiesession' => true));
     $proxySettings = $this->getConfig()->getProxySettings();
     if (!empty($proxySettings)) {
         $req->setOptions(['proxyhost' => $proxySettings['host'], 'proxyport' => $proxySettings['port'], 'proxytype' => $proxySettings['type']]);
         if ($proxySettings['user']) {
             $req->setOptions(['proxyauth' => "{$proxySettings['user']}:{$proxySettings['pass']}", 'proxyauthtype' => $proxySettings['authtype']]);
         }
     }
     return $req;
 }
Example #17
0
 function handleWork($farmId)
 {
     try {
         $dbFarm = DBFarm::LoadByID($farmId);
         $governance = new Scalr_Governance($dbFarm->EnvID);
         $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications');
         $curDate = new DateTime();
         $td = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE));
         if ($td > $curDate) {
             // only inform user
             $days = $td->diff($curDate)->days;
             $notifications = json_decode($dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND), true);
             if (is_array($settings)) {
                 foreach ($settings as $n) {
                     if (!$notifications[$n['key']] && $n['period'] >= $days) {
                         $mailer = Scalr::getContainer()->mailer;
                         $tdHuman = Scalr_Util_DateTime::convertDateTime($td, $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'M j, Y');
                         if ($n['to'] == 'owner') {
                             $user = new Scalr_Account_User();
                             $user->loadById($dbFarm->createdByUserId);
                             if (Scalr::config('scalr.auth_mode') == 'ldap') {
                                 $email = $user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL);
                                 if (!$email) {
                                     $email = $user->getEmail();
                                 }
                             } else {
                                 $email = $user->getEmail();
                             }
                             $mailer->addTo($email);
                         } else {
                             foreach (explode(',', $n['emails']) as $email) {
                                 $mailer->addTo(trim($email));
                             }
                         }
                         $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml', array('{{terminate_date}}' => $tdHuman, '{{farm}}' => $dbFarm->Name, '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id));
                         $notifications[$n['key']] = 1;
                         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, json_encode($notifications));
                         $this->logger->info("Notification was sent by key: " . $n['key'] . " about farm: " . $dbFarm->Name . " by lease manager");
                     }
                 }
             }
         } else {
             // terminate farm
             $event = new FarmTerminatedEvent(0, 1, false, 1);
             Scalr::FireEvent($farmId, $event);
             $this->logger->info("Farm: " . $dbFarm->Name . " was terminated by lease manager");
         }
     } catch (Exception $e) {
         var_dump($e->getMessage());
     }
 }
Example #18
0
 public function apiAction()
 {
     if (!$this->user->getSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY) || !$this->user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY)) {
         $keys = Scalr::GenerateAPIKeys();
         $this->user->setSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY, $keys['id']);
         $this->user->setSetting(Scalr_Account_User::SETTING_API_SECRET_KEY, $keys['key']);
     }
     $params[Scalr_Account_User::SETTING_API_ENABLED] = $this->user->getSetting(Scalr_Account_User::SETTING_API_ENABLED) == 1 ? true : false;
     $params[Scalr_Account_User::SETTING_API_IP_WHITELIST] = (string) $this->user->getSetting(Scalr_Account_User::SETTING_API_IP_WHITELIST);
     $params[Scalr_Account_User::SETTING_API_ACCESS_KEY] = $this->user->getSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY);
     $params[Scalr_Account_User::SETTING_API_SECRET_KEY] = $this->user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY);
     $params['api.endpoint'] = \Scalr::config('scalr.endpoint.scheme') . '://' . \Scalr::config('scalr.endpoint.host') . '/api/api.php';
     $params['envName'] = $this->getEnvironment() ? $this->getEnvironment()->name : '';
     $this->response->page('ui/core/api.js', $params);
 }
Example #19
0
 public function editAction()
 {
     $platforms = array();
     $governanceEnabledPlatforms = array(SERVER_PLATFORMS::EC2, SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::OPENSTACK, SERVER_PLATFORMS::NEBULA, SERVER_PLATFORMS::MIRANTIS, SERVER_PLATFORMS::VIO, SERVER_PLATFORMS::VERIZON, SERVER_PLATFORMS::CISCO, SERVER_PLATFORMS::HPCLOUD, SERVER_PLATFORMS::OCS, SERVER_PLATFORMS::RACKSPACENG_US, SERVER_PLATFORMS::AZURE);
     //intersection of enabled platforms and supported by governance
     foreach (array_intersect($this->getEnvironment()->getEnabledPlatforms(), $governanceEnabledPlatforms) as $platform) {
         //we only need ec2 locations at the moment
         $platforms[$platform] = $platform == SERVER_PLATFORMS::EC2 ? self::loadController('Platforms')->getCloudLocations($platform, false) : array();
     }
     $chefServers = [];
     foreach (ChefServer::getList($this->user->getAccountId(), $this->getEnvironmentId()) as $chefServer) {
         $chefServers[] = ['id' => $chefServer->id, 'url' => $chefServer->url, 'scope' => $chefServer->getScope()];
     }
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $this->response->page('ui/core/governance/edit.js', array('platforms' => $platforms, 'values' => $governance->getValues(), 'chef' => ['servers' => $chefServers], 'scalr.aws.ec2.limits.security_groups_per_instance' => \Scalr::config('scalr.aws.ec2.limits.security_groups_per_instance')), array('ui/core/governance/lease.js'), array('ui/core/governance/edit.css'));
 }
Example #20
0
 public static function generateTenderMultipassToken($data)
 {
     $salted = \Scalr::config('scalr.ui.tender_api_key') . \Scalr::config('scalr.ui.tender_site_key');
     $hash = hash('sha1', $salted, true);
     $saltedHash = substr($hash, 0, 16);
     $iv = "OpenSSL for Ruby";
     // double XOR first block
     for ($i = 0; $i < 16; $i++) {
         $data[$i] = $data[$i] ^ $iv[$i];
     }
     $pad = 16 - strlen($data) % 16;
     $data = $data . str_repeat(chr($pad), $pad);
     $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
     mcrypt_generic_init($cipher, $saltedHash, $iv);
     $encryptedData = mcrypt_generic($cipher, $data);
     mcrypt_generic_deinit($cipher);
     return urlencode(base64_encode($encryptedData));
 }
Example #21
0
 /**
  * @test
  */
 public function testLdapFunctional()
 {
     if (!\Scalr::config('scalr.connections.ldap.user')) {
         $this->markTestSkipped('scalr.connections.ldap section is not defined in the config.');
     }
     $config = \Scalr::getContainer()->get('ldap.config');
     $ldap = \Scalr::getContainer()->ldap($config->user, $config->password);
     $valid = $ldap->isValidUser();
     $this->assertTrue($valid, 'It expects valid user\'s credentials. ' . $ldap->getLog());
     $ldap->unbind();
     $ldap = \Scalr::getContainer()->ldap($config->user, '');
     $valid = $ldap->isValidUser();
     $this->assertFalse($valid, 'User can be authenticated without password. ' . $ldap->getLog());
     $ldap->unbind();
     $ldap = \Scalr::getContainer()->ldap($config->user, 'invalidpassword');
     $valid = $ldap->isValidUser();
     $this->assertFalse($valid, 'User with invalid password should not be authenticated. ' . $ldap->getLog());
     $ldap->unbind();
 }
Example #22
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\AbstractTask::onCompleted()
  */
 public function onCompleted()
 {
     if (!\Scalr::config('scalr.dns.global.enabled')) {
         return true;
     }
     $db = \Scalr::getDb();
     $remoteBind = new Scalr_Net_Dns_Bind_RemoteBind();
     $transport = new Scalr_Net_Dns_Bind_Transports_LocalFs('/usr/sbin/rndc', '/var/named/etc/namedb/client_zones');
     $remoteBind->setTransport($transport);
     $zones = $db->GetAll("SELECT id FROM dns_zones WHERE iszoneconfigmodified = '1'");
     $s_zones = [];
     if (count($zones) != 0) {
         foreach ($zones as $zone) {
             $DBDNSZone = DBDNSZone::loadById($zone['id']);
             switch ($DBDNSZone->status) {
                 case DNS_ZONE_STATUS::PENDING_DELETE:
                 case DNS_ZONE_STATUS::INACTIVE:
                     $remoteBind->removeZoneFromNamedConf($DBDNSZone->zoneName);
                     break;
                 default:
                     $remoteBind->addZoneToNamedConf($DBDNSZone->zoneName, $DBDNSZone->getContents(true));
                     $DBDNSZone->status = DNS_ZONE_STATUS::ACTIVE;
                     break;
             }
             $s_zones[] = $DBDNSZone;
         }
         $remoteBind->saveNamedConf();
         foreach ($s_zones as $DBDNSZone) {
             if ($DBDNSZone->status == DNS_ZONE_STATUS::PENDING_DELETE) {
                 $DBDNSZone->remove();
             } else {
                 if ($DBDNSZone->status == DNS_ZONE_STATUS::INACTIVE) {
                     $DBDNSZone->isOnNsServer = 0;
                 } else {
                     $DBDNSZone->isOnNsServer = 1;
                 }
                 $DBDNSZone->isZoneConfigModified = 0;
                 $DBDNSZone->save();
             }
         }
     }
     $remoteBind->reloadBind();
 }
Example #23
0
 public function defaultAction()
 {
     if ($this->user->getType() == Scalr_Account_User::TYPE_SCALR_ADMIN) {
         $this->response->page('ui/dashboard/admin.js');
     } else {
         $loadJs = array('ui/dashboard/columns.js');
         $cloudynEnabled = \Scalr::config('scalr.cloudyn.master_email') ? true : false;
         $billingEnabled = \Scalr::config('scalr.billing.enabled') ? true : false;
         $panel = $this->user->getDashboard($this->getEnvironmentId());
         if (empty($panel['configuration'])) {
             // default configurations
             $client = Client::Load($this->user->getAccountId());
             if ($client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
                 // old customer
                 $panel['configuration'] = array(array(array('name' => 'dashboard.status')), array(array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5)), array('name' => 'dashboard.usagelaststat', 'params' => array('farmCount' => 5))), array(array('name' => 'dashboard.lasterrors', 'params' => array('errorCount' => 10))));
                 if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) {
                     array_unshift($panel['configuration'][0], array('name' => 'dashboard.billing'));
                 }
             } else {
                 // new customer
                 $panel['configuration'] = array(array(array('name' => 'dashboard.tutorapp')), array(array('name' => 'dashboard.tutordns')), array(array('name' => 'dashboard.tutorfarm'), array('name' => 'dashboard.announcement', 'params' => array('newsCount' => 5))));
                 if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $billingEnabled) {
                     $panel['configuration'][1][] = array('name' => 'dashboard.billing');
                 }
             }
             $this->user->setDashboard($this->getEnvironmentId(), $panel);
             $panel = $this->user->getDashboard($this->getEnvironmentId());
         }
         // section for adding required widgets
         if ($cloudynEnabled && !in_array('cloudynInstalled', $panel['flags']) && !in_array('dashboard.cloudyn', $panel['widgets']) && !!$this->environment->isPlatformEnabled(SERVER_PLATFORMS::EC2)) {
             if (!isset($panel['configuration'][0])) {
                 $panel['configuration'][0] = array();
             }
             array_unshift($panel['configuration'][0], array('name' => 'dashboard.cloudyn'));
             $panel['flags'][] = 'cloudynInstalled';
             $this->user->setDashboard($this->getEnvironmentId(), $panel);
             $panel = $this->user->getDashboard($this->getEnvironmentId());
         }
         $panel = $this->fillDash($panel);
         $this->response->page('ui/dashboard/view.js', array('panel' => $panel, 'flags' => array('cloudynEnabled' => $cloudynEnabled, 'billingEnabled' => $billingEnabled)), $loadJs, array('ui/dashboard/view.css'));
     }
 }
Example #24
0
 /**
  * Makes sure the broker is running.
  * If it isn't running method will start it.
  *
  * @return int  Returns non false if broker is running
  */
 public static function ensureBrokerRunning()
 {
     $client = (new Client(\Scalr::config('scalr.crontab.sockets.broker')))->setTimeout(100)->setRetries(1)->setLogger(\Scalr::getContainer()->logger('Mdp\\Client')->setLevel(\Scalr::config('scalr.crontab.log_level')))->connect();
     $mmiReq = new Zmsg();
     $mmiReq->push("system.healthcheck");
     $mmiRep = $client->send("mmi.service", $mmiReq);
     if ($mmiRep) {
         $ok = $mmiRep->pop();
     } else {
         $ok = false;
         //Make sure another broker process isn't hanging
         self::terminateBroker();
         //Broker has to be started in the separate process
         $op = [];
         $logFile = \Scalr::config('scalr.crontab.log');
         exec(self::getStartBrokerCommand() . ' ' . ($logFile == '/dev/null' ? '> ' : '>> ') . escapeshellcmd($logFile) . ' 2>&1 & echo $!', $op);
         $pid = intval($op[0]);
     }
     return $ok;
 }
Example #25
0
 /**
  * Generate data for ApiTestCaseV2
  *
  * @param string $fixtures patch to fixtures directory
  * @return array
  * @throws \Scalr\System\Config\Exception\YamlException
  */
 public static function dataFixtures($fixtures)
 {
     // set config
     static::$testUserId = \Scalr::config('scalr.phpunit.userid');
     static::$user = User::findPk(static::$testUserId);
     static::$testEnvId = \Scalr::config('scalr.phpunit.envid');
     static::$env = Environment::findPk(static::$testEnvId);
     $data = [];
     foreach (new DirectoryIterator($fixtures) as $fileInfo) {
         if ($fileInfo->isFile()) {
             $class = __NAMESPACE__ . '\\' . ucfirst($fileInfo->getBasename('.yaml'));
             if (class_exists($class)) {
                 /* @var $object TestDataFixtures */
                 $object = new $class(Yaml::load($fileInfo->getPathname())->toArray());
                 $object->prepareTestData();
                 $data = array_merge($data, $object->preparePathInfo());
             }
         }
     }
     return $data;
 }
Example #26
0
 /**
  * {@inheritdoc}
  * @see ApiSpecMutator::apply()
  */
 public function apply(Yaml $config, $version)
 {
     $clouds = \Scalr::config('scalr.allowed_clouds');
     if (isset($this->spec['definitions']['CloudLocation']['properties']['cloudPlatform']['enum'])) {
         $excessClouds = array_diff($this->spec['definitions']['CloudLocation']['properties']['cloudPlatform']['enum'], $clouds);
         if (!empty($excessClouds)) {
             $this->removeItem('definitions.CloudLocation.properties.cloudPlatform.enum', $excessClouds);
         }
     }
     if (in_array('ec2', $clouds)) {
         $clouds = array_merge($clouds, ['awsclassic', 'awsvpc']);
     }
     if (isset($this->spec['definitions']['PlacementConfiguration']['properties']['placementConfigurationType']['enum'])) {
         $placementConfigurationsTypes = $this->spec['definitions']['PlacementConfiguration']['properties']['placementConfigurationType']['enum'];
         $refs = $this->spec['definitions']['PlacementConfiguration']['x-concreteTypes'];
         foreach ($refs as $pos => $ref) {
             // '#/definitions/' length = 14
             // 'PlacementConfiguration' length = 22
             $refs[$pos] = substr($ref['$ref'], 14, -22);
         }
         $extraTypes = [];
         foreach ($placementConfigurationsTypes as $type) {
             // 'PlacementConfiguration' length = 22
             $typeName = substr($type, 0, -22);
             if (!in_array(strtolower($typeName), $clouds)) {
                 $extraTypes[] = $type;
                 $this->removeItem("definitions.{$type}");
                 $inRefs = array_search($typeName, $refs);
                 if ($inRefs !== false) {
                     $this->removeItem("definitions.PlacementConfiguration.x-concreteTypes", $inRefs);
                 }
             }
         }
         if (!empty($extraTypes)) {
             $this->removeItem('definitions.PlacementConfiguration.properties.placementConfigurationType.enum', $extraTypes);
         }
     }
 }
 public function ListGlobalVariables()
 {
     $ResponseDOMDocument = $this->CreateResponse();
     $configNode = $ResponseDOMDocument->createElement("variables");
     $globalVariables = new Scalr_Scripting_GlobalVariables($this->DBServer->clientId, $this->DBServer->envId, Scalr_Scripting_GlobalVariables::SCOPE_SERVER);
     $vars = $globalVariables->listVariables($this->DBServer->GetFarmRoleObject()->RoleID, $this->DBServer->farmId, $this->DBServer->farmRoleId, $this->DBServer->serverId);
     foreach ($vars as $key => $value) {
         $settingNode = $ResponseDOMDocument->createElement("variable");
         if (preg_match("/[\\<\\>\\&]+/", $value['value'])) {
             $valueEl = $ResponseDOMDocument->createCDATASection($value['value']);
         } else {
             $valueEl = $ResponseDOMDocument->createTextNode($value['value']);
         }
         $settingNode->appendChild($valueEl);
         $settingNode->setAttribute("name", $value['name']);
         $settingNode->setAttribute("private", $value['private']);
         $configNode->appendChild($settingNode);
     }
     $formats = \Scalr::config("scalr.system.global_variables.format");
     foreach ($this->DBServer->GetScriptingVars() as $name => $value) {
         $name = "SCALR_" . strtoupper($name);
         $value = trim($value);
         if (isset($formats[$name])) {
             $value = @sprintf($formats[$name], $value);
         }
         $settingNode = $ResponseDOMDocument->createElement("variable");
         if (preg_match("/[\\<\\>\\&]+/", $value)) {
             $valueEl = $ResponseDOMDocument->createCDATASection($value);
         } else {
             $valueEl = $ResponseDOMDocument->createTextNode($value);
         }
         $settingNode->appendChild($valueEl);
         $settingNode->setAttribute("name", $name);
         $configNode->appendChild($settingNode);
     }
     $ResponseDOMDocument->documentElement->appendChild($configNode);
     return $ResponseDOMDocument;
 }
Example #28
0
 /**
  * Gets configured HttpRequest
  *
  * @return \HttpRequest
  */
 private function getRequest()
 {
     if (!$this->request) {
         $opt = ['timeout' => 15];
         if (\Scalr::config('scalr.aws.use_proxy')) {
             $proxy = \Scalr::config('scalr.connections.proxy');
             if (in_array($proxy['use_on'], array('both', 'scalr'))) {
                 $opt['proxyhost'] = $proxy['host'];
                 $opt['proxyport'] = $proxy['port'];
                 $opt['proxytype'] = $proxy['type'];
                 if (!empty($proxy['pass']) && !empty($proxy['user'])) {
                     $opt['proxyauth'] = "{$proxy['user']}:{$proxy['pass']}";
                     $opt['proxyauthtype'] = $proxy['authtype'];
                 }
             }
         }
         $this->request = new \HttpRequest(null, HTTP_METH_GET, $opt);
     } else {
         $this->request->resetCookies(true);
         $this->request->clearHistory();
     }
     return $this->request;
 }
Example #29
0
 /**
  * Gets configured http Request
  *
  * @return Request
  */
 private function getRequest()
 {
     if (!$this->request) {
         $opt = ['timeout' => 15];
         if (\Scalr::config('scalr.aws.use_proxy')) {
             $proxy = \Scalr::config('scalr.connections.proxy');
             if (in_array($proxy['use_on'], array('both', 'scalr'))) {
                 $opt['proxyhost'] = $proxy['host'];
                 $opt['proxyport'] = $proxy['port'];
                 $opt['proxytype'] = $proxy['type'];
                 if (!empty($proxy['pass']) && !empty($proxy['user'])) {
                     $opt['proxyauth'] = "{$proxy['user']}:{$proxy['pass']}";
                     $opt['proxyauthtype'] = $proxy['authtype'];
                 }
             }
         }
         $this->request = new Request("GET");
         $this->request->setOptions($opt);
     } else {
         $this->request->setOptions(['cookiesession' => true]);
     }
     return $this->request;
 }
Example #30
0
 /**
  * Verifies that Full access role is defined properly.
  *
  * All existing resources must be defined and allowed for this role.
  * All existing resource unique permissions must be defined and allowed for this role.
  *
  * @test
  * @dataProvider providerPredefinedRoles
  */
 public function testPredefinedRoles($roleId, $allowed)
 {
     if (\Scalr::config('scalr.phpunit.skip_functional_tests')) {
         $this->markTestSkipped();
     }
     $acl = \Scalr::getContainer()->acl;
     $role = $acl->getRole($roleId);
     $this->assertInstanceOf('Scalr\\Acl\\Role\\RoleObject', $role);
     $this->assertNotEmpty($role->getName(), 'Role name must be defined');
     $this->assertEquals($roleId, $role->getRoleId());
     $roleResources = $role->getResources();
     $this->assertInstanceOf('ArrayObject', $roleResources);
     /* @var $resourceDefinition Resource\ResourceObject */
     foreach (Resource\Definition::getAll() as $resourceId => $resourceDefinition) {
         // Absence of the record is considered as forbidden
         if (!$allowed && !isset($roleResources[$resourceId])) {
             continue;
         }
         $this->assertTrue(isset($roleResources[$resourceId]), sprintf('All resources must be defined for the %s role. ' . 'You should add records to the acl_role_resources table with role_id(%d)', $role->getName(), self::ROLE_FULL_ACCESS));
         /* @var $resource Role\RoleResourceObject */
         $resource = $roleResources[$resourceId];
         $this->assertTrue($resource->isGranted() == $allowed, sprintf('%s resource must be %s for the %s role', $resourceDefinition->getName(), $allowed ? 'allowed' : 'forbidden', $role->getName()));
         $permissions = $resource->getPermissions();
         $this->assertInstanceOf('ArrayObject', $permissions);
         foreach ($resourceDefinition->getPermissions() as $permissionId => $description) {
             // Absence of the record is considered as forbidden
             if (!$allowed && !isset($permissions[$permissionId])) {
                 continue;
             }
             $this->assertTrue(isset($permissions[$permissionId]), sprintf('Permission [%s - %s] must be defined for the %s role. ' . 'You should add record to the acl_role_resource_permission table with ' . 'key (role_id[%d], resource_id[0x%x], perm_id[%s]).', $resourceDefinition->getName(), $permissionId, $role->getName(), $role->getRoleId(), $resource->getResourceId(), $permissionId));
             /* @var $permission Role\RoleResourcePermissionObject */
             $permission = $permissions[$permissionId];
             $this->assertInstanceOf('Scalr\\Acl\\Role\\RoleResourcePermissionObject', $permission);
             $this->assertTrue($permission->isGranted() == $allowed, sprintf('Permission [%s - %s] must be %s for the %s role.', $resourceDefinition->getName(), $permissionId, $allowed ? 'allowed' : 'forbidden', $role->getName()));
         }
     }
 }