-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsugar-network
executable file
·303 lines (258 loc) · 10.2 KB
/
sugar-network
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python
# Copyright (C) 2012 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import sys
import shlex
import types
from json import dumps, loads
from os.path import join, exists
from sugar_network.toolkit import coroutine
coroutine.inject()
from sugar_network import db, client, toolkit
from sugar_network.model import RESOURCES
from sugar_network.client import IPCConnection
from sugar_network.client.auth import BasicCreds, SugarCreds
from sugar_network.client.routes import ClientRoutes
from sugar_network.client.injector import Injector
from sugar_network.toolkit.router import Router, Request, Response
from sugar_network.toolkit.coroutine import this
from sugar_network.toolkit import Option, application, i18n, enforce
quiet = Option(
'turn off any output',
default=False, type_cast=Option.bool_cast, action='store_true',
name='quiet')
porcelain = Option(
'give the output in an easy-to-parse format for scripts',
default=False, type_cast=Option.bool_cast, action='store_true',
short_option='-P', name='porcelain')
post_data = Option(
'send content as a string from POST or PUT command',
name='post_data', short_option='-d')
post_file = Option(
'send content of the specified file from POST or PUT command',
name='post_file', short_option='-f')
json = Option(
'treat POST or PUT command content as a JSON data',
name='json', short_option='-j', default=False,
type_cast=Option.bool_cast, action='store_true')
offline = Option(
'do not connect to Sugar Network server',
default=False, type_cast=Option.bool_cast, action='store_true',
name='offline')
_ESCAPE_VALUE_RE = re.compile(r'([^\[\]\{\}0-9][^\]\[\{\}]+)')
class Application(application.Application):
def __init__(self, **kwargs):
application.Application.__init__(self, **kwargs)
application.rundir.value = join(client.local_root.value, 'run')
if not exists(toolkit.cachedir.value):
os.makedirs(toolkit.cachedir.value)
@application.command(
'send raw API POST request; '
'specifies all ARGUMENTs the particular API call requires',
args='PATH [ARGUMENT=VALUE]')
def POST(self):
self._request('POST', True, Response())
@application.command(
'send raw API PUT request; '
'specifies all ARGUMENTs the particular API call requires',
args='PATH [ARGUMENT=VALUE]')
def PUT(self):
self._request('PUT', True, Response())
@application.command(
'send raw API DELETE request',
args='PATH')
def DELETE(self):
self._request('DELETE', False, Response())
@application.command(
'send raw API GET request; '
'specifies all ARGUMENTs the particular API call requires',
args='PATH [ARGUMENT=VALUE]')
def GET(self):
self._request('GET', False, Response())
@application.command(
'send raw API HEAD request; '
'specifies all ARGUMENTs the particular API call requires',
args='PATH [ARGUMENT=VALUE]')
def HEAD(self):
response = Response()
self._request('HEAD', False, response)
result = {}
result.update(response)
self._dump(result)
def _request(self, method, post, response):
request = Request(method=method)
request.allow_redirects = True
request.accept_encoding = ''
if post:
if post_data.value is None and post_file.value is None:
json.value = True
post_data.value = sys.stdin.read()
if post_data.value:
request.content = post_data.value.strip()
elif post_file.value:
with file(post_file.value, 'rb') as f:
# TODO Avoid loading entire file
request.content = f.read()
request.content_type = 'application/octet-stream'
if json.value:
try:
request.content = loads(request.content)
request.content_type = 'application/json'
except Exception, error:
raise RuntimeError('Malformed JSON post data: %s' % error)
self._parse_path(request)
self._parse_args(request)
pid_path = None
cp = None
try:
if self.check_for_instance():
cp = IPCConnection()
else:
pid_path = self.new_instance()
cp = ClientRouter()
result = cp.call(request, response)
if result is None:
pass
elif response.content_type == 'application/json':
self._dump(result)
elif isinstance(result, types.GeneratorType):
for chunk in result:
self._dump(chunk)
elif hasattr(result, 'read'):
if response.content_type == 'text/event-stream':
while True:
chunk = toolkit.readline(result)
if not chunk:
break
if chunk.startswith('data: '):
self._dump(loads(chunk[6:]))
else:
while True:
chunk = result.read(toolkit.BUFFER_SIZE)
if not chunk:
break
self._print(chunk)
else:
self._print(result, '\n')
finally:
if cp is not None:
cp.close()
if pid_path:
os.unlink(pid_path)
def _parse_path(self, request):
if self.args and self.args[0].startswith('/'):
request.path = self.args.pop(0).strip('/').split('/')
def _parse_args(self, props):
for arg in self.args:
arg = shlex.split(arg)
if not arg:
continue
arg = arg[0]
if '=' in arg:
arg, value = arg.split('=', 1)
else:
arg = arg
value = 1
arg = arg.strip()
enforce(arg, 'No argument name in %r expression', arg)
if arg in props:
if isinstance(props[arg], basestring):
props[arg] = [props[arg]]
props[arg].append(value)
else:
props[arg] = value
def _dump(self, result):
if not porcelain.value:
self._print(dumps(result, indent=2, ensure_ascii=False), '\n')
return
def porcelain_dump(value):
if type(value) is dict:
if len(value) == 1:
porcelain_dump(value.values()[0])
else:
for i in sorted(value.items()):
self._print('%-18s%s' % i, '\n')
else:
if type(value) not in (list, tuple):
value = [value]
term = '\n' if len(value) > 5 else '\t'
for n, i in enumerate(value):
if n:
self._print(term)
if type(i) is dict and len(i) == 1:
i = i.values()[0]
self._print('%s' % i)
self._print('\n')
if type(result) in (list, tuple):
for i in result:
porcelain_dump(i)
elif type(result) is dict and \
'total' in result and 'result' in result:
for i in result['result']:
porcelain_dump(i)
else:
porcelain_dump(result)
def _print(self, *data):
if not quiet.value:
sys.stdout.write(''.join(data))
class ClientRouter(Router, ClientRoutes):
def __init__(self):
home = db.Volume(client.path('db'), RESOURCES)
if client.login.value and client.password.value:
creds = BasicCreds(client.login.value, client.password.value)
elif client.keyfile.value:
creds = SugarCreds(client.keyfile.value)
this.injector = Injector(client.path('cache'),
client.cache_lifetime.value, client.cache_limit.value,
client.cache_limit_percent.value)
Router.__init__(self, self)
ClientRoutes.__init__(self, home, creds, no_subscription=True)
if not offline.value:
api_url = None if client.discover_node.value else client.api.value
self.connect(api_url)
for event in self.subscribe(event='inline', state='online'):
if event['event'] != 'pong':
break
server = coroutine.WSGIServer(
('localhost', client.ipc_port.value), self)
coroutine.spawn(server.serve_forever)
#coroutine.dispatch()
i18n.init('sugar-network')
# New defaults
application.debug.value = client.logger_level()
# If tmpfs is mounted to /tmp, `os.fstat()` will return 0 free space
# and will brake offline synchronization logic
toolkit.cachedir.value = client.profile_path('tmp')
Option.seek('main', [
application.debug, quiet, porcelain, post_data, post_file, json, offline,
])
Option.seek('main', [toolkit.cachedir])
Option.seek('client', client)
Option.seek('db', db)
app = Application(
name='sugar-network-client',
description='Sugar Network client utility',
epilog='See http://wiki.sugarlabs.org/go/Sugar_Network '
'for details.',
config_files=[
'/etc/sweets.d',
'/etc/sweets.conf',
'~/.config/sweets/config',
client.profile_path('sweets.conf'),
],
)
app.start()