当前位置: 首页>>代码示例>>PHP>>正文


PHP Scalr_Environment::init方法代码示例

本文整理汇总了PHP中Scalr_Environment::init方法的典型用法代码示例。如果您正苦于以下问题:PHP Scalr_Environment::init方法的具体用法?PHP Scalr_Environment::init怎么用?PHP Scalr_Environment::init使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Scalr_Environment的用法示例。


在下文中一共展示了Scalr_Environment::init方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: run2

 protected function run2($stage)
 {
     $this->console->out("Populating new properties");
     $platforms = $envs = [];
     foreach (array_keys(\SERVER_PLATFORMS::GetList()) as $platform) {
         $platforms[$platform] = PlatformFactory::NewPlatform($platform);
     }
     $result = $this->db->Execute("\n                SELECT s.server_id, s.`platform`, s.`cloud_location`, s.env_id, s.`type`\n                FROM servers AS s\n                WHERE s.`status` NOT IN (?, ?) AND s.`type` IS NOT NULL\n            ", [Server::STATUS_PENDING_TERMINATE, Server::STATUS_TERMINATED]);
     while ($row = $result->FetchRow()) {
         if (!empty($row["type"])) {
             if (!array_key_exists($row["env_id"], $envs)) {
                 $envs[$row["env_id"]] = \Scalr_Environment::init()->loadById($row["env_id"]);
             }
             if ($this->isPlatformEnabled($envs[$row["env_id"]], $row["platform"])) {
                 try {
                     $instanceTypeEntity = $platforms[$row["platform"]]->getInstanceType($row["type"], $envs[$row["env_id"]], $row["cloud_location"]);
                     /* @var $instanceTypeEntity CloudInstanceType */
                     if ($instanceTypeEntity && (int) $instanceTypeEntity->vcpus > 0) {
                         $this->db->Execute("\n                                INSERT IGNORE INTO server_properties (`server_id`, `name`, `value`) VALUES (?, ?, ?)\n                            ", [$row["server_id"], Server::INFO_INSTANCE_VCPUS, $instanceTypeEntity->vcpus]);
                     }
                 } catch (\Exception $e) {
                     $this->console->warning("Can't get access to %s, error: %s", $row["platform"], $e->getMessage());
                 }
             }
         }
     }
 }
开发者ID:solderzzc,项目名称:scalr,代码行数:27,代码来源:Update20150818090745.php

