Search in sources :

Example 1 with SharedQueryState

use of io.prestosql.statestore.SharedQueryState in project hetu-core by openlookeng.

the class SqlQueryManager method killExpiredQuery.

/**
 * Kill query when expired, state has already been updated in StateFetcher.
 */
private void killExpiredQuery() {
    if (!isMultiCoordinatorEnabled()) {
        return;
    }
    List<QueryExecution> localRunningQueries = queryTracker.getAllQueries().stream().filter(query -> query.getState() == RUNNING).collect(toImmutableList());
    Map<String, SharedQueryState> queries = StateCacheStore.get().getCachedStates(StateStoreConstants.FINISHED_QUERY_STATE_COLLECTION_NAME);
    if (queries != null) {
        Set<String> expiredQueryIds = queries.entrySet().stream().filter(entry -> isQueryExpired(entry.getValue())).map(entry -> entry.getKey()).collect(Collectors.toSet());
        if (!expiredQueryIds.isEmpty()) {
            for (QueryExecution localQuery : localRunningQueries) {
                if (expiredQueryIds.contains(localQuery.getQueryId().getId())) {
                    localQuery.fail(new PrestoException(QUERY_EXPIRE, "Query killed because the query has expired. Please try again in a few minutes."));
                }
            }
        }
    }
}
Also used : Plan(io.prestosql.sql.planner.Plan) Duration(io.airlift.units.Duration) PreDestroy(javax.annotation.PreDestroy) ObjectMapperProvider(io.airlift.json.ObjectMapperProvider) Locale(java.util.Locale) Map(java.util.Map) QueryMonitor(io.prestosql.event.QueryMonitor) StateCacheStore(io.prestosql.statestore.StateCacheStore) ClusterMemoryManager(io.prestosql.memory.ClusterMemoryManager) PrestoException(io.prestosql.spi.PrestoException) SharedQueryState(io.prestosql.statestore.SharedQueryState) StateMap(io.prestosql.spi.statestore.StateMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ErrorType(io.prestosql.spi.ErrorType) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) ExceededCpuLimitException(io.prestosql.ExceededCpuLimitException) Threads.threadsNamed(io.airlift.concurrent.Threads.threadsNamed) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) Objects(java.util.Objects) List(java.util.List) SessionPropertyManager(io.prestosql.metadata.SessionPropertyManager) PostConstruct(javax.annotation.PostConstruct) GENERIC_INTERNAL_ERROR(io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR) SystemSessionProperties.getQueryMaxCpuTime(io.prestosql.SystemSessionProperties.getQueryMaxCpuTime) QueryEditorUIModule(io.prestosql.queryeditorui.QueryEditorUIModule) Nested(org.weakref.jmx.Nested) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) StateChangeListener(io.prestosql.execution.StateMachine.StateChangeListener) Logger(io.airlift.log.Logger) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ThreadPoolExecutorMBean(io.airlift.concurrent.ThreadPoolExecutorMBean) EmbedVersion(io.prestosql.version.EmbedVersion) Flatten(org.weakref.jmx.Flatten) QUERY_EXPIRE(io.prestosql.spi.StandardErrorCode.QUERY_EXPIRE) Supplier(java.util.function.Supplier) Inject(javax.inject.Inject) Managed(org.weakref.jmx.Managed) BasicQueryInfo(io.prestosql.server.BasicQueryInfo) Objects.requireNonNull(java.util.Objects.requireNonNull) Session(io.prestosql.Session) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RUNNING(io.prestosql.execution.QueryState.RUNNING) QueryId(io.prestosql.spi.QueryId) NoSuchElementException(java.util.NoSuchElementException) ExecutorService(java.util.concurrent.ExecutorService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) QuerySnapshotManager(io.prestosql.snapshot.QuerySnapshotManager) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StateUtils.isMultiCoordinatorEnabled(io.prestosql.utils.StateUtils.isMultiCoordinatorEnabled) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Ordering(com.google.common.collect.Ordering) QueryOutputInfo(io.prestosql.execution.QueryExecution.QueryOutputInfo) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) StateStoreProvider(io.prestosql.statestore.StateStoreProvider) Futures.immediateFailedFuture(com.google.common.util.concurrent.Futures.immediateFailedFuture) StateStoreConstants(io.prestosql.statestore.StateStoreConstants) SharedQueryState(io.prestosql.statestore.SharedQueryState) PrestoException(io.prestosql.spi.PrestoException)

