Esempio n. 1
0
 /**
  * Sets up a PfShell in which Rultor can function.
  *
  * @return PfShell loaded with credentials for new Rultor runner container
  * @throws IOException on failure
  */
 public PfShell shell() throws IOException {
   final ExposedPort ssh = ExposedPort.tcp(22);
   final Ports ports = new Ports();
   ports.bind(ssh, Ports.Binding(null));
   final CreateContainerResponse container =
       this.client
           .createContainerCmd(this.build())
           .withExposedPorts(ssh)
           .withPortBindings(ports)
           .exec();
   this.containers.add(container);
   this.client.startContainerCmd(container.getId()).exec();
   return new PfShell(
       this.profile,
       this.client.infoCmd().exec().getName(),
       this.client
           .inspectContainerCmd(container.getId())
           .exec()
           .getNetworkSettings()
           .getPorts()
           .getBindings()
           .values()
           .iterator()
           .next()[0]
           .getHostPort(),
       "root",
       this.key(container));
 }
  @Test
  public void info() throws DockerException {
    // Make sure that there is at least one container for the assertion
    // TODO extract this into a shared method
    if (dockerClient.listContainersCmd().withShowAll(true).exec().size() == 0) {
      CreateContainerResponse container =
          dockerClient
              .createContainerCmd("busybox")
              .withName("docker-java-itest-info")
              .withCmd("touch", "/test")
              .exec();

      LOG.info("Created container: {}", container);
      assertThat(container.getId(), not(isEmptyOrNullString()));

      dockerClient.startContainerCmd(container.getId()).exec();
    }

    Info dockerInfo = dockerClient.infoCmd().exec();
    LOG.info(dockerInfo.toString());

    assertTrue(dockerInfo.toString().contains("containers"));
    assertTrue(dockerInfo.toString().contains("images"));
    assertTrue(dockerInfo.toString().contains("debug"));

    assertTrue(dockerInfo.getContainers() > 0);
    assertTrue(dockerInfo.getImages() > 0);
    assertTrue(dockerInfo.getNFd() > 0);
    assertTrue(dockerInfo.getNGoroutines() > 0);
    assertTrue(dockerInfo.getNCPU() > 0);
  }
Esempio n. 3
0
 @Override
 public void close() throws IOException {
   for (final CreateContainerResponse container : this.containers) {
     this.client.killContainerCmd(container.getId()).exec();
     this.client.removeContainerCmd(container.getId()).exec();
   }
   this.client.close();
 }
  @Test()
  public void inspectContainer() throws DockerException {

    String containerName = "generated_" + new SecureRandom().nextInt();

    CreateContainerResponse container =
        dockerClient.createContainerCmd("busybox").withCmd("top").withName(containerName).exec();
    LOG.info("Created container {}", container.toString());
    assertThat(container.getId(), not(isEmptyString()));

    InspectContainerResponse containerInfo =
        dockerClient.inspectContainerCmd(container.getId()).exec();
    assertEquals(containerInfo.getId(), container.getId());
  }
  @Test
  public void inspectContainerRestartCount() throws DockerException {

    CreateContainerResponse container =
        dockerClient.createContainerCmd("busybox").withCmd("env").exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(isEmptyString()));

    InspectContainerResponse inspectContainerResponse =
        dockerClient.inspectContainerCmd(container.getId()).exec();

    assertThat(inspectContainerResponse.getRestartCount(), equalTo(0));
  }
  @Test
  public void inspectContainerNetworkSettings() throws DockerException {

    CreateContainerResponse container =
        dockerClient.createContainerCmd("busybox").withCmd("env").exec();

    LOG.info("Created container {}", container.toString());

    assertThat(container.getId(), not(isEmptyString()));

    InspectContainerResponse inspectContainerResponse =
        dockerClient.inspectContainerCmd(container.getId()).exec();

    assertFalse(inspectContainerResponse.getNetworkSettings().getHairpinMode());
  }
  public StellarDocker() {
    dockerClient = DockerClientBuilder.getInstance("unix:///var/run/docker.sock").build();
    cleanup.addStep(dockerClient::close);

    dockerClient
        .pullImageCmd(STELLAR_DOCKER_IMAGE)
        .exec(new PullImageResultCallback())
        .awaitSuccess();

    try {
      final CreateContainerResponse container =
          dockerClient
              .createContainerCmd(STELLAR_DOCKER_IMAGE)
              .withAttachStderr(false)
              .withAttachStdin(false)
              .withAttachStdout(false)
              .withPortBindings(new PortBinding(new Ports.Binding(), ExposedPort.tcp(HORIZON_PORT)))
              .withName(STELLAR_CONTAINER_NAME)
              .exec();
      cleanup.addStep(
          () -> {
            try {
              dockerClient.removeContainerCmd(container.getId()).exec();
            } catch (final DockerException e) {
              /* Do nothing.  Don't inhibit further cleanup.*/
            }
          });
    } catch (final ConflictException e) {
      // the container is already created.
    }

    try {
      dockerClient.startContainerCmd(STELLAR_CONTAINER_NAME).exec();

      cleanup.addStep(
          () -> {
            try {
              dockerClient.stopContainerCmd(STELLAR_CONTAINER_NAME).exec();
            } catch (final DockerException e) {
              /* Do nothing.  Don't inhibit further cleanup.*/
            }
          });
    } catch (final NotModifiedException e) {
      // the container is already running.
    }
  }