示例2: run1

 /**
  * Performs upgrade literally for the stage ONE.
  *
  * Implementation of this method performs update steps needs to be taken
  * to accomplish upgrade successfully.
  *
  * If there are any error during an execution of this scenario it must
  * throw an exception.
  *
  * @param   int  $stage  optional The stage number
  * @throws  \Exception
  */
 protected function run1($stage)
 {
     $environments = $this->db->Execute("SELECT id FROM client_environments WHERE status='Active'");
     while ($env = $environments->FetchRow()) {
         $environment = \Scalr_Environment::init()->loadById($env['id']);
         foreach (PlatformFactory::getOpenstackBasedPlatforms() as $platform) {
             if ($platform == \SERVER_PLATFORMS::RACKSPACENG_UK || $platform == \SERVER_PLATFORMS::RACKSPACENG_US) {
                 continue;
             }
             try {
                 if ($environment->isPlatformEnabled($platform)) {
                     $os = $environment->openstack($platform);
                     //It throws an exception on failure
                     $zones = $os->listZones();
                     $zone = array_shift($zones);
                     $os = $environment->openstack($platform, $zone->name);
                     // Check SG Extension
                     $pars[$this->getOpenStackOption($platform, 'EXT_SECURITYGROUPS_ENABLED')] = (int) $os->servers->isExtensionSupported(ServersExtension::securityGroups());
                     // Check Floating Ips Extension
                     $pars[$this->getOpenStackOption($platform, 'EXT_FLOATING_IPS_ENABLED')] = (int) $os->servers->isExtensionSupported(ServersExtension::floatingIps());
                     // Check Cinder Extension
                     $pars[$this->getOpenStackOption($platform, 'EXT_CINDER_ENABLED')] = (int) $os->hasService('volume');
                     // Check Swift Extension
                     $pars[$this->getOpenStackOption($platform, 'EXT_SWIFT_ENABLED')] = (int) $os->hasService('object-store');
                     // Check LBaas Extension
                     $pars[$this->getOpenStackOption($platform, 'EXT_LBAAS_ENABLED')] = $os->hasService('network') ? (int) $os->network->isExtensionSupported('lbaas') : 0;
                     $environment->setPlatformConfig($pars);
                 }
             } catch (\Exception $e) {
                 $this->console->out("Update settings for env: {$env['id']} failed: " . $e->getMessage());
             }
         }
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:46,代码来源:Update20140211014306.php

示例3: run1

 protected function run1($stage)
 {
     $envs = [];
     $platform = SERVER_PLATFORMS::GCE;
     $platformModule = PlatformFactory::NewPlatform($platform);
     /* @var $platformModule GoogleCEPlatformModule*/
     $result = $this->db->Execute("\n            SELECT s.`server_id`, s.`cloud_location`, s.`type`, s.`env_id`, sp.`value` AS vcpus\n            FROM servers AS s\n            LEFT JOIN server_properties sp ON sp.`server_id`= s.`server_id` AND sp.`name` = ?\n            WHERE s.`status` NOT IN (?, ?)\n            AND s.`type` IS NOT NULL\n            AND s.`platform` = ?\n        ", [Server::INFO_INSTANCE_VCPUS, Server::STATUS_PENDING_TERMINATE, Server::STATUS_TERMINATED, $platform]);
     while ($row = $result->FetchRow()) {
         if (!empty($row["type"]) && empty($row['vcpus'])) {
             if (!array_key_exists($row["env_id"], $envs)) {
                 $envs[$row["env_id"]] = \Scalr_Environment::init()->loadById($row["env_id"]);
             }
             try {
                 $instanceTypeInfo = $platformModule->getInstanceType($row["type"], $envs[$row["env_id"]], $row["cloud_location"]);
                 if ($instanceTypeInfo instanceof CloudInstanceType) {
                     $vcpus = $instanceTypeInfo->vcpus;
                 } else {
                     trigger_error("Value of vcpus for instance type " . $row["type"] . " is missing for platform " . $platform, E_USER_WARNING);
                     $vcpus = 0;
                 }
                 if ((int) $vcpus > 0) {
                     $this->db->Execute("\n                            INSERT INTO server_properties (`server_id`, `name`, `value`) VALUES (?, ?, ?)\n                            ON DUPLICATE KEY UPDATE `value` = ?\n                        ", [$row["server_id"], Server::INFO_INSTANCE_VCPUS, $vcpus, $vcpus]);
                 }
             } catch (\Exception $e) {
                 $this->console->warning("Can't get access to %s, error: %s", $platform, $e->getMessage());
             }
         }
     }
 }
开发者ID:scalr,项目名称:scalr,代码行数:29,代码来源:Update20160401132637.php

示例4: getAccountEnvironmentsList

 public function getAccountEnvironmentsList()
 {
     $environments = $this->user->getEnvironments();
     $result = array();
     foreach ($environments as &$row) {
         $env = Scalr_Environment::init()->loadById($row['id']);
         $row['platforms'] = $env->getEnabledPlatforms();
         $row['teams'] = array();
         if ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap') {
             $row['teamIds'] = array();
         }
         foreach ($env->getTeams() as $teamId) {
             if ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap') {
                 $team = new Scalr_Account_Team();
                 $team->loadById($teamId);
                 $row['teams'][] = $team->name;
                 $row['teamIds'][] = $teamId;
             } else {
                 $row['teams'][] = $teamId;
             }
         }
         $row['dtAdded'] = Scalr_Util_DateTime::convertTz($env->dtAdded);
         $row['status'] = $env->status;
         if ($this->getContainer()->analytics->enabled) {
             $row['ccId'] = $env->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID);
         }
         $result[] =& $row;
     }
     return $result;
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:30,代码来源:Account2.php

示例5: setUpBeforeClass

 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, ''];
         }
     }
 }
开发者ID:scalr,项目名称:scalr,代码行数:32,代码来源:GlobalVariablesTest.php

