<commit_before>/*
 * Copyright (c) 2012-2017 Red Hat, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.workspace.infrastructure.docker;

import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.FAILED;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.RUNNING;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.STARTING;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.STOPPED;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.che.api.core.model.workspace.runtime.MachineStatus;
import org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity;
import org.eclipse.che.api.core.notification.EventService;
import org.eclipse.che.api.installer.server.model.impl.InstallerImpl;
import org.eclipse.che.api.workspace.server.DtoConverter;
import org.eclipse.che.api.workspace.server.hc.ServersChecker;
import org.eclipse.che.api.workspace.server.hc.ServersCheckerFactory;
import org.eclipse.che.api.workspace.server.model.impl.RuntimeIdentityImpl;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.spi.InternalEnvironment;
import org.eclipse.che.api.workspace.server.spi.InternalMachineConfig;
import org.eclipse.che.api.workspace.server.spi.RuntimeStartInterruptedException;
import org.eclipse.che.api.workspace.shared.dto.event.MachineStatusEvent;
import org.eclipse.che.dto.server.DtoFactory;
import org.eclipse.che.workspace.infrastructure.docker.bootstrap.DockerBootstrapper;
import org.eclipse.che.workspace.infrastructure.docker.bootstrap.DockerBootstrapperFactory;
import org.eclipse.che.workspace.infrastructure.docker.logs.MachineLoggersFactory;
import org.eclipse.che.workspace.infrastructure.docker.model.DockerContainerConfig;
import org.eclipse.che.workspace.infrastructure.docker.model.DockerEnvironment;
import org.eclipse.che.workspace.infrastructure.docker.monit.AbnormalMachineStopHandler;
import org.eclipse.che.workspace.infrastructure.docker.network.NetworkLifecycle;
import org.eclipse.che.workspace.infrastructure.docker.registry.DockerRegistryClient;
import org.eclipse.che.workspace.infrastructure.docker.server.mapping.ExternalIpURLRewriter;
import org.eclipse.che.workspace.infrastructure.docker.snapshot.SnapshotDao;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * Tests {@link DockerInternalRuntime}.
 *
 * @author <NAME>
 */
public class DockerInternalRuntimeTest {

  private static final RuntimeIdentity IDENTITY = new RuntimeIdentityImpl("ws1", "env1", "usr1");
  private static final String DEV_MACHINE = "DEV_MACHINE";
  private static final String DB_MACHINE = "DB_MACHINE";

  @Mock private DockerBootstrapperFactory bootstrapperFactory;
  @Mock private DockerRuntimeContext runtimeContext;
  @Mock private EventService eventService;
  @Mock private DockerMachineStarter starter;
  @Mock private NetworkLifecycle networks;
  @Mock private DockerBootstrapper bootstrapper;

  @Captor private ArgumentCaptor<MachineStatusEvent> eventCaptor;

  private DockerInternalRuntime dockerRuntime;

  @BeforeMethod
  public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    final DockerContainerConfig config1 = new DockerContainerConfig();
    final DockerContainerConfig config2 = new DockerContainerConfig();
    final DockerEnvironment environment = new DockerEnvironment();
    final InternalMachineConfig internalMachineCfg1 = mock(InternalMachineConfig.class);
    when(internalMachineCfg1.getInstallers()).thenReturn(singletonList(newInstaller(1)));
    final InternalMachineConfig internalMachineCfg2 = mock(InternalMachineConfig.class);
    when(internalMachineCfg2.getInstallers()).thenReturn(singletonList(newInstaller(2)));
    environment.setContainers(ImmutableMap.of(DEV_MACHINE, config1, DB_MACHINE, config2));

