-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtmux-logs
executable file
·94 lines (77 loc) · 2.43 KB
/
tmux-logs
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
#!/bin/sh
TMUX_SESSION_NAME=$(tmux display-message -p "#S")
NAMESPACE=$KUBECTL_PLUGINS_CURRENT_NAMESPACE
SELECTOR=$KUBECTL_PLUGINS_LOCAL_FLAG_SELECTOR
CONTAINER=$KUBECTL_PLUGINS_LOCAL_FLAG_CONTAINER
# creates a new tmux window
createNewTmuxWindow() {
tmux new-window $1
}
# ensure tmux executable exists
ensureTmuxExists() {
if [ -z "$(which tmux)" ]; then
echo "tmux executable not found ... is it installed?"
exit 1
fi
}
# ensure desired tmux session exists, otherwise exit
ensureTmuxSessionExists() {
if ! tmux ls 2> /dev/null | grep -q "${TMUX_SESSION_NAME}: "; then
echo "Failed to connect to tmux session."
exit 1
fi
}
# gets pod and container names from a name selector
getPodContainers() {
if [ -z "${CONTAINER}" ]; then
GO_TEMPLATE="{{range .items}}{{\$name:=.metadata.name}}{{range .spec.containers}}{{print \$name}}_{{.name}} {{end}}{{end}}"
else
GO_TEMPLATE="{{range .items}}{{\$name:=.metadata.name}}{{range .spec.containers}}{{if eq .name \"${CONTAINER}\"}}{{print \$name}}_{{.name}} {{end}}{{end}}{{end}}"
fi
if [ -z "${SELECTOR}" ]; then
kubectl get pods -n ${NAMESPACE} -o go-template --template="${GO_TEMPLATE}"
else
kubectl get pods -n ${NAMESPACE} -l "${SELECTOR}" -o go-template --template="${GO_TEMPLATE}"
fi
}
# switch the tmux window layout
selectTmuxLayout() {
tmux select-layout $1
}
# creates a new tmux window
splitTmuxWindow() {
tmux split-window $1
}
# set synchronization for current tmux window
synchronizePanes() {
tmux set-window-option synchronize-panes "on"
}
# unset synchronization for current tmux window
unsynchronizePanes() {
tmux set-window-option synchronize-panes "off"
}
tailContainerLogs() {
INDEX=0
POD_CONTAINERS=$(getPodContainers)
for POD_CONTAINER in ${POD_CONTAINERS}; do
POD_CONTAINER_SPACED="${POD_CONTAINER/_/ }"
KUBECTL_LOGS_COMMAND="kubectl -n ${NAMESPACE} logs -f ${POD_CONTAINER_SPACED}"
if [ ${INDEX} -eq 0 ]; then
createNewTmuxWindow "${KUBECTL_LOGS_COMMAND}"
else
splitTmuxWindow "${KUBECTL_LOGS_COMMAND}"
selectTmuxLayout tiled
fi
INDEX=$((INDEX+1))
done
if [ ${INDEX} -eq 0 ]; then
echo "No matching pods found!"
fi
}
# execute pre-command checks
ensureTmuxExists
ensureTmuxSessionExists
# tail container logs
tailContainerLogs
# synchronize panes
synchronizePanes