示例6: run2

 protected function run2($stage)
 {
     $farms = $this->db->Execute("SELECT farmid, value FROM farm_settings WHERE name='ec2.vpc.id' AND value != '' AND value IS NOT NULL");
     while ($farm = $farms->FetchRow()) {
         $dbFarm = \DBFarm::LoadByID($farm['farmid']);
         $roles = $dbFarm->GetFarmRoles();
         foreach ($roles as $dbFarmRole) {
             $vpcSubnetId = $dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_VPC_SUBNET_ID);
             if ($vpcSubnetId && substr($vpcSubnetId, 0, 6) != 'subnet') {
                 $subnets = json_decode($vpcSubnetId);
                 $vpcSubnetId = $subnets[0];
             }
             if ($vpcSubnetId) {
                 try {
                     $platform = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::EC2);
                     $info = $platform->listSubnets(\Scalr_Environment::init()->loadById($dbFarm->EnvID), $dbFarmRole->CloudLocation, $farm['value'], true, $vpcSubnetId);
                     if ($info && $info['type'] != 'public') {
                         $routerRole = $dbFarm->GetFarmRoleByBehavior(\ROLE_BEHAVIORS::VPC_ROUTER);
                         $dbFarmRole->SetSetting(\Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID, $routerRole->ID);
                         $this->console->out("Updating router.scalr.farm_role_id property for Farm Role: %s", $dbFarmRole->ID);
                     }
                 } catch (\Exception $e) {
                     continue;
                 }
             }
         }
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:28,代码来源:Update20140612235154.php

示例7: getEnvironmentsList

 /**
  * Gets a list of environments by key
  *
  * @param  string $query Search query
  * @return array  Returns array of environments
  */
 private function getEnvironmentsList($query = null)
 {
     $envs = [];
     $environments = $this->user->getEnvironments($query);
     if (count($environments) > 0) {
         $iterator = ChartPeriodIterator::create('month', gmdate('Y-m-01'), null, 'UTC');
         //It calculates usage for all provided enviroments
         $usage = $this->getContainer()->analytics->usage->getFarmData($this->user->getAccountId(), [], $iterator->getStart(), $iterator->getEnd(), [TagEntity::TAG_ID_ENVIRONMENT, TagEntity::TAG_ID_FARM]);
         //It calculates usage for previous period same days
         $prevusage = $this->getContainer()->analytics->usage->getFarmData($this->user->getAccountId(), [], $iterator->getPreviousStart(), $iterator->getPreviousEnd(), [TagEntity::TAG_ID_ENVIRONMENT, TagEntity::TAG_ID_FARM]);
         foreach ($environments as $env) {
             if (isset($usage['data'][$env['id']]['data'])) {
                 $envs[$env['id']]['topSpender'] = $this->getFarmTopSpender($usage['data'][$env['id']]['data']);
             } else {
                 $envs[$env['id']]['topSpender'] = null;
             }
             $envs[$env['id']]['name'] = $env['name'];
             $envs[$env['id']]['envId'] = $env['id'];
             $ccId = \Scalr_Environment::init()->loadById($env['id'])->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID);
             if (!empty($ccId)) {
                 $envs[$env['id']]['ccId'] = $ccId;
                 $envs[$env['id']]['ccName'] = CostCentreEntity::findPk($ccId)->name;
             }
             $totalCost = round(isset($usage['data'][$env['id']]) ? $usage['data'][$env['id']]['cost'] : 0, 2);
             $prevCost = round(isset($prevusage['data'][$env['id']]) ? $prevusage['data'][$env['id']]['cost'] : 0, 2);
             $envs[$env['id']] = $this->getWrappedUsageData(['iterator' => $iterator, 'usage' => $totalCost, 'prevusage' => $prevCost]) + $envs[$env['id']];
         }
     }
     return array_values($envs);
 }
开发者ID:mheydt,项目名称:scalr,代码行数:36,代码来源:Environments.php

