Search in sources :

Example 1 with SetView

use of com.google.common.collect.Sets.SetView in project presto by prestodb.

the class DiscoveryNodeManager method refreshNodesInternal.

private synchronized void refreshNodesInternal() {
    // This is currently a blacklist.
    // TODO: make it a whitelist (a failure-detecting service selector) and maybe build in support for injecting this in airlift
    Set<ServiceDescriptor> services = serviceSelector.selectAllServices().stream().filter(service -> !failureDetector.getFailed().contains(service)).filter(service -> !nodeStatusService.isPresent() || nodeStatusService.get().isAllowed(service.getLocation()) || isCoordinator(service) || isResourceManager(service)).collect(toImmutableSet());
    ImmutableSet.Builder<InternalNode> activeNodesBuilder = ImmutableSortedSet.orderedBy(comparing(InternalNode::getNodeIdentifier));
    ImmutableSet.Builder<InternalNode> inactiveNodesBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<InternalNode> shuttingDownNodesBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<InternalNode> coordinatorsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<InternalNode> resourceManagersBuilder = ImmutableSet.builder();
    ImmutableSetMultimap.Builder<ConnectorId, InternalNode> byConnectorIdBuilder = ImmutableSetMultimap.builder();
    Map<String, InternalNode> nodes = new HashMap<>();
    SetMultimap<String, ConnectorId> connectorIdsByNodeId = HashMultimap.create();
    // For a given connectorId, sort the nodes based on their nodeIdentifier
    byConnectorIdBuilder.orderValuesBy(comparing(InternalNode::getNodeIdentifier));
    if (isMemoizeDeadNodesEnabled && this.nodes != null) {
        nodes.putAll(this.nodes);
    }
    if (isMemoizeDeadNodesEnabled && this.connectorIdsByNodeId != null) {
        connectorIdsByNodeId.putAll(this.connectorIdsByNodeId);
    }
    for (ServiceDescriptor service : services) {
        URI uri = getHttpUri(service, httpsRequired);
        OptionalInt thriftPort = getThriftServerPort(service);
        NodeVersion nodeVersion = getNodeVersion(service);
        // Currently, a node may have the roles of both a coordinator and a worker.  In the future, a resource manager may also
        // take the form of a coordinator, hence these flags are not exclusive.
        boolean coordinator = isCoordinator(service);
        boolean resourceManager = isResourceManager(service);
        if (uri != null && nodeVersion != null) {
            InternalNode node = new InternalNode(service.getNodeId(), uri, thriftPort, nodeVersion, coordinator, resourceManager, ALIVE);
            NodeState nodeState = getNodeState(node);
            switch(nodeState) {
                case ACTIVE:
                    activeNodesBuilder.add(node);
                    if (coordinator) {
                        coordinatorsBuilder.add(node);
                    }
                    if (resourceManager) {
                        resourceManagersBuilder.add(node);
                    }
                    nodes.put(node.getNodeIdentifier(), node);
                    // record available active nodes organized by connector id
                    String connectorIds = service.getProperties().get("connectorIds");
                    if (connectorIds != null) {
                        connectorIds = connectorIds.toLowerCase(ENGLISH);
                        for (String id : CONNECTOR_ID_SPLITTER.split(connectorIds)) {
                            ConnectorId connectorId = new ConnectorId(id);
                            byConnectorIdBuilder.put(connectorId, node);
                            connectorIdsByNodeId.put(node.getNodeIdentifier(), connectorId);
                        }
                    }
                    // always add system connector
                    byConnectorIdBuilder.put(new ConnectorId(GlobalSystemConnector.NAME), node);
                    break;
                case INACTIVE:
                    inactiveNodesBuilder.add(node);
                    break;
                case SHUTTING_DOWN:
                    shuttingDownNodesBuilder.add(node);
                    break;
                default:
                    log.error("Unknown state %s for node %s", nodeState, node);
            }
        }
    }
    if (allNodes != null) {
        // log node that are no longer active (but not shutting down)
        SetView<InternalNode> missingNodes = difference(allNodes.getActiveNodes(), Sets.union(activeNodesBuilder.build(), shuttingDownNodesBuilder.build()));
        for (InternalNode missingNode : missingNodes) {
            log.info("Previously active node is missing: %s (last seen at %s)", missingNode.getNodeIdentifier(), missingNode.getHost());
        }
    }
    // nodes by connector id changes anytime a node adds or removes a connector (note: this is not part of the listener system)
    activeNodesByConnectorId = byConnectorIdBuilder.build();
    if (isMemoizeDeadNodesEnabled) {
        SetView<String> deadNodeIds = difference(nodes.keySet(), activeNodesBuilder.build().stream().map(InternalNode::getNodeIdentifier).collect(toImmutableSet()));
        for (String nodeId : deadNodeIds) {
            InternalNode deadNode = nodes.get(nodeId);
            Set<ConnectorId> deadNodeConnectorIds = connectorIdsByNodeId.get(nodeId);
            for (ConnectorId id : deadNodeConnectorIds) {
                byConnectorIdBuilder.put(id, new InternalNode(deadNode.getNodeIdentifier(), deadNode.getInternalUri(), deadNode.getThriftPort(), deadNode.getNodeVersion(), deadNode.isCoordinator(), deadNode.isResourceManager(), DEAD));
            }
        }
    }
    this.nodes = ImmutableMap.copyOf(nodes);
    this.nodesByConnectorId = byConnectorIdBuilder.build();
    this.connectorIdsByNodeId = ImmutableSetMultimap.copyOf(connectorIdsByNodeId);
    AllNodes allNodes = new AllNodes(activeNodesBuilder.build(), inactiveNodesBuilder.build(), shuttingDownNodesBuilder.build(), coordinatorsBuilder.build(), resourceManagersBuilder.build());
    // only update if all nodes actually changed (note: this does not include the connectors registered with the nodes)
    if (!allNodes.equals(this.allNodes)) {
        // assign allNodes to a local variable for use in the callback below
        this.allNodes = allNodes;
        coordinators = coordinatorsBuilder.build();
        resourceManagers = resourceManagersBuilder.build();
        // notify listeners
        List<Consumer<AllNodes>> listeners = ImmutableList.copyOf(this.listeners);
        nodeStateEventExecutor.submit(() -> listeners.forEach(listener -> listener.accept(allNodes)));
    }
}
Also used : ServiceType(com.facebook.airlift.discovery.client.ServiceType) URISyntaxException(java.net.URISyntaxException) DEAD(com.facebook.presto.metadata.InternalNode.NodeStatus.DEAD) NodeVersion(com.facebook.presto.client.NodeVersion) ACTIVE(com.facebook.presto.spi.NodeState.ACTIVE) PreDestroy(javax.annotation.PreDestroy) Sets.difference(com.google.common.collect.Sets.difference) Executors.newSingleThreadScheduledExecutor(java.util.concurrent.Executors.newSingleThreadScheduledExecutor) HashMultimap(com.google.common.collect.HashMultimap) GlobalSystemConnector(com.facebook.presto.connector.system.GlobalSystemConnector) Map(java.util.Map) ServiceSelector(com.facebook.airlift.discovery.client.ServiceSelector) URI(java.net.URI) Splitter(com.google.common.base.Splitter) ENGLISH(java.util.Locale.ENGLISH) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) CommunicationProtocol(com.facebook.presto.server.InternalCommunicationConfig.CommunicationProtocol) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) NodeState(com.facebook.presto.spi.NodeState) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ConnectorId(com.facebook.presto.spi.ConnectorId) INACTIVE(com.facebook.presto.spi.NodeState.INACTIVE) NodeStatusService(com.facebook.presto.statusservice.NodeStatusService) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) Logger(com.facebook.airlift.log.Logger) NodeInfo(com.facebook.airlift.node.NodeInfo) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Comparator.comparing(java.util.Comparator.comparing) ExecutorService(java.util.concurrent.ExecutorService) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Threads.threadsNamed(com.facebook.airlift.concurrent.Threads.threadsNamed) SHUTTING_DOWN(com.facebook.presto.spi.NodeState.SHUTTING_DOWN) InternalCommunicationConfig(com.facebook.presto.server.InternalCommunicationConfig) ALIVE(com.facebook.presto.metadata.InternalNode.NodeStatus.ALIVE) SetView(com.google.common.collect.Sets.SetView) DriftClient(com.facebook.drift.client.DriftClient) HttpClient(com.facebook.airlift.http.client.HttpClient) SetMultimap(com.google.common.collect.SetMultimap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) HttpUriBuilder.uriBuilderFrom(com.facebook.airlift.http.client.HttpUriBuilder.uriBuilderFrom) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) FailureDetector(com.facebook.presto.failureDetector.FailureDetector) ThriftServerInfoClient(com.facebook.presto.server.thrift.ThriftServerInfoClient) NodeState(com.facebook.presto.spi.NodeState) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) URI(java.net.URI) NodeVersion(com.facebook.presto.client.NodeVersion) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Consumer(java.util.function.Consumer) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) ConnectorId(com.facebook.presto.spi.ConnectorId)

