-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
executable file
·335 lines (283 loc) · 11.6 KB
/
server.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python
"""
Tornado server providing a socket.io repeater for NICE publish-subscribe
streams.
"""
import os
import logging
import sys
import getopt
#import socket
#import re
from tornado import web
from tornado.httpclient import HTTPError
import tornadio2 as sio
from tornadio2.router import HandshakeHandler, TornadioRouter, version_info, ioloop, DEFAULT_SETTINGS, PROTOCOLS
from tornadio2 import persistent, polling, sessioncontainer, session, proto, preflight, stats
import instrument
import pubsub
from pubsub import Publisher, Subscriber
INSTRUMENTS = {} # Start without any instruments
SERVER = "sparkle.ncnr.nist.gov"
ROOT = os.path.normpath(os.path.dirname(__file__))
SUBSCRIBER_PORT = 8001
CONTROLLER_PORT = SUBSCRIBER_PORT+1
PUBLISHER_PORT = SUBSCRIBER_PORT+2
DEBUG = False
NICE_SETTINGS = dict(
gzip = True,
)
WEB_SETTINGS = dict(
static_path = os.path.join(ROOT, "static"),
#cookie_secret = cookie.get_cookie(),
#xsrf_cookies = True,
#login_url = "/login",
gzip = True,
flash_policy_port = 10843,
flash_policy_file = os.path.join(ROOT, 'flashpolicy.xml'),
)
class IndexHandler(web.RequestHandler):
"""Regular HTTP handler to serve the index.html page"""
def get(self):
self.render('index.html')
class RestHandler(web.RequestHandler):
"""
RESTful interface to channel state
The router will be set up to take a url path such as::
http://localhost:8001/bt4/device/state
and translate this into a request for the current state on the
device subscription for the bt4 instrument.
This is not a general REST interface. In particular, the normal
REST url pattern of "http://server/<table>/<id>" which is
appropriate for database access is not supported for channels.
"""
def get(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "GET")
def put(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "PUT")
def post(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "POST")
def delete(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "DELETE")
def header(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "HEADER")
def patch(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "PATCH")
def options(self, instrument, channel, resource):
return self._call_handler(instrument, channel, resource, "OPTIONS")
def _call_handler(self, instrument, channel, resource, action):
# Allow mash-ups
self.set_header("Access-Control-Allow-Origin", SERVER)
INSTRUMENTS[instrument].channel[channel].rest(self, action, resource)
class BaseHandler(HandshakeHandler):
def set_default_headers(self):
#print "allow requests from other parts of this server"
self.set_header("Access-Control-Allow-Origin", SERVER)
print "allow cookies (why?)"
self.set_header("Access-Control-Allow-Credentials", "true")
class MyRouter(TornadioRouter):
"""TornadIO2 Router that allows specifying your own Handler"""
def __init__(self,
connection,
user_settings=dict(),
namespace='socket.io',
io_loop=None,
handler=HandshakeHandler):
"""Constructor.
`connection`
SocketConnection class instance
`user_settings`
Settings
`namespace`
Router namespace, defaulted to 'socket.io'
`io_loop`
IOLoop instance, optional.
"""
# TODO: Version check
if version_info[0] < 2:
raise Exception('TornadIO2 requires Tornado 2.0 or higher.')
# Store connection class
self._connection = connection
# Initialize io_loop
self.io_loop = io_loop or ioloop.IOLoop.instance()
# set the handler
self.handler = handler
# Settings
self.settings = DEFAULT_SETTINGS.copy()
if user_settings:
self.settings.update(user_settings)
# Sessions
self._sessions = sessioncontainer.SessionContainer()
check_interval = self.settings['session_check_interval']
self._sessions_cleanup = ioloop.PeriodicCallback(self._sessions.expire,
check_interval,
self.io_loop)
self._sessions_cleanup.start()
# Stats
self.stats = stats.StatsCollector()
self.stats.start(self.io_loop)
# Initialize URLs
self._transport_urls = [
(r'/%s/(?P<version>\d+)/$' % namespace,
self.handler,
dict(server=self))
]
for t in self.settings.get('enabled_protocols', dict()):
proto = PROTOCOLS.get(t)
if not proto:
# TODO: Error logging
continue
# Only version 1 is supported
self._transport_urls.append(
(r'/%s/1/%s/(?P<session_id>[^/]+)/?' %
(namespace, t),
proto,
dict(server=self))
)
class WebConnection(sio.SocketConnection):
"""
Manage the top level socket IO connection.
"""
def get_endpoint(self, endpoint):
"""
Parse /instrument/channel into specific channel handlers.
"""
if not endpoint.startswith('/'): return
try:
_,name,channel = endpoint.split('/', 3)
except ValueError:
return
# Clients should not be able to create arbitrary instruments
if name not in INSTRUMENTS:
raise HTTPError(404,"Instrument %s is not online"%name)
#print "Web connection to",name,channel,INSTRUMENTS[name],INSTRUMENTS[name].channel[channel]
#print INSTRUMENTS[name].channel[channel].channel_state()
# Don't allow control from the general web connection
if channel != 'control':
return lambda *args, **kw: Subscriber(INSTRUMENTS[name].channel[channel], *args, **kw)
class NiceConnection(sio.SocketConnection):
"""
Manage the top level socket IO connection.
"""
def get_endpoint(self, endpoint):
"""
Parse /instrument/channel into specific channel handlers.
"""
if not endpoint.startswith('/'): return
try:
_,name,channel = endpoint.split('/', 3)
except ValueError:
return
if name not in INSTRUMENTS:
INSTRUMENTS[name] = instrument.Instrument(name=name)
#print "NICE connection to",name,channel,INSTRUMENTS[name],INSTRUMENTS[name].channel[channel]
#print INSTRUMENTS[name].channel[channel].channel_state()
# There is role reversal with publisher and subscriber for the control
# channel: the instrument is acting as a single subscriber for all
# the web clients who are publishing commands to control it.
if channel == 'control':
return lambda *args, **kw: Subscriber(INSTRUMENTS[name].channel[channel], *args, **kw)
elif channel in INSTRUMENTS[name].channel:
return lambda *args, **kw: Publisher(INSTRUMENTS[name].channel[channel], *args, **kw)
class ControlConnection(sio.SocketConnection):
"""
Put the instrument control web connection on its own port.
"""
# TODO: may want per instrument restrictions on web access, perhaps through authentication
def get_endpoint(self, endpoint):
"""
Parse /instrument/channel into specific channel handlers.
"""
if not endpoint.startswith('/'): return
try:
_,name,channel = endpoint.split('/', 3)
except ValueError:
return
if name not in INSTRUMENTS:
raise HTTPError(404,"Instrument %s is not online"%name)
# There is role reversal with publisher and subscriber for the control
# channel: here the instrument is acting as a single subscriber to
# all of the web clients who are publishing commands to control it.
if channel == 'control':
return lambda *args, **kw: Publisher(INSTRUMENTS[name].channel[channel], *args, **kw)
def serve():
"""
Run the NICE repeater, forwarding subscription streams to the web.
"""
# Define the interface to the internal and external servers
nice_router = MyRouter(NiceConnection, handler=BaseHandler)
control_router = MyRouter(ControlConnection, handler=BaseHandler)
web_router = MyRouter(WebConnection, handler=BaseHandler)
web_routes = [
(r"/", IndexHandler),
# TODO: the following pattern is too generic it matches most /x/y/z
# it only works because '.' is excluded from the matched patterns.
(r"/(?P<instrument>[a-zA-Z0-9_]*)/(?P<channel>[a-z_]*)/(?P<resource>[a-z_]*)", RestHandler),
]
# Point the servers to internal and external ports
subscriber_app = web.Application(
web_router.apply_routes(web_routes),
socket_io_port=SUBSCRIBER_PORT,
debug=DEBUG,
**WEB_SETTINGS)
controller_app = web.Application(
control_router.apply_routes([]),
socket_io_port=CONTROLLER_PORT,
debug=DEBUG,
**NICE_SETTINGS)
publisher_app = web.Application(
nice_router.apply_routes([]),
socket_io_port=PUBLISHER_PORT,
debug=DEBUG,
**NICE_SETTINGS)
# Server application
loop = ioloop.IOLoop.instance()
sio.SocketServer(subscriber_app, auto_start=False, io_loop=loop)
sio.SocketServer(controller_app, auto_start=False, io_loop=loop)
sio.SocketServer(publisher_app, auto_start=False, io_loop=loop)
logging.info('Entering IOLoop...')
loop.start()
def usage():
print """\
usage: server.py [options]
--port=integer
Port number for web connections. Default is 8001. Controllers
connect on port+1 and publishers on port+2
--capture=filename
Save the entire published data streams to a file so they can be replayed
with test/playback.py
--debug
Run the tornado server in debug mode, which provides error messages on the
client and triggers restart when the server file changes.
The web port should be widely accessible, the publisher port should only be
accessible to instrument computers and the controller port should only be
accessible to computers that are allowed to control the instruments. The
port permissions should be configured within the firewall.
"""
def main():
try:
longopts = ["capture=","port=","debug"]
opts, args = getopt.getopt(sys.argv[1:], "c:p:d", longopts)
if args:
raise getopt.GetoptError("server.py only accepts options")
except getopt.GetoptError, exc:
print str(exc)
usage()
sys.exit(1)
DEBUG=False
for name,value in opts:
if name in ("-c", "--capture"):
pubsub.start_capture(value)
elif name in ("-p", "--port"):
SUBSCRIBER_PORT = int(value)
CONTROLLER_PORT = SUBSCRIBER_PORT+1
PUBLISHER_PORT = SUBSCRIBER_PORT+2
elif name in ("-d", "--debug"):
DEBUG = True
else:
print "unknown option",name
#logging.getLogger().setLevel(logging.INFO)
logging.getLogger().setLevel(logging.DEBUG if DEBUG else logging.INFO)
serve()
if __name__ == "__main__":
main()