Search in sources :

Example 1 with Queue

use of java.util.Queue in project che by eclipse.

the class CheEnvironmentEngine method startEnvironmentQueue.

/**
     * Starts all machine from machine queue of environment.
     */
private void startEnvironmentQueue(String namespace, String workspaceId, String devMachineName, String networkId, boolean recover, MachineStartedHandler startedHandler) throws ServerException, EnvironmentException {
    // Starting all machines in environment one by one by getting configs
    // from the corresponding starting queue.
    // Config will be null only if there are no machines left in the queue
    String envName;
    MessageConsumer<MachineLogMessage> envLogger;
    String creator = EnvironmentContext.getCurrent().getSubject().getUserId();
    try (@SuppressWarnings("unused") Unlocker u = stripedLocks.readLock(workspaceId)) {
        EnvironmentHolder environmentHolder = environments.get(workspaceId);
        if (environmentHolder == null) {
            throw new ServerException("Environment start is interrupted.");
        }
        envName = environmentHolder.name;
        envLogger = environmentHolder.logger;
    }
    try {
        machineProvider.createNetwork(networkId);
        String machineName = queuePeekOrFail(workspaceId);
        while (machineName != null) {
            boolean isDev = devMachineName.equals(machineName);
            // Environment start is failed when any machine start is failed, so if any error
            // occurs during machine creation then environment start fail is reported and
            // start resources such as queue and descriptor must be cleaned up
            CheServiceImpl service;
            @Nullable ExtendedMachine extendedMachine;
            try (@SuppressWarnings("unused") Unlocker u = stripedLocks.readLock(workspaceId)) {
                EnvironmentHolder environmentHolder = environments.get(workspaceId);
                if (environmentHolder == null) {
                    throw new ServerException("Environment start is interrupted.");
                }
                service = environmentHolder.environment.getServices().get(machineName);
                extendedMachine = environmentHolder.environmentConfig.getMachines().get(machineName);
            }
            // should not happen
            if (service == null) {
                LOG.error("Start of machine with name {} in workspace {} failed. Machine not found in start queue", machineName, workspaceId);
                throw new ServerException(format("Environment of workspace with ID '%s' failed due to internal error", workspaceId));
            }
            final String finalMachineName = machineName;
            // needed to reuse startInstance method and
            // create machine instances by different implementation-specific providers
            MachineStarter machineStarter = (machineLogger, machineSource) -> {
                CheServiceImpl serviceWithNormalizedSource = normalizeServiceSource(service, machineSource);
                return machineProvider.startService(namespace, workspaceId, envName, finalMachineName, isDev, networkId, serviceWithNormalizedSource, machineLogger);
            };
            MachineImpl machine = MachineImpl.builder().setConfig(MachineConfigImpl.builder().setDev(isDev).setLimits(new MachineLimitsImpl(bytesToMB(service.getMemLimit()))).setType("docker").setName(machineName).setEnvVariables(service.getEnvironment()).build()).setId(service.getId()).setWorkspaceId(workspaceId).setStatus(MachineStatus.CREATING).setEnvName(envName).setOwner(creator).build();
            checkInterruption(workspaceId, envName);
            Instance instance = startInstance(recover, envLogger, machine, machineStarter);
            checkInterruption(workspaceId, envName);
            startedHandler.started(instance, extendedMachine);
            checkInterruption(workspaceId, envName);
            // Machine destroying is an expensive operation which must be
            // performed outside of the lock, this section checks if
            // the environment wasn't stopped while it is starting and sets
            // polled flag to true if the environment wasn't stopped.
            // Also polls the proceeded machine configuration from the queue
            boolean queuePolled = false;
            try (@SuppressWarnings("unused") Unlocker u = stripedLocks.writeLock(workspaceId)) {
                ensurePreDestroyIsNotExecuted();
                EnvironmentHolder environmentHolder = environments.get(workspaceId);
                if (environmentHolder != null) {
                    final Queue<String> queue = environmentHolder.startQueue;
                    if (queue != null) {
                        queue.poll();
                        queuePolled = true;
                    }
                }
            }
            // must be destroyed
            if (!queuePolled) {
                try {
                    eventService.publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.DESTROYING).withDev(isDev).withMachineName(machineName).withMachineId(instance.getId()).withWorkspaceId(workspaceId));
                    instance.destroy();
                    removeMachine(workspaceId, instance.getId());
                    eventService.publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.DESTROYED).withDev(isDev).withMachineName(machineName).withMachineId(instance.getId()).withWorkspaceId(workspaceId));
                } catch (MachineException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
                throw new ServerException("Workspace '" + workspaceId + "' start interrupted. Workspace stopped before all its machines started");
            }
            machineName = queuePeekOrFail(workspaceId);
        }
    } catch (RuntimeException | ServerException | EnvironmentStartInterruptedException e) {
        boolean interrupted = Thread.interrupted();
        EnvironmentHolder env;
        try (@SuppressWarnings("unused") Unlocker u = stripedLocks.writeLock(workspaceId)) {
            env = environments.remove(workspaceId);
        }
        try {
            destroyEnvironment(env.networkId, env.machines);
        } catch (Exception remEx) {
            LOG.error(remEx.getLocalizedMessage(), remEx);
        }
        if (interrupted) {
            throw new EnvironmentStartInterruptedException(workspaceId, envName);
        }
        try {
            throw e;
        } catch (ServerException | EnvironmentStartInterruptedException rethrow) {
            throw rethrow;
        } catch (Exception wrap) {
            throw new ServerException(wrap.getMessage(), wrap);
        }
    }
}
Also used : MachineStatusEvent(org.eclipse.che.api.machine.shared.dto.event.MachineStatusEvent) MachineStatus(org.eclipse.che.api.core.model.machine.MachineStatus) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) AgentImpl(org.eclipse.che.api.agent.shared.model.impl.AgentImpl) StripedLocks(org.eclipse.che.commons.lang.concurrent.StripedLocks) WorkspaceSharedPool(org.eclipse.che.api.workspace.server.WorkspaceSharedPool) AgentException(org.eclipse.che.api.agent.server.exception.AgentException) Utils.getDevMachineName(org.eclipse.che.api.workspace.shared.Utils.getDevMachineName) PreDestroy(javax.annotation.PreDestroy) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) Map(java.util.Map) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) MessageConsumer(org.eclipse.che.api.core.util.MessageConsumer) CheServiceBuildContextImpl(org.eclipse.che.api.environment.server.model.CheServiceBuildContextImpl) NameGenerator(org.eclipse.che.commons.lang.NameGenerator) EventService(org.eclipse.che.api.core.notification.EventService) ConcurrentCompositeLineConsumer(org.eclipse.che.api.core.util.lineconsumer.ConcurrentCompositeLineConsumer) EventSubscriber(org.eclipse.che.api.core.notification.EventSubscriber) Collections.emptyList(java.util.Collections.emptyList) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) MachineSource(org.eclipse.che.api.core.model.machine.MachineSource) MachineLogMessageImpl(org.eclipse.che.api.machine.server.model.impl.MachineLogMessageImpl) Nullable(org.eclipse.che.commons.annotation.Nullable) String.format(java.lang.String.format) IoUtil(org.eclipse.che.commons.lang.IoUtil) Objects(java.util.Objects) EnvironmentException(org.eclipse.che.api.environment.server.exception.EnvironmentException) List(java.util.List) Environment(org.eclipse.che.api.core.model.workspace.Environment) PostConstruct(javax.annotation.PostConstruct) ServerConfImpl(org.eclipse.che.api.machine.server.model.impl.ServerConfImpl) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) AgentRegistry(org.eclipse.che.api.agent.server.AgentRegistry) ConcurrentFileLineConsumer(org.eclipse.che.api.core.util.lineconsumer.ConcurrentFileLineConsumer) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) MachineInstanceProviders(org.eclipse.che.api.machine.server.MachineInstanceProviders) AgentKeyImpl(org.eclipse.che.api.agent.shared.model.impl.AgentKeyImpl) Size(org.eclipse.che.commons.lang.Size) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) AbstractLineConsumer(org.eclipse.che.api.core.util.AbstractLineConsumer) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) Singleton(javax.inject.Singleton) OOM(org.eclipse.che.api.machine.server.event.InstanceStateEvent.Type.OOM) CheServicesEnvironmentImpl(org.eclipse.che.api.environment.server.model.CheServicesEnvironmentImpl) SnapshotImpl(org.eclipse.che.api.machine.server.model.impl.SnapshotImpl) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) InstanceProvider(org.eclipse.che.api.machine.server.spi.InstanceProvider) ApiException(org.eclipse.che.api.core.ApiException) ServerConf2(org.eclipse.che.api.core.model.workspace.ServerConf2) ConflictException(org.eclipse.che.api.core.ConflictException) InstanceStateEvent(org.eclipse.che.api.machine.server.event.InstanceStateEvent) Named(javax.inject.Named) Instance(org.eclipse.che.api.machine.server.spi.Instance) SnapshotDao(org.eclipse.che.api.machine.server.spi.SnapshotDao) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) Logger(org.slf4j.Logger) ExtendedMachine(org.eclipse.che.api.core.model.workspace.ExtendedMachine) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) IOException(java.io.IOException) MachineLogMessage(org.eclipse.che.api.core.model.machine.MachineLogMessage) NotFoundException(org.eclipse.che.api.core.NotFoundException) File(java.io.File) Machine(org.eclipse.che.api.core.model.machine.Machine) MachineSourceImpl(org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl) Collectors.toList(java.util.stream.Collectors.toList) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) RecipeDownloader(org.eclipse.che.api.machine.server.util.RecipeDownloader) ServerException(org.eclipse.che.api.core.ServerException) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ArrayDeque(java.util.ArrayDeque) DIE(org.eclipse.che.api.machine.server.event.InstanceStateEvent.Type.DIE) ServerException(org.eclipse.che.api.core.ServerException) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) Instance(org.eclipse.che.api.machine.server.spi.Instance) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) ExtendedMachine(org.eclipse.che.api.core.model.workspace.ExtendedMachine) AgentException(org.eclipse.che.api.agent.server.exception.AgentException) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) EnvironmentException(org.eclipse.che.api.environment.server.exception.EnvironmentException) ApiException(org.eclipse.che.api.core.ApiException) ConflictException(org.eclipse.che.api.core.ConflictException) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) IOException(java.io.IOException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ServerException(org.eclipse.che.api.core.ServerException) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) MachineLogMessage(org.eclipse.che.api.core.model.machine.MachineLogMessage) Nullable(org.eclipse.che.commons.annotation.Nullable)