Example 2 with SetView

use of com.google.common.collect.Sets.SetView in project snow-owl by b2ihealthcare.

the class CommitInfoSearchRequest method addSecurityFilter.

private void addSecurityFilter(final ExpressionBuilder builder, RepositoryContext context) {
    final User user = context.service(User.class);
    if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) {
        return;
    }
    final List<Permission> readPermissions = user.getPermissions().stream().filter(p -> Permission.ALL.equals(p.getOperation()) || Permission.OPERATION_BROWSE.equals(p.getOperation())).collect(Collectors.toList());
    final Set<String> exactResourceIds = readPermissions.stream().flatMap(p -> p.getResources().stream()).filter(resource -> !resource.endsWith("*")).collect(Collectors.toSet());
    final Set<String> resourceIdPrefixes = readPermissions.stream().flatMap(p -> p.getResources().stream()).filter(resource -> isWildCardResource(resource)).map(resource -> resource.substring(0, resource.length() - 1)).collect(Collectors.toSet());
    SetView<String> resourceIds = Sets.union(exactResourceIds, resourceIdPrefixes);
    ExpressionBuilder branchFilter = Expressions.builder();
    ResourceRequests.prepareSearch().filterByIds(resourceIds).setLimit(resourceIds.size()).setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE).buildAsync().getRequest().execute(context).stream().filter(TerminologyResource.class::isInstance).map(TerminologyResource.class::cast).forEach(r -> {
        if (resourceIdPrefixes.contains(r.getId())) {
            final String branchPattern = String.format("%s(/[a-zA-Z0-9.~_\\-]{1,%d})?", r.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH);
            branchFilter.should(regexp(BRANCH, branchPattern));
        }
    });
    builder.filter(branchFilter.build());
}
Also used : TerminologyResource(com.b2international.snowowl.core.TerminologyResource) Expressions(com.b2international.index.revision.Commit.Expressions) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) ResourceRequests(com.b2international.snowowl.core.request.ResourceRequests) Hits(com.b2international.index.Hits) DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH(com.b2international.index.revision.RevisionBranch.DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH) Collection(java.util.Collection) Set(java.util.Set) Commit(com.b2international.index.revision.Commit) SetView(com.google.common.collect.Sets.SetView) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) ResourceDocument(com.b2international.snowowl.core.internal.ResourceDocument) Expressions.regexp(com.b2international.index.query.Expressions.regexp) List(java.util.List) SearchIndexResourceRequest(com.b2international.snowowl.core.request.SearchIndexResourceRequest) Expressions(com.b2international.index.query.Expressions) Permission.isWildCardResource(com.b2international.snowowl.core.identity.Permission.isWildCardResource) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder) Expression(com.b2international.index.query.Expression) Permission(com.b2international.snowowl.core.identity.Permission) User(com.b2international.snowowl.core.identity.User) BRANCH(com.b2international.index.revision.Commit.Fields.BRANCH) User(com.b2international.snowowl.core.identity.User) Permission(com.b2international.snowowl.core.identity.Permission) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder)

