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