serverWsgi.michel.py 22.2 KB
Newer Older
Caillat Michel's avatar
Caillat Michel committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python

from bottle import route, run, get, request, view, default_app, response

import astropy

import sys
import socket
import getopt
import os
import traceback
import collections
import numpy as np

import json
import errno
import logging
18
from autologging import logged, TRACE, traced
Caillat Michel's avatar
Caillat Michel committed
19
20
21
22
23
24
25
26
27

ARTEMIXDataDir = None
FITSRootDir = None
SAMPDataDir = None
baseUrl = "/artemix"

logger = None
dm = None

28
import dataManager_michel as dataManager
Caillat Michel's avatar
Caillat Michel committed
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

#####################################################################
#                                                                   #
#                            Utilities                              #
#                                                                   #
#####################################################################

""" enable cross domain ajax requests

"""
def enable_cors(fn):
  def _enable_cors(*args, **kwargs):
    # set CORS headers
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

    if request.method != 'OPTIONS':
        # actual request; reply with the actual response
        return fn(*args, **kwargs)

  return _enable_cors

def getFloatValue(value):
    if value is not None and str(value) != "null":
        return float(value)
    return None

def getIntValue(value):
    if value is not None and str(value) != "null":
        return int(value)
    return None

def getBoolValue(value):
    if value is not None and str(value) != "null":
        return value == "true"
    return None

"""
	Replaces NaN values by None in array
"""
def cleanNanInList(arr):
	# result = listToClean
	# for i in range(0, len(result)):
	# 	for j in range(0, len(result[i])):
	# 		if np.isnan(result[i][j]):
	# 			result[i][j] = None
    result = arr
    result[np.isnan(result)] = None
    return result

"""
    Given filename ( string )
    returns a string where each space character present in filename is replaced by '+' character.
"""
def rebuildFilename(filename):
    result = byteify(filename.replace(" ", "+"))
    if ((result[0] == '"' and result[len(result) - 1] == '"') or ( result[0] == "'" and result[len(result) - 1] == "'" )):
        result = result[1:-1]
    return result

"""
    A function to transform the content of a dictionary a unicode value into its ascii's
    see https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json
"""

def byteify(input):
    #logging.debug("byteify : entering")
    #logging.debug("input = %r and itstype = %s" % (input, type(input)))
    result = None
    if isinstance(input, dict):
        result = {byteify(key): byteify(value)
                for key, value in input.items()}
    elif isinstance(input, list):
        result = [byteify(element) for element in input]
    elif isinstance(input, str):
        result =  input.encode('utf-8').decode('utf-8')
    elif isinstance(input, bytes):
        result = input.encode('utf-8').decode('utf-8')
    else:
        result = input
    #logging.debug("result = %r" % result)
    return result


#####################################################################
#                                                                   #
#                   Routes definitions                              #
#                                                                   #
#####################################################################

"""
  Check that the server is alive and waiting.
"""
@route(baseUrl+"/ping", name='upAnWaiting', method='GET')
@enable_cors
def upAnWaiting():
  logger.debug("upAndWaiting : entering")
  logger.debug("upAndWaiting : exiting")
  return "{status: %r, message : 'Up and waiting', 'result': %r}" % (True, request)

"""
    Given two values expressed in degrees one for a Right Ascension (ra) and one for a Declination
    returns their respectives conversion in Hour Minute Second and Degree Minute Second
"""
@route( baseUrl+'/degToHMSDMS', name='degToHMSDMS', method='GET')
@enable_cors
def degToHMSDMS():
    fileName = rebuildFilename(request.GET['fileName'])
    ra = getFloatValue(request.GET['ra'])
    dec = getFloatValue(request.GET['dec'])
    sessionID = request.GET['sessionID']
    response.content_type = "application/json; charset=utf-8"
142
    return json.dumps(dm.degToHMSDMS(ra, dec, fileName))
Caillat Michel's avatar
Caillat Michel committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160


"""
    Given a FITS filename and an interval of positive integers values and
    an integer step returns an array of Hour:Minute:Second right ascension values
    located on the grid defined by (start, end, step)
"""
@route( baseUrl+'/rangeToHMS', name='rangeToHMS', method='GET')
@enable_cors
def rangeToHMS():

    fileName = rebuildFilename(request.GET['fileName'])
    sessionID = request.GET['sessionID']
    start = getIntValue(request.GET['start'])
    end = getIntValue(request.GET['end'])
    step = getIntValue(request.GET['step'])
    response.content_type = "application/json; charset=utf-8"

