Be a bit more robust to poorly defined codemux attribute values
[nodemanager.git] / plugins / codemux.py
1 # $Id$
2 # $URL$
3
4 """Codemux configurator.  Monitors slice attributes and configures CoDemux to mux port 80 based on HOST field in HTTP request.  Forwards to localhost port belonging to configured slice."""
5
6 import logger
7 import os
8 import vserver
9 from sets import Set
10 from config import Config
11
12 CODEMUXCONF="/etc/codemux/codemux.conf"
13
14 def start(options, conf):
15     logger.log("codemux plugin starting up...")
16
17 def GetSlivers(data, config, plc = None):
18     """
19     For each sliver with the codemux attribute, parse out "host,port" 
20     and make entry in conf.  Restart service after.
21     """
22     if 'OVERRIDES' in dir(config):
23         if config.OVERRIDES.get('codemux') == '-1':
24             logger.log("codemux:  Disabled", 2)
25             stopService()
26             return
27
28     logger.log("codemux:  Starting.", 2)
29     # slices already in conf
30     slicesinconf = parseConf()
31     # slices that need to be written to the conf
32     codemuxslices = {}
33     
34     # XXX Hack for planetflow
35     if slicesinconf.has_key("root"): _writeconf = False
36     else: _writeconf = True
37
38     # Parse attributes and update dict of scripts
39     for sliver in data['slivers']:
40         for attribute in sliver['attributes']:
41             if attribute['tagname'] == 'codemux':
42                 # add to conf.  Attribute is [host, port]
43                 parts = attribute['value'].split(",")
44                 if len(parts)<2:
45                     logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
46                     continue
47                 params = {'host': parts[0], 'port': parts[1]}
48                 try:
49                     # Check to see if sliver is running.  If not, continue
50                     if vserver.VServer(sliver['name']).is_running():
51                         # Check if new or needs updating
52                         if (sliver['name'] not in slicesinconf.keys()) \
53                         or (params not in slicesinconf.get(sliver['name'], [])):
54                             logger.log("codemux:  Updaiting slice %s using %s" % \
55                                 (sliver['name'], params['host']))
56                             #  Toggle write.
57                             _writeconf = True
58                         # Add to dict of codemuxslices.  Make list to support more than one
59                         # codemuxed host per slice.
60                         codemuxslices.setdefault(sliver['name'],[])
61                         codemuxslices[sliver['name']].append(params)
62                 except:
63                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
64                                 % sliver['name'])
65                     pass
66
67     # Remove slices from conf that no longer have the attribute
68     for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
69         # XXX Hack for root slice
70         if deadslice != "root": 
71             logger.log("codemux:  Removing %s" % deadslice)
72             _writeconf = True 
73
74     if _writeconf:  writeConf(sortDomains(codemuxslices))    
75     # ensure the service is running
76     startService()
77
78
79 def writeConf(slivers, conf = CODEMUXCONF):
80     '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
81     f = open(conf, "w")
82     # This needs to be the first entry...
83     try: 
84         f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
85     except AttributeError: 
86         logger.log("codemux:  Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
87         f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
88     # Sort items for like domains
89     for mapping in slivers:
90         for (host, params) in mapping.iteritems():
91             if params['slice'] == "root":  continue
92             f.write("%s %s %s\n" % (host, params['slice'], params['port']))
93     f.truncate()
94     f.close()
95     try:  restartService()
96     except:  logger.log_exc()
97
98
99 def sortDomains(slivers):
100     '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
101     dnames = {} # {host: slice}
102     for (slice, params) in slivers.iteritems():
103         for mapping in params:
104             dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
105     hosts = dnames.keys()
106     # sort by length
107     hosts.sort(key=str.__len__)
108     # longer first
109     hosts.reverse()
110     # make list of slivers
111     sortedslices = []
112     for host in hosts: sortedslices.append({host: dnames[host]})
113     
114     return sortedslices
115
116         
117 def parseConf(conf = CODEMUXCONF):
118     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
119     slicesinconf = {} # default
120     try: 
121         f = open(conf)
122         for line in f.readlines():
123             if line.startswith("#") \
124             or (len(line.split()) > 4) \
125             or (len(line.split()) < 3):
126                 continue
127             (host, slice, port) = line.split()[:3]
128             logger.log("codemux:  found %s in conf" % slice, 2)
129             slicesinconf.setdefault(slice, [])
130             slicesinconf[slice].append({"host": host, "port": port})
131         f.close()
132     except IOError: logger.log_exc()
133     return slicesinconf
134
135
136 def isRunning():
137     if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
138         return True
139     else:
140         return False
141
142
143 def restartService():
144     logger.log("codemux:  Restarting codemux service")
145     if isRunning():
146         logger.log_call("/etc/init.d/codemux","condrestart")
147     else:
148         logger.log_call("/etc/init.d/codemux","restart")
149
150
151 def startService():
152     if not isRunning():
153         logger.log("codemux:  Starting codemux service")
154         logger.log_call("/etc/init.d/codemux", "start")
155
156
157 def stopService():
158     if isRunning():
159         logger.log("codemux:  Stopping codemux service")
160         logger.log_call("/etc/init.d/codemux", "stop")