Beispiel #1
0
 /**
  * Gets default search criteria according environment scope
  *
  * @return array Returns array of the search criteria
  */
 private function getDefaultCriteria()
 {
     $environment = $this->getEnvironment();
     $criteria = [['envId' => $environment->id]];
     if (!$this->hasPermissions(Acl::RESOURCE_FARMS)) {
         $where = [];
         $farm = new Farm();
         $farmTeam = new FarmTeam();
         if ($this->hasPermissions(Acl::RESOURCE_OWN_FARMS)) {
             $where[] = "{$farm->columnOwnerId()} = " . $farm->qstr('ownerId', $this->getUser()->id);
         }
         if ($this->hasPermissions(Acl::RESOURCE_TEAM_FARMS)) {
             $join[] = "\n                    LEFT JOIN {$farmTeam->table('ft')} ON {$farmTeam->columnFarmId('ft')} = {$farm->columnId()}\n                    LEFT JOIN `account_team_users` `atu` ON `atu`.`team_id` = {$farmTeam->columnTeamId('ft')}\n                    LEFT JOIN `account_team_envs` `ate` ON `ate`.`team_id` = {$farmTeam->columnTeamId('ft')} AND `ate`.`env_id` = {$farm->columnEnvId()}\n                ";
             $where[] = "`atu`.`user_id` = " . $farmTeam->db()->qstr($this->getUser()->id) . " AND `ate`.`team_id` IS NOT NULL";
         }
         if (!empty($where)) {
             $criteria[Farm::STMT_WHERE] = '(' . join(' OR ', $where) . ')';
         }
         if (!empty($join)) {
             if (empty($criteria[Farm::STMT_FROM])) {
                 $criteria[Farm::STMT_FROM] = $farm->table();
             }
             $criteria[Farm::STMT_FROM] .= implode(' ', $join);
         }
     }
     return $criteria;
 }
Beispiel #2
0
 /**
  * Gets Default search criteria for the Environment scope
  *
  * @return array Returns array of the default search criteria for the Environment scope
  */
 private function getDefaultCriteria()
 {
     $server = new Server();
     $defaultCondition = sprintf("{$server->columnAccountId()} = %d AND {$server->columnEnvId()} = %d ", $this->getUser()->accountId, $this->getEnvironment()->id);
     $and = " AND {$server->columnFarmId()} IS NOT NULL ";
     if (!$this->hasPermissions(Acl::RESOURCE_FARMS)) {
         $where = [];
         $farm = new Farm();
         $farmTeam = new FarmTeam();
         $join[] = " LEFT JOIN {$farm->table('f')} ON {$farm->columnId('f')} = {$server->columnFarmId()}";
         if ($this->hasPermissions(Acl::RESOURCE_OWN_FARMS)) {
             $where[] = "{$farm->columnOwnerId('f')} = " . $farm->qstr('ownerId', $this->getUser()->id);
         }
         if ($this->hasPermissions(Acl::RESOURCE_TEAM_FARMS)) {
             $join[] = "\n                    LEFT JOIN {$farmTeam->table('ft')} ON {$farmTeam->columnFarmId('ft')} = {$farm->columnId('f')}\n                    LEFT JOIN `account_team_users` `atu` ON `atu`.`team_id` = {$farmTeam->columnTeamId('ft')}\n                    LEFT JOIN `account_team_envs` `ate` ON `ate`.`team_id` = {$farmTeam->columnTeamId('ft')} AND `ate`.`env_id` = {$farm->columnEnvId('f')}\n                ";
             $where[] = "`atu`.`user_id` = " . $farmTeam->db()->qstr($this->getUser()->id) . " AND `ate`.`team_id` IS NOT NULL";
         }
         if (!empty($where)) {
             $criteria[Farm::STMT_WHERE] = '(' . $defaultCondition . $and . ' AND ' . join(' OR ', $where) . ')';
         }
         $criteria[Farm::STMT_FROM] = $server->table() . implode(' ', $join);
     }
     // add Temporary and Importing Servers to response
     if ($this->hasPermissions(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE)) {
         $extraCondition = sprintf("({$defaultCondition} AND {$server->columnFarmId()} IS NULL AND {$server->columnStatus()} IN ('%s', '%s'))", Server::STATUS_IMPORTING, Server::STATUS_TEMPORARY);
         if (empty($criteria[Farm::STMT_WHERE]) && $this->hasPermissions(Acl::RESOURCE_FARMS)) {
             $criteria[Farm::STMT_WHERE] = "(({$defaultCondition}{$and}) OR {$extraCondition})";
         } else {
             if (empty($criteria[Farm::STMT_WHERE])) {
                 $criteria[Farm::STMT_WHERE] = "{$extraCondition}";
             } else {
                 $criteria[Farm::STMT_WHERE] = "({$criteria[Farm::STMT_WHERE]} OR {$extraCondition})";
             }
         }
     }
     if (empty($criteria[Farm::STMT_WHERE])) {
         $criteria[Farm::STMT_WHERE] = $defaultCondition;
     }
     return $criteria;
 }
