diff --git a/examples/README.md b/examples/README.md index d84c633ae2..43a11fba4e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -5,6 +5,11 @@ Please read the description at the top of each example for more information about what the script does and any prerequisites. Most scripts also include comments throughout the code. +## Available Examples + +- pod_logs.py — basic (blocking) pod log streaming example +- pod_logs_non_blocking.py — non-blocking streaming of pod logs with graceful shutdown + ## Setup These scripts require Python 2.7 or 3.5+ and the Kubernetes client which can be diff --git a/examples/pod_logs_non_blocking.py b/examples/pod_logs_non_blocking.py new file mode 100644 index 0000000000..01673790e5 --- /dev/null +++ b/examples/pod_logs_non_blocking.py @@ -0,0 +1,51 @@ +""" +Non-blocking pod log streaming example. + +Demonstrates how to stream Kubernetes pod logs without blocking indefinitely +by using socket timeouts and graceful shutdown. +""" + +import threading +import time +import socket +from kubernetes import client, config +from urllib3.exceptions import ReadTimeoutError + +stop_event = threading.Event() + + +def stream_logs(): + config.load_kube_config() + v1 = client.CoreV1Api() + + resp = v1.read_namespaced_pod_log( + name="log-demo", + namespace="default", + follow=True, + _preload_content=False + ) + + # 👇 make socket non-blocking with timeout + resp._fp.fp.raw._sock.settimeout(1) + + try: + while not stop_event.is_set(): + try: + data = resp.read(1024) + if data: + print(data.decode(), end="") + except (socket.timeout, ReadTimeoutError): + continue + finally: + resp.close() + print("\nLog streaming stopped cleanly.") + + +t = threading.Thread(target=stream_logs) +t.start() + +try: + time.sleep(15) +finally: + stop_event.set() + t.join()