kubernetes-client/javascript

cpFromPod fails with 'Unexpected end of data' error due to gzipped tar output

Summary

  • Context: The cpFromPod method in the Cp class copies files from a Kubernetes pod to the local filesystem by executing a tar command inside the pod and streaming the output to tar-fs.extract() for extraction.

  • Bug: The tar command uses the z flag to create a gzipped archive, but tar-fs.extract() does not automatically decompress gzipped data, causing extraction to fail.

  • Actual vs. expected: When copying files from a pod, the operation fails with “Error: Unexpected end of data” instead of successfully extracting the files to the target directory.

  • Impact: The cpFromPod functionality is completely broken, preventing users from copying files from pods to their local filesystem.

Code with bug

public async cpFromPod(
  namespace: string,
  podName: string,
  containerName: string,
  srcPath: string,
  tgtPath: string,
  cwd?: string,
): Promise<void> {
  const command = ['tar', 'zcf', '-']; // <-- BUG 🔴 The 'z' flag creates gzipped output, but tar-fs.extract() doesn't gunzip automatically

  if (cwd) {
    command.push('-C', cwd);
  }

  command.push(srcPath);

  const writerStream = tar.extract(tgtPath);
  const errStream = new WritableStreamBuffer();

  this.execInstance.exec(
    namespace,
    podName,
    containerName,
    command,
    writerStream,
    errStream,
    null,
    false,
    async () => {
      if (errStream.size()) {
        throw new Error(
          `Error from cpFromPod - details:\n ${errStream.getContentsAsString()}`,
        );
      }
    },
  );
}

Evidence

The tar-fs package’s extract() method expects uncompressed tar data. When the tar command includes the z flag, it produces gzipped output that tar-fs.extract() cannot process, resulting in parsing errors. Unlike the previously used tar package which handled gzipped data automatically, tar-fs requires uncompressed tar streams.

Recommended fix

Remove the z flag from the tar command to produce uncompressed tar output that tar-fs.extract() can process. Change ['tar', 'zcf', '-'] to ['tar', 'cf', '-']. // <– FIX 🟢