Exemplo n.º 1
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();
 }
Exemplo n.º 2
0
 /**
  * @return CryptoTool
  */
 protected function getCrypto()
 {
     if (!$this->crypto) {
         $this->crypto = \Scalr::getContainer()->crypto;
     }
     return $this->crypto;
 }
Exemplo n.º 3
0
 public function __construct(Scalr_Net_Dns_Bind_Transports_Ssh2_AuthInfo $authInfo, $host, $port, $rndcPath, $zonesPath)
 {
     $this->ssh2Client = new Scalr_Net_Ssh2_Client();
     $this->logger = \Scalr::getContainer()->logger(__CLASS__);
     $this->rndcPath = $rndcPath;
     $this->zonesPath = $zonesPath;
     $this->host = $host;
     switch ($authInfo->getType()) {
         case Scalr_Net_Dns_Bind_Transports_Ssh2_AuthInfo::TYPE_PASSWORD:
             $this->ssh2Client->addPassword($authInfo->login, $authInfo->password);
             break;
         case Scalr_Net_Dns_Bind_Transports_Ssh2_AuthInfo::TYPE_PUBKEY:
             $this->ssh2Client->addPubkey($authInfo->login, $authInfo->pubKeyPath, $authInfo->privKeyPath, $authInfo->keyPassword);
             break;
     }
     try {
         $this->ssh2Client->connect($host, $port);
     } catch (Scalr_Net_Ssh2_Exception $e) {
         throw new Exception("Unable to initialize SSH2 Transport: {$e->getMessage()}");
     }
     // COunt initial number of zones
     $this->zonesCount = $this->rndcStatus();
     if (!$this->zonesCount) {
         throw new Exception(sprintf(_("Cannot fetch RNDC status on %s"), $host));
     }
 }
Exemplo n.º 4
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())));
     }
 }
Exemplo n.º 5
0
 /**
  * {@inheritdoc}
  * @see Scalr\Tests\TestCase::tearDownAfterClass()
  */
 public static function tearDownAfterClass()
 {
     foreach (static::$testData as $rec) {
         if ($rec['class'] === Farm::class) {
             $entry = $rec['pk'];
             $farm = Farm::findPk(...$entry);
             /* @var $farm Farm */
             if (!empty($farm)) {
                 try {
                     \Scalr::FireEvent($farm->id, new FarmTerminatedEvent(false, false, false, false, true, static::$user->id));
                     foreach ($farm->servers as $server) {
                         try {
                             $dbServer = Server::findPk($server->serverId);
                             /* @var $dbServer Server */
                             $dbServer->terminate(Server::TERMINATE_REASON_FARM_TERMINATED, true, static::$user);
                         } catch (Exception $e) {
                             \Scalr::logException($e);
                         }
                         $server->delete();
                     }
                 } catch (Exception $e) {
                     \Scalr::logException($e);
                 }
             }
         }
     }
     parent::tearDownAfterClass();
 }
Exemplo n.º 6
0
 function startChild()
 {
     // Reopen DB connection in child
     $this->db = Core::GetDBInstance(null, true);
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
 }
Exemplo n.º 7
0
 function __construct()
 {
     $this->cryptoTool = \Scalr::getContainer()->srzcrypto;
     $this->serializer = new Scalr_Messaging_XmlSerializer();
     $this->jsonSerializer = new Scalr_Messaging_JsonSerializer();
     $this->logger = \Scalr::getContainer()->logger(__CLASS__);
 }
Exemplo n.º 8
0
 function __construct($nodeName, $jobConfig)
 {
     parent::__construct($nodeName, $jobConfig);
     $this->logger = \Scalr::getContainer()->logger(__CLASS__);
     if (!key_exists("datacenter", $jobConfig)) {
         throw new Scalr_System_Cronjob_Exception("Configuration array must have a key for 'datacenter'");
     }
     $dcConfig = $jobConfig["datacenter"];
     if (!$dcConfig["centers"]) {
         throw new Scalr_System_Cronjob_Exception("No datacenters defined in configuration");
     }
     if (!$dcConfig["leader"]) {
         throw new Scalr_System_Cronjob_Exception("Configuration array must have a key for 'datacenter'.'leader' " . "that names the leader datacenter");
     }
     $centers = array_map("trim", explode(",", $dcConfig["centers"]));
     $nodeCenterMap = array();
     foreach ($centers as $center) {
         $nodes = array_map("trim", explode(",", $dcConfig[$center]));
         foreach ($nodes as $node) {
             $nodeCenterMap[$node] = $center;
         }
     }
     $this->dataCenter = key_exists($this->nodeName, $nodeCenterMap) ? $nodeCenterMap[$this->nodeName] : $dcConfig["default"];
     $this->leaderDataCenter = $dcConfig["leader"];
 }
