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."\
56 # Remove slices from conf that no longer have the attribute
57 for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
58 # XXX Hack for root slice
59 if deadslice != "root":
60 logger.log("codemux: Removing %s" % deadslice)
63 if _writeconf: writeConf(sortDomains(codemuxslices))
65 def writeConf(slivers, conf = CODEMUXCONF):
66 '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
68 # This needs to be the first entry...
70 f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
71 except AttributeError:
72 logger.log("codemux: Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
73 f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
74 # Sort items for like domains
75 for mapping in slivers:
76 for (host, params) in mapping.iteritems():
77 if params['slice'] == "root": continue
78 f.write("%s %s %s\n" % (host, params['slice'], params['port']))
82 except: logger.log_exc()
84 def sortDomains(slivers):
85 '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
86 dnames = {} # {host: slice}
87 for (slice, params) in slivers.iteritems():
88 for mapping in params:
89 dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
92 hosts.sort(key=str.__len__)
95 # make list of slivers
97 for host in hosts: sortedslices.append({host: dnames[host]})
101 def parseConf(conf = CODEMUXCONF):
102 '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
103 slicesinconf = {} # default
106 for line in f.readlines():
107 if line.startswith("#") \
108 or (len(line.split()) > 4) \
109 or (len(line.split()) < 3):
111 (host, slice, port) = line.split()[:3]
112 logger.log("codemux: found %s in conf" % slice, 2)
113 slicesinconf.setdefault(slice, [])
114 slicesinconf[slice].append({"host": host, "port": port})
116 except IOError: logger.log_exc()
119 def restartService():
120 logger.log("codemux: Restarting codemux service")
121 os.system("/etc/init.d/codemux stop")
122 f = os.popen("/sbin/pidof codemux")
126 pids = tmp[0].rstrip("\n").split()
128 logger.log("codemux: Killing stalled pid %s" % pid, 2)
130 os.system("/etc/init.d/codemux start")