init() public static method

Init
public static init ( string $className = null ) : Scalr_Environment
$className string
return Scalr_Environment
Example #1
0
 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());
                 }
             }
         }
     }
 }
Example #2
0
 /**
  * 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());
             }
         }
     }
 }
Example #3
0
 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());
             }
         }
     }
 }
Example #4
0
 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;
 }
Example #5
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     if (self::isSkippedFunctionalTest(self::TEST_TYPE_UI)) {
         return;
     }
     $db = \Scalr::getDb();
     self::deleteTestVariables();
     $envId = \Scalr::config('scalr.phpunit.envid');
     if (!$envId) {
         return;
     }
     $env = \Scalr_Environment::init()->loadById($envId);
     self::$vars[ScopeInterface::SCOPE_SCALR] = new Scalr_Scripting_GlobalVariables();
     self::$vars[ScopeInterface::SCOPE_ACCOUNT] = new Scalr_Scripting_GlobalVariables($env->clientId, 0, ScopeInterface::SCOPE_ACCOUNT);
     self::$vars[ScopeInterface::SCOPE_ENVIRONMENT] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_ENVIRONMENT);
     self::$args[ScopeInterface::SCOPE_SCALR] = self::$args[ScopeInterface::SCOPE_ACCOUNT] = self::$args[ScopeInterface::SCOPE_ENVIRONMENT] = [0, 0, 0, ''];
     /* @var $farm Farm */
     $farm = Farm::findOne([['envId' => $env->id]]);
     if ($farm) {
         self::$vars[ScopeInterface::SCOPE_FARM] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_FARM);
         self::$args[ScopeInterface::SCOPE_FARM] = [0, $farm->id, 0, ''];
         /* @var $farmRole FarmRole */
         $farmRole = FarmRole::findOne([['farmId' => $farm->id]]);
         if ($farmRole) {
             self::$vars[ScopeInterface::SCOPE_ROLE] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_ROLE);
             self::$args[ScopeInterface::SCOPE_ROLE] = [$farmRole->roleId, 0, 0, ''];
             self::$vars[ScopeInterface::SCOPE_FARMROLE] = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_FARMROLE);
             self::$args[ScopeInterface::SCOPE_FARMROLE] = [$farmRole->roleId, $farm->id, $farmRole->id, ''];
         }
     }
 }
Example #6
0
 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;
                 }
             }
         }
     }
 }
Example #7
0
 /**
  * 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);
 }
Example #8
0
 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();
     }
 }
Example #9
0
 /**
  * {@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();
     }
 }
Example #10
0
 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()}");
             }
         }
     }
 }
 /**
  * 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()));
         }
     }
 }
Example #12
0
 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];
 }
Example #13
0
 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 . ")");
     }
 }
Example #14
0
 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);
 }
Example #15
0
 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);
 }
Example #16
0
 public function getContext()
 {
     $data = array();
     if ($this->user) {
         $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => $this->getEnvironment() ? $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS) : '', 'type' => $this->user->getType());
         if (!$this->user->isScalrAdmin()) {
             $data['farms'] = $this->db->getAll('SELECT id, name FROM farms WHERE env_id = ? ORDER BY name', array($this->getEnvironmentId()));
             if ($this->user->getAccountId() != 0) {
                 $data['flags'] = $this->user->getAccount()->getFeaturesList();
                 $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false;
             } else {
                 $data['flags'] = array();
             }
             $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled');
             $data['flags']['featureUsersPermissions'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_USERS_PERMISSIONS);
             $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url');
             $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url');
             $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true);
             if ($this->user->isAccountOwner()) {
                 if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) {
                     if (count($this->environment->getEnabledPlatforms()) == 0) {
                         $data['flags']['needEnvConfig'] = Scalr_Environment::init()->loadDefault($this->user->getAccountId())->id;
                     }
                 }
             }
             $data['environments'] = $this->user->getEnvironments();
             if ($this->getEnvironment() && $this->user->isTeamOwner()) {
                 $data['user']['isTeamOwner'] = true;
             }
         }
         $data['platforms'] = array();
         $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds');
         foreach (SERVER_PLATFORMS::getList() as $platform => $platformName) {
             if (!in_array($platform, $allowedClouds) || $platform == SERVER_PLATFORMS::UCLOUD && !$this->request->getHeaderVar('Interface-Beta')) {
                 continue;
             }
             $data['platforms'][$platform] = array('enabled' => $this->user->isScalrAdmin() ? false : !!$this->environment->isPlatformEnabled($platform), 'name' => $platformName);
         }
     }
     $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode');
     $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken();
     return $data;
 }
Example #17
0
 protected function run1($stage)
 {
     if (\Scalr::getContainer()->analytics->enabled) {
         $properties = EnvironmentProperty::find([['name' => Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET]]);
         foreach ($properties as $property) {
             /* @var $property EnvironmentProperty */
             $environment = \Scalr_Environment::init()->loadById($property->envId);
             $accountType = $environment->getPlatformConfigValue(Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE);
             if ($accountType == Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE_REGULAR) {
                 $region = Aws::REGION_US_EAST_1;
             } else {
                 $platformModule = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::EC2);
                 /* @var $platformModule Ec2PlatformModule */
                 $locations = array_keys($platformModule->getLocationsByAccountType($accountType));
                 $region = reset($locations);
             }
             $environment->setPlatformConfig([Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_REGION => $region]);
         }
     }
 }
