com.github.dockerjava.api.model.Frame Java Examples

The following examples show how to use com.github.dockerjava.api.model.Frame. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContainerLogs.java    From OpenLabeler with Apache License 2.0 7 votes vote down vote up
public List<String> getDockerLogs() {

        final List<String> logs = new ArrayList<>();

        LogContainerCmd logContainerCmd = dockerClient.logContainerCmd(containerId);
        logContainerCmd.withStdOut(true).withStdErr(true);
        logContainerCmd.withSince( lastLogTime );  // UNIX timestamp (integer) to filter logs. Specifying a timestamp will only output log-entries since that timestamp.
        // logContainerCmd.withTail(4);  // get only the last 4 log entries

        logContainerCmd.withTimestamps(true);

        try {
            logContainerCmd.exec(new LogContainerResultCallback() {
                @Override
                public void onNext(Frame item) {
                    logs.add(item.toString());
                }
            }).awaitCompletion();
        } catch (InterruptedException e) {
            LOG.severe("Interrupted Exception!" + e.getMessage());
        }

        lastLogTime = (int) (System.currentTimeMillis() / 1000) + 5;  // assumes at least a 5 second wait between calls to getDockerLogs

        return logs;
    }
 
Example #2
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void passRawFrameWithoutColors() throws TimeoutException, IOException {
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    WaitingConsumer waitConsumer = new WaitingConsumer();
    callback.addConsumer(OutputType.STDOUT, waitConsumer);
    callback.onNext(new Frame(StreamType.RAW, FRAME_PAYLOAD.getBytes()));
    waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("Test2"), 1, TimeUnit.SECONDS);
    waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("Тест1"), 1, TimeUnit.SECONDS);
    Exception exception = null;
    try {
        waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("Test3"), 1, TimeUnit.SECONDS);
    } catch (Exception e) {
        exception = e;
    }
    assertTrue(exception instanceof TimeoutException);
    callback.close();
    waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("Test3"), 1, TimeUnit.SECONDS);
}
 
Example #3
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void passRawFrameWithColors() throws TimeoutException, IOException {
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    WaitingConsumer waitConsumer = new WaitingConsumer().withRemoveAnsiCodes(false);
    callback.addConsumer(OutputType.STDOUT, waitConsumer);
    callback.onNext(new Frame(StreamType.RAW, FRAME_PAYLOAD.getBytes()));
    waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("\u001B[1;33mTest2\u001B[0m"), 1, TimeUnit.SECONDS);
    waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("\u001B[0;32mТест1\u001B[0m"), 1, TimeUnit.SECONDS);
    Exception exception = null;
    try {
        waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("\u001B[0;31mTest3\u001B[0m"), 1, TimeUnit.SECONDS);
    } catch (Exception e) {
        exception = e;
    }
    assertTrue(exception instanceof TimeoutException);
    callback.close();
    waitConsumer.waitUntil(frame -> frame.getType() == OutputType.STDOUT && frame.getUtf8String().equals("\u001B[0;31mTest3\u001B[0m"), 1, TimeUnit.SECONDS);
}
 
Example #4
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void reconstructBreakedUnicode() throws IOException {
    String payload = "Тест";
    byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);
    byte[] bytes1 = new byte[(int) (payloadBytes.length * 0.6)];
    byte[] bytes2 = new byte[payloadBytes.length - bytes1.length];
    System.arraycopy(payloadBytes, 0, bytes1, 0, bytes1.length);
    System.arraycopy(payloadBytes, bytes1.length, bytes2, 0, bytes2.length);
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false);
    callback.addConsumer(OutputType.STDOUT, consumer);
    callback.onNext(new Frame(StreamType.RAW, bytes1));
    callback.onNext(new Frame(StreamType.RAW, bytes2));
    callback.close();
    assertEquals(payload, consumer.toUtf8String());
}
 