Esempio n. 8
0
 /**
  * Retrieves SSH private key needed to connect to a given container.
  *
  * @param container Container from which to get the SSH key
  * @return SSH private key
  * @throws IOException on failure
  */
 private String key(final CreateContainerResponse container) throws IOException {
   final StringWriter writer = new StringWriter();
   IOUtils.copy(
       this.client.copyFileFromContainerCmd(container.getId(), "/root/.ssh/id_rsa").exec(),
       writer);
   final String key = writer.toString();
   return key.substring(key.indexOf('-'), key.lastIndexOf('-') + 1);
 }
  @Test(groups = "ignoreInCircleCi")
  public void testStopContainer() throws DockerException {
    final RemoteApiVersion apiVersion = getVersion(dockerClient);

    CreateContainerResponse container =
        dockerClient.createContainerCmd("busybox").withCmd("sleep", "9999").exec();
    LOG.info("Created container: {}", container.toString());
    assertThat(container.getId(), not(isEmptyString()));
    dockerClient.startContainerCmd(container.getId()).exec();

    LOG.info("Stopping container: {}", container.getId());
    dockerClient.stopContainerCmd(container.getId()).withTimeout(2).exec();

    InspectContainerResponse inspectContainerResponse =
        dockerClient.inspectContainerCmd(container.getId()).exec();
    LOG.info("Container Inspect: {}", inspectContainerResponse.toString());

    assertThat(inspectContainerResponse.getState().getRunning(), is(equalTo(false)));

    final Integer exitCode = inspectContainerResponse.getState().getExitCode();
    if (apiVersion.equals(VERSION_1_22)) {
      assertThat(exitCode, is(0));
    } else {
      assertThat(exitCode, not(0));
    }
  }
