Simple module for toggling network namespaces based on slice attributes
[nodemanager.git] / codemux.py
1 # $Id$
2 # $URL$
3
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."""
5
6 import logger
7 import os
8 import vserver
9 from sets import Set
10 from config import Config
11
12 CODEMUXCONF="/etc/codemux/codemux.conf"
13
14 def start(options, config):
15     pass
16
17
18 def GetSlivers(data):
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
24     codemuxslices = {}
25     
26     # XXX Hack for planetflow
27     if slicesinconf.has_key("root"): _writeconf = False
28     else: _writeconf = True
29
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]}
37                 try:
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']))
45                             #  Toggle write.
46                             _writeconf = True
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)
51                 except:
52                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
53                                 % sliver['name'])
54                     pass
55
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)
61             _writeconf = True 
62
63     if _writeconf:  writeConf(sortDomains(codemuxslices))
64
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.'''
67     f = open(conf, "w")
68     # This needs to be the first entry...
69     try: 
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']))
79     f.truncate()
80     f.close()
81     try:  restartService()
82     except:  logger.log_exc()
83
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']}
90     hosts = dnames.keys()
91     # sort by length
92     hosts.sort(key=str.__len__)
93     # longer first
94     hosts.reverse()
95     # make list of slivers
96     sortedslices = []
97     for host in hosts: sortedslices.append({host: dnames[host]})
98     
99     return sortedslices
100         
101 def parseConf(conf = CODEMUXCONF):
102     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
103     slicesinconf = {} # default
104     try: 
105         f = open(conf)
106         for line in f.readlines():
107             if line.startswith("#") \
108             or (len(line.split()) > 4) \
109             or (len(line.split()) < 3):
110                 continue
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})
115         f.close()
116     except IOError: logger.log_exc()
117     return slicesinconf
118
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")
123     tmp = f.readlines()
124     f.close()
125     if len(tmp) > 0: 
126         pids = tmp[0].rstrip("\n").split()
127         for pid in pids:
128             logger.log("codemux:  Killing stalled pid %s" % pid, 2)
129             os.kill(pid, 9)
130     os.system("/etc/init.d/codemux start")