forked from kubernetes-client/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpod_logs_non_blocking.py
More file actions
54 lines (43 loc) · 1.31 KB
/
Copy pathpod_logs_non_blocking.py
File metadata and controls
54 lines (43 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
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
# Note: when streaming logs with _preload_content=False, the transport may
# deliver arbitrary chunk boundaries, so callers should split or buffer data
# themselves if they need line-oriented processing.
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()