Exemplo n.º 9
0
 protected function run1($stage)
 {
     $this->console->out(sprintf("Reencrypting %s database from %s/%s to %s/%s!", \Scalr::getContainer()->config->get('scalr.connections.mysql.name'), $this->source->getCryptoAlgo(), $this->source->getCipherMode(), $this->target->getCryptoAlgo(), $this->target->getCipherMode()));
     set_error_handler(function ($code, $message, $file, $line, $context) {
         \Scalr::errorHandler($code, $message, $file, $line, $context);
         if ($code == E_STRICT) {
             throw new Exception($message);
         }
     }, E_USER_ERROR | E_STRICT | E_RECOVERABLE_ERROR | E_ERROR);
     try {
         $this->db->Execute('START TRANSACTION;');
         $this->recrypt('ssh_keys', ['private_key', 'public_key']);
         $this->recrypt('services_ssl_certs', ['ssl_pkey', 'ssl_pkey_password']);
         $this->recrypt('account_user_settings', ['value'], "WHERE `name` = 'security.2fa.ggl.key'", ['user_id', 'name']);
         $this->recrypt('services_chef_servers', ['auth_key', 'v_auth_key']);
         $this->recrypt('variables', ['value'], '', ['name'], $this->globals);
         $this->recrypt('account_variables', ['value'], '', ['name', 'account_id'], $this->globals);
         $this->recrypt('client_environment_variables', ['value'], '', ['name', 'env_id'], $this->globals);
         $this->recrypt('role_variables', ['value'], '', ['name', 'role_id'], $this->globals);
         $this->recrypt('farm_variables', ['value'], '', ['name', 'farm_id'], $this->globals);
         $this->recrypt('farm_role_variables', ['value'], '', ['name', 'farm_role_id'], $this->globals);
         $this->recrypt('server_variables', ['value'], '', ['name', 'server_id'], $this->globals);
         $reflection = new ReflectionClass('Scalr_Environment');
         $method = $reflection->getMethod('getEncryptedVariables');
         $method->setAccessible(true);
         $this->recrypt('client_environment_properties', ['value'], "WHERE `name` IN ('" . implode("','", array_keys($method->invoke(null))) . "')");
         $this->db->Execute("COMMIT;");
     } catch (\Exception $e) {
         $this->rollback($e->getCode(), $e->getMessage());
         restore_error_handler();
         throw $e;
     }
     restore_error_handler();
 }
Exemplo n.º 10
0
 public function __call($method, $args)
 {
     // If observer enabled
     if (!$this->Config || $this->Config->GetFieldByName("IsEnabled")->Value == 0) {
         return;
     }
     $enabled = $this->Config->GetFieldByName("{$method}Notify");
     if (!$enabled || $enabled->Value == 0) {
         return;
     }
     $DB = \Scalr::getDb();
     // Event name
     $name = substr($method, 2);
     // Event message
     $message = $DB->GetOne("SELECT message FROM events WHERE event_id = ? LIMIT 1", array($args[0]->GetEventID()));
     $farm_name = $DB->GetOne("SELECT name FROM farms WHERE id=? LIMIT 1", array($args[0]->GetFarmID()));
     // Set subject
     if (!$farm_name) {
         $this->Mailer->setSubject("{$name} event notification (FarmID: {$args[0]->GetFarmID()})");
     } else {
         $this->Mailer->setSubject("{$name} event notification (FarmID: {$args[0]->GetFarmID()} FarmName: {$farm_name})");
     }
     // Set body
     $this->Mailer->setMessage($message);
     // Send mail
     try {
         $res = $this->Mailer->send();
     } catch (\Exception $e) {
         $res = false;
     }
     if (!$res) {
         Logger::getLogger(__CLASS__)->info("Mail sent to '{$this->Config->GetFieldByName("EventMailTo")->Value}'. Result: {$res}");
     }
 }
