Search in sources :

Example 1 with InternalRuntime

use of org.eclipse.che.api.workspace.server.spi.InternalRuntime in project che-server by eclipse-che.

the class InconsistentRuntimesDetectorTest method shouldThrowExceptionIfNonK8sRuntimeIsReturnOnCheckingConsistency.

@Test(expectedExceptions = InfrastructureException.class, expectedExceptionsMessageRegExp = "Fetched internal runtime 'workspace1:owner1' is not Kubernetes, it is not possible to check consistency.")
public void shouldThrowExceptionIfNonK8sRuntimeIsReturnOnCheckingConsistency() throws Exception {
    // given
    InternalRuntime runtime = mock(InternalRuntime.class);
    when(runtime.getContext()).thenReturn(k8sContext);
    doReturn(runtime).when(workspaceRuntimes).getInternalRuntime("workspace1");
    // when
    inconsistentRuntimesDetector.checkOne("workspace1");
    // then
    verifyNoMoreInteractions(eventPublisher);
}
Also used : InternalRuntime(org.eclipse.che.api.workspace.server.spi.InternalRuntime) Test(org.testng.annotations.Test)

Example 2 with InternalRuntime

use of org.eclipse.che.api.workspace.server.spi.InternalRuntime in project che-server by eclipse-che.

the class WorkspaceRuntimes method recoverOne.

