io.fabric8.kubernetes.client.dsl.ExecWatch Java Examples

The following examples show how to use io.fabric8.kubernetes.client.dsl.ExecWatch. 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: ContainerExecEndpoint.java    From apollo with Apache License 2.0 7 votes vote down vote up
@OnOpen
public void onOpen(Session session, @PathParam("podName") String podName, @PathParam("containerName") String containerName) {
    int environmentId = StringParser.getIntFromQueryString(session.getQueryString(), QUERY_STRING_ENVIRONMENT_KEY);
    int serviceId = StringParser.getIntFromQueryString(session.getQueryString(), QUERY_STRING_SERVICE_KEY);

    Environment environment = environmentDao.getEnvironment(environmentId);
    Service service = serviceDao.getService(serviceId);

    // Get default shell
    String defaultShell = Optional.ofNullable(service.getDefaultShell()).orElse("/bin/bash");

    KubernetesHandler kubernetesHandler = kubernetesHandlerStore.getOrCreateKubernetesHandler(environment);

    logger.info("Opening ExecWatch to container {} in pod {} in environment {} related to service {}",
            containerName, podName, environment.getName(), service.getName());

    ExecWatch execWatch = kubernetesHandler.getExecWatch(podName, containerName,defaultShell);
    ExecutorService executor = Executors.newFixedThreadPool(2);

    SessionExecModel sessionExecModel = new SessionExecModel(execWatch, executor);
    openReaderThreads(session, sessionExecModel);

    // Initialize the ExecWatch against kubernetes handler
    execWebSocketSessionStore.addSession(session, sessionExecModel);
}
 
Example #2
Source File: ArquillianTest.java    From kubernetes-integration-test with Apache License 2.0 6 votes vote down vote up
private void loadSql() throws Exception{
    // Run command in container using OpenShiftClient java client - run sql in mysql
    log.info("Sql load - start");
    final CountDownLatch latch = new CountDownLatch(1);
    OutputStream execOut = new ByteArrayOutputStream();
    OutputStream execErr = new ByteArrayOutputStream();
    ExecWatch exec = oc.pods().withName("mariadb")
            .readingInput(this.getClass().getClassLoader().getResourceAsStream("sql/sql-load.sql"))
            .writingOutput(execOut)
            .writingError(execErr)
            //.withTTY() //Optional
            .usingListener(createCountDownListener(latch))
            .exec("/opt/rh/rh-mariadb102/root/usr/bin/mysql","-u", "myuser", "-pmypassword", "-h", "127.0.0.1", "testdb")
            ;
    if (!latch.await(20, TimeUnit.SECONDS)) {
        throw new Exception("Exec timeout");
    }
    log.info("Exec out: {}", ((ByteArrayOutputStream) execOut).toString());
    log.info("Exec err: {}", ((ByteArrayOutputStream) execErr).toString());
    log.info("Sql load - end");
}
 
Example #3
Source File: ContainerExecEndpoint.java    From apollo with Apache License 2.0 6 votes vote down vote up
@OnMessage
public void onMessageReceived(Session session, String command) {
    SessionExecModel sessionModel = execWebSocketSessionStore.getSessionExecModel(session);
    ExecWatch execWatch = sessionModel.getExecWatch();

    if (execWatch == null) {
        logger.info("Got message to an unknown ExecWatch, ignoring!");
        return;
    }
    try {
        execWatch.getInput().write(command.getBytes());

    } catch (IOException e) {
        logger.warn("Got IO Exception while writing to the ExecWatch!", e);
    }
}
 
Example #4
Source File: PodExecDecorator.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Launcher decorate(final Launcher launcher, Node node) {
    return new Launcher.DecoratedLauncher(launcher) {
        @Override
        public Proc launch(ProcStarter starter) throws IOException {
            AtomicBoolean processAlive = new AtomicBoolean(false);
            CountDownLatch processStarted = new CountDownLatch(1);
            CountDownLatch processFinished = new CountDownLatch(1);

            ExecWatch execWatch = kubernetes.exec(name, containerName, processAlive, processStarted, processFinished, launcher.getListener().getLogger(),
                    getCommands(starter)
            );
            return new PodExecProc(name, processAlive, processFinished, execWatch);
        }

        @Override
        public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
            kubernetes.deletePod(name);
        }
    };
}
 
Example #5
Source File: PodIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void copyFile() throws IOException {
  // Wait for resources to get ready
  ReadyEntity<Pod> podReady = new ReadyEntity<>(Pod.class, client, pod1.getMetadata().getName(), currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(podReady);

  File tmpDir = Files.createTempDir();
  ExecWatch watch = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).writingOutput(System.out).exec("sh", "-c", "echo 'hello' > /msg");
  client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).file("/msg").copy(tmpDir.toPath());
  File msg = tmpDir.toPath().resolve("msg").toFile();
  assertTrue(msg.exists());
  try (InputStream is = new FileInputStream(msg))  {
    String result = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
    assertEquals("hello", result);
  }
}
 