Exemplo n.º 11
0
 /**
  * Constructor
  */
 function __construct()
 {
     $this->Logger = \Scalr::getContainer()->logger('SignalHandler');
     if (!function_exists("pcntl_signal")) {
         throw new \Exception("Function pcntl_signal() is not found. PCNTL must be enabled in PHP.", E_ERROR);
     }
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Observer\AbstractEventObserver::OnBeforeInstanceLaunch()
  */
 public function OnBeforeInstanceLaunch(\BeforeInstanceLaunchEvent $event)
 {
     if ($event->DBServer->platform != \SERVER_PLATFORMS::EC2) {
         return;
     }
     $DBFarm = $event->DBServer->GetFarmObject();
     $DBFarmRole = $event->DBServer->GetFarmRoleObject();
     // Create EBS volume for MySQLEBS
     if (!$event->DBServer->IsSupported("0.6")) {
         // Only for old AMIs
         if ($DBFarmRole->GetRoleObject()->hasBehavior(\ROLE_BEHAVIORS::MYSQL) && $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_DATA_STORAGE_ENGINE) == \MYSQL_STORAGE_ENGINE::EBS) {
             $server = $event->DBServer;
             $masterServer = $DBFarm->GetMySQLInstances(true);
             $isMaster = !$masterServer || $masterServer[0]->serverId == $server->serverId;
             $farmMasterVolId = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_MASTER_EBS_VOLUME_ID);
             $createEbs = $isMaster && !$farmMasterVolId;
             if ($createEbs) {
                 \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->info(new FarmLogMessage($event->DBServer, sprintf("Need EBS volume for MySQL %s instance...", $isMaster ? "Master" : "Slave")));
                 $req = new CreateVolumeRequestData($event->DBServer->GetProperty(\EC2_SERVER_PROPERTIES::AVAIL_ZONE), $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_EBS_VOLUME_SIZE));
                 $aws = $event->DBServer->GetEnvironmentObject()->aws($DBFarmRole->CloudLocation);
                 $res = $aws->ec2->volume->create($req);
                 if (!empty($res->volumeId)) {
                     $DBFarmRole->SetSetting(Entity\FarmRoleSetting::MYSQL_MASTER_EBS_VOLUME_ID, $res->volumeId, Entity\FarmRoleSetting::TYPE_LCL);
                     \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->info(new FarmLogMessage($event->DBServer, sprintf("MySQL %S volume created. Volume ID: %s...", $isMaster ? "Master" : "Slave", !empty($res->volumeId) ? $res->volumeId : null)));
                 }
             }
         }
     }
 }
Exemplo n.º 13
0
    public function run()
    {
        $container = \Scalr::getContainer();
        $db = $container->adodb;
        $row = $db->GetRow("SHOW TABLES LIKE 'upgrades'");
        if ($row) {
            print "Tables already exist. Terminating.\n";
            exit;
        }
        $script = <<<EOL
            CREATE TABLE `upgrades` (
             `uuid` VARBINARY(16) NOT NULL COMMENT 'Unique identifier of update',
             `released` DATETIME NOT NULL COMMENT 'The time when upgrade script is issued',
             `appears` DATETIME NOT NULL COMMENT 'The time when upgrade does appear',
             `applied` DATETIME DEFAULT NULL COMMENT 'The time when update is successfully applied',
             `status` TINYINT NOT NULL COMMENT 'Upgrade status',
             `hash` VARBINARY (20) COMMENT 'SHA1 hash of the upgrade file',
             PRIMARY KEY (`uuid`),
             INDEX `idx_status` (`status`),
             INDEX `idx_appears` (`appears`)
            ) ENGINE = InnoDB;

            CREATE TABLE `upgrade_messages` (
              `uuid` VARBINARY(16) NOT NULL COMMENT 'upgrades.uuid reference',
              `created` DATETIME NOT NULL COMMENT 'Creation timestamp',
              `message` TEXT COMMENT 'Error messages',
              INDEX idx_uuid (`uuid`),
              CONSTRAINT `upgrade_messages_ibfk_1` FOREIGN KEY (`uuid`) REFERENCES `upgrades` (`uuid`) ON DELETE CASCADE
            ) ENGINE = InnoDB;
EOL;
        $lines = array_filter(preg_split('/;[\\s\\r\\n]*/m', $script));
        foreach ($lines as $stmt) {
            $db->Execute($stmt);
        }
    }
