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."""
10 from config import Config
12 CODEMUXCONF="/etc/codemux/codemux.conf"
14 def start(options, conf):
15 logger.log("codemux: plugin starting up...")
17 def GetSlivers(data, config, plc = None):
19 For each sliver with the codemux attribute, parse out "host,port"
20 and make entry in conf. Restart service after.
22 if 'OVERRIDES' in dir(config):
23 if config.OVERRIDES.get('codemux') == '-1':
24 logger.log("codemux: Disabled", 2)
28 logger.log("codemux: Starting.", 2)
29 # slices already in conf
30 slicesinconf = parseConf()
31 # slices that need to be written to the conf
34 # XXX Hack for planetflow
35 if slicesinconf.has_key("root"): _writeconf = False
36 else: _writeconf = True
38 # Parse attributes and update dict of scripts
39 if 'slivers' not in data:
40 logger.log_missing_data("codemux.GetSlivers", 'slivers')
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(",")
48 logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
50 params = {'host': parts[0], 'port': parts[1]}
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']))
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)
66 logger.log("codemux: sliver %s not running yet. Deferring."\
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)
77 if _writeconf: writeConf(sortDomains(codemuxslices))
78 # ensure the service is running
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.'''
85 # This needs to be the first entry...
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']))
99 except: logger.log_exc("codemux.writeConf failed to restart service")
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()
110 hosts.sort(key=str.__len__)
113 # make list of slivers
115 for host in hosts: sortedslices.append({host: dnames[host]})
120 def parseConf(conf = CODEMUXCONF):
121 '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
122 slicesinconf = {} # default
125 for line in f.readlines():
126 if line.startswith("#") \
127 or (len(line.split()) > 4) \
128 or (len(line.split()) < 3):
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})
135 except IOError: logger.log_exc("codemux.parseConf got IOError")
140 if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
146 def restartService():
147 logger.log("codemux: Restarting codemux service")
149 logger.log_call(["/etc/init.d/codemux","condrestart", ])
151 logger.log_call(["/etc/init.d/codemux","restart", ])
156 logger.log("codemux: Starting codemux service")
157 logger.log_call(["/etc/init.d/codemux", "start", ])
158 logger.log_call(["/sbin/chkconfig", "codemux", "on"])
163 logger.log("codemux: Stopping codemux service")
164 logger.log_call(["/etc/init.d/codemux", "stop", ])
165 logger.log_call(["/sbin/chkconfig", "codemux", "off"])