From 2d918142d581cae690a84fcdd75f4b6f11539539 Mon Sep 17 00:00:00 2001 From: Jack Henschel Date: Fri, 20 Oct 2023 07:59:34 +0200 Subject: [PATCH 1/2] [wip] Implement pod exec functionality --- kr8s/_objects.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/kr8s/_objects.py b/kr8s/_objects.py index aa659c63..382e8573 100644 --- a/kr8s/_objects.py +++ b/kr8s/_objects.py @@ -729,6 +729,45 @@ async def logs( async for line in resp.aiter_lines(): yield line + def exec(self, command: List[str], container: str) -> Generator[str]: + """Executes a command inside a pod and returns the output.""" + + params = {} + params["stdout"] = True + params["tty"] = True + params["command"] = command + + if container: + params["container"] = container + else: + # TODO: automatically choose correct container based on + # "kubectl.kubernetes.io/default-container" annotation + # or fallback to the "first" container of the pod + raise Error("A container must be provided") + + headers = { + "X-Stream-Protocol-Version": "v4.channel.k8s.io", + } + + # example "kubectl exec -n my-namespace my-pod -- cat /etc/passwd": + # POST https://{kube_api}/api/v1/namespaces/my-namespace/pods/my-pod/exec?command=cat&command=%2Fetc%2Fpasswd&container=nginx&stdin=true&stdout=true + + # NOTE: DOES NOT WORK + # httpx does not support the "Connection: Upgrade" mechanism to switch the + # transport to SPDY or Websockets. + with contextlib.supress(httpx.ReadTimeout): + with self.api.call_api( + "POST", + url=f"{self.endpoint}/{self.name}/exec", + namespace=self.namespace, + params=params, + stream=True, + headers=headers, + ) as resp: + for line in resp.iter_lines(): + yield line + + def portforward(self, remote_port: int, local_port: int = None) -> int: """Port forward a pod. From 8a475af01b15961661a1fb7b14433acaf3db777d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 20 Oct 2023 06:28:37 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- kr8s/_objects.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/kr8s/_objects.py b/kr8s/_objects.py index 382e8573..ac232322 100644 --- a/kr8s/_objects.py +++ b/kr8s/_objects.py @@ -757,17 +757,16 @@ def exec(self, command: List[str], container: str) -> Generator[str]: # transport to SPDY or Websockets. with contextlib.supress(httpx.ReadTimeout): with self.api.call_api( - "POST", - url=f"{self.endpoint}/{self.name}/exec", - namespace=self.namespace, - params=params, - stream=True, - headers=headers, + "POST", + url=f"{self.endpoint}/{self.name}/exec", + namespace=self.namespace, + params=params, + stream=True, + headers=headers, ) as resp: for line in resp.iter_lines(): yield line - def portforward(self, remote_port: int, local_port: int = None) -> int: """Port forward a pod.