@VisibleForTesting
InternalRuntime<?> recoverOne(RuntimeInfrastructure infra, RuntimeIdentity identity) throws ServerException, ConflictException {
    if (isStartRefused.get()) {
        throw new ConflictException(format("Recovery of the workspace '%s' is rejected by the system, " + "no more workspaces are allowed to start", identity.getWorkspaceId()));
    }
    WorkspaceImpl workspace;
    try {
        workspace = workspaceDao.get(identity.getWorkspaceId());
    } catch (NotFoundException x) {
        throw new ServerException(format("Workspace configuration is missing for the runtime '%s:%s'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()));
    }
    Environment environment = null;
    WorkspaceConfigImpl workspaceConfig = workspace.getConfig();
    if (workspaceConfig == null) {
        workspaceConfig = devfileConverter.convert(workspace.getDevfile());
    }
    if (identity.getEnvName() != null) {
        environment = workspaceConfig.getEnvironments().get(identity.getEnvName());
        if (environment == null) {
            throw new ServerException(format("Environment configuration is missing for the runtime '%s:%s'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()));
        }
    }
    InternalRuntime runtime;
    try {
        InternalEnvironment internalEnv = createInternalEnvironment(environment, workspaceConfig.getAttributes(), workspaceConfig.getCommands(), workspaceConfig.getDevfile());
        runtime = infra.prepare(identity, internalEnv).getRuntime();
        WorkspaceStatus runtimeStatus = runtime.getStatus();
        try (Unlocker ignored = lockService.writeLock(workspace.getId())) {
            statuses.replace(identity.getWorkspaceId(), runtimeStatus);
            runtimes.putIfAbsent(identity.getWorkspaceId(), runtime);
        }
        LOG.info("Successfully recovered workspace runtime '{}'. Its status is '{}'", identity.getWorkspaceId(), runtimeStatus);
        return runtime;
    } catch (NotFoundException x) {
        LOG.warn("Not able to create internal environment for  '{}'. Reason: '{}'", identity.getWorkspaceId(), x.getMessage());
        try (Unlocker ignored = lockService.writeLock(identity.getWorkspaceId())) {
            runtimes.remove(identity.getWorkspaceId());
            statuses.remove(identity.getWorkspaceId());
        }
        publishWorkspaceStatusEvent(identity.getWorkspaceId(), STOPPED, STOPPING, "Workspace is stopped. Reason: " + x.getMessage(), false);
        throw new ServerException(format("Couldn't recover runtime '%s:%s'. Error: %s", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()));
    } catch (InfrastructureException | ValidationException x) {
        throw new ServerException(format("Couldn't recover runtime '%s:%s'. Error: %s", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()));
    }
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ServerException(org.eclipse.che.api.core.ServerException) ValidationException(org.eclipse.che.api.core.ValidationException) ConflictException(org.eclipse.che.api.core.ConflictException) NotFoundException(org.eclipse.che.api.core.NotFoundException) InternalRuntime(org.eclipse.che.api.workspace.server.spi.InternalRuntime) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) InternalEnvironment(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment) InternalEnvironment(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment) Environment(org.eclipse.che.api.core.model.workspace.config.Environment) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) InternalInfrastructureException(org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with InternalRuntime

use of org.eclipse.che.api.workspace.server.spi.InternalRuntime in project che-server by eclipse-che.

the class WorkspaceRuntimes method getInternalRuntime.

/**
 * Returns {@link InternalRuntime} implementation for workspace with the specified id.
 *
 * <p>If memory-storage does not contain internal runtime, then runtime will be recovered if it is
 * active. Otherwise, an exception will be thrown.
 *
 * @param workspaceId identifier of workspace to fetch runtime
 * @return {@link InternalRuntime} implementation for workspace with the specified id.
 * @throws InfrastructureException if any infrastructure exception occurs
 * @throws ServerException if there is no active runtime for the specified workspace
 * @throws ServerException if any other exception occurs
 */
public InternalRuntime<?> getInternalRuntime(String workspaceId) throws InfrastructureException, ServerException {
    try (Unlocker ignored = lockService.writeLock(workspaceId)) {
        InternalRuntime<?> runtime = runtimes.get(workspaceId);
        if (runtime == null) {
            try {
                final Optional<RuntimeIdentity> runtimeIdentity = infrastructure.getIdentities().stream().filter(id -> id.getWorkspaceId().equals(workspaceId)).findAny();
                if (runtimeIdentity.isPresent()) {
                    LOG.info("Runtime for workspace '{}' is requested but there is no cached one. Recovering it.", workspaceId);
                    runtime = recoverOne(infrastructure, runtimeIdentity.get());
                } else {
                    // runtime is not considered by Infrastructure as active
                    throw new ServerException("No active runtime is found");
                }
            } catch (ServerException e) {
                statuses.remove(workspaceId);
                throw e;
            } catch (UnsupportedOperationException | ConflictException e) {
                statuses.remove(workspaceId);
                throw new ServerException(e.getMessage(), e);
            }
        }
        return runtime;
    }
}
Also used : RuntimeIdentity(org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity) NamespaceResolutionContext(org.eclipse.che.api.workspace.server.spi.NamespaceResolutionContext) STOPPED_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.STOPPED_ATTRIBUTE_NAME) ThreadLocalPropagateContext(org.eclipse.che.commons.lang.concurrent.ThreadLocalPropagateContext) LoggerFactory(org.slf4j.LoggerFactory) PostConstruct(jakarta.annotation.PostConstruct) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) RUNNING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.RUNNING) RuntimeInfrastructure(org.eclipse.che.api.workspace.server.spi.RuntimeInfrastructure) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) InternalEnvironmentFactory(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironmentFactory) WorkspaceStatusEvent(org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent) InternalEnvironment(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment) Map(java.util.Map) DevfileConverter(org.eclipse.che.api.workspace.server.devfile.convert.DevfileConverter) WorkspaceDao(org.eclipse.che.api.workspace.server.spi.WorkspaceDao) Collectors.toSet(java.util.stream.Collectors.toSet) NameGenerator(org.eclipse.che.commons.lang.NameGenerator) EventService(org.eclipse.che.api.core.notification.EventService) Command(org.eclipse.che.api.core.model.workspace.config.Command) ImmutableSet(com.google.common.collect.ImmutableSet) RuntimeContext(org.eclipse.che.api.workspace.server.spi.RuntimeContext) RuntimeAbnormalStoppingEvent(org.eclipse.che.api.workspace.server.event.RuntimeAbnormalStoppingEvent) ImmutableMap(com.google.common.collect.ImmutableMap) Collections.emptyList(java.util.Collections.emptyList) EventSubscriber(org.eclipse.che.api.core.notification.EventSubscriber) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) String.format(java.lang.String.format) STOPPED_ABNORMALLY_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.STOPPED_ABNORMALLY_ATTRIBUTE_NAME) Sets(com.google.common.collect.Sets) RuntimeImpl(org.eclipse.che.api.workspace.server.model.impl.RuntimeImpl) Nullable(org.eclipse.che.commons.annotation.Nullable) RuntimeStartInterruptedException(org.eclipse.che.api.workspace.server.spi.RuntimeStartInterruptedException) STARTING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STARTING) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) List(java.util.List) RuntimeIdentityImpl(org.eclipse.che.api.workspace.server.model.impl.RuntimeIdentityImpl) TracingTags(org.eclipse.che.commons.tracing.TracingTags) RuntimeIdentity(org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity) WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE(org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE) Entry(java.util.Map.Entry) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) STOPPED(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPED) Workspace(org.eclipse.che.api.core.model.workspace.Workspace) STOPPING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPING) System.currentTimeMillis(java.lang.System.currentTimeMillis) CommandImpl(org.eclipse.che.api.workspace.server.model.impl.CommandImpl) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Singleton(javax.inject.Singleton) Traced(org.eclipse.che.commons.annotation.Traced) ValidationException(org.eclipse.che.api.core.ValidationException) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) Inject(javax.inject.Inject) CHE_DEVWORKSPACES_ENABLED_PROPERTY(org.eclipse.che.api.workspace.shared.Constants.CHE_DEVWORKSPACES_ENABLED_PROPERTY) WORKSPACE_STOPPED_BY(org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_STOPPED_BY) InternalInfrastructureException(org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ERROR_MESSAGE_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.ERROR_MESSAGE_ATTRIBUTE_NAME) Subject(org.eclipse.che.commons.subject.Subject) ConflictException(org.eclipse.che.api.core.ConflictException) DevfileImpl(org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl) Named(javax.inject.Named) DBInitializer(org.eclipse.che.core.db.DBInitializer) DtoFactory(org.eclipse.che.dto.server.DtoFactory) ProbeScheduler(org.eclipse.che.api.workspace.server.hc.probe.ProbeScheduler) InternalRuntime(org.eclipse.che.api.workspace.server.spi.InternalRuntime) Collections.emptyMap(java.util.Collections.emptyMap) Logger(org.slf4j.Logger) RuntimeAbnormalStoppedEvent(org.eclipse.che.api.workspace.server.event.RuntimeAbnormalStoppedEvent) Constants(org.eclipse.che.api.workspace.shared.Constants) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) SetView(com.google.common.collect.Sets.SetView) WORKSPACE_STOP_REASON(org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_STOP_REASON) Environment(org.eclipse.che.api.core.model.workspace.config.Environment) NotFoundException(org.eclipse.che.api.core.NotFoundException) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) WORKSPACE_RUNTIMES_ID_ATTRIBUTE(org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_RUNTIMES_ID_ATTRIBUTE) ServerException(org.eclipse.che.api.core.ServerException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker)