Example #6
Source File: KubernetesHandler.java    From apollo with Apache License 2.0 5 votes vote down vote up
public ExecWatch getExecWatch(String podName, String containerName, String... command) {

        return kubernetesClient
                .pods()
                .inNamespace(environment.getKubernetesNamespace())
                .withName(podName)
                .inContainer(containerName)
                .redirectingInput()
                .redirectingOutput()
                .redirectingError()
                .withTTY()
                .exec(command);
    }
 
Example #7
Source File: ExecExampleWithTerminalSize.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    if (args.length < 1) {
        System.out.println("Usage: podName [master] [namespace] [columns] [lines]\n" +
          "Use env variable COLUMNS & LINES to initialize terminal size.");
        return;
      }

    String podName = args[0];
    String namespace = "default";
    String master = "https://localhost:8443/";
    String columns = "80";
    String lines = "24";

    if (args.length > 1) {
        master = args[1];
      }
      if (args.length > 2) {
        namespace = args[2];
        if (args.length > 3) {
          columns = args[3];
          if (args.length > 4) {
            lines = args[4];
          }
        }
      }

    Config config = new ConfigBuilder().withMasterUrl(master).build();
    try (final KubernetesClient client = new DefaultKubernetesClient(config);
         ExecWatch watch = client.pods().inNamespace(namespace).withName(podName)
            .readingInput(System.in)
            .writingOutput(System.out)
            .writingError(System.err)
            .withTTY()
            .usingListener(new SimpleListener())
            .exec("env", "TERM=xterm", "COLUMNS=" + columns, "LINES=" + lines, "bash")){

        Thread.sleep(10 * 1000);
    }
}
 
Example #8
Source File: ExecExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    if (args.length < 1) {
        System.out.println("Usage: podName [master] [namespace]");
        return;
      }

    String podName = args[0];
    String namespace = "default";
    String master = "https://localhost:8443/";

    if (args.length > 1) {
        master = args[1];
      }
      if (args.length > 2) {
        namespace = args[2];
      }

    Config config = new ConfigBuilder().withMasterUrl(master).build();
    try (final KubernetesClient client = new DefaultKubernetesClient(config);
         ExecWatch watch = client.pods().inNamespace(namespace).withName(podName)
            .readingInput(System.in)
            .writingOutput(System.out)
            .writingError(System.err)
            .withTTY()
            .usingListener(new SimpleListener())
            .exec()){

        Thread.sleep(10 * 1000);
    }
}
 
Example #9
Source File: ExecPipesExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, IOException {
    String master = "https://localhost:8443/";
    String podName = null;

    if (args.length == 2) {
        master = args[0];
        podName = args[1];
    }
    if (args.length == 1) {
        podName = args[0];
    }

    Config config = new ConfigBuilder().withMasterUrl(master).build();
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    try (
            KubernetesClient client = new DefaultKubernetesClient(config);
            ExecWatch watch = client.pods().withName(podName)
                    .redirectingInput()
                    .redirectingOutput()
                    .redirectingError()
                    .redirectingErrorChannel()
                    .exec();
            InputStreamPumper pump = new InputStreamPumper(watch.getOutput(), new SystemOutCallback()))
    {

        executorService.submit(pump);
        watch.getInput().write("ls -al\n".getBytes());
        Thread.sleep(5 * 1000);
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    } finally {
        executorService.shutdownNow();
    }
}
 
Example #10
Source File: PodIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void readFileEscapedParams() throws IOException {
  // Wait for resources to get ready
  ReadyEntity<Pod> podReady = new ReadyEntity<>(Pod.class, client, pod1.getMetadata().getName(), currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(podReady);
  ExecWatch watch = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).writingOutput(System.out).exec("sh", "-c", "echo 'H$ll* (W&RLD}' > /msg");
  try (InputStream is = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).file("/msg").read())  {
    String result = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
    assertEquals("H$ll* (W&RLD}", result);
  }
}
 
Example #11
Source File: PodIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void readFile() throws IOException {
  // Wait for resources to get ready
  ReadyEntity<Pod> podReady = new ReadyEntity<>(Pod.class, client, pod1.getMetadata().getName(), currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(podReady);
  ExecWatch watch = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).writingOutput(System.out).exec("sh", "-c", "echo 'hello' > /msg");
  try (InputStream is = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).file("/msg").read())  {
    String result = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
    assertEquals("hello", result);
  }
}
 