Example #18
0
 public function xGetWindowsPasswordAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_SECURITY_RETRIEVE_WINDOWS_PASSWORDS);
     $this->request->defineParams(array('serverId'));
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     if ($dbServer->platform == SERVER_PLATFORMS::EC2) {
         $env = Scalr_Environment::init()->loadById($dbServer->envId);
         $ec2 = $env->aws($dbServer->GetCloudLocation())->ec2;
         $encPassword = $ec2->instance->getPasswordData($dbServer->GetCloudServerID());
         $privateKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->farmId, $dbServer->GetCloudLocation(), $dbServer->platform);
         $password = Scalr_Util_CryptoTool::opensslDecrypt(base64_decode($encPassword->passwordData), $privateKey->getPrivate());
     } elseif (PlatformFactory::isOpenstack($dbServer->platform)) {
         $env = Scalr_Environment::init()->loadById($dbServer->envId);
         $os = $env->openstack($dbServer->platform, $dbServer->GetCloudLocation());
         //TODO:
     } else {
         throw new Exception("Requested operation supported only by EC2");
     }
     $this->response->data(array('password' => $password));
 }
Example #19
0
 protected function run1($stage)
 {
     $this->console->out("Retrieving all environments");
     $res = $this->db->Execute("\n            SELECT e.id FROM client_environments e\n            JOIN client_environment_properties p ON e.id = p.env_id\n            WHERE p.name = ? AND p.value != ''\n        ", array(Ec2PlatformModule::ACCESS_KEY));
     while ($rec = $res->FetchRow()) {
         $env = \Scalr_Environment::init()->loadById($rec['id']);
         if (!$env instanceof \Scalr_Environment) {
             continue;
         }
         $accountNumber = $env->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_ID);
         try {
             $num = $env->aws()->getAccountNumber();
             if ($num != $accountNumber) {
                 $this->console->out('Updating account_number for %d environment: "%s" -> "%s"', $env->id, $accountNumber, $num);
                 $env->setPlatformConfig(array(Ec2PlatformModule::ACCOUNT_ID => $num));
             }
         } catch (\Exception $e) {
             $this->console->warning("Environment %s fails: %s", $env->id, $e->getMessage());
         }
     }
 }
Example #20
0
 /**
  * Raises onCloudAdd notification event
  *
  * @param   string              $platform    A platform name.
  * @param   \Scalr_Environment  $environment An environment object which cloud is created in.
  * @param   \Scalr_Account_User $user        An user who has created platform.
  */
 public function onCloudAdd($platform, $environment, $user)
 {
     $container = \Scalr::getContainer();
     $analytics = $container->analytics;
     //Nothing to do in case analytics is disabled
     if (!$analytics->enabled) {
         return;
     }
     if (!$environment instanceof \Scalr_Environment) {
         $environment = \Scalr_Environment::init()->loadById($environment);
     }
     $pm = PlatformFactory::NewPlatform($platform);
     //Check if there are some price for this platform and endpoint url
     if (($endpointUrl = $pm->hasCloudPrices($environment)) === true) {
         return;
     }
     //Disabled or badly configured environment
     if ($endpointUrl === false && !in_array($platform, [\SERVER_PLATFORMS::EC2, \SERVER_PLATFORMS::GCE])) {
         return;
     }
     //Send a message to financial admin if there are not any price for this cloud
     $baseUrl = rtrim($container->config('scalr.endpoint.scheme') . "://" . $container->config('scalr.endpoint.host'), '/');
     //Disable notifications for hosted Scalr
     if (!\Scalr::isAllowedAnalyticsOnHostedScalrAccount($environment->clientId)) {
         return;
     }
     $emails = $this->getFinancialAdminEmails();
     //There isn't any financial admin
     if (empty($emails)) {
         return;
     }
     $emails = array_map(function ($email) {
         return '<' . trim($email, '<>') . '>';
     }, $emails);
     try {
         $res = $container->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/analytics_on_cloud_add.eml.php', ['isPublicCloud' => $platform == \SERVER_PLATFORMS::EC2, 'userEmail' => $user->getEmail(), 'cloudName' => \SERVER_PLATFORMS::GetName($platform), 'linkToPricing' => $baseUrl . '/#/analytics/pricing?platform=' . urlencode($platform) . '&url=' . urlencode($endpointUrl === false ? '' : $analytics->prices->normalizeUrl($endpointUrl))], join(',', $emails));
     } catch (\Exception $e) {
     }
 }
