Since: 5.9 (10.06.2015)
Author: Roman Kolodnitskyi (r.kolodnitskyi@scalr.com)
Inheritance: extends Scalr\Model\AbstractEntity, implements Scalr\DataType\ScopeInterface
Beispiel #1
0
 public function _name($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Entity\FarmRoleScalingMetric */
             $to->name = ScalingMetricAdapter::metricNameToData($from->metric->name);
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             $this->validateString($from->name, 'Property name contains invalid characters');
             /* @var $metric Entity\ScalingMetric */
             $metric = Entity\ScalingMetric::findOne([['name' => ScalingMetricAdapter::metricNameToEntity($from->name)]]);
             if (empty($metric)) {
                 throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, sprintf('Scaling metric with name %s does not exist', $from->name));
             }
             /* @var $to Entity\FarmRoleScalingMetric */
             $to->metricId = $metric->id;
             $to->metric = $metric;
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             return [[]];
     }
 }
Beispiel #2
0
 /**
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xListMetricsAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_GENERAL_CUSTOM_SCALING_METRICS);
     $criteria = [['$or' => [['envId' => $this->getEnvironmentId()], ['envId' => null]]]];
     $metrics = (array) Entity\ScalingMetric::result(Entity\ScalingMetric::RESULT_ENTITY_COLLECTION)->find($criteria, null, ['id' => true, 'name' => true, 'filePath' => true]);
     $this->response->data(['data' => $metrics, 'total' => count($metrics)]);
 }
Beispiel #3
0
 /**
  * {@inheritdoc}
  * @see ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof Entity\ScalingMetric) {
         throw new InvalidArgumentException(sprintf("First argument must be instance of Scalr\\Model\\Entity\\ScalingMetric class"));
     }
     if (empty($entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Missed property name');
     }
     if (!preg_match('/^' . Entity\ScalingMetric::NAME_REGEXP . '$/', $entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, 'Scaling metric name should be both alphanumeric and greater than 5 chars');
     }
     $criteria = $this->controller->getScopeCriteria();
     $criteria[] = ['name' => $entity->name];
     $criteria[] = ['id' => ['$ne' => $entity->id]];
     if (!empty(Entity\ScalingMetric::findOne($criteria))) {
         throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, sprintf('Scaling metric with name %s already exists', $entity->name));
     }
     if (empty($entity->retrieveMethod)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Missed property retrieveMethod');
     }
     if (!in_array($entity->retrieveMethod, [Entity\ScalingMetric::RETRIEVE_METHOD_EXECUTE, Entity\ScalingMetric::RETRIEVE_METHOD_READ, Entity\ScalingMetric::RETRIEVE_METHOD_URL_REQUEST])) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, 'Unexpected retrieveMethod value');
     }
     $uriParts = parse_url($entity->filePath);
     if (!$uriParts) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, 'Property filePath is invalid');
     }
     if ($entity->retrieveMethod == Entity\ScalingMetric::RETRIEVE_METHOD_URL_REQUEST && (empty($uriParts['scheme']) || !in_array($uriParts['scheme'], ['http', 'https']))) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid path for request.');
     }
     if (empty($entity->calcFunction)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Missed property function');
     }
     if (empty($entity->filePath)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Missed property filePath');
     }
 }
Beispiel #4
0
 /**
  *
  * @return Entity\ScalingMetric
  */
 function getMetric()
 {
     if (!$this->metric) {
         $this->metric = Entity\ScalingMetric::findPk($this->metricId);
     }
     return $this->metric;
 }
Beispiel #5
0
 /**
  * Get ScalingMetric entity
  *
  * @param string $criteria search criteria
  * @return ScalingMetric
  */
 protected function getScalingMetric($criteria)
 {
     /* @var $metric ScalingMetric */
     $metric = ScalingMetric::findOne([['name' => $criteria]]);
     static::toDelete(ScalingMetric::class, [$metric->id]);
     return $metric;
 }
