e81baee6bb08d4b8c20f9ac670b564d54b7e3534
[living-lab-site.git] / cis / cis_lb / load_balancer / base.py
1 import threading
2 import urllib
3 import json
4
5 import config
6 import logger
7
8
9 class LoadBalancer(threading.Thread):
10     
11     def __init__(self, id, queue):
12         """
13         Initialize Load Balancer,
14         """
15
16         threading.Thread.__init__(self, \
17                 name = '%s%02d' % (self.__class__.__name__, id))
18         
19         self.queue = queue
20     
21     def run(self):
22         
23         while True:
24             (request, data) = self.queue.get()
25             urls = config.CIS_URLS[:]
26             code = json.loads(data)['code']
27             
28             while len(urls) != 0:
29                 cis = self.choose(urls)
30                 
31                 # Request is forwarded to the chosen CIS.
32                 try:
33                     urllib.urlopen(cis + request, data)
34                 except IOError:
35                     logger.log_msg('#%s: Failed to forward request to %s' \
36                             % (code, cis), \
37                             logger.LOG_LEVEL_ERROR)
38                     continue
39                 
40                 logger.log_msg('#%s: Request forwarded to %s' \
41                             % (code, cis), \
42                         logger.LOG_LEVEL_INFO)
43                 break
44             
45             if len(urls) == 0:
46                 logger.log_msg('#%s: Failed to forward request to any CIS' \
47                             % code, \
48                             logger.LOG_LEVEL_FATAL)
49                 self.notify_error(code)
50             
51             self.queue.task_done()
52     
53     def notify_error(self, code):
54         logger.log_msg('#%s: notifying web server about the error...'\
55                 % code)
56         
57         if config.WS_ERROR[len(config.WS_ERROR) - 1] == '/':
58             url = config.WS_ERROR + code
59         else:
60             url = config.WS_ERROR + '/' + code
61         url = url + '/' + 'unreachable'
62         
63         f = urllib.urlopen(url)
64         f.read()
65         
66     def choose(self, urls):
67         """
68         Implement load balancing policy in this method for child classes which
69         choses a CIS from urls parameter. The chosen URL should be deleted from
70         urls list.
71         """        
72         pass