Example 2 with SharedQueryState

use of io.prestosql.statestore.SharedQueryState in project hetu-core by openlookeng.

the class DistributedResourceGroup method internalRefreshStats.

/**
 * Update internal stats for all the children groups
 * Stats are calculated based on cached resource group states from state store
 * Stats include: running queries, queued queries, memory usage, cpu usage
 */
@Override
protected void internalRefreshStats() {
    checkState(Thread.holdsLock(root), "Must hold lock to refresh stats");
    synchronized (root) {
        if (subGroups.isEmpty()) {
            descendantRunningQueries = 0;
            descendantQueuedQueries = 0;
            cachedMemoryUsageBytes = 0;
            Optional<SharedResourceGroupState> resourceGroupState = getSharedResourceGroupState();
            if (!resourceGroupState.isPresent()) {
                return;
            }
            resourceGroupState.ifPresent(state -> this.lastExecutionTime = state.getLastExecutionTime());
            Set<SharedQueryState> sharedQueryStates = resourceGroupState.get().getRunningQueries();
            for (SharedQueryState state : sharedQueryStates) {
                cachedMemoryUsageBytes += state.getTotalMemoryReservation().toBytes();
            }
            // get cpuUsageMillis from resourceGroupState
            cpuUsageMillis = resourceGroupState.get().getCpuUsageMillis();
        } else {
            int tempDescendantRunningQueries = 0;
            int tempDescendantQueuedQueries = 0;
            long tempCachedMemoryUsageBytes = 0L;
            long tempCpuUsageMillis = 0L;
            for (BaseResourceGroup group : subGroups()) {
                group.internalRefreshStats();
                tempCpuUsageMillis += ((DistributedResourceGroup) group).cpuUsageMillis;
            }
            // Sub-groups are created on demand, so need to also check stats in sub-groups created on other coordinators
            for (SharedResourceGroupState state : getSharedSubGroups()) {
                tempDescendantRunningQueries += state.getRunningQueries().size();
                tempDescendantQueuedQueries += state.getQueuedQueries().size();
                tempCachedMemoryUsageBytes += state.getRunningQueries().stream().mapToLong(query -> query.getTotalMemoryReservation().toBytes()).reduce(0, (memoryUsage1, memoryUsage2) -> memoryUsage1 + memoryUsage2);
            }
            descendantRunningQueries = tempDescendantRunningQueries;
            descendantQueuedQueries = tempDescendantQueuedQueries;
            cachedMemoryUsageBytes = tempCachedMemoryUsageBytes;
            cpuUsageMillis = tempCpuUsageMillis;
        }
        lastUpdateTime = new DateTime();
    }
}
Also used : SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState) Logger(io.airlift.log.Logger) PriorityQueue(java.util.PriorityQueue) StateStore(io.prestosql.spi.statestore.StateStore) GENERIC_INSUFFICIENT_RESOURCES(io.prestosql.spi.StandardErrorCode.GENERIC_INSUFFICIENT_RESOURCES) CounterStat(io.airlift.stats.CounterStat) Duration(io.airlift.units.Duration) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) BiConsumer(java.util.function.BiConsumer) DistributedResourceGroupUtils(io.prestosql.utils.DistributedResourceGroupUtils) StateCacheStore(io.prestosql.statestore.StateCacheStore) LinkedList(java.util.LinkedList) QueryStateInfo.createQueryStateInfo(io.prestosql.server.QueryStateInfo.createQueryStateInfo) PrestoException(io.prestosql.spi.PrestoException) SharedQueryState(io.prestosql.statestore.SharedQueryState) Executor(java.util.concurrent.Executor) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) DateTime(org.joda.time.DateTime) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) KillPolicy(io.prestosql.spi.resourcegroups.KillPolicy) TimeUnit(java.util.concurrent.TimeUnit) ResourceGroupId(io.prestosql.spi.resourcegroups.ResourceGroupId) DataSize(io.airlift.units.DataSize) List(java.util.List) Lock(java.util.concurrent.locks.Lock) SchedulingPolicy(io.prestosql.spi.resourcegroups.SchedulingPolicy) QueryState(io.prestosql.execution.QueryState) Optional(java.util.Optional) Queue(java.util.Queue) Comparator(java.util.Comparator) QueryStateInfo(io.prestosql.server.QueryStateInfo) ManagedQueryExecution(io.prestosql.execution.ManagedQueryExecution) StateStoreConstants(io.prestosql.statestore.StateStoreConstants) SharedQueryState(io.prestosql.statestore.SharedQueryState) SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState) DateTime(org.joda.time.DateTime)

