getContainer() public static méthode

Gets DI container
public static getContainer ( ) : Container
Résultat Scalr\DependencyInjection\Container
Exemple #1
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);
     }
 }
Exemple #2
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);
        }
    }
Exemple #3
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)));
                 }
             }
         }
     }
 }
Exemple #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();
 }
Exemple #5
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);
 }
Exemple #6
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\Type\AbstractType::toPhp()
  */
 public function toPhp($value)
 {
     if ($value === null) {
         return null;
     }
     return \Scalr::getContainer()->crypto->decrypt($value);
 }
Exemple #7
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.");
     }
 }
Exemple #8
0
 /**
  * @param $config
  * @key string $jobDir
  * @key string $clsSuffix
  * @key string $clsNamespace
  * @key bool $oldSyntax (default true)
  * TODO: add $getopt key
  * TODO: support new syntax: php cron.php [options] task
  */
 function __construct($config)
 {
     foreach ($config as $k => $v) {
         $this->{$k} = $v;
     }
     $this->logger = \Scalr::getContainer()->logger(__CLASS__);
 }
Exemple #9
0
 /**
  * @param $config
  * @key string [name]
  * @key string [key]
  * @key array [items]
  */
 function __construct($config)
 {
     $this->logger = \Scalr::getContainer()->logger(__CLASS__);
     $this->initialConfig = $config;
     $this->shm = new Scalr_System_Ipc_Shm($config);
     $key = $this->shm->key + 8;
     $this->logger->debug(sprintf("Get semaphore (key: 0x%08x)", $key));
     $this->sem = sem_get($key, 1, 0666, true);
     if (!$this->sem) {
         throw new Scalr_System_Ipc_Exception("Cannot sem_get (key: {$key})");
     }
     if (!sem_acquire($this->sem)) {
         throw new Scalr_System_Ipc_Exception("Cannot acquire semaphore");
     }
     try {
         $meta = $this->getMeta();
         if ($meta === null) {
             $this->clear0();
         }
         sem_release($this->sem);
     } catch (Exception $e) {
         sem_release($this->sem);
         throw $e;
     }
     if ($config["items"]) {
         foreach ($config["items"] as $item) {
             $this->add($item);
         }
     }
 }
Exemple #10
0
 public function Run()
 {
     $container = Scalr::getContainer();
     $db = $container->adodb;
     $db->Execute("ALTER TABLE  `farm_role_scripts` ADD  `script_path` VARCHAR( 255 ) NULL ;");
     $db->Execute("ALTER TABLE  `apache_vhosts` DROP INDEX  `ix_name` , ADD UNIQUE  `ix_name` (  `name` ,  `env_id` ,  `farm_id` ) ;");
 }
Exemple #11
0
 /**
  * Makes request itself to the set or default url
  *
  * @name  sendRequest
  * @param mixed $url
  * @return array  $data
  */
 private function sendRequest()
 {
     try {
         $response = \Scalr::getContainer()->http->sendRequest($this->httpRequest);
         $data = $response->getBody()->toString();
         $this->LastResponseHeaders = $response->getHeaders();
         $this->LastResponseBody = $data;
         if ($response->getResponseCode() >= 400) {
             $errMsg = json_decode($data);
             if (is_object($errMsg)) {
                 $errMsg = @array_values(@get_object_vars($errMsg));
                 $errMsg = $errMsg[0];
             }
             $code = $errMsg->code ? $errMsg->code : 0;
             $msg = $errMsg->details ? $errMsg->details : trim($data);
             throw new Exception(sprintf('Request to Rackspace failed (Code: %s): %s', $code, $msg));
         }
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception($message);
     }
     return $data;
 }
Exemple #12
0
 public function Run()
 {
     $container = Scalr::getContainer();
     $db = $container->adodb;
     $db->Execute("CREATE TABLE IF NOT EXISTS `farm_role_cloud_services` (\n          `id` varchar(36) NOT NULL,\n          `type` varchar(10) NOT NULL,\n          `env_id` int(11) NOT NULL,\n          `farm_id` int(11) NOT NULL,\n          `farm_role_id` int(11) NOT NULL,\n          `platform` varchar(36) DEFAULT NULL,\n          `cloud_location` varchar(36) DEFAULT NULL,\n          PRIMARY KEY (`id`),\n          KEY `farm_role_id` (`farm_role_id`),\n          KEY `farm_id` (`farm_id`)\n        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n        ");
     $db->Execute("ALTER TABLE `farm_role_cloud_services`\n  ADD CONSTRAINT `farm_role_cloud_services_ibfk_1` FOREIGN KEY (`farm_role_id`) REFERENCES `farm_roles` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;\n        ");
 }
Exemple #13
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"];
 }
Exemple #14
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();
 }
Exemple #15
0
 public function __construct($id = null)
 {
     $this->id = $id;
     $this->container = \Scalr::getContainer();
     $this->db = \Scalr::getDb();
     $this->dbMessageKeyNotFound = get_class($this) . " " . $this->dbMessageKeyNotFound;
 }