Example #5
Source File: DefaultInvocationBuilder.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public void post(Object entity, InputStream stdin, ResultCallback<Frame> resultCallback) {
    final DockerHttpClient.Request request;
    try {
        request = requestBuilder
            .method(DockerHttpClient.Request.Method.POST)
            .putHeader("content-type", "application/json")
            .body(new ByteArrayInputStream(objectMapper.writeValueAsBytes(entity)))
            .hijackedInput(stdin)
            .build();
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }

    executeAndStream(
        request,
        resultCallback,
        new FramedInputStreamConsumer(resultCallback)
    );
}
 
Example #6
Source File: FrameConsumerResultCallback.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Override
public void onNext(Frame frame) {
    if (frame != null) {
        OutputFrame outputFrame = OutputFrame.forFrame(frame);
        if (outputFrame != null) {
            Consumer<OutputFrame> consumer = consumers.get(outputFrame.getType());
            if (consumer == null) {
                LOGGER.error("got frame with type {}, for which no handler is configured", frame.getStreamType());
            } else if (outputFrame.getBytes() != null && outputFrame.getBytes().length > 0) {
                if (frame.getStreamType() == StreamType.RAW) {
                    processRawFrame(outputFrame, consumer);
                } else {
                    processOtherFrame(outputFrame, consumer);
                }
            }
        }
    }
}
 
Example #7
Source File: AttachContainerCmdExec.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
protected Void execute0(AttachContainerCmd command, ResultCallback<Frame> resultCallback) {

    WebTarget webTarget = getBaseResource().path("/containers/{id}/attach").resolveTemplate("id",
            command.getContainerId());

    webTarget = booleanQueryParam(webTarget, "logs", command.hasLogsEnabled());
    webTarget = booleanQueryParam(webTarget, "stdout", command.hasStdoutEnabled());
    webTarget = booleanQueryParam(webTarget, "stderr", command.hasStderrEnabled());
    webTarget = booleanQueryParam(webTarget, "stdin", command.getStdin() != null);
    webTarget = booleanQueryParam(webTarget, "stream", command.hasFollowStreamEnabled());

    LOGGER.trace("POST: {}", webTarget);

    webTarget.request().post(null, command.getStdin(), resultCallback);

    return null;
}
 
Example #8
Source File: LogContainerCmdExec.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
protected Void execute0(LogContainerCmd command, ResultCallback<Frame> resultCallback) {

    WebTarget webTarget = getBaseResource().path("/containers/{id}/logs").resolveTemplate("id",
            command.getContainerId());

    if (command.getTail() != null) {
        webTarget = webTarget.queryParam("tail", command.getTail());
    }

    if (command.getSince() != null) {
        webTarget = webTarget.queryParam("since", command.getSince());
    }

    webTarget = booleanQueryParam(webTarget, "timestamps", command.hasTimestampsEnabled());
    webTarget = booleanQueryParam(webTarget, "stdout", command.hasStdoutEnabled());
    webTarget = booleanQueryParam(webTarget, "stderr", command.hasStderrEnabled());
    webTarget = booleanQueryParam(webTarget, "follow", command.hasFollowStreamEnabled());

    LOGGER.trace("GET: {}", webTarget);

    webTarget.request().get(resultCallback);

    return null;
}
 
Example #9
Source File: DockerContainersUtil.java    From minimesos with Apache License 2.0 6 votes vote down vote up
/**
 * Synchronized method for returning logs of docker container
 *
 * @param containerId - ID of the container ot lookup logs
 * @return list of strings, where every string is log line
 */
public static List<String> getDockerLogs(String containerId) {

    final List<String> logs = new ArrayList<>();

    LogContainerCmd logContainerCmd = DockerClientFactory.build().logContainerCmd(containerId);
    logContainerCmd.withStdOut(true).withStdErr(true);
    try {
        logContainerCmd.exec(new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                logs.add(item.toString());
            }
        }).awaitCompletion();
    } catch (InterruptedException e) {
        throw new MinimesosException("Failed to retrieve logs of container " + containerId, e);
    }

    return logs;
}
 
