f14fdc05e62687228bb1618fcb485067fa5c9f98
[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     logger.log("codemux: plugin starting up...")
16
17 def GetSlivers(data, config, plc = None):
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     if 'slivers' not in data:
39         logger.log("codemux.GetSlivers: could not find the slivers keyin data (PLC connection down?) - IGNORED")
40         return
41
42     # Parse attributes and update dict of scripts
43     for sliver in data['slivers']:
44         for attribute in sliver['attributes']:
45             if attribute['tagname'] == 'codemux':
46                 # add to conf.  Attribute is [host, port]
47                 parts = attribute['value'].split(",")
48                 if len(parts)<2:
49                     logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
50                     continue
51                 params = {'host': parts[0], 'port': parts[1]}
52                 try:
53                     # Check to see if sliver is running.  If not, continue
54                     if vserver.VServer(sliver['name']).is_running():
55                         # Check if new or needs updating
56                         if (sliver['name'] not in slicesinconf.keys()) \
57                         or (params not in slicesinconf.get(sliver['name'], [])):
58                             logger.log("codemux:  Updaiting slice %s using %s" % \
59                                 (sliver['name'], params['host']))
60                             #  Toggle write.
61                             _writeconf = True
62                         # Add to dict of codemuxslices.  Make list to support more than one
63                         # codemuxed host per slice.
64                         codemuxslices.setdefault(sliver['name'],[])
65                         codemuxslices[sliver['name']].append(params)
66                 except:
67                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
68                                 % sliver['name'])
69                     pass
70
71     # Remove slices from conf that no longer have the attribute
72     for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
73         # XXX Hack for root slice
74         if deadslice != "root": 
75             logger.log("codemux:  Removing %s" % deadslice)
76             _writeconf = True 
77
78     if _writeconf:  writeConf(sortDomains(codemuxslices))    
79     # ensure the service is running
80     startService()
81
82
83 def writeConf(slivers, conf = CODEMUXCONF):
84     '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
85     f = open(conf, "w")
86     # This needs to be the first entry...
87     try: 
88         f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
89     except AttributeError: 
90         logger.log("codemux:  Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
91         f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
92     # Sort items for like domains
93     for mapping in slivers:
94         for (host, params) in mapping.iteritems():
95             if params['slice'] == "root":  continue
96             f.write("%s %s %s\n" % (host, params['slice'], params['port']))
97     f.truncate()
98     f.close()
99     try:  restartService()
100     except:  logger.log_exc()
101
102
103 def sortDomains(slivers):
104     '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
105     dnames = {} # {host: slice}
106     for (slice, params) in slivers.iteritems():
107         for mapping in params:
108             dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
109     hosts = dnames.keys()
110     # sort by length
111     hosts.sort(key=str.__len__)
112     # longer first
113     hosts.reverse()
114     # make list of slivers
115     sortedslices = []
116     for host in hosts: sortedslices.append({host: dnames[host]})
117     
118     return sortedslices
119
120         
121 def parseConf(conf = CODEMUXCONF):
122     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
123     slicesinconf = {} # default
124     try: 
125         f = open(conf)
126         for line in f.readlines():
127             if line.startswith("#") \
128             or (len(line.split()) > 4) \
129             or (len(line.split()) < 3):
130                 continue
131             (host, slice, port) = line.split()[:3]
132             logger.log("codemux:  found %s in conf" % slice, 2)
133             slicesinconf.setdefault(slice, [])
134             slicesinconf[slice].append({"host": host, "port": port})
135         f.close()
136     except IOError: logger.log_exc()
137     return slicesinconf
138
139
140 def isRunning():
141     if len(os.popen("pidof codemux").readline().rstrip("\n")) > 0:
142         return True
143     else:
144         return False
145
146
147 def restartService():
148     if not os.path.exists("/etc/init.d/codemux"): return
149     logger.log("codemux:  Restarting codemux service")
150     if isRunning():
151         logger.log_call("/etc/init.d/codemux","condrestart")
152     else:
153         logger.log_call("/etc/init.d/codemux","restart")
154
155
156 def startService():
157     if not os.path.exists("/etc/init.d/codemux"): return
158     if not isRunning():
159         logger.log("codemux:  Starting codemux service")
160         logger.log_call("/etc/init.d/codemux", "start")
161     logger.log_call("/sbin/chkconfig", "codemux", "on")
162
163
164 def stopService():
165     if not os.path.exists("/etc/init.d/codemux"): return
166     if isRunning():
167         logger.log("codemux:  Stopping codemux service")
168         logger.log_call("/etc/init.d/codemux", "stop")
169     logger.log_call("/sbin/chkconfig", "codemux", "off")