-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathpod_logs_non_blocking.py
More file actions
51 lines (40 loc) · 1.09 KB
/
pod_logs_non_blocking.py
File metadata and controls
51 lines (40 loc) · 1.09 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
"""
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()