Example 2 with Queue

use of java.util.Queue in project jetty.project by eclipse.

the class AsyncRestServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Long start = System.nanoTime();
    // Do we have results yet?
    Queue<Map<String, String>> results = (Queue<Map<String, String>>) request.getAttribute(RESULTS_ATTR);
    // If no results, this must be the first dispatch, so send the REST request(s)
    if (results == null) {
        // define results data structures
        final Queue<Map<String, String>> resultsQueue = new ConcurrentLinkedQueue<>();
        request.setAttribute(RESULTS_ATTR, results = resultsQueue);
        // suspend the request
        // This is done before scheduling async handling to avoid race of
        // dispatch before startAsync!
        final AsyncContext async = request.startAsync();
        async.setTimeout(30000);
        // extract keywords to search for
        String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(",");
        final AtomicInteger outstanding = new AtomicInteger(keywords.length);
        // Send request each keyword
        for (final String item : keywords) {
            _client.newRequest(restURL(item)).method(HttpMethod.GET).send(new AsyncRestRequest() {

                @Override
                void onAuctionFound(Map<String, String> auction) {
                    resultsQueue.add(auction);
                }

                @Override
                void onComplete() {
                    if (outstanding.decrementAndGet() <= 0)
                        async.dispatch();
                }
            });
        }
        // save timing info and return
        request.setAttribute(START_ATTR, start);
        request.setAttribute(DURATION_ATTR, System.nanoTime() - start);
        return;
    }
    // We have results!
    // Generate the response
    String thumbs = generateThumbs(results);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html><head>");
    out.println(STYLE);
    out.println("</head><body><small>");
    long initial = (Long) request.getAttribute(DURATION_ATTR);
    long start0 = (Long) request.getAttribute(START_ATTR);
    long now = System.nanoTime();
    long total = now - start0;
    long generate = now - start;
    long thread = initial + generate;
    out.print("<b>Asynchronous: " + sanitize(request.getParameter(ITEMS_PARAM)) + "</b><br/>");
    out.print("Total Time: " + ms(total) + "ms<br/>");
    out.print("Thread held (<span class='red'>red</span>): " + ms(thread) + "ms (" + ms(initial) + " initial + " + ms(generate) + " generate )<br/>");
    out.print("Async wait (<span class='green'>green</span>): " + ms(total - thread) + "ms<br/>");
    out.println("<img border='0px' src='asyncrest/red.png'   height='20px' width='" + width(initial) + "px'>" + "<img border='0px' src='asyncrest/green.png' height='20px' width='" + width(total - thread) + "px'>" + "<img border='0px' src='asyncrest/red.png'   height='20px' width='" + width(generate) + "px'>");
    out.println("<hr />");
    out.println(thumbs);
    out.println("</small>");
    out.println("</body></html>");
    out.close();
}
Also used : AsyncContext(javax.servlet.AsyncContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Queue(java.util.Queue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 3 with Queue

use of java.util.Queue in project storm by apache.

the class DefaultResourceAwareStrategy method orderExecutors.

/**
     * Order executors based on how many in and out connections it will potentially need to make.
     * First order components by the number of in and out connections it will have.  Then iterate through the sorted list of components.
     * For each component sort the neighbors of that component by how many connections it will have to make with that component.
     * Add an executor from this component and then from each neighboring component in sorted order.  Do this until there is nothing left to schedule
     *
     * @param td                  The topology the executors belong to
     * @param unassignedExecutors a collection of unassigned executors that need to be unassigned. Should only try to assign executors from this list
     * @return a list of executors in sorted order
     */
private List<ExecutorDetails> orderExecutors(TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) {
    Map<String, Component> componentMap = td.getComponents();
    List<ExecutorDetails> execsScheduled = new LinkedList<>();
    Map<String, Queue<ExecutorDetails>> compToExecsToSchedule = new HashMap<>();
    for (Component component : componentMap.values()) {
        compToExecsToSchedule.put(component.id, new LinkedList<ExecutorDetails>());
        for (ExecutorDetails exec : component.execs) {
            if (unassignedExecutors.contains(exec)) {
                compToExecsToSchedule.get(component.id).add(exec);
            }
        }
    }
    Set<Component> sortedComponents = sortComponents(componentMap);
    sortedComponents.addAll(componentMap.values());
    for (Component currComp : sortedComponents) {
        Map<String, Component> neighbors = new HashMap<String, Component>();
        for (String compId : (List<String>) ListUtils.union(currComp.children, currComp.parents)) {
            neighbors.put(compId, componentMap.get(compId));
        }
        Set<Component> sortedNeighbors = sortNeighbors(currComp, neighbors);
        Queue<ExecutorDetails> currCompExesToSched = compToExecsToSchedule.get(currComp.id);
        boolean flag = false;
        do {
            flag = false;
            if (!currCompExesToSched.isEmpty()) {
                execsScheduled.add(currCompExesToSched.poll());
                flag = true;
            }
            for (Component neighborComp : sortedNeighbors) {
                Queue<ExecutorDetails> neighborCompExesToSched = compToExecsToSchedule.get(neighborComp.id);
                if (!neighborCompExesToSched.isEmpty()) {
                    execsScheduled.add(neighborCompExesToSched.poll());
                    flag = true;
                }
            }
        } while (flag);
    }
    return execsScheduled;
}
Also used : ExecutorDetails(org.apache.storm.scheduler.ExecutorDetails) HashMap(java.util.HashMap) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) Component(org.apache.storm.scheduler.resource.Component) Queue(java.util.Queue)

Example 4 with Queue

use of java.util.Queue in project pinot by linkedin.

the class InnerSegmentSelectionMultiValueQueriesTest method testSelectionOrderBy.

@Test
public void testSelectionOrderBy() {
    String query = "SELECT" + SELECTION + " FROM testTable" + ORDER_BY;
    // Test query without filter.
    MSelectionOrderByOperator selectionOrderByOperator = getOperatorForQuery(query);
    IntermediateResultsBlock resultsBlock = (IntermediateResultsBlock) selectionOrderByOperator.nextBlock();
    ExecutionStatistics executionStatistics = selectionOrderByOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 100000L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 0L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 400000L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    DataSchema selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 4);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column5");
    Assert.assertEquals(selectionDataSchema.getColumnName(3), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.STRING);
    Assert.assertEquals(selectionDataSchema.getColumnType(3), FieldSpec.DataType.INT_ARRAY);
    Queue<Serializable[]> selectionResult = (Queue<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    Serializable[] lastRow = selectionResult.peek();
    Assert.assertEquals(lastRow.length, 4);
    Assert.assertEquals((String) lastRow[0], "AKXcXcIqsqOJFsdwxZ");
    Assert.assertEquals(lastRow[3], new int[] { 1252 });
    // Test query with filter.
    selectionOrderByOperator = getOperatorForQueryWithFilter(query);
    resultsBlock = (IntermediateResultsBlock) selectionOrderByOperator.nextBlock();
    executionStatistics = selectionOrderByOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 15620L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 282430L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 62480L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 4);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column5");
    Assert.assertEquals(selectionDataSchema.getColumnName(3), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.STRING);
    Assert.assertEquals(selectionDataSchema.getColumnType(3), FieldSpec.DataType.INT_ARRAY);
    selectionResult = (Queue<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    lastRow = selectionResult.peek();
    Assert.assertEquals(lastRow.length, 4);
    Assert.assertEquals((String) lastRow[0], "AKXcXcIqsqOJFsdwxZ");
    Assert.assertEquals(lastRow[3], new int[] { 2147483647 });
}
Also used : DataSchema(com.linkedin.pinot.common.utils.DataSchema) ExecutionStatistics(com.linkedin.pinot.core.operator.ExecutionStatistics) Serializable(java.io.Serializable) IntermediateResultsBlock(com.linkedin.pinot.core.operator.blocks.IntermediateResultsBlock) Queue(java.util.Queue) MSelectionOrderByOperator(com.linkedin.pinot.core.operator.query.MSelectionOrderByOperator) Test(org.testng.annotations.Test)

Example 5 with Queue

use of java.util.Queue in project pinot by linkedin.

the class InnerSegmentSelectionSingleValueQueriesTest method testSelectionOrderBy.

@Test
public void testSelectionOrderBy() {
    String query = "SELECT" + SELECTION + " FROM testTable" + ORDER_BY;
    // Test query without filter.
    MSelectionOrderByOperator selectionOrderByOperator = getOperatorForQuery(query);
    IntermediateResultsBlock resultsBlock = (IntermediateResultsBlock) selectionOrderByOperator.nextBlock();
    ExecutionStatistics executionStatistics = selectionOrderByOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 30000L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 0L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 120000L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 30000L);
    DataSchema selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 4);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnName(1), "column1");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.INT);
    Assert.assertEquals(selectionDataSchema.getColumnType(1), FieldSpec.DataType.INT);
    Queue<Serializable[]> selectionResult = (Queue<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    Serializable[] lastRow = selectionResult.peek();
    Assert.assertEquals(lastRow.length, 4);
    Assert.assertEquals(((Integer) lastRow[0]).intValue(), 6043515);
    Assert.assertEquals(((Integer) lastRow[1]).intValue(), 10542595);
    // Test query with filter.
    selectionOrderByOperator = getOperatorForQueryWithFilter(query);
    resultsBlock = (IntermediateResultsBlock) selectionOrderByOperator.nextBlock();
    executionStatistics = selectionOrderByOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 6129L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 84134L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 24516L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 30000L);
    selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 4);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnName(1), "column1");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.INT);
    Assert.assertEquals(selectionDataSchema.getColumnType(1), FieldSpec.DataType.INT);
    selectionResult = (Queue<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    lastRow = selectionResult.peek();
    Assert.assertEquals(lastRow.length, 4);
    Assert.assertEquals(((Integer) lastRow[0]).intValue(), 6043515);
    Assert.assertEquals(((Integer) lastRow[1]).intValue(), 462769197);
}
Also used : DataSchema(com.linkedin.pinot.common.utils.DataSchema) ExecutionStatistics(com.linkedin.pinot.core.operator.ExecutionStatistics) Serializable(java.io.Serializable) IntermediateResultsBlock(com.linkedin.pinot.core.operator.blocks.IntermediateResultsBlock) Queue(java.util.Queue) MSelectionOrderByOperator(com.linkedin.pinot.core.operator.query.MSelectionOrderByOperator) Test(org.testng.annotations.Test)

Aggregations

Queue (java.util.Queue)228 List (java.util.List)69 Test (org.junit.Test)66 HashMap (java.util.HashMap)65 ArrayList (java.util.ArrayList)52 Map (java.util.Map)49 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)49 LinkedList (java.util.LinkedList)33 Set (java.util.Set)33 IOException (java.io.IOException)30 Collections (java.util.Collections)29 Collectors (java.util.stream.Collectors)27 Collection (java.util.Collection)25 HashSet (java.util.HashSet)25 BlockingQueue (java.util.concurrent.BlockingQueue)23 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)23 ArrayDeque (java.util.ArrayDeque)22 PriorityQueue (java.util.PriorityQueue)22 Arrays (java.util.Arrays)21 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)20