-
Notifications
You must be signed in to change notification settings - Fork 477
/
client.py
283 lines (234 loc) · 8.34 KB
/
client.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from . import ejson as json
from protocol import DDPProtocol
from threading import Event, Thread
from ws4py.client.threadedclient import WebSocketClient
import argparse
import socket
import sys
import time
import uuid
class WSClient(WebSocketClient):
def __init__(self, *args, **kwargs):
self.client = kwargs.pop('client')
self.protocol = DDPProtocol(self)
super(WSClient, self).__init__(*args, **kwargs)
def connect(self):
self.sock.settimeout(10)
rv = super(WSClient, self).connect()
if self.sock:
self.sock.settimeout(None)
return rv
def opened(self):
self.protocol.on_open()
def closed(self, code, reason=None):
self.protocol.on_close(code, reason)
def received_message(self, message):
self.protocol.on_message(message.data.decode('utf8'))
def on_open(self):
self.client.on_open()
def on_message(self, message):
self.client._recv(message)
def on_close(self, code, reason=None):
self.client.on_close(code, reason)
class Call(object):
def __init__(self, method, params):
self.id = str(uuid.uuid4())
self.method = method
self.params = params
self.returned = Event()
self.result = None
self.error = None
self.trace = None
class ClientException(Exception):
def __init__(self, error, trace=None):
self.error = error
self.trace = trace
def __str__(self):
return self.error
class CallTimeout(ClientException):
pass
class Client(object):
def __init__(self, uri=None):
self._calls = {}
self._pings = {}
if uri is None:
uri = 'ws://127.0.0.1:6000/websocket'
self._ws = WSClient(uri, client=self)
self._closed = Event()
self._ws.connect()
self._connected = Event()
self._connected.wait(5)
self._event_callbacks = {}
if not self._connected.is_set():
raise ClientException('Failed connection handshake')
def __enter__(self):
return self
def __exit__(self, typ, value, traceback):
self.close()
if typ is not None:
raise
def _send(self, data):
self._ws.send(json.dumps(data))
def _recv(self, message):
_id = message.get('id')
msg = message.get('msg')
if msg == 'connected':
self._connected.set()
elif msg == 'failed':
raise ClientException('Unsupported protocol version')
elif msg == 'pong' and _id is not None:
ping_event = self._pings.get(_id)
if ping_event:
ping_event.set()
elif _id is not None and msg == 'result':
call = self._calls.get(_id)
if call:
call.result = message.get('result')
if 'error' in message:
call.error = message['error'].get('error')
call.trace = message['error'].get('trace')
call.returned.set()
self._unregister_call(call)
elif msg in ('added', 'changed', 'removed'):
if self.event_callback:
if '*' in self._event_callbacks:
self._event_callbacks['*'](msg.upper(), **message)
if collection in self._event_callbacks:
self._event_callbacks[collection](msg.upper(), **message)
def register_event_callback(self, name, callback):
self._event_callbacks[name] = callback
def on_open(self):
self._send({
'msg': 'connect',
'version': '1',
'support': ['1'],
})
def on_close(self, code, reason=None):
self._closed.set()
def _register_call(self, call):
self._calls[call.id] = call
def _unregister_call(self, call):
self._calls.pop(call.id, None)
def call(self, method, *params, **kwargs):
timeout = kwargs.pop('timeout', 60)
c = Call(method, params)
self._register_call(c)
self._send({
'msg': 'method',
'method': c.method,
'id': c.id,
'params': c.params,
})
if not c.returned.wait(timeout):
self._unregister_call(c)
raise CallTimeout("Call timeout")
if c.error:
raise ClientException(c.error, c.trace)
return c.result
def ping(self, timeout=10):
_id = str(uuid.uuid4())
event = self._pings[_id] = Event()
self._send({
'msg': 'ping',
'id': _id,
})
if not event.wait(timeout):
return False
return True
def close(self):
self._ws.close()
# Wait for websocketclient thread to close
self._closed.wait(1)
def __del__(self):
self.close()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--quiet', action='store_true')
parser.add_argument('-u', '--uri')
parser.add_argument('-U', '--username')
parser.add_argument('-P', '--password')
parser.add_argument('-t', '--timeout', type=int)
subparsers = parser.add_subparsers(help='sub-command help', dest='name')
iparser = subparsers.add_parser('call', help='Call method')
iparser.add_argument('method', nargs='+')
iparser = subparsers.add_parser('ping', help='Ping')
iparser = subparsers.add_parser('waitready', help='Wait server')
iparser = subparsers.add_parser('sql', help='Run SQL command')
iparser.add_argument('sql', nargs='+')
args = parser.parse_args()
def from_json(args):
for i in args:
try:
yield json.loads(i)
except:
yield i
if args.name == 'call':
with Client(uri=args.uri) as c:
try:
if args.username and args.password:
if not c.call('auth.login', args.username, args.password):
raise ValueError('Invalid username or password')
except Exception as e:
print "Failed to login: ", e
sys.exit(0)
try:
kwargs = {}
if args.timeout:
kwargs['timeout'] = args.timeout
rv = c.call(args.method[0], *list(from_json(args.method[1:])), **kwargs)
if isinstance(rv, (int, str, unicode)):
print(rv)
else:
print(json.dumps(rv))
except ClientException as e:
if not args.quiet and e.trace:
print >> sys.stderr, e.trace['formatted']
sys.exit(1)
elif args.name == 'ping':
with Client(uri=args.uri) as c:
if not c.ping():
sys.exit(1)
elif args.name == 'sql':
with Client(uri=args.uri) as c:
try:
if args.username and args.password:
if not c.call('auth.login', args.username, args.password):
raise ValueError('Invalid username or password')
except Exception as e:
print "Failed to login: ", e
sys.exit(0)
rv = c.call('datastore.sql', args.sql[0])
if rv:
for i in rv:
data = []
for f in i:
if isinstance(f, bool):
data.append(str(int(f)))
else:
data.append(str(f))
print '|'.join(data)
elif args.name == 'waitready':
"""
This command is supposed to wait until we are able to connect
to middleware and perform a simple operation (core.ping)
Reason behind this is because middlewared starts and we have to
wait the boot process until it is ready to serve connections
"""
def waitready(args):
while True:
try:
with Client(uri=args.uri) as c:
return c.call('core.ping')
except socket.error:
time.sleep(0.2)
continue
thread = Thread(target=waitready, args=[args])
thread.daemon = True
thread.start()
thread.join(args.timeout)
if thread.is_alive():
sys.exit(1)
else:
sys.exit(0)
if __name__ == '__main__':
main()