public function xSaveAction() { $this->request->defineParams(array('category' => array('type' => 'string'), 'name' => array('type' => 'string'), 'value' => array('type' => 'json'))); $governance = new Scalr_Governance($this->getEnvironmentId()); $category = $this->getParam('category'); $name = $this->getParam('name'); $value = $this->getParam('value'); if ($category == Scalr_Governance::CATEGORY_GENERAL && $name == Scalr_Governance::GENERAL_LEASE) { $enabled = (bool) $value['limits']['enableDefaultLeaseDuration']; unset($value['limits']['enableDefaultLeaseDuration']); if (!$governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $value['enabled'] == 1 && $enabled) { $dt = new DateTime(); $dt->add(new DateInterval('P' . $value['limits']['defaultLifePeriod'] . 'D')); $farms = $this->db->GetCol('SELECT id FROM farms WHERE env_id = ? AND status = ?', array($this->getEnvironmentId(), FARM_STATUS::RUNNING)); foreach ($farms as $farmId) { $farm = DBFarm::LoadByID($farmId); $farm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); $farm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s')); $farm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, ''); $farm->SetSetting(DBFarm::SETTING_LEASE_EXTEND_CNT, 0); } } } $governance->setValue($category, $name, $value); $this->response->success('Successfully saved'); }
public static function farmSave(DBFarm $DBFarm, array $roles) { foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != SERVER_PLATFORMS::EUCALYPTUS) { continue; } $location = $DBFarmRole->CloudLocation; $sshKey = Scalr_Model::init(Scalr_Model::SSH_KEY); if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $location)) { $key_name = "FARM-{$DBFarm->ID}"; $eucaClient = Scalr_Service_Cloud_Eucalyptus::newCloud($DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Eucalyptus::SECRET_KEY, true, $location), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Eucalyptus::ACCESS_KEY, true, $location), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Eucalyptus::EC2_URL, true, $location)); $result = $eucaClient->CreateKeyPair($key_name); if ($result->keyMaterial) { $sshKey->farmId = $DBFarm->ID; $sshKey->clientId = $DBFarm->ClientID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = SERVER_PLATFORMS::EUCALYPTUS; $sshKey->setPrivate($result->keyMaterial); $sshKey->save(); } } } }
public static function farmSave(\DBFarm $DBFarm, array $roles) { foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != \SERVER_PLATFORMS::EC2) { continue; } $location = $DBFarmRole->CloudLocation; $sshKey = \Scalr_Model::init(\Scalr_Model::SSH_KEY); if (!$sshKey->loadGlobalByFarmId($DBFarm->EnvID, $DBFarm->ID, $location, \SERVER_PLATFORMS::EC2)) { $key_name = "FARM-" . $DBFarm->ID . "-" . SCALR_ID; $aws = $DBFarm->GetEnvironmentObject()->aws($location); $result = $aws->ec2->keyPair->create($key_name); if (!empty($result->keyMaterial)) { $sshKey->farmId = $DBFarm->ID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = \SERVER_PLATFORMS::EC2; $sshKey->setPrivate($result->keyMaterial); $sshKey->save(); } } } }
public function StartThread($farminfo) { $db = \Scalr::getDb(); $DBFarm = DBFarm::LoadByID($farminfo['id']); foreach ($DBFarm->GetFarmRoles() as $DBFarmRole) { foreach ($DBFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, SERVER_STATUS::PENDING, SERVER_STATUS::TROUBLESHOOTING)), array()) as $DBServer) { $launchTime = strtotime($DBServer->dateAdded); $lastCheckTime = (int) $DBServer->GetProperty(SERVER_PROPERTIES::STATISTICS_LAST_CHECK_TS); if (!$lastCheckTime) { $lastCheckTime = $launchTime; } $period = round((time() - $lastCheckTime) / 60); $maxMinutes = date("j") * 24 * 60 - date("H") * 60; if ($period > $maxMinutes) { $period = $maxMinutes; } $serverType = $DBServer->GetFlavor(); if (!$serverType) { continue; } $db->Execute("INSERT INTO servers_stats SET\n `usage` = ?,\n `instance_type` = ?,\n `env_id` = ?,\n `month` = ?,\n `year` = ?,\n `farm_id` = ?,\n `cloud_location` = ?\n ON DUPLICATE KEY UPDATE `usage` = `usage` + ?\n ", array($period, $serverType, $DBServer->envId, date("m"), date("Y"), $DBServer->farmId, $DBServer->GetCloudLocation(), $period)); $DBServer->SetProperty(SERVER_PROPERTIES::STATISTICS_LAST_CHECK_TS, time()); } //for each items } }
/** * Gets DBFarm object * * @return \DBFarm */ public function getFarmObject() { if (!$this->dbFarm && !empty($this->farmId)) { $this->dbFarm = \DBFarm::LoadByID($this->farmId); } return $this->dbFarm; }
/** * Release IP address when instance terminated * * @param HostDownEvent $event */ public function OnHostDown(HostDownEvent $event) { if ($event->DBServer->IsRebooting()) { return; } try { $DBFarm = DBFarm::LoadByID($this->FarmID); if ($event->replacementDBServer) { $ip = $this->DB->GetRow("SELECT * FROM elastic_ips WHERE server_id=?", array($event->DBServer->serverId)); if ($ip) { $aws = $DBFarm->GetEnvironmentObject()->aws($event->DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION)); try { // Associates elastic ip address with instance $aws->ec2->address->associate(new AssociateAddressRequestData($event->replacementDBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $ip['ipaddress'])); $this->DB->Execute("UPDATE elastic_ips SET state='1', server_id=? WHERE ipaddress=?", array($event->replacementDBServer->serverId, $ip['ipaddress'])); Scalr::FireEvent($this->FarmID, new IPAddressChangedEvent($event->replacementDBServer, $ip['ipaddress'], $event->replacementDBServer->localIp)); } catch (Exception $e) { if (!stristr($e->getMessage(), "does not belong to you")) { throw new Exception($e->getMessage()); } } } } else { $this->DB->Execute("UPDATE elastic_ips SET state='0', server_id='' WHERE server_id=?", array($event->DBServer->serverId)); } } catch (Exception $e) { } }
protected function run2($stage) { $farms = $this->db->Execute("SELECT farmid, value FROM farm_settings WHERE name='ec2.vpc.id' AND value != '' AND value IS NOT NULL"); while ($farm = $farms->FetchRow()) { $dbFarm = \DBFarm::LoadByID($farm['farmid']); $roles = $dbFarm->GetFarmRoles(); foreach ($roles as $dbFarmRole) { $vpcSubnetId = $dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_VPC_SUBNET_ID); if ($vpcSubnetId && substr($vpcSubnetId, 0, 6) != 'subnet') { $subnets = json_decode($vpcSubnetId); $vpcSubnetId = $subnets[0]; } if ($vpcSubnetId) { try { $platform = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::EC2); $info = $platform->listSubnets(\Scalr_Environment::init()->loadById($dbFarm->EnvID), $dbFarmRole->CloudLocation, $farm['value'], true, $vpcSubnetId); if ($info && $info['type'] != 'public') { $routerRole = $dbFarm->GetFarmRoleByBehavior(\ROLE_BEHAVIORS::VPC_ROUTER); $dbFarmRole->SetSetting(\Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID, $routerRole->ID); $this->console->out("Updating router.scalr.farm_role_id property for Farm Role: %s", $dbFarmRole->ID); } } catch (\Exception $e) { continue; } } } } }
private function getBackupDetails($backupId) { $links = array(); $backup = Scalr_Db_Backup::init()->loadById($backupId); $this->user->getPermissions()->validate($backup); $data = array('backup_id' => $backup->id, 'farm_id' => $backup->farmId, 'type' => ROLE_BEHAVIORS::GetName($backup->service) ? ROLE_BEHAVIORS::GetName($backup->service) : 'unknown', 'date' => Scalr_Util_DateTime::convertTz($backup->dtCreated), 'size' => $backup->size ? round($backup->size / 1024 / 1024, 2) : 0, 'provider' => $backup->provider, 'cloud_location' => $backup->cloudLocation, 'farmName' => DBFarm::LoadByIDOnlyName($backup->farmId)); $downloadParts = $backup->getParts(); foreach ($downloadParts as $part) { $part['size'] = $part['size'] ? round($part['size'] / 1024 / 1024, 2) : ''; if ($part['size'] == 0) { $part['size'] = 0.01; } if ($data['provider'] == 's3') { $part['link'] = $this->getS3SignedUrl($part['path']); } else { if ($data['provider'] == 'cf') { if ($backup->platform == SERVER_PLATFORMS::RACKSPACE) { $part['link'] = $this->getCfSignedUrl($part['path'], $data['cloud_location'], $backup->platform); } else { $part['link'] = "swift://{$part['path']}"; } } else { continue; } } $part['path'] = pathinfo($part['path']); $links[$part['number']] = $part; } $data['links'] = $links; return $data; }
public function xRequestResultAction() { $this->request->defineParams(array('requests' => array('type' => 'json'), 'decision')); if (!in_array($this->getParam('decision'), array(FarmLease::STATUS_APPROVE, FarmLease::STATUS_DECLINE))) { throw new Scalr_Exception_Core('Wrong status'); } foreach ($this->getParam('requests') as $id) { $req = $this->db->GetRow('SELECT * FROM farm_lease_requests WHERE id = ? LIMIT 1', array($id)); if ($req) { $dbFarm = DBFarm::LoadByID($req['farm_id']); $this->user->getPermissions()->validate($dbFarm); $this->db->Execute('UPDATE farm_lease_requests SET status = ?, answer_comment = ?, answer_user_id = ? WHERE id = ?', array($this->getParam('decision'), $this->getParam('comment'), $this->user->getId(), $id)); try { $mailer = Scalr::getContainer()->mailer; if ($dbFarm->ownerId) { $user = Entity\Account\User::findPk($dbFarm->ownerId); if (\Scalr::config('scalr.auth_mode') == 'ldap') { $email = $user->getSetting(Entity\Account\User\UserSetting::NAME_LDAP_EMAIL); if (!$email) { $email = $user->email; } } else { $email = $user->email; } $mailer->addTo($email); } else { $mailer = null; } } catch (Exception $e) { $mailer = null; } if ($this->getParam('decision') == FarmLease::STATUS_APPROVE) { if ($req['request_days'] > 0) { $dt = $dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE); $dt = new DateTime($dt); $dt->add(new DateInterval('P' . $req['request_days'] . 'D')); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s')); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, null); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_approve.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{date}}' => $dt->format('M j, Y'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } else { $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, ''); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE, ''); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, ''); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_forever.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } else { $dt = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE)); SettingEntity::increase(SettingEntity::LEASE_DECLINED_REQUEST); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_decline.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{date}}' => $dt->format('M j, Y'), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } } $this->response->success(); }
/** * {@inheritdoc} * @see Scalr_UI_Controller_Dashboard_Widget::hasWidgetAccess */ public function hasWidgetAccess($params) { if (!empty($params['farmId'])) { $farm = DBFarm::LoadByID($params['farmId']); $this->request->restrictFarmAccess($farm, Acl::PERM_FARMS_STATISTICS); } else { throw new Scalr_Exception_Core('Farm ID could not be empty'); } }
public function OnFarmTerminated(\FarmTerminatedEvent $event) { $dbFarm = \DBFarm::LoadByID($this->FarmID); foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { foreach (\Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $bObj) { $bObj->onFarmTerminated($dbFarmRole); } } }
/** * Gets DBFarm object * * @return \DBFarm */ public function getFarmObject() { try { if (!$this->dbFarm && !empty($this->farmId)) { $this->dbFarm = \DBFarm::LoadByID($this->farmId); } } catch (Exception $e) { } return $this->dbFarm; }
public function ApacheVhostCreate($DomainName, $FarmID, $FarmRoleID, $DocumentRootDir, $EnableSSL, $SSLPrivateKey = null, $SSLCertificate = null) { $this->restrictAccess(Acl::RESOURCE_SERVICES_APACHE); $validator = new Scalr_Validator(); if ($validator->validateDomain($DomainName) !== true) { $err[] = _("Domain name is incorrect"); } $DBFarm = DBFarm::LoadByID($FarmID); if ($DBFarm->EnvID != $this->Environment->id) { throw new Exception(sprintf("Farm #%s not found", $FarmID)); } $this->user->getPermissions()->validate($DBFarm); $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID); if ($DBFarm->ID != $DBFarmRole->FarmID) { throw new Exception(sprintf("FarmRole #%s not found on Farm #%s", $FarmRoleID, $FarmID)); } if (!$DocumentRootDir) { throw new Exception(_("DocumentRootDir required")); } $options = serialize(array("document_root" => trim($DocumentRootDir), "logs_dir" => "/var/log", "server_admin" => $this->user->getEmail())); $httpConfigTemplateSSL = @file_get_contents(dirname(__FILE__) . "/../../templates/services/apache/ssl.vhost.tpl"); $httpConfigTemplate = @file_get_contents(dirname(__FILE__) . "/../../templates/services/apache/nonssl.vhost.tpl"); $vHost = Scalr_Service_Apache_Vhost::init(); $vHost->envId = (int) $this->Environment->id; $vHost->clientId = $this->user->getAccountId(); $vHost->domainName = $DomainName; $vHost->isSslEnabled = $EnableSSL ? true : false; $vHost->farmId = $FarmID; $vHost->farmRoleId = $FarmRoleID; $vHost->httpdConf = $httpConfigTemplate; $vHost->templateOptions = $options; //SSL stuff if ($vHost->isSslEnabled) { $cert = new Scalr_Service_Ssl_Certificate(); $cert->envId = $DBFarm->EnvID; $cert->name = $DomainName; $cert->privateKey = base64_decode($SSLPrivateKey); $cert->certificate = base64_decode($SSLCertificate); $cert->save(); $vHost->sslCertId = $cert->id; $vHost->httpdConfSsl = $httpConfigTemplateSSL; } else { $vHost->sslCertId = 0; } $vHost->save(); $servers = $DBFarm->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING))); foreach ($servers as $DBServer) { if ($DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::NGINX) || $DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::APACHE)) { $DBServer->SendMessage(new Scalr_Messaging_Msg_VhostReconfigure()); } } $response = $this->CreateInitialResponse(); $response->Result = 1; return $response; }
/** * Release IP address when instance terminated * * @param HostDownEvent $event */ public function OnHostDown(\HostDownEvent $event) { if ($event->DBServer->IsRebooting()) { return; } try { $DBFarm = \DBFarm::LoadByID($this->FarmID); $this->DB->Execute("UPDATE elastic_ips SET state='0', server_id='' WHERE server_id=?", array($event->DBServer->serverId)); } catch (\Exception $e) { } }
public function __construct(DBServer $dbServer, $port = 8010) { $this->dbServer = $dbServer; $this->port = $port; if ($this->dbServer->farmId) { if (DBFarm::LoadByID($this->dbServer->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $this->isVPC = true; } } $this->cryptoTool = Scalr_Messaging_CryptoTool::getInstance(); }
/** * Set FarmID for Event * @param integer $farm_id * @return void */ public function SetFarmID($farm_id) { if ($this->FarmID === null) { $this->FarmID = $farm_id; if ($farm_id) { $this->DBFarm = DBFarm::LoadByID($farm_id); } } else { throw new Exception("FarmID already set for this event"); } }
/** * Upload S3cmd config file, AWS private key and certificate to instance aftre instance boot. * Also execute hostInit hooks from hooks/hostInit folder * * @param array $instanceinfo * @param string $local_ip * @param string $remote_ip * @param string $public_key */ public function OnHostInit(HostInitEvent $event) { if ($event->DBServer->IsSupported("0.5")) { $this->Logger->info("Scalarizr instance. Skipping SSH observer..."); return true; } if ($event->DBServer->platform != SERVER_PLATFORMS::EC2) { return true; } // Get farm info and client info from database; $DBFarm = DBFarm::LoadByID($this->FarmID); $DBRole = DBRole::loadById($event->DBServer->roleId); // Get Role info $ssh_port = $DBRole->getProperty(DBRole::PROPERTY_SSH_PORT) ? $DBRole->getProperty(DBRole::PROPERTY_SSH_PORT) : 22; // Generate s3cmd config file $s3cfg = CONFIG::$S3CFG_TEMPLATE; $s3cfg = str_replace("[access_key]", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $s3cfg); $s3cfg = str_replace("[secret_key]", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY), $s3cfg); $s3cfg = str_replace("\r\n", "\n", $s3cfg); // Prepare public key for SSH connection $pub_key_file = tempnam("/tmp", "AWSK"); $res = file_put_contents($pub_key_file, $event->PublicKey); $this->Logger->debug("Creating temporary file for public key: {$res}"); try { $key = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($event->DBServer->farmId, $event->DBServer->GetFarmRoleObject()->CloudLocation); if (!$key) { throw new Exception(_("There is no SSH key for server: {$event->DBServer->serverId}")); } } catch (Exception $e) { throw new Exception("Cannot init SshKey object: {$e->getMessage()}"); } // Prepare private key for SSH connection $priv_key_file = tempnam("/tmp", "AWSK"); $res = file_put_contents($priv_key_file, $key->getPrivate()); $this->Logger->debug("Creating temporary file for private key: {$res}"); // Connect to SSH $SSH2 = new Scalr_Net_Ssh2_Client(); $SSH2->addPubkey("root", $pub_key_file, $priv_key_file); if ($SSH2->connect($event->ExternalIP, $ssh_port)) { // Upload keys and s3 config to instance $res = $SSH2->sendFile("/etc/aws/keys/pk.pem", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), "w+", false); $res2 = $SSH2->sendFile("/etc/aws/keys/cert.pem", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE), "w+", false); $res3 = $SSH2->sendFile("/etc/aws/keys/s3cmd.cfg", $s3cfg, "w+", false); // remove temporary files @unlink($pub_key_file); @unlink($priv_key_file); } else { // remove temporary files @unlink($pub_key_file); @unlink($priv_key_file); Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($this->FarmID, "Cannot upload ec2 keys to '{$event->DBServer->serverId}' instance. Failed to connect to SSH '{$event->ExternalIP}:{$ssh_port}'")); throw new Exception("Cannot upload keys on '{$event->DBServer->serverId}'. Failed to connect to '{$event->ExternalIP}:{$ssh_port}'."); } }
public function getContent($params = array()) { $this->request->restrictAccess(Acl::RESOURCE_FARMS_STATISTICS); $STATS_URL = 'http://monitoring.scalr.net'; if (!empty($params['farmid'])) { $dbFarm = DBFarm::LoadByID($params['farmid']); $this->user->getPermissions()->validate($dbFarm); } $content = @file_get_contents("{$STATS_URL}/server/statistics.php?" . http_build_query(array('version' => 2, 'task' => 'get_stats_image_url', 'farmid' => $params['farmid'], 'watchername' => $params['watchername'], 'graph_type' => $params['graph_type'], 'role' => $params['role']))); return json_decode($content); }
public function __construct(DBServer $dbServer, $port = 8010) { $this->dbServer = $dbServer; $this->port = $port; if ($this->dbServer->farmId) { if (DBFarm::LoadByID($this->dbServer->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $this->isVPC = true; } } $this->cryptoTool = \Scalr::getContainer()->srzcrypto($this->dbServer->GetKey(true)); }
public function __construct(DBServer $dbServer, $port = 8008, $timeout = 5) { $this->dbServer = $dbServer; $this->port = $port; $this->timeout = $timeout; if ($this->dbServer->farmId) { if (DBFarm::LoadByID($this->dbServer->farmId)->GetSetting(Entity\FarmSetting::EC2_VPC_ID)) { $this->isVPC = true; } } $this->cryptoTool = \Scalr::getContainer()->srzcrypto($this->dbServer->GetKey(true)); }
/** * @return DBFarmRole */ public function getFarmRole() { $this->request->defineParams(array('farmId' => array('type' => 'int'))); $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if ($dbFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) { return $dbFarmRole; } } throw new Exception("Role not found"); }
public function getContent($params = array()) { $dbFarm = DBFarm::LoadByID($params['farmId']); $this->user->getPermissions()->validate($dbFarm); $farmRoles = array(); foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { $servCount = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid = ? AND status IN ('Pending', 'Initializing', 'Running', 'Temporary')", array($dbFarmRole->ID)); if ($servCount) { $farmRoles[] = array('farmId' => $params['farmId'], 'roleId' => $this->db->GetOne("SELECT role_id FROM farm_roles WHERE id=? AND farmid=? LIMIT 1", array($dbFarmRole->ID, $params['farmId'])), 'farmRoleId' => $dbFarmRole->ID, 'farmRoleAlias' => $dbFarmRole->Alias, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'servCount' => $servCount); } } return array('servers' => $farmRoles, 'name' => $dbFarm->Name); }
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()); } }
public function onFarmSave(DBFarm $dbFarm, DBFarmRole $dbFarmRole) { $vpcId = $dbFarm->GetSetting(Entity\FarmSetting::EC2_VPC_ID); if (!$vpcId) { //REMOVE VPC RELATED SETTINGS return; } if ($dbFarmRole->GetSetting(self::ROLE_VPC_ROUTER_CONFIGURED) == 1) { // ALL OBJECTS ALREADY CONFIGURED return true; } $aws = $dbFarm->GetEnvironmentObject()->aws($dbFarmRole->CloudLocation); $niId = $dbFarmRole->GetSetting(self::ROLE_VPC_NID); // If there is no public IP allocate it and associate with NI $publicIp = $dbFarmRole->GetSetting(self::ROLE_VPC_IP); if ($niId && !$publicIp) { $filter = array(array('name' => AddressFilterNameType::networkInterfaceId(), 'value' => $niId)); $addresses = $aws->ec2->address->describe(null, null, $filter); $address = $addresses->get(0); $associate = false; if (!$address) { $address = $aws->ec2->address->allocate('vpc'); $associate = true; } $publicIp = $address->publicIp; if ($associate) { $associateAddressRequestData = new AssociateAddressRequestData(); $associateAddressRequestData->networkInterfaceId = $niId; $associateAddressRequestData->allocationId = $address->allocationId; $associateAddressRequestData->allowReassociation = true; //Associate PublicIP with NetworkInterface $aws->ec2->address->associate($associateAddressRequestData); } $dbFarmRole->SetSetting(self::ROLE_VPC_IP, $publicIp, Entity\FarmRoleSetting::TYPE_LCL); $dbFarmRole->SetSetting(self::ROLE_VPC_AID, $address->allocationId, Entity\FarmRoleSetting::TYPE_LCL); } $dbFarmRole->SetSetting(self::ROLE_VPC_ROUTER_CONFIGURED, 1, Entity\FarmRoleSetting::TYPE_LCL); }
public static function farmSave(DBFarm $DBFarm, array $roles) { foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != SERVER_PLATFORMS::CLOUDSTACK) { continue; } $location = $DBFarmRole->CloudLocation; $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_URL), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::SECRET_KEY)); $sshKey = Scalr_SshKey::init(); if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $location)) { $key_name = "FARM-{$DBFarm->ID}"; $result = $cs->createSSHKeyPair($key_name); if ($result->keypair->privatekey) { $sshKey->farmId = $DBFarm->ID; $sshKey->clientId = $DBFarm->ClientID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = SERVER_PLATFORMS::CLOUDSTACK; $sshKey->setPrivate($result->keypair->privatekey); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } $networkId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_ID); $set = fasle; foreach ($cs->listNetworks("", "", "", $networkId) as $network) { if ($network->id == $networkId) { $DBFarmRole->SetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE, $network->type); $set = true; } } if (!$set) { throw new Exception("Unable to get GuestIPType for Network #{$networkId}. Please try again later or choose another network offering."); } } }
public function Run() { $container = Scalr::getContainer(); $db = $container->adodb; $farms = $db->Execute("SELECT id FROM farms"); while ($farm = $farms->FetchRow()) { $dbFarm = DBFarm::LoadByID($farm['id']); if (!$dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE)) { $env = $dbFarm->GetEnvironmentObject(); $tz = $env->getPlatformConfigValue(ENVIRONMENT_SETTINGS::TIMEZONE); $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $tz); } } }
protected function run1($stage) { $rs = $this->db->Execute("\n SELECT s.server_id, s.farm_id\n FROM servers s\n JOIN farms f ON f.id = s.farm_id\n WHERE s.status IN ('Running', 'Pending launch', 'Pending terminate')\n "); while ($rec = $rs->FetchRow()) { try { $dbServer = \DBServer::LoadByID($rec['server_id']); $farm = \DBFarm::LoadByID($rec['farm_id']); $environment = $dbServer->GetEnvironmentObject(); $dbServer->SetProperties(array(\SERVER_PROPERTIES::FARM_CREATED_BY_ID => $farm->createdByUserId, \SERVER_PROPERTIES::FARM_CREATED_BY_EMAIL => $farm->createdByUserEmail, \SERVER_PROPERTIES::FARM_PROJECT_ID => $farm->GetSetting(Entity\FarmSetting::PROJECT_ID), \SERVER_PROPERTIES::ENV_CC_ID => $environment->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID))); } catch (\Exception $e) { continue; } } }
/** * Release IP address when instance terminated * * @param \HostDownEvent $event */ public function OnHostDown(\HostDownEvent $event) { if (!in_array($event->DBServer->platform, array(\SERVER_PLATFORMS::CLOUDSTACK, \SERVER_PLATFORMS::IDCF))) { return; } if ($event->DBServer->IsRebooting()) { return; } try { $DBFarm = \DBFarm::LoadByID($this->FarmID); //disable static nat if ($event->DBServer->remoteIp) { $cs = $DBFarm->GetEnvironmentObject()->cloudstack($event->DBServer->platform); $requestObject = new ListIpAddressesData(); $requestObject->ipaddress = $event->DBServer->remoteIp; $ipInfo = $cs->listPublicIpAddresses($requestObject); $info = !empty($ipInfo[0]) ? $ipInfo[0] : null; if (!empty($info->isstaticnat)) { if ($info->virtualmachineid == $event->DBServer->GetCloudServerID()) { $this->Logger->warn(new \FarmLogMessage($this->FarmID, sprintf(_("Calling disableStaticNat for IP: %s"), $event->DBServer->remoteIp))); $cs->firewall->disableStaticNat($info->id); } } } if ($event->replacementDBServer) { $ip = $this->DB->GetRow("SELECT * FROM elastic_ips WHERE server_id=? LIMIT 1", array($event->DBServer->serverId)); if ($ip) { $cs = $DBFarm->GetEnvironmentObject()->cloudstack($event->replacementDBServer->platform); try { $cs->firewall->disableStaticNat($ip['allocation_id']); } catch (\Exception $e) { } try { $cs->firewall->enableStaticNat(array('ipaddressid' => $ip['allocation_id'], 'virtualmachineid' => $event->replacementDBServer->GetCloudServerID())); $this->DB->Execute("UPDATE elastic_ips SET state='1', server_id=? WHERE ipaddress=?", array($event->replacementDBServer->serverId, $ip['ipaddress'])); \Scalr::FireEvent($this->FarmID, new \IPAddressChangedEvent($event->replacementDBServer, $ip['ipaddress'], $event->replacementDBServer->localIp)); } catch (\Exception $e) { if (!stristr($e->getMessage(), "does not belong to you")) { throw new \Exception($e->getMessage()); } } } } else { $this->DB->Execute("UPDATE elastic_ips SET state='0', server_id='' WHERE server_id=?", array($event->DBServer->serverId)); } } catch (\Exception $e) { \Logger::getLogger("Cloudstack::OnHostDown")->fatal($e->getMessage()); } }
/** * @return Role[] */ public function getTestRoles() { $roles = Role::find([['envId' => $this->getEnvironment()->id]]); return array_filter(iterator_to_array($roles), function (Role $role) { $dbRole = \DBRole::loadById($role->id); $farms = $dbRole->getFarms(); foreach ($farms as $farmId) { $farm = \DBFarm::LoadByID($farmId); if ($farm->Status) { return false; } } return true; }); }
protected function ValidateRequestByFarmHash($farmid, $instanceid, $authhash) { try { $DBFarm = DBFarm::LoadByID($farmid); $DBServer = DBServer::LoadByPropertyValue(EC2_SERVER_PROPERTIES::INSTANCE_ID, $instanceid); } catch (Exception $e) { if (!$DBServer) { throw new Exception(sprintf(_("Cannot verify the instance you are making request from. Make sure that farmid, instance-id and auth-hash parameters are specified."))); } } if ($DBFarm->Hash != $authhash || $DBFarm->ID != $DBServer->farmId) { throw new Exception(sprintf(_("Cannot verify the instance you are making request from. Make sure that farmid (%s), instance-id (%s) and auth-hash (%s) parameters are valid."), $farmid, $instanceid, $authhash)); } return $DBServer; }