/** * {@inheritdoc} * @see \Scalr\System\Zmq\Cron\TaskInterface::worker() */ public function worker($request) { //Warming up static DI cache \Scalr::getContainer()->warmup(); // Reconfigure observers \Scalr::ReconfigureObservers(); try { $dbFarm = DBFarm::LoadByID($request->farmId); $curDate = new DateTime(); $tdValue = $dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE); if ($tdValue) { $td = new DateTime($tdValue); if ($td < $curDate) { //Terminates farm $event = new FarmTerminatedEvent(0, 1, false, 1); SettingEntity::increase(SettingEntity::LEASE_TERMINATE_FARM); \Scalr::FireEvent($request->farmId, $event); $this->log('INFO', sprintf('Farm: %s [ID: %d] was terminated by lease manager', $dbFarm->Name, $dbFarm->ID)); } else { // only inform user $days = $td->diff($curDate)->days; $notifications = json_decode($dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND), true); $governance = new Scalr_Governance($dbFarm->EnvID); $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications'); 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->log('INFO', "Notification was sent by key: %s about farm: %s [ID: %d] by lease manager", $n['key'], $dbFarm->Name, $dbFarm->ID); } } } } } } catch (Exception $e) { throw $e; } return $request; }
public function xRequestResultAction() { $this->request->defineParams(array('requests' => array('type' => 'json'), 'decision')); if (!in_array($this->getParam('decision'), array(FarmLease::STATUS_APPROVE, FarmLease::STATUS_DECLINE))) { throw new Scalr_Exception_Core('Wrong status'); } foreach ($this->getParam('requests') as $id) { $req = $this->db->GetRow('SELECT * FROM farm_lease_requests WHERE id = ? LIMIT 1', array($id)); if ($req) { $dbFarm = DBFarm::LoadByID($req['farm_id']); $this->user->getPermissions()->validate($dbFarm); $this->db->Execute('UPDATE farm_lease_requests SET status = ?, answer_comment = ?, answer_user_id = ? WHERE id = ?', array($this->getParam('decision'), $this->getParam('comment'), $this->user->getId(), $id)); try { $mailer = Scalr::getContainer()->mailer; $user = new Scalr_Account_User(); $user->loadById($dbFarm->createdByUserId); if ($this->getContainer()->config('scalr.auth_mode') == 'ldap') { if ($user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)) { $mailer->addTo($user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)); } else { $mailer->addTo($user->getEmail()); } } else { $mailer->addTo($user->getEmail()); } } catch (Exception $e) { $mailer = null; } if ($this->getParam('decision') == FarmLease::STATUS_APPROVE) { if ($req['request_days'] > 0) { $dt = $dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE); $dt = new DateTime($dt); $dt->add(new DateInterval('P' . $req['request_days'] . 'D')); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s')); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, null); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_approve.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{date}}' => $dt->format('M j, Y'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } else { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, ''); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, ''); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, ''); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_forever.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } else { $dt = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE)); SettingEntity::increase(SettingEntity::LEASE_DECLINED_REQUEST); if ($mailer) { $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_decline.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{date}}' => $dt->format('M j, Y'), '{{comment}}' => $this->getParam('comment'), '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); } } } } $this->response->success(); }
/** * {@inheritdoc} * @see \Scalr\System\Zmq\Cron\TaskInterface::worker() */ public function worker($request) { //Warming up static DI cache \Scalr::getContainer()->warmup(); // Reconfigure observers \Scalr::ReconfigureObservers(); try { $dbFarm = DBFarm::LoadByID($request->farmId); $curDate = new DateTime(); $tdValue = $dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE); if ($tdValue) { $td = new DateTime($tdValue); if ($td < $curDate) { //Terminates farm SettingEntity::increase(SettingEntity::LEASE_TERMINATE_FARM); //Ajdusts both account & environment for the audit log \Scalr::getContainer()->auditlogger->setAccountId($dbFarm->ClientID)->setAccountId($dbFarm->EnvID); \Scalr::FireEvent($request->farmId, new FarmTerminatedEvent(0, 1, false, 1, true, null)); $this->log('INFO', sprintf('Farm: %s [ID: %d] was terminated by lease manager', $dbFarm->Name, $dbFarm->ID)); } else { // only inform user $days = $td->diff($curDate)->days; $notifications = json_decode($dbFarm->GetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND), true); $governance = new Scalr_Governance($dbFarm->EnvID); $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications'); 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(Entity\FarmSetting::TIMEZONE), 'M j, Y'); /* @var $user Entity\Account\User */ if ($n['to'] == 'owner') { if ($dbFarm->ownerId) { $user = Entity\Account\User::findPk($dbFarm->ownerId); } else { $user = Entity\Account\User::findOne([['accountId' => $dbFarm->ClientID], ['type' => Entity\Account\User::TYPE_ACCOUNT_OWNER]]); } 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 { foreach (explode(',', $n['emails']) as $email) { $mailer->addTo(trim($email)); } } $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml.php', array('terminateDate' => $tdHuman, 'farm' => $dbFarm->Name, 'envName' => $dbFarm->GetEnvironmentObject()->name, 'envId' => $dbFarm->GetEnvironmentObject()->id, 'showOwnerWarning' => !$dbFarm->ownerId)); $notifications[$n['key']] = 1; $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, json_encode($notifications)); $this->log('INFO', "Notification was sent by key: %s about farm: %s [ID: %d] by lease manager", $n['key'], $dbFarm->Name, $dbFarm->ID); } } } } } } catch (Exception $e) { throw $e; } return $request; }
/** * Get announcements from rss feed or from rss cache if any * * @param $type string Announcement type * @param $params mixed[] See self::CONFIG_DEFAULT * - interval int Diff in seconds from NOW. For announcements filtering. * - feedUrlCfg string Name of the config parameter with RSS feed url. * - cacheId string ID of SettingEntity, holding cache. * - cacheLifetime int Cache lifetime in seconds. * @return array * @throws \Scalr_Exception_Core */ private function rssAnnouncements($type, $params) { $now = $this->tmRequestDashboard; $minTm = $now - $params['interval']; $cacheId = $params['cacheId']; $cacheLifeTime = $params['cacheLifetime']; $data = []; $limit = 100; $feedUrl = $this->getContainer()->config->get($params['feedUrlCfg']); $cache = SettingEntity::getValue($cacheId); if (empty($feedUrl)) { if (!empty($cache)) { SettingEntity::setValue($cacheId, null); } return ['data' => []]; } /* @var $cacheObj array */ if (!empty($cache)) { $cacheObj = unserialize($cache); } if (isset($cacheObj) && $now - $cacheObj['tm'] < $cacheLifeTime) { $data = $cacheObj['data']; } else { /* @var $feedXml SimpleXMLElement */ $feedXml = $this->getRssFeedXml($feedUrl); if ($feedXml !== false) { switch ($type) { case self::TYPE_CHANGELOG: foreach ($feedXml->entry as $key => $item) { $published = strtotime((string) $item->published); $data[] = ['title' => (string) $item->title, 'url' => (string) $item->link->attributes()->href, 'timestamp' => $published]; } break; case self::TYPE_SCALRBLOG: foreach ($feedXml->channel->item as $key => $item) { $published = strtotime((string) $item->pubDate); $data[] = ['title' => (string) $item->title, 'url' => (string) $item->link, 'timestamp' => $published]; } } } SettingEntity::setValue($cacheId, serialize(['tm' => $now, 'data' => $data])); } $count = 0; foreach ($data as &$item) { if ($limit < $count || $minTm > $item['timestamp']) { break; } $item['type'] = $type; $item['time'] = date('M d Y', $item['timestamp']); $count++; } if ($count < count($data)) { array_splice($data, $count); } return ['data' => $data]; }
public function xLeaseExtendAction() { if (!$this->getParam('farmId')) { throw new Exception(_('Server not found')); } $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_LAUNCH_TERMINATE); $governance = new Scalr_Governance($this->getEnvironmentId()); if (!($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $dbFarm->GetSetting(Entity\FarmSetting::LEASE_STATUS) && $dbFarm->Status == FARM_STATUS::RUNNING)) { throw new Scalr_Exception_Core('You can\'t manage lease for this farm'); } $config = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, null); $terminateDate = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE)); if ($config['leaseExtension'] != 'allow') { throw new Scalr_Exception_Core('You can\'t extend lease for this farm'); } if ($this->getParam('extend') == 'standard') { $standardExtend = $terminateDate->diff(new DateTime())->days < $config['defaultLifePeriod'] && $dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT) < $config['leaseExtensionStandardNumber']; if ($standardExtend) { $terminateDate->add(new DateInterval('P' . intval($config['defaultLifePeriod']) . 'D')); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT, $dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT) + 1); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE, $terminateDate->format('Y-m-d H:i:s')); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, null); Entity\SettingEntity::increase(Entity\SettingEntity::LEASE_STANDARD_REQUEST); $this->response->success('Farm expiration date was changed'); } else { $this->response->failure('Limit of changes was reached'); } } else { if ($this->getParam('extend') == 'non-standard') { $lease = new FarmLease($dbFarm); $comment = $this->getParam('comment'); $last = $lease->getLastRequest(); if ($last && $last['status'] == FarmLease::STATUS_PENDING) { $this->response->failure('You\'ve already made expiration request. Before make another one, wait for answer.'); } else { if ($this->getParam('by') == 'days' && intval($this->getParam('byDays')) > 0) { $lease->addRequest(intval($this->getParam('byDays')), $comment, $this->user->getId()); } else { if ($this->getParam('by') == 'date' && strtotime($this->getParam('byDate'))) { $dt = new DateTime($this->getParam('byDate')); $lease->addRequest($terminateDate->diff($dt)->days, $comment, $this->user->getId()); } else { if ($this->getParam('by') == 'forever') { $lease->addRequest(0, $comment, $this->user->getId()); } else { throw new Scalr_Exception_Core('Invalid period format'); } } } Entity\SettingEntity::increase(Entity\SettingEntity::LEASE_NOT_STANDARD_REQUEST); $mailer = Scalr::getContainer()->mailer; if ($this->getContainer()->config('scalr.auth_mode') == 'ldap') { $owner = $this->user->getAccount()->getOwner(); if ($owner->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)) { $mailer->addTo($owner->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL)); } else { $mailer->addTo($owner->getEmail()); } } else { $mailer->addTo($this->user->getAccount()->getOwner()->getEmail()); } if ($config['leaseExtensionNonStandardNotifyEmails']) { $emails = explode(',', $config['leaseExtensionNonStandardNotifyEmails']); foreach ($emails as $email) { $email = trim($email); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $mailer->addTo($email); } } } $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_request.eml', array('{{farm_name}}' => $dbFarm->Name, '{{user_name}}' => $this->user->getEmail(), '{{comment}}' => $comment, '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id)); $this->response->success('Farm expiration request was sent'); } } else { if ($this->getParam('extend') == 'cancel') { $lease = new FarmLease($dbFarm); if ($lease->cancelLastRequest()) { $this->response->success('Non-standard extend was cancelled'); } else { $this->response->failure('Last request wasn\'t found'); } } else { $this->response->failure('Invalid extend type'); } } } }
$envId = (int) $_SERVER['HTTP_X_SCALR_ENV_ID']; $pathChunks = explode('/', $path); $version = array_shift($pathChunks); $path = '/' . $path; $user = Scalr_Account_User::init(); $user->loadByApiAccessKey($keyId); if (!$user->getSetting(Scalr_Account_User::SETTING_API_ENABLED)) { throw new Exception("API disabled for this account"); } //Check IP whitelist $postData = isset($_POST['rawPostData']) ? $_POST['rawPostData'] : ''; $secretKey = $user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY); $stringToSign = "{$path}:{$keyId}:{$envId}:{$postData}:{$secretKey}"; $validToken = CryptoTool::hash($stringToSign); if ($validToken != $token) { throw new Exception("Invalid authentification token"); } // prepate input data $postDataConvert = array(); foreach (json_decode($postData, true) as $key => $value) { $postDataConvert[str_replace('.', '_', $key)] = $value; } $request = Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_API, Scalr::getAllHeaders(), $_SERVER, $postDataConvert, $_FILES, $user->id, $envId); $request->requestApiVersion = intval(trim($version, 'v')); SettingEntity::increase('internalapi.' . join('.', $pathChunks)); Scalr_Api_Controller::handleRequest($pathChunks); Scalr_UI_Response::getInstance()->sendResponse(); } catch (Exception $e) { Scalr_UI_Response::getInstance()->failure($e->getMessage()); Scalr_UI_Response::getInstance()->sendResponse(); }