don't invoke /etc/init.d/codemux if it is not installed
[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     if 'slivers' not in data:
40         logger.log_missing_data("codemux.GetSlivers", 'slivers')
41         return
42     for sliver in data['slivers']:
43         for attribute in sliver['attributes']:
44             if attribute['tagname'] == 'codemux':
45                 # add to conf.  Attribute is [host, port]
46                 parts = attribute['value'].split(",")
47                 if len(parts)<2:
48                     logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
49                     continue
50                 params = {'host': parts[0], 'port': parts[1]}
51                 try:
52                     # Check to see if sliver is running.  If not, continue
53                     if vserver.VServer(sliver['name']).is_running():
54                         # Check if new or needs updating
55                         if (sliver['name'] not in slicesinconf.keys()) \
56                         or (params not in slicesinconf.get(sliver['name'], [])):
57                             logger.log("codemux:  Updaiting slice %s using %s" % \
58                                 (sliver['name'], params['host']))
59                             #  Toggle write.
60                             _writeconf = True
61                         # Add to dict of codemuxslices.  Make list to support more than one
62                         # codemuxed host per slice.
63                         codemuxslices.setdefault(sliver['name'],[])
64                         codemuxslices[sliver['name']].append(params)
65                 except:
66                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
67                                 % sliver['name'])
68                     pass
69
70     # Remove slices from conf that no longer have the attribute
71     for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
72         # XXX Hack for root slice
73         if deadslice != "root": 
74             logger.log("codemux:  Removing %s" % deadslice)
75             _writeconf = True 
76
77     if _writeconf:  writeConf(sortDomains(codemuxslices))    
78     # ensure the service is running
79     startService()
80
81
82 def writeConf(slivers, conf = CODEMUXCONF):
83     '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
84     f = open(conf, "w")
85     # This needs to be the first entry...
86     try: 
87         f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
88     except AttributeError: 
89         logger.log("codemux:  Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
90         f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
91     # Sort items for like domains
92     for mapping in slivers:
93         for (host, params) in mapping.iteritems():
94             if params['slice'] == "root":  continue
95             f.write("%s %s %s\n" % (host, params['slice'], params['port']))
96     f.truncate()
97     f.close()
98     try:  restartService()
99     except:  logger.log_exc("codemux.writeConf failed to restart service")
100
101
102 def sortDomains(slivers):
103     '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
104     dnames = {} # {host: slice}
105     for (slice, params) in slivers.iteritems():
106         for mapping in params:
107             dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
108     hosts = dnames.keys()
109     # sort by length
110     hosts.sort(key=str.__len__)
111     # longer first
112     hosts.reverse()
113     # make list of slivers
114     sortedslices = []
115     for host in hosts: sortedslices.append({host: dnames[host]})
116     
117     return sortedslices
118
119         
120 def parseConf(conf = CODEMUXCONF):
121     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
122     slicesinconf = {} # default
123     try: 
124         f = open(conf)
125         for line in f.readlines():
126             if line.startswith("#") \
127             or (len(line.split()) > 4) \
128             or (len(line.split()) < 3):
129                 continue
130             (host, slice, port) = line.split()[:3]
131             logger.log("codemux:  found %s in conf" % slice, 2)
132             slicesinconf.setdefault(slice, [])
133             slicesinconf[slice].append({"host": host, "port": port})
134         f.close()
135     except IOError: logger.log_exc("codemux.parseConf got IOError")
136     return slicesinconf
137
138
139 def isRunning():
140     if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
141         return True
142     else:
143         return False
144
145 def restartService():
146     if not os.path.exists("/etc/init.d/codemux"): return
147     logger.log("codemux:  Restarting codemux service")
148     if isRunning():
149         logger.log_call(["/etc/init.d/codemux","condrestart", ])
150     else:
151         logger.log_call(["/etc/init.d/codemux","restart", ])
152
153 def startService():
154     if not os.path.exists("/etc/init.d/codemux"): return
155     if not isRunning():
156         logger.log("codemux:  Starting codemux service")
157         logger.log_call(["/etc/init.d/codemux", "start", ])
158     logger.log_call(["/sbin/chkconfig", "codemux", "on"])
159
160
161 def stopService():
162     if not os.path.exists("/etc/init.d/codemux"): return
163     if isRunning():
164         logger.log("codemux:  Stopping codemux service")
165         logger.log_call(["/etc/init.d/codemux", "stop", ])
166     logger.log_call(["/sbin/chkconfig", "codemux", "off"])