-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathk.logcli
executable file
·78 lines (61 loc) · 2.02 KB
/
k.logcli
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
#!/usr/bin/env python3
import argparse
import subprocess
import signal
import sys
import os
import atexit
import time
import socket
import random
random.seed()
port = random.randint(30000, 31767)
def sigint_handler(signal, frame):
#print("Interrupted")
sys.exit(0)
def kill_child():
if portfw_pid is None:
pass
else:
os.kill(portfw_pid, signal.SIGTERM)
def check_port(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
try:
s.connect(("127.0.0.1", port))
return True
except ConnectionRefusedError:
return False
def setup_port_forwarding():
global portfw_pid
proc = subprocess.Popen(["kubectl","port-forward", "svc/loki", "-n", "monitoring", str(port)+":3100"])
portfw_pid = proc.pid
while not check_port(port):
time.sleep(1)
print("Port fowarding ready", file=sys.stderr)
# set signal and exit handlers
signal.signal(signal.SIGINT, sigint_handler)
atexit.register(kill_child)
parser = argparse.ArgumentParser()
parser.add_argument("query", nargs="?", default="{app!=\"promtail\"}", help="promQL query")
parser.add_argument("--since", default="5m", help="Lookback window.")
parser.add_argument("--limit", "--count", default="30", help="Limit on number of entries to print.")
parser.add_argument("--no-tail", "-T", action='store_true', help="Do not wait for more lines (tail the log)")
args, extra_args = parser.parse_known_args()
setup_port_forwarding()
# decide labels to print
include_labels = ["hostname", "comm", "unit", "app_kubernetes_io_name", "app"]
if 'namespace="' not in args.query:
include_labels.append("namespace")
else:
#include_labels.append("instance")
include_labels.append("pod")
#include_labels.append("container_name")
# construct options
opts = ["--addr=http://localhost:"+str(port), "--limit="+args.limit, "--since="+args.since]
for label in include_labels:
opts.append("--include-label="+label)
if not args.no_tail:
opts.append("--tail")
# call teh query
subprocess.run(["logcli", "query"] + opts + [*extra_args, args.query])