-
Notifications
You must be signed in to change notification settings - Fork 0
/
mymem.py
executable file
·162 lines (138 loc) · 4.73 KB
/
mymem.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
#!/usr/bin/env python
# -*-coding:utf-8-*-
import socket
import json
import time
import sys
from os import popen as bash
RECV_SIZE = 4096
class Client(object):
def __init__(self,
server,
timeout=None):
self.sock = None
self.server = server
self.timeout = timeout
def _connect(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(self.server)
sock.settimeout(self.timeout)
self.sock = sock
def _close(self):
if self.sock:
self.sock.close()
self.sock = None
def get(self, name):
name += b''
cmd = name + b'\r\n'
if not self.sock:
self._connect()
self.sock.sendall(cmd)
buf = b''
result = []
while True:
buf, line = parseline(self.sock, buf)
if line == b'END':
self._close()
return result
result.append(line)
def parseline(sock, buf):
chunks = []
last_char = b''
while True:
if last_char == b'\r' and buf[0:1] == b'\n':
# Strip the last character from the last chunk.
chunks[-1] = chunks[-1][:-1]
return buf[1:], b''.join(chunks)
elif buf.find(b'\r\n') != -1:
before, sep, after = buf.partition(b"\r\n")
chunks.append(before)
return after, b''.join(chunks)
if buf:
chunks.append(buf)
last_char = buf[-1:]
try:
buf = sock.recv(RECV_SIZE)
except IOError as e:
raise e
def mget_stats():
"""
@return: memcache stats dict
"""
c = Client((host, port), timeout=5)
stat = c.get("stats")
stats = {}
for i in stat:
stat_name = i.split()[1]
stat_value = i.split()[2]
stats[stat_name] = stat_value
data = []
stats['usage'] = '{.2f}'.format(float(100 * float(stats['bytes']) / float(stats['limit_maxbytes'])))
###服务刚起是,访问可能为0##
if (float(stats['get_hits']) + float(stats['get_misses'])) != 0:
stats['get_hit_ratio'] = '{:.2f}'.format(float(100 * float(stats['get_hits']) /
(float(stats['get_hits']) + float(stats['get_misses']))))
else:
stats['get_hit_ratio'] = '0.0'
stats_list = ['usage', 'get_hit_ratio', 'evictions']
for key in stats_list:
stats_dict = {
'metric': '{0}.total.{1}'.format(metric, key),
'endpoint': endpoint,
'timestamp': timestamp,
'step': step,
'value': stats[key],
'counterType': 'GAUGE',
'tags': 'port=11211,metric=memcache'
}
data.append(stats_dict)
return data
def mget_slabs():
"""
@return: memcache slabs list
"""
c = Client((host, port), timeout=5)
slabs = c.get("stats slabs")
data = []
##slabs返回值倒数第二个是
num_slabs = int(slabs[-2].split()[2])
###每个slab有16个元素的返回值,循环处理
for n in range(num_slabs):
slabs_one = slabs[16 * n:16 * (n + 1)]
slab_name = slabs_one[0].split(':')[0].split()[-1]
slab_pages_k = slabs_one[2].split()[1].split(':')[1]
slab_pages_v = slabs_one[2].split()[-1]
slab_pages_dict = {
'metric': '{0}.slabs.slab_{1}.{2}'.format(metric, slab_name, slab_pages_k),
'endpoint': endpoint,
'timestamp': timestamp,
'step': step,
'value': slab_pages_v,
'counterType': 'GAUGE',
'tags': 'port=11211,metric=memcache'
}
slab_used_percent_name = slabs_one[4].split()[1].split(':')[1]
slab_used_percent_value = 100 * (float(slabs_one[4].split()[-1]) / float(slabs_one[3].split()[-1]))
slab_used_percent_dict = {
'metric': '{0}.slabs.slab_{1}.{2}_percent'.format(metric, slab_name, slab_used_percent_name),
'endpoint': endpoint,
'timestamp': timestamp,
'step': step,
'value':'{:2f}'.format(slab_used_percent_value),
'counterType': 'GAUGE',
'tags': 'port=11211,metric=memcache'
}
data.append(slab_pages_dict)
data.append(slab_used_percent_dict)
return data
def main():
mem_data = mget_stats() + mget_slabs()
json.dump(mem_data, sys.stdout)
if __name__ == "__main__":
host = bash("ps aux | grep memcache|grep -v grep |awk -F'-l' '{print $2}' |awk '{print $1}'").read()
port = bash("ps aux | grep memcache|grep -v grep |awk -F'-p' '{print $2}' |awk '{print $1}'").read()
timestamp = int(time.time())
step = 60
endpoint = 'memcache-monitor'
metric = 'memcache'
main()