use of org.eclipse.che.api.environment.server.exception.EnvironmentException in project che by eclipse.
the class CheEnvironmentEngine method startInstance.
private Instance startInstance(boolean recover, MessageConsumer<MachineLogMessage> environmentLogger, MachineImpl machine, MachineStarter machineStarter) throws ServerException, EnvironmentException {
LineConsumer machineLogger = null;
Instance instance = null;
try {
addMachine(machine);
eventService.publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.CREATING).withDev(machine.getConfig().isDev()).withMachineName(machine.getConfig().getName()).withMachineId(machine.getId()).withWorkspaceId(machine.getWorkspaceId()));
machineLogger = getMachineLogger(environmentLogger, machine.getId(), machine.getConfig().getName());
MachineImpl originMachine = new MachineImpl(machine);
try {
MachineSourceImpl machineSource = null;
if (recover) {
try {
SnapshotImpl snapshot = snapshotDao.getSnapshot(machine.getWorkspaceId(), machine.getEnvName(), machine.getConfig().getName());
machineSource = snapshot.getMachineSource();
// Snapshot image location has SHA-256 digest which needs to be removed,
// otherwise it will be pulled without tag and cause problems
String imageName = machineSource.getLocation();
if (imageName.contains("@sha256:")) {
machineSource.setLocation(imageName.substring(0, imageName.indexOf('@')));
}
} catch (NotFoundException e) {
try {
machineLogger.writeLine("Failed to boot machine from snapshot: snapshot not found. " + "Machine will be created from origin source.");
} catch (IOException ignore) {
}
}
}
instance = machineStarter.startMachine(machineLogger, machineSource);
} catch (SourceNotFoundException e) {
if (recover) {
LOG.error("Image of snapshot for machine " + machine.getConfig().getName() + " not found. " + "Machine will be created from origin source.");
machine = originMachine;
instance = machineStarter.startMachine(machineLogger, null);
} else {
throw e;
}
}
replaceMachine(instance);
eventService.publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.RUNNING).withDev(machine.getConfig().isDev()).withMachineName(machine.getConfig().getName()).withMachineId(instance.getId()).withWorkspaceId(machine.getWorkspaceId()));
return instance;
} catch (ApiException | RuntimeException e) {
boolean interrupted = Thread.interrupted();
removeMachine(machine.getWorkspaceId(), machine.getId());
if (instance != null) {
try {
instance.destroy();
} catch (Exception destroyingExc) {
LOG.error(destroyingExc.getLocalizedMessage(), destroyingExc);
}
}
if (machineLogger != null) {
try {
machineLogger.writeLine("[ERROR] " + e.getLocalizedMessage());
} catch (IOException ioEx) {
LOG.error(ioEx.getLocalizedMessage(), ioEx);
}
try {
machineLogger.close();
} catch (IOException ioEx) {
LOG.error(ioEx.getLocalizedMessage(), ioEx);
}
}
eventService.publish(newDto(MachineStatusEvent.class).withEventType(MachineStatusEvent.EventType.ERROR).withDev(machine.getConfig().isDev()).withMachineName(machine.getConfig().getName()).withMachineId(machine.getId()).withWorkspaceId(machine.getWorkspaceId()));
if (interrupted) {
Thread.currentThread().interrupt();
}
throw new ServerException(e.getLocalizedMessage(), e);
}
}
use of org.eclipse.che.api.environment.server.exception.EnvironmentException 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);
}
}
}
use of org.eclipse.che.api.environment.server.exception.EnvironmentException in project che by eclipse.
the class WorkspaceRuntimes method startEnvironmentAndPublishEvents.
/**
* Starts the environment publishing all the necessary events.
* Respects task interruption & stops the workspace if starting task is cancelled.
*/
private void startEnvironmentAndPublishEvents(EnvironmentImpl environment, String workspaceId, String envName, boolean recover) throws ServerException, EnvironmentException, ConflictException {
try {
envEngine.start(workspaceId, envName, environment, recover, new WebsocketMessageConsumer<>(format(ENVIRONMENT_OUTPUT_CHANNEL_TEMPLATE, workspaceId)), machineAgentsLauncher);
} catch (EnvironmentStartInterruptedException x) {
// environment start was interrupted, it's either shutdown or direct stop
// in the case of shutdown make sure the status is correct,
// otherwise workspace is already stopping
compareAndSetStatus(workspaceId, WorkspaceStatus.STARTING, WorkspaceStatus.STOPPING);
removeStateAndPublishStopEvents(workspaceId);
throw x;
} catch (EnvironmentException | ServerException | ConflictException x) {
// environment can't be started for some reason, STARTING -> STOPPED
removeState(workspaceId);
eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class).withWorkspaceId(workspaceId).withEventType(EventType.ERROR).withPrevStatus(WorkspaceStatus.STARTING).withStatus(WorkspaceStatus.STOPPED).withError("Start of environment '" + envName + "' failed. Error: " + x.getMessage()));
throw x;
}
// disallow direct start cancellation, STARTING -> RUNNING
WorkspaceStatus prevStatus;
try (@SuppressWarnings("unused") Unlocker u = locks.writeLock(workspaceId)) {
checkIsNotTerminated("finish workspace start");
RuntimeState state = states.get(workspaceId);
prevStatus = state.status;
if (state.status == WorkspaceStatus.STARTING) {
state.status = WorkspaceStatus.RUNNING;
state.startTask = null;
state.startFuture = null;
}
}
// or stop is called directly, anyway stop the environment
if (Thread.interrupted() || prevStatus != WorkspaceStatus.STARTING) {
try {
stopEnvironmentAndPublishEvents(workspaceId, WorkspaceStatus.STARTING);
} catch (Exception x) {
LOG.error("Couldn't stop the environment '{}' of the workspace '{}'. Error: {}", envName, workspaceId, x.getMessage());
}
throw new EnvironmentStartInterruptedException(workspaceId, envName);
}
// normally started, notify clients
eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class).withWorkspaceId(workspaceId).withStatus(WorkspaceStatus.RUNNING).withEventType(EventType.RUNNING).withPrevStatus(WorkspaceStatus.STARTING));
}
use of org.eclipse.che.api.environment.server.exception.EnvironmentException in project che by eclipse.
the class LocalCheInfrastructureProvisioner method provision.
@Override
public void provision(EnvironmentImpl envConfig, CheServicesEnvironmentImpl internalEnv) throws EnvironmentException {
String devMachineName = getDevMachineName(envConfig);
if (devMachineName == null) {
throw new EnvironmentException("ws-machine is not found on agents applying");
}
CheServiceImpl devMachine = internalEnv.getServices().get(devMachineName);
for (CheServiceImpl machine : internalEnv.getServices().values()) {
ArrayList<String> volumes = new ArrayList<>(machine.getVolumes());
volumes.add(terminalVolumeProvider.get());
machine.setVolumes(volumes);
}
// add bind-mount volume for projects in a workspace
String projectFolderVolume;
try {
projectFolderVolume = format("%s:%s%s", workspaceFolderPathProvider.getPath(internalEnv.getWorkspaceId()), projectFolderPath, projectsVolumeOptions);
} catch (IOException e) {
throw new EnvironmentException("Error occurred on resolving path to files of workspace " + internalEnv.getWorkspaceId());
}
List<String> devMachineVolumes = devMachine.getVolumes();
devMachineVolumes.add(SystemInfo.isWindows() ? pathEscaper.escapePath(projectFolderVolume) : projectFolderVolume);
// add volume with ws-agent archive
devMachineVolumes.add(wsAgentVolumeProvider.get());
// add volume and variable to setup ws-agent configuration
String dockerExtConfVolume = dockerExtConfBindingProvider.get();
if (dockerExtConfVolume != null) {
devMachineVolumes.add(dockerExtConfVolume);
}
HashMap<String, String> environmentVars = new HashMap<>(devMachine.getEnvironment());
environmentVars.put(CheBootstrap.CHE_LOCAL_CONF_DIR, DockerExtConfBindingProvider.EXT_CHE_LOCAL_CONF_DIR);
devMachine.setEnvironment(environmentVars);
// apply basic infra (e.g. agents)
super.provision(envConfig, internalEnv);
}
use of org.eclipse.che.api.environment.server.exception.EnvironmentException in project che by eclipse.
the class WorkspaceRuntimesTest method failsWorkspaceStartWhenEnvironmentStartIsFailed.
@Test
public void failsWorkspaceStartWhenEnvironmentStartIsFailed() throws Exception {
WorkspaceImpl workspace = newWorkspace("workspace", "env-name");
rejectEnvironmentStart(workspace, "env-name", new EnvironmentException("no no no!"));
CompletableFuture<WorkspaceRuntimeImpl> cmpFuture = runtimes.startAsync(workspace, "env-name", false);
try {
captureAsyncTaskAndExecuteSynchronously();
} catch (EnvironmentException x) {
assertEquals(x.getMessage(), "no no no!");
verifyCompletionException(cmpFuture, EnvironmentException.class, "no no no!");
}
assertFalse(runtimes.hasRuntime(workspace.getId()));
verifyEventsSequence(event("workspace", WorkspaceStatus.STOPPED, WorkspaceStatus.STARTING, EventType.STARTING, null), event("workspace", WorkspaceStatus.STARTING, WorkspaceStatus.STOPPED, EventType.ERROR, "Start of environment 'env-name' failed. Error: no no no!"));
}
Aggregations