-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathtarantool_admin.py
64 lines (50 loc) · 1.56 KB
/
tarantool_admin.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
import socket
import yaml
class TarantoolAdmin(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.is_connected = False
self.socket = None
def connect(self):
self.socket = socket.create_connection((self.host, self.port))
self.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
self.is_connected = True
self.socket.recv(256) # skip greeting
def disconnect(self):
if self.is_connected:
self.socket.close()
self.socket = None
self.is_connected = False
def reconnect(self):
self.disconnect()
self.connect()
def __enter__(self):
self.connect()
return self
def __exit__(self, type, value, tb):
self.disconnect()
def __call__(self, command):
return self.execute(command)
def execute(self, command):
if not command:
return
if not self.is_connected:
self.connect()
cmd = (command.replace('\n', ' ') + '\n').encode()
try:
self.socket.sendall(cmd)
except socket.error:
# reconnect and try again
self.reconnect()
self.socket.sendall(cmd)
bufsiz = 4096
res = ""
while True:
buf = self.socket.recv(bufsiz)
if not buf:
break
res = res + buf.decode()
if (res.rfind("\n...\n") >= 0 or res.rfind("\r\n...\r\n") >= 0):
break
return yaml.safe_load(res)