Exemplo n.º 14
0
 /**
  * Saves all relations between all users of this team and ACL roles
  *
  * @param   array   $data Roles array should look like array(user_id => array(account_role_id, ...))
  * @throws  \Scalr\Acl\Exception\AclException
  */
 public function setUserRoles(array $data = array())
 {
     if (empty($this->id)) {
         throw new \Scalr\Acl\Exception\AclException(sprintf("ID of the team is expected. It hasn't been initialized yet."));
     }
     \Scalr::getContainer()->acl->setAllRolesForTeam($this->id, $data, $this->accountId);
 }
Exemplo n.º 15
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Tests\TestCase::setUp()
  */
 protected function setUp()
 {
     parent::setUp();
     if (!\Scalr::getContainer()->analytics->enabled) {
         $this->markTestSkipped("Cost analytics has not been enabled in the configuration.");
     }
 }
Exemplo n.º 16
0
 public function Run()
 {
     $container = Scalr::getContainer();
     $db = $container->adodb;
     $db->Execute("ALTER TABLE  `global_variables` ADD  `format` VARCHAR( 15 ) NULL , ADD  `validator` VARCHAR( 255 ) NULL ;");
     $db->Execute("ALTER TABLE  `apache_vhosts` DROP INDEX  `ix_name` , ADD UNIQUE  `ix_name` (  `name` ,  `env_id` ,  `farm_id`, `farm_roleid` ) ;");
 }
Exemplo n.º 17
0
 function startChild()
 {
     // Reopen DB connection in child
     $this->db = $this->getContainer()->adodb;
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
 }
Exemplo n.º 18
0
 public function xSaveAction($url, $endpointId = null)
 {
     if (!$endpointId) {
         $endpoint = new WebhookEndpoint();
         $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT;
         $endpoint->accountId = $this->getEnvironment()->clientId;
         $endpoint->envId = $this->getEnvironmentId();
         $endpoint->securityKey = Scalr::GenerateRandomKey(64);
     } else {
         $endpoint = WebhookEndpoint::findPk($endpointId);
         if ($endpoint->envId != $this->getEnvironmentId() || $endpoint->accountId != $this->getEnvironment()->clientId) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint');
         }
     }
     foreach (WebhookEndpoint::findByUrl($url) as $ep) {
         if ($ep->endpointId != $endpoint->endpointId && $ep->envId == $this->getEnvironmentId()) {
             $this->request->addValidationErrors('url', 'Endpoint url must be unique within environment');
             break;
         }
     }
     if ($this->request->isValid()) {
         if ($endpoint->url != $url) {
             $endpoint->isValid = false;
             $endpoint->url = $url;
         }
         ////temporarily disable url validation per Igor`s request(see also webhooks/endpoints/view.js)
         $endpoint->isValid = true;
         $endpoint->save();
         $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey)));
     } else {
         $this->response->data($this->request->getValidationErrors());
         $this->response->failure();
     }
 }
Exemplo n.º 19
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;
 }
Exemplo n.º 20
0
 /**
  * @test
  * @dataProvider providerModifications
  *
  * @param array $data
  * @param array $modifications
  * @param array $expected
  */
 public function testModifications($data, $modifications, $expected)
 {
     $mutator = new TestMutator($modifications);
     $mutator->setSpec($data);
     $mutator->apply(\Scalr::getContainer()->config(), 'test');
     $this->assertEquals($data, $expected);
 }
