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 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 } }
/** * 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; } } } } }
/** * Gets DBFarm object * * @return \DBFarm */ public function getFarmObject() { if (!$this->dbFarm && !empty($this->farmId)) { $this->dbFarm = \DBFarm::LoadByID($this->farmId); } return $this->dbFarm; }
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(); }
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); } } }
/** * {@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'); } }
/** * 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; }
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)); }
/** * 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(); }
/** * 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); }
/** * 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"); } }
/** * @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 __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)); }
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 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()); } }
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; }
/** * @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; }); }
/** * 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) { $observers = $this->db->Execute("SELECT * FROM farm_event_observers WHERE event_observer_name = 'MailEventObserver'"); while ($observer = $observers->FetchRow()) { $dbFarm = \DBFarm::LoadByID($observer['farmid']); // Create endpoint $endpointId = $this->db->GetOne("SELECT endpoint_id FROM webhook_endpoints WHERE env_id = ? AND url = ?", array($dbFarm->EnvID, 'SCALR_MAIL_SERVICE')); if ($endpointId) { $endpoint = WebhookEndpoint::findPk(bin2hex($endpointId)); } else { $endpoint = new WebhookEndpoint(); $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT; $endpoint->accountId = $dbFarm->ClientID; $endpoint->envId = $dbFarm->EnvID; $endpoint->securityKey = \Scalr::GenerateRandomKey(64); $endpoint->isValid = true; $endpoint->url = "SCALR_MAIL_SERVICE"; $endpoint->save(); } //Create webhook configuration $webhook = new WebhookConfig(); $webhook->level = WebhookConfig::LEVEL_ENVIRONMENT; $webhook->accountId = $dbFarm->ClientID; $webhook->envId = $dbFarm->EnvID; $webhook->name = "MailEventObserver(FarmID: {$dbFarm->ID})"; $webhook->postData = $this->db->GetOne("SELECT value FROM farm_event_observers_config WHERE `key` = ? AND observerid = ?", array('EventMailTo', $observer['id'])); $webhook->save(); //save endpoints $configEndpoint = new WebhookConfigEndpoint(); $configEndpoint->webhookId = $webhook->webhookId; $configEndpoint->setEndpoint($endpoint); $configEndpoint->save(); //save events $dbEvents = $this->db->Execute("SELECT * FROM farm_event_observers_config WHERE `key` LIKE '%Notify' AND observerid = ?", array($observer['id'])); while ($info = $dbEvents->FetchRow()) { preg_match('/On([A-Za-z0-9]+)Notify/si', $info['key'], $matches); $configEvent = new WebhookConfigEvent(); $configEvent->webhookId = $webhook->webhookId; $configEvent->eventType = $matches[1]; $configEvent->save(); } //save farms $configFarm = new WebhookConfigFarm(); $configFarm->webhookId = $webhook->webhookId; $configFarm->farmId = $dbFarm->ID; $configFarm->save(); } }
/** * Gets the first farm which is owned by the test user * * @param bool $owned optional True for farm which is owned by the user, * false - for farms from user's account which is not * owned by the user. * @return \DBFarm|null Returns the farm object or null */ public function getFarm($owned = true) { $key = $owned ? 'owned' : 'not-owned'; if (!isset(self::$cache['farms'][$key])) { self::$cache['farms'][$key] = false; $db = \Scalr::getDb(); $user = $this->getUser(); if ($user instanceof \Scalr_Account_User) { $id = $db->GetOne("\n SELECT id FROM farms\n WHERE created_by_id " . ($owned ? '=' : '<>') . " ? AND clientid = ?\n LIMIT 1\n ", array($user->getId(), $user->getAccountId())); if ($id) { self::$cache['farms'][$key] = \DBFarm::LoadByID($id); } } } return self::$cache['farms'][$key] instanceof \DBFarm ? self::$cache['farms'][$key] : null; }
public function xListAction($serverId = null, $farmId = null, $farmRoleId = null, $status = null) { $sql = "SELECT sa.* FROM server_alerts sa LEFT JOIN farms f ON f.id = sa.farm_id WHERE sa.env_id = ?"; $args = [$this->getEnvironmentId()]; if ($serverId) { $sql .= ' AND sa.server_id = ?'; $args[] = $serverId; } if ($farmId) { $sql .= ' AND sa.farm_id = ?'; $args[] = $farmId; if ($farmRoleId) { $sql .= ' AND sa.farm_roleid = ?'; $args[] = $farmRoleId; } } if ($status) { $sql .= ' AND sa.status = ?'; $args[] = $status; } list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args, 'f'); $response = $this->buildResponseFromSql2($sql, ['metric', 'status', 'dtoccured', 'dtlastcheck', 'dtsolved', 'details'], ['server_id', 'details'], $args); foreach ($response['data'] as $i => $row) { $row['dtoccured'] = Scalr_Util_DateTime::convertTz($row['dtoccured']); if ($row['dtlastcheck']) { $row['dtlastcheck'] = Scalr_Util_DateTime::convertTz($row['dtlastcheck']); } else { $row['dtlastcheck'] = false; } if ($row['status'] == Alerts::STATUS_RESOLVED) { $row['dtsolved'] = Scalr_Util_DateTime::convertTz($row['dtsolved']); } else { $row['dtsolved'] = false; } $row['metric'] = Alerts::getMetricName($row['metric']); $row['farm_name'] = DBFarm::LoadByID($row['farm_id'])->Name; try { $row['role_name'] = DBFarmRole::LoadByID($row['farm_roleid'])->GetRoleObject()->name; $dbServer = DBServer::LoadByID($row['server_id']); $row['server_exists'] = $dbServer->status == SERVER_STATUS::RUNNING ? true : false; } catch (Exception $e) { } $response['data'][$i] = $row; } $this->response->data($response); }
public function statusAction() { $dbFarmRole = $this->getFarmRole(); $moduleParams['farmName'] = DBFarm::LoadByID($this->getParam('farmId'))->Name; $moduleParams['farmRoleId'] = $dbFarmRole->ID; $moduleParams['farmHash'] = $dbFarmRole->GetFarmObject()->Hash; $moduleParams['mongodb'] = array(); $moduleParams['mongodb']['password'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::ROLE_PASSWORD); $moduleParams['mongodb']['status'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_STATUS); $serverStatus = array(); $pendingServers = 0; foreach ($dbFarmRole->GetServersByFilter(null, array('status' => array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) as $server) { $shardIndex = $server->GetProperty(Scalr_Role_Behavior_MongoDB::SERVER_SHARD_INDEX); $replicaSetIndex = $server->GetProperty(Scalr_Role_Behavior_MongoDB::SERVER_REPLICA_SET_INDEX); if (isset($serverStatus[$shardIndex][$replicaSetIndex])) { continue; } switch ($server->status) { case SERVER_STATUS::PENDING: case SERVER_STATUS::INIT: case SERVER_STATUS::PENDING_LAUNCH: $serverStatus[$shardIndex][$replicaSetIndex] = 'pending'; $pendingServers++; break; case SERVER_STATUS::RUNNING: $status = $server->GetProperty(Scalr_Role_Behavior_MongoDB::SERVER_NODE_STATUS); $serverStatus[$shardIndex][$replicaSetIndex] = $status ? $status : 'active'; break; default: $serverStatus[$shardIndex][$replicaSetIndex] = 'terminated'; break; } } for ($i = 0; $i < $dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::ROLE_SHARDS_COUNT); $i++) { for ($j = 0; $j < $dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::ROLE_REPLICAS_COUNT); $j++) { $moduleParams['mongodb']['map'][$i][$j] = !is_null($serverStatus[$i][$j]) ? $serverStatus[$i][$j] : "terminated"; } } $moduleParams['dtLastBundle'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_LAST_TS) ? Scalr_Util_DateTime::convertTz((int) $dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_LAST_TS), 'd M Y \\a\\t H:i:s') : 'Never'; $moduleParams['pendingServers'] = $pendingServers; $this->response->page('ui/services/mongodb/status.js', $moduleParams, array(), array('ui/services/mongodb/status.css')); }
public function xListAlertsAction() { $this->request->defineParams(array('sort' => array('type' => 'string', 'default' => 'id'), 'dir' => array('type' => 'string', 'default' => 'DESC'))); $sql = "SELECT * FROM server_alerts WHERE env_id='" . $this->getEnvironmentId() . "'"; if ($this->getParam('serverId')) { $sql .= ' AND server_id = ' . $this->db->qstr($this->getParam('serverId')); } if ($this->getParam('farmId')) { $sql .= ' AND farm_id = ' . $this->db->qstr($this->getParam('farmId')); if ($this->getParam('farmRoleId')) { $sql .= ' AND farm_roleid = ' . $this->db->qstr($this->getParam('farmRoleId')); } } if ($this->getParam('status')) { $sql .= ' AND status = ' . $this->db->qstr($this->getParam('status')); } $response = $this->buildResponseFromSql($sql, array('server_id', 'details')); foreach ($response['data'] as $i => $row) { $row['dtoccured'] = Scalr_Util_DateTime::convertTz($row['dtoccured']); if ($row['dtlastcheck']) { $row['dtlastcheck'] = Scalr_Util_DateTime::convertTz($row['dtlastcheck']); } else { $row['dtlastcheck'] = false; } if ($row['status'] == Alerts::STATUS_RESOLVED) { $row['dtsolved'] = Scalr_Util_DateTime::convertTz($row['dtsolved']); } else { $row['dtsolved'] = false; } $row['metric'] = Alerts::getMetricName($row['metric']); $row['farm_name'] = DBFarm::LoadByID($row['farm_id'])->Name; try { $row['role_name'] = DBFarmRole::LoadByID($row['farm_roleid'])->GetRoleObject()->name; $dbServer = DBServer::LoadByID($row['server_id']); $row['server_exists'] = $dbServer->status == SERVER_STATUS::RUNNING ? true : false; } catch (Exception $e) { } $response['data'][$i] = $row; } $this->response->data($response); }