Esempio n. 10
0
 /**
  * create a new container from a image, and run it after build completed
  *
  * @param image
  * @param name
  * @param cmd
  * @param ports
  */
 public void create(String image, String name, String cmd, String ports) {
   DockerClient cli = docker.getDockerClient();
   if (cli == null) return;
   CreateContainerCmd ccc = cli.createContainerCmd(image);
   ccc.withName(name);
   if (cmd != null && !"".equals(cmd)) ccc.withCmd(cmd);
   CreateContainerResponse ccr = ccc.exec();
   String id = ccr.getId();
   StartContainerCmd scc = cli.startContainerCmd(id);
   Ports portBindings = new Ports();
   String[] portPairs = ports.split(" ");
   for (String portPair : portPairs) {
     String[] localHost = portPair.split(":");
     if (localHost.length != 2) continue;
     ExposedPort ep = new ExposedPort("tcp", Integer.valueOf(localHost[0]));
     Binding binding = new Binding(Integer.valueOf(localHost[1]));
     portBindings.bind(ep, binding);
   }
   scc.withPortBindings(portBindings);
   scc.exec();
 }
  public boolean createContainer(InstanceStartRequest request, InstanceStartResponse response) {
    logger.info(String.format("begin createContainer: %s", request));

    String imageId = request.getImageId();
    String containerId;
    try {
      // 1. create cmd
      CreateContainerCmd containerCmd = dockerClient.createContainerCmd(imageId);

      // 2. invoke post processor before create container
      CreateContainerContext createContainerContext =
          buildCreateContainerContext(request, containerCmd);
      applyCreateContainerProcessorsBeforeCreate(createContainerContext);

      // 3. exec cmd
      CreateContainerResponse createContainerResponse = containerCmd.exec();

      // 4. invoke post processor after create container
      applyCreateContainerProcessorsAfterCreate(createContainerContext);

      containerId = createContainerResponse.getId();
      request.setContainerId(containerId);

      if (containerId == null) {
        response.fail("create container failed, created containerId is null!");
      } else {
        response.success();
      }
    } catch (Exception e) {
      response.fail(e.toString());
      logger.error(String.format("error createContainer: %s", request), e);
    }

    logger.info(String.format("end createContainer: %s", response));

    return response.isSuccess();
  }
  @Test(groups = "ignoreInCircleCi")
  public void removeContainer() throws DockerException {

    CreateContainerResponse container =
        dockerClient.createContainerCmd("busybox").withCmd("true").exec();

    dockerClient.startContainerCmd(container.getId()).exec();
    dockerClient
        .waitContainerCmd(container.getId())
        .exec(new WaitContainerResultCallback())
        .awaitStatusCode();

    LOG.info("Removing container: {}", container.getId());
    dockerClient.removeContainerCmd(container.getId()).exec();

    List<Container> containers2 = dockerClient.listContainersCmd().withShowAll(true).exec();

    Matcher matcher = not(hasItem(hasField("id", startsWith(container.getId()))));
    assertThat(containers2, matcher);
  }
  @Test
  public void testWaitContainer() throws DockerException {

    CreateContainerResponse container =
        dockerClient.createContainerCmd("busybox").withCmd("true").exec();

    LOG.info("Created container: {}", container.toString());
    assertThat(container.getId(), not(isEmptyString()));

    dockerClient.startContainerCmd(container.getId()).exec();

    int exitCode = dockerClient.waitContainerCmd(container.getId()).exec();
    LOG.info("Container exit code: {}", exitCode);

    assertThat(exitCode, equalTo(0));

    InspectContainerResponse inspectContainerResponse =
        dockerClient.inspectContainerCmd(container.getId()).exec();
    LOG.info("Container Inspect: {}", inspectContainerResponse.toString());

    assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(false)));
    assertThat(inspectContainerResponse.getState().getExitCode(), is(equalTo(exitCode)));
  }
Esempio n. 14
0
  @POST
  public Response createContainer(
      @FormParam("containerName") String containerName,
      @FormParam("userId") String userId,
      @FormParam("cmd") String cmd,
      @FormParam("imageName") String imageName)
      throws HibernateException {
    DockerClient dockerClient = MyDockerClient.getDockerClient();
    try {
      String[] cmdarr = {};
      if (!("".equals(cmd) || cmd == null)) cmdarr = cmd.split(" ");
      CreateContainerResponse ccResponse =
          dockerClient
              .createContainerCmd(imageName)
              .withName(containerName)
              .withTty(true)
              .withStdinOpen(true)
              .withCmd(cmdarr)
              .exec();
      System.out.println("have created" + ccResponse.toString());
      List<Container> containers = dockerClient.listContainersCmd().withShowAll(true).exec();
      String fullNameString = null;
      for (int i = 0; i < containers.size(); i++) {
        if (containers.get(i).getId().equals(ccResponse.getId())) {
          fullNameString = containers.get(i).getNames()[0];
          System.out.println("find it" + fullNameString);
        }
      }
      String hostName = fullNameString.split("/")[1];
      // Map<String, String> mes = new HashMap<String, String>();
      // mes.put("id", ccResponse.getId());
      // mes.put("assignHost", hostName);
      model.Container con =
          new model.Container(
              containerName, Integer.valueOf(userId), imageName, ccResponse.getId(), hostName);
      beginTransaction();
      Serializable s = session.save(con);

      endTransaction(true);
      System.out.println(s);

      return ParseToReponse.parse("1", "createContainer successfully", "id:" + s, 0);
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
      return ParseToReponse.parse("1", e.getMessage(), "id:", 0);
    }

    // String queryString = "from Image where name=?";
    // beginTransaction();
    // Query query = session.createQuery(queryString);
    // query.setParameter(0, imageFullNname);
    // List<Image> image1 = query.list();
    // if(image1.size()>0){
    // beginTransaction();
    // Image Image2 = (Image) session.load(Image.class,
    // image1.get(0).getId());
    // session.delete(Image2);
    // endTransaction(true);
    // }

    // Image image = new Image(imageFullNname, Integer.valueOf(isPublic),
    // Integer.valueOf(userId), imageLongId);
    // beginTransaction();
    // Serializable s = session.save(image);
    // endTransaction(true);
    // System.out.println(s);

  }