-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrouting.py
481 lines (400 loc) · 16.5 KB
/
routing.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""Routing Service for EIDA.
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
any later version.
:Copyright:
2014-2023 Helmholtz Centre Potsdam GFZ German Research Centre for Geosciences, Potsdam, Germany
:License:
GPLv3
:Platform:
Linux
.. moduleauthor:: Javier Quinteros <javier@gfz-potsdam.de>, GEOFON, GFZ Potsdam
"""
import os
import cgi
import datetime
import logging
import configparser
import json
from http import HTTPStatus
from routeutils.wsgicomm import WIContentError
from routeutils.wsgicomm import WIClientError
from routeutils.wsgicomm import WIError
from routeutils.wsgicomm import send_plain_response
from routeutils.wsgicomm import send_json_response
from routeutils.wsgicomm import send_html_response
from routeutils.wsgicomm import send_xml_response
from routeutils.wsgicomm import send_error_response
from routeutils.utils import Stream
from routeutils.utils import TW
from routeutils.utils import GeoRectangle
from routeutils.utils import RequestMerge
from routeutils.utils import RoutingCache
from routeutils.utils import RoutingException
from routeutils.utils import str2date
from routeutils.routing import lsNSLC
from routeutils.routing import applyFormat
from typing import Union
from typing import List
def getParam(parameters: Union[cgi.FieldStorage, dict], names: Union[list, set],
default: Union[str, None], csv: bool = False) -> Union[str, List[str], None]:
"""Read a parameter and return its value or a default value in case it is not found.
The csv parameter is used to split the value in case of multiple values separated by commas. This means
that the result will be a string if csv is False, and a list of string(s) if csv is True.
"""
for n in names:
if n in parameters:
if isinstance(parameters[n], list):
raise Exception('Parameter(s) %s returned a list instead of a value. Multiple input?' % names)
result = parameters[n].value.upper()
break
else:
result = default
# WARNING This converts the result from a string to a list with a string(s) if "cvs" is True
if csv:
result = result.split(',')
return result
def makeQueryGET(parameters: Union[cgi.FieldStorage, dict]) -> RequestMerge:
"""Process a request made via a GET method."""
global routes
# List all the accepted parameters
allowedParams = ['net', 'network',
'sta', 'station',
'loc', 'location',
'cha', 'channel',
'start', 'starttime',
'end', 'endtime',
'minlat', 'minlatitude',
'maxlat', 'maxlatitude',
'minlon', 'minlongitude',
'maxlon', 'maxlongitude',
'service', 'format',
'alternative', 'nodata']
for param in parameters:
if param not in allowedParams:
msg = 'Unknown parameter: %s' % param
raise WIClientError(msg)
try:
# If CSV is True the result will be a list!
net = getParam(parameters, ['net', 'network'], '*', csv=True)
sta = getParam(parameters, ['sta', 'station'], '*', csv=True)
loc = getParam(parameters, ['loc', 'location'], '*', csv=True)
cha = getParam(parameters, ['cha', 'channel'], '*', csv=True)
# Here the result will be a string
start = getParam(parameters, ['start', 'starttime'], None)
except Exception as e:
raise WIClientError(str(e))
try:
if start is not None:
start = str2date(start)
except Exception:
msg = 'Error while converting starttime parameter.'
raise WIClientError(msg)
# The result will be a string (not a list)
endt = getParam(parameters, ['end', 'endtime'], None)
try:
if endt is not None:
endt = str2date(endt)
except Exception:
msg = 'Error while converting endtime parameter.'
raise WIClientError(msg)
try:
minlat = float(getParam(parameters, ['minlat', 'minlatitude'],
'-90.0'))
except Exception:
msg = 'Error while converting the minlatitude parameter.'
raise WIClientError(msg)
try:
maxlat = float(getParam(parameters, ['maxlat', 'maxlatitude'],
'90.0'))
except Exception:
msg = 'Error while converting the maxlatitude parameter.'
raise WIClientError(msg)
try:
minlon = float(getParam(parameters, ['minlon', 'minlongitude'],
'-180.0'))
except Exception:
msg = 'Error while converting the minlongitude parameter.'
raise WIClientError(msg)
try:
maxlon = float(getParam(parameters, ['maxlon', 'maxlongitude'],
'180.0'))
except Exception:
msg = 'Error while converting the maxlongitude parameter.'
raise WIClientError(msg)
# These two results will be strings
ser = getParam(parameters, ['service'], 'dataselect').lower()
aux = getParam(parameters, ['alternative'], 'false').lower()
if aux == 'true':
alt = True
elif aux == 'false':
alt = False
else:
msg = 'Wrong value passed in parameter "alternative"'
raise WIClientError(msg)
# form will be a string
form = getParam(parameters, ['format'], 'xml').lower()
if alt and (form == 'get'):
msg = 'alternative=true and format=get are incompatible parameters'
raise WIClientError(msg)
# print start, type(start), endt, type(endt), (start > endt)
if (start is not None) and (endt is not None) and (start > endt):
msg = 'Start datetime cannot be greater than end datetime'
raise WIClientError(msg)
if ((minlat == -90.0) and (maxlat == 90.0) and (minlon == -180.0) and
(maxlon == 180.0)):
geoLoc = None
else:
geoLoc = GeoRectangle(minlat, maxlat, minlon, maxlon)
result = RequestMerge()
# Expand lists in parameters (f.i., cha=BHZ,HHN) and yield all possible
# values
for (n, s, l, c) in lsNSLC(net, sta, loc, cha):
try:
st = Stream(n, s, l, c)
tw = TW(start, endt)
result.extend(routes.getRoute(st, tw, ser, geoLoc, alt))
except RoutingException:
pass
if len(result) == 0:
raise WIContentError()
return result
def makeQueryPOST(postText) -> RequestMerge:
"""Process a request made via a POST method."""
global routes
# These are the parameters accepted appart from N.S.L.C
extraParams = ['format', 'service', 'alternative', 'nodata',
'minlat', 'minlatitude',
'maxlat', 'maxlatitude',
'minlon', 'minlongitude',
'maxlon', 'maxlongitude']
# Default values
ser = 'dataselect'
alt = False
result = RequestMerge()
# Check if we are still processing the header of the POST body. This has a
# format like key=value, one per line.
inHeader = True
minlat = -90.0
maxlat = 90.0
minlon = -180.0
maxlon = 180.0
filterdefined = False
for line in postText.splitlines():
if not len(line):
continue
if inHeader and ('=' not in line):
inHeader = False
if inHeader:
try:
key, value = line.split('=')
key = key.strip()
value = value.strip()
except Exception:
msg = 'Wrong format detected while processing: %s' % line
raise WIClientError(msg)
if key not in extraParams:
msg = 'Unknown parameter "%s"' % key
raise WIClientError(msg)
if key == 'service':
ser = value
elif key == 'alternative':
alt = True if value.lower() == 'true' else False
elif key == 'minlat':
minlat = float(value.lower())
elif key == 'maxlat':
maxlat = float(value.lower())
elif key == 'minlon':
minlon = float(value.lower())
elif key == 'maxlon':
maxlon = float(value.lower())
continue
# I'm already in the main part of the POST body, where the streams are
# specified
filterdefined = True
net, sta, loc, cha, start, endt = line.split()
net = net.upper()
sta = sta.upper()
loc = loc.upper()
try:
if start.strip() == '*':
start = None
else:
start = str2date(start)
except Exception:
msg = 'Error while converting %s to datetime' % start
raise WIClientError(msg)
try:
if endt.strip() == '*':
endt = None
else:
endt = str2date(endt)
except Exception:
msg = 'Error while converting %s to datetime' % endt
raise WIClientError(msg)
if ((minlat == -90.0) and (maxlat == 90.0) and (minlon == -180.0) and
(maxlon == 180.0)):
geoLoc = None
else:
geoLoc = GeoRectangle(minlat, maxlat, minlon, maxlon)
try:
st = Stream(net, sta, loc, cha)
tw = TW(start, endt)
result.extend(routes.getRoute(st, tw, ser, geoLoc, alt))
except RoutingException:
pass
if not filterdefined:
st = Stream('*', '*', '*', '*')
tw = TW(None, None)
geoLoc = None
result.extend(routes.getRoute(st, tw, ser, geoLoc, alt))
if len(result) == 0:
raise WIContentError()
return result
# This variable will be treated as GLOBAL by all the other functions
routes = None
def application(environ, start_response):
"""Main WSGI handler. Process requests and calls proper functions."""
global routes
fname = environ['PATH_INFO']
config = configparser.RawConfigParser()
here = os.path.dirname(__file__)
config.read(os.path.join(here, 'routing.cfg'))
verbo = config.get('Service', 'verbosity')
baseURL = config.get('Service', 'baseURL')
# Warning is the default value
verboNum = getattr(logging, verbo.upper(), 30)
logging.info('Verbosity configured with %s' % verboNum)
logging.basicConfig(level=verboNum)
# Among others, this will filter wrong function names,
# but also the favicon.ico request, for instance.
if fname is None:
raise WIClientError('Method name not recognized!')
# return send_html_response(status, 'Error! ' + status, start_response)
if len(environ['QUERY_STRING']) > 1000:
return send_error_response("414 Request URI too large",
"maximum URI length is 1000 characters",
start_response)
try:
if environ['REQUEST_METHOD'] == 'GET':
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
try:
outForm = getParam(form, ['format'], default='xml').lower()
except Exception:
message = "Error while parsing parameter 'format': %s" % str(form['format'])
return send_error_response("400 Bad Request", message, start_response)
elif environ['REQUEST_METHOD'] == 'POST':
try:
length = int(environ.get('CONTENT_LENGTH', '0'))
except ValueError:
length = 0
# If there is a body to read
if length:
form = environ['wsgi.input'].read(length).decode()
else:
form = environ['wsgi.input'].read().decode()
for line in form.splitlines():
if not len(line):
continue
if '=' not in line:
break
k, v = line.split('=')
if k.strip() == 'format':
outForm = v.strip()
else:
raise Exception
except ValueError as e:
if str(e) == "Maximum content length exceeded":
# Add some user-friendliness (this message triggers an alert
# box on the client)
return send_error_response("400 Bad Request",
"maximum request size exceeded",
start_response)
return send_error_response("400 Bad Request", str(e), start_response)
# Check whether the function called is implemented
implementedFunctions = ['query', 'application.wadl', 'localconfig',
'globalconfig', 'version', 'info', '',
'virtualnets', 'endpoints', 'dc']
if routes is None:
# Add routing cache here, to be accessible to all modules
routesFile = os.path.join(here, 'data', 'routing.xml')
configFile = os.path.join(here, 'routing.cfg')
routes = RoutingCache(routesFile, configFile)
fname = environ['PATH_INFO'].split('/')[-1]
if fname not in implementedFunctions:
return send_error_response("400 Bad Request",
'Function "%s" not implemented.' % fname,
start_response)
if fname == '':
# here = os.path.dirname(__file__)
helpFile = os.path.join(here, 'help.html')
with open(helpFile, 'r') as helpHandle:
iterObj = helpHandle.read()
status = '200 OK'
return send_html_response(status, iterObj, start_response)
elif fname == 'application.wadl':
# here = os.path.dirname(__file__)
appWadl = os.path.join(here, 'application.wadl')
with open(appWadl, 'r') \
as appFile:
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
iterObj = appFile.read() % (baseURL, tomorrow)
status = '200 OK'
return send_xml_response(status, iterObj, start_response)
elif fname == 'query':
makeQuery = globals()['makeQuery%s' % environ['REQUEST_METHOD']]
try:
iterObj = makeQuery(form)
iterObj = applyFormat(iterObj, outForm)
status = '200 OK'
if outForm == 'xml':
return send_xml_response(status, iterObj, start_response)
elif outForm == 'json':
return send_json_response(status, iterObj, start_response)
else:
return send_plain_response(status, iterObj, start_response)
except WIError as w:
if isinstance(w, WIContentError) and 'nodata' in form:
retcode = getParam(form, ['nodata'], '204')
retstatus = '%s %s' % (retcode, HTTPStatus(int(retcode)).phrase)
else:
retstatus = w.status
return send_error_response(retstatus, w.body, start_response)
elif fname == 'dc':
try:
with open(os.path.join(here, 'data', 'routing.json')) as fin:
dc = json.load(fin)
except Exception:
dc = dict()
return send_json_response('200 OK', dc, start_response)
elif fname == 'endpoints':
result = routes.endpoints()
return send_plain_response('200 OK', result, start_response)
elif fname == 'localconfig':
result = routes.localConfig()
if outForm == 'xml':
return send_xml_response('200 OK', result,
start_response)
elif fname == 'globalconfig':
result = routes.globalConfig()
if outForm == 'fdsn':
return send_json_response('200 OK', result,
start_response)
# Only FDSN format is supported for the time being
text = 'Only format=FDSN is supported'
return send_error_response("400 Bad Request", text, start_response)
elif fname == 'virtualnets':
result = routes.virtualNets()
return send_json_response('200 OK', result,
start_response)
elif fname == 'version':
text = "1.2.3"
return send_plain_response('200 OK', text, start_response)
elif fname == 'info':
config = configparser.RawConfigParser()
# here = os.path.dirname(__file__)
config.read(os.path.join(here, 'routing.cfg'))
text = config.get('Service', 'info')
return send_plain_response('200 OK', text, start_response)
raise Exception('This point should have never been reached!')