8
8
from optparse import OptionParser
10
from multiprocessing import Process, current_process
10
from multiprocessing import Process
11
11
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
12
from SocketServer import ThreadingMixIn
14
class MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):
13
17
class PcilibServerHandler(BaseHTTPRequestHandler):
312
elif(command == 'get_scripts_list'):
315
scripts = s.pcilib.get_scripts_list()
316
except Exception as e:
317
s.error(str(e), data)
320
#Success! Create and send reply
321
s.wrapMessageAndSend({'status': 'ok', 'scripts': scripts}, data)
325
elif(command == 'run_script'):
326
#check required arguments
327
if not 'script_name' in data:
328
s.error('message doesnt contains "script_name" field, '
329
'which is required for "run_script" command', data)
331
#parse command arguments and convert them to string
332
script_name = str(data.get('script_name'))
333
value = data.get('value', None)
337
out = s.pcilib.run_script(script_name, value)
338
except Exception as e:
339
s.error(str(e), data)
342
#Success! Create and send reply
343
if(type(out) == bytearray):
345
s.send_header('content-disposition', 'inline; filename=value')
346
s.send_header('content-type', 'application/octet-stream')
350
s.wrapMessageAndSend({'status': 'ok', 'value': out}, data)
303
354
#elif(command == 'lock_global'):
304
355
# #check if global_lock already setted by server
324
375
# s.wrapMessageAndSend({'status': 'ok'}, data)
329
379
s.error('command "' + command + '" undefined', data)
332
382
s.error('message doesnt contains "command" field, which is required', data)
336
#print str(s.headers['content-type'])
337
#print post_data['some']
339
387
#open device context
340
388
#def openPcilibInstance(s, device, model):
418
466
' lock_id: - lock id\n'
469
' command: get_scripts_list - Get aviable scripts with description\n'
472
' command: run_script - Run specified script\n'
474
' script_name: - script name (with extension)\n'
475
' value: - input value in json format\n'
422
out = {'status': 'ok', 'usage' : usage}
423
s.wrapMessageAndSend(out, received_message)
480
#send help as plain text
482
s.send_header('content-type', 'text/plain')
425
486
#Send error message with text description
426
487
def error(s, info, received_message = None):
439
500
message['received_message'] = received_message
440
501
s.wfile.write(json.dumps(message))
442
def serve_forever(server):
444
server.serve_forever()
445
except KeyboardInterrupt:
448
def runpool(server, number_of_processes):
449
# create child processes to act as workers
450
for i in range(number_of_processes-1):
451
Process(target=serve_forever, args=(server,)).start()
453
# main process also acts as a worker
454
serve_forever(server)
503
class ApiServer(MultiThreadedHTTPServer):
504
def __init__(self, device='/dev/fpga0', model=None, adress=('0.0.0.0', 9000)):
505
#redirect logs to exeption
506
pcipywrap.redirect_logs_to_exeption()
507
#pass Pcipywrap to to server handler
508
self.lib = pcipywrap.Pcipywrap(device, model)
510
PcilibServerHandler(self.lib, *args)
511
MultiThreadedHTTPServer.__init__(self, adress, handler)
456
513
if __name__ == '__main__':
466
523
parser.add_option("-m", "--model", action="store",
467
524
type="string", dest="model", default=None,
468
525
help="Memory model (autodetected)")
469
parser.add_option("-n", "--number_processes", action="store",
470
type="int", dest="processes", default=4,
471
help="Number of processes, used by server (4)")
472
527
opts = parser.parse_args()[0]
529
HOST_NAME = '0.0.0.0'
475
530
PORT_NUMBER = opts.port
476
531
MODEL = opts.model
477
532
DEVICE = opts.device
481
#Set enviroment variables, if it not setted already
482
if not 'APP_PATH' in os.environ:
484
file_dir = os.path.dirname(os.path.abspath(__file__))
485
APP_PATH = str(os.path.abspath(file_dir + '/../..'))
486
os.environ["APP_PATH"] = APP_PATH
488
if not 'PCILIB_MODEL_DIR' in os.environ:
489
os.environ['PCILIB_MODEL_DIR'] = os.environ["APP_PATH"] + "/xml"
491
if not 'LD_LIBRARY_PATH' in os.environ:
492
os.environ['LD_LIBRARY_PATH'] = os.environ["APP_PATH"] + "/pcilib"
496
#redirect logs to exeption
497
pcipywrap.__redirect_logs_to_exeption()
499
#pass Pcipywrap to to server handler
501
lib = pcipywrap.Pcipywrap(DEVICE, MODEL)
503
PcilibServerHandler(lib, *args)
506
httpd = HTTPServer((HOST_NAME, PORT_NUMBER), handler)
507
runpool(httpd, opts.processes)
535
httpd = ApiServer(DEVICE, MODEL, (HOST_NAME, PORT_NUMBER))
509
537
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
511
# httpd.serve_forever()
512
#except KeyboardInterrupt:
540
httpd.serve_forever()
541
except KeyboardInterrupt:
515
544
httpd.server_close()
516
546
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)