Example #12
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public ExecWatch exec(String... command) {
    String[] actualCommands = command.length >= 1 ? command : EMPTY_COMMAND;
    try {
        URL url = getURLWithCommandParams(HttpUrl.get(getResourceUrl()).newBuilder(), actualCommands);
        Request.Builder r = new Request.Builder().url(url).header("Sec-WebSocket-Protocol", "v4.channel.k8s.io").get();
        OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        final ExecWebSocketListener execWebSocketListener = new ExecWebSocketListener(getConfig(), in, out, err, errChannel, inPipe, outPipe, errPipe, errChannelPipe, execListener, bufferSize);
        clone.newWebSocket(r.build(), execWebSocketListener);
        execWebSocketListener.waitUntilReady();
        return execWebSocketListener;
    } catch (Throwable t) {
        throw KubernetesClientException.launderThrowable(forOperationType("exec"), t);
    }
}
 
Example #13
Source File: ContainerExecProc.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
public ContainerExecProc(ExecWatch watch, AtomicBoolean alive, CountDownLatch finished, OutputStream stdin,
        ByteArrayOutputStream error) {
    this.watch = watch;
    this.stdin = stdin == null ? watch.getInput() : stdin;
    this.alive = alive;
    this.finished = finished;
    this.error = error;
    Timer.get().schedule(this, 1, TimeUnit.MINUTES);
}
 
Example #14
Source File: ContainerExecDecorator.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private static void closeWatch(ExecWatch watch) {
    try {
        watch.close();
    } catch (Exception e) {
        LOGGER.log(Level.INFO, "failed to close watch", e);
    }
}
 
Example #15
Source File: SessionExecModel.java    From apollo with Apache License 2.0 4 votes vote down vote up
public SessionExecModel(ExecWatch execWatch, ExecutorService executor) {
    this.execWatch = execWatch;
    this.executor = executor;
}
 
Example #16
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public ContainerResource<String, LogWatch, InputStream, PipedOutputStream, OutputStream, PipedInputStream, String, ExecWatch, Boolean, InputStream, Boolean> inContainer(String containerId) {
    return new PodOperationsImpl(getContext().withContainerId(containerId));
}
 
Example #17
Source File: SessionExecModel.java    From apollo with Apache License 2.0 4 votes vote down vote up
public ExecWatch getExecWatch() {
    return execWatch;
}
 
Example #18
Source File: PodExecProc.java    From kubernetes-pipeline-plugin with Apache License 2.0 4 votes vote down vote up
public PodExecProc(String podName, AtomicBoolean alive, CountDownLatch finished, ExecWatch watch) {
    this.podName = podName;
    this.watch = watch;
    this.alive = alive;
    this.finished = finished;
}
 
Example #19
Source File: ContainerExecProc.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Deprecated
public ContainerExecProc(ExecWatch watch, AtomicBoolean alive, CountDownLatch finished,
        Callable<Integer> exitCode) {
    this(watch, alive, finished, null, new ByteArrayOutputStream());
}
 
Example #20
Source File: ContainerExecProc.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Deprecated
public ContainerExecProc(ExecWatch watch, AtomicBoolean alive, CountDownLatch finished,
        ByteArrayOutputStream error) {
    this(watch, alive, finished, null, error);
}
 
Example #21
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Execable<String, ExecWatch> usingListener(ExecListener execListener) {
    return new PodOperationsImpl(getContext().withExecListener(execListener));
}
 
Example #22
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public ExecListenable<String, ExecWatch> withTTY() {
    return new PodOperationsImpl(getContext().withTty(true));
}
 
Example #23
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecable<String, ExecWatch> redirectingErrorChannel() {
    return readingErrorChannel(new PipedInputStream());
}
 
Example #24
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecable<String, ExecWatch> readingErrorChannel(PipedInputStream errChannelPipe) {
    return new PodOperationsImpl(getContext().withErrChannelPipe(errChannelPipe));
}
 
Example #25
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecable<String, ExecWatch> writingErrorChannel(OutputStream errChannel) {
    return new PodOperationsImpl(getContext().withErrChannel(errChannel));
}
 
Example #26
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecErrorChannelable<String, OutputStream, PipedInputStream, ExecWatch> redirectingError() {
    return readingError(new PipedInputStream());
}
 
Example #27
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecErrorChannelable<String, OutputStream, PipedInputStream, ExecWatch> readingError(PipedInputStream errPipe) {
    return new PodOperationsImpl(getContext().withErrPipe(errPipe));
}
 
Example #28
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecErrorChannelable<String, OutputStream, PipedInputStream, ExecWatch> writingError(OutputStream err) {
    return new PodOperationsImpl(getContext().withErr(err));
}
 
Example #29
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecErrorable<String, OutputStream, PipedInputStream, ExecWatch> redirectingOutput() {
    return readingOutput(new PipedInputStream());
}
 
Example #30
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public TtyExecErrorable<String, OutputStream, PipedInputStream, ExecWatch> readingOutput(PipedInputStream outPipe) {
    return new PodOperationsImpl(getContext().withOutPipe(outPipe));
}