-
Notifications
You must be signed in to change notification settings - Fork 1
/
sstoreclient.py
83 lines (77 loc) · 2.46 KB
/
sstoreclient.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
import socket
import json
# Class which acts as an interface to S-Store.
class sstoreclient(object):
addr = None
port = None
s = None
pipe = None
buf = None
connected = False
def __init__(self, addr='localhost', port=6000):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.pipe = self.s.makefile()
self.addr = addr
self.port = port
self.buf = ''
self.connected = False
def connect(self):
if not self.connected:
self.s.connect((self.addr, self.port))
self.connected = True
return True
def disconnect(self):
try:
self.s.close()
finally:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.pipe.close()
finally:
self.pipe = self.s.makefile()
self.connected = False
return True
def reconnect(self):
self.disconnect()
self.connect()
return True
def call_proc(self, proc='', args=[], keepalive=False):
# Connect first, if necessary.
if not self.connected:
self.connect()
# Clear buffer.
self.buf = ''
# Construct the object which will be converted to JSON and sent to the
# database client.
call = dict()
call['proc'] = proc
call['args'] = list()
for arg in args:
call['args'] += [arg]
# Send JSON to the database client, then receive results.
try:
self.pipe.write(json.dumps(call) + "\n")
try:
self.pipe.flush()
except Exception as e:
# If socket was terminated prematurely, attempt to reconnect.
if e.errno == 32:
self.reconnect()
self.pipe.write(json.dumps(call) + "\n")
self.pipe.flush()
else:
raise e
except Exception as e:
# If socket was terminated prematurely, attempt to reconnect.
if e.errno == 32:
self.reconnect()
self.pipe.write(json.dumps(call) + "\n")
self.pipe.flush()
else:
raise e
self.buf = self.pipe.readline()
rtn = json.loads(self.buf)
# If we haven't instructed the connection to stay open, disconnect.
if not keepalive:
self.disconnect()
return rtn