File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -5,6 +5,11 @@ Please read the description at the top of each example for more information
55about what the script does and any prerequisites. Most scripts also include
66comments throughout the code.
77
8+ ## Available Examples
9+
10+ - pod_logs.py — basic (blocking) pod log streaming example
11+ - pod_logs_non_blocking.py — non-blocking streaming of pod logs with graceful shutdown
12+
813## Setup
914
1015These scripts require Python 2.7 or 3.5+ and the Kubernetes client which can be
Original file line number Diff line number Diff line change 1+ """
2+ Non-blocking pod log streaming example.
3+
4+ Demonstrates how to stream Kubernetes pod logs without blocking indefinitely
5+ by using socket timeouts and graceful shutdown.
6+ """
7+
8+ import threading
9+ import time
10+ import socket
11+ from kubernetes import client , config
12+ from urllib3 .exceptions import ReadTimeoutError
13+
14+ stop_event = threading .Event ()
15+
16+
17+ def stream_logs ():
18+ config .load_kube_config ()
19+ v1 = client .CoreV1Api ()
20+
21+ resp = v1 .read_namespaced_pod_log (
22+ name = "log-demo" ,
23+ namespace = "default" ,
24+ follow = True ,
25+ _preload_content = False
26+ )
27+
28+ # 👇 make socket non-blocking with timeout
29+ resp ._fp .fp .raw ._sock .settimeout (1 )
30+
31+ try :
32+ while not stop_event .is_set ():
33+ try :
34+ data = resp .read (1024 )
35+ if data :
36+ print (data .decode (), end = "" )
37+ except (socket .timeout , ReadTimeoutError ):
38+ continue
39+ finally :
40+ resp .close ()
41+ print ("\n Log streaming stopped cleanly." )
42+
43+
44+ t = threading .Thread (target = stream_logs )
45+ t .start ()
46+
47+ try :
48+ time .sleep (15 )
49+ finally :
50+ stop_event .set ()
51+ t .join ()
You can’t perform that action at this time.
0 commit comments