Example #10
Source File: ChaosContainer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public String getContainerLog() {
    StringBuilder sb = new StringBuilder();

    LogContainerCmd logContainerCmd = this.dockerClient.logContainerCmd(containerId);
    logContainerCmd.withStdOut(true).withStdErr(true);
    try {
        logContainerCmd.exec(new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                sb.append(new String(item.getPayload(), UTF_8));
            }
        }).awaitCompletion();
    } catch (InterruptedException e) {

    }
    return sb.toString();
}
 
Example #11
Source File: ChaosContainer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public void tailContainerLog() {
    CompletableFuture.runAsync(() -> {
        while (null == containerId) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                return;
            }
        }

        LogContainerCmd logContainerCmd = this.dockerClient.logContainerCmd(containerId);
        logContainerCmd.withStdOut(true).withStdErr(true).withFollowStream(true);
        logContainerCmd.exec(new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                log.info(new String(item.getPayload(), UTF_8));
            }
        });
    });
}
 
Example #12
Source File: LogSwarmObjectExec.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
protected Void execute0(LogSwarmObjectCmd command, ResultCallback<Frame> resultCallback) {

    WebTarget webTarget = getBaseResource().path("/" + endpoint + "/{id}/logs").resolveTemplate("id", command.getId());

    if (command.getTail() != null) {
        webTarget = webTarget.queryParam("tail", command.getTail());
    } else {
        webTarget = webTarget.queryParam("tail", "all");
    }

    if (command.getSince() != null) {
        webTarget = webTarget.queryParam("since", command.getSince());
    }

    webTarget = booleanQueryParam(webTarget, "timestamps", command.getTimestamps());
    webTarget = booleanQueryParam(webTarget, "stdout", command.getStdout());
    webTarget = booleanQueryParam(webTarget, "stderr", command.getStderr());
    webTarget = booleanQueryParam(webTarget, "follow", command.getFollow());

    LOGGER.trace("GET: {}", webTarget);

    webTarget.request().get(resultCallback);

    return null;
}
 
Example #13
Source File: FrameReaderITest.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void canCloseFrameReaderAndReadExpectedLines() throws Exception {
    assumeNotSwarm("", dockerClient);

    // wait for the container to be successfully executed
    int exitCode = dockerClient.waitContainerCmd(dockerfileFixture.getContainerId())
            .start().awaitStatusCode();
    assertEquals(0, exitCode);

    final List<Frame> loggingFrames = getLoggingFrames();
    final Frame outFrame = new Frame(StreamType.STDOUT, "to stdout\n".getBytes());
    final Frame errFrame = new Frame(StreamType.STDERR, "to stderr\n".getBytes());
    
    assertThat(loggingFrames, containsInAnyOrder(outFrame, errFrame));
    assertThat(loggingFrames, hasSize(2));
}
 