Example #21
0
     $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::USERNAME] = $env->getPlatformConfigValue(SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::USERNAME);
     $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::PASSWORD] = $env->getPlatformConfigValue(SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::PASSWORD);
     $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::TENANT_NAME] = $env->getPlatformConfigValue(SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::TENANT_NAME);
 }
 if ($updateEnv) {
     $env->setPlatformConfig(array(SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::AUTH_TOKEN => false));
 }
 //var_dump($pars);
 $os = new OpenStack(new OpenStackConfig($pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::USERNAME], $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::KEYSTONE_URL], 'fake-region', null, null, null, $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::PASSWORD], $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::TENANT_NAME]));
 $zones = $os->listZones();
 if ($updateEnv) {
     $env->enablePlatform(SERVER_PLATFORMS::ECS, true);
     $env->setPlatformConfig($pars);
 }
 unset($env);
 $env = Scalr_Environment::init()->loadById($envId);
 \Scalr::getContainer()->environment = $env;
 $configSet = false;
 foreach ($zones as $zone) {
     $osClient = $env->openstack(SERVER_PLATFORMS::ECS, $zone->name);
     // Check SG Extension
     if (!$configSet) {
         $pars2 = array();
         $pars2[getOpenStackOption('EXT_SECURITYGROUPS_ENABLED')] = (int) $osClient->servers->isExtensionSupported(ServersExtension::securityGroups());
         // Check Floating Ips Extension
         $pars2[getOpenStackOption('EXT_FLOATING_IPS_ENABLED')] = (int) $osClient->servers->isExtensionSupported(ServersExtension::floatingIps());
         // Check Cinder Extension
         $pars2[getOpenStackOption('EXT_CINDER_ENABLED')] = (int) $osClient->hasService('volume');
         // Check Swift Extension
         $pars2[getOpenStackOption('EXT_SWIFT_ENABLED')] = (int) $osClient->hasService('object-store');
         // Check LBaas Extension
Example #22
0
 /**
  * xGetPlatformInstanceTypesAction
  *
  * @param    string        $platform      The name of the cloud platform
  * @param    string        $cloudLocation The cloud location
  * @param    string        $envId         optional The identifier of the environment
  * @param    string        $effectiveDate optional The date on which prices should be applied YYYY-MM-DD
  * @throws   \Exception
  */
 public function xGetPlatformInstanceTypesAction($platform, $cloudLocation, $envId = null, $effectiveDate = null)
 {
     list($curDate, $effectiveDate) = $this->handleEffectiveDate($effectiveDate);
     $pm = PlatformFactory::NewPlatform($platform);
     $env = null;
     $url = '';
     try {
         if (!empty($envId)) {
             $env = Scalr_Environment::init()->loadById($envId);
             if (PlatformFactory::isOpenstack($platform)) {
                 $key = Entity\CloudCredentialsProperty::OPENSTACK_KEYSTONE_URL;
             } else {
                 if (PlatformFactory::isCloudstack($platform)) {
                     $key = Entity\CloudCredentialsProperty::CLOUDSTACK_API_URL;
                 } else {
                     throw new Exception('This action is not yet supported for the specified cloud platform.');
                 }
             }
             if (empty($url)) {
                 $url = $env->keychain($platform)->properties[$key];
             }
         } else {
             if ($platform == SERVER_PLATFORMS::EC2 || $platform == SERVER_PLATFORMS::GCE) {
                 $gcenvid = $this->getEnvIdByPlatform($platform);
                 $env = Scalr_Environment::init()->loadById($gcenvid);
             }
         }
     } catch (Exception $e) {
         if (stristr($e->getMessage(), 'not found')) {
             //Tries to find url from the cloud_locations table
             if (empty($url) && (PlatformFactory::isOpenstack($platform) || PlatformFactory::isCloudstack($platform))) {
                 $clEntity = CloudLocation::findOne([['platform' => $platform], ['cloudLocation' => $cloudLocation]], null, ['updated' => false]);
                 if ($clEntity instanceof CloudLocation) {
                     $url = $clEntity->url;
                 }
             }
         } else {
             throw $e;
         }
     }
     $result = $this->getTypesWithPrices($cloudLocation, $url, $pm, $platform, $effectiveDate, $env);
     $this->response->data(['data' => $result]);
 }
Example #23
0
 /**
  * Create tags for different EC2 objects (instance, volume, ami)
  * @param object $object (DBServer and BundleTask)
  */
 public static function createObjectTags($object)
 {
     if ($object instanceof \BundleTask) {
         // Create tags for AMI
         try {
             $env = \Scalr_Environment::init()->loadById($object->envId);
             $aws = $env->aws($object->cloudLocation);
             if ($object->farmId != 0) {
                 $dbServer = \DBServer::LoadByID($object->serverId);
                 $objectTags = [];
                 foreach ($dbServer->getAwsTags(true) as $k => $v) {
                     if ($k != 'Name') {
                         $objectTags[] = ['key' => $k, 'value' => $v];
                     }
                 }
                 $aws->ec2->image->describe($object->snapshotId)->get(0)->createTags($objectTags);
                 $object->Log(sprintf("Added %s tags for AMI (%s)", count($objectTags), $object->snapshotId));
             } else {
                 return;
             }
         } catch (\Exception $e) {
             $object->Log(sprintf("Scalr was unable to add tags for AMI (%s): %s", $object->snapshotId, $e->getMessage()));
         }
     } elseif ($object instanceof \DBServer) {
         // Create tags for Instance and root-device volume
         try {
             $dbServer = $object;
             $aws = $dbServer->GetEnvironmentObject()->aws($dbServer);
             if ($dbServer->farmId != 0) {
                 $ind = $aws->ec2->instance->describe($dbServer->GetProperty(\EC2_SERVER_PROPERTIES::INSTANCE_ID))->get(0)->instancesSet->get(0);
                 $metaTagFound = false;
                 foreach ($ind->tagSet as $tag) {
                     /* @var $tag \Scalr\Service\Aws\Ec2\DataType\ResourceTagSetData */
                     if ($tag->key == \Scalr_Governance::SCALR_META_TAG_NAME) {
                         $metaTagFound = true;
                         break;
                     }
                 }
                 if ($metaTagFound) {
                     return;
                 }
                 $instanceTags = [];
                 $volumeTags = [];
                 foreach ($dbServer->getAwsTags(true) as $k => $v) {
                     $instanceTags[] = ['key' => $k, 'value' => $v];
                     if ($k != 'Name') {
                         $volumeTags[] = ['key' => $k, 'value' => $v];
                     }
                 }
                 $res = $ind->createTags($instanceTags);
                 // We also need to tag root device
                 if ($ind->rootDeviceType == 'ebs') {
                     $filter = array(array('name' => VolumeFilterNameType::attachmentInstanceId(), 'value' => $dbServer->GetCloudServerID()), array('name' => VolumeFilterNameType::attachmentDevice(), 'value' => '/dev/sda1'));
                     $ebs = $aws->ec2->volume->describe(null, $filter);
                     foreach ($ebs as $volume) {
                         /* @var $volume \Scalr\Service\Aws\Ec2\DataType\VolumeData */
                         $volume->createTags($volumeTags);
                     }
                 }
             }
         } catch (\Exception $e) {
             \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->error(new \FarmLogMessage($dbServer->farmId, sprintf(_("Scalr was unable to add tags to the server/volume '{$dbServer->serverId}': %s"), $e->getMessage()), $dbServer->serverId));
         }
     } else {
         return;
     }
 }
Example #24
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Pcntl\ProcessInterface::OnEndForking()
  */
 public function OnEndForking()
 {
     $db = \Scalr::getDb();
     \Scalr::getContainer()->logger(__CLASS__)->warn("OnEndForking: start");
     $list = $db->GetAll("\n            SELECT farm_roleid\n            FROM farm_role_settings\n            WHERE name=? AND value='1'\n        ", array(Scalr_Db_Msr::DATA_STORAGE_EBS_ENABLE_ROTATION));
     foreach ($list as $list_item) {
         try {
             $DBFarmRole = DBFarmRole::LoadByID($list_item['farm_roleid']);
         } catch (Exception $e) {
             continue;
         }
         try {
             $DBFarm = $DBFarmRole->GetFarmObject();
         } catch (Exception $e) {
             continue;
         }
         if ($DBFarm->Status == FARM_STATUS::RUNNING) {
             $old_snapshots = $db->GetAll("\n                    SELECT id FROM storage_snapshots\n                    WHERE farm_roleid=?\n                    AND `type`='ebs'\n                    ORDER BY dtcreated ASC\n                ", array($DBFarmRole->ID));
             $r = (int) $DBFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EBS_ROTATE);
             if (count($old_snapshots) > $r && $r > 0) {
                 try {
                     $aws = $DBFarm->GetEnvironmentObject()->aws($DBFarmRole);
                     while (count($old_snapshots) > $r) {
                         $snapinfo = array_shift($old_snapshots);
                         try {
                             $aws->ec2->snapshot->delete($snapinfo['id']);
                             $this->deleteStorageSnapshot($snapinfo['id']);
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "does not exist")) {
                                 $this->deleteStorageSnapshot($snapinfo['id']);
                             } else {
                                 throw $e;
                             }
                         }
                     }
                     //Releases memory
                     $DBFarm->GetEnvironmentObject()->getContainer()->release('aws');
                     unset($aws);
                 } catch (Exception $e) {
                     $this->logger->warn(sprintf(_("Cannot delete old snapshot ({$snapinfo['id']}): %s"), $e->getMessage()));
                 }
             }
         }
     }
     \Scalr::getContainer()->logger(__CLASS__)->warn("OnEndForking: rotate mysql snapshots");
     // Rotate MySQL master snapshots.
     $list = $db->GetAll("\n            SELECT farm_roleid\n            FROM farm_role_settings\n            WHERE name=? AND value='1'\n        ", [Entity\FarmRoleSetting::MYSQL_EBS_SNAPS_ROTATION_ENABLED]);
     foreach ($list as $list_item) {
         try {
             $DBFarmRole = DBFarmRole::LoadByID($list_item['farm_roleid']);
         } catch (Exception $e) {
             continue;
         }
         try {
             $DBFarm = $DBFarmRole->GetFarmObject();
         } catch (Exception $e) {
             continue;
         }
         if ($DBFarm->Status == FARM_STATUS::RUNNING) {
             $old_snapshots = $db->GetAll("\n                    SELECT * FROM storage_snapshots\n                    WHERE ismysql='1'\n                    AND farm_roleid=?\n                    AND `type`='ebs'\n                    ORDER BY dtcreated ASC\n                ", [$DBFarmRole->ID]);
             if (count($old_snapshots) > $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_EBS_SNAPS_ROTATE)) {
                 try {
                     $aws = $DBFarm->GetEnvironmentObject()->aws($DBFarmRole);
                     while (count($old_snapshots) > $DBFarmRole->GetSetting(Entity\FarmRoleSetting::MYSQL_EBS_SNAPS_ROTATE)) {
                         $snapinfo = array_shift($old_snapshots);
                         try {
                             $aws->ec2->snapshot->delete($snapinfo['id']);
                             $this->deleteEbsSnapshotInfo($snapinfo['id']);
                             $this->deleteStorageSnapshot($snapinfo['id']);
                         } catch (Exception $e) {
                             if (stristr($e->getMessage(), "does not exist")) {
                                 $this->deleteEbsSnapshotInfo($snapinfo['id']);
                                 $this->deleteStorageSnapshot($snapinfo['id']);
                             } else {
                                 throw $e;
                             }
                         }
                     }
                     $DBFarm->GetEnvironmentObject()->getContainer()->release('aws');
                     unset($aws);
                 } catch (Exception $e) {
                     $this->logger->warn(sprintf(_("Cannot delete old snapshots snapshotid:%s. %s"), isset($snapinfo['id']) ? $snapinfo['id'] : 'null', $e->getMessage()));
                 }
             }
         }
     }
     \Scalr::getContainer()->logger(__CLASS__)->warn("OnEndForking: auto-snapshot volumes");
     // Auto - snapshotting
     $snapshots_settings = $db->Execute("\n            SELECT * FROM autosnap_settings\n            WHERE (`dtlastsnapshot` < NOW() - INTERVAL `period` HOUR OR `dtlastsnapshot` IS NULL)\n            AND objectid != '0' AND object_type = ?", array(AUTOSNAPSHOT_TYPE::EBSSnap));
     \Scalr::getContainer()->logger(__CLASS__)->warn(sprintf("OnEndForking: found %s volumes", $snapshots_settings->RecordCount()));
     while ($snapshot_settings = $snapshots_settings->FetchRow()) {
         try {
             $environment = Scalr_Environment::init()->loadById($snapshot_settings['env_id']);
             $account = Scalr_Account::init()->loadById($environment->clientId);
             if ($account->status != Scalr_Account::STATUS_ACTIVE) {
                 continue;
             }
             $aws = $environment->aws($snapshot_settings['region']);
             // Check volume
             try {
                 $volume = $aws->ec2->volume->describe($snapshot_settings['objectid'])->get(0);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "does not exist")) {
                     $db->Execute("DELETE FROM autosnap_settings WHERE id=?", array($snapshot_settings['id']));
                 }
                 throw $e;
             }
             $description = "Auto snapshot created by Scalr";
             if (true) {
                 $info = $db->GetRow("\n                        SELECT * FROM ec2_ebs WHERE volume_id=? LIMIT 1\n                    ", array($snapshot_settings['objectid']));
                 $farmName = false;
                 $roleName = false;
                 $serverIndex = false;
                 if ($info) {
                     try {
                         $farmName = DBFarm::LoadByID($info['farm_id'])->Name;
                         $roleName = DBFarmRole::LoadByID($info['farm_roleid'])->GetRoleObject()->name;
                         $serverIndex = $info['server_index'];
                     } catch (Exception $e) {
                     }
                 }
                 if ($farmName) {
                     $description = sprintf("Auto snapshot created by Scalr: %s -> %s #%s", $farmName, $roleName, $serverIndex);
                 }
             }
             //Creates a new snapshot
             $snapshot = $aws->ec2->snapshot->create($snapshot_settings['objectid'], $description);
             if (!empty($volume->tagSet) && $volume->tagSet->count()) {
                 try {
                     //We need to do sleep due to eventual consistency on EC2
                     sleep(2);
                     //Set tags (copy them from the original EBS volume)
                     $snapshot->createTags($volume->tagSet);
                 } catch (Exception $e) {
                     //We want to hear from the cases when it cannot set tag to snapshot
                     trigger_error(sprintf("Could not set tag to snapshot: %s", $e->getMessage()), E_USER_WARNING);
                 }
             }
             $db->Execute("\n                    UPDATE autosnap_settings SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?\n                ", [$snapshot->snapshotId, $snapshot_settings['id']]);
             $db->Execute("\n                    INSERT INTO ebs_snaps_info SET snapid=?, comment=?, dtcreated=NOW(), region=?, autosnapshotid=?\n                ", [$snapshot->snapshotId, _("Auto-snapshot"), $snapshot_settings['region'], $snapshot_settings['id']]);
             // Remove old snapshots
             if ($snapshot_settings['rotate'] != 0) {
                 $old_snapshots = $db->GetAll("\n                        SELECT * FROM ebs_snaps_info\n                        WHERE autosnapshotid=?\n                        ORDER BY id ASC\n                    ", [$snapshot_settings['id']]);
                 if (count($old_snapshots) > $snapshot_settings['rotate']) {
                     try {
                         while (count($old_snapshots) > $snapshot_settings['rotate']) {
                             $snapinfo = array_shift($old_snapshots);
                             try {
                                 $aws->ec2->snapshot->delete($snapinfo['snapid']);
                                 $this->deleteEbsSnapshotInfo($snapinfo['id']);
                             } catch (Exception $e) {
                                 if (stristr($e->getMessage(), "does not exist")) {
                                     $this->deleteEbsSnapshotInfo($snapinfo['id']);
                                 }
                                 throw $e;
                             }
                         }
                     } catch (Exception $e) {
                         $this->logger->error(sprintf(_("Cannot delete old snapshots for volume %s. %s"), $snapshot_settings['objectid'], $e->getMessage()));
                     }
                 }
             }
             $environment->getContainer()->release('aws');
             unset($aws);
         } catch (Exception $e) {
             $this->logger->warn(sprintf(_("Cannot create snapshot for volume %s. %s"), $snapshot_settings['objectid'], $e->getMessage()));
         }
     }
 }
