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(plc, data, config):
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 params = {'host': attribute['value'].split(",")[0],
44 'port': attribute['value'].split(",")[1]}
46 # Check to see if sliver is running. If not, continue
47 if vserver.VServer(sliver['name']).is_running():
48 # Check if new or needs updating
49 if (sliver['name'] not in slicesinconf.keys()) \
50 or (params not in slicesinconf.get(sliver['name'], [])):
51 logger.log("codemux: Updaiting slice %s using %s" % \
52 (sliver['name'], params['host']))
55 # Add to dict of codemuxslices. Make list to support more than one
56 # codemuxed host per slice.
57 codemuxslices.setdefault(sliver['name'],[])
58 codemuxslices[sliver['name']].append(params)
60 logger.log("codemux: sliver %s not running yet. Deferring."\
64 # Remove slices from conf that no longer have the attribute
65 for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
66 # XXX Hack for root slice
67 if deadslice != "root":
68 logger.log("codemux: Removing %s" % deadslice)
71 if _writeconf: writeConf(sortDomains(codemuxslices))
72 # ensure the service is running
76 def writeConf(slivers, conf = CODEMUXCONF):
77 '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
79 # This needs to be the first entry...
81 f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
82 except AttributeError:
83 logger.log("codemux: Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
84 f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
85 # Sort items for like domains
86 for mapping in slivers:
87 for (host, params) in mapping.iteritems():
88 if params['slice'] == "root": continue
89 f.write("%s %s %s\n" % (host, params['slice'], params['port']))
93 except: logger.log_exc()
96 def sortDomains(slivers):
97 '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
98 dnames = {} # {host: slice}
99 for (slice, params) in slivers.iteritems():
100 for mapping in params:
101 dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
102 hosts = dnames.keys()
104 hosts.sort(key=str.__len__)
107 # make list of slivers
109 for host in hosts: sortedslices.append({host: dnames[host]})
114 def parseConf(conf = CODEMUXCONF):
115 '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
116 slicesinconf = {} # default
119 for line in f.readlines():
120 if line.startswith("#") \
121 or (len(line.split()) > 4) \
122 or (len(line.split()) < 3):
124 (host, slice, port) = line.split()[:3]
125 logger.log("codemux: found %s in conf" % slice, 2)
126 slicesinconf.setdefault(slice, [])
127 slicesinconf[slice].append({"host": host, "port": port})
129 except IOError: logger.log_exc()
134 if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
140 def restartService():
141 logger.log("codemux: Restarting codemux service")
143 logger.log_call("/etc/init.d/codemux","condrestart")
145 logger.log_call("/etc/init.d/codemux","restart")
150 logger.log("codemux: Starting codemux service")
151 logger.log_call("/etc/init.d/codemux", "start")
156 logger.log("codemux: Stopping codemux service")
157 logger.log_call("/etc/init.d/codemux", "stop")