-
Notifications
You must be signed in to change notification settings - Fork 0
/
follow-kube-logs.py
executable file
·378 lines (266 loc) · 12 KB
/
follow-kube-logs.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#!/usr/bin/env python3
import subprocess
import shlex
import json
import os
import signal
import sys
import ctypes
import argparse
import datetime
class Util:
kubectl = "kubectl"
@staticmethod
def get_kubectl():
return Util.kubectl
@staticmethod
def set_kubectl(cmd):
Util.kubectl = cmd
class RunCommand:
trace_on = False
exit_on_error = True
@staticmethod
def trace(on_off):
RunCommand.trace_on = on_off
@staticmethod
def exit_on_error(on_off):
RunCommand.exit_on_error = on_off
def __init__(self, command_line):
self.command_line = command_line
self.exit_code = 0
self.run(command_line)
def run(self, command_line):
try:
if RunCommand.trace_on:
print(">{}".format( command_line ))
process = subprocess.Popen(shlex.split(command_line), \
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error_out) = process.communicate()
self.exit_code = process.wait()
self.output = output.decode("utf-8")
self.error_out = error_out.decode("utf-8")
self.exit_code = process.wait()
if RunCommand.trace_on:
print(">exit code: {} output: {} stderr: {}".format(self.exit_code, self.output, self.error_out))
if RunCommand.exit_on_error and self.exit_code != 0:
print(self.make_error_message())
exit(1)
return self.exit_code
except FileNotFoundError:
self.output = ""
self.error_out = "file not found"
self.exit_code = 1
return self.exit_code
def result(self):
return self.exit_code, self.output
def make_error_message(self):
return_value = ""
if self.command_line != "":
return_value += " command line: {}.".format(self.command_line)
if self.exit_code != 0:
return_value += " exit status: {}. ".format(self.exit_code)
if self.error_out != "":
return_value += " " + self.error_out
return return_value
def get_selector(namespace, object_type, object_name):
cmd = "{} -n {} get {} {}".format(Util.get_kubectl(), namespace, object_type, object_name) + " -o jsonpath='{.spec.selector.matchLabels}'"
runner = RunCommand(cmd)
obj = json.loads(runner.output)
cmd_opts = ""
for item in obj.items():
if cmd_opts != "":
cmd_opts += ","
cmd_opts += "{}={}".format(item[0], item[1])
return cmd_opts
def open_and_redirect_os_stdout(log_file):
file = open(log_file, "w")
original_stdout_fd = sys.stdout.fileno()
#libc = ctypes.CDLL(None)
#c_stdout = ctypes.c_void_p.in_dll(libc, 'stdout')
#libc.fflush(c_stdout)
# Make original_stdout_fd point to the same file as to_fd
os.dup2(file.fileno(), original_stdout_fd)
def intput_with_timeout(timeout_sec):
import select
ready, _, _ = select.select([sys.stdin], [],[], timeout_sec)
if ready:
return sys.stdin.readline().rstrip('\n'), True
return "", False
class LogPods:
def __init__(self, namespace, object_type, object_name, outputdir):
self.child_pids = []
self.pods_handled = {}
self.namespace = namespace
self.outputdir = outputdir
self.selector_label = get_selector(self.namespace, object_type, object_name)
def show_pids_in_deployment(self):
# show the pods of this deployment and their status
self.get_pods_cmd = "{} -n {} get pods -l {}".format(Util.get_kubectl(), self.namespace, self.selector_label)
runner = RunCommand(self.get_pods_cmd)
strnow = str(datetime.datetime.now())
print(runner.output.replace("\n","\n{} ".format(strnow)))
def run(self):
self.show_pids_in_deployment()
print("starting to log ...")
# make the log dir
if not os.path.isdir(self.outputdir):
os.mkdir(self.outputdir)
self.scand_pods_and_start_logging(True)
print("press enter to stop logging")
while True:
text, has_pressed = intput_with_timeout(1)
if has_pressed:
break
self.scand_pods_and_start_logging(False)
self.stop_logging()
def scand_pods_and_start_logging(self, first_call):
# this clusterfuck gets the following:
# each line starts with the name of the pod and it's phase, then followed by the names of the containers for that pod
cmdex = self.get_pods_cmd + """ -o jsonpath="{range .items[*]}{' '}{.metadata.name}{' '}{.status.phase}{range .spec.containers[*]}{' '}{.name}{end}{'\\n'}{end}" """
runner = RunCommand(cmdex)
handled_pods = []
for line in runner.output.split("\n"):
if line != "":
tokens = line.split()
pod_name=tokens[0]
pod_phase=tokens[1]
if pod_phase != "Running":
continue
handled_pods.append(pod_name)
if not pod_name in self.pods_handled:
if not first_call:
strnow = str(datetime.datetime.now())
print("{} {} {}".format(strnow, pod_name, pod_phase))
pod_dir = os.path.join(self.outputdir, pod_name)
if not os.path.isdir(pod_dir):
os.mkdir(pod_dir)
del tokens[0]
del tokens[0]
for container_name in tokens:
log_file = "{}/{}.log".format(pod_dir, container_name)
print("logging pod {} container {}".format(pod_name, container_name))
cmdlog = "{} logs -n {} --follow {} -c {}".format(Util.get_kubectl(), self.namespace, pod_name, container_name)
parent_pid = os.getpid()
child_pid = os.fork()
if child_pid == 0:
cmd_list = cmdlog.split()
# this one works only on stuff used by python's pring
#sys.stdout = open(log_file, "w")
#sys.stderr = sys.stdout
open_and_redirect_os_stdout(log_file)
os.execvp(cmd_list[0], cmd_list)
exit(1)
else:
self.pods_handled[pod_name] = child_pid
if not first_call:
for pod in set(self.pods_handled.keys()):
if not pod in handled_pods:
strnow = str(datetime.datetime.now())
print("{} pod {} stopped".format(strnow, pod))
del self.pods_handled[pod]
def stop_logging(self):
print("stopping logging...")
for pid in self.pods_handled.values():
os.kill(pid, signal.SIGSTOP)
def parse_cmd_line():
if len(sys.argv) == 2 and sys.argv[1] == '-h' and os.environ.get("SHORT_HELP_MODE"):
print("follows logs of all containers in all pods of a deployment, for some time period")
sys.exit(1)
usage = '''
This program starts to follow the logs of containers in all pods of a kubernetes deployment.
The output is written to a file per container.
The script then waits for user input, logging is stopped once the user has pressed enter.
'''
parse = argparse.ArgumentParser(description=usage, \
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
group = parse.add_argument_group("log pods/containers in either one of deployment/replicaset/statefuleset")
group.add_argument('--namespace', '-n', type=str, default="", \
dest='namespace', help='optional: specify namespace of deployment')
group.add_argument('--deployment', '-d', type=str, default="", \
dest='deployment', help='name of deployment')
group.add_argument('--stset', '-s', type=str, default="", \
dest='statefulset', help='name of statefull set')
group.add_argument('--rset', '-r', type=str, default="", \
dest='replicaset', help='name of replica set')
group.add_argument('--out', '-o', type=str, default="", \
dest='outdir', help='mandatory: name of output directory')
ctl_cmd = group.add_argument('--kubectl', '-k', type=str, default="kubectl", \
dest='kubecmd', help='optional: name of kubectl command')
group.add_argument('--trace', '-x', action='store_true', \
dest='trace', help='optional: enable tracing')
group = parse.add_argument_group("suport for bash autocompletion of command line arguments")
group.add_argument('--complete-bash', '-b', action='store_true', \
dest='complete_bash', default=False, help='show bash source of completion function')
group.add_argument('--complete', '-c', action='store_true', \
dest='complete', default=False, help='internal: used during code completion')
# that's the trick for having the same option in two groups
group._group_actions.append(ctl_cmd)
#group.add_argument('--kubectl', '-k', type=str, default="kubectl", \
# dest='kubecmd', help='optional: name of kubectl command')
return parse.parse_args(), parse
def bash_complete():
current_word = os.getenv('COMP_CWORD')
cmdline = os.getenv('COMP_LINE')
if current_word != "":
current_word_index = int(current_word)
words = cmdline.split()
if words[current_word_index-1] == "-n":
cmd = Util.get_kubectl() + """ get namespaces -o jsonpath="{.items[*]['metadata.name']}" """
runner = RunCommand(cmd)
print(runner.output)
elif get_obj_type_from_option(words[current_word_index-1]):
obj_type = get_obj_type_from_option(words[current_word_index-1])
# was there a namespace specified?
namespace = "default"
for i in range(0,len(words)-1):
if words[i] == "-n":
namespace = words[i+1]
cmd = Util.get_kubectl() + " get " + obj_type + " -n " + namespace + """ -o jsonpath="{.items[*]['metadata.name']}" """
#print(cmd, file=sys.stderr)
runner = RunCommand(cmd)
print(runner.output)
elif words[current_word_index-1][0:1] == "-":
print ("--namespace --deployment --rset --stset --out --kubectl --trace -n -d -r -s -o -k -x")
def get_obj_type_from_option(opt_string):
if opt_string == "-d" or opt_string == "--deployment":
return "deployment"
if opt_string == "-r" or opt_string == "--rset":
return "replicaset"
if opt_string == "-s" or opt_string == "--stset":
return "statefulset"
return ""
def show_bash_completion():
print("""
function _follow-kube-logs {
local cur opts
export COMP_CWORD
export COMP_LINE
opts=$(follow-kube-logs.py -c """ + "-k {}".format( Util.get_kubectl() ) + """ )
cur="${COMP_WORDS[COMP_CWORD]}"
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
}
complete -F _follow-kube-logs follow-kube-logs.py
""")
def main():
cmd_args, cmd_parser = parse_cmd_line()
Util.set_kubectl(cmd_args.kubecmd)
if cmd_args.complete:
bash_complete()
elif cmd_args.complete_bash:
show_bash_completion()
elif (cmd_args.deployment != "" or cmd_args.replicaset != "" or cmd_args.statefulset != "") and cmd_args.outdir != "":
RunCommand.trace(cmd_args.trace)
if cmd_args.deployment != "":
obj_type="deployment"
obj_name=cmd_args.deployment
elif cmd_args.replicaset != "":
obj_type="replicaset"
obj_name=cmd_args.replicaset
elif cmd_args.statefulset != "":
obj_type="statefulset"
obj_name=cmd_args.statefulset
log_pods = LogPods(cmd_args.namespace, obj_type, obj_name, cmd_args.outdir)
log_pods.run()
else:
cmd_parser.print_help()
main()