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, config):
19 """For each sliver with the codemux attribute, parse out "host,port" and make entry in conf. Restart service after."""
20 logger.log("codemux: Starting.", 2)
21 # slices already in conf
22 slicesinconf = parseConf()
23 # slices that need to be written to the conf
26 # XXX Hack for planetflow
27 if slicesinconf.has_key("root"): _writeconf = False
28 else: _writeconf = True
30 # Parse attributes and update dict of scripts
31 for sliver in data['slivers']:
32 for attribute in sliver['attributes']:
33 if attribute['name'] == 'codemux':
34 # add to conf. Attribute is [host, port]
35 params = {'host': attribute['value'].split(",")[0],
36 'port': attribute['value'].split(",")[1]}
38 # Check to see if sliver is running. If not, continue
39 if vserver.VServer(sliver['name']).is_running():
40 # Check if new or needs updating
41 if (sliver['name'] not in slicesinconf.keys()) \
42 or (params not in slicesinconf.get(sliver['name'], [])):
43 logger.log("codemux: Updaiting slice %s using %s" % \
44 (sliver['name'], params['host']))
47 # Add to dict of codemuxslices. Make list to support more than one
48 # codemuxed host per slice.
49 codemuxslices.setdefault(sliver['name'],[])
50 codemuxslices[sliver['name']].append(params)
52 logger.log("codemux: sliver %s not running yet. Deferring."\
55 logger.log_exc(name = "codemux")
58 # Remove slices from conf that no longer have the attribute
59 for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
60 # XXX Hack for root slice
61 if deadslice != "root":
62 logger.log("codemux: Removing %s" % deadslice)
65 if _writeconf: writeConf(sortDomains(codemuxslices))
67 def writeConf(slivers, conf = CODEMUXCONF):
68 '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
70 # This needs to be the first entry...
71 f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
72 # Sort items for like domains
73 for mapping in slivers:
74 for (host, params) in mapping.iteritems():
75 if params['slice'] == "root": continue
76 f.write("%s %s %s\n" % (host, params['slice'], params['port']))
80 except: logger.log_exc()
82 def sortDomains(slivers):
83 '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
84 dnames = {} # {host: slice}
85 for (slice, params) in slivers.iteritems():
86 for mapping in params:
87 dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
90 hosts.sort(key=str.__len__)
93 # make list of slivers
95 for host in hosts: sortedslices.append({host: dnames[host]})
99 def parseConf(conf = CODEMUXCONF):
100 '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
101 slicesinconf = {} # default
104 for line in f.readlines():
105 if line.startswith("#") or (len(line.split()) > 4):
107 (host, slice, port) = line.split()[:3]
108 logger.log("codemux: found %s in conf" % slice, 2)
109 slicesinconf.setdefault(slice, [])
110 slicesinconf[slice].append({"host": host, "port": port})
112 except IOError: logger.log_exc()
115 def restartService():
116 logger.log("codemux: Restarting codemux service")
117 os.system("/etc/init.d/codemux stop")
118 f = os.popen("/sbin/pidof codemux")
122 pids = tmp[0].rstrip("\n").split()
124 logger.log("codemux: Killing stalled pid %s" % pid, 2)
126 os.system("/etc/init.d/codemux start")