Fabric8 exec command in pod: piped commands?

86 Views Asked by At

I'm trying to execute piped commands on a single call in a pod. I'd like to do something more sophisticated, but first I'd like to be able to simply count lines from a ls output like this:

    private ExecWatch execCmd(Pod pod, CompletableFuture<String> data, String... command) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        return this.kubernetesClient.pods().inNamespace(pod.getMetadata().getNamespace())
                .withName(pod.getMetadata().getName()).writingOutput(baos).writingError(baos)
                .usingListener(new SimpleListener(data, baos)).exec(command);
    }

And then

        CompletableFuture<String> data = new CompletableFuture<>();
        try (ExecWatch execWatch = execCmd(pod, data, "ls", "-lrt", "internal_folder/", "| wc -l"))         {
            result = data.get(executionTimeout.getSeconds(), TimeUnit.SECONDS);
        }

No matter how do I arrange the command: "|", "wc","-l"; or "internal_folder/ | wc -l"; and many others, it always results on: "ls: cannot access '| wc -l': No such file or directory"

How could I do this? thanks in advance.

1

There are 1 best solutions below

4
On

You can do it by passing whole command as input to sh -c. I tested it with this code on Fabric8 Kubernetes Client v6.9.2 and it seems to work for me:

try (KubernetesClient client = new KubernetesClientBuilder().build()) {
  PodResource podResource = client.pods()
      .inNamespace("default")
      .withName("exrf9fr");
  ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
  try (ExecWatch execWatch = podResource.writingOutput(baos).terminateOnError()
      .exec("sh", "-c", "ls -lrt /proc | wc -l")) {

    execWatch.exitCode().join();
  }

  System.out.println("Result : " + baos);
}