Search in sources :

Example 1 with MachineLimitsImpl

use of org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl 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 MachineLimitsImpl

use of org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl in project che by eclipse.

the class CheEnvironmentEngineTest method shouldUseConfiguredInMachineRamInsteadOfSetDefaultOnMachineStart.

@Test
public void shouldUseConfiguredInMachineRamInsteadOfSetDefaultOnMachineStart() throws Exception {
    // given
    List<Instance> instances = startEnv();
    String workspaceId = instances.get(0).getWorkspaceId();
    when(engine.generateMachineId()).thenReturn("newMachineId");
    Instance newMachine = mock(Instance.class);
    when(newMachine.getId()).thenReturn("newMachineId");
    when(newMachine.getWorkspaceId()).thenReturn(workspaceId);
    when(machineProvider.startService(anyString(), anyString(), anyString(), anyString(), anyBoolean(), anyString(), any(CheServiceImpl.class), any(LineConsumer.class))).thenReturn(newMachine);
    MachineConfigImpl config = createConfig(false);
    String machineName = "extraMachine";
    config.setName(machineName);
    config.setLimits(new MachineLimitsImpl(4096));
    // when
    engine.startMachine(workspaceId, config, emptyList());
    // then
    ArgumentCaptor<CheServiceImpl> captor = ArgumentCaptor.forClass(CheServiceImpl.class);
    verify(machineProvider).startService(anyString(), anyString(), anyString(), eq(machineName), eq(false), anyString(), captor.capture(), any(LineConsumer.class));
    CheServiceImpl actualService = captor.getValue();
    assertEquals((long) actualService.getMemLimit(), 4096L * 1024L * 1024L);
}
Also used : LineConsumer(org.eclipse.che.api.core.util.LineConsumer) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) Instance(org.eclipse.che.api.machine.server.spi.Instance) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 3 with MachineLimitsImpl

use of org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl in project che by eclipse.

the class MachineProviderImpl method startService.