Example #14
Source File: FrameReaderITest.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void canLogInOneThreadAndExecuteCommandsInAnother() throws Exception {

    Thread thread = new Thread(() -> {
        try {
            Iterator<Frame> frames = getLoggingFrames().iterator();

            while (frames.hasNext()) {
                frames.next();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });

    thread.start();

    try (DockerfileFixture busyboxDockerfile = new DockerfileFixture(dockerClient, "busyboxDockerfile")) {
        busyboxDockerfile.open();
    }

    thread.join();

}
 
Example #15
Source File: OutputFrame.java    From testcontainers-java with MIT License 5 votes vote down vote up
public static OutputFrame forFrame(Frame frame) {
    OutputType outputType = OutputType.forStreamType(frame.getStreamType());
    if (outputType == null) {
        return null;
    }
    return new OutputFrame(outputType, frame.getPayload());
}
 
Example #16
Source File: LogContainerTestCallback.java    From elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(Frame frame) {
    try {
        log.append(IOUtils.toString(new ByteArrayInputStream(frame.getPayload()), "UTF-8"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void passStdoutEmptyLine() {
    String payload = "";
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false);
    callback.addConsumer(OutputType.STDOUT, consumer);
    callback.onNext(new Frame(StreamType.STDOUT, payload.getBytes()));
    assertEquals(payload, consumer.toUtf8String());
}
 
Example #18
Source File: BesuNode.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private void showLogFromBesuContainer() {
  docker
      .logContainerCmd(besuContainerId)
      .withStdOut(true)
      .withStdErr(true)
      .withFollowStream(true)
      .withTail(500)
      .exec(
          new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
              LOG.info(item.toString());
            }
          });
}
 
Example #19
Source File: StreamLog.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(Frame item) {
    try {
        lines.put(new String(item.getPayload(), UTF_8));
    } catch (InterruptedException e) {
        currentThread().interrupt();
    }
}
 
Example #20
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void passStdoutSingleLine() {
    String payload = "Test";
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false);
    callback.addConsumer(OutputType.STDOUT, consumer);
    callback.onNext(new Frame(StreamType.STDOUT, payload.getBytes()));
    assertEquals(payload, consumer.toUtf8String());
}
 
Example #21
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void passStdoutNull() {
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false);
    callback.addConsumer(OutputType.STDOUT, consumer);
    callback.onNext(new Frame(StreamType.STDOUT, null));
    assertEquals("", consumer.toUtf8String());
}
 
Example #22
Source File: StreamLogTest.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGiveAStreamContainingLineOfFrameFromOtherThread()
    throws ExecutionException, InterruptedException {
    CountDownLatch streamStarted = new CountDownLatch(1);
    executor.submit(() -> streamLog.onNext(new Frame(StreamType.RAW, "added line".getBytes(UTF_8))));
    Future<?> streamCompleted = executor.submit(completeStreamOnceStarted(streamStarted));
    assertThat(streamLog.stream().peek((l) -> streamStarted.countDown())).contains("added line");
    assertExecutionOf(streamCompleted::get).hasNoAssertionFailures();
}
 
Example #23
Source File: FrameConsumerResultCallbackTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void passStdoutSingleLineWithNewline() {
    String payload = "Test\n";
    FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false);
    callback.addConsumer(OutputType.STDOUT, consumer);
    callback.onNext(new Frame(StreamType.STDOUT, payload.getBytes()));
    assertEquals(payload, consumer.toUtf8String());
}
 
Example #24
Source File: ExecStartResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(Frame frame) {
    if (frame != null) {
        try {
            switch (frame.getStreamType()) {
                case STDOUT:
                case RAW:
                    if (stdout != null) {
                        stdout.write(frame.getPayload());
                        stdout.flush();
                    }
                    break;
                case STDERR:
                    if (stderr != null) {
                        stderr.write(frame.getPayload());
                        stderr.flush();
                    }
                    break;
                default:
                    LOGGER.error("unknown stream type:" + frame.getStreamType());
            }
        } catch (IOException e) {
            onError(e);
        }

        LOGGER.debug(frame.toString());
    }
}
 
Example #25
Source File: DefaultInvocationBuilder.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void get(ResultCallback<Frame> resultCallback) {
    DockerHttpClient.Request request = requestBuilder
        .method(DockerHttpClient.Request.Method.GET)
        .build();

    executeAndStream(
        request,
        resultCallback,
        new FramedInputStreamConsumer(resultCallback)
    );
}
 