Example #25
0
 /**
  * Get default environment (or given) and check access to it
  * @param integer $envId
  * @return Scalr_Environment
  * @throws Scalr_Exception_Core
  */
 public function getDefaultEnvironment($envId = 0)
 {
     try {
         if ($envId) {
             $environment = Scalr_Environment::init()->loadById($envId);
             if (!$this->getPermissions()->check($environment)) {
                 $envId = 0;
             }
         } else {
             $envId = (int) $this->getSetting(Scalr_Account_User::SETTING_UI_ENVIRONMENT);
             if ($envId) {
                 $environment = Scalr_Environment::init()->loadById($envId);
                 if (!$this->getPermissions()->check($environment)) {
                     $envId = 0;
                 }
             }
         }
     } catch (Exception $e) {
         $envId = 0;
     }
     if (!$envId) {
         $envs = $this->getEnvironments();
         if (count($envs)) {
             $environment = Scalr_Environment::init()->loadById($envs[0]['id']);
         } else {
             throw new Scalr_Exception_Core('You don\'t have access to any environment.');
         }
     }
     $this->getPermissions()->validate($environment);
     return $environment;
 }
Example #26
0
 /**
  * {@inheritdoc}
  * @see Scalr_System_Cronjob_MultiProcess_DefaultWorker::handleWork()
  */
 function handleWork($farmId)
 {
     try {
         $dbFarm = DBFarm::LoadByID($farmId);
         if ($dbFarm->Status != FARM_STATUS::RUNNING) {
             return;
         }
     } catch (Exception $e) {
         return;
     }
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         $instancesHealth = array();
         if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
             $env = Scalr_Environment::init()->loadById($dbFarm->EnvID);
             $aws = $env->aws($dbFarmRole);
             $statusList = $aws->ec2->instance->describeStatus();
             foreach ($statusList as $sd) {
                 /* @var $sd \Scalr\Service\Aws\Ec2\DataType\InstanceStatusData */
                 $instancesHealth[$sd->instanceId] = $sd;
             }
             unset($statusList);
             //Releases memory
             $env->getContainer()->release('aws');
             unset($aws);
         }
         $servers = $this->db->Execute("\n                SELECT server_id FROM servers\n                WHERE farm_roleid = ? AND status = ?\n            ", array($dbFarmRole->ID, SERVER_STATUS::RUNNING));
         while ($server = $servers->FetchRow()) {
             $dbServer = DBServer::LoadByID($server['server_id']);
             // Do not support ami-scripts
             if (!$dbServer->IsSupported("0.5")) {
                 continue;
             }
             // Do not support windows
             if ($dbServer->IsSupported("0.8") && !$dbServer->IsSupported("0.9")) {
                 continue;
             }
             if ($dbServer->GetProperty(SERVER_PROPERTIES::REBOOTING)) {
                 continue;
             }
             $serverAlerts = new Alerts($dbServer);
             //Check AWS healthchecks
             if ($dbServer->platform == SERVER_PLATFORMS::EC2) {
                 try {
                     /* @var $statusInfo \Scalr\Service\Aws\Ec2\DataType\InstanceStatusData */
                     $statusInfo = isset($instancesHealth[$dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)]) ? $instancesHealth[$dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)] : null;
                     if ($statusInfo) {
                         $check = Alerts::METRIC_AWS_SYSTEM_STATUS;
                         $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
                         if ($statusInfo->systemStatus->status == 'ok' && $hasActiveAlert) {
                             Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
                         } elseif ($statusInfo->systemStatus->status != 'ok' && $statusInfo->systemStatus->status != 'initializing' && !$hasActiveAlert) {
                             $txtDetails = "";
                             $details = $statusInfo->systemStatus->details;
                             if ($details) {
                                 foreach ($details as $d) {
                                     /* @var $d \Scalr\Service\Aws\Ec2\DataType\InstanceStatusDetailsSetData */
                                     $txtDetails .= " {$d->name} is {$d->status},";
                                 }
                                 $txtDetails = trim($txtDetails, " ,");
                                 unset($details);
                             }
                             Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, "{$statusInfo->systemStatus->status}: {$txtDetails}"));
                         }
                         $check = Alerts::METRIC_AWS_INSTANCE_STATUS;
                         $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
                         if ($statusInfo->instanceStatus->status == 'ok' && $hasActiveAlert) {
                             Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
                         } else {
                             if ($statusInfo->instanceStatus->status != 'ok' && $statusInfo->instanceStatus->status != 'initializing' && !$hasActiveAlert) {
                                 $txtDetails = "";
                                 $details = $statusInfo->instanceStatus->details;
                                 if ($details) {
                                     foreach ($details as $d) {
                                         /* @var $d \Scalr\Service\Aws\Ec2\DataType\InstanceStatusDetailsSetData */
                                         $txtDetails .= " {$d->name} is {$d->status},";
                                     }
                                     $txtDetails = trim($txtDetails, " ,");
                                     unset($details);
                                 }
                                 Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, "{$statusInfo->instanceStatus->status}: {$txtDetails}"));
                             }
                         }
                         unset($statusInfo);
                     }
                 } catch (Exception $e) {
                 }
             }
             //Not supported by VPC yet.
             if ($dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
                 continue;
             }
             $ip = $dbServer->getSzrHost();
             //Check scalr-upd-client status
             $check = Alerts::METRIC_SCALARIZR_UPD_CLIENT_CONNECTIVITY;
             $port = $dbServer->getPort(DBServer::PORT_UPDC);
             $result = $this->checkPort($ip, $port);
             $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
             if (!$result['status'] && !$hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, $result['error']));
             } elseif ($result['status'] && $hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
             } elseif ($hasActiveAlert) {
                 $serverAlerts->updateLastCheckTime($check);
             }
             //Check scalarizr connectivity status
             $check = Alerts::METRIC_SCALARIZR_CONNECTIVITY;
             $port = $dbServer->getPort(DBServer::PORT_CTRL);
             $result = $this->checkPort($ip, $port);
             $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
             if (!$result['status'] && !$hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, $result['error']));
             } elseif ($result['status'] && $hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
             } elseif ($hasActiveAlert) {
                 $serverAlerts->updateLastCheckTime($check);
             }
         }
     }
     exit;
 }