@Override
public Instance startService(String namespace, String workspaceId, String envName, String machineName, boolean isDev, String networkName, CheServiceImpl service, LineConsumer machineLogger) throws ServerException {
    // copy to not affect/be affected by changes in origin
    service = new CheServiceImpl(service);
    ProgressLineFormatterImpl progressLineFormatter = new ProgressLineFormatterImpl();
    ProgressMonitor progressMonitor = currentProgressStatus -> {
        try {
            machineLogger.writeLine(progressLineFormatter.format(currentProgressStatus));
        } catch (IOException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    };
    String container = null;
    try {
        String image = prepareImage(machineName, service, progressMonitor);
        container = createContainer(workspaceId, machineName, isDev, image, networkName, service);
        connectContainerToAdditionalNetworks(container, service);
        docker.startContainer(StartContainerParams.create(container));
        readContainerLogsInSeparateThread(container, workspaceId, service.getId(), machineLogger);
        DockerNode node = dockerMachineFactory.createNode(workspaceId, container);
        dockerInstanceStopDetector.startDetection(container, service.getId(), workspaceId);
        final String userId = EnvironmentContext.getCurrent().getSubject().getUserId();
        MachineImpl machine = new MachineImpl(MachineConfigImpl.builder().setDev(isDev).setName(machineName).setType("docker").setLimits(new MachineLimitsImpl((int) Size.parseSizeToMegabytes(service.getMemLimit() + "b"))).setSource(new MachineSourceImpl(service.getBuild() != null ? "context" : "image").setLocation(service.getBuild() != null ? service.getBuild().getContext() : service.getImage())).build(), service.getId(), workspaceId, envName, userId, MachineStatus.RUNNING, null);
        return dockerMachineFactory.createInstance(machine, container, image, node, machineLogger);
    } catch (SourceNotFoundException e) {
        throw e;
    } catch (RuntimeException | ServerException | NotFoundException | IOException e) {
        cleanUpContainer(container);
        throw new ServerException(e.getLocalizedMessage(), e);
    }
}
Also used : ConnectContainer(org.eclipse.che.plugin.docker.client.json.network.ConnectContainer) RemoveContainerParams(org.eclipse.che.plugin.docker.client.params.RemoveContainerParams) Arrays(java.util.Arrays) MachineStatus(org.eclipse.che.api.core.model.machine.MachineStatus) HostConfig(org.eclipse.che.plugin.docker.client.json.HostConfig) DockerConnectorProvider(org.eclipse.che.plugin.docker.client.DockerConnectorProvider) Volume(org.eclipse.che.plugin.docker.client.json.Volume) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) NewNetwork(org.eclipse.che.plugin.docker.client.json.network.NewNetwork) BuildImageParams(org.eclipse.che.plugin.docker.client.params.BuildImageParams) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) Thread.sleep(java.lang.Thread.sleep) NetworkingConfig(org.eclipse.che.plugin.docker.client.json.container.NetworkingConfig) LoggingUncaughtExceptionHandler(org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler) FileCleaner(org.eclipse.che.api.core.util.FileCleaner) Collectors.toSet(java.util.stream.Collectors.toSet) ProgressLineFormatterImpl(org.eclipse.che.plugin.docker.client.ProgressLineFormatterImpl) GetContainerLogsParams(org.eclipse.che.plugin.docker.client.params.GetContainerLogsParams) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) Set(java.util.Set) Nullable(org.eclipse.che.commons.annotation.Nullable) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) WindowsPathEscaper(org.eclipse.che.commons.lang.os.WindowsPathEscaper) ConnectContainerToNetworkParams(org.eclipse.che.plugin.docker.client.params.network.ConnectContainerToNetworkParams) List(java.util.List) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) TagParams(org.eclipse.che.plugin.docker.client.params.TagParams) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) Pattern(java.util.regex.Pattern) UserSpecificDockerRegistryCredentialsProvider(org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) PullParams(org.eclipse.che.plugin.docker.client.params.PullParams) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) EndpointConfig(org.eclipse.che.plugin.docker.client.json.network.EndpointConfig) ImageNotFoundException(org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException) Size(org.eclipse.che.commons.lang.Size) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) HashMap(java.util.HashMap) Function(java.util.function.Function) StartContainerParams(org.eclipse.che.plugin.docker.client.params.StartContainerParams) ArrayList(java.util.ArrayList) RemoveImageParams(org.eclipse.che.plugin.docker.client.params.RemoveImageParams) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor) LATEST_TAG(org.eclipse.che.plugin.docker.machine.DockerInstance.LATEST_TAG) CreateNetworkParams(org.eclipse.che.plugin.docker.client.params.network.CreateNetworkParams) PortBinding(org.eclipse.che.plugin.docker.client.json.PortBinding) SocketTimeoutException(java.net.SocketTimeoutException) MachineInstanceProvider(org.eclipse.che.api.environment.server.MachineInstanceProvider) Collections.singletonMap(java.util.Collections.singletonMap) Named(javax.inject.Named) Instance(org.eclipse.che.api.machine.server.spi.Instance) ExecutorService(java.util.concurrent.ExecutorService) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) Collections.emptyMap(java.util.Collections.emptyMap) Logger(org.slf4j.Logger) DockerNode(org.eclipse.che.plugin.docker.machine.node.DockerNode) Files(java.nio.file.Files) NetworkNotFoundException(org.eclipse.che.plugin.docker.client.exception.NetworkNotFoundException) FileWriter(java.io.FileWriter) MoreObjects(com.google.common.base.MoreObjects) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) IOException(java.io.IOException) SystemInfo(org.eclipse.che.api.core.util.SystemInfo) RemoveNetworkParams(org.eclipse.che.plugin.docker.client.params.RemoveNetworkParams) NotFoundException(org.eclipse.che.api.core.NotFoundException) File(java.io.File) ContainerNotFoundException(org.eclipse.che.plugin.docker.client.exception.ContainerNotFoundException) MachineSourceImpl(org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) ServerException(org.eclipse.che.api.core.ServerException) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) DockerConnector(org.eclipse.che.plugin.docker.client.DockerConnector) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) DockerNode(org.eclipse.che.plugin.docker.machine.node.DockerNode) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) ServerException(org.eclipse.che.api.core.ServerException) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) ProgressLineFormatterImpl(org.eclipse.che.plugin.docker.client.ProgressLineFormatterImpl) MachineSourceImpl(org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) ImageNotFoundException(org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException) NetworkNotFoundException(org.eclipse.che.plugin.docker.client.exception.NetworkNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ContainerNotFoundException(org.eclipse.che.plugin.docker.client.exception.ContainerNotFoundException) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) IOException(java.io.IOException) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor)

Example 4 with MachineLimitsImpl

use of org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl in project che by eclipse.

the class CheEnvironmentEngineTest method createMachine.

private static MachineImpl createMachine(String workspaceId, String envName, CheServiceImpl service, String serviceName, boolean isDev) {
    MachineSourceImpl machineSource;
    if (service.getBuild() != null && service.getBuild().getContext() != null) {
        machineSource = new MachineSourceImpl("dockerfile").setLocation(service.getBuild().getContext());
    } else if (service.getImage() != null) {
        machineSource = new MachineSourceImpl("image").setLocation(service.getImage());
    } else if (service.getBuild() != null && service.getBuild().getContext() == null && service.getBuild().getDockerfileContent() != null) {
        machineSource = new MachineSourceImpl("dockerfile").setContent(service.getBuild().getDockerfileContent());
    } else {
        throw new IllegalArgumentException("Build context or image should contain non empty value");
    }
    MachineLimitsImpl limits = new MachineLimitsImpl((int) Size.parseSizeToMegabytes(service.getMemLimit() + "b"));
    return MachineImpl.builder().setConfig(MachineConfigImpl.builder().setDev(isDev).setName(serviceName).setSource(machineSource).setLimits(limits).setType("docker").build()).setId(service.getId()).setOwner("userName").setStatus(MachineStatus.RUNNING).setWorkspaceId(workspaceId).setEnvName(envName).setRuntime(new MachineRuntimeInfoImpl(emptyMap(), emptyMap(), emptyMap())).build();
}
Also used : MachineRuntimeInfoImpl(org.eclipse.che.api.machine.server.model.impl.MachineRuntimeInfoImpl) MachineSourceImpl(org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl)