161
    return json.dumps(dm.rangeToHMS(start, end, step, fileName))
Caillat Michel's avatar
Caillat Michel committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178

"""
    Given a FITS filename and an interval of positive integers values and
    an integer step returns an array of Degree:Minute:Second declination values
    located on the grid defined by (start, end, step)
"""
@route( baseUrl+'/rangeToDMS', name='rangeToDMS', method='GET')
@enable_cors
def rangeToDMS():

    fileName = rebuildFilename(request.GET['fileName'])
    sessionID = request.GET['sessionID']
    start = getIntValue(request.GET['start'])
    end = getIntValue(request.GET['end'])
    step = getIntValue(request.GET['step'])
    response.content_type = "application/json; charset=utf-8"

179
    return json.dumps(dm.rangeToDMS(start, end, step, fileName))
Caillat Michel's avatar
Caillat Michel committed
180
181
182
183
184
185
186
187

"""
    Given fileName read corresponding the FITS file in memory
    returns the FITS header of that file.
"""
@route( baseUrl+'/setData', name='setData', method='GET')
@enable_cors
def setData():
188
189
    logger.debug("setData : entering")
    relFITSFilePath = rebuildFilename(request.GET['fileName'])
Caillat Michel's avatar
Caillat Michel committed
190
191
    sessionID = request.GET['sessionID']
    response.content_type = "application/json; charset=utf-8"
192
193
194
    result = dm.setData(relFITSFilePath)
    logger.debug("setData : exiting")
    return json.dumps(result)
Caillat Michel's avatar
Caillat Michel committed
195
196
197
198
199
200
201
202
203
204
205
206
207

"""
    Given filename return the shape of the data cube contained
    in fileName
"""
@route( baseUrl+'/getDimensions', name='getDimensions', method='GET')
@enable_cors
def getDimensions():

    fileName = rebuildFilename(request.GET['fileName'])
    sessionID = request.GET['sessionID']
    response.content_type = "application/json; charset=utf-8"

208
    return json.dumps(dm.getDimensions(fileName))
Caillat Michel's avatar
Caillat Michel committed
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

"""
    Given a multidimensional array l
    return a flattened representation of l
"""
@route( baseUrl+'/flatten', name='flatten', method='GET')
@enable_cors
def flatten():

    l = request.GET['l']

    return json.dumps(dm.flatten(l))

"""
    Given relFITSFilePath and a triple of integer values iFreq, iRA, iDEC
    returns the pixel value with coordinates (iFreq, iRA, iDEC) in the data cube
    associated to relFITSFilePath.
"""
@route( baseUrl+'/getPixelValueAtiFreqiRAiDEC', name="getPixelValueAtiFreqiRAiDEC", method='GET')
@enable_cors
def getPixelValueAtiFreqiRAiDEC():
    logger.debug("getPixelValueAtiFreqiRAiDEC - wrapper : entering" )

    relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    sessionID = request.GET['sessionID']
    iFreq = getIntValue(request.GET['iFreq'])
    iRA = getIntValue(request.GET['iRA'])
    iDEC = getIntValue(request.GET['iDEC'])
    response.content_type = "application/json; charset=utf-8"

    result = json.dumps(dm.getPixelValueAtiFreqiRAiDEC(relFITSFilePath, iFreq, iRA, iDEC))
    logger.debug("getPixelValueAtiFreqiRAiDEC - wrapper : exiting" )
    return result

