-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkubepodmetric
executable file
·180 lines (151 loc) · 6 KB
/
kubepodmetric
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
#!/usr/bin/env python2
import sys
import os
import re
import time
import json
import argparse
import math
def getHpa(data, podName):
for item in data:
name = item['metadata']['name'].encode('utf8')
if name.find(podName) > -1:
if item['status']['currentReplicas'] > 0:
return float(item['spec']['targetCPUUtilizationPercentage'])
parser = argparse.ArgumentParser(
description='Fetch some useful pod Kubernetes statistics ')
parser.add_argument('podPrefix', metavar='POD_PREFIX_NAME', type=str,
help='Pod name prefix that should be measured')
parser.add_argument('-s', dest='summarized',
default=False, action='store_true',
help='Summarizes pod metrics')
parser.add_argument('-w', dest='watch',
default=False, action='store_true',
help='Watch Kubernetes to change state')
args = parser.parse_args()
pod_prefix = args.podPrefix
watch = args.watch
summarized = args.summarized
command = 'kubectl top pods'
if pod_prefix:
command += '| grep %s' % pod_prefix
hpaCluster = getHpa(json.loads(
os.popen('kubectl get hpa -o=json').read())['items'], pod_prefix)
cpusL = 0.0
cpusR = 0.0
memsL = 0.0
memsR = 0.0
nameColLength = 30
loop = True
describeOutput = False
app_name = False
try:
if summarized:
print('APPNAME%s\tCPU\tMEMORY\tQTY\tHPA\tLimCPU\tLimMEM\tLimHPA' %
(' ' * (nameColLength - 7)))
while loop:
output = os.popen(command).read()
if summarized:
versions = []
output = output.strip().split("\n")
lines = len(output)
cpu = 0.0
mem = 0.0
cpuMax = 0.0
memMax = 0.0
for line in output:
cols = (' '.join(line.split())).split(' ')
pod_name = cols[0]
pod_name_splitted = pod_name.split('-')
if not app_name:
app_name = pod_name_splitted[0]
if app_name != pod_name_splitted[0]:
raise BaseException('Different apps were found with informed prefix. Prefix: "%s" Apps found: "%s" and "%s"' % (
pod_prefix, app_name, pod_name_splitted[0]))
if pod_name_splitted[1] not in versions:
versions.append(pod_name_splitted[1])
if not describeOutput:
describeOutput = True
os.popen(
'kubectl describe pods %s > /tmp/kubepodmetric_describe' % cols[0])
cpus = os.popen(
'cat /tmp/kubepodmetric_describe | grep cpu | tail -n3').read().strip().split("\n")
mems = os.popen(
'cat /tmp/kubepodmetric_describe | grep memory | tail -n3').read().strip().split("\n")
os.unlink('/tmp/kubepodmetric_describe')
cpuStripped = []
for line in cpus:
cpuStripped.append(line.strip())
memStripped = []
for line in mems:
memStripped.append(line.strip())
for line in cpuStripped:
if line == '' or line[0] != 'c':
continue
line = line.replace(' ', '')
i = 0
if len(line) > 1 and line[0] != line[1]:
i = 1
if cpusL == 0.0:
cpusL = eval(line.split(':')[
i].replace('m', '*0.01'))
continue
if cpusR == 0.0:
cpusR = eval(line.split(':')[
i].replace('m', '*0.01'))
for line in memStripped:
if line == '' or line[0] != 'm':
continue
i = 0
if len(line) > 1 and line[0] != line[1]:
i = 1
line = line.replace(' ', '')
if memsL == 0.0:
memsL = eval(line.split(':')[i].replace(
'Mi', '').replace('Gi', '*1000'))
continue
if memsR == 0.0 and memsL > 0:
memsR = eval(line.split(':')[i].replace(
'Mi', '').replace('Gi', '*1000'))
if len(cols) is 3:
cpuI = float(eval(cols[1].replace('m', '*0.01')))
memI = float(eval(cols[2].replace(
'Mi', '').replace('Gi', '*1000')))
cpu += cpuI
mem += memI
if cpuI > cpuMax:
cpuMax = cpuI
if memI > memMax:
memMax = memI
cpu /= lines
mem /= lines
pHpa = '-'
pCpu = '-'
pMem = '-'
if hpaCluster is None or cpusR == 0:
hpa = 0
pHpa = 0
else:
hpa = cpu/cpusR
hpa = int(hpa * 100)
pHpa = int(100*hpa/hpaCluster)
if cpusL > 0:
pCpu = int(100 * cpuMax / cpusL)
if memsL > 0:
pMem = int(100 * memMax / memsL)
cpu *= 100
versions = ' (%s)' % ','.join(versions)
app_name_spacing = ' ' * \
(nameColLength - len(app_name) - len(versions))
print('%s%s%s\t%sm\t%sMi\t%s\t%s%%\t%s%%\t%s%%\t%s%%' % (app_name, versions, app_name_spacing, int(
math.ceil(cpu)), int(math.ceil(mem)), lines, hpa, pCpu, pMem, pHpa))
else:
print(output)
if not watch:
loop = False
else:
time.sleep(3)
except KeyboardInterrupt:
pass
except:
raise