/alps/pcitool

To get this branch, use:
bzr branch http://suren.me/webbzr/alps/pcitool

« back to all changes in this revision

Viewing changes to pywrap/api_server.py

  • Committer: Vasilii Chernov
  • Date: 2016-03-01 15:42:48 UTC
  • mto: This revision was merged to the branch mainline in revision 367.
  • Revision ID: vchernov@inr.ru-20160301154248-dpu4wdachiezj2fb
1. api-serer:
   - change multiprosessing work mechanism
   - add new pywrap functions handling
2. html-server: 
   - now works through api-server

Show diffs side-by-side

added added

removed removed

Lines of Context:
7
7
import json
8
8
from optparse import OptionParser
9
9
 
10
 
from multiprocessing import Process, current_process
 
10
from multiprocessing import Process
11
11
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
 
12
from SocketServer import ThreadingMixIn
 
13
 
 
14
class MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):
 
15
    pass
12
16
 
13
17
class PcilibServerHandler(BaseHTTPRequestHandler):
14
18
   
22
26
      s.end_headers()
23
27
      
24
28
   def do_GET(s):
 
29
      #run request in separate process
 
30
      p = Process(target=s.do_GET_worker, args=())
 
31
      p.start()
 
32
      p.join()
 
33
      
 
34
   def do_GET_worker(s):
25
35
      length = int(s.headers['Content-Length'])
26
36
      
27
37
      #deserialize input data
289
299
            lock_id = str(data.get('lock_id'))
290
300
            
291
301
            try:
292
 
               print 'unlocking ' + lock_id
293
302
               s.pcilib.unlock(lock_id)
294
303
            except Exception as e:
295
304
               s.error(str(e), data) 
300
309
            
301
310
            
302
311
            
 
312
         elif(command == 'get_scripts_list'):
 
313
            scripts = list()
 
314
            try:
 
315
               scripts = s.pcilib.get_scripts_list()
 
316
            except Exception as e:
 
317
               s.error(str(e), data) 
 
318
               return
 
319
 
 
320
            #Success! Create and send reply
 
321
            s.wrapMessageAndSend({'status': 'ok', 'scripts': scripts}, data)
 
322
         
 
323
         
 
324
         
 
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)
 
330
               return
 
331
            #parse command arguments and convert them to string
 
332
            script_name = str(data.get('script_name'))
 
333
            value = data.get('value', None)
 
334
            
 
335
            out = None
 
336
            try:
 
337
               out = s.pcilib.run_script(script_name, value)
 
338
            except Exception as e:
 
339
               s.error(str(e), data) 
 
340
               return
 
341
 
 
342
            #Success! Create and send reply
 
343
            if(type(out) == bytearray):
 
344
               s.send_response(200)
 
345
               s.send_header('content-disposition', 'inline; filename=value')
 
346
               s.send_header('content-type', 'application/octet-stream')
 
347
               s.end_headers()
 
348
               s.wfile.write(out)
 
349
            else:
 
350
               s.wrapMessageAndSend({'status': 'ok', 'value': out}, data)
 
351
            
 
352
            
 
353
            
303
354
         #elif(command == 'lock_global'):
304
355
         #   #check if global_lock already setted by server
305
356
         #   try:
324
375
         #   s.wrapMessageAndSend({'status': 'ok'}, data)
325
376
         
326
377
         
327
 
                
328
378
         else:
329
379
                    s.error('command "' + command + '" undefined', data)
330
380
                    return
331
381
      else:
332
382
                  s.error('message doesnt contains "command" field, which is required', data)
333
383
                  return
334
 
                  
335
 
       
336
 
      #print str(s.headers['content-type'])
337
 
      #print post_data['some']
 
384
        
 
385
        
338
386
      
339
387
   #open device context 
340
388
   #def openPcilibInstance(s, device, model):
418
466
      '      lock_id: - lock id\n'
419
467
      '\n'
420
468
      
 
469
      '  command: get_scripts_list - Get aviable scripts with description\n'
 
470
      '\n'
 
471
      
 
472
      '  command: run_script - Run specified script\n'
 
473
      '    required fields\n'
 
474
      '      script_name: - script name (with extension)\n'
 
475
      '      value: - input value in json format\n'
 
476
      '\n'
 
477
      
421
478
      '\n')
422
 
      out = {'status': 'ok', 'usage' : usage}
423
 
      s.wrapMessageAndSend(out, received_message)
 
479
      
 
480
      #send help as plain text
 
481
      s.send_response(200)
 
482
      s.send_header('content-type', 'text/plain')
 
483
      s.end_headers()
 
484
      s.wfile.write(usage)
424
485
 
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))
441
502
 
442
 
def serve_forever(server):
443
 
   try:
444
 
      server.serve_forever()
445
 
   except KeyboardInterrupt:
446
 
      pass
447
 
        
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()
452
 
 
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)
 
509
      def handler(*args):
 
510
         PcilibServerHandler(self.lib, *args)
 
511
      MultiThreadedHTTPServer.__init__(self, adress, handler)
455
512
 
456
513
if __name__ == '__main__':
457
514
   
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)")
 
526
 
472
527
   opts = parser.parse_args()[0]
473
528
   
474
 
   HOST_NAME = ''
 
529
   HOST_NAME = '0.0.0.0'
475
530
   PORT_NUMBER = opts.port
476
531
   MODEL = opts.model
477
532
   DEVICE = opts.device
478
533
   
479
 
   
480
 
   
481
 
   #Set enviroment variables, if it not setted already
482
 
   if not 'APP_PATH' in os.environ:
483
 
      APP_PATH = ''
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
487
 
 
488
 
   if not 'PCILIB_MODEL_DIR' in os.environ:   
489
 
      os.environ['PCILIB_MODEL_DIR'] = os.environ["APP_PATH"] + "/xml"
490
 
      
491
 
   if not 'LD_LIBRARY_PATH' in os.environ: 
492
 
      os.environ['LD_LIBRARY_PATH'] = os.environ["APP_PATH"] + "/pcilib"
493
 
   
494
 
   
495
 
   
496
 
   #redirect logs to exeption
497
 
   pcipywrap.__redirect_logs_to_exeption()
498
 
   
499
 
   #pass Pcipywrap to to server handler
500
 
   global pcilib
501
 
   lib = pcipywrap.Pcipywrap(DEVICE, MODEL)
502
 
   def handler(*args):
503
 
      PcilibServerHandler(lib, *args)
504
 
   
505
534
   #start server
506
 
   httpd = HTTPServer((HOST_NAME, PORT_NUMBER), handler)
507
 
   runpool(httpd, opts.processes)
 
535
   httpd = ApiServer(DEVICE, MODEL, (HOST_NAME, PORT_NUMBER))
508
536
   
509
537
   print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
510
 
   #try:
511
 
   #   httpd.serve_forever()
512
 
   #except KeyboardInterrupt:
513
 
   #   pass
 
538
   
 
539
   try:
 
540
      httpd.serve_forever()
 
541
   except KeyboardInterrupt:
 
542
      pass
514
543
      
515
544
   httpd.server_close()
 
545
   
516
546
   print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)