/** * Sets user which is asssociated with the role superposition object * * @param \Scalr_Account_User|int $user User object or ID of the user * @return AccountRoleSuperposition * @throws \InvalidArgumentException */ public function setUser($user) { if ($user === null || $user instanceof \Scalr_Account_User) { $this->user = $user; } else { $userId = intval($user); if (empty($userId)) { throw new \InvalidArgumentException("Invalid ID of the user."); } $this->user = \Scalr_Account_User::init(); $this->user->loadById($userId); } return $this; }
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(); }
/** * Gets an test User instance * * @return \Scalr_Account_user Returns user instance */ protected function getUser() { if (!isset($this->user)) { if (empty($this->_testUserId)) { $this->_testUserId = \Scalr::config('scalr.phpunit.userid'); } $this->user = \Scalr_Account_User::init(); $this->user->loadById($this->_testUserId); } return $this->user; }
function handleWork($farmId) { try { $dbFarm = DBFarm::LoadByID($farmId); $governance = new Scalr_Governance($dbFarm->EnvID); $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, 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); if (is_array($settings)) { 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, '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); $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()); } }
/** * 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) { $dashboards = $this->db->Execute('SELECT user_id, env_id FROM account_user_dashboard'); foreach ($dashboards as $keys) { try { $user = new \Scalr_Account_User(); $user->loadById($keys['user_id']); $dash = $user->getDashboard($keys['env_id']); if (!(is_array($dash) && isset($dash['configuration']) && is_array($dash['configuration']) && isset($dash['flags']) && is_array($dash['flags']))) { // old configuration, remove it $this->db->Execute('DELETE FROM account_user_dashboard WHERE user_id = ? AND env_id = ?', array($keys['user_id'], $keys['env_id'])); continue; } foreach ($dash['configuration'] as &$column) { foreach ($column as &$widget) { if ($widget['name'] == 'dashboard.monitoring') { $metrics = array('CPUSNMP' => 'cpu', 'LASNMP' => 'la', 'NETSNMP' => 'net', 'ServersNum' => 'snum', 'MEMSNMP' => 'mem'); $params = array('farmId' => $widget['params']['farmid'], 'period' => $widget['params']['graph_type'], 'metrics' => $metrics[$widget['params']['watchername']], 'title' => $widget['params']['title'], 'hash' => $this->db->GetOne('SELECT hash FROM farms WHERE id = ?', array($widget['params']['farmid']))); if (stristr($widget['params']['role'], "INSTANCE_")) { $ar = explode('_', $widget['params']['role']); $params['farmRoleId'] = $ar[1]; $params['index'] = $ar[2]; } else { if ($widget['params']['role'] != 'FARM' && $widget['params']['role'] != 'role') { $params['farmRoleId'] = $widget['params']['role']; } } $widget['params'] = $params; } } } $user->setDashboard($keys['env_id'], $dash); } catch (\Exception $e) { $this->console->warning($e->getMessage()); } } }
public function xLoginAsAction() { if ($this->getParam('accountId')) { $account = new Scalr_Account(); $account->loadById($this->getParam('accountId')); $user = $account->getOwner(); } else { $user = new Scalr_Account_User(); $user->loadById($this->getParam('userId')); } if ($user->status != User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. You cannot login into it.'); } Scalr_Session::create($user->getId(), $this->user->getId()); try { $envId = $this->getEnvironmentId(true) ?: $user->getDefaultEnvironment()->id; } catch (Exception $e) { $envId = null; } $this->auditLog("user.auth.login", $user, $envId, $this->request->getRemoteAddr(), $this->user->getId()); $this->response->success(); }
public function xLoginAsAction() { if ($this->getParam('accountId')) { $account = new Scalr_Account(); $account->loadById($this->getParam('accountId')); $user = $account->getOwner(); } else { $user = new Scalr_Account_User(); $user->loadById($this->getParam('userId')); } Scalr_Session::create($user->getId(), true); $this->response->success(); }
private function loginUserGet($login, $password, $accountId, $scalrCaptcha, $scalrCaptchaChallenge) { 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->varDump($groups); $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 (count($userAvailableAccounts) == 0) { throw new Scalr_Exception_Core('You don\'t have access to any account. ' . $ldap->getLog()); } if (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()); } 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']); } else { if (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) { // kaptcha if ($user->loginattempts > 2 && $this->getContainer()->config->get('scalr.ui.recaptcha.private_key')) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://www.google.com/recaptcha/api/verify'); curl_setopt($curl, CURLOPT_POST, true); $post = 'privatekey=' . urlencode($this->getContainer()->config->get('scalr.ui.recaptcha.private_key')) . '&remoteip=' . urlencode($this->request->getRemoteAddr()) . '&challenge=' . urlencode($scalrCaptchaChallenge) . '&response=' . urlencode($scalrCaptcha); curl_setopt($curl, CURLOPT_POSTFIELDS, $post); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLINFO_HEADER_OUT, true); $response = curl_exec($curl); curl_close($curl); $responseStrings = explode("\n", $response); if ($responseStrings[0] !== 'true') { $this->response->data(array('loginattempts' => $user->loginattempts, 'kaptchaError' => $response)); throw new Exception(); } } if (!$user->checkPassword($password)) { 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)'); } }
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)'); } }
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)); }
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)); }