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 if 'slivers' not in data:
39 logger.log("codemux.GetSlivers: could not find the slivers keyin data (PLC connection down?) - IGNORED")
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(",")
49 logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
55 params = {'host': parts[0], 'port': parts[1], 'ip': ip}
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']))
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)
72 logger.log("codemux: sliver %s not running yet. Deferring."\
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)
83 if _writeconf: writeConf(sortDomains(codemuxslices))
84 # ensure the service is running
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.'''
91 # This needs to be the first entry...
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']))
104 try: restartService()
105 except: logger.log_exc()
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()
116 hosts.sort(key=str.__len__)
119 # make list of slivers
121 for host in hosts: sortedslices.append({host: dnames[host]})
126 def parseConf(conf = CODEMUXCONF):
127 '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
128 slicesinconf = {} # default
131 for line in f.readlines():
132 if line.startswith("#") \
133 or (len(line.split()) > 4) \
134 or (len(line.split()) < 3):
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})
141 except IOError: logger.log_exc()
146 if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
152 def restartService():
153 if not os.path.exists("/etc/init.d/codemux"): return
154 logger.log("codemux: Restarting codemux service")
156 logger.log_call("/etc/init.d/codemux","condrestart")
158 logger.log_call("/etc/init.d/codemux","restart")
162 if not os.path.exists("/etc/init.d/codemux"): return
164 logger.log("codemux: Starting codemux service")
165 logger.log_call("/etc/init.d/codemux", "start")
166 logger.log_call("/sbin/chkconfig", "codemux", "on")
170 if not os.path.exists("/etc/init.d/codemux"): return
172 logger.log("codemux: Stopping codemux service")
173 logger.log_call("/etc/init.d/codemux", "stop")
174 logger.log_call("/sbin/chkconfig", "codemux", "off")