"""
    Given an integer sliceNumb and an integer step
    and a string fileName
    returns a 2D array made of one pixel every (step, step)
    of the slice sliceNumb in the datacube contained in fileName
"""
@route( baseUrl+'/getSlice', name='getSlice', method='GET')
@enable_cors
def getSlice():
252
    logger.debug("getSlice - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
253

254
    relFITSFilePath = rebuildFilename(request.GET['fileName'])
Caillat Michel's avatar
Caillat Michel committed
255
256
257
    sessionID = request.GET['sessionID']
    sliceNumb = int(request.GET['sliceNumb'])
    step = int(request.GET['step'])
258
    result = dm.getSlice(sliceNumb, step, relFITSFilePath)
Caillat Michel's avatar
Caillat Michel committed
259
    response.content_type = "application/json; charset=utf-8"
260
261
    logger.debug("getSlice - wrapper : exiting" )

Caillat Michel's avatar
Caillat Michel committed
262
263
264
265
266
267
268
269
270
271
    return json.dumps(result)

"""
    Given one pair, x and y, of integer coordinates in the RAxDEC plane and
    a frequency range defined by a pair of integers startZ and endZ
    returns the values contained in the data cube at [startZ:endZ, x, y]
"""
@route( baseUrl+'/getFreq', name='getFreq', method='GET')
@enable_cors
def getFreq():
272
    logger.debug("getFreq - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
273

274
    relFITSFilePath = rebuildFilename(request.GET['fileName'])
Caillat Michel's avatar
Caillat Michel committed
275
276
277
278
279
280
    sessionID = request.GET['sessionID']
    x = getIntValue(request.GET['x'])
    y = getIntValue(request.GET['y'])
    startZ = getIntValue(request.GET['startZ'])
    endZ = getIntValue(request.GET['endZ'])
    response.content_type = "application/json; charset=utf-8"
281
282
    result = json.dumps(dm.getFreq(relFITSFilePath, x, y, startZ, endZ))
    logger.debug("getFreq - wrapper : exiting" )
Caillat Michel's avatar
Caillat Michel committed
283

284
    return result
Caillat Michel's avatar
Caillat Michel committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302

"""
    Given two pairs -- startX,endX and startY,endY -- defining a rectangular area the RAxDEC plane
    and a frequency range defined by a pair of integers startZ and endZ
    returns the result of numpy.nansum(datacube[startZ:endZ, startY:endY, startX:endX], (1,2))
    multiplied by cdelt and divided by convert where

    * cdelt == 4 * math.log(2) * abs(CDELT1) * pi180 * abs(CDELT2) * pi180
    * convert == pi * bmaj * bmin
    * bmaj == BMAJ * pi180
    * bmin == BMIN * pi180
    * pi180 == pi / 180 / 4.86e-6

    That is a weighted sum the defined area of the data cube along the frequency axis.
"""
@route( baseUrl+'/getAverageSpectrum', name='getAverageSpectrum', method='GET')
@enable_cors
def getAverageSpectrum():
303
    logger.debug("getAverageSpectrum - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
304
305
306
307
308
309
310
311
312
313

    relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    sessionID = request.GET['sessionID']

    startY = getIntValue(request.GET['startY'])
    endY = getIntValue(request.GET['endY'])
    startX = getIntValue(request.GET['startX'])
    endX = getIntValue(request.GET['endX'])
    retFITS = getBoolValue(request.GET['retFITS'])
    response.content_type = "application/json; charset=utf-8"
314
315
    result = json.dumps(dm.getAverageSpectrum(relFITSFilePath, startY, endY, startX, endX, retFITS))
    logger.debug("getAverageSpectrum - wrapper : exiting" )
Caillat Michel's avatar
Caillat Michel committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337

    return result

"""
    Given two pairs -- RAPix0,RAPix1 and DECPix0,DECPix1 -- defining a rectangular area the RAxDEC plane
    and a frequency defined by an integer sliceIndex
    returns the result of numpy.nansum(datacube[sliceIndex, startY:endY, startX:endX], (1,2))
    multiplied by 4 * log(2) * cdelt1 * pi / 180 / 4.86e-6 * cdelt2 * pi / 180 / 4.86e-6
"""
@route( baseUrl+'/getSumOverSliceRectArea', name='getSumOverSliceRectArea', method='GET')
@enable_cors
def getSumOverSliceRectArea():
    relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    sessionID = request.GET['sessionID']

    DECPix0 = getIntValue(request.GET['DECPix0'])
    DECPix1 = getIntValue(request.GET['DECPix1'])
    RAPix0 = getIntValue(request.GET['RAPix0'])
    RAPix1 = getIntValue(request.GET['RAPix1'])
    sliceIndex = getIntValue(request.GET['sliceIndex'])

    response.content_type = "application/json; charset=utf-8"
338
    result = json.dumps(dm.getSumOverSliceRectArea(relFITSFilePath,  sliceIndex, RAPix0, RAPix1, DECPix0, DECPix1))
Caillat Michel's avatar
Caillat Michel committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    return result

"""
    Given two pairs -- startX,endX and startY,endY -- defining a rectangular area the RAxDEC plane
    and a frequency range defined by a pair of integers startZ and endZ
    returns the result of numpy.nansum(datacube[startZ:endZ, startY:endY, startX:endX], 0)
    multiplied by 4 * log(2) * cdelt1 * pi / 180 / 4.86e-6 * cdelt2 * pi / 180 / 4.86e-6
"""
@route( baseUrl+'/getAverage', name='getAverage', method='GET')
@enable_cors
def getAverage():

    fileName = rebuildFilename(request.GET['fileName'])
    sessionID = request.GET['sessionID']
    step = getIntValue(request.GET['step'])
    startY = getIntValue(request.GET['startY'])
    endY = getIntValue(request.GET['endY'])
    startX = getIntValue(request.GET['startX'])
    endX = getIntValue(request.GET['endX'])
    startZ = getIntValue(request.GET['startZ'])
    endZ = getIntValue(request.GET['endZ'])
360
    result = dm.getAverage(fileName,  step, startZ, endZ, startY, endY, startX, endX)
Caillat Michel's avatar
Caillat Michel committed
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
    response.content_type = "application/json; charset=utf-8"

    return json.dumps(result)

"""
Create a FITS file whose type is TABLE and content is the spectrum at position (iRA, iDEC)
along with the frequencies/velocities.

Returns the content of the file.
"""
@route( baseUrl+'/createFits', name='createFits', method='POST')
@enable_cors
def createFits():
    header = request.json['header']
    relFITSFilePath = request.json['relFITSFilePath']
    iRA = request.json['iRA']
    iDEC = request.json['iDEC']
    response.content_type = "application/json; charset=utf-8"

    return json.dumps(dm.createFits(relFITSFilePath, iRA, iDEC))

"""
    Given fileName
    returns the FITS header
"""
@route( baseUrl+'/getHeader', name='getHeader', method='GET')
@enable_cors
def getHeader():
389
390
391
392
393
    global logger
    global dm
    logger.debug("getHeader : entering")
    relFITSFilePath = rebuildFilename(request.GET['fileName'])
    logger.debug(f"relFITSFilePath = {relFITSFilePath}")
Caillat Michel's avatar
Caillat Michel committed
394
    response.content_type = "application/json; charset=utf-8"
395
396
397
    result = json.dumps(dm.getHeader(relFITSFilePath))
    logger.debug("getHeader : exiting")
    return result
Caillat Michel's avatar
Caillat Michel committed
398
399
400
401
402
403
404
405
406
407
408
409

"""
    Given fileName
    returns the area in the RA x DEC plane of the data contained in the data cube
    as a pair of pairs ((ramin, ramax), ( decmin, decmax))
"""
@route( baseUrl+'/RADECRangeInDegrees', name='RADECRangeInDegrees', method='GET')
@enable_cors
def RADECRangeInDegrees():
    fileName = rebuildFilename(request.GET['fileName'])
    sessionID = request.GET['sessionID']
    response.content_type = "application/json; charset=utf-8"
410
    return json.dumps(dm.RADECRangeInDegrees(fileName))
Caillat Michel's avatar
Caillat Michel committed
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

"""
    Given relFITSFilePath and sliceIndex

    produces a PNG file representing the slice number int(sliceIndex_s) of the datacube along the frequency axis

    returns a dictionary {"data_steps" : data_steps, "path_to_png": relPNGFilePath} where :

    * data_steps is a dictionary color -> physical quantity for a flux density
    * relPNGFilePath a path to the PNG file relative to the root directory of PNG files.
"""
@route( baseUrl+'/getOneSliceAsPNG', name='getOneSliceAsPNG', method='POST')
@enable_cors
def getOneSliceAsPNG():
    request_body = (request.body.read())
    body = None
    response.content_type = "application/json; charset=utf-8"

    try:
        body = byteify(json.loads(request_body))
        relFITSFilePath = rebuildFilename(body['relFITSFilePath'])
        sliceIndex = getIntValue(body['sliceIndex'])
        ittName = body['ittName']
        lutName = body['lutName']
        vmName = body['vmName']
        sessionID = getIntValue(body['sessionID'])
437
        ret = dm.getOneSliceAsPNG(sliceIndex, relFITSFilePath, ittName,lutName, vmName)
Caillat Michel's avatar
Caillat Michel committed
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
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exc()
        message = "%s ! %s" %  (repr(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        ret = {"status": False, "message": message}
    return json.dumps(ret)

"""
    Given relFITSFilePath and a pair sliceIndex0, sliceIndex1
    performs a weighted sum slices with indices in [sliceIndex0, sliceIndex1] along the frequency axis
    and saves it as a PNG file.

    returns a dictionary {"data_steps" : data_steps, "path_to_png": relPNGFilePath} where :

    * data_steps is a dictionary color -> physical quantity for a flux density
    * relPNGFilePath a path to the PNG file relative to the root directory of PNG files.
"""
@route( baseUrl+'/getSummedSliceRangeAsPNG', name='getSummedSliceRangeAsPNG', method='POST')
@enable_cors
def getSummedSliceRangeAsPNG():
    response.content_type = "application/json; charset=utf-8"

    try:
        body = byteify(json.loads(request.body.read()))
        logger.debug("getSummedSliceRangeAsPNG(): body = %r" % json.loads(request.body.read()) )
        relFITSFilePath = rebuildFilename(body['relFITSFilePath'])
        sliceIndex0 = getIntValue(body['sliceIndex0'])
        sliceIndex1 = getIntValue(body['sliceIndex1'])
        ittName = body['ittName']
        lutName = body['lutName']
        vmName = body['vmName']
        sessionID = getIntValue(body['sessionID'])
470
        ret =  dm.getSummedSliceRangeAsPNG(sliceIndex0, sliceIndex1, relFITSFilePath, ittName, lutName, vmName);
Caillat Michel's avatar
Caillat Michel committed
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        ret = {"status": False, "message": message}
    return json.dumps(ret)

"""
    Given the values of a spectrum 'ydata' passed with the corresponding frequency values 'xdata'
    at an (x,y) given position ( integer indexes ) in the RAxDEC plan of a cube, generate a FITS file containing that
    spectrum. Supposedly be used for interoperability based on SAMP. A typical interlocutor is CASSIS

    @header the FITS Header of the file contaning the input data cube.
    @relFITSFilePath the path to the input data cube on disk.
    @iRA a single integer value containing the index along the RA axis
    @iDEC a single integer value containing the index along the DEC axis
"""
@route( baseUrl+'/createFits', name='createFits', method='POST')
@enable_cors
def createFits():
    response.content_type = "application/json; charset=utf-8"

    body = byteify(json.loads(request.body.read()))
    relFITSFilePath = body['relFITSFilePath']
    iRA = getIntValue(body['iRA'])
    iDEC = getIntValue(body['iDEC'])
    response.content_type = "application/json; charset=utf-8"

    ret = dm.createFits(relFITSFilePath, iRA, iDEC)
    return json.dumps(ret)


"""
    Returns all the entries directly located under a given subdirectory.
    The subdirectory must be passed as a full path implicitely
    rooted at FITSFilePrefix.
    i.e. :
    "/" will be interpreted as FITSFilePrefix+"/"
    "/2018" will be interpreted as FITSFilePrefix+"/2018"
    etc...
    The result is a JSON array of dictionaries , on the basis of one dictionary per inode:
    [{'title': filename of the entry, 'key': the FITSFilePrefix rooted path of the entry, 'folder' : true (resp. false) if the inode is (resp. is not) a subdir, 'lazy': true}]
"""
@route( baseUrl+'/getEntries', name='getEntries', method='POST')
@enable_cors
def getEntries() :
Caillat Michel's avatar
Caillat Michel committed
517
    logger.debug("getEntries : entering...")
Caillat Michel's avatar
Caillat Michel committed
518
519
    response.content_type = "application/json; charset=utf-8"
    body = byteify(json.loads(request.body.read()))
Caillat Michel's avatar
Caillat Michel committed
520
    logger.debug(request.body)
Caillat Michel's avatar
Caillat Michel committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    relKey = body['relKey']
    ret = dm.getEntries(relKey)
    logger.debug("getEntries : entering")
    return json.dumps(ret)

"""
   Returns the rendering capabilities of the server in terms of ITTs, LUTs and video modes ( direct [, reverse ).
   These capabilities are defined in lists of names so that a client knows which names to use e.g. 1) to build
   menus in a GUI  , 2) query the server to apply the ITT and/or LUT and/or video mode of its choice for the
   construction of the images.
"""
@route( baseUrl+'/renderingCapabilities', name='renderingCapabilities', method='GET')
@enable_cors
def renderingCapabilities():
535
  logger.debug("renderingCapabilities wrapper : entering")
Caillat Michel's avatar
Caillat Michel committed
536
  response.content_type = "application/json; charset=utf-8"
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
  result = dm.renderingCapabilities()
  logger.debug("renderingCapabilities wrapper : exiting")
  return json.dumps(result)

"""
  Returns a collection of informations about the DatBlocks present
  in memory at the time of the call.
"""
@route( baseUrl+'/getDataBlockInfos', name='getDataBlockInfos', method='POST')
@enable_cors
def getDataBlockInfos():
    logger.debug("getDataBlockInfos wrapper : entering")
    result = dm.getDataBlockInfos()
    logger.debug("getDataBlockInfos wrapper : exiting")
    return json.dumps(result)

"""
  Erase the DataBlocks idle for a duration greater than DataBlock.getMaxIdle
  (env var YAFITSS_MAXIDLE)
"""
@route( baseUrl+'/purgeDataBlocks', name='purgeDataBlocks', method='POST')
@enable_cors
def purgeDataBlocks():
    logger.debug("purgeDataBlocks wrapper : entering")
    result = dm.purgeDataBlocks()
    logger.debug("purgeDataBlocks wrapper : exiting")
    return json.dumps(result)
Caillat Michel's avatar
Caillat Michel committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

#
#    End of the class
#
#

"""
    start local bottle server
    @port port number
    @debug True if debug enabled
"""
def main(argv):

    global logger
    global dm

    try :
        print (argv)
        opts, args = getopt.getopt(argv[1:], "p:", ["port="])
        print (opts)
    except getopt.GetoptError:
        print ("Bad command")
        sys.exit(2)

588
    port = 4251
Caillat Michel's avatar
Caillat Michel committed
589
590
591
592
    for opt, arg in opts:
        if opt in ('-p', '--port'):
            port = int(arg)

593
    logger = logging.getLogger('serverWsgi.michel.new')
Caillat Michel's avatar
Caillat Michel committed
594
595
596
597
    logger.setLevel(logging.DEBUG)

    # create console handler and set level to debug
    #ch = logging.StreamHandler()
Caillat Michel's avatar
Caillat Michel committed
598
599

    #create file handler and set level to debug
Caillat Michel's avatar
Caillat Michel committed
600
601
602
603
604
    theRootDir = "/home/partemix"
    theLogDir = theRootDir + '/log/'
    theLogFile = theLogDir + os.path.splitext(os.path.basename(argv[0]))[0] + '-'+str(port)+'.log'
    print (theLogFile)
    ch = logging.FileHandler(theLogFile)
Caillat Michel's avatar
Caillat Michel committed
605

Caillat Michel's avatar
Caillat Michel committed
606
607
608
609
    ch.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Caillat Michel's avatar
Caillat Michel committed
610

Caillat Michel's avatar
Caillat Michel committed
611
612
    # add formatter to ch
    ch.setFormatter(formatter)
Caillat Michel's avatar
Caillat Michel committed
613

Caillat Michel's avatar
Caillat Michel committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    # add ch to logger
    logger.addHandler(ch)

    hostname = socket.gethostname()
    logger.debug("%s just starting server on %s:%d" % (argv[0], hostname, port))
    logger.debug("Using astropy version %s" % (astropy.version.version))

    # Obtain a data manager implementation
    dm = dataManager.DataManagerImpl(logger)

    app = default_app()
    run(host=hostname, port=port, debug=True, quiet=False)
    return

if __name__ == '__main__':
    main(sys.argv)