Example 4 with InternalRuntime

use of org.eclipse.che.api.workspace.server.spi.InternalRuntime in project devspaces-images by redhat-developer.

the class InconsistentRuntimesDetectorTest method shouldThrowExceptionIfNonK8sRuntimeIsReturnOnCheckingConsistency.

@Test(expectedExceptions = InfrastructureException.class, expectedExceptionsMessageRegExp = "Fetched internal runtime 'workspace1:owner1' is not Kubernetes, it is not possible to check consistency.")
public void shouldThrowExceptionIfNonK8sRuntimeIsReturnOnCheckingConsistency() throws Exception {
    // given
    InternalRuntime runtime = mock(InternalRuntime.class);
    when(runtime.getContext()).thenReturn(k8sContext);
    doReturn(runtime).when(workspaceRuntimes).getInternalRuntime("workspace1");
    // when
    inconsistentRuntimesDetector.checkOne("workspace1");
    // then
    verifyNoMoreInteractions(eventPublisher);
}
Also used : InternalRuntime(org.eclipse.che.api.workspace.server.spi.InternalRuntime) Test(org.testng.annotations.Test)

Example 5 with InternalRuntime

use of org.eclipse.che.api.workspace.server.spi.InternalRuntime in project devspaces-images by redhat-developer.

the class WorkspaceRuntimes method startAsync.

/**
 * Starts all machines from specified workspace environment, creates workspace runtime instance
 * based on that environment.
 *
 * <p>During the start of the workspace its runtime is visible with {@link
 * WorkspaceStatus#STARTING} status.
 *
 * @param workspace workspace which environment should be started
 * @param envName optional environment name to run
 * @param options whether machines should be recovered(true) or not(false)
 * @return completable future of start execution.
 * @throws ConflictException when workspace is already running
 * @throws ConflictException when start is interrupted
 * @throws NotFoundException when any not found exception occurs during environment start
 * @throws ServerException other error occurs during environment start
 * @see WorkspaceStatus#STARTING
 * @see WorkspaceStatus#RUNNING
 */