    doNothing().when(networks).createNetwork(nullable(String.class));
    when(runtimeContext.getIdentity()).thenReturn(IDENTITY);
    when(runtimeContext.getDockerEnvironment()).thenReturn(environment);
    final LinkedList<String> orderedContainers = new LinkedList<>();
    orderedContainers.add(DEV_MACHINE);
    orderedContainers.add(DB_MACHINE);
    when(runtimeContext.getOrderedContainers()).thenReturn(orderedContainers);
    InternalEnvironment internalEnvironment = mock(InternalEnvironment.class);
    when(runtimeContext.getEnvironment()).thenReturn(internalEnvironment);
    when(internalEnvironment.getMachines())
        .thenReturn(
            ImmutableMap.of(DEV_MACHINE, internalMachineCfg1, DB_MACHINE, internalMachineCfg2));
    ServersCheckerFactory serversCheckerFactory = mock(ServersCheckerFactory.class);
    when(serversCheckerFactory.create(any(), nullable(String.class), any()))
        .thenReturn(mock(ServersChecker.class));
    dockerRuntime =
        new DockerInternalRuntime(
            runtimeContext,
            mock(ExternalIpURLRewriter.class),
            networks,
            starter,
            mock(SnapshotDao.class),
            mock(DockerRegistryClient.class),
            eventService,
            bootstrapperFactory,
            serversCheckerFactory,
            mock(MachineLoggersFactory.class));
  }

  @Test
  public void startsDockerRuntimeAndPropagatesMachineStatusEvents() throws Exception {
    mockInstallersBootstrap();
    mockContainerStart();
    dockerRuntime.start(emptyMap());

    verify(starter, times(2))
        .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
    verify(eventService, times(4)).publish(any(MachineStatusEvent.class));
    verifyEventsOrder(
        newEvent(DEV_MACHINE, STARTING, null),
        newEvent(DEV_MACHINE, RUNNING, null),
        newEvent(DB_MACHINE, STARTING, null),
        newEvent(DB_MACHINE, RUNNING, null));
  }

  @Test(expectedExceptions = InfrastructureException.class)
  public void throwsExceptionWhenOneMachineStartFailed() throws Exception {
    final String msg = "container start failed";
    mockInstallersBootstrap();
    mockContainerStartFailed(new InfrastructureException(msg));

    try {
      dockerRuntime.start(emptyMap());
    } catch (InfrastructureException ex) {
      verify(starter, times(1))
          .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
      verify(eventService, times(2)).publish(any(MachineStatusEvent.class));
      verifyEventsOrder(newEvent(DEV_MACHINE, STARTING, null), newEvent(DEV_MACHINE, FAILED, msg));
      throw ex;
    }
  }

  @Test(expectedExceptions = InfrastructureException.class)
  public void throwsExceptionWhenBootstrappingOfInstallersFailed() throws Exception {
    mockInstallersBootstrapFailed(new InfrastructureException("bootstrap failed"));
    mockContainerStart();
    try {
      dockerRuntime.start(emptyMap());
    } catch (InfrastructureException ex) {
      verify(starter, times(1))
          .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
      verify(bootstrapper, times(1)).bootstrap();
      verify(eventService, times(3)).publish(any(MachineStatusEvent.class));
      verifyEventsOrder(
          newEvent(DEV_MACHINE, STARTING, null),
          newEvent(DEV_MACHINE, FAILED, "bootstrap failed"),
          newEvent(DEV_MACHINE, STOPPED, null));
      throw ex;
    }
  }

  @Test(expectedExceptions = RuntimeStartInterruptedException.class)
  public void throwsInterruptionExceptionWhenNetworkCreationInterrupted() throws Exception {
    doThrow(RuntimeStartInterruptedException.class)
        .when(networks)
        .createNetwork(nullable(String.class));

    try {
      dockerRuntime.start(emptyMap());
    } catch (InfrastructureException ex) {
      verify(starter, never())
          .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());<commit_msg>RuntimeStartInterruptedException is a checked exception that can't be thrown by createNetwork method It is reported with new version of Mockito<commit_after>/*
 * Copyright (c) 2012-2017 Red Hat, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.workspace.infrastructure.docker;

import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.FAILED;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.RUNNING;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.STARTING;
import static org.eclipse.che.api.core.model.workspace.runtime.MachineStatus.STOPPED;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.che.api.core.model.workspace.runtime.MachineStatus;
import org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity;
import org.eclipse.che.api.core.notification.EventService;
import org.eclipse.che.api.installer.server.model.impl.InstallerImpl;
import org.eclipse.che.api.workspace.server.DtoConverter;
import org.eclipse.che.api.workspace.server.hc.ServersChecker;
import org.eclipse.che.api.workspace.server.hc.ServersCheckerFactory;
import org.eclipse.che.api.workspace.server.model.impl.RuntimeIdentityImpl;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.spi.InternalEnvironment;
import org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException;
import org.eclipse.che.api.workspace.server.spi.InternalMachineConfig;
import org.eclipse.che.api.workspace.server.spi.RuntimeStartInterruptedException;
import org.eclipse.che.api.workspace.shared.dto.event.MachineStatusEvent;
import org.eclipse.che.dto.server.DtoFactory;
import org.eclipse.che.workspace.infrastructure.docker.bootstrap.DockerBootstrapper;
import org.eclipse.che.workspace.infrastructure.docker.bootstrap.DockerBootstrapperFactory;
import org.eclipse.che.workspace.infrastructure.docker.logs.MachineLoggersFactory;
import org.eclipse.che.workspace.infrastructure.docker.model.DockerContainerConfig;
import org.eclipse.che.workspace.infrastructure.docker.model.DockerEnvironment;
import org.eclipse.che.workspace.infrastructure.docker.monit.AbnormalMachineStopHandler;
import org.eclipse.che.workspace.infrastructure.docker.network.NetworkLifecycle;
import org.eclipse.che.workspace.infrastructure.docker.registry.DockerRegistryClient;
import org.eclipse.che.workspace.infrastructure.docker.server.mapping.ExternalIpURLRewriter;
import org.eclipse.che.workspace.infrastructure.docker.snapshot.SnapshotDao;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * Tests {@link DockerInternalRuntime}.
 *
 * @author <NAME>
 */
public class DockerInternalRuntimeTest {

  private static final RuntimeIdentity IDENTITY = new RuntimeIdentityImpl("ws1", "env1", "usr1");
  private static final String DEV_MACHINE = "DEV_MACHINE";
  private static final String DB_MACHINE = "DB_MACHINE";

  @Mock private DockerBootstrapperFactory bootstrapperFactory;
  @Mock private DockerRuntimeContext runtimeContext;
  @Mock private EventService eventService;
  @Mock private DockerMachineStarter starter;
  @Mock private NetworkLifecycle networks;
  @Mock private DockerBootstrapper bootstrapper;

  @Captor private ArgumentCaptor<MachineStatusEvent> eventCaptor;

  private DockerInternalRuntime dockerRuntime;

  @BeforeMethod
  public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    final DockerContainerConfig config1 = new DockerContainerConfig();
    final DockerContainerConfig config2 = new DockerContainerConfig();
    final DockerEnvironment environment = new DockerEnvironment();
    final InternalMachineConfig internalMachineCfg1 = mock(InternalMachineConfig.class);
    when(internalMachineCfg1.getInstallers()).thenReturn(singletonList(newInstaller(1)));
    final InternalMachineConfig internalMachineCfg2 = mock(InternalMachineConfig.class);
    when(internalMachineCfg2.getInstallers()).thenReturn(singletonList(newInstaller(2)));
    environment.setContainers(ImmutableMap.of(DEV_MACHINE, config1, DB_MACHINE, config2));

    doNothing().when(networks).createNetwork(nullable(String.class));
    when(runtimeContext.getIdentity()).thenReturn(IDENTITY);
    when(runtimeContext.getDockerEnvironment()).thenReturn(environment);
    final LinkedList<String> orderedContainers = new LinkedList<>();
    orderedContainers.add(DEV_MACHINE);
    orderedContainers.add(DB_MACHINE);
    when(runtimeContext.getOrderedContainers()).thenReturn(orderedContainers);
    InternalEnvironment internalEnvironment = mock(InternalEnvironment.class);
    when(runtimeContext.getEnvironment()).thenReturn(internalEnvironment);
    when(internalEnvironment.getMachines())
        .thenReturn(
            ImmutableMap.of(DEV_MACHINE, internalMachineCfg1, DB_MACHINE, internalMachineCfg2));
    ServersCheckerFactory serversCheckerFactory = mock(ServersCheckerFactory.class);
    when(serversCheckerFactory.create(any(), nullable(String.class), any()))
        .thenReturn(mock(ServersChecker.class));
    dockerRuntime =
        new DockerInternalRuntime(
            runtimeContext,
            mock(ExternalIpURLRewriter.class),
            networks,
            starter,
            mock(SnapshotDao.class),
            mock(DockerRegistryClient.class),
            eventService,
            bootstrapperFactory,
            serversCheckerFactory,
            mock(MachineLoggersFactory.class));
  }

  @Test
  public void startsDockerRuntimeAndPropagatesMachineStatusEvents() throws Exception {
    mockInstallersBootstrap();
    mockContainerStart();
    dockerRuntime.start(emptyMap());

    verify(starter, times(2))
        .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
    verify(eventService, times(4)).publish(any(MachineStatusEvent.class));
    verifyEventsOrder(
        newEvent(DEV_MACHINE, STARTING, null),
        newEvent(DEV_MACHINE, RUNNING, null),
        newEvent(DB_MACHINE, STARTING, null),
        newEvent(DB_MACHINE, RUNNING, null));
  }

  @Test(expectedExceptions = InfrastructureException.class)
  public void throwsExceptionWhenOneMachineStartFailed() throws Exception {
    final String msg = "container start failed";
    mockInstallersBootstrap();
    mockContainerStartFailed(new InfrastructureException(msg));

    try {
      dockerRuntime.start(emptyMap());
    } catch (InfrastructureException ex) {
      verify(starter, times(1))
          .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
      verify(eventService, times(2)).publish(any(MachineStatusEvent.class));
      verifyEventsOrder(newEvent(DEV_MACHINE, STARTING, null), newEvent(DEV_MACHINE, FAILED, msg));
      throw ex;
    }
  }

  @Test(expectedExceptions = InfrastructureException.class)
  public void throwsExceptionWhenBootstrappingOfInstallersFailed() throws Exception {
    mockInstallersBootstrapFailed(new InfrastructureException("bootstrap failed"));
    mockContainerStart();
    try {
      dockerRuntime.start(emptyMap());
    } catch (InfrastructureException ex) {
      verify(starter, times(1))
          .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
      verify(bootstrapper, times(1)).bootstrap();
      verify(eventService, times(3)).publish(any(MachineStatusEvent.class));
      verifyEventsOrder(
          newEvent(DEV_MACHINE, STARTING, null),
          newEvent(DEV_MACHINE, FAILED, "bootstrap failed"),
          newEvent(DEV_MACHINE, STOPPED, null));
      throw ex;
    }
  }

  @Test(expectedExceptions = InternalInfrastructureException.class)
  public void throwsInternalInfrastructureExceptionWhenNetworkCreationInterrupted()
      throws Exception {
    doThrow(InternalInfrastructureException.class)
        .when(networks)
        .createNetwork(nullable(String.class));

    try {
      dockerRuntime.start(emptyMap());
    } catch (InfrastructureException ex) {
      verify(starter, never())
          .startContainer(nullable(String.class), nullable(String.class), any(), any(), any());
{'fraction_non_alphanumeric': 0.10236644924801898, 'fraction_numerical': 0.0036655705891865667, 'mean_word_length': 5.261221734728316, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5112907', 'n_tokens_mistral': 5205, 'n_tokens_neox': 5116, 'n_words': 910}