Example 3 with SetView

use of com.google.common.collect.Sets.SetView in project molgenis by molgenis.

the class RestController method retrieveEntityCollection.

/**
 * Does a rsql/fiql query, returns the result as csv
 * <p>
 * Parameters:
 * <p>
 * q: the query
 * <p>
 * attributes: the attributes to return, if not specified returns all attributes
 * <p>
 * start: the index of the first row, default 0
 * <p>
 * num: the number of results to return, default 100, max 10000
 * <p>
 * <p>
 * Example: /api/v1/csv/person?q=firstName==Piet&attributes=firstName,lastName&start=10&num=100
 */
@GetMapping(value = "/csv/{entityTypeId}", produces = "text/csv")
@ResponseBody
public EntityCollection retrieveEntityCollection(@PathVariable("entityTypeId") String entityTypeId, @RequestParam(value = "attributes", required = false) String[] attributes, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final Set<String> attributesSet = toAttributeSet(attributes);
    EntityType meta;
    Iterable<Entity> entities;
    try {
        meta = dataService.getEntityType(entityTypeId);
        Query<Entity> q = new QueryStringParser(meta, molgenisRSQL).parseQueryString(req.getParameterMap());
        String[] sortAttributeArray = req.getParameterMap().get("sortColumn");
        if (sortAttributeArray != null && sortAttributeArray.length == 1 && StringUtils.isNotEmpty(sortAttributeArray[0])) {
            String sortAttribute = sortAttributeArray[0];
            String[] sortOrderArray = req.getParameterMap().get("sortOrder");
            Sort.Direction order = Sort.Direction.ASC;
            if (sortOrderArray != null && sortOrderArray.length == 1 && StringUtils.isNotEmpty(sortOrderArray[0])) {
                String sortOrder = sortOrderArray[0];
                switch(sortOrder) {
                    case "ASC":
                        order = Sort.Direction.ASC;
                        break;
                    case "DESC":
                        order = Sort.Direction.DESC;
                        break;
                    default:
                        throw new RuntimeException("unknown sort order");
                }
            }
            q.sort().on(sortAttribute, order);
        }
        if (q.getPageSize() == 0) {
            q.pageSize(EntityCollectionRequest.DEFAULT_ROW_COUNT);
        }
        if (q.getPageSize() > EntityCollectionRequest.MAX_ROWS) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Num exceeded the maximum of " + EntityCollectionRequest.MAX_ROWS + " rows");
            return null;
        }
        entities = () -> dataService.findAll(entityTypeId, q).iterator();
    } catch (ConversionFailedException | RSQLParserException | UnknownAttributeException | IllegalArgumentException | UnsupportedOperationException | UnknownEntityException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return null;
    } catch (MolgenisDataAccessException e) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }
    // Check attribute names
    Iterable<String> attributesIterable = Iterables.transform(meta.getAtomicAttributes(), attribute -> attribute.getName().toLowerCase());
    if (attributesSet != null) {
        SetView<String> diff = Sets.difference(attributesSet, Sets.newHashSet(attributesIterable));
        if (!diff.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown attributes " + diff);
            return null;
        }
    }
    attributesIterable = Iterables.transform(meta.getAtomicAttributes(), Attribute::getName);
    if (attributesSet != null) {
        attributesIterable = Iterables.filter(attributesIterable, attribute -> attributesSet.contains(attribute.toLowerCase()));
    }
    return new DefaultEntityCollection(entities, attributesIterable);
}
Also used : UnknownTokenException(org.molgenis.security.core.token.UnknownTokenException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) RestService(org.molgenis.data.rest.service.RestService) ErrorMessageResponse(org.molgenis.web.ErrorMessageResponse) LoggerFactory(org.slf4j.LoggerFactory) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) RunAsSystemAspect.runAsSystem(org.molgenis.security.core.runas.RunAsSystemAspect.runAsSystem) ENFORCED(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationSetting.ENFORCED) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(org.molgenis.data.meta.model.Attribute) AuthenticationSettings(org.molgenis.security.settings.AuthenticationSettings) Valid(javax.validation.Valid) User(org.molgenis.data.security.auth.User) Matcher(java.util.regex.Matcher) ObjectError(org.springframework.validation.ObjectError) USER(org.molgenis.data.security.auth.UserMetaData.USER) AuthenticationException(org.springframework.security.core.AuthenticationException) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) DefaultEntityCollection(org.molgenis.data.support.DefaultEntityCollection) org.molgenis.data(org.molgenis.data) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) UserAccountService(org.molgenis.security.user.UserAccountService) ConversionException(org.springframework.core.convert.ConversionException) Instant(java.time.Instant) EntityType(org.molgenis.data.meta.model.EntityType) Sets(com.google.common.collect.Sets) UserPermissionEvaluator(org.molgenis.security.core.UserPermissionEvaluator) LocalDate(java.time.LocalDate) MolgenisRSQL(org.molgenis.core.ui.data.rsql.MolgenisRSQL) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Entry(java.util.Map.Entry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Pattern(java.util.regex.Pattern) Authentication(org.springframework.security.core.Authentication) UserMetaData(org.molgenis.data.security.auth.UserMetaData) Iterables(com.google.common.collect.Iterables) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) java.util(java.util) ENABLED(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationSetting.ENABLED) TokenParam(org.molgenis.security.token.TokenParam) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) QueryImpl(org.molgenis.data.support.QueryImpl) RSQLParserException(cz.jirutka.rsql.parser.RSQLParserException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) EntityUtils.getTypedValue(org.molgenis.data.util.EntityUtils.getTypedValue) Objects.requireNonNull(java.util.Objects.requireNonNull) Href(org.molgenis.core.ui.data.support.Href) ATTRIBUTE_META_DATA(org.molgenis.data.meta.model.AttributeMetadata.ATTRIBUTE_META_DATA) BASE_URI(org.molgenis.data.rest.RestController.BASE_URI) AttributeType(org.molgenis.data.meta.AttributeType) Logger(org.slf4j.Logger) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) SetView(com.google.common.collect.Sets.SetView) IOException(java.io.IOException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) ErrorMessage(org.molgenis.web.ErrorMessageResponse.ErrorMessage) HttpStatus(org.springframework.http.HttpStatus) TokenService(org.molgenis.security.core.token.TokenService) MultipartFile(org.springframework.web.multipart.MultipartFile) Transactional(org.springframework.transaction.annotation.Transactional) DefaultEntityCollection(org.molgenis.data.support.DefaultEntityCollection) RSQLParserException(cz.jirutka.rsql.parser.RSQLParserException) EntityType(org.molgenis.data.meta.model.EntityType) ConversionFailedException(org.springframework.core.convert.ConversionFailedException)

Aggregations

Sets (com.google.common.collect.Sets)3 SetView (com.google.common.collect.Sets.SetView)3 List (java.util.List)2 Set (java.util.Set)2 Hits (com.b2international.index.Hits)1 Expression (com.b2international.index.query.Expression)1 Expressions (com.b2international.index.query.Expressions)1 ExpressionBuilder (com.b2international.index.query.Expressions.ExpressionBuilder)1 Expressions.regexp (com.b2international.index.query.Expressions.regexp)1 Commit (com.b2international.index.revision.Commit)1 Expressions (com.b2international.index.revision.Commit.Expressions)1 BRANCH (com.b2international.index.revision.Commit.Fields.BRANCH)1 DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH (com.b2international.index.revision.RevisionBranch.DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH)1 TerminologyResource (com.b2international.snowowl.core.TerminologyResource)1 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)1 Permission (com.b2international.snowowl.core.identity.Permission)1 Permission.isWildCardResource (com.b2international.snowowl.core.identity.Permission.isWildCardResource)1 User (com.b2international.snowowl.core.identity.User)1 ResourceDocument (com.b2international.snowowl.core.internal.ResourceDocument)1 ResourceRequests (com.b2international.snowowl.core.request.ResourceRequests)1