将文件复制到Kubernetes Pod

时间:2020-05-11 01:15:54

标签: python kubernetes kubernetes-python-client

我正在尝试使用以下方式将二进制文件复制到Kubernetes容器中。如果文件是文本格式而不是二进制文件,则脚本可以工作。

from kubernetes import client, config

try:
    config.load_kube_config()
except TypeError:
    config.load_incluster_config()

api = client.CoreV1Api()

exec_command = ['tar', 'xvf', '-', '-C', '/']
resp = stream(
    api.connect_get_namespaced_pod_exec,
    'pod_name', 'namespace', command=exec_command,
    stderr=True, stdin=True, stdout=True, tty=False, _preload_content=False
)

source_file = './test_data/simulated/some.nc'
destination_path = '/tmp/some.nc'

with TemporaryFile() as tar_buffer:
    with tarfile.open(fileobj=tar_buffer, mode='w') as tar:
        tar.add(name=source_file, arcname=destination_path)
    tar_buffer.seek(0)
    commands = []
    commands.append(tar_buffer.read())

    while resp.is_open():
        resp.update(timeout=1)
        if resp.peek_stdout():
            print("STDOUT: %s" % resp.read_stdout())
        if resp.peek_stderr():
            print("STDERR: %s" % resp.read_stderr())
        if commands:
            c = commands.pop(0)
            resp.write_stdin(str(c))
            # works if source and destination files are txt format
            # and the above line is resp.write_stdin(c.decode())
        else:
            break
    resp.close()

在STDERR上,我得到以下日志“ tar:这看起来不像tar存档”

1 个答案:

答案 0 :(得分:0)

我找到了一个完全可以做到这一点的软件包。我的问题是复制二进制文件。原来,该程序包运行一个Kubernetes作业来完成复制。

https://github.com/nuvo/skbn