@Traced
public CompletableFuture<Void> startAsync(WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException {
    TracingTags.WORKSPACE_ID.set(workspace.getId());
    final String workspaceId = workspace.getId();
    if (isStartRefused.get()) {
        throw new ConflictException(format("Start of the workspace '%s' is rejected by the system, " + "no more workspaces are allowed to start", workspace.getName()));
    }
    WorkspaceConfigImpl config = workspace.getConfig();
    if (config == null) {
        config = devfileConverter.convert(workspace.getDevfile());
    }
    if (envName == null) {
        envName = config.getDefaultEnv();
    }
    String infraNamespace = workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE);
    if (isNullOrEmpty(infraNamespace)) {
        throw new ServerException(String.format("Workspace does not have infrastructure namespace " + "specified. Please set value of '%s' workspace attribute.", WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE));
    }
    final RuntimeIdentity runtimeId = new RuntimeIdentityImpl(workspaceId, envName, EnvironmentContext.getCurrent().getSubject().getUserId(), infraNamespace);
    try {
        InternalEnvironment internalEnv = createInternalEnvironment(config.getEnvironments().get(envName), config.getAttributes(), config.getCommands(), config.getDevfile());
        RuntimeContext runtimeContext = infrastructure.prepare(runtimeId, internalEnv);
        InternalRuntime runtime = runtimeContext.getRuntime();
        try (Unlocker ignored = lockService.writeLock(workspaceId)) {
            final WorkspaceStatus existingStatus = statuses.putIfAbsent(workspaceId, STARTING);
            if (existingStatus != null) {
                throw new ConflictException(format("Could not start workspace '%s' because its state is '%s'", workspaceId, existingStatus));
            }
            setRuntimesId(workspaceId);
            runtimes.put(workspaceId, runtime);
        }
        LOG.info("Starting workspace '{}/{}' with id '{}' by user '{}'", workspace.getNamespace(), workspace.getName(), workspace.getId(), sessionUserNameOr("undefined"));
        publishWorkspaceStatusEvent(workspaceId, STARTING, STOPPED, null, true, options);
        return CompletableFuture.runAsync(ThreadLocalPropagateContext.wrap(new StartRuntimeTask(workspace, options, runtime)), sharedPool.getExecutor());
    } catch (ValidationException e) {
        LOG.error(e.getLocalizedMessage(), e);
        throw new ConflictException(e.getLocalizedMessage());
    } catch (InfrastructureException e) {
        LOG.error(e.getLocalizedMessage(), e);
        throw new ServerException(e.getLocalizedMessage(), e);
    }
}
Also used : ServerException(org.eclipse.che.api.core.ServerException) ValidationException(org.eclipse.che.api.core.ValidationException) ConflictException(org.eclipse.che.api.core.ConflictException) InternalRuntime(org.eclipse.che.api.workspace.server.spi.InternalRuntime) RuntimeIdentity(org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) InternalEnvironment(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) RuntimeContext(org.eclipse.che.api.workspace.server.spi.RuntimeContext) RuntimeIdentityImpl(org.eclipse.che.api.workspace.server.model.impl.RuntimeIdentityImpl) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) InternalInfrastructureException(org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException) Traced(org.eclipse.che.commons.annotation.Traced)

Aggregations

InternalRuntime (org.eclipse.che.api.workspace.server.spi.InternalRuntime)10 ConflictException (org.eclipse.che.api.core.ConflictException)6 ServerException (org.eclipse.che.api.core.ServerException)6 ValidationException (org.eclipse.che.api.core.ValidationException)6 WorkspaceStatus (org.eclipse.che.api.core.model.workspace.WorkspaceStatus)6 RuntimeIdentity (org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity)6 RuntimeIdentityImpl (org.eclipse.che.api.workspace.server.model.impl.RuntimeIdentityImpl)6 WorkspaceConfigImpl (org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl)6 WorkspaceImpl (org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl)6 InfrastructureException (org.eclipse.che.api.workspace.server.spi.InfrastructureException)6 InternalInfrastructureException (org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException)6 RuntimeContext (org.eclipse.che.api.workspace.server.spi.RuntimeContext)6 InternalEnvironment (org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment)6 Unlocker (org.eclipse.che.commons.lang.concurrent.Unlocker)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 NotFoundException (org.eclipse.che.api.core.NotFoundException)4 Environment (org.eclipse.che.api.core.model.workspace.config.Environment)4 Traced (org.eclipse.che.commons.annotation.Traced)4 MoreObjects.firstNonNull (com.google.common.base.MoreObjects.firstNonNull)2