Beispiel #3
0
 /**
  * @param   int         $farmId
  * @param   int         $expirePeriod
  * @param   bool        $manageable
  * @param   string      $owner
  * @param   int         $chefServerId
  * @param   string      $projectId
  * @param   int         $status
  * @throws  Exception
  * @throws  Scalr_Exception_Core
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xListFarmsAction($farmId = null, $expirePeriod = null, $manageable = false, $owner = null, $chefServerId = null, $projectId = null, $status = null)
 {
     $this->request->restrictAccess([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS]);
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $leaseStatus = $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE);
     $f = new Entity\Farm();
     $sql = "\n            SELECT {$f->fields('f')}, au.email AS ownerEmail,\n                (SELECT " . Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id) . ") AS farmTeamIdPerm,\n                GROUP_CONCAT(DISTINCT at.name SEPARATOR ', ') AS farmTeams,\n                GROUP_CONCAT(DISTINCT behavior) AS behaviors,\n                (SELECT COUNT(*) FROM farm_roles WHERE farmid = f.id) AS rolesCnt,\n                (SELECT COUNT(*) FROM dns_zones WHERE farm_id = f.id) AS zonesCnt,\n                (SELECT COUNT(*) FROM server_alerts WHERE farm_id= f.id AND status = ?) AS alertsCnt,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?,?,?,?)) AS runningServers,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?)) AS suspendedServers,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?)) AS nonRunningServers\n            FROM {$f->table('f')}\n            LEFT JOIN account_users au ON au.id = f.created_by_id\n            LEFT JOIN farm_teams ft ON ft.farm_id = {$f->columnId('f')}\n            LEFT JOIN account_teams at ON at.id = ft.team_id\n            LEFT JOIN farm_roles fr ON fr.farmid = {$f->columnId('f')}\n            LEFT JOIN role_behaviors rb ON rb.role_id = fr.role_id\n            WHERE {$f->columnEnvId('f')} = ?\n            AND :FILTER:\n            AND " . $this->request->getFarmSqlQuery($manageable ? Acl::PERM_FARMS_UPDATE : null);
     $args = [Entity\Server\Alert::STATUS_FAILED, Entity\Server::STATUS_PENDING, Entity\Server::STATUS_INIT, Entity\Server::STATUS_RUNNING, Entity\Server::STATUS_TEMPORARY, Entity\Server::STATUS_RESUMING, Entity\Server::STATUS_SUSPENDED, Entity\Server::STATUS_PENDING_SUSPEND, Entity\Server::STATUS_TERMINATED, Entity\Server::STATUS_PENDING_TERMINATE, $this->getEnvironmentId()];
     if ($leaseStatus && $expirePeriod) {
         $dt = new DateTime();
         $dt->add(new DateInterval('P' . $expirePeriod . 'D'));
         $sql .= " AND EXISTS (\n                        SELECT 1 FROM farm_settings\n                        WHERE farm_settings.farmid = f.id\n                        AND farm_settings.name = ?\n                        AND farm_settings.value != ''\n                        AND farm_settings.value < ?\n                    ) AND f.status = ?";
         $args[] = Entity\FarmSetting::LEASE_TERMINATE_DATE;
         $args[] = $dt->format('Y-m-d H:i:s');
         $args[] = Entity\Farm::STATUS_RUNNING;
     }
     if ($farmId) {
         $sql .= ' AND f.id = ?';
         $args[] = $farmId;
     }
     if ($owner) {
         if ($owner == 'me') {
             $sql .= " AND {$f->columnOwnerId('f')} = ?";
             $args[] = $this->getUser()->id;
         } else {
             if ($owner == 'team') {
                 $sql .= " AND " . Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id);
             }
         }
     }
     if ($chefServerId) {
         $sql .= " AND f.id IN (\n                SELECT fr.farmid\n                FROM farm_roles fr\n                INNER JOIN farm_role_settings frs1 ON fr.id = frs1.farm_roleid AND frs1.name = ? AND frs1.value = ?\n                INNER JOIN farm_role_settings frs2 ON fr.id = frs2.farm_roleid AND frs2.name = ? AND frs2.value = ?\n            )";
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_SERVER_ID;
         $args[] = $chefServerId;
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_BOOTSTRAP;
         $args[] = 1;
     }
     if ($this->getContainer()->analytics->enabled && $projectId) {
         $sql .= " AND EXISTS (\n                SELECT 1 FROM farm_settings\n                WHERE farm_settings.farmid = f.id\n                AND farm_settings.name = " . $this->db->qstr(Entity\FarmSetting::PROJECT_ID) . "\n                AND farm_settings.value = ?) ";
         $args[] = $projectId;
     }
     $sql .= " GROUP BY {$f->columnId('f')}";
     $response = $this->buildResponseFromSql2($sql, array('id', 'name', 'dtadded', 'ownerEmail', 'status'), array('f.name', 'f.id', 'f.comments'), $args);
     foreach ($response["data"] as &$r) {
         $farm = new Entity\Farm();
         $farm->load($r);
         $row = get_object_vars($farm);
         $row['ownerEmail'] = $r['ownerEmail'];
         $row['farmTeams'] = $r['farmTeams'];
         $row['behaviors'] = $r['behaviors'];
         $row['rolesCnt'] = $r['rolesCnt'];
         $row['zonesCnt'] = $r['zonesCnt'];
         $row['alertsCnt'] = $r['alertsCnt'];
         $row['runningServers'] = $r['runningServers'];
         $row['suspendedServers'] = $r['suspendedServers'];
         $row['nonRunningServers'] = $r['nonRunningServers'];
         $row['added'] = Scalr_Util_DateTime::convertTz($farm->added);
         $row['lock'] = $farm->settings[Entity\FarmSetting::LOCK];
         if ($row['lock']) {
             try {
                 $farm->checkLocked();
             } catch (\Scalr\Exception\LockedException $e) {
                 $row['lockComment'] = $e->getMessage();
             }
         }
         if ($leaseStatus && $farm->settings[Entity\FarmSetting::LEASE_STATUS]) {
             $row['lease'] = $farm->settings[Entity\FarmSetting::LEASE_NOTIFICATION_SEND] ? 'Expire' : $farm->settings[Entity\FarmSetting::LEASE_STATUS];
             if ($row['lease'] == 'Expire') {
                 $dt = new DateTime();
                 $td = new DateTime($farm->settings[Entity\FarmSetting::LEASE_TERMINATE_DATE]);
                 $days = 0;
                 $hours = 1;
                 $interval = $dt->diff($td);
                 if ($interval) {
                     $days = $interval->days;
                     $hours = $interval->h ? $interval->h : 1;
                 }
                 $row['leaseMessage'] = sprintf('Your farm lease is about to expire in %d %s, after which this farm will be terminated', $days ? $days : $hours, $days ? $days > 1 ? 'days' : 'day' : ($hours > 1 ? 'hours' : 'hour'));
             }
         }
         $behaviors = explode(',', $row['behaviors']);
         $row["havemysqlrole"] = in_array(ROLE_BEHAVIORS::MYSQL, $behaviors);
         $row["havemysql2role"] = in_array(ROLE_BEHAVIORS::MYSQL2, $behaviors);
         $row["havepgrole"] = in_array(ROLE_BEHAVIORS::POSTGRESQL, $behaviors);
         $row["haveredisrole"] = in_array(ROLE_BEHAVIORS::REDIS, $behaviors);
         $row["haverabbitmqrole"] = in_array(ROLE_BEHAVIORS::RABBITMQ, $behaviors);
         $row["havemongodbrole"] = in_array(ROLE_BEHAVIORS::MONGODB, $behaviors);
         $row["haveperconarole"] = in_array(ROLE_BEHAVIORS::PERCONA, $behaviors);
         $row["havemariadbrole"] = in_array(ROLE_BEHAVIORS::MARIADB, $behaviors);
         $row['statusTxt'] = Entity\Farm::getStatusName($farm->status);
         if ($row['status'] == Entity\Farm::STATUS_RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find([['farmId' => $farm->id], ['farmRoleId' => null]]) as $shortcut) {
                 /* @var $shortcut \Scalr\Model\Entity\ScriptShortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
         $row['farmOwnerIdPerm'] = $farm->ownerId && $this->getUser()->id == $farm->ownerId;
         $row['farmTeamIdPerm'] = !!$r['farmTeamIdPerm'];
         $r = $row;
     }
     $this->response->data($response);
 }
Beispiel #4
0
 /**
  * @param   string  $query
  * @throws  Scalr_Exception_Core
  */
 public function xSearchResourcesAction($query)
 {
     if (trim($query) == '') {
         $this->response->data(['data' => []]);
         return;
     }
     $environments = $this->request->getScope() == ScopeInterface::SCOPE_ACCOUNT ? array_map(function ($r) {
         return $r['id'];
     }, $this->user->getEnvironments()) : [$this->getEnvironmentId()];
     $f = new Entity\Farm();
     $s = new Entity\Server();
     $fr = new Entity\FarmRole();
     $ft = new Entity\FarmTeam();
     $e = new Entity\Account\Environment();
     $at = new Entity\Account\Team();
     $sp = new Entity\Server\Property();
     $farmSql = [];
     $serverSql = [];
     $queryEnc = "%{$query}%";
     foreach ($environments as $envId) {
         $acl = $this->user->getAclRolesByEnvironment($envId);
         $isTermporaryServerPerm = $acl->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_BUILD) || $acl->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_IMPORT);
         if ($acl->isAllowed(Acl::RESOURCE_FARMS)) {
             $farmSql[] = "{$f->columnEnvId('f')} = {$envId}";
             if ($isTermporaryServerPerm) {
                 $serverSql[] = "{$s->columnEnvId} = {$envId}";
             } else {
                 $serverSql[] = "{$s->columnEnvId} = {$envId} AND {$s->columnFarmId} IS NOT NULL";
             }
         } else {
             $q = [];
             if ($acl->isAllowed(Acl::RESOURCE_TEAM_FARMS)) {
                 $q[] = Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id);
             }
             if ($acl->isAllowed(Acl::RESOURCE_OWN_FARMS)) {
                 $q[] = "{$f->columnOwnerId('f')} = '" . intval($this->getUser()->id) . "'";
             }
             if (count($q)) {
                 $farmSql[] = "{$f->columnEnvId('f')} = {$envId} AND (" . join(" OR ", $q) . ")";
             }
             if ($isTermporaryServerPerm) {
                 $q[] = "{$s->columnStatus} IN ('" . Entity\Server::STATUS_IMPORTING . "', '" . Entity\Server::STATUS_TEMPORARY . "') AND {$s->columnFarmId} IS NULL";
             }
             if (count($q)) {
                 $serverSql[] = "{$s->columnEnvId} = {$envId} AND (" . join(" OR ", $q) . ")";
             }
         }
     }
     $farms = [];
     if (count($farmSql)) {
         $farmStmt = $this->db->Execute("\n                SELECT {$f->columnId('f')} AS id, {$f->columnName('f')} AS name, {$f->columnEnvId('f')} AS envId, {$f->columnStatus('f')} AS status,\n                {$f->columnAdded('f')} AS added, {$f->columnCreatedByEmail('f')} AS createdByEmail, {$e->columnName} AS `envName`,\n                GROUP_CONCAT({$at->columnName} SEPARATOR ', ') AS teamName\n                FROM {$f->table('f')}\n                LEFT JOIN {$e->table()} ON {$f->columnEnvId('f')} = {$e->columnId}\n                LEFT JOIN {$ft->table()} ON {$ft->columnFarmId} = {$f->columnId('f')}\n                LEFT JOIN {$at->table()} ON {$at->columnId} = {$ft->columnTeamId}\n                WHERE ({$f->columnName('f')} LIKE ? OR {$f->columnId('f')} = ?) AND (" . join(" OR ", $farmSql) . ")\n                GROUP BY {$f->columnId('f')}", [$queryEnc, $query]);
         $names = ['id' => 'ID', 'name' => 'Name'];
         while ($farm = $farmStmt->FetchRow()) {
             $farm['status'] = Entity\Farm::getStatusName($farm['status']);
             $farm['added'] = Scalr_Util_DateTime::convertTz($farm['added'], 'M j, Y H:i');
             if (stristr($farm['name'], $query)) {
                 $m = 'name';
             } else {
                 $m = 'id';
             }
             $farms[] = ['entityName' => 'farm', 'envId' => $farm['envId'], 'envName' => $farm['envName'], 'matchField' => $names[$m], 'matchValue' => $farm[$m], 'data' => $farm];
         }
     }
     $servers = [];
     if (count($serverSql)) {
         $serverStmt = $this->db->Execute("\n                SELECT {$s->columnServerId} AS serverId, {$s->columnFarmId} AS farmId, {$s->columnFarmRoleId} AS farmRoleId,\n                {$s->columnEnvId} AS envId, {$s->columnPlatform} AS platform, {$s->columnInstanceTypeName} AS instanceTypeName,\n                {$s->columnStatus} AS status, {$s->columnCloudLocation} AS cloudLocation, {$s->columnRemoteIp} AS publicIp,\n                {$s->columnLocalIp} AS privateIp, {$s->columnAdded} AS added, {$f->columnName('f')} AS farmName,\n                {$fr->columnAlias} AS farmRoleName, {$e->columnName} AS `envName`, {$fr->columnRoleId} AS roleId,\n                {$sp->columnValue('sp1', 'hostname')}\n                FROM {$s->table()}\n                LEFT JOIN {$f->table('f')} ON {$f->columnId('f')} = {$s->columnFarmId}\n                LEFT JOIN {$fr->table()} ON {$fr->columnId} = {$s->columnFarmRoleId}\n                LEFT JOIN {$e->table()} ON {$e->columnId} = {$s->columnEnvId}\n                LEFT JOIN {$sp->table('sp1')} ON {$sp->columnServerId('sp1')} = {$s->columnServerId} AND {$sp->columnName('sp1')} = ?\n                WHERE ({$s->columnRemoteIp} LIKE ? OR {$s->columnLocalIp} LIKE ? OR {$sp->columnValue('sp1')} LIKE ?) AND (" . join(" OR ", $serverSql) . ")\n                GROUP BY {$s->columnServerId}", [Scalr_Role_Behavior::SERVER_BASE_HOSTNAME, $queryEnc, $queryEnc, $queryEnc]);
         $names = ['publicIp' => 'Public IP', 'privateIp' => 'Private IP', 'hostname' => 'Hostname'];
         while ($server = $serverStmt->FetchRow()) {
             $server['added'] = Scalr_Util_DateTime::convertTz($server['added'], 'M j, Y H:i');
             if (strstr($server['publicIp'], $query)) {
                 $m = 'publicIp';
             } else {
                 if (strstr($server['privateIp'], $query)) {
                     $m = 'privateIp';
                 } else {
                     $m = 'hostname';
                 }
             }
             $servers[] = ['entityName' => 'server', 'envId' => $server['envId'], 'envName' => $server['envName'], 'matchField' => $names[$m], 'matchValue' => $server[$m], 'data' => $server];
         }
     }
     $this->response->data(['data' => array_merge($farms, $servers)]);
 }