|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from aiohttp.http import WSMsgType |
| 4 | + |
| 5 | +from kubernetes.aio import client, config, utils |
| 6 | +from kubernetes.aio.client.api_client import ApiClient |
| 7 | +from kubernetes.aio.stream import WsApiClient |
| 8 | +from kubernetes.aio.stream.ws_client import ( |
| 9 | + ERROR_CHANNEL, STDERR_CHANNEL, STDOUT_CHANNEL, |
| 10 | +) |
| 11 | + |
| 12 | +BUSYBOX_POD = "busybox-test" |
| 13 | + |
| 14 | + |
| 15 | +async def find_busybox_pod(): |
| 16 | + async with ApiClient() as api: |
| 17 | + v1 = client.CoreV1Api(api) |
| 18 | + ret = await v1.list_pod_for_all_namespaces() |
| 19 | + for i in ret.items: |
| 20 | + if i.metadata.namespace == 'default' and i.metadata.name == BUSYBOX_POD: |
| 21 | + print(f"Found busybox pod: {i.metadata.name}") |
| 22 | + return i.metadata.name |
| 23 | + return None |
| 24 | + |
| 25 | + |
| 26 | +async def create_busybox_pod(): |
| 27 | + print(f"Pod {BUSYBOX_POD} does not exist. Creating it...") |
| 28 | + manifest = { |
| 29 | + 'apiVersion': 'v1', |
| 30 | + 'kind': 'Pod', |
| 31 | + 'metadata': { |
| 32 | + 'name': BUSYBOX_POD, |
| 33 | + }, |
| 34 | + 'spec': { |
| 35 | + 'containers': [{ |
| 36 | + 'image': 'busybox', |
| 37 | + 'name': 'sleep', |
| 38 | + "args": [ |
| 39 | + "/bin/sh", |
| 40 | + "-c", |
| 41 | + "while true; do date; sleep 5; done" |
| 42 | + ] |
| 43 | + }] |
| 44 | + } |
| 45 | + } |
| 46 | + async with ApiClient() as api: |
| 47 | + objects = await utils.create_from_dict(api, manifest, namespace="default") |
| 48 | + pod = objects[0] |
| 49 | + print(f"Created pod {pod.metadata.name}.") |
| 50 | + return pod.metadata.name |
| 51 | + |
| 52 | + |
| 53 | +async def wait_busybox_pod_ready(): |
| 54 | + print(f"Waiting pod {BUSYBOX_POD} to be ready.") |
| 55 | + async with ApiClient() as api: |
| 56 | + v1 = client.CoreV1Api(api) |
| 57 | + while True: |
| 58 | + ret = await v1.read_namespaced_pod(name=BUSYBOX_POD, namespace="default") |
| 59 | + if ret.status.phase != 'Pending': |
| 60 | + break |
| 61 | + await asyncio.sleep(1) |
| 62 | + |
| 63 | + |
| 64 | +async def main(): |
| 65 | + # Configs can be set in Configuration class directly or using helper |
| 66 | + # utility. If no argument provided, the config will be loaded from |
| 67 | + # default location. |
| 68 | + await config.load_kube_config() |
| 69 | + |
| 70 | + pod = await find_busybox_pod() |
| 71 | + if not pod: |
| 72 | + pod = await create_busybox_pod() |
| 73 | + await wait_busybox_pod_ready() |
| 74 | + |
| 75 | + # Execute a command in a pod non-interactively, and display its output |
| 76 | + print("-------------") |
| 77 | + async with WsApiClient() as ws_api: |
| 78 | + v1_ws = client.CoreV1Api(api_client=ws_api) |
| 79 | + exec_command = [ |
| 80 | + "/bin/sh", |
| 81 | + "-c", |
| 82 | + "echo This message goes to stderr >&2; echo This message goes to stdout", |
| 83 | + ] |
| 84 | + ret = await v1_ws.connect_get_namespaced_pod_exec( |
| 85 | + pod, |
| 86 | + "default", |
| 87 | + command=exec_command, |
| 88 | + stderr=True, |
| 89 | + stdin=False, |
| 90 | + stdout=True, |
| 91 | + tty=False, |
| 92 | + ) |
| 93 | + print(f"Response: {ret}") |
| 94 | + |
| 95 | + # Execute a command interactively. If _preload_content=False is passed to |
| 96 | + # connect_get_namespaced_pod_exec(), the returned object is an aiohttp ClientWebSocketResponse |
| 97 | + # object, that can be manipulated directly. |
| 98 | + print("-------------") |
| 99 | + async with WsApiClient() as ws_api: |
| 100 | + v1_ws = client.CoreV1Api(api_client=ws_api) |
| 101 | + exec_command = ['/bin/sh'] |
| 102 | + websocket = await v1_ws.connect_get_namespaced_pod_exec( |
| 103 | + BUSYBOX_POD, |
| 104 | + "default", |
| 105 | + command=exec_command, |
| 106 | + stderr=True, |
| 107 | + stdin=True, |
| 108 | + stdout=True, |
| 109 | + tty=False, |
| 110 | + _preload_content=False, |
| 111 | + ) |
| 112 | + commands = [ |
| 113 | + "echo 'This message goes to stdout'\n", |
| 114 | + "echo 'This message goes to stderr' >&2\n", |
| 115 | + "exit 1\n", |
| 116 | + ] |
| 117 | + error_data = "" |
| 118 | + closed = False |
| 119 | + async with websocket as ws: |
| 120 | + while commands and not closed: |
| 121 | + command = commands.pop(0) |
| 122 | + stdin_channel_prefix = chr(0) |
| 123 | + await ws.send_bytes((stdin_channel_prefix + command).encode("utf-8")) |
| 124 | + while True: |
| 125 | + try: |
| 126 | + msg = await ws.receive(timeout=1) |
| 127 | + except asyncio.TimeoutError: |
| 128 | + break |
| 129 | + if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): |
| 130 | + closed = True |
| 131 | + break |
| 132 | + channel = msg.data[0] |
| 133 | + data = msg.data[1:].decode("utf-8") |
| 134 | + if not data: |
| 135 | + continue |
| 136 | + if channel == STDOUT_CHANNEL: |
| 137 | + print(f"stdout: {data}") |
| 138 | + elif channel == STDERR_CHANNEL: |
| 139 | + print(f"stderr: {data}") |
| 140 | + elif channel == ERROR_CHANNEL: |
| 141 | + error_data += data |
| 142 | + if error_data: |
| 143 | + returncode = ws_api.parse_error_data(error_data) |
| 144 | + print(f"Exit code: {returncode}") |
| 145 | + |
| 146 | +if __name__ == "__main__": |
| 147 | + loop = asyncio.get_event_loop() |
| 148 | + loop.run_until_complete(main()) |
| 149 | + loop.close() |
0 commit comments