Example 5 with MachineLimitsImpl

use of org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl in project che by eclipse.

the class WorkspaceServiceTest method testWorkspaceLinks.

@Test
public void testWorkspaceLinks() throws Exception {
    // given
    final WorkspaceImpl workspace = createWorkspace(createConfigDto());
    EnvironmentImpl environment = workspace.getConfig().getEnvironments().get(workspace.getConfig().getDefaultEnv());
    assertNotNull(environment);
    final WorkspaceRuntimeImpl runtime = new WorkspaceRuntimeImpl(workspace.getConfig().getDefaultEnv(), null);
    MachineConfigImpl devMachineConfig = MachineConfigImpl.builder().setDev(true).setEnvVariables(emptyMap()).setServers(emptyList()).setLimits(new MachineLimitsImpl(1024)).setSource(new MachineSourceImpl("type").setContent("content")).setName(environment.getMachines().keySet().iterator().next()).setType("type").build();
    runtime.setDevMachine(new MachineImpl(devMachineConfig, "machine123", workspace.getId(), workspace.getConfig().getDefaultEnv(), USER_ID, MachineStatus.RUNNING, new MachineRuntimeInfoImpl(emptyMap(), emptyMap(), singletonMap("8080/https", new ServerImpl("wsagent", "https", "address", "url", new ServerPropertiesImpl("path", "internaladdress", "internalurl"))))));
    runtime.getMachines().add(runtime.getDevMachine());
    workspace.setStatus(RUNNING);
    workspace.setRuntime(runtime);
    when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace);
    // when
    final Response response = given().auth().basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD).when().get(SECURE_PATH + "/workspace/" + workspace.getId());
    // then
    assertEquals(response.getStatusCode(), 200);
    final WorkspaceDto workspaceDto = unwrapDto(response, WorkspaceDto.class);
    final Set<String> actualRels = workspaceDto.getLinks().stream().map(Link::getRel).collect(toSet());
    final Set<String> expectedRels = new HashSet<>(asList(LINK_REL_START_WORKSPACE, LINK_REL_REMOVE_WORKSPACE, GET_ALL_USER_WORKSPACES, LINK_REL_GET_SNAPSHOT, LINK_REL_GET_WORKSPACE_EVENTS_CHANNEL, LINK_REL_IDE_URL, LINK_REL_SELF, LINK_REL_ENVIRONMENT_OUTPUT_CHANNEL, LINK_REL_ENVIRONMENT_STATUS_CHANNEL));
    assertTrue(actualRels.equals(expectedRels), format("Links difference: '%s'. \n" + "Returned links: '%s', \n" + "Expected links: '%s'.", Sets.symmetricDifference(actualRels, expectedRels), actualRels.toString(), expectedRels.toString()));
    assertNotNull(workspaceDto.getRuntime().getLink(LINK_REL_STOP_WORKSPACE), "Runtime doesn't contain stop link");
    assertNotNull(workspaceDto.getRuntime().getLink(WSAGENT_REFERENCE), "Runtime doesn't contain wsagent link");
    assertNotNull(workspaceDto.getRuntime().getLink(WSAGENT_WEBSOCKET_REFERENCE), "Runtime doesn't contain wsagent.websocket link");
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) MachineSourceImpl(org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) WorkspaceRuntimeImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceRuntimeImpl) MachineLimitsImpl(org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl) WorkspaceDto(org.eclipse.che.api.workspace.shared.dto.WorkspaceDto) Matchers.anyString(org.mockito.Matchers.anyString) MachineRuntimeInfoImpl(org.eclipse.che.api.machine.server.model.impl.MachineRuntimeInfoImpl) Response(com.jayway.restassured.response.Response) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) ServerImpl(org.eclipse.che.api.machine.server.model.impl.ServerImpl) ServerPropertiesImpl(org.eclipse.che.api.machine.server.model.impl.ServerPropertiesImpl) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Aggregations

MachineLimitsImpl (org.eclipse.che.api.machine.server.model.impl.MachineLimitsImpl)5 MachineConfigImpl (org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl)4 LineConsumer (org.eclipse.che.api.core.util.LineConsumer)3 MachineSourceImpl (org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl)3 File (java.io.File)2 IOException (java.io.IOException)2 String.format (java.lang.String.format)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 Pattern (java.util.regex.Pattern)2 Inject (javax.inject.Inject)2 Named (javax.inject.Named)2 NotFoundException (org.eclipse.che.api.core.NotFoundException)2 ServerException (org.eclipse.che.api.core.ServerException)2 MachineStatus (org.eclipse.che.api.core.model.machine.MachineStatus)2 ServerConf (org.eclipse.che.api.core.model.machine.ServerConf)2 CheServiceImpl (org.eclipse.che.api.environment.server.model.CheServiceImpl)2 MachineImpl (org.eclipse.che.api.machine.server.model.impl.MachineImpl)2 MachineRuntimeInfoImpl (org.eclipse.che.api.machine.server.model.impl.MachineRuntimeInfoImpl)2