Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
51 changes: 51 additions & 0 deletions examples/pod_logs_non_blocking.py
Original file line number Diff line number Diff line change
@@ -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()