Search in sources :

Example 1 with ThreadFactoryBuilder

use of org.apache.flink.shaded.guava30.com.google.common.util.concurrent.ThreadFactoryBuilder in project che by eclipse.

the class WorkspaceRuntimes method shutdown.

/**
     * Terminates workspace runtimes service, so no more workspaces are allowed to start
     * or to be stopped directly, all the running workspaces are going to be stopped,
     * all the starting tasks will be eventually interrupted.
     *
     * @throws IllegalStateException
     *         if component shutdown is already called
     */
public void shutdown() throws InterruptedException {
    if (!isShutdown.compareAndSet(false, true)) {
        throw new IllegalStateException("Workspace runtimes service shutdown has been already called");
    }
    List<String> idsToStop;
    try (@SuppressWarnings("unused") Unlocker u = locks.writeAllLock()) {
        idsToStop = states.entrySet().stream().filter(e -> e.getValue().status != WorkspaceStatus.STOPPING).map(Map.Entry::getKey).collect(Collectors.toList());
        states.clear();
    }
    if (!idsToStop.isEmpty()) {
        LOG.info("Shutdown running environments, environments to stop: '{}'", idsToStop.size());
        ExecutorService executor = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors(), new ThreadFactoryBuilder().setNameFormat("StopEnvironmentsPool-%d").setDaemon(false).build());
        for (String id : idsToStop) {
            executor.execute(() -> {
                try {
                    envEngine.stop(id);
                } catch (EnvironmentNotRunningException ignored) {
                // might be already stopped
                } catch (Exception x) {
                    LOG.error(x.getMessage(), x);
                }
            });
        }
        executor.shutdown();
        try {
            if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                executor.shutdownNow();
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOG.error("Unable to stop runtimes termination pool");
                }
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
Also used : ENVIRONMENT_OUTPUT_CHANNEL_TEMPLATE(org.eclipse.che.api.machine.shared.Constants.ENVIRONMENT_OUTPUT_CHANNEL_TEMPLATE) AgentLauncher(org.eclipse.che.api.agent.server.launcher.AgentLauncher) Agent(org.eclipse.che.api.agent.shared.model.Agent) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) StripedLocks(org.eclipse.che.commons.lang.concurrent.StripedLocks) AgentException(org.eclipse.che.api.agent.server.exception.AgentException) RUNNING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.RUNNING) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) Future(java.util.concurrent.Future) WorkspaceStatusEvent(org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) Map(java.util.Map) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) EventService(org.eclipse.che.api.core.notification.EventService) CancellationException(java.util.concurrent.CancellationException) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Collectors(java.util.stream.Collectors) Nullable(org.eclipse.che.commons.annotation.Nullable) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) CountDownLatch(java.util.concurrent.CountDownLatch) STARTING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STARTING) EnvironmentException(org.eclipse.che.api.environment.server.exception.EnvironmentException) List(java.util.List) Environment(org.eclipse.che.api.core.model.workspace.Environment) CheEnvironmentEngine(org.eclipse.che.api.environment.server.CheEnvironmentEngine) AgentKey(org.eclipse.che.api.agent.shared.model.AgentKey) EventType(org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent.EventType) AgentLauncherFactory(org.eclipse.che.api.agent.server.launcher.AgentLauncherFactory) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) AgentRegistry(org.eclipse.che.api.agent.server.AgentRegistry) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Workspace(org.eclipse.che.api.core.model.workspace.Workspace) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Singleton(javax.inject.Singleton) SnapshotImpl(org.eclipse.che.api.machine.server.model.impl.SnapshotImpl) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) HashSet(java.util.HashSet) WebsocketMessageConsumer(org.eclipse.che.api.core.util.WebsocketMessageConsumer) WorkspaceRuntimeImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceRuntimeImpl) Objects.requireNonNull(java.util.Objects.requireNonNull) ConflictException(org.eclipse.che.api.core.ConflictException) Comparator.comparing(java.util.Comparator.comparing) Instance(org.eclipse.che.api.machine.server.spi.Instance) SnapshotDao(org.eclipse.che.api.machine.server.spi.SnapshotDao) DtoFactory(org.eclipse.che.dto.server.DtoFactory) ExecutorService(java.util.concurrent.ExecutorService) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) Logger(org.slf4j.Logger) ExtendedMachine(org.eclipse.che.api.core.model.workspace.ExtendedMachine) SNAPSHOTTING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.SNAPSHOTTING) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) NotFoundException(org.eclipse.che.api.core.NotFoundException) TimeUnit(java.util.concurrent.TimeUnit) SnapshotException(org.eclipse.che.api.machine.server.exception.SnapshotException) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) AgentSorter(org.eclipse.che.api.agent.server.impl.AgentSorter) 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) MachineStartedHandler(org.eclipse.che.api.environment.server.MachineStartedHandler) Collections(java.util.Collections) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) ExecutorService(java.util.concurrent.ExecutorService) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) 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) CancellationException(java.util.concurrent.CancellationException) EnvironmentException(org.eclipse.che.api.environment.server.exception.EnvironmentException) ConflictException(org.eclipse.che.api.core.ConflictException) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) NotFoundException(org.eclipse.che.api.core.NotFoundException) SnapshotException(org.eclipse.che.api.machine.server.exception.SnapshotException) ServerException(org.eclipse.che.api.core.ServerException)

