python (k8s) 3. pod

1. pod_namespace_watch.py

# -*- coding: utf8 -*-


from kubernetes import client, config, watch


def main():
    config.load_kube_config()
    v1 = client.CoreV1Api()
    count = 10
    w = watch.Watch()
    for event in w.stream(v1.list_namespace, timeout_seconds=10):
        print("Event: %s %s" % (event['type'], event['object'].metadata.name))
        count -= 1
        if not count:
            w.stop()
    print("Finished namespace stream.")

    for event in w.stream(v1.list_pod_for_all_namespaces, timeout_seconds=10):
        print("Event: %s %s %s" %(
            event['type'],
            event['object'].kind,
            event['object'].metadata.name
        ))
        count -= 1
        if not count:
            w.stop()

    print("finished pod stream")


if __name__ == '__main__':
    main()

2. pod_exec.py

# -*- coding: utf8 -*-

"""
使用Busybox Container演示exec的功能
"""

import time

from kubernetes import config
from kubernetes.client import Configuration
from kubernetes.client.apis import core_v1_api  # github官网为 kubernetes.client.api import ...

from kubernetes.client.rest import ApiException
from kubernetes.stream import stream


def exec_commands(api_instance):
    # 以下为 exec_commands()
    name = 'busybox-test'
    resp = None
    try:
        resp = api_instance.read_namespaced_pod(name=name, namespace='default')
    except ApiException as e:
        if e.status != 404:
            print("Unknown error: %s" % e)
            exit(1)

    if not resp:
        print("Pod %s does not exists. Creating it..." % name)
        pod_manifest = {
            'apiVersion': 'v1',
            'kind': 'Pod',
            'metadata': {
                'name': name
            },
            'spec': {
                'containers': [{
                    'image': 'busybox',
                    'name': 'sleep',
                    'args': [
                        "/bin/bash",
                        "-c",
                        "while true; do date; sleep 5; done"
                    ]
                }]
            }
        }
        resp = api_instance.create_namespaced_pod(body=pod_manifest, namespace='default')

        while True:
            resp = api_instance.read_namespaced_pod(name=name, namespace='default')
            if resp.status.phase != 'Pending':
                break
            time.sleep(1)
        print("Done.")
    # 调用 exec 等待返回
    exec_command = [
        "/bin/bash",
        "-c",
        "echo This message goes to stderr; echo This message goes to stdout"
    ]
    resp = stream(api_instance.connect_get_namespaced_pod_exec, name, command=exec_command, stderr=True, stdin=False,
                  stdout=True, tty=False)
    print("Response: " + resp)

    # 交互式调用 exec
    exec_command = ["/bin/bash"]
    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  name,
                  'default',
                  command=exec_command,
                  stderr=True, stdin=True,
                  stdout=True, tty=False,
                  _preload_content=False)
    commands = [
        "echo This message goes to stdout",
        "echo \"This message goes to stderr\" >&2",
    ]
    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)
            print("Runing command... %s\n" % c)
            resp.write_stdin(c + '\n')
        else:
            break

    resp.write_stdin('date\n')
    sdate = resp.readline_stdout(timeout=3)
    print("Server date command returns: %s" % sdate)
    resp.write_stdin("whoami\n")
    user = resp.readline_stdout(timeout=3)
    print("Server user is: %s" % user)
    resp.close()


def main():
    config.load_kube_config()
    c = Configuration()
    c.assert_hostname = False
    Configuration.set_default(c)
    core_v1 = core_v1_api.CoreV1Api()
    exec_commands(core_v1)


if __name__ == '__main__':
    main()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值