Example #27
0
 /**
  * Gets project properties and parameters
  *
  * @param   ProjectEntity    $projectEntity          Project entity
  * @param   string           $calculate     optional Whether response should be adjusted with cost usage data
  * @return  array Returns cost centre properties and parameters
  */
 private function getProjectData(ProjectEntity $projectEntity, $calculate = false)
 {
     $ret = array('ccId' => $projectEntity->ccId, 'ccName' => $projectEntity->getCostCenter() !== null ? $projectEntity->getCostCenter()->name : null, 'projectId' => $projectEntity->projectId, 'name' => $projectEntity->name, 'billingCode' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE), 'description' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_DESCRIPTION), 'leadEmail' => $projectEntity->getProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL), 'created' => $projectEntity->created->format('Y-m-d'), 'createdByEmail' => $projectEntity->createdByEmail, 'archived' => $projectEntity->archived, 'shared' => $projectEntity->shared, 'farmsCount' => count($projectEntity->getFarmsList()));
     if (!empty($projectEntity->accountId) && $projectEntity->shared === ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         $ret['accountId'] = $projectEntity->accountId;
         $ret['accountName'] = Scalr_Account::init()->loadById($projectEntity->accountId)->name;
     } elseif (!empty($projectEntity->envId) && $projectEntity->shared === ProjectEntity::SHARED_WITHIN_ENV) {
         $ret['accountId'] = $projectEntity->accountId;
         $ret['accountName'] = Scalr_Account::init()->loadById($projectEntity->accountId)->name;
         $ret['envId'] = $projectEntity->envId;
         $ret['envName'] = Scalr_Environment::init()->loadById($projectEntity->envId)->name;
     }
     if ($calculate) {
         $iterator = ChartPeriodIterator::create('month', gmdate('Y-m-01'), null, 'UTC');
         $usage = $this->getContainer()->analytics->usage->get(['projectId' => $ret['projectId']], $iterator->getStart(), $iterator->getEnd());
         //It calculates usage for previous period same days
         $prevusage = $this->getContainer()->analytics->usage->get(['projectId' => $ret['projectId']], $iterator->getPreviousStart(), $iterator->getPreviousEnd());
         $ret = $this->getWrappedUsageData(['ccId' => $ret['ccId'], 'projectId' => $ret['projectId'], 'iterator' => $iterator, 'usage' => $usage['cost'], 'prevusage' => $prevusage['cost']]) + $ret;
     }
     return $ret;
 }
Example #28
0
 public function init()
 {
     $this->env = Scalr_Environment::init()->loadById($this->getParam(Scalr_UI_Controller_Environments::CALL_PARAM_NAME));
     $this->user->getPermissions()->validate($this->env);
 }
Example #29
0
 /**
  *
  * @param string $name
  * @param boolean $isSystem
  * @throws Scalr_Exception_LimitExceeded
  * @return Scalr_Environment
  */
 public function createEnvironment($name, $isSystem = false)
 {
     if (!$this->id) {
         throw new Exception("Account is not created");
     }
     $this->validateLimit(Scalr_Limits::ACCOUNT_ENVIRONMENTS, 1);
     $env = Scalr_Environment::init()->create($name, $this->id, $isSystem);
     $config[ENVIRONMENT_SETTINGS::TIMEZONE] = "America/Adak";
     $env->setPlatformConfig($config, false);
     return $env;
 }
Example #30
0
 public function xChangeEnvironmentAction()
 {
     $env = Scalr_Environment::init()->loadById($this->getParam('envId'));
     foreach ($this->user->getEnvironments() as $e) {
         if ($env->id == $e['id']) {
             Scalr_Session::getInstance()->setEnvironmentId($e['id']);
             $this->response->success();
             return;
         }
     }
     throw new Scalr_Exception_InsufficientPermissions();
 }