Exemplo n.º 21
0
 public function usageAction()
 {
     $acl = \Scalr::getContainer()->acl;
     $accountRole = $acl->getAccountRole($this->getParam('accountRoleId'));
     $this->user->getPermissions()->validate($accountRole);
     $this->response->page('ui/account2/roles/usage.js', array('users' => array_values($acl->getUsersHaveAccountRole($this->getParam('accountRoleId'), $this->request->getUser()->getAccountId())), 'role' => array('id' => $accountRole->getRoleId(), 'name' => $accountRole->getName())));
 }
Exemplo n.º 22
0
 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;
 }
 public function StartThread($farminfo)
 {
     $db = \Scalr::getDb();
     $DBFarm = DBFarm::LoadByID($farminfo['id']);
     foreach ($DBFarm->GetFarmRoles() as $DBFarmRole) {
         foreach ($DBFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, SERVER_STATUS::PENDING, SERVER_STATUS::TROUBLESHOOTING)), array()) as $DBServer) {
             $launchTime = strtotime($DBServer->dateAdded);
             $lastCheckTime = (int) $DBServer->GetProperty(SERVER_PROPERTIES::STATISTICS_LAST_CHECK_TS);
             if (!$lastCheckTime) {
                 $lastCheckTime = $launchTime;
             }
             $period = round((time() - $lastCheckTime) / 60);
             $maxMinutes = date("j") * 24 * 60 - date("H") * 60;
             if ($period > $maxMinutes) {
                 $period = $maxMinutes;
             }
             $serverType = $DBServer->GetFlavor();
             if (!$serverType) {
                 continue;
             }
             $db->Execute("INSERT INTO servers_stats SET\n                    `usage` = ?,\n                    `instance_type` = ?,\n                    `env_id` = ?,\n                    `month` = ?,\n                    `year` = ?,\n                    `farm_id` = ?,\n                    `cloud_location` = ?\n                ON DUPLICATE KEY UPDATE `usage` = `usage` + ?\n                ", array($period, $serverType, $DBServer->envId, date("m"), date("Y"), $DBServer->farmId, $DBServer->GetCloudLocation(), $period));
             $DBServer->SetProperty(SERVER_PROPERTIES::STATISTICS_LAST_CHECK_TS, time());
         }
         //for each items
     }
 }
Exemplo n.º 24
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\Platforms\Openstack\OpenstackPlatformModule::GetServerIPAddresses()
  */
 public function GetServerIPAddresses(\DBServer $DBServer)
 {
     $config = \Scalr::getContainer()->config;
     $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
     $result = $client->servers->getServerDetails($DBServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::SERVER_ID));
     $publicNetworkName = 'public';
     $privateNetworkName = 'private';
     if (is_array($result->addresses->{$publicNetworkName})) {
         foreach ($result->addresses->{$publicNetworkName} as $addr) {
             if ($addr->version == 4) {
                 $remoteIp = $addr->addr;
                 break;
             }
         }
     }
     if (!$remoteIp && $result->accessIPv4) {
         $remoteIp = $result->accessIPv4;
     }
     if (is_array($result->addresses->{$privateNetworkName})) {
         foreach ($result->addresses->{$privateNetworkName} as $addr) {
             if ($addr->version == 4) {
                 $localIp = $addr->addr;
                 break;
             }
         }
     }
     if (!$localIp) {
         $localIp = $remoteIp;
     }
     return array('localIp' => $localIp, 'remoteIp' => $remoteIp);
 }
Exemplo n.º 25
0
 public static function doJob($job)
 {
     $db = \Scalr::getDb();
     $messageSerializer = new Scalr_Messaging_XmlSerializer();
     $message = $db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($job->workload()));
     try {
         if ($message['handle_attempts'] >= 3) {
             $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
         } else {
             try {
                 $DBServer = DBServer::LoadByID($message['server_id']);
             } catch (Exception $e) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
                 return;
             }
             if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) {
                 // Only 0.2-68 or greater version support this feature.
                 if ($DBServer->IsSupported("0.2-68")) {
                     $msg = $messageSerializer->unserialize($message['message']);
                     $DBServer->SendMessage($msg);
                 } else {
                     $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::UNSUPPORTED, $message['id']));
                 }
             } elseif (in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
             }
         }
     } catch (Exception $e) {
         //var_dump($e->getMessage());
     }
 }