示例8: init

 public function init()
 {
     $this->env = Scalr_Environment::init()->loadById($this->getParam(Scalr_UI_Controller_Environments::CALL_PARAM_NAME));
     $this->user->getPermissions()->validate($this->env);
     if (!($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER || $this->user->isTeamUserInEnvironment($this->env->id, Scalr_Account_Team::PERMISSIONS_OWNER))) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:8,代码来源:Platform.php

示例9: init

 /**
  * {@inheritdoc}
  * @see Scalr_UI_Controller::init()
  */
 public function init()
 {
     $this->env = Scalr_Environment::init()->loadById($this->getParam(Scalr_UI_Controller_Environments::CALL_PARAM_NAME));
     $this->user->getPermissions()->validate($this->env);
     if (!($this->user->isAccountOwner() || $this->user->isTeamOwnerInEnvironment($this->env->id) || $this->request->isAllowed(Acl::RESOURCE_ENV_CLOUDS_ENVIRONMENT))) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:12,代码来源:Platform.php

示例10: run1

 protected function run1($stage)
 {
     $envIds = $this->db->Execute("SELECT `id` FROM `client_environments`");
     $platformVariables = static::getCloudsCredentialProperties();
     foreach ($envIds as $row) {
         $environment = \Scalr_Environment::init()->loadById($row['id']);
         $platforms = [];
         foreach (array_keys(SERVER_PLATFORMS::getList()) as $platform) {
             if ($environment->getPlatformConfigValue($platform . '.is_enabled', false)) {
                 $platforms[] = $platform;
             }
         }
         foreach ($platforms as $platform) {
             try {
                 switch ($platform) {
                     case SERVER_PLATFORMS::RACKSPACE:
                         foreach (['rs-ORD1', 'rs-LONx'] as $location) {
                             $cloudCredentials = new Entity\CloudCredentials();
                             $cloudCredentials->accountId = $environment->getAccountId();
                             $cloudCredentials->envId = $environment->id;
                             $cloudCredentials->cloud = "{$location}.{$platform}";
                             $cloudCredentials->name = "{$environment->id}-{$environment->getAccountId()}-{$cloudCredentials->cloud}-" . \Scalr::GenerateUID(true);
                             foreach ($platformVariables[$platform] as $name => $newName) {
                                 $value = $environment->getPlatformConfigValue($name, true, $location);
                                 if ($value === null) {
                                     $value = false;
                                 }
                                 $cloudCredentials->properties[$newName] = $value;
                             }
                             $cloudCredentials->save();
                             $cloudCredentials->bindToEnvironment($environment);
                         }
                         break;
                     default:
                         $cloudCredentials = new Entity\CloudCredentials();
                         $cloudCredentials->accountId = $environment->getAccountId();
                         $cloudCredentials->envId = $environment->id;
                         $cloudCredentials->cloud = $platform;
                         $cloudCredentials->name = "{$environment->id}-{$environment->getAccountId()}-{$platform}-" . \Scalr::GenerateUID(true);
                         $cloudCredentials->status = Entity\CloudCredentials::STATUS_ENABLED;
                         foreach ($platformVariables[$platform] as $name => $newName) {
                             $value = $environment->getPlatformConfigValue($name);
                             if ($value === null) {
                                 $value = false;
                             }
                             $cloudCredentials->properties[$newName] = $value;
                         }
                         $cloudCredentials->save();
                         $cloudCredentials->bindToEnvironment($environment);
                         break;
                 }
             } catch (Exception $e) {
                 $this->console->error(get_class($e) . " in {$e->getFile()} on line {$e->getLine()}: " . $e->getMessage());
                 error_log(get_class($e) . " in {$e->getFile()} at line {$e->getLine()}: {$e->getMessage()}\n{$e->getTraceAsString()}");
             }
         }
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:58,代码来源:Update20151009141048.php

示例11: OnStartForking

 /**
  * Auto-snapshoting
  * {@inheritdoc}
  * @see \Scalr\System\Pcntl\ProcessInterface::OnStartForking()
  */
 public function OnStartForking()
 {
     $db = \Scalr::getDb();
     // selects rows where the snapshot's time has come to create new snapshot.
     $resultset = $db->Execute("\n            SELECT * FROM autosnap_settings\n            WHERE (`dtlastsnapshot` < NOW() - INTERVAL `period` HOUR OR `dtlastsnapshot` IS NULL)\n            AND objectid != '0'\n            AND object_type = ?\n        ", array(AUTOSNAPSHOT_TYPE::RDSSnap));
     while ($snapshotsSettings = $resultset->FetchRow()) {
         try {
             $environment = Scalr_Environment::init()->loadById($snapshotsSettings['env_id']);
             $aws = $environment->aws($snapshotsSettings['region']);
             // Check instance. If instance wasn't found then delete current recrod from settings table
             try {
                 $aws->rds->dbInstance->describe($snapshotsSettings['objectid']);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid") || stristr($e->getMessage(), "security token included in the request is invalid")) {
                     $db->Execute("\n                            DELETE FROM autosnap_settings WHERE id = ?\n                        ", array($snapshotsSettings['id']));
                 }
                 $this->Logger->error(sprintf(_("RDS instance %s was not found. " . "Auto-snapshot settings for this instance will be deleted. %s."), $snapshotsSettings['objectid'], $e->getMessage()));
                 throw $e;
             }
             // snapshot random unique name
             $snapshotId = "scalr-auto-" . dechex(microtime(true) * 10000) . rand(0, 9);
             try {
                 // Create new snapshot
                 $aws->rds->dbSnapshot->create($snapshotsSettings['objectid'], $snapshotId);
                 // update last snapshot creation date in settings
                 $db->Execute("\n                        UPDATE autosnap_settings\n                        SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?\n                    ", array($snapshotId, $snapshotsSettings['id']));
                 // create new snapshot record in DB
                 $db->Execute("\n                        INSERT INTO rds_snaps_info\n                        SET snapid = ?,\n                            comment = ?,\n                            dtcreated = NOW(),\n                            region = ?,\n                            autosnapshotid = ?\n                    ", array($snapshotId, _("Auto snapshot"), $snapshotsSettings['region'], $snapshotsSettings['id']));
             } catch (Exception $e) {
                 $this->Logger->warn(sprintf(_("Could not create RDS snapshot: %s."), $e->getMessage()));
             }
             // Remove old snapshots
             if ($snapshotsSettings['rotate'] != 0) {
                 $oldSnapshots = $db->GetAll("\n                        SELECT * FROM rds_snaps_info\n                        WHERE autosnapshotid = ?\n                        ORDER BY id ASC\n                    ", array($snapshotsSettings['id']));
                 if (count($oldSnapshots) > $snapshotsSettings['rotate']) {
                     while (count($oldSnapshots) > $snapshotsSettings['rotate']) {
                         // takes the oldest snapshot ...
                         $deletingSnapshot = array_shift($oldSnapshots);
                         try {
                             // and deletes it from amazon and from DB
                             $aws->rds->dbSnapshot->delete($deletingSnapshot['snapid']);
                             $db->Execute("\n                                    DELETE FROM rds_snaps_info WHERE id = ?\n                                ", array($deletingSnapshot['id']));
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid")) {
                                 $db->Execute("\n                                        DELETE FROM rds_snaps_info WHERE id = ?\n                                    ", array($deletingSnapshot['id']));
                             }
                             $this->Logger->error(sprintf(_("DBsnapshot %s for RDS instance %s was not found and cannot be deleted . %s."), $deletingSnapshot['snapid'], $snapshotsSettings['objectid'], $e->getMessage()));
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             $this->Logger->warn(sprintf(_("Cannot create snapshot for RDS Instance %s. %s"), $snapshotsSettings['objectid'], $e->getMessage()));
         }
     }
 }
开发者ID:rickb838,项目名称:scalr,代码行数:61,代码来源:class.RDSMaintenanceProcess.php

示例12: getContent

 public function getContent($params = array())
 {
     $environments = $this->user->getEnvironments();
     foreach ($environments as &$env) {
         $environment = Scalr_Environment::init()->loadById($env['id']);
         $env['farmsCount'] = $environment->getFarmsCount();
         $env['serversCount'] = $environment->getRunningServersCount();
     }
     return ['environments' => $environments];
 }
开发者ID:mheydt,项目名称:scalr,代码行数:10,代码来源:Environments.php

示例13: run2

 protected function run2($stage)
 {
     $envIds = $this->db->GetCol('SELECT DISTINCT env_id FROM `comments` WHERE env_id > 0');
     $this->console->out("Environments to process: " . count($envIds));
     foreach ($envIds as $index => $envId) {
         if ($this->db->GetOne('SELECT 1 FROM `security_group_rules_comments` WHERE env_id = ? LIMIT 1', array($envId))) {
             $this->console->out("Skip environment #{$index}(" . $envId . ")");
             continue;
         }
         try {
             $env = \Scalr_Environment::init()->loadById($envId);
         } catch (\Exception $e) {
             continue;
         }
         $locations = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::EC2)->getLocations($env);
         $container = \Scalr::getContainer();
         $container->environment = $env;
         foreach ($locations as $location => $locatonName) {
             try {
                 $sgList = $env->aws($location)->ec2->securityGroup->describe();
             } catch (\Exception $e) {
                 continue 2;
             }
             /* @var $sg SecurityGroupData */
             foreach ($sgList as $sg) {
                 $rules = array();
                 foreach ($sg->ipPermissions as $rule) {
                     /* @var $ipRange IpRangeData */
                     foreach ($rule->ipRanges as $ipRange) {
                         $rules[] = "{$rule->ipProtocol}:{$rule->fromPort}:{$rule->toPort}:{$ipRange->cidrIp}";
                     }
                     /* @var $group UserIdGroupPairData */
                     foreach ($rule->groups as $group) {
                         $ruleSg = $group->userId . '/' . ($group->groupName ? $group->groupName : $group->groupId);
                         $rules[] = "{$rule->ipProtocol}:{$rule->fromPort}:{$rule->toPort}:{$ruleSg}";
                     }
                 }
                 foreach ($rules as $rule) {
                     $comment = $this->db->GetOne('SELECT comment FROM `comments` WHERE env_id = ? AND sg_name = ? AND rule = ? LIMIT 1', array($envId, $sg->groupName, $rule));
                     if ($comment) {
                         try {
                             $this->db->Execute("\n                                    INSERT IGNORE `security_group_rules_comments` (`env_id`, `platform`, `cloud_location`, `vpc_id`, `group_name`, `rule`, `comment`)\n                                    VALUES (?, ?, ?, ?, ?, ?, ?)\n                                ", array($env->id, \SERVER_PLATFORMS::EC2, $location, $sg->vpcId, $sg->groupName, $rule, $comment));
                         } catch (\Exception $e) {
                         }
                     }
                 }
             }
         }
         $this->console->out("Environment processed: #{$index}(" . $envId . ")");
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:51,代码来源:Update20140213144218.php

示例14: Run

 public function Run()
 {
     global $db;
     $time = microtime(true);
     $images = $db->Execute("SELECT * FROM role_images WHERE architecture IS NULL AND platform = 'ec2' ORDER BY id DESC");
     while ($image = $images->FetchRow()) {
         $role = DBRole::loadById($image['role_id']);
         if ($role->clientId == 0) {
             continue;
         }
         $environemnt = Scalr_Environment::init()->loadById($role->envId);
         try {
             $acrh = $environemnt->aws($image['cloud_location'])->ec2->image->describe($image['image_id'])->get(0)->architecture;
             $db->Execute("UPDATE role_images SET architecture = ? WHERE id = ?", array($acrh, $image['id']));
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "does not exist") && stristr($e->getMessage(), 'The image id')) {
                 //$db->Execute("DELETE FROM role_images WHERE id = ?", array($image['id']));
                 print "Removed {$image['image_id']} because: {$e->getMessage()}\n";
                 continue;
             } elseif (stristr($e->getMessage(), "AWS was not able to validate the provided access credentials")) {
                 continue;
             } elseif (stristr($e->getMessage(), "You are not subscribed to this service")) {
                 continue;
             } elseif (stristr($e->getMessage(), "Invalid id")) {
                 $db->Execute("DELETE FROM role_images WHERE id = ?", array($image['id']));
                 continue;
             }
             var_dump($e->getMessage());
             exit;
         }
     }
     $db->Execute("ALTER TABLE  `roles` DROP  `is_stable` , DROP  `approval_state` , DROP  `szr_version` ;");
     $db->Execute("ALTER TABLE  `roles` DROP  `architecture` ;");
     $db->Execute("ALTER TABLE  `roles` ADD  `os_family` VARCHAR( 30 ) NULL ,\n            ADD  `os_generation` VARCHAR( 10 ) NULL ,\n            ADD  `os_version` VARCHAR( 10 ) NULL\n        ");
     //SSL certs refactoring
     $db->Execute("ALTER TABLE  `apache_vhosts` ADD  `ssl_cert_id` INT( 11 ) NULL");
     $db->Execute("CREATE TABLE IF NOT EXISTS `services_ssl_certs` (\n          `id` int(11) NOT NULL AUTO_INCREMENT,\n          `env_id` int(11) NOT NULL,\n          `name` varchar(40) NOT NULL,\n          `ssl_pkey` text NULL,\n          `ssl_cert` text NULL,\n          `ssl_cabundle` text NULL,\n          PRIMARY KEY (`id`)\n        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;");
     $vhosts = $db->Execute("SELECT * FROM apache_vhosts WHERE is_ssl_enabled = '1'");
     while ($vhost = $vhosts->FetchRow()) {
         $db->Execute("INSERT INTO services_ssl_certs SET\n                env_id = ?,\n                name = ?,\n                ssl_pkey = ?,\n                ssl_cert = ?,\n                ssl_cabundle = ?\n            ", array($vhost['env_id'], $vhost['name'], $vhost['ssl_key'], $vhost['ssl_cert'], $vhost['ca_cert']));
         $certId = $db->Insert_ID();
         $db->Execute("UPDATE apache_vhosts SET ssl_cert_id = ? WHERE id = ?", array($certId, $vhost['id']));
     }
     print "Done.\n";
     $t = round(microtime(true) - $time, 2);
     printf("Upgrade process took %0.2f seconds\n\n\n", $t);
 }
开发者ID:recipe,项目名称:scalr,代码行数:47,代码来源:upgrade_20130417.php

示例15: Run

 public function Run()
 {
     global $db;
     $time = microtime(true);
     $rs = $db->Execute("\n            SELECT DISTINCT c1.`env_id`\n            FROM `client_environment_properties` c1\n            JOIN `client_environment_properties` c2 ON c2.env_id = c1.env_id\n            WHERE c1.`name` = 'cloudyn.enabled' AND c1.`value` = '1'\n            AND c2.`name` = 'ec2.is_enabled' AND c2.`value` = '1'\n        ");
     foreach ($rs as $row) {
         $env = Scalr_Environment::init();
         $env->loadById($row['env_id']);
         $awsUsername = sprintf('scalr-cloudyn-%s-%s', $env->id, SCALR_ID);
         $policyName = sprintf('cloudynpolicy-%s', $env->id);
         try {
             $policy = $env->aws->iam->user->getUserPolicy($awsUsername, $policyName);
             $aPolicy = json_decode($policy, true);
             $bUpdated = false;
             if (!empty($aPolicy['Statement'])) {
                 foreach ($aPolicy['Statement'] as $k => $v) {
                     if (!isset($v['Effect']) || $v['Effect'] != 'Allow') {
                         continue;
                     }
                     if (!empty($v['Action']) && is_array($v['Action'])) {
                         $ptr =& $aPolicy['Statement'][$k]['Action'];
                         if (!in_array("rds:List*", $ptr)) {
                             $ptr[] = "rds:List*";
                             $bUpdated = true;
                         }
                         if (!in_array("s3:GetBucketTagging", $ptr)) {
                             $ptr[] = "s3:GetBucketTagging";
                             $bUpdated = true;
                         }
                         unset($ptr);
                         if ($bUpdated) {
                             $env->aws->iam->user->putUserPolicy($awsUsername, $policyName, json_encode($aPolicy));
                             break;
                         }
                     }
                 }
             }
         } catch (ClientException $e) {
             echo $e->getMessage() . "\n";
         }
         unset($env);
     }
     print "Done.\n";
     $t = round(microtime(true) - $time, 2);
     printf("Upgrade process took %0.2f seconds\n\n\n", $t);
 }
开发者ID:recipe,项目名称:scalr,代码行数:46,代码来源:upgrade_20130401.php


注:本文中的Scalr_Environment::init方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。