Example 2 with ThreadFactoryBuilder

use of org.apache.flink.shaded.guava30.com.google.common.util.concurrent.ThreadFactoryBuilder in project che by eclipse.

the class SystemManager method stopServices.

/**
     * Stops some of the system services preparing system to lighter shutdown.
     * System status is changed from {@link SystemStatus#RUNNING} to
     * {@link SystemStatus#PREPARING_TO_SHUTDOWN}.
     *
     * @throws ConflictException
     *         when system status is different from running
     */
public void stopServices() throws ConflictException {
    if (!statusRef.compareAndSet(RUNNING, PREPARING_TO_SHUTDOWN)) {
        throw new ConflictException("System shutdown has been already called, system status: " + statusRef.get());
    }
    ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(false).setNameFormat("ShutdownSystemServicesPool").setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()).build());
    exec.execute(ThreadLocalPropagateContext.wrap(this::doStopServices));
    exec.shutdown();
}
Also used : ConflictException(org.eclipse.che.api.core.ConflictException) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder)

Example 3 with ThreadFactoryBuilder

use of org.apache.flink.shaded.guava30.com.google.common.util.concurrent.ThreadFactoryBuilder in project che by eclipse.

the class WorkspaceRuntimeIntegrationTest method setUp.

@BeforeMethod
public void setUp() throws Exception {
    CheEnvironmentEngine environmentEngine = new CheEnvironmentEngine(snapshotDao, machineInstanceProviders, "/tmp", 2000, eventService, environmentParser, new DefaultServicesStartStrategy(), instanceProvider, infrastructureProvisioner, "http://localhost:8080/api", recipeDownloader, containerNameGenerator, agentRegistry, sharedPool);
    runtimes = new WorkspaceRuntimes(eventService, environmentEngine, agentSorter, launcherFactory, agentRegistry, snapshotDao, sharedPool);
    executor = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder().setNameFormat(this.getClass().toString() + "-%d").build());
    EnvironmentContext.getCurrent().setSubject(new SubjectImpl("name", "id", "token", false));
}
Also used : CheEnvironmentEngine(org.eclipse.che.api.environment.server.CheEnvironmentEngine) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) DefaultServicesStartStrategy(org.eclipse.che.api.environment.server.DefaultServicesStartStrategy) SubjectImpl(org.eclipse.che.commons.subject.SubjectImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 4 with ThreadFactoryBuilder

use of org.apache.flink.shaded.guava30.com.google.common.util.concurrent.ThreadFactoryBuilder in project hadoop by apache.

the class EntityGroupFSTimelineStore method serviceStart.

@Override
protected void serviceStart() throws Exception {
    super.serviceStart();
    LOG.info("Starting {}", getName());
    summaryStore.start();
    Configuration conf = getConfig();
    aclManager = new TimelineACLsManager(conf);
    aclManager.setTimelineStore(summaryStore);
    summaryTdm = new TimelineDataManager(summaryStore, aclManager);
    summaryTdm.init(conf);
    addService(summaryTdm);
    // start child services that aren't already started
    super.serviceStart();
    if (!fs.exists(activeRootPath)) {
        fs.mkdirs(activeRootPath);
        fs.setPermission(activeRootPath, ACTIVE_DIR_PERMISSION);
    }
    if (!fs.exists(doneRootPath)) {
        fs.mkdirs(doneRootPath);
        fs.setPermission(doneRootPath, DONE_DIR_PERMISSION);
    }
    objMapper = new ObjectMapper();
    objMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
    jsonFactory = new MappingJsonFactory(objMapper);
    final long scanIntervalSecs = conf.getLong(YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_SCAN_INTERVAL_SECONDS, YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_SCAN_INTERVAL_SECONDS_DEFAULT);
    final long cleanerIntervalSecs = conf.getLong(YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_CLEANER_INTERVAL_SECONDS, YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_CLEANER_INTERVAL_SECONDS_DEFAULT);
    final int numThreads = conf.getInt(YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_THREADS, YarnConfiguration.TIMELINE_SERVICE_ENTITYGROUP_FS_STORE_THREADS_DEFAULT);
    LOG.info("Scanning active directory {} every {} seconds", activeRootPath, scanIntervalSecs);
    LOG.info("Cleaning logs every {} seconds", cleanerIntervalSecs);
    executor = new ScheduledThreadPoolExecutor(numThreads, new ThreadFactoryBuilder().setNameFormat("EntityLogPluginWorker #%d").build());
    executor.scheduleAtFixedRate(new EntityLogScanner(), 0, scanIntervalSecs, TimeUnit.SECONDS);
    executor.scheduleAtFixedRate(new EntityLogCleaner(), cleanerIntervalSecs, cleanerIntervalSecs, TimeUnit.SECONDS);
}
Also used : MappingJsonFactory(com.fasterxml.jackson.databind.MappingJsonFactory) Configuration(org.apache.hadoop.conf.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) TimelineACLsManager(org.apache.hadoop.yarn.server.timeline.security.TimelineACLsManager) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JaxbAnnotationIntrospector(com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector)

Example 5 with ThreadFactoryBuilder

use of org.apache.flink.shaded.guava30.com.google.common.util.concurrent.ThreadFactoryBuilder in project hive by apache.

the class HiveMetaStoreChecker method checkPartitionDirs.

/**
   * Assume that depth is 2, i.e., partition columns are a and b
   * tblPath/a=1  => throw exception
   * tblPath/a=1/file => throw exception
   * tblPath/a=1/b=2/file => return a=1/b=2
   * tblPath/a=1/b=2/c=3 => return a=1/b=2
   * tblPath/a=1/b=2/c=3/file => return a=1/b=2
   *
   * @param basePath
   *          Start directory
   * @param allDirs
   *          This set will contain the leaf paths at the end.
   * @param maxDepth
   *          Specify how deep the search goes.
   * @throws IOException
   *           Thrown if we can't get lists from the fs.
   * @throws HiveException
   */
private void checkPartitionDirs(Path basePath, Set<Path> allDirs, int maxDepth) throws IOException, HiveException {
    // Here we just reuse the THREAD_COUNT configuration for
    // METASTORE_FS_HANDLER_THREADS_COUNT since this results in better performance
    // The number of missing partitions discovered are later added by metastore using a
    // threadpool of size METASTORE_FS_HANDLER_THREADS_COUNT. If we have different sized
    // pool here the smaller sized pool of the two becomes a bottleneck
    int poolSize = conf.getInt(ConfVars.METASTORE_FS_HANDLER_THREADS_COUNT.varname, 15);
    ExecutorService executor;
    if (poolSize <= 1) {
        LOG.debug("Using single-threaded version of MSCK-GetPaths");
        executor = MoreExecutors.sameThreadExecutor();
    } else {
        LOG.debug("Using multi-threaded version of MSCK-GetPaths with number of threads " + poolSize);
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("MSCK-GetPaths-%d").build();
        executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(poolSize, threadFactory);
    }
    checkPartitionDirs(executor, basePath, allDirs, basePath.getFileSystem(conf), maxDepth);
    executor.shutdown();
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder)

Aggregations

ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)530 ExecutorService (java.util.concurrent.ExecutorService)178 ThreadFactory (java.util.concurrent.ThreadFactory)164 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)80 IOException (java.io.IOException)68 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)59 ArrayList (java.util.ArrayList)51 Test (org.junit.Test)47 ExecutionException (java.util.concurrent.ExecutionException)46 Future (java.util.concurrent.Future)42 CountDownLatch (java.util.concurrent.CountDownLatch)38 List (java.util.List)35 Map (java.util.Map)34 HashMap (java.util.HashMap)32 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)32 TimeUnit (java.util.concurrent.TimeUnit)27 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)25 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)24 File (java.io.File)23 Executors (java.util.concurrent.Executors)22