e2ad38171fc371da8639576b797b6f35ab05f590
[living-lab-site.git] / cis / cis_lb / cis_lb.py
1 #!/usr/bin/env python
2
3 import sys
4 import urllib
5 import web
6 import time
7 import threading
8 from Queue import Queue
9
10 # Located in the parent directory; execute from that location or put it in PYTHONPATH
11 import logger
12 import config
13
14
15 class LBWorker(threading.Thread):
16     """
17     Load Balancing Worker: chooses a CIS where the request should be forwarded
18     or broadcasts the requests to all CIS machines if required.
19     """
20     
21     def __init__(self, id):
22         """
23         Initialize Load Balancing Worker.
24         """
25
26         threading.Thread.__init__(self, name = 'LBWorker%02d' % id)
27     
28     def run(self):
29         
30         while True:
31             job = Server.queue.get()
32             
33             print '%s is working at %s...' % (self.name, repr(job))
34             time.sleep(10)
35             
36             Server.queue.task_done()
37
38
39 class Server:
40     
41     def POST(self, request):
42         
43         Server.queue.put( ('POST', request, web.data()) )
44         
45         #return web.data()
46
47 if __name__ == '__main__':
48     
49     Server.queue = Queue()
50     
51     # Create job threads.
52     lb_workers = []
53     for i in range(0, config.JOB_THREADS_COUNT):
54         lb_worker = LBWorker(i)
55         lb_worker.daemon = True
56         lb_worker.start()
57         lb_workers.append(lb_worker)
58     
59     # Web service.
60     urls = ('/(.*)', 'Server')
61     app = web.application(urls, globals())
62     app.run()