Example #26
Source File: AttachContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void attachContainerWithoutTTY() throws Exception {
    DockerClient dockerClient = dockerRule.getClient();

    String snippet = "hello world";

    CreateContainerResponse container = dockerClient.createContainerCmd(DEFAULT_IMAGE)
            .withCmd("echo", snippet)
            .withTty(false)
            .exec();

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

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

    AttachContainerTestCallback callback = new AttachContainerTestCallback() {
        @Override
        public void onNext(Frame frame) {
            assertThat(frame.getStreamType(), equalTo(StreamType.STDOUT));
            super.onNext(frame);
        };
    };

    dockerClient.attachContainerCmd(container.getId())
            .withStdErr(true)
            .withStdOut(true)
            .withFollowStream(true)
            .withLogs(true)
            .exec(callback)
            .awaitCompletion(30, TimeUnit.SECONDS);
    callback.close();

    assertThat(callback.toString(), containsString(snippet));
}
 
Example #27
Source File: AttachContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void attachContainerWithTTY() throws Exception {
    DockerClient dockerClient = dockerRule.getClient();

    File baseDir = new File(Thread.currentThread().getContextClassLoader()
            .getResource("attachContainerTestDockerfile").getFile());

    String imageId = dockerRule.buildImage(baseDir);

    CreateContainerResponse container = dockerClient.createContainerCmd(imageId).withTty(true).exec();

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

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

    AttachContainerTestCallback callback = new AttachContainerTestCallback() {
        @Override
        public void onNext(Frame frame) {
            assertThat(frame.getStreamType(), equalTo(StreamType.RAW));
            super.onNext(frame);
        };
    };

    dockerClient.attachContainerCmd(container.getId())
            .withStdErr(true)
            .withStdOut(true)
            .withFollowStream(true)
            .exec(callback)
            .awaitCompletion(15, TimeUnit.SECONDS);
    callback.close();

    LOG.debug("log: {}", callback.toString());

    // HexDump.dump(collectFramesCallback.toString().getBytes(), 0, System.out, 0);
    assertThat(callback.toString(), containsString("stdout\r\nstderr"));
}
 
Example #28
Source File: AttachContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void attachContainerStdinUnsupported() throws Exception {

    DockerClient dockerClient = dockerRule.getClient();
    Assume.assumeFalse("does not support stdin attach", getFactoryType().supportsStdinAttach());
    expectedException.expect(UnsupportedOperationException.class);

    String snippet = "hello world";

    CreateContainerResponse container = dockerClient.createContainerCmd(DEFAULT_IMAGE)
            .withCmd("echo", snippet)
            .withTty(false)
            .exec();

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

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

    AttachContainerTestCallback callback = new AttachContainerTestCallback() {
        @Override
        public void onNext(Frame frame) {
            assertThat(frame.getStreamType(), equalTo(StreamType.STDOUT));
            super.onNext(frame);
        };
    };

    InputStream stdin = new ByteArrayInputStream("".getBytes());

    dockerClient.attachContainerCmd(container.getId())
            .withStdErr(true)
            .withStdOut(true)
            .withFollowStream(true)
            .withLogs(true)
            .withStdIn(stdin)
            .exec(callback)
            .awaitCompletion(30, TimeUnit.SECONDS);
    callback.close();
}
 
Example #29
Source File: ExecStartCmdExec.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
protected Void execute0(ExecStartCmd command, ResultCallback<Frame> resultCallback) {
    WebTarget webTarget = getBaseResource().path("/exec/{id}/start").resolveTemplate("id", command.getExecId());

    webTarget.request().accept(MediaType.APPLICATION_JSON).post(command, command.getStdin(), resultCallback);

    return null;
}
 
Example #30
Source File: FrameReaderITest.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private List<Frame> getLoggingFrames() throws Exception {

        FrameReaderITestCallback collectFramesCallback = new FrameReaderITestCallback();

        dockerClient.logContainerCmd(dockerfileFixture.getContainerId()).withStdOut(true).withStdErr(true)
                .withTailAll()
                // we can't follow stream here as it blocks reading from resulting InputStream infinitely
                // .withFollowStream()
                .exec(collectFramesCallback).awaitCompletion();

        return collectFramesCallback.frames;
    }