Exemple #16
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));
     }
 }
Exemple #17
0
 /**
  * Get spec array for current service
  *
  * @param $service string available api service (user|account|admin)
  * @return array
  */
 protected function getSpecFile($service)
 {
     $describer = new Describer(self::$apiVersion, $service, \Scalr::getContainer()->config());
     $reflectionSpecProperties = (new \ReflectionClass('Scalr\\Util\\Api\\Describer'))->getProperty('specFile');
     $reflectionSpecProperties->setAccessible(true);
     return yaml_parse_file($reflectionSpecProperties->getValue($describer));
 }
Exemple #18
0
 /**
  * @return CryptoTool
  */
 protected function getCrypto()
 {
     if (!$this->crypto) {
         $this->crypto = \Scalr::getContainer()->crypto;
     }
     return $this->crypto;
 }
Exemple #19
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);
     };
 }
Exemple #20
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())));
     }
 }
Exemple #21
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::worker()
  */
 public function worker($request)
 {
     if (!\Scalr::config('scalr.dns.global.enabled')) {
         $this->getLogger()->error("Unable to process the request. scalr.dns.global.enabled = false");
         return;
     }
     //Warming up static DI cache
     \Scalr::getContainer()->warmup();
     $DBDNSZone = DBDNSZone::loadById($request->id);
     $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);
     switch ($DBDNSZone->status) {
         case DNS_ZONE_STATUS::PENDING_DELETE:
         case DNS_ZONE_STATUS::INACTIVE:
             $remoteBind->removeZoneDbFile($DBDNSZone->zoneName);
             $DBDNSZone->isZoneConfigModified = 1;
             break;
         case DNS_ZONE_STATUS::PENDING_CREATE:
         case DNS_ZONE_STATUS::PENDING_UPDATE:
             $remoteBind->addZoneDbFile($DBDNSZone->zoneName, $DBDNSZone->getContents());
             if ($DBDNSZone->status == DNS_ZONE_STATUS::PENDING_CREATE) {
                 $DBDNSZone->isZoneConfigModified = 1;
             }
             $DBDNSZone->status = DNS_ZONE_STATUS::ACTIVE;
             break;
     }
     $DBDNSZone->save();
     return $request;
 }
Exemple #22
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__);
 }
Exemple #23
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())));
 }
 /**
  * {@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;
 }
 /**
  * {@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.");
     }
 }
Exemple #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;
 }
 /**
  * {@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);
 }
Exemple #28
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);
 }
Exemple #29
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` ) ;");
 }
Exemple #30
0
 function __construct($process_classes_folder)
 {
     $this->Logger = \Scalr::getContainer()->logger('JobLauncher');
     $processes = @glob("{$process_classes_folder}/class.*Process.php");
     $options = array();
     if (count($processes) > 0) {
         foreach ($processes as $process) {
             $filename = basename($process);
             $directory = dirname($process);
             if (!file_exists($directory . "/" . $filename)) {
                 throw new \Exception(sprintf("File %s does not exist.", $directory . "/" . $filename));
             }
             include_once $directory . "/" . $filename;
             preg_match("/class.(.*)Process.php/s", $filename, $tmp);
             $process_name = $tmp[1];
             if (class_exists("{$process_name}Process")) {
                 $reflect = new \ReflectionClass("{$process_name}Process");
                 if ($reflect) {
                     if ($reflect->implementsInterface('Scalr\\System\\Pcntl\\ProcessInterface')) {
                         $options[$process_name] = $reflect->getProperty("ProcessDescription")->getValue($reflect->newInstance());
                     } else {
                         throw new \Exception("Class '{$process_name}Process' doesn't implement 'ProcessInterface'.", E_ERROR);
                     }
                 } else {
                     throw new \Exception("Cannot use ReflectionAPI for class '{$process_name}Process'", E_ERROR);
                 }
             } else {
                 throw new \Exception("'{$process}' does not contain definition for '{$process_name}Process'", E_ERROR);
             }
         }
     } else {
         throw new \Exception(_("No job classes found in {$process_classes_folder}"), E_ERROR);
     }
     $options["help"] = "Print this help";
     $options["piddir=s"] = "PID directory";
     $Getopt = new \Zend_Console_Getopt($options);
     try {
         $opts = $Getopt->getOptions();
     } catch (\Zend_Console_Getopt_Exception $e) {
         print "{$e->getMessage()}\n\n";
         die($Getopt->getUsageMessage());
     }
     if (in_array("help", $opts) || count($opts) == 0 || !$options[$opts[0]]) {
         print $Getopt->getUsageMessage();
         exit;
     } else {
         $this->ProcessName = $opts[0];
         /*
         if (in_array("piddir", $opts)) {
             $piddir = trim($Getopt->getOption("piddir"));
             if (substr($piddir, 0, 1) != '/') {
                 //$this->PIDDir = realpath($process_classes_folder . "/" . $piddir);
             } else {
                 //$this->PIDDir = $piddir;
             }
         }
         */
     }
 }