Beispiel #6
0
 /**
  * Get a list of names farm-role scaling metrics.
  *
  * @param int $farmRoleId farm-role identifier
  * @return array
  */
 public static function listFarmRoleMetric($farmRoleId)
 {
     $result = [];
     /* @var $metric ScalingMetric */
     $metric = new ScalingMetric();
     /* @var $farmRoleMetric FarmRoleScalingMetric */
     $farmRoleMetric = new FarmRoleScalingMetric();
     $criteria[static::STMT_FROM] = "{$metric->table()} JOIN  {$farmRoleMetric->table()}  ON {$farmRoleMetric->columnMetricId} = {$metric->columnId}";
     $criteria[static::STMT_WHERE] = "{$farmRoleMetric->columnFarmRoleId} = {$farmRoleId}";
     $farmRoleMetrics = ScalingMetric::find($criteria);
     if ($farmRoleMetrics->count() > 0) {
         /* @var $scalingMetric ScalingMetric */
         foreach ($farmRoleMetrics as $scalingMetric) {
             $result[] = $scalingMetric->name;
         }
     }
     return $result;
 }
Beispiel #7
0
 /**
  * @param int $farmId optional
  * @param int $roleId optional
  * @param string $scalrPageHash optional
  * @param string $scalrPageUiHash optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xGetFarmAction($farmId = null, $roleId = null, $scalrPageHash = null, $scalrPageUiHash = null)
 {
     if ($scalrPageHash && $scalrPageHash != $this->calcFarmDesignerHash()) {
         $this->response->data(['scalrPageHashMismatch' => true]);
         return;
     }
     if ($scalrPageUiHash && $scalrPageUiHash != $this->response->pageUiHash()) {
         $this->response->data(['scalrPageUiHashMismatch' => true]);
         return;
     }
     $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true));
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]);
     //platforms list
     $platforms = self::loadController('Platforms')->getEnabledPlatforms();
     if (empty($platforms)) {
         throw new Exception('Before building new farm you need to configure environment and setup cloud credentials');
     }
     $moduleParams['categories'] = self::loadController('Roles')->listRoleCategories(true, true);
     $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     if ($moduleParams['farmVpcEc2Enabled']) {
         $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false);
     }
     if ($farmId) {
         $this->request->checkPermissions(DBFarm::LoadByID($farmId)->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE);
         $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
         $moduleParams['farm'] = $c->getFarm2($farmId);
     } else {
         $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE);
         // TODO: remove hack, do better
         $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM);
         $moduleParams['farmVariables'] = $vars->getValues();
     }
     $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'scripting', 'ec2', 'openstack', 'gce', 'azure', 'security', 'devel', 'storage', 'variables', 'advanced', 'chef');
     //deprecated tabs
     if (\Scalr::config('scalr.ui.show_deprecated_features')) {
         $moduleParams['tabs'][] = 'ebs';
     }
     $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
     $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->keychain(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => file_get_contents(APPPATH . '/templates/services/nginx/server_section.tpl'), 'server_section_ssl' => file_get_contents(APPPATH . '/templates/services/nginx/server_section_ssl.tpl')));
     $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy');
     $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo');
     if (Scalr::isHostedScalr()) {
         $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = ['latest' => Utils::getScalarizrUpdateRepoTitle('latest')];
         if ($this->user->getAccount()->priority == 100) {
             $moduleParams['tabParams']['scalr.scalarizr_update.repos']['stable'] = Utils::getScalarizrUpdateRepoTitle('stable');
         }
     } else {
         $repos = array_keys(\Scalr::config('scalr.scalarizr_update.repos'));
         $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_combine($repos, $repos);
     }
     $moduleParams['tabParams']['scalr.scalarizr_update.devel_repos'] = is_array(\Scalr::config('scalr.scalarizr_update.devel_repos')) ? array_keys(\Scalr::config('scalr.scalarizr_update.devel_repos')) : [];
     $moduleParams['tabParams']['scalr.aws.ec2.limits.security_groups_per_instance'] = \Scalr::config('scalr.aws.ec2.limits.security_groups_per_instance');
     $moduleParams['metrics'] = Entity\ScalingMetric::getList($this->getEnvironmentId());
     $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones();
     $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
     if ($moduleParams['farm']['farm']['ownerEditable']) {
         $moduleParams['usersList'] = [];
         foreach (Entity\Account\User::findByAccountId($this->user->getAccountId()) as $user) {
             $moduleParams['usersList'][] = ['id' => $user->id, 'email' => $user->email];
         }
     }
     $defaultFarmRoleSecurityGroups = array('default');
     if (\Scalr::config('scalr.aws.security_group_name')) {
         $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name');
     }
     $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups), 'base.abort_init_on_script_fail' => \Scalr::config('scalr.system.scripting.default_abort_init_on_script_fail') ? 1 : 0, 'base.disable_firewall_management' => \Scalr::config('scalr.system.default_disable_firewall_management') ? 1 : 0);
     //cost analytics
     if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
         $farmCostData = $this->getFarmCostData($farmId);
         $moduleParams['analytics'] = $farmCostData['analytics'];
         if ($farmId) {
             $moduleParams['farm']['farm']['projectId'] = $farmCostData['projectId'];
             $moduleParams['analytics']['farmCostMetering'] = $farmCostData['farmCostMetering'];
         }
     }
     $moduleParams['farmLaunchPermission'] = $farmId ? $moduleParams['farm']['farm']['launchPermission'] : $this->request->isAllowed([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS], Acl::PERM_FARMS_LAUNCH_TERMINATE);
     $this->response->data($moduleParams);
 }
Beispiel #8
0
 /**
  * @param int $farmId optional
  * @param int $roleId optional
  * @param string $scalrPageHash optional
  * @param string $scalrPageUiHash optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xGetFarmAction($farmId = null, $roleId = null, $scalrPageHash = null, $scalrPageUiHash = null)
 {
     if ($scalrPageHash && $scalrPageHash != $this->calcFarmDesignerHash()) {
         $this->response->data(['scalrPageHashMismatch' => true]);
         return;
     }
     if ($scalrPageUiHash && $scalrPageUiHash != $this->response->pageUiHash()) {
         $this->response->data(['scalrPageUiHashMismatch' => true]);
         return;
     }
     $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true));
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]);
     //platforms list
     $platforms = self::loadController('Platforms')->getEnabledPlatforms();
     if (empty($platforms)) {
         throw new Exception('Before building new farm you need to configure environment and setup cloud credentials');
     }
     //categories list
     $categories = $this->db->GetAll("SELECT c.id, c.name, COUNT(DISTINCT r.id) AS total\n             FROM role_categories c\n             LEFT JOIN roles r ON c.id = r.cat_id AND (r.env_id IS NULL OR r.env_id = ?) AND r.id IN (\n                SELECT role_id\n                FROM role_images\n                WHERE role_id = r.id\n                AND platform IN ('" . implode("','", array_keys($platforms)) . "')\n             )\n             WHERE c.env_id IS NULL OR c.env_id = ?\n             GROUP BY c.id\n            ", array($this->environment->id, $this->environment->id));
     $moduleParams['categories'] = array();
     foreach ($categories as $g) {
         $moduleParams['categories'][$g['id']] = $g;
     }
     $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     if ($moduleParams['farmVpcEc2Enabled']) {
         $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false);
     }
     if ($farmId) {
         $this->request->restrictFarmAccess(DBFarm::LoadByID($farmId), Acl::PERM_FARMS_MANAGE);
         $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
         $moduleParams['farm'] = $c->getFarm2($farmId);
     } else {
         $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
         // TODO: remove hack, do better
         $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM);
         $moduleParams['farmVariables'] = $vars->getValues();
     }
     $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'scripting', 'ec2', 'openstack', 'gce', 'azure', 'security', 'devel', 'storage', 'variables', 'advanced', 'chef');
     //deprecated tabs
     if (\Scalr::config('scalr.ui.show_deprecated_features')) {
         $moduleParams['tabs'][] = 'deployments';
         $moduleParams['tabs'][] = 'ebs';
         $moduleParams['tabs'][] = 'servicesconfig';
     }
     $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
     $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->cloudCredentials(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => file_get_contents(APPPATH . '/templates/services/nginx/server_section.tpl'), 'server_section_ssl' => file_get_contents(APPPATH . '/templates/services/nginx/server_section_ssl.tpl')));
     $moduleParams['tabParams']['scalr.dns.global.enabled'] = \Scalr::config('scalr.dns.global.enabled');
     $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy');
     $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_keys(\Scalr::config('scalr.scalarizr_update.repos'));
     $moduleParams['tabParams']['scalr.scalarizr_update.devel_repos'] = is_array(\Scalr::config('scalr.scalarizr_update.devel_repos')) ? array_keys(\Scalr::config('scalr.scalarizr_update.devel_repos')) : [];
     $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo');
     $moduleParams['tabParams']['scalr.aws.ec2.limits.security_groups_per_instance'] = \Scalr::config('scalr.aws.ec2.limits.security_groups_per_instance');
     $moduleParams['metrics'] = Entity\ScalingMetric::getList($this->getEnvironmentId());
     $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones();
     $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
     if ($moduleParams['farm']['farm']['ownerEditable']) {
         $moduleParams['usersList'] = Scalr_Account_User::getList($this->user->getAccountId());
     }
     $defaultFarmRoleSecurityGroups = array('default');
     if (\Scalr::config('scalr.aws.security_group_name')) {
         $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name');
     }
     $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups), 'base.abort_init_on_script_fail' => \Scalr::config('scalr.system.scripting.default_abort_init_on_script_fail') ? 1 : 0, 'base.disable_firewall_management' => \Scalr::config('scalr.system.default_disable_firewall_management') ? 1 : 0);
     //cost analytics
     if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
         $farmCostData = $this->getFarmCostData($farmId);
         $moduleParams['analytics'] = $farmCostData['analytics'];
         if ($farmId) {
             $moduleParams['farm']['farm']['projectId'] = $farmCostData['projectId'];
             $moduleParams['analytics']['farmCostMetering'] = $farmCostData['farmCostMetering'];
         }
     }
     $moduleParams['farmLaunchPermission'] = $farmId ? $moduleParams['farm']['farm']['launchPermission'] : $this->request->isFarmAllowed(null, Acl::PERM_FARMS_LAUNCH_TERMINATE);
     if ($moduleParams['farm']['farm']['teamOwnerEditable'] || !$farmId) {
         if ($this->user->canManageAcl()) {
             $teams = $this->db->getAll('SELECT id, name, description FROM account_teams WHERE account_id = ?', array($this->user->getAccountId()));
         } else {
             $teams = $this->user->getTeams();
             $teamId = $moduleParams['farm']['farm']['teamOwner'];
             $flag = !!$teamId;
             foreach ($teams as $t) {
                 if ($t['id'] == $teamId) {
                     $flag = false;
                     break;
                 }
             }
             if ($flag) {
                 // team is missed in list, add manually
                 $team = $this->db->GetRow('SELECT name, description FROM account_teams WHERE id = ?', [$teamId]);
                 array_unshift($teams, ['id' => $teamId, 'name' => $team ? $team['name'] : '', 'description' => $team ? $team['description'] : '']);
             }
         }
         array_unshift($teams, ['id' => 0, 'name' => '']);
         $moduleParams['teamsList'] = $teams;
     }
     $this->response->data($moduleParams);
 }