Example 3 with SharedQueryState

use of io.prestosql.statestore.SharedQueryState in project hetu-core by openlookeng.

the class DistributedResourceGroup method internalCancelQuery.

public void internalCancelQuery() {
    checkState(Thread.holdsLock(root), "Must hold lock to check cancel query");
    synchronized (root) {
        if (!subGroups.isEmpty()) {
            for (BaseResourceGroup group : subGroups()) {
                ((DistributedResourceGroup) group).internalCancelQuery();
            }
            return;
        }
        if (cachedMemoryUsageBytes <= softMemoryLimitBytes) {
            return;
        }
        Optional<SharedResourceGroupState> resourceGroupState = getSharedResourceGroupState();
        if (!resourceGroupState.isPresent()) {
            return;
        }
        Set<SharedQueryState> globalRunningQueries = resourceGroupState.get().getRunningQueries();
        List<SharedQueryState> sortedQueryList;
        Lock lock = stateStore.getLock(id.toString());
        boolean locked = false;
        try {
            // If lock is not free, then we return immediately, so no need to refresh after taking lock.
            // Before next call of this function, refresh will already happen.
            locked = lock.tryLock();
            if (locked) {
                switch(killPolicy) {
                    case HIGH_MEMORY_QUERIES:
                        double absMemoryMargin = 1 - (double) memoryMarginPercent / 100;
                        double absQueryProgressMargin = 1 - (double) queryProgressMarginPercent / 100;
                        sortedQueryList = globalRunningQueries.stream().sorted((o1, o2) -> {
                            if (o1.getTotalMemoryReservation().toBytes() < o2.getTotalMemoryReservation().toBytes() * absMemoryMargin || o2.getTotalMemoryReservation().toBytes() < o1.getTotalMemoryReservation().toBytes() * absMemoryMargin) {
                                return ((Long) o2.getTotalMemoryReservation().toBytes()).compareTo(o1.getTotalMemoryReservation().toBytes());
                            }
                            // if query progress difference is within 5%, then order will be decided based on memory itself.
                            if (o1.getQueryProgress().orElse(0) < o2.getQueryProgress().orElse(0) * absQueryProgressMargin || o2.getQueryProgress().orElse(0) < o1.getQueryProgress().orElse(0) * absQueryProgressMargin) {
                                return ((Double) o1.getQueryProgress().orElse(0)).compareTo((o2.getQueryProgress().orElse(0)));
                            }
                            return ((Long) o2.getTotalMemoryReservation().toBytes()).compareTo(o1.getTotalMemoryReservation().toBytes());
                        }).collect(Collectors.toList());
                        break;
                    case OLDEST_QUERIES:
                        sortedQueryList = globalRunningQueries.stream().sorted(Comparator.comparing(o -> (o.getExecutionStartTime().get()))).collect(Collectors.toList());
                        break;
                    case RECENT_QUERIES:
                        sortedQueryList = globalRunningQueries.stream().sorted(Comparator.comparing(o -> (o.getExecutionStartTime().get()), Comparator.reverseOrder())).collect(Collectors.toList());
                        break;
                    case FINISH_PERCENTAGE_QUERIES:
                        sortedQueryList = globalRunningQueries.stream().sorted(Comparator.comparing(o -> (o.getQueryProgress().orElse(0)))).collect(Collectors.toList());
                        break;
                    case NO_KILL:
                    // fall through
                    default:
                        sortedQueryList = new ArrayList<>();
                }
                long tempGlobalCachedMemoryUsage = cachedMemoryUsageBytes;
                long tempLocalCachedMemoryUsage = cachedMemoryUsageBytes;
                // So in this case only Q1 will be killed from local coordinator.
                for (SharedQueryState query : sortedQueryList) {
                    for (ManagedQueryExecution localQuery : runningQueries) {
                        if (query.getBasicQueryInfo().getQueryId().equals(localQuery.getBasicQueryInfo().getQueryId())) {
                            LOG.info("Query " + localQuery.getBasicQueryInfo().getQueryId() + " is getting killed for resource group " + this + " query will be killed with policy " + killPolicy);
                            localQuery.fail(new PrestoException(GENERIC_INSUFFICIENT_RESOURCES, "Memory consumption " + tempLocalCachedMemoryUsage + " exceed the limit " + softMemoryLimitBytes + "for resource group " + this));
                            queryFinished(localQuery);
                            tempLocalCachedMemoryUsage -= query.getTotalMemoryReservation().toBytes();
                            break;
                        }
                    }
                    tempGlobalCachedMemoryUsage -= query.getTotalMemoryReservation().toBytes();
                    if (tempGlobalCachedMemoryUsage <= softMemoryLimitBytes) {
                        break;
                    }
                }
            }
        } catch (RuntimeException e) {
            return;
        } finally {
            if (locked) {
                lock.unlock();
            }
        }
    }
}
Also used : SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState) Logger(io.airlift.log.Logger) PriorityQueue(java.util.PriorityQueue) StateStore(io.prestosql.spi.statestore.StateStore) GENERIC_INSUFFICIENT_RESOURCES(io.prestosql.spi.StandardErrorCode.GENERIC_INSUFFICIENT_RESOURCES) CounterStat(io.airlift.stats.CounterStat) Duration(io.airlift.units.Duration) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) BiConsumer(java.util.function.BiConsumer) DistributedResourceGroupUtils(io.prestosql.utils.DistributedResourceGroupUtils) StateCacheStore(io.prestosql.statestore.StateCacheStore) LinkedList(java.util.LinkedList) QueryStateInfo.createQueryStateInfo(io.prestosql.server.QueryStateInfo.createQueryStateInfo) PrestoException(io.prestosql.spi.PrestoException) SharedQueryState(io.prestosql.statestore.SharedQueryState) Executor(java.util.concurrent.Executor) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) DateTime(org.joda.time.DateTime) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) KillPolicy(io.prestosql.spi.resourcegroups.KillPolicy) TimeUnit(java.util.concurrent.TimeUnit) ResourceGroupId(io.prestosql.spi.resourcegroups.ResourceGroupId) DataSize(io.airlift.units.DataSize) List(java.util.List) Lock(java.util.concurrent.locks.Lock) SchedulingPolicy(io.prestosql.spi.resourcegroups.SchedulingPolicy) QueryState(io.prestosql.execution.QueryState) Optional(java.util.Optional) Queue(java.util.Queue) Comparator(java.util.Comparator) QueryStateInfo(io.prestosql.server.QueryStateInfo) ManagedQueryExecution(io.prestosql.execution.ManagedQueryExecution) StateStoreConstants(io.prestosql.statestore.StateStoreConstants) ManagedQueryExecution(io.prestosql.execution.ManagedQueryExecution) PrestoException(io.prestosql.spi.PrestoException) Lock(java.util.concurrent.locks.Lock) SharedQueryState(io.prestosql.statestore.SharedQueryState) SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState)

