public function xListTasksAction() { $this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'dtadded', 'direction' => 'DESC')))); $sql = "\n SELECT\n dt.id, dma.name AS application_name, servers.index AS server_index, farms.name AS farm_name, roles.name AS role_name,\n dt.status AS status, dt.dtadded AS dtadded\n FROM dm_deployment_tasks dt\n LEFT JOIN dm_applications dma ON dt.dm_application_id = dma.id\n LEFT JOIN servers ON servers.id = dt.server_id\n LEFT JOIN farms ON servers.farm_id = farms.id\n LEFT JOIN roles ON servers.farm_roleid = roles.id\n WHERE dt.`status` != ? AND dt.env_id = ?\n "; $args = array(Scalr_Dm_DeploymentTask::STATUS_ARCHIVED, $this->getEnvironmentId()); list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args, 'farms'); $response = $this->buildResponseFromSql2($sql, array('id', 'application_name', 'farm_name', 'role_name', 'server_index', 'status', 'dtadded', 'dtdeployed'), array(), $args); foreach ($response["data"] as $k => $row) { $data = false; try { $deploymentTask = Scalr_Dm_DeploymentTask::init()->loadById($row['id']); $application = $deploymentTask->getApplication(); try { $dbServer = DBServer::LoadByID($deploymentTask->serverId); $serverIndex = $dbServer->index; } catch (Exception $e) { } $data = array('id' => $deploymentTask->id, 'application_name' => $application->name, 'application_id' => $deploymentTask->applicationId, 'server_id' => $deploymentTask->serverId, 'server_index' => $serverIndex, 'remote_path' => $deploymentTask->remotePath, 'status' => $deploymentTask->status, 'dtadded' => $deploymentTask->dtAdded ? Scalr_Util_DateTime::convertTz($deploymentTask->dtAdded) : "", 'dtdeployed' => $deploymentTask->dtDeployed ? Scalr_Util_DateTime::convertTz($deploymentTask->dtDeployed) : "Never"); try { $dbFarmRole = DBFarmRole::LoadByID($deploymentTask->farmRoleId); $data['farm_roleid'] = $dbFarmRole->ID; $data['role_name'] = $dbFarmRole->GetRoleObject()->name; $data['farm_id'] = $dbFarmRole->FarmID; $data['farm_name'] = $dbFarmRole->GetFarmObject()->Name; } catch (Exception $e) { } } catch (Exception $e) { } $response["data"][$k] = $data; } $this->response->data($response); }
public function getScriptingLogAction() { $this->request->restrictAccess(Acl::RESOURCE_LOGS_SCRIPTING_LOGS); $this->request->defineParams(array('executionId' => array('type' => 'string'))); $info = $this->db->GetRow("SELECT * FROM scripting_log WHERE execution_id = ? LIMIT 1", array($this->getParam('executionId'))); if (!$info) { throw new Exception('Script execution log not found'); } try { $dbServer = DBServer::LoadByID($info['server_id']); if (!in_array($dbServer->status, array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING))) { throw new Exception(); } } catch (Exception $e) { throw new Exception('Server was terminated and logs no longer available'); } //Note! We should not check not-owned-farms permission here. It's approved by Igor. if ($dbServer->envId != $this->environment->id) { throw new \Scalr_Exception_InsufficientPermissions(); } $client = Scalr_Net_Scalarizr_Client::getClient($dbServer, Scalr_Net_Scalarizr_Client::NAMESPACE_SYSTEM, $dbServer->getPort(DBServer::PORT_API)); $logs = $client->getScriptLogs($this->getParam('executionId')); $msg = sprintf("STDERR: %s \n\n STDOUT: %s", base64_decode($logs->stderr), base64_decode($logs->stdout)); $msg = nl2br(htmlspecialchars($msg)); $this->response->data(array('message' => $msg)); }
/** * 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) { if (!$this->hasTableColumn('servers', 'cloud_location')) { $this->db->Execute("ALTER TABLE `servers`\n ADD `cloud_location` VARCHAR(255) NULL AFTER `index`,\n ADD `cloud_location_zone` VARCHAR(255) NULL AFTER `cloud_location`\n "); } else { if (!$this->hasTableColumnType('servers', 'cloud_location', 'varchar(255)')) { $this->db->Execute("ALTER TABLE `servers`\n CHANGE `cloud_location` `cloud_location` VARCHAR(255) NULL,\n CHANGE `cloud_location_zone` `cloud_location_zone` VARCHAR(255) NULL\n "); } } $servers = $this->db->Execute("SELECT server_id FROM servers"); while ($server = $servers->FetchRow()) { try { $dbServer = \DBServer::LoadByID($server['server_id']); $dbServer->cloudLocation = $dbServer->GetCloudLocation(); if ($dbServer->platform == \SERVER_PLATFORMS::EC2) { $dbServer->cloudLocationZone = $dbServer->GetProperty(\EC2_SERVER_PROPERTIES::AVAIL_ZONE); } if ($dbServer->platform == \SERVER_PLATFORMS::EUCALYPTUS) { $dbServer->cloudLocationZone = $dbServer->GetProperty(\EUCA_SERVER_PROPERTIES::AVAIL_ZONE); } if ($dbServer->platform == \SERVER_PLATFORMS::GCE) { $dbServer->cloudLocationZone = $dbServer->GetProperty(\GCE_SERVER_PROPERTIES::CLOUD_LOCATION); } $dbServer->Save(); } catch (\Exception $e) { } } }
public function xGetDetailsAction() { $amazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($this->getParam('cloudLocation'), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE)); $rInstances = $amazonEC2Client->DescribeReservedInstances(); $rInstances = $rInstances->reservedInstancesSet->item; if ($rInstances instanceof stdClass) { $rInstances = array($rInstances); } $result = array(); foreach ($rInstances as $rInstance) { if ($rInstance->state == 'active') { $result[$rInstance->availabilityZone][$rInstance->instanceType]['rCount'] += $rInstance->instanceCount; } } $servers = $this->db->Execute("SELECT servers.server_id FROM `servers` INNER JOIN server_properties ON server_properties.server_id = servers.server_id \r\n\t\t\tWHERE status=? AND name='ec2.region' AND env_id=? AND value=?", array(SERVER_STATUS::RUNNING, $this->getEnvironmentId(), $this->getParam('cloudLocation'))); while ($server = $servers->FetchRow()) { $dbServer = DBServer::LoadByID($server['server_id']); $result[$dbServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE)][$dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_TYPE)]['iCount']++; } $retval = array(); foreach ($result as $availZone => $i) { foreach ($i as $instanceType => $data) { $retval[] = array('availZone' => $availZone, 'instanceType' => $instanceType, 'scalrInstances' => (int) $data['iCount'], 'reservedInstances' => (int) $data['rCount']); } } $this->response->data(array('success' => true, 'data' => $retval)); }
protected function run4() { $this->console->notice('Fill image_id in servers table'); // ec2 $this->db->Execute("\n UPDATE servers s JOIN server_properties sp ON s.server_id = sp.server_id\n SET s.image_id = sp.value\n WHERE sp.name = ? AND s.platform = ?\n ", [\EC2_SERVER_PROPERTIES::AMIID, \SERVER_PLATFORMS::EC2]); // rackspace $this->db->Execute("\n UPDATE servers s JOIN server_properties sp ON s.server_id = sp.server_id\n SET s.image_id = sp.value\n WHERE sp.name = ? AND s.platform = ?\n ", [\RACKSPACE_SERVER_PROPERTIES::IMAGE_ID, \SERVER_PLATFORMS::RACKSPACE]); //cloudstack foreach (PlatformFactory::getCloudstackBasedPlatforms() as $platform) { foreach ($this->db->GetCol('SELECT server_id FROM servers WHERE platform = ?', [$platform]) as $serverId) { try { $dbServer = \DBServer::LoadByID($serverId); $env = (new \Scalr_Environment())->loadById($dbServer->envId); if ($dbServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID)) { $lst = $env->cloudstack($platform)->instance->describe(['id' => $dbServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID)]); if ($lst && $lst->count() == 1) { $instance = $lst->offsetGet(0); $dbServer->imageId = $instance->templateid; $this->console->notice('Set imageId: %s for serverId: %s', $dbServer->imageId, $serverId); $dbServer->save(); } else { $this->console->warning('Instance not found: %s for serverId: %s', $dbServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID), $serverId); } } } catch (\Exception $e) { $this->console->warning($e->getMessage()); } } } // openstack foreach (PlatformFactory::getOpenstackBasedPlatforms() as $platform) { $this->db->Execute("\n UPDATE servers s LEFT JOIN server_properties sp ON s.server_id = sp.server_id\n SET s.image_id = sp.value\n WHERE sp.name = ? AND s.platform = ?\n ", [\OPENSTACK_SERVER_PROPERTIES::IMAGE_ID, $platform]); } }
public static function doJob($job) { $db = Core::GetDBInstance(null, true); $messageSerializer = new Scalr_Messaging_XmlSerializer(); $message = $db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($job->workload())); try { if ($message['handle_attempts'] >= 3) { $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); } else { try { $DBServer = DBServer::LoadByID($message['server_id']); } catch (Exception $e) { $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); return; } if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) { // Only 0.2-68 or greater version support this feature. if ($DBServer->IsSupported("0.2-68")) { $msg = $messageSerializer->unserialize($message['message']); $DBServer->SendMessage($msg); } else { $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::UNSUPPORTED, $message['id'])); } } elseif (in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) { $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); } } } catch (Exception $e) { //var_dump($e->getMessage()); } }
function handleWork($msgId) { $message = $this->db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($msgId)); try { if ($message['handle_attempts'] >= 3) { $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); } else { try { $DBServer = DBServer::LoadByID($message['server_id']); } catch (Exception $e) { $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); return; } if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) { $msg = $this->messageSerializer->unserialize($message['message']); $msg->dbMessageId = $message['id']; $DBServer->SendMessage($msg); } elseif (in_array($DBServer->status, array(SERVER_STATUS::TROUBLESHOOTING, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED))) { $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); } } } catch (Exception $e) { //var_dump($e->getMessage()); } }
public function xListTasksAction() { $this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'dtadded', 'direction' => 'DESC')))); $sql = "SELECT id FROM dm_deployment_tasks WHERE status !='" . Scalr_Dm_DeploymentTask::STATUS_ARCHIVED . "' AND env_id = '{$this->getEnvironmentId()}'"; $response = $this->buildResponseFromSql($sql, array("id")); foreach ($response["data"] as $k => $row) { $data = false; try { $deploymentTask = Scalr_Dm_DeploymentTask::init()->loadById($row['id']); $application = $deploymentTask->getApplication(); try { $dbServer = DBServer::LoadByID($deploymentTask->serverId); $serverIndex = $dbServer->index; } catch (Exception $e) { } $data = array('id' => $deploymentTask->id, 'application_name' => $application->name, 'application_id' => $deploymentTask->applicationId, 'server_id' => $deploymentTask->serverId, 'server_index' => $serverIndex, 'remote_path' => $deploymentTask->remotePath, 'status' => $deploymentTask->status, 'dtadded' => $deploymentTask->dtAdded ? Scalr_Util_DateTime::convertTz($deploymentTask->dtAdded) : "", 'dtdeployed' => $deploymentTask->dtDeployed ? Scalr_Util_DateTime::convertTz($deploymentTask->dtDeployed) : "Never"); try { $dbFarmRole = DBFarmRole::LoadByID($deploymentTask->farmRoleId); $data['farm_roleid'] = $dbFarmRole->ID; $data['role_name'] = $dbFarmRole->GetRoleObject()->name; $data['farm_id'] = $dbFarmRole->FarmID; $data['farm_name'] = $dbFarmRole->GetFarmObject()->Name; } catch (Exception $e) { } } catch (Exception $e) { } $response["data"][$k] = $data; } $this->response->data($response); }
public function ServerGetExtendedInformation($ServerID) { $DBServer = DBServer::LoadByID($ServerID); if ($DBServer->envId != $this->Environment->id) { throw new Exception(sprintf("Server ID #%s not found", $ServerID)); } $response = $this->CreateInitialResponse(); $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerExtendedInformation($DBServer); $response->ServerInfo = new stdClass(); $scalrProps = array('ServerID' => $DBServer->serverId, 'Platform' => $DBServer->platform, 'RemoteIP' => $DBServer->remoteIp ? $DBServer->remoteIp : '', 'LocalIP' => $DBServer->localIp ? $DBServer->localIp : '', 'Status' => $DBServer->status, 'Index' => $DBServer->index, 'AddedAt' => $DBServer->dateAdded); foreach ($scalrProps as $k => $v) { $response->ServerInfo->{$k} = $v; } $response->PlatformProperties = new stdClass(); if (is_array($info) && count($info)) { foreach ($info as $name => $value) { $name = str_replace(".", "_", $name); $name = preg_replace("/[^A-Za-z0-9_-]+/", "", $name); if ($name == 'MonitoringCloudWatch') { continue; } $response->PlatformProperties->{$name} = $value; } } $response->ScalrProperties = new stdClass(); if (count($DBServer->GetAllProperties())) { $it = array(); foreach ($DBServer->GetAllProperties() as $name => $value) { $name = preg_replace("/[^A-Za-z0-9-]+/", "", $name); $response->ScalrProperties->{$name} = $value; } } return $response; }
public function xDisableAction() { $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); $aws = $this->getEnvironment()->aws($dbServer->GetCloudLocation()); $aws->ec2->instance->unmonitor($dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)); $this->response->success("Cloudwatch monitoring successfully enabled for the instance"); }
private function getFarmRoleStaticIps($cloudLocation, $farmRoleId) { $gceClient = $this->getGceClient($this->environment); $projectId = $this->environment->getPlatformConfigValue(GoogleCEPlatformModule::PROJECT_ID); $map = array(); if ($farmRoleId) { $dbFarmRole = DBFarmRole::LoadByID($farmRoleId); $this->user->getPermissions()->validate($dbFarmRole); $maxInstances = $dbFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MAX_INSTANCES); for ($i = 1; $i <= $maxInstances; $i++) { $map[] = array('serverIndex' => $i); } $servers = $dbFarmRole->GetServersByFilter(); for ($i = 0; $i < count($servers); $i++) { if ($servers[$i]->status != SERVER_STATUS::TERMINATED && $servers[$i]->status != SERVER_STATUS::TROUBLESHOOTING && $servers[$i]->index) { $map[$servers[$i]->index - 1]['serverIndex'] = $servers[$i]->index; $map[$servers[$i]->index - 1]['serverId'] = $servers[$i]->serverId; $map[$servers[$i]->index - 1]['remoteIp'] = $servers[$i]->remoteIp; $map[$servers[$i]->index - 1]['instanceId'] = $servers[$i]->GetProperty(GCE_SERVER_PROPERTIES::SERVER_NAME); } } $ips = $this->db->GetAll('SELECT ipaddress, instance_index FROM elastic_ips WHERE farm_roleid = ?', array($dbFarmRole->ID)); for ($i = 0; $i < count($ips); $i++) { $map[$ips[$i]['instance_index'] - 1]['elasticIp'] = $ips[$i]['ipaddress']; } } $response = $gceClient->addresses->listAddresses($projectId, $cloudLocation); $ips = array(); /* @var $ip \Google_Service_Compute_Address */ foreach ($response as $ip) { var_dump($ip); $itm = array('ipAddress' => $ip->address); $info = $this->db->GetRow("\n SELECT * FROM elastic_ips WHERE ipaddress = ? LIMIT 1\n ", array($itm['ipAddress'])); if ($info) { try { if ($info['server_id'] && $itm['instanceId']) { $dbServer = DBServer::LoadByID($info['server_id']); if ($dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID) != $itm['instanceId']) { for ($i = 0; $i < count($map); $i++) { if ($map[$i]['elasticIp'] == $itm['ipAddress']) { $map[$i]['warningInstanceIdDoesntMatch'] = true; } } } } $farmRole = DBFarmRole::LoadByID($info['farm_roleid']); $this->user->getPermissions()->validate($farmRole); $itm['roleName'] = $farmRole->GetRoleObject()->name; $itm['farmName'] = $farmRole->GetFarmObject()->Name; $itm['serverIndex'] = $info['instance_index']; } catch (Exception $e) { } } //TODO: Mark Router EIP ad USED $ips[] = $itm; } return array('map' => $map, 'ips' => $ips); }
public function __construct(DBServer $DBServer) { parent::__construct(); $this->DBServer = $DBServer; $r_server = Core::GetDBInstance()->GetRow("SELECT server_id FROM servers WHERE replace_server_id=?", array($DBServer->serverId)); if ($r_server) { $this->replacementDBServer = DBServer::LoadByID($r_server['server_id']); } }
function handle($queue, $payload) { $contentType = $_SERVER['CONTENT_TYPE']; // Authenticate request try { $this->logger->info(sprintf("Validating server (server_id: %s)", $_SERVER["HTTP_X_SERVER_ID"])); try { $DBServer = DBServer::LoadByID($_SERVER["HTTP_X_SERVER_ID"]); } catch (Exception $e) { throw new Exception(sprintf(_("Server '%s' is not known by Scalr"), $_SERVER["HTTP_X_SERVER_ID"])); } $cryptoKey = $DBServer->GetKey(true); $this->cryptoTool->setCryptoKey($cryptoKey); // $isOneTimeKey = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_KEY_TYPE) == SZR_KEY_TYPE::ONE_TIME; $isOneTimeKey = false; $keyExpired = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_ONETIME_KEY_EXPIRED); if ($isOneTimeKey && $keyExpired) { throw new Exception(_("One-time crypto key expired")); } $this->logger->info(sprintf(_("Validating signature '%s'"), $_SERVER["HTTP_X_SIGNATURE"])); $this->validateSignature($payload, $_SERVER["HTTP_X_SIGNATURE"], $_SERVER["HTTP_DATE"]); if ($isOneTimeKey) { $DBServer->SetProperty(SERVER_PROPERTIES::SZR_ONETIME_KEY_EXPIRED, 1); } } catch (Exception $e) { return array(401, $e->getMessage()); } // Decrypt and decode message try { $this->logger->info(sprintf(_("Decrypting message '%s'"), $payload)); $string = $this->cryptoTool->decrypt($payload); if ($contentType == 'application/json') { $message = $this->jsonSerializer->unserialize($string); $type = 'json'; } else { $message = $this->serializer->unserialize($string); $type = 'xml'; } if ($isOneTimeKey && !$message instanceof Scalr_Messaging_Msg_HostInit) { return array(401, _("One-time crypto key valid only for HostInit message")); } } catch (Exception $e) { return array(400, $e->getMessage()); } // Handle message $accepted = false; foreach ($this->handlers as $handler) { if ($handler->accept($queue)) { $this->logger->info("Notify handler " . get_class($handler)); $handler->handle($queue, $message, $string, $type); $accepted = true; } } return $accepted ? array(201, "Created") : array(400, sprintf("Unknown queue '%s'", $queue)); }
function handle($queue, Scalr_Messaging_Msg $message, $rawMessage) { $dbserver = DBServer::LoadByID($message->getServerId()); if ($message instanceof Scalr_Messaging_Msg_ExecScriptResult) { try { $this->db->Execute("INSERT DELAYED INTO scripting_log SET \n\t\t\t\t\tfarmid = ?,\n\t\t\t\t\tserver_id = ?, \n\t\t\t\t\tevent = ?,\n\t\t\t\t\tmessage = ?, \n\t\t\t\t\tdtadded = NOW() \n\t\t\t\t", array($dbserver->farmId, $message->getServerId(), $message->eventName, sprintf("Script '%s' execution result (Time: %s s, Exit code: %s). %s %s", $message->scriptName, round($message->timeElapsed, 2), $message->returnCode, base64_decode($message->stderr), base64_decode($message->stdout)))); if ($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]) { DBServer::LoadByID($message->getServerId())->SetProperty(SERVER_PROPERTIES::SZR_VESION, $message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]); } } catch (Exception $e) { $this->logger->warn($e->getMessage()); } } elseif ($message instanceof Scalr_Messaging_Msg_Log) { foreach ($message->entries as $entry) { try { $this->db->Execute("INSERT DELAYED INTO logentries SET \n\t\t\t\t\t\tserverid = ?, \n\t\t\t\t\t\tmessage = ?, \n\t\t\t\t\t\tseverity = ?, \n\t\t\t\t\t\ttime = ?, \n\t\t\t\t\t\tsource = ?, \n\t\t\t\t\t\tfarmid = ?\n\t\t\t\t\t", array($message->getServerId(), $entry->msg, self::$severityCodes[$entry->level], time(), $entry->name, $dbserver->farmId)); if ($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]) { DBServer::LoadByID($message->getServerId())->SetProperty(SERVER_PROPERTIES::SZR_VESION, $message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]); } } catch (Exception $e) { $this->logger->error($e->getMessage()); } } } elseif ($message instanceof Scalr_Messaging_Msg_RebundleLog) { try { $this->db->Execute("INSERT INTO bundle_task_log SET \n\t\t\t\t\tbundle_task_id = ?,\n\t\t\t\t\tdtadded = NOW(),\n\t\t\t\t\tmessage = ?\n\t\t\t\t", array($message->bundleTaskId, $message->message)); } catch (Exception $e) { $this->logger->error($e->getMessage()); } } elseif ($message instanceof Scalr_Messaging_Msg_DeployLog) { try { $this->db->Execute("INSERT INTO dm_deployment_task_logs SET \n\t\t\t\t\t`dm_deployment_task_id` = ?,\n\t\t\t\t\t`dtadded` = NOW(),\n\t\t\t\t\t`message` = ?\n\t\t\t\t", array($message->deployTaskId, $message->message)); } catch (Exception $e) { } } elseif ($message instanceof Scalr_Messaging_Msg_OperationDefinition) { try { if ($message->name == 'Execute scripts') { return; } $this->db->Execute("INSERT INTO server_operations SET \n\t\t\t\t\t`id` = ?,\n\t\t\t\t\t`server_id` = ?,\n\t\t\t\t\t`timestamp` = ?,\n\t\t\t\t\t`status`\t= ?,\n\t\t\t\t\t`name` = ?,\n\t\t\t\t\t`phases` = ?\n\t\t\t\t", array($message->id, $dbserver->serverId, time(), 'running', $message->name, json_encode($message->phases))); } catch (Exception $e) { } } elseif ($message instanceof Scalr_Messaging_Msg_OperationProgress) { try { if ($message->warning) { $msg = $message->warning->message; $trace = $message->warning->trace; $handler = $message->warning->handler; } $this->db->Execute("INSERT INTO server_operation_progress SET \n\t\t\t\t\t`operation_id` = ?,\n\t\t\t\t\t`timestamp` = ?,\n\t\t\t\t\t`phase` = ?,\n\t\t\t\t\t`step` = ?,\n\t\t\t\t\t`status` = ?,\n\t\t\t\t\t`message`= ?,\n\t\t\t\t\t`trace` = ?,\n\t\t\t\t\t`handler` = ?,\n\t\t\t\t\t`progress` = ?,\n\t\t\t\t\t`stepno` = ? \n\t\t\t\t\tON DUPLICATE KEY UPDATE status = ?, progress = ?, trace = ?, handler = ?, message = ?\n\t\t\t\t", array($message->id, $message->getTimestamp(), $message->phase, $message->step, $message->status, $msg, $trace, $handler, $message->progress, $message->stepno, $message->status, $message->progress, $trace, $handler, $msg)); } catch (Exception $e) { } } }
/** * {@inheritdoc} * @see Scalr_System_Cronjob_MultiProcess_DefaultWorker::startForking() */ function startForking($workQueue) { // Reopen DB connection after daemonizing $this->db = $this->getContainer()->adodb; // Check that time has come to cleanup dead servers $doCleanup = false; sem_acquire($this->cleanupSem); try { if (time() - (int) $this->lastCleanup->get(0) >= $this->cleanupInterval) { $doCleanup = true; $this->lastCleanup->put(0, time()); } } catch (Exception $e) { sem_release($this->cleanupSem); } sem_release($this->cleanupSem); if ($doCleanup) { $this->logger->info("Cleanup dead servers"); try { $importing_servers = $this->db->GetAll("\n SELECT server_id FROM servers\n WHERE status IN(?, ?)\n AND `dtadded` < NOW() - INTERVAL 1 DAY\n ", array(SERVER_STATUS::IMPORTING, SERVER_STATUS::TEMPORARY)); foreach ($importing_servers as $ts) { $dbServer = DBServer::LoadByID($ts['server_id']); if ($dbServer->status == SERVER_STATUS::TEMPORARY) { try { $dbServer->terminate(DBServer::TERMINATE_REASON_TEMPORARY_SERVER_ROLE_BUILDER); } catch (Exception $e) { } } else { if ($dbServer->status == SERVER_STATUS::IMPORTING) { $dbServer->Remove(); } } } $pending_launch_servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status=?", array(SERVER_STATUS::PENDING_LAUNCH)); try { foreach ($pending_launch_servers as $ts) { $DBServer = DBServer::LoadByID($ts['server_id']); if ($DBServer->status == SERVER_STATUS::PENDING_LAUNCH) { $account = Scalr_Account::init()->loadById($DBServer->clientId); if ($account->status == Scalr_Account::STATUS_ACTIVE) { Scalr::LaunchServer(null, $DBServer); } } } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Can't load server with ID #'%s'", $ts['server_id'], $e->getMessage())); } } catch (Exception $e) { $this->logger->fatal("Poller::cleanup failed: {$e->getMessage()}"); } } }
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; } } }
public function associateAction() { $dbServers = $this->db->GetAll("SELECT server_id FROM servers WHERE platform=? AND status=? AND env_id=?", array(SERVER_PLATFORMS::EC2, SERVER_STATUS::RUNNING, $this->getEnvironmentId())); if (count($dbServers) == 0) { throw new Exception("You have no running servers on EC2 platform"); } $servers = array(); foreach ($dbServers as $dbServer) { $dbServer = DBServer::LoadByID($dbServer['server_id']); if ($dbServer->GetProperty(EC2_SERVER_PROPERTIES::REGION) == $this->getParam('cloudLocation')) { } } $this->response->page('ui/tools/aws/ec2/eips/associate.js', array('servers' => '')); }
public function __construct(DBServer $DBServer) { parent::__construct(); $this->DBServer = $DBServer; $r_server = \Scalr::getDb()->GetRow("SELECT server_id FROM servers WHERE replace_server_id=? LIMIT 1", array($DBServer->serverId)); if ($r_server) { $this->replacementDBServer = DBServer::LoadByID($r_server['server_id']); } try { $history = $this->DBServer->getServerHistory(); $this->terminationReasonId = $history->terminateReasonId; $this->terminationReason = $history->terminateReason; } catch (Exception $e) { } }
protected function ValidateRequestBySignature($signature, $timestamp, $serverid) { ksort($this->Request); $string_to_sign = ""; foreach ($this->Request as $k => $v) { $string_to_sign .= "{$k}{$v}"; } $string_to_sign .= $timestamp; $DBServer = DBServer::LoadByID($serverid); $auth_key = $DBServer->GetKey(true); $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, $string_to_sign, $auth_key, 1)); if ($valid_sign != $signature) { throw new Exception("Signature doesn't match"); } return $DBServer; }
protected function run2($stage) { $this->console->out("Initializing project_id field in servers_history table"); $rows = $this->db->Execute("\n SELECT sh.server_id, fs.value AS project_id FROM servers_history sh\n JOIN servers s\n ON s.server_id = sh.server_id\n JOIN farm_settings fs\n ON fs.farmid = sh.farm_id AND fs.name = 'project_id'\n WHERE sh.project_id IS NULL AND fs.value IS NOT NULL AND LENGTH(fs.value) > 0\n "); $this->db->BeginTrans(); try { while ($record = $rows->FetchRow()) { $dbServer = \DBServer::LoadByID($record['server_id']); $dbServer->SetProperty(\SERVER_PROPERTIES::FARM_PROJECT_ID, $record['project_id']); $this->db->Execute("\n UPDATE servers_history sh\n SET sh.project_id = ?\n WHERE sh.servers_id = ?", [$record['project_id'], $record['server_id']]); } $this->db->CommitTrans(); } catch (Exception $e) { $this->db->RollbackTrans(); } }
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 xAttachAction() { $aws = $this->getEnvironment()->aws($this->getParam('cloudLocation')); $this->request->defineParams(array('cloudLocation', 'serverId', 'volumeId', 'mount', 'mountPoint')); $errmsg = null; try { $dbEbsVolume = DBEBSVolume::loadByVolumeId($this->getParam('volumeId')); if ($dbEbsVolume->isManual == 0) { $errmsg = sprintf(_("This volume was automatically created for role '%s' on farm '%s' and cannot be re-attahced manually."), $this->db->GetOne("\n SELECT name FROM roles\n JOIN farm_roles ON farm_roles.role_id = roles.id\n WHERE farm_roles.id=?\n LIMIT 1\n ", array($dbEbsVolume->farmRoleId)), $this->db->GetOne("SELECT name FROM farms WHERE id=? LIMIT 1", array($dbEbsVolume->farmId))); } } catch (Exception $e) { } if (!empty($errmsg)) { throw new Exception($errmsg); } /* @var $info VolumeData */ $info = $aws->ec2->volume->describe($this->getParam('volumeId'))->get(0); $dBServer = DBServer::LoadByID($this->getParam('serverId')); $image = Image::findOne([['platform' => $dBServer->platform], ['id' => $dBServer->imageId], ['cloudLocation' => $dBServer->GetCloudLocation()]]); $device = $dBServer->GetFreeDeviceName($image->isEc2HvmImage()); $res = $info->attach($dBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $device); if ($this->getParam('attachOnBoot') == 'on') { $dbEbsVolume = new DBEBSVolume(); $dbEbsVolume->attachmentStatus = EC2_EBS_ATTACH_STATUS::ATTACHING; $dbEbsVolume->isManual = true; $dbEbsVolume->volumeId = $info->volumeId; $dbEbsVolume->ec2AvailZone = $info->availabilityZone; $dbEbsVolume->ec2Region = $this->getParam('cloudLocation'); $dbEbsVolume->deviceName = $device; $dbEbsVolume->farmId = $dBServer->farmId; $dbEbsVolume->farmRoleId = $dBServer->farmRoleId; $dbEbsVolume->serverId = $dBServer->serverId; $dbEbsVolume->serverIndex = $dBServer->index; $dbEbsVolume->size = $info->size; $dbEbsVolume->snapId = $info->snapshotId; $dbEbsVolume->mount = $this->getParam('mount') == 1; $dbEbsVolume->mountPoint = $this->getParam('mountPoint'); $dbEbsVolume->mountStatus = $this->getParam('mount') == 1 ? EC2_EBS_MOUNT_STATUS::AWAITING_ATTACHMENT : EC2_EBS_MOUNT_STATUS::NOT_MOUNTED; $dbEbsVolume->clientId = $this->user->getAccountId(); $dbEbsVolume->envId = $this->getEnvironmentId(); $dbEbsVolume->Save(); } $this->response->success('EBS volume has been successfully attached'); }
public function xAttachAction() { $this->request->defineParams(array('cloudLocation', 'serverId', 'volumeId', 'mount', 'mountPoint')); try { $dBEbsVolume = DBEBSVolume::loadByVolumeId($this->getParam('volumeId')); if ($DBEBSVolume->isManual == 0) { $errmsg = sprintf(_("This volume was automatically created for role '%s' on farm '%s' and cannot be re-attahced manually."), $this->db->GetOne("SELECT name FROM roles INNER JOIN farm_roles ON farm_roles.role_id = roles.id WHERE farm_roles.id=?", array($dBEbsVolume->farmRoleId)), $this->db->GetOne("SELECT name FROM farms WHERE id=?", array($dBEbsVolume->farmId))); } } catch (Exception $e) { } if ($errmsg) { throw new Exception($errmsg); } $amazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($this->getParam('cloudLocation'), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE)); $r = $amazonEC2Client->DescribeVolumes($this->getParam('volumeId')); $info = $r->volumeSet->item; $dBServer = DBServer::LoadByID($this->getParam('serverId')); $attachVolumeType = new AttachVolumeType($this->getParam('volumeId'), $dBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $dBServer->GetFreeDeviceName()); $res = $amazonEC2Client->AttachVolume($attachVolumeType); if ($this->getParam('attachOnBoot') == 'on') { $dBEbsVolume = new DBEBSVolume(); $dBEbsVolume->attachmentStatus = EC2_EBS_ATTACH_STATUS::ATTACHING; $dBEbsVolume->isManual = true; $dBEbsVolume->volumeId = $this->getParam('volumeId'); $dBEbsVolume->ec2AvailZone = $info->availabilityZone; $dBEbsVolume->ec2Region = $this->getParam('cloudLocation'); $dBEbsVolume->deviceName = $attachVolumeType->device; $dBEbsVolume->farmId = $dBServer->farmId; $dBEbsVolume->farmRoleId = $dBServer->farmRoleId; $dBEbsVolume->serverId = $dBServer->serverId; $dBEbsVolume->serverIndex = $dBServer->index; $dBEbsVolume->size = $info->size; $dBEbsVolume->snapId = $info->snapshotId; $dBEbsVolume->mount = $this->getParam('mount') == 1 ? true : false; $dBEbsVolume->mountPoint = $this->getParam('mountPoint'); $dBEbsVolume->mountStatus = $this->getParam('mount') == 1 ? EC2_EBS_MOUNT_STATUS::AWAITING_ATTACHMENT : EC2_EBS_MOUNT_STATUS::NOT_MOUNTED; $dBEbsVolume->clientId = $this->user->getAccountId(); $dBEbsVolume->envId = $this->getEnvironmentId(); $dBEbsVolume->Save(); } $this->response->success('EBS volume successfully attached'); }
/** * 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) { $servers = $this->db->Execute("\n SELECT server_id FROM servers WHERE status='Running'\n AND server_id NOT IN (\n SELECT servers.server_id FROM servers\n INNER JOIN server_properties ON server_properties.server_id = servers.server_id\n WHERE server_properties.name = 'base.hostname' AND value != ''\n )\n "); $cnt = 0; while ($server = $servers->FetchRow()) { $dbServer = \DBServer::LoadByID($server['server_id']); if ($dbServer->IsSupported('0.23.0')) { try { $hostname = $dbServer->scalarizr->system->getHostname(); if ($hostname) { $dbServer->SetProperty(\Scalr_Role_Behavior::SERVER_BASE_HOSTNAME, $hostname); $cnt++; } } catch (\Exception $e) { $this->console->out("Unable to get hostname from server: {$dbServer->remoteIp} ({$dbServer->serverId})"); } } } $this->console->out("Successfully updated {$cnt} servers"); }
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); }
protected function ValidateRequestBySignature($signature, $timestamp, $serverid) { ksort($this->Request); $string_to_sign = ""; foreach ($this->Request as $k => $v) { $string_to_sign .= "{$k}{$v}"; } try { $DBServer = DBServer::LoadByID($serverid); } catch (Exception $e) { if (stristr($e->getMessage(), 'not found in database')) { throw new ForbiddenException($e->getMessage()); } throw $e; } $valid_sign = \Scalr\Util\CryptoTool::keySign($string_to_sign, $DBServer->GetKey(true), $timestamp, static::HASH_ALGO); if ($valid_sign != $signature) { throw new ForbiddenException("Signature doesn't match"); } return $DBServer; }
function handleWork($deploymentTaskId) { try { $deploymentTask = Scalr_Model::init(Scalr_Model::DM_DEPLOYMENT_TASK)->loadById($deploymentTaskId); try { $dbServer = DBServer::LoadByID($deploymentTask->serverId); } catch (Exception $e) { $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_ARCHIVED; return; } switch ($deploymentTask->status) { case Scalr_Dm_DeploymentTask::STATUS_PENDING: $deploymentTask->deploy(); break; case Scalr_Dm_DeploymentTask::STATUS_DEPLOYING: //TODO: break; } } catch (Exception $e) { var_dump($e->getMessage()); } }
public function attachAction() { $platformName = $this->getParam('platform'); if (!$platformName) { throw new Exception("Cloud should be specified"); } if (!$this->environment->isPlatformEnabled($platformName)) { throw new Exception("Cloud is not configured in current environment"); } $dbServers = $this->db->GetAll("SELECT server_id FROM servers WHERE platform=? AND status=? AND env_id=?", array($this->getParam('platform'), SERVER_STATUS::RUNNING, $this->getEnvironmentId())); if (count($dbServers) == 0) { throw new Exception("You have no running servers on {$platformName} platform"); } $servers = array(); foreach ($dbServers as $dbServer) { $dbServer = DBServer::LoadByID($dbServer['server_id']); $servers[$dbServer->serverId] = $dbServer->getNameByConvention(); } if (count($servers) == 0) { throw new Exception("You have no running servers on the availablity zone of this volume"); } $this->response->page('ui/tools/openstack/volumes/attach.js', array('servers' => $servers)); }
protected function ValidateRequestBySignature($signature, $timestamp, $serverid) { ksort($this->Request); $string_to_sign = ""; foreach ($this->Request as $k => $v) { $string_to_sign .= "{$k}{$v}"; } $string_to_sign .= $timestamp; try { $DBServer = DBServer::LoadByID($serverid); } catch (Exception $e) { if (stristr($e->getMessage(), 'not found in database')) { throw new ForbiddenException($e->getMessage()); } throw $e; } $auth_key = $DBServer->GetKey(true); $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, $string_to_sign, $auth_key, 1)); if ($valid_sign != $signature) { throw new ForbiddenException("Signature doesn't match"); } return $DBServer; }
/** * @param string $cloudLocation * @param string $addressId optional */ public function xListAction($cloudLocation, $addressId = '') { $platform = PlatformFactory::NewPlatform(SERVER_PLATFORMS::GCE); $client = $platform->getClient($this->environment); /* @var $client Google_Service_Compute */ $retval = array(); $addresses = $client->addresses->listAddresses($this->environment->keychain(SERVER_PLATFORMS::GCE)->properties[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], $cloudLocation, $addressId ? ['filter' => "name eq {$addressId}"] : []); foreach ($addresses as $address) { /* @var $address Google_Service_Compute_Address */ $item = array('id' => $address->name, 'ip' => ip2long($address->address), 'description' => $address->description, 'createdAt' => strtotime($address->creationTimestamp), 'status' => $address->status); if ($item['status'] == 'IN_USE') { $instanceURL = $address->users[0]; $instanceName = substr($instanceURL, strrpos($instanceURL, "/") + 1); $item['instanceId'] = $instanceName; try { $dbServer = DBServer::LoadByID($item['instanceId']); if ($dbServer && $dbServer->envId == $this->environment->id) { $item['farmId'] = $dbServer->farmId; $item['farmName'] = $dbServer->GetFarmObject()->Name; $item['farmRoleId'] = $dbServer->farmRoleId; $item['roleName'] = $dbServer->GetFarmRoleObject()->GetRoleObject()->name; $item['serverIndex'] = $dbServer->index; $item['serverId'] = $dbServer->serverId; } } catch (Exception $e) { } } $retval[] = $item; } $response = $this->buildResponseFromData($retval, array('id', 'ip', 'description', 'createdAt')); foreach ($response['data'] as &$row) { $row['createdAt'] = Scalr_Util_DateTime::convertTz($row['createdAt']); $row['ip'] = long2ip($row['ip']); } $this->response->data($response); }