Exemplo n.º 26
0
 public function getValue(DBFarmRole $dbFarmRole, Scalr_Scaling_FarmRoleMetric $farmRoleMetric)
 {
     $servers = $dbFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::RUNNING));
     $dbFarm = $dbFarmRole->GetFarmObject();
     $roleLA = 0;
     if (count($servers) == 0) {
         return false;
     }
     $retval = array();
     foreach ($servers as $DBServer) {
         if ($dbFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_EXCLUDE_DBMSR_MASTER) == 1) {
             $isMaster = $DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) == 1 || $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER) == 1;
             if ($isMaster) {
                 continue;
             }
         }
         try {
             $period = $farmRoleMetric->getSetting(self::SETTING_LA_PERIOD);
             $index = 0;
             if ($period == 15) {
                 $index = 2;
             } elseif ($period == 5) {
                 $index = 1;
             }
             $la = $DBServer->scalarizr->system->loadAverage();
             if ($la[$index] !== null && $la[$index] !== false) {
                 $la = (double) number_format($la[$index], 2);
             }
             $retval[] = $la;
         } catch (Exception $e) {
             \Scalr::getContainer()->logger(__CLASS__)->warn(new FarmLogMessage($DBServer->farmId, sprintf("Unable to read LoadAverage value from server %s: %s", $DBServer->getNameByConvention(), $e->getMessage()), $DBServer->serverId));
         }
     }
     return count($retval) > 0 ? $retval : false;
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  * @see Scalr\Tests.TestCase::setUp()
  */
 protected function setUp()
 {
     $this->container = \Scalr::getContainer();
     //Usual service
     $this->container->test1 = function ($cont) {
         return new DiObject1();
     };
     //Shared service
     $this->container->setShared('test2', function ($cont) {
         return new DiObject1();
     });
     //Service which is using singletone behaviour
     //but delegated internally by additional parameters.
     $this->container->test3 = function ($cont, $args) {
         $params = array();
         $params['region'] = isset($args[0]) ? $args[0] : 'default';
         $serviceid = 'test3.' . md5($params['region']);
         if (!$cont->initialized($serviceid)) {
             $cont->setShared($serviceid, function ($cont) use($params) {
                 return new DiObject1($params['region']);
             });
         }
         return $cont->get($serviceid);
     };
 }
Exemplo n.º 28
0
 /**
  * {@inheritdoc}
  */
 public function worker($request)
 {
     //Warming up static DI cache
     \Scalr::getContainer()->warmup();
     try {
         $dbFarmRole = DBFarmRole::LoadByID($request->id);
         $dbFarm = $dbFarmRole->GetFarmObject();
         /* @var $env Scalr_Environment */
         $env = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($dbFarm->EnvID);
         $tz = $env->getPlatformConfigValue(Scalr_Environment::SETTING_TIMEZONE);
         if (!$tz) {
             $tz = date_default_timezone_get();
         }
         $farmTz = $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE);
         if ($farmTz) {
             $tz = $farmTz;
         }
         //skip terminated farms
         if ($dbFarm->Status != FARM_STATUS::RUNNING) {
             return $request;
         }
     } catch (Exception $e) {
         $this->getLogger()->warn("Could not load farm role with id:%d, %s", $request->id, $e->getMessage());
         return $request;
     }
     $this->performDbMsrAction('BUNDLE', $dbFarmRole, $tz);
     $backupsNotSupported = in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF));
     if (!$backupsNotSupported) {
         $this->performDbMsrAction('BACKUP', $dbFarmRole, $tz);
     }
     return $request;
 }
Exemplo n.º 29
0
 public function __construct($id = null)
 {
     $this->id = $id;
     $this->container = \Scalr::getContainer();
     $this->db = \Scalr::getDb();
     $this->dbMessageKeyNotFound = get_class($this) . " " . $this->dbMessageKeyNotFound;
 }
Exemplo n.º 30
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Tests\TestCase::setUp()
  */
 protected function setUp()
 {
     $this->config = \Scalr::getContainer()->config;
     if (!$this->config->defined('scalr.crontab')) {
         $this->markTestSkipped("scalr.crontab section of config has not been defined.");
     }
 }