Example 4 with SharedQueryState

use of io.prestosql.statestore.SharedQueryState in project hetu-core by openlookeng.

the class DistributedResourceGroupTemp method internalCancelQuery.

public void internalCancelQuery() {
    checkState(Thread.holdsLock(root), "Must hold lock to check cancel query");
    synchronized (root) {
        if (!subGroups.isEmpty()) {
            for (BaseResourceGroup group : subGroups()) {
                ((DistributedResourceGroupTemp) group).internalCancelQuery();
            }
            return;
        }
        long cachedMemoryUsageBytes = getGlobalCachedMemoryUsageBytes();
        if (cachedMemoryUsageBytes <= softMemoryLimitBytes) {
            return;
        }
        Optional<SharedResourceGroupState> resourceGroupState = getSharedResourceGroupState();
        if (!resourceGroupState.isPresent()) {
            return;
        }
        Set<SharedQueryState> globalRunningQueries = resourceGroupState.get().getRunningQueries();
        List<SharedQueryState> sortedQueryList;
        Lock lock = stateStore.getLock(id.toString());
        boolean locked = false;
        try {
            // If lock is not free, then we return immediately, so no need to refresh after taking lock.
            // Before next call of this function, refresh will already happen.
            locked = lock.tryLock();
            if (locked) {
                switch(killPolicy) {
                    case HIGH_MEMORY_QUERIES:
                        double absMemoryMargin = 1 - (double) memoryMarginPercent / 100;
                        double absQueryProgressMargin = 1 - (double) queryProgressMarginPercent / 100;
                        sortedQueryList = globalRunningQueries.stream().sorted((o1, o2) -> {
                            if (o1.getTotalMemoryReservation().toBytes() < o2.getTotalMemoryReservation().toBytes() * absMemoryMargin || o2.getTotalMemoryReservation().toBytes() < o1.getTotalMemoryReservation().toBytes() * absMemoryMargin) {
                                return ((Long) o2.getTotalMemoryReservation().toBytes()).compareTo(o1.getTotalMemoryReservation().toBytes());
                            }
                            // if query progress difference is within 5%, then order will be decided based on memory itself.
                            if (o1.getQueryProgress().orElse(0) < o2.getQueryProgress().orElse(0) * absQueryProgressMargin || o2.getQueryProgress().orElse(0) < o1.getQueryProgress().orElse(0) * absQueryProgressMargin) {
                                return ((Double) o1.getQueryProgress().orElse(0)).compareTo((o2.getQueryProgress().orElse(0)));
                            }
                            return ((Long) o2.getTotalMemoryReservation().toBytes()).compareTo(o1.getTotalMemoryReservation().toBytes());
                        }).collect(Collectors.toList());
                        break;
                    case OLDEST_QUERIES:
                        sortedQueryList = globalRunningQueries.stream().sorted(Comparator.comparing(o -> (o.getExecutionStartTime().get()))).collect(Collectors.toList());
                        break;
                    case RECENT_QUERIES:
                        sortedQueryList = globalRunningQueries.stream().sorted(Comparator.comparing(o -> (o.getExecutionStartTime().get()), Comparator.reverseOrder())).collect(Collectors.toList());
                        break;
                    case FINISH_PERCENTAGE_QUERIES:
                        sortedQueryList = globalRunningQueries.stream().sorted(Comparator.comparing(o -> (o.getQueryProgress().orElse(0)))).collect(Collectors.toList());
                        break;
                    case NO_KILL:
                    // fall through
                    default:
                        sortedQueryList = new ArrayList<>();
                }
                long tempGlobalCachedMemoryUsage = cachedMemoryUsageBytes;
                long tempLocalCachedMemoryUsage = localCachedMemoryUsageBytes;
                // So in this case only Q1 will be killed from local coordinator.
                for (SharedQueryState query : sortedQueryList) {
                    for (ManagedQueryExecution localQuery : localRunningQueries) {
                        if (query.getBasicQueryInfo().getQueryId().equals(localQuery.getBasicQueryInfo().getQueryId())) {
                            LOG.info("Query " + localQuery.getBasicQueryInfo().getQueryId() + " is getting killed for resource group " + this + " query will be killed with policy " + killPolicy);
                            localQuery.fail(new PrestoException(GENERIC_INSUFFICIENT_RESOURCES, "Memory consumption " + tempLocalCachedMemoryUsage + " exceed the limit " + softMemoryLimitBytes + "for resource group " + this));
                            queryFinished(localQuery);
                            tempLocalCachedMemoryUsage -= query.getTotalMemoryReservation().toBytes();
                            break;
                        }
                    }
                    tempGlobalCachedMemoryUsage -= query.getTotalMemoryReservation().toBytes();
                    if (tempGlobalCachedMemoryUsage <= softMemoryLimitBytes) {
                        break;
                    }
                }
            }
        } catch (RuntimeException e) {
            return;
        } finally {
            if (locked) {
                lock.unlock();
            }
        }
    }
}
Also used : SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState) PriorityQueue(java.util.PriorityQueue) StateStore(io.prestosql.spi.statestore.StateStore) GENERIC_INSUFFICIENT_RESOURCES(io.prestosql.spi.StandardErrorCode.GENERIC_INSUFFICIENT_RESOURCES) Duration(io.airlift.units.Duration) ObjectMapperProvider(io.airlift.json.ObjectMapperProvider) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Map(java.util.Map) DistributedResourceGroupUtils(io.prestosql.utils.DistributedResourceGroupUtils) StateCacheStore(io.prestosql.statestore.StateCacheStore) LongMath.saturatedMultiply(com.google.common.math.LongMath.saturatedMultiply) QueryStateInfo.createQueryStateInfo(io.prestosql.server.QueryStateInfo.createQueryStateInfo) PrestoException(io.prestosql.spi.PrestoException) SharedQueryState(io.prestosql.statestore.SharedQueryState) StateMap(io.prestosql.spi.statestore.StateMap) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ResourceGroupId(io.prestosql.spi.resourcegroups.ResourceGroupId) DataSize(io.airlift.units.DataSize) List(java.util.List) LongMath.saturatedAdd(com.google.common.math.LongMath.saturatedAdd) SchedulingPolicy(io.prestosql.spi.resourcegroups.SchedulingPolicy) Optional(java.util.Optional) Queue(java.util.Queue) ManagedQueryExecution(io.prestosql.execution.ManagedQueryExecution) Logger(io.airlift.log.Logger) CounterStat(io.airlift.stats.CounterStat) LongMath.saturatedSubtract(com.google.common.math.LongMath.saturatedSubtract) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) USER_ERROR(io.prestosql.spi.ErrorType.USER_ERROR) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) Objects.requireNonNull(java.util.Objects.requireNonNull) BiConsumer(java.util.function.BiConsumer) LinkedList(java.util.LinkedList) InternalNodeManager(io.prestosql.metadata.InternalNodeManager) Executor(java.util.concurrent.Executor) StateCollection(io.prestosql.spi.statestore.StateCollection) InternalNode(io.prestosql.metadata.InternalNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) KillPolicy(io.prestosql.spi.resourcegroups.KillPolicy) TimeUnit(java.util.concurrent.TimeUnit) Lock(java.util.concurrent.locks.Lock) QueryState(io.prestosql.execution.QueryState) Comparator(java.util.Comparator) QueryStateInfo(io.prestosql.server.QueryStateInfo) StateStoreConstants(io.prestosql.statestore.StateStoreConstants) ManagedQueryExecution(io.prestosql.execution.ManagedQueryExecution) PrestoException(io.prestosql.spi.PrestoException) Lock(java.util.concurrent.locks.Lock) SharedQueryState(io.prestosql.statestore.SharedQueryState) SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState)

Example 5 with SharedQueryState

use of io.prestosql.statestore.SharedQueryState in project hetu-core by openlookeng.

the class DistributedResourceGroupTemp method internalStartNext.

/**
 * Check if there is any queued query in any eligible sub-group that can be started
 *
 * @return if any query has been started in sub-groups
 */
protected boolean internalStartNext() {
    checkState(Thread.holdsLock(root), "Must hold lock to find next query");
    synchronized (root) {
        if (!canRunMore()) {
            return false;
        }
        // Only start the query if it exists locally
        Optional<SharedResourceGroupState> resourceGroupState = getSharedResourceGroupState();
        PriorityQueue<SharedQueryState> globalQueuedQueries = resourceGroupState.isPresent() ? resourceGroupState.get().getQueuedQueries() : new PriorityQueue<>();
        if (!globalQueuedQueries.isEmpty() && !localQueuedQueries.isEmpty()) {
            // Get queued query with longest queued time from state cache store.
            // Remove it if local queued queries contains it.
            SharedQueryState nextQuery = globalQueuedQueries.peek();
            for (ManagedQueryExecution localQuery : localQueuedQueries) {
                if (nextQuery.getBasicQueryInfo().getQueryId().equals(localQuery.getBasicQueryInfo().getQueryId())) {
                    Lock lock = stateStore.getLock(id.toString());
                    boolean locked = false;
                    try {
                        locked = lock.tryLock(MILLISECONDS_PER_SECOND, TimeUnit.MILLISECONDS);
                        if (locked) {
                            // Get the most recent cached state store status and check canRunMore again
                            // Avoid the race condition that state store is updated by other process
                            // Make sure queued query start is synchronized
                            DistributedResourceGroupUtils.mapCachedStates();
                            if (canRunMore()) {
                                startInBackground(localQuery);
                                return true;
                            }
                        }
                        return false;
                    } catch (InterruptedException | RuntimeException e) {
                        return false;
                    } finally {
                        if (locked) {
                            lock.unlock();
                        }
                    }
                }
            }
        }
        // Try to find least recently used eligible group
        DistributedResourceGroupTemp chosenGroup = findLeastRecentlyExecutedSubgroup();
        if (chosenGroup == null) {
            return false;
        }
        // Try to start queued query in the group
        boolean started = chosenGroup.internalStartNext();
        long currentTime = System.currentTimeMillis();
        if (lastStartMillis != 0) {
            timeBetweenStartsSec.update(Math.max(0, (currentTime - lastStartMillis) / MILLISECONDS_PER_SECOND));
        }
        lastStartMillis = currentTime;
        return started;
    }
}
Also used : ManagedQueryExecution(io.prestosql.execution.ManagedQueryExecution) Lock(java.util.concurrent.locks.Lock) SharedQueryState(io.prestosql.statestore.SharedQueryState) SharedResourceGroupState(io.prestosql.statestore.SharedResourceGroupState)

Aggregations

SharedQueryState (io.prestosql.statestore.SharedQueryState)12 SharedResourceGroupState (io.prestosql.statestore.SharedResourceGroupState)8 Map (java.util.Map)7 ResourceGroupId (io.prestosql.spi.resourcegroups.ResourceGroupId)6 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)5 Logger (io.airlift.log.Logger)5 Duration (io.airlift.units.Duration)5 ManagedQueryExecution (io.prestosql.execution.ManagedQueryExecution)5 PrestoException (io.prestosql.spi.PrestoException)5 StateCacheStore (io.prestosql.statestore.StateCacheStore)5 StateStoreConstants (io.prestosql.statestore.StateStoreConstants)4 HashMap (java.util.HashMap)4 List (java.util.List)4 Objects.requireNonNull (java.util.Objects.requireNonNull)4 Set (java.util.Set)4 TimeUnit (java.util.concurrent.TimeUnit)4 Lock (java.util.concurrent.locks.Lock)4 Collectors (java.util.stream.Collectors)4 ThreadSafe (javax.annotation.concurrent.ThreadSafe)4 Managed (org.weakref.jmx.Managed)4