- turn net.py into a NM plugin and move to plugin directory
[nodemanager.git] / plugins / 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, conf):
15     pass
16
17 def GetSlivers(plc, data, config):
18     """
19     For each sliver with the codemux attribute, parse out "host,port" 
20     and make entry in conf.  Restart service after.
21     """
22     if 'OVERRIDES' in dir(config):
23         if config.OVERRIDES.get('codemux') == '-1':
24             logger.log("codemux:  Disabled", 2)
25             stopService()
26             return
27
28     logger.log("codemux:  Starting.", 2)
29     # slices already in conf
30     slicesinconf = parseConf()
31     # slices that need to be written to the conf
32     codemuxslices = {}
33     
34     # XXX Hack for planetflow
35     if slicesinconf.has_key("root"): _writeconf = False
36     else: _writeconf = True
37
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]}
45                 try:
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']))
53                             #  Toggle write.
54                             _writeconf = True
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)
59                 except:
60                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
61                                 % sliver['name'])
62                     pass
63
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)
69             _writeconf = True 
70
71     if _writeconf:  writeConf(sortDomains(codemuxslices))    
72     # ensure the service is running
73     startService()
74
75
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.'''
78     f = open(conf, "w")
79     # This needs to be the first entry...
80     try: 
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']))
90     f.truncate()
91     f.close()
92     try:  restartService()
93     except:  logger.log_exc()
94
95
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()
103     # sort by length
104     hosts.sort(key=str.__len__)
105     # longer first
106     hosts.reverse()
107     # make list of slivers
108     sortedslices = []
109     for host in hosts: sortedslices.append({host: dnames[host]})
110     
111     return sortedslices
112
113         
114 def parseConf(conf = CODEMUXCONF):
115     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
116     slicesinconf = {} # default
117     try: 
118         f = open(conf)
119         for line in f.readlines():
120             if line.startswith("#") \
121             or (len(line.split()) > 4) \
122             or (len(line.split()) < 3):
123                 continue
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})
128         f.close()
129     except IOError: logger.log_exc()
130     return slicesinconf
131
132
133 def isRunning():
134     if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
135         return True
136     else:
137         return False
138
139
140 def restartService():
141     logger.log("codemux:  Restarting codemux service")
142     if isRunning():
143         logger.log_call("/etc/init.d/codemux","condrestart")
144     else:
145         logger.log_call("/etc/init.d/codemux","restart")
146
147
148 def startService():
149     if not isRunning():
150         logger.log("codemux:  Starting codemux service")
151         logger.log_call("/etc/init.d/codemux", "start")
152
153
154 def stopService():
155     if isRunning():
156         logger.log("codemux:  Stopping codemux service")
157         logger.log_call("/etc/init.d/codemux", "stop")