public function xRequestResultAction() { $this->request->defineParams(array('requests' => array('type' => 'json'), 'decision')); if (!in_array($this->getParam('decision'), array(FarmLease::STATUS_APPROVE, FarmLease::STATUS_DECLINE))) { throw new Scalr_Exception_Core('Wrong status'); } foreach ($this->getParam('requests') as $id) { $req = $this->db->GetRow('SELECT * FROM farm_lease_requests WHERE id = ? LIMIT 1', array($id)); if ($req) { $dbFarm = DBFarm::LoadByID($req['farm_id']); $this->user->getPermissions()->validate($dbFarm); $this->db->Execute('UPDATE farm_lease_requests SET status = ?, answer_comment = ?, answer_user_id = ? WHERE id = ?', array($this->getParam('decision'), $this->getParam('comment'), $this->user->getId(), $id)); try { $mailer = Scalr::getContainer()->mailer; $user = new Scalr_Account_User(); $user->loadById($dbFarm->createdByUserId); if ($this->getContainer()->config('scalr.auth_mode') == 'ldap') { if ($user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)) { $mailer->addTo($user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)); } else { $mailer->addTo($user->getEmail()); } } else { $mailer->addTo($user->getEmail()); } } catch (Exception $e) { $mailer = null; } if ($this->getParam('decision') == FarmLease::STATUS_APPROVE) { if ($req['request_days'] > 0) { $dt = $dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE); $dt = new DateTime($dt); $dt->add(new DateInterval('P' . $req['request_days'] . 'D')); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s')); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, null); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_approve.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{date}}' => $dt->format('M j, Y'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } else { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, ''); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, ''); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, ''); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_forever.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } else { $dt = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE)); SettingEntity::increase(SettingEntity::LEASE_DECLINED_REQUEST); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_decline.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{date}}' => $dt->format('M j, Y'), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } } $this->response->success(); }
function handleWork($farmId) { try { $dbFarm = DBFarm::LoadByID($farmId); $governance = new Scalr_Governance($dbFarm->EnvID); $settings = $governance->getValue(Scalr_Governance::GENERAL_LEASE, 'notifications'); $curDate = new DateTime(); $td = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE)); if ($td > $curDate) { // only inform user $days = $td->diff($curDate)->days; $notifications = json_decode($dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND), true); foreach ($settings as $n) { if (!$notifications[$n['key']] && $n['period'] >= $days) { $mailer = Scalr::getContainer()->mailer; $tdHuman = Scalr_Util_DateTime::convertDateTime($td, $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'M j, Y'); if ($n['to'] == 'owner') { $user = new Scalr_Account_User(); $user->loadById($dbFarm->createdByUserId); if (Scalr::config('scalr.auth_mode') == 'ldap') { $email = $user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL); if (!$email) { $email = $user->getEmail(); } } else { $email = $user->getEmail(); } $mailer->addTo($email); } else { foreach (explode(',', $n['emails']) as $email) { $mailer->addTo(trim($email)); } } $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml', array('{{terminate_date}}' => $tdHuman, '{{farm}}' => $dbFarm->Name)); $notifications[$n['key']] = 1; $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, json_encode($notifications)); $this->logger->info("Notification was sent by key: " . $n['key'] . " about farm: " . $dbFarm->Name . " by lease manager"); } } } else { // terminate farm $event = new FarmTerminatedEvent(0, 1, false, 1); Scalr::FireEvent($farmId, $event); $this->logger->info("Farm: " . $dbFarm->Name . " was terminated by lease manager"); } } catch (Exception $e) { var_dump($e->getMessage()); } }
/** * Initializes a new farm * * TODO: Rewrite this terrible code. * * @param string $name The name of the farm * @param Scalr_Account_User $user The user * @param int $envId The identifier of the environment * @return DBFarm */ public static function create($name, Scalr_Account_User $user, $envId) { $account = $user->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new self(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ClientID = $account->id; $dbFarm->EnvID = $envId; $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); $dbFarm->changedByUserId = $user->getId(); $dbFarm->changedTime = microtime(); $dbFarm->Name = $name; $dbFarm->RolesLaunchOrder = 0; $dbFarm->Comments = ""; $dbFarm->save(); $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); return $dbFarm; }
protected function getUserInfoByAccountId($accountId) { if (!isset($this->accountsCache[$accountId])) { if ($accountId) { try { $acc = new \Scalr_Account(); $acc->loadById($accountId); $this->accountsCache[$accountId] = array('id' => $acc->getOwner()->id, 'email' => $acc->getOwner()->getEmail()); } catch (\Exception $e) { $this->console->error($e->getMessage()); return array('id' => 0, 'email' => ''); } } else { $user = new \Scalr_Account_User(); $user->loadByEmail('admin', 0); $this->accountsCache[$accountId] = array('id' => $user->id, 'email' => $user->getEmail()); } } return $this->accountsCache[$accountId]; }
/** * Migrates an Image to another Cloud Location * * @param string $cloudLocation The cloud location * @param \Scalr_Account_User|\Scalr\Model\Entity\Account\User $user The user object * @return Image * @throws Exception * @throws NotEnabledPlatformException * @throws DomainException */ public function migrateEc2Location($cloudLocation, $user) { if (!$this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { throw new NotEnabledPlatformException("You can migrate image between regions only on EC2 cloud"); } if ($this->cloudLocation == $cloudLocation) { throw new DomainException('Destination region is the same as source one'); } $snap = $this->getEnvironment()->aws($this->cloudLocation)->ec2->image->describe($this->id); if ($snap->count() == 0) { throw new Exception("Image haven't been found on cloud."); } if ($snap->get(0)->toArray()['imageState'] != 'available') { throw new Exception('Image is not in "available" status on cloud and cannot be copied.'); } $this->checkImage(); // re-check properties $aws = $this->getEnvironment()->aws($cloudLocation); $newImageId = $aws->ec2->image->copy($this->cloudLocation, $this->id, $this->name, "Image was copied by Scalr from image: {$this->name}, cloudLocation: {$this->cloudLocation}, id: {$this->id}", null, $cloudLocation); $newImage = new Image(); $newImage->platform = $this->platform; $newImage->cloudLocation = $cloudLocation; $newImage->id = $newImageId; $newImage->name = $this->name; $newImage->architecture = $this->architecture; $newImage->size = $this->size; $newImage->accountId = $this->accountId; $newImage->envId = $this->envId; $newImage->osId = $this->osId; $newImage->source = Image::SOURCE_MANUAL; $newImage->type = $this->type; $newImage->agentVersion = $this->agentVersion; $newImage->createdById = $user->getId(); $newImage->createdByEmail = $user->getEmail(); $newImage->status = Image::STATUS_ACTIVE; $newImage->isScalarized = $this->isScalarized; $newImage->hasCloudInit = $this->hasCloudInit; $newImage->save(); $newImage->setSoftware($this->getSoftware()); return $newImage; }
/** * Gets email address of the user who fires an event * * @return string */ public function getUserEmail() { return $this->user ? $this->user->getEmail() : '[scalr]'; }
/** * @param string $newRoleName * @param Scalr_Account_User $user * @param int $envId * @return int * @throws Exception */ public function cloneRole($newRoleName, $user, $envId) { $this->db->BeginTrans(); $accountId = $user->getAccountId(); try { $this->db->Execute("INSERT INTO roles SET\n name = ?,\n origin = ?,\n client_id = ?,\n env_id = ?,\n cat_id = ?,\n description = ?,\n behaviors = ?,\n generation = ?,\n os_id = ?,\n dtadded = NOW(),\n added_by_userid = ?,\n added_by_email = ?\n ", array($newRoleName, $accountId ? ROLE_TYPE::CUSTOM : ROLE_TYPE::SHARED, empty($accountId) ? null : intval($accountId), empty($envId) ? null : intval($envId), $this->catId, $this->description, $this->behaviorsRaw, 2, $this->osId, $user->getId(), $user->getEmail())); $newRoleId = $this->db->Insert_Id(); //Set behaviors foreach ($this->getBehaviors() as $behavior) { $this->db->Execute("INSERT IGNORE INTO role_behaviors SET role_id = ?, behavior = ?", array($newRoleId, $behavior)); } // Set images $rsr7 = $this->db->Execute("SELECT * FROM role_images WHERE role_id = ?", array($this->id)); while ($r7 = $rsr7->FetchRow()) { $this->db->Execute("INSERT INTO role_images SET\n `role_id` = ?,\n `cloud_location` = ?,\n `image_id` = ?,\n `platform` = ?\n ", array($newRoleId, $r7['cloud_location'], $r7['image_id'], $r7['platform'])); } $props = $this->db->Execute("SELECT * FROM role_properties WHERE role_id=?", array($this->id)); while ($p1 = $props->FetchRow()) { $this->db->Execute("\n INSERT INTO role_properties\n SET `role_id` = ?,\n `name`\t= ?,\n `value`\t= ?\n ON DUPLICATE KEY UPDATE\n `value` = ?\n ", array($newRoleId, $p1['name'], $p1['value'], $p1['value'])); } //Set global variables $variables = new Scalr_Scripting_GlobalVariables($this->clientId, $this->envId, ScopeInterface::SCOPE_ROLE); $variables->setValues($variables->getValues($this->id), $newRoleId); //Set scripts $rsr8 = $this->db->Execute("SELECT * FROM role_scripts WHERE role_id = ?", array($this->id)); while ($r8 = $rsr8->FetchRow()) { $this->db->Execute("INSERT INTO role_scripts SET\n role_id = ?,\n event_name = ?,\n target = ?,\n script_id = ?,\n version = ?,\n timeout = ?,\n issync = ?,\n params = ?,\n order_index = ?,\n script_type = ?,\n script_path = ?,\n hash = ?\n ", array($newRoleId, $r8['event_name'], $r8['target'], $r8['script_id'], $r8['version'], $r8['timeout'], $r8['issync'], $r8['params'], $r8['order_index'], $r8['script_type'], $r8['script_path'], CryptoTool::sault(12))); } //Set environments only for account-scope roles if (!empty($accountId) && empty($envId)) { $rsr9 = $this->db->Execute("SELECT * FROM role_environments WHERE role_id = ?", array($this->id)); while ($r9 = $rsr9->FetchRow()) { $this->db->Execute("INSERT INTO role_environments SET\n role_id = ?,\n env_id = ?\n ", array($newRoleId, $r9['env_id'])); } } } catch (Exception $e) { $this->db->RollbackTrans(); throw $e; } $this->db->CommitTrans(); if (!empty($newRoleId)) { $newRole = self::loadById($newRoleId); $newRole->syncAnalyticsTags(); } return $newRoleId; }
/** * 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) { } }
private function AuthenticateRESTv3($request) { if (!$request['Signature']) { throw new Exception("Signature is missing"); } if (!$request['KeyID']) { throw new Exception("KeyID is missing"); } if (!$request['Timestamp'] && !$request['TimeStamp']) { throw new Exception("Timestamp is missing"); } if ($request['Timestamp']) { $request['TimeStamp'] = $request['Timestamp']; } //You mustn't do urldecode here in the next API version! $string_to_sign = "{$request['Action']}:{$request['KeyID']}:" . urldecode($request['TimeStamp']); $this->debug['stringToSign'] = $string_to_sign; try { $this->user = Scalr_Account_User::init()->loadByApiAccessKey($request['KeyID']); } catch (Exception $e) { } if (!$this->user) { throw new Exception("The specified KeyID does not exist"); } $auth_key = $this->user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY); if ($this->user->getAccountId()) { if (\Scalr::config('scalr.auth_mode') == 'ldap') { $this->Environment = Scalr_Environment::init()->loadById($request['EnvID']); try { $user = strtok($this->user->getEmail(), '@'); $ldap = \Scalr::getContainer()->ldap($user, null); if (!$ldap->isValidUsername()) { throw new Exception('Incorrect login or password (1)'); } $this->user->applyLdapGroups($ldap->getUserGroups()); } catch (Exception $e) { throw new Exception("Incorrect login or password (1)" . "\n" . $ldap->getLog()); } } else { if (!$request['EnvID']) { $envs = $this->user->getEnvironments(); if (!$envs[0]['id']) { throw new Exception("User has no access to any environments"); } $this->Environment = Scalr_Environment::init()->loadById($envs[0]['id']); } else { $this->Environment = Scalr_Environment::init()->loadById($request['EnvID']); } } $this->user->getPermissions()->setEnvironmentId($this->Environment->id)->validate($this->Environment); //We must set environment to DI Container. $this->getContainer()->environment = $this->Environment; } $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, trim($string_to_sign), $auth_key, 1)); //You mustn't do this in the next API version! $request['Signature'] = str_replace(" ", "+", urldecode($request['Signature'])); //You mustn't do urldecode here in the next API version! $this->debug['reqSignature'] = urldecode($request['Signature']); $this->debug['validSignature'] = $valid_sign; $this->debug['usedAuthVersion'] = 3; $this->debug['sha256AccessKey'] = hash(self::HASH_ALGO, $auth_key); if ($valid_sign != $request['Signature']) { //This is workaround to bugfix SCALRCORE-400. //It needn't have made unnecessary urldecode operation with request parameters. $sts2 = "{$request['Action']}:{$request['KeyID']}:{$request['TimeStamp']}"; $vs2 = base64_encode(hash_hmac(self::HASH_ALGO, trim($sts2), $auth_key, 1)); if ($vs2 != $request['Signature']) { throw new Exception("Signature doesn't match"); } } }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = false; } else { $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } if ($bNew) { $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } else { if ($dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->createdByUserId) { $user = (new Scalr_Account_User())->loadById($farm['owner']); $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); // TODO: move to subclass \Farm\Setting\OwnerHistory $history = unserialize($dbFarm->GetSetting(DBFarm::SETTING_OWNER_HISTORY)); if (!is_array($history)) { $history = []; } $history[] = ['newId' => $user->getId(), 'newEmail' => $user->getEmail(), 'changedById' => $this->user->getId(), 'changedByEmail' => $this->user->getEmail(), 'dt' => date('Y-m-d H:i:s')]; $dbFarm->SetSetting(DBFarm::SETTING_OWNER_HISTORY, serialize($history)); } $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $farm[DBFarm::SETTING_SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $farm[DBFarm::SETTING_SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages'])) { if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs']); } } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }
/** * @param string $login * @param string $password * @param int $accountId * @param string $scalrCaptcha * @return Scalr_Account_User * @throws Exception * @throws Scalr_Exception_Core * @throws \Scalr\System\Config\Exception\YamlException */ private function loginUserGet($login, $password, $accountId, $scalrCaptcha) { if ($login != '' && $password != '') { $isAdminLogin = $this->db->GetOne('SELECT * FROM account_users WHERE email = ? AND account_id = 0', array($login)); if ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap' && !$isAdminLogin) { $ldap = $this->getContainer()->ldap($login, $password); $this->response->setHeader('X-Scalr-LDAP-Login', $login); $tldap = 0; $start = microtime(true); $result = $ldap->isValidUser(); $tldap = microtime(true) - $start; if ($result) { try { //Tries to retrieve user's email address from LDAP or provides that login is always with domain suffix if (($pos = strpos($login, '@')) === false) { $login = $ldap->getEmail(); } $start = microtime(true); $groups = $ldap->getUserGroups(); $gtime = microtime(true) - $start; $tldap += $gtime; $this->response->setHeader('X-Scalr-LDAP-G-Query-Time', sprintf('%0.4f sec', $gtime)); $this->response->setHeader('X-Scalr-LDAP-Query-Time', sprintf('%0.4f sec', $tldap)); $this->response->setHeader('X-Scalr-LDAP-CLogin', $login); $this->ldapGroups = $groups; } catch (Exception $e) { throw new Exception($e->getMessage() . $ldap->getLog()); } foreach ($groups as $key => $name) { $groups[$key] = $this->db->qstr($name); } $userAvailableAccounts = array(); if ($ldap->getConfig()->debug) { $this->response->setHeader('X-Scalr-LDAP-Debug', json_encode($ldap->getLog())); } // System users are not members of any group so if there is no groups then skip this. if (count($groups) > 0) { foreach ($this->db->GetAll(' SELECT clients.id, clients.name FROM clients JOIN client_environments ON client_environments.client_id = clients.id JOIN account_team_envs ON account_team_envs.env_id = client_environments.id JOIN account_teams ON account_teams.id = account_team_envs.team_id WHERE account_teams.name IN(' . join(',', $groups) . ')') as $value) { $userAvailableAccounts[$value['id']] = $value; } } foreach ($this->db->GetAll("\n SELECT clients.id, clients.name, clients.org, clients.dtadded\n FROM clients\n JOIN account_users ON account_users.account_id = clients.id\n WHERE account_users.email = ? AND account_users.type = ?", array($login, Scalr_Account_User::TYPE_ACCOUNT_OWNER)) as $value) { $value['dtadded'] = Scalr_Util_DateTime::convertTz($value['dtadded'], 'M j, Y'); $userAvailableAccounts[$value['id']] = $value; } $userAvailableAccounts = array_values($userAvailableAccounts); if (empty($userAvailableAccounts)) { throw new Scalr_Exception_Core('You don\'t have access to any account. ' . $ldap->getLog()); } elseif (count($userAvailableAccounts) == 1) { $accountId = $userAvailableAccounts[0]['id']; } else { $ids = array(); foreach ($userAvailableAccounts as $value) { $ids[] = $value['id']; } if (!$accountId && !in_array($accountId, $ids)) { $this->response->data(array('accounts' => $userAvailableAccounts)); throw new Exception(); } } $user = new Scalr_Account_User(); $user = $user->loadByEmail($login, $accountId); if (!$user) { $user = new Scalr_Account_User(); $user->type = Scalr_Account_User::TYPE_TEAM_USER; $user->status = Scalr_Account_User::STATUS_ACTIVE; $user->create($login, $accountId); } if (!$user->fullname) { $user->fullname = $ldap->getFullName(); $user->save(); } if ($ldap->getUsername() != $ldap->getEmail()) { $user->setSetting(Scalr_Account_User::SETTING_LDAP_EMAIL, $ldap->getEmail()); $user->setSetting(Scalr_Account_User::SETTING_LDAP_USERNAME, $ldap->getUsername()); } else { $user->setSetting(Scalr_Account_User::SETTING_LDAP_EMAIL, ''); } } else { throw new Exception("Incorrect login or password (1) " . $ldap->getLog()); } } else { $userAvailableAccounts = $this->db->GetAll(' SELECT account_users.id AS userId, clients.id, clients.name, clients.org, clients.dtadded, au.email AS `owner` FROM account_users LEFT JOIN clients ON clients.id = account_users.account_id LEFT JOIN account_users au ON account_users.account_id = au.account_id WHERE account_users.email = ? AND (au.type = ? OR account_users.type = ? OR account_users.type = ?) GROUP BY userId ', array($login, Scalr_Account_User::TYPE_ACCOUNT_OWNER, Scalr_Account_User::TYPE_SCALR_ADMIN, Scalr_Account_User::TYPE_FIN_ADMIN)); foreach ($userAvailableAccounts as &$ac) { $ac['dtadded'] = Scalr_Util_DateTime::convertTz($ac['dtadded'], 'M j, Y'); } if (count($userAvailableAccounts) == 1) { $user = new Scalr_Account_User(); $user->loadById($userAvailableAccounts[0]['userId']); } elseif (count($userAvailableAccounts) > 1) { if ($accountId) { foreach ($userAvailableAccounts as $acc) { if ($acc['id'] == $accountId) { $user = new Scalr_Account_User(); $user->loadById($acc['userId']); break; } } } else { $this->response->data(array('accounts' => $userAvailableAccounts)); throw new Exception(); } } else { throw new Exception("Incorrect login or password (3)"); } if ($user) { if ($user->status != User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. Please contact your account owner.'); } // kaptcha if ($user->loginattempts > 3 && $this->getContainer()->config->get('scalr.ui.recaptcha.private_key')) { if (!$scalrCaptcha || ($r = $this->validateReCaptcha($scalrCaptcha)) !== true) { $this->response->data(array('loginattempts' => $user->loginattempts, 'scalrCaptchaError' => isset($r) ? $r : 'empty-value')); throw new Exception(); } } if (!$user->checkPassword($password)) { $attempts = (int) $this->getContainer()->config->get('scalr.security.user.suspension.failed_login_attempts'); if ($attempts > 0 && $user->loginattempts >= $attempts && $user->getEmail() != 'admin') { $user->status = User::STATUS_INACTIVE; $user->loginattempts = 0; $user->save(); throw new Exception('User account has been deactivated. Please contact your account owner.'); } if ($this->getContainer()->config->get('scalr.ui.recaptcha.private_key')) { $this->response->data(array('loginattempts' => $user->loginattempts)); } throw new Exception("Incorrect login or password (1)"); } } else { throw new Exception("Incorrect login or password (2)"); } } // valid user, other checks $whitelist = $user->getVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST); if ($whitelist) { $subnets = unserialize($whitelist); if (!Scalr_Util_Network::isIpInSubnets($this->request->getRemoteAddr(), $subnets)) { throw new Exception('The IP address you are attempting to log in from isn\'t authorized'); } } return $user; } else { throw new Exception('Incorrect login or password (0)'); } }
/** * @param $name * @param \Scalr_Account_User $user * @return Script */ public function fork($name, \Scalr_Account_User $user) { $script = new self(); $script->name = $name; $script->description = $this->description; $script->os = $this->os; $script->isSync = $this->isSync; $script->timeout = $this->timeout; $script->accountId = $user->getAccountId() ? $user->getAccountId() : NULL; $script->envId = $this->envId; $script->createdById = $user->getId(); $script->createdByEmail = $user->getEmail(); $script->save(); $version = new ScriptVersion(); $version->scriptId = $script->id; $version->changedById = $user->getId(); $version->changedByEmail = $user->getEmail(); $version->content = $this->getLatestVersion()->content; $version->version = 1; $version->save(); return $script; }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'))); $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } if ($this->getParam('farm')) { $dbFarm->Name = strip_tags($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = trim(strip_tags($farm['description'])); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues($farm['variables'], 0, $dbFarm->ID, 0, '', false); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } //Audit log start //!TODO Enable Audit log for Farm Builder // $auditLog = $this->getEnvironment()->auditLog; // $docRoleSettingsBefore = new FarmRoleSettingsDocument($oldRoleSettings); // $docRoleSettingsBefore['farmroleid'] = $dbFarmRole->ID; // $docRoleSettings = new FarmRoleSettingsDocument(array_merge((array)$role['scaling_settings'], (array)$role['settings'])); // $docRoleSettings['farmroleid'] = $dbFarmRole->ID; $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } // $auditLog->log('Farm has been saved', array(AuditLogTags::TAG_UPDATE), $docRoleSettings, $docRoleSettingsBefore); // unset($docRoleSettings); // unset($docRoleSettingsBefore); //Audit log finish /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ //try { $dbFarmRole->getStorage()->setConfigs((array) $role['storages']['configs']); //} catch (FarmRoleStorageException $e) { // $errors[] = array('farm_role_id' => 1, 'tab' => 'storage', 'error' => $e->getMessage()); //} $farmRoleVariables->setValues($role['variables'], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false); Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platfrom specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } $this->response->success('Farm successfully saved'); $this->response->data(array('farmId' => $dbFarm->ID)); }
/** * Migrates an Image to another Cloud Location * * @param string $cloudLocation The cloud location * @param \Scalr_Account_User|\Scalr\Model\Entity\Account\User $user The user object * @return Image * @throws NotEnabledPlatformException * @throws DomainException */ public function migrateEc2Location($cloudLocation, $user) { if (!$this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { throw new NotEnabledPlatformException("You can migrate image between regions only on EC2 cloud"); } if ($this->cloudLocation == $cloudLocation) { throw new DomainException('Destination region is the same as source one'); } $this->checkImage(); // re-check properties $aws = $this->getEnvironment()->aws($cloudLocation); $newImageId = $aws->ec2->image->copy($this->cloudLocation, $this->id, $this->name, "Image was copied by Scalr from image: {$this->name}, cloudLocation: {$this->cloudLocation}, id: {$this->id}", null, $cloudLocation); $newImage = new Image(); $newImage->platform = $this->platform; $newImage->cloudLocation = $cloudLocation; $newImage->id = $newImageId; $newImage->name = $this->name; $newImage->architecture = $this->architecture; $newImage->size = $this->size; $newImage->envId = $this->envId; $newImage->osId = $this->osId; $newImage->source = Image::SOURCE_MANUAL; $newImage->type = $this->type; $newImage->agentVersion = $this->agentVersion; $newImage->createdById = $user->getId(); $newImage->createdByEmail = $user->getEmail(); $newImage->status = Image::STATUS_ACTIVE; $newImage->save(); $newImage->setSoftware($this->getSoftware()); return $newImage; }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'rolesToRemove' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } else { if ($this->getParam('changed')) { $this->checkFarmConfigurationIntegrity($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'), (array) $this->getParam('rolesToRemove')); } } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); if ($this->getContainer()->analytics->enabled) { $projectId = $farm['projectId']; if (empty($projectId)) { $ccId = $dbFarm->GetEnvironmentObject()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); if (!empty($ccId)) { //Assigns Project automatically only if it is the one withing the Cost Center $projects = ProjectEntity::findByCcId($ccId); if (count($projects) == 1) { $projectId = $projects->getArrayCopy()[0]->projectId; } } } if (!empty($projectId) && $dbFarm->GetSetting(Entity\FarmSetting::PROJECT_ID) != $projectId) { $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_PROJECTS); } } $bNew = false; } else { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ownerId = $this->user->getId(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $setFarmTeams = false; if ($bNew) { $setFarmTeams = true; } else { if ($dbFarm->ownerId == $this->user->getId() || $this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->ownerId) { $dbFarm->ownerId = $farm['owner']; $f = Entity\Farm::findPk($dbFarm->ID); Entity\FarmSetting::addOwnerHistory($f, User::findPk($farm['owner']), User::findPk($this->user->getId())); $f->save(); } $setFarmTeams = true; } } $dbFarm->save(); if ($setFarmTeams && is_array($farm['teamOwner'])) { /* @var $f Entity\Farm */ $f = Entity\Farm::findPk($dbFarm->ID); $f->setTeams(empty($farm['teamOwner']) ? [] : Entity\Account\Team::find([['name' => ['$in' => $farm['teamOwner']]], ['accountId' => $this->getUser()->accountId]])); $f->save(); } if ($bNew) { $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_ID, $this->user->getId()); $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_EMAIL, $this->user->getEmail()); } $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(Entity\FarmSetting::TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_ID, isset($farm["vpc_id"]) ? $farm['vpc_id'] : null); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_REGION, isset($farm["vpc_id"]) ? $farm['vpc_region'] : null); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY, $farm[Entity\FarmSetting::SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE, $farm[Entity\FarmSetting::SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(Entity\FarmSetting::CRYPTO_KEY)) { $dbFarm->SetSetting(Entity\FarmSetting::CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if (isset($virtualFarmRoles[$role['farm_role_id']])) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { /** TODO: Remove because will be handled with virtual_ **/ $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][Entity\FarmRoleSetting::SCALING_MAX_INSTANCES] = $role['settings'][Entity\FarmRoleSetting::SCALING_MIN_INSTANCES]; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (!empty($virtualFarmRoles)) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if (!empty($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID])) { foreach ($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs'], false); } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); if ($role['settings']['aws.elb.remove']) { $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE); } \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } } } $rolesToRemove = $this->getParam('rolesToRemove'); if (!empty($rolesToRemove)) { $currentFarmRoles = Entity\FarmRole::find([['farmId' => $dbFarm->ID], ['id' => ['$in' => $rolesToRemove]]]); /* @var $farmRole Entity\FarmRole */ foreach ($currentFarmRoles as $farmRole) { $farmRole->delete(); } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }