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 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(",")
45 logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
47 params = {'host': parts[0], 'port': parts[1]}
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']))
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)
63 logger.log("codemux: sliver %s not running yet. Deferring."\
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)
74 if _writeconf: writeConf(sortDomains(codemuxslices))
75 # ensure the service is running
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.'''
82 # This needs to be the first entry...
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']))
96 except: logger.log_exc()
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()
107 hosts.sort(key=str.__len__)
110 # make list of slivers
112 for host in hosts: sortedslices.append({host: dnames[host]})
117 def parseConf(conf = CODEMUXCONF):
118 '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
119 slicesinconf = {} # default
122 for line in f.readlines():
123 if line.startswith("#") \
124 or (len(line.split()) > 4) \
125 or (len(line.split()) < 3):
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})
132 except IOError: logger.log_exc()
137 if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
143 def restartService():
144 logger.log("codemux: Restarting codemux service")
146 logger.log_call("/etc/init.d/codemux","condrestart")
148 logger.log_call("/etc/init.d/codemux","restart")
153 logger.log("codemux: Starting codemux service")
154 logger.log_call("/etc/init.d/codemux", "start")
159 logger.log("codemux: Stopping codemux service")
160 logger.log_call("/etc/init.d/codemux", "stop")