/** * {@inheritdoc} * @see Scalr\Tests\TestCase::tearDownAfterClass() */ public static function tearDownAfterClass() { foreach (static::$testData as $rec) { if ($rec['class'] === Farm::class) { $entry = $rec['pk']; $farm = Farm::findPk(...$entry); /* @var $farm Farm */ if (!empty($farm)) { try { \Scalr::FireEvent($farm->id, new FarmTerminatedEvent(false, false, false, false, true, static::$user->id)); foreach ($farm->servers as $server) { try { $dbServer = Server::findPk($server->serverId); /* @var $dbServer Server */ $dbServer->terminate(Server::TERMINATE_REASON_FARM_TERMINATED, true, static::$user); } catch (Exception $e) { \Scalr::logException($e); } $server->delete(); } } catch (Exception $e) { \Scalr::logException($e); } } } } parent::tearDownAfterClass(); }
public static function tearDownAfterClass() { //We have to remove CostCenter properties as they don't have foreign keys foreach (static::$testData as $rec) { if ($rec['class'] === Farm::class) { $entry = $rec['pk']; $farm = Farm::findPk(...$entry); if (!empty($farm)) { try { $farm->checkLocked(); \Scalr::FireEvent($farm->id, new FarmTerminatedEvent(false, false, false, false, true, static::$user->id)); foreach ($farm->servers as $server) { try { $DBServer = DBServer::LoadByID($server->id); $DBServer->terminate(DBServer::TERMINATE_REASON_FARM_TERMINATED, true, static::$user->id); } catch (Exception $e) { \Scalr::logException($e); } $server->delete(); } } catch (Exception $e) { \Scalr::logException($e); } } } } parent::tearDownAfterClass(); }
/** * Logs failed requests data * * @param Request $request API request data * @param Response $response API response data */ public function logError(Request $request, Response $response) { if ($this->enabled && !empty($this->writer)) { try { $time = time(); $status = $response->getStatus(); $data = ["tag" => $this->defaultTag, "dateTime" => $time, "message" => $status, "extra" => ['request' => ['remote_ip' => $request->getIp(), 'method' => $request->getMethod(), 'url' => $request->getUrl() . $request->getPath(), 'headers' => $request->headers(), 'body' => $request->getBody()], 'response' => $response->finalize(), 'tags' => [$this->defaultTag, $status], 'time' => $time], "type" => "ApiLog"]; $this->writer->send($data); } catch (Exception $e) { \Scalr::logException(new Exception(sprintf("Api logger could not save the record: %s", $e->getMessage()), $e->getCode(), $e)); } } }
public function xListBucketsAction() { $aws = $this->getAws(); $distributions = []; try { //Retrieves the list of all distributions $distList = $this->getAws(Aws::REGION_US_EAST_1)->cloudFront->distribution->describe(); /* @var $dist DistributionData */ foreach ($distList as $dist) { /* @var $org DistributionConfigOriginData */ foreach ($dist->distributionConfig->origins as $org) { $distributions[preg_replace('#\\.s3\\.amazonaws\\.com$#', '', $org->domainName)] = $dist; } unset($dist); } } catch (ClientException $e) { Scalr::logException($e); } // Get list of all user buckets $buckets = []; /* @var $bucket BucketData */ foreach ($aws->s3->bucket->getList() as $bucket) { $bucketName = $bucket->bucketName; if (empty($distributions[$bucketName])) { $info = ["name" => $bucketName]; } else { $dist = $distributions[$bucketName]; $info = ["name" => $bucketName, "cfid" => $dist->distributionId, "cfurl" => $dist->domainName, "cname" => $dist->distributionConfig->aliases->get(0)->cname, "status" => $dist->status, "enabled" => $dist->distributionConfig->enabled ? 'true' : 'false']; } $c = explode("-", $info['name']); if ($c[0] == 'farm') { $hash = $c[1]; $farm = $this->db->GetRow("\n SELECT id, name\n FROM farms\n WHERE hash = ? AND env_id = ?\n LIMIT 1\n ", [$hash, $this->environment->id]); if ($farm) { $info['farmId'] = $farm['id']; $info['farmName'] = $farm['name']; } } $buckets[] = $info; } $response = $this->buildResponseFromData($buckets, array('name', 'farmName')); $this->response->data($response); }
/** * {@inheritdoc} * @see \Scalr\Observer\AbstractEventObserver::OnFarmLaunched() */ public function OnFarmLaunched(FarmLaunchedEvent $event) { //SYSTEM DNS RECORD if (\Scalr::config('scalr.dns.static.enabled')) { try { $hash = DBFarm::LoadByID($event->GetFarmID())->Hash; $pdnsDb = \Scalr::getContainer()->dnsdb; $pdnsDb->Execute("INSERT INTO `domains` SET `name`=?, `type`=?, `scalr_farm_id`=?", array("{$hash}." . \Scalr::config('scalr.dns.static.domain_name'), 'NATIVE', $event->GetFarmID())); } catch (Exception $e) { \Scalr::logException($e); } } $zones = DBDNSZone::loadByFarmId($event->GetFarmID()); if (count($zones) == 0) { return; } foreach ($zones as $zone) { if ($zone->status == DNS_ZONE_STATUS::INACTIVE) { $zone->status = DNS_ZONE_STATUS::PENDING_CREATE; $zone->isZoneConfigModified = 1; $zone->save(); } } }
header("HTTP/1.0 500"); } } //Collects access log with processing time $accessLogPath = '/var/log/scalr/ui.log'; if (is_writable($accessLogPath)) { global $response, $path; if (isset($path) && $response instanceof Scalr_UI_Response) { @error_log(sprintf("%s,%s,\"%s\",%0.4f,%0.4f,%d\n", date('M d H:i:s P'), $error && !empty($error['type']) ? $error['type'] : 'OK', str_replace('"', '""', $path), $response->getHeader('X-Scalr-Inittime'), $response->getHeader('X-Scalr-Actiontime'), \Scalr::getDb()->numberQueries + (\Scalr::getContainer()->analytics->enabled ? \Scalr::getContainer()->cadb->numberQueries : 0)), 3, $accessLogPath); } } }); //NOTE: Apache mod_rewrite sets REDIRECT_URL instead of REQUEST_URI environment variable, we need to get final overridden URI $path = trim(str_replace("?{$_SERVER['QUERY_STRING']}", "", isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI']), '/'); $logMysqlExcepton = function ($e) { \Scalr::logException($e); Scalr_UI_Response::getInstance()->data(array('errorDB' => true)); Scalr_UI_Response::getInstance()->debugException($e); Scalr_UI_Response::getInstance()->failure($e instanceof \Scalr\Exception\MysqlConnectionException ? 'Database connection issue' : 'Database error'); Scalr_UI_Response::getInstance()->sendResponse(); }; try { $startTime = microtime(true); require __DIR__ . '/src/prepend.inc.php'; $prependTime = microtime(true); // public controller for link like /public/*; don't check CSRF $publicController = !strncmp('public', $path, strlen('public')); $session = Scalr_Session::getInstance(); $time1 = microtime(true); try { $request = Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_UI, getallheaders(), $_SERVER, $_REQUEST, $_FILES, $session->getUserId(), null);
/** * Also Removes Cost Centers properties generated for test * * {@inheritdoc} * @see Scalr\Tests\Functional\Api\ApiTestCase::tearDownAfterClass() */ public static function tearDownAfterClass() { ksort(static::$testData, SORT_REGULAR); foreach (static::$testData as $priority => $data) { foreach ($data as $class => $ids) { if ($class === 'Scalr\\Stats\\CostAnalytics\\Entity\\CostCentreEntity') { $ids = array_unique($ids, SORT_REGULAR); foreach ($ids as $entry) { /* @var $cc CostCentreEntity */ $cc = $class::findPk(...$entry); if (!empty($cc)) { try { CostCentrePropertyEntity::deleteByCcId($cc->ccId); AccountCostCenterEntity::deleteByCcId($cc->ccId); $cc->delete(); } catch (\Exception $e) { \Scalr::logException($e); } } } unset(static::$testData[$priority][$class]); } } } parent::tearDownAfterClass(); }
/** * {@inheritdoc} * @see \Scalr\Api\Rest\Application::defaultError() */ protected function defaultError($e = null) { if ($e instanceof Exception) { $errorEnvelope = $this->getErrorEnvelope(); if ($e instanceof ApiErrorException) { $errorEnvelope->errors[] = new ErrorMessage($e->getError(), $e->getMessage()); $this->response->setStatus($e->getStatus()); } else { if (!$e instanceof ErrorException) { \Scalr::logException($e); $errorEnvelope->errors[] = new ErrorMessage(ErrorMessage::ERR_INTERNAL_SERVER_ERROR, "Server Error"); $this->response->setStatus(500); } } $this->response->setContentType("application/json", "utf-8"); return @json_encode($errorEnvelope); } return ''; }
/** * Gets default error content * * @param \ErrorException $e optional An Exception * @return string */ protected function defaultError($e = null) { if ($e instanceof \Exception && !$e instanceof \ErrorException) { \Scalr::logException($e); } return $this->getDefaultTemplate('Error', 'A webstite error has occured'); }
public function checkLifeCycle($widgets) { $result = array(); foreach ($widgets as $id => $object) { $name = str_replace('dashboard.', '', $object['name']); try { $widget = Scalr_UI_Controller::loadController($name, 'Scalr_UI_Controller_Dashboard_Widget'); } catch (Exception $e) { continue; } try { $result[$id]['widgetContent'] = $widget->getContent($object['params']); } catch (ADODB_Exception $e) { \Scalr::logException($e); $result[$id]['widgetError'] = 'Database error'; } catch (Exception $e) { $result[$id]['widgetError'] = $e->getMessage(); } } return $result; }
public function xGetOpenstackResourcesAction() { $client = $this->environment->openstack($this->getParam('platform'), $this->getParam('cloudLocation')); $data = array(); // List flavors $data['flavors'] = array(); foreach ($client->servers->listFlavors() as $flavor) { $data['flavors'][] = array('id' => (string) $flavor->id, 'name' => $flavor->name); } try { if ($client->hasService('volume')) { $data['volume_types'] = array(); $volumeTypes = $client->volume->listVolumeTypes()->toArray(); foreach ($volumeTypes as $volumeType) { $data['volume_types'][] = array('id' => $volumeType->id, 'name' => $volumeType->name); } //TODO: Add support for extra-specs } } catch (Exception $e) { \Scalr::logException($e); } try { if ($client->servers->isExtensionSupported(ServersExtension::EXT_AVAILABILITY_ZONE)) { $availZones = $client->servers->listAvailabilityZones(); $data['availabilityZones'] = array(); foreach ($availZones as $zone) { if ($zone->zoneState->available == true) { $data['availabilityZones'][] = ['id' => (string) $zone->zoneName, 'name' => (string) $zone->zoneName, 'state' => (string) $zone->zoneState->available ? 'available' : 'unavailable']; } } } } catch (Exception $e) { \Scalr::logException($e); } if ($client->hasService('network') && !in_array($this->getParam('platform'), array(SERVER_PLATFORMS::RACKSPACENG_US, SERVER_PLATFORMS::RACKSPACENG_UK))) { $data['ipPools'] = array(array('id' => '', 'name' => '')); $data['networks'] = array(); $networks = $client->network->listNetworks(); $tenantId = $client->getConfig()->getAuthToken()->getTenantId(); foreach ($networks as $network) { if ($network->status == 'ACTIVE') { if ($network->{"router:external"} == true || $network->name == 'public') { $data['ipPools'][] = array('id' => $network->id, 'name' => $network->name); } if ($tenantId == $network->tenant_id || $network->shared == true) { $data['networks'][] = array('id' => $network->id, 'name' => $network->name); } } } } else { //Check floating IPs if ($client->servers->isExtensionSupported(ServersExtension::EXT_FLOATING_IP_POOLS)) { $data['ipPools'] = array(array('id' => '', 'name' => '')); $pools = $client->servers->listFloatingIpPools(); foreach ($pools as $pool) { $data['ipPools'][] = array('id' => $pool->name, 'name' => $pool->name); } } } $this->response->data(array('data' => $data)); }
/** * Removes API key and Entities generated for test * * @throws \Scalr\Exception\ModelException */ public static function tearDownAfterClass() { foreach (array_reverse(static::$testData) as $rec) { $class = $rec['class']; $entry = $rec['pk']; $initProperties = $rec['initProp']; $entity = new $class(); /* @var $entity AbstractEntity */ foreach ($entity->getIterator()->getPrimaryKey() as $pos => $prop) { $entity->{$prop} = $entry[$pos]; } //we should init properties which will be used in delete action foreach ($initProperties as $prop => $value) { $entity->{$prop} = $value; } try { //deletePk method does not remove related objects $entity->delete(); } catch (Exception $e) { //we should remove all created Entities \Scalr::logException($e); } } static::$testData = []; if (!empty(static::$apiKeyEntity)) { static::$apiKeyEntity->delete(); } static::changeLoggerConfiguration(); }
public static function handleRequest($pathChunks) { $startTime = microtime(true); if ($pathChunks[0] == '') { $pathChunks = array('guest'); } try { $user = Scalr_UI_Request::getInstance()->getUser(); if (!$user && !($pathChunks[0] == 'guest' || $pathChunks[0] == 'public')) { throw new Scalr_Exception_InsufficientPermissions(); } $controller = self::loadController(array_shift($pathChunks), 'Scalr_UI_Controller', true); $class = get_class($controller); $controller->uiCacheKeyPattern = ''; if ($user && $user->getAccountId() && $user->getAccount()->status != Scalr_Account::STATUS_ACTIVE && $user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER && $class != 'Scalr_UI_Controller_Account2' && $class != 'Scalr_UI_Controller_Core' && $class != 'Scalr_UI_Controller_Dashboard' && $class != 'Scalr_UI_Controller_Guest' && $class != 'Scalr_UI_Controller_Public') { // suspended account, user = owner, replace controller with billing or allow billing action/guest action throw new Exception('Your account has been suspended.'); } else { $r = explode('_', $class); $controller->addUiCacheKeyPatternChunk(strtolower(array_pop($r))); $controller->call($pathChunks); } } catch (Scalr_UI_Exception_AccessDenied $e) { Scalr_UI_Response::getInstance()->setHttpResponseCode(403); } catch (Scalr_Exception_InsufficientPermissions $e) { if (is_object($user)) { Scalr_UI_Response::getInstance()->failure($e->getMessage()); } else { Scalr_UI_Response::getInstance()->setHttpResponseCode(403); } } catch (Scalr_UI_Exception_NotFound $e) { Scalr_UI_Response::getInstance()->setHttpResponseCode(404); } catch (ADODB_Exception $e) { \Scalr::logException($e); Scalr_UI_Response::getInstance()->debugException($e); Scalr_UI_Response::getInstance()->failure('Database error'); } catch (FileNotFoundException $e) { Scalr_UI_Response::getInstance()->failure(sprintf("File '%s' not found", $e->getPath())); Scalr_UI_Response::getInstance()->setHttpResponseCode(404); } catch (Exception $e) { $rawHtml = get_class($e) == 'Scalr_Exception_LimitExceeded'; Scalr_UI_Response::getInstance()->debugException($e); Scalr_UI_Response::getInstance()->failure($e->getMessage(), $rawHtml); } Scalr_UI_Response::getInstance()->setHeader("X-Scalr-ActionTime", microtime(true) - $startTime); }
/** * Logs event to a specified backend * * @param string $event Event tag * @param mixed $extra optional Extra data to pass. * @param mixed $extra,... optional * @return boolean Indicates whether operation was successful * @throws AuditLoggerException */ public function auditLog($event, ...$extra) { if (!$this->enabled) { return true; } if (!empty($extra)) { if (array_key_exists($event, $this->subscribers)) { $extra = $this->subscribers[$event](...$extra); } else { $extra = $extra[0]; } } else { $extra = []; } $adjusted = []; foreach ($extra as $key => $val) { if (($pos = strpos($key, '.')) == 0) { //It will adjust data key with the event name when the key either does not contain //dot or starts with dot. $adjusted[$event . ($pos === false ? '.' : '') . $key] = $val; } else { $adjusted[$key] = $val; } } $adjusted = array_merge($this->getCommonData(), $adjusted); $adjusted["tags"] = [$event]; if (!empty($this->defaultTag)) { $adjusted["tags"][] = $this->defaultTag; } $data = ["tag" => $this->defaultTag, "message" => $event, "extra" => $adjusted]; try { $result = $this->writer->send($data); } catch (Exception $e) { \Scalr::logException(new Exception(sprintf("Audit logger couldn't log the record: %s", $e->getMessage()), $e->getCode(), $e)); $result = false; } return $result; }