spaces after comma
[nodemanager.git] / plugins / codemux.py
index 65623f3..b25b703 100644 (file)
@@ -1,22 +1,19 @@
-# $Id$
-# $URL$
-
 """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."""
 
 import logger
 import os
 """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."""
 
 import logger
 import os
-import vserver
-from sets import Set
+
 from config import Config
 from config import Config
+import slivermanager
 
 CODEMUXCONF="/etc/codemux/codemux.conf"
 
 
 CODEMUXCONF="/etc/codemux/codemux.conf"
 
-def start(options, conf):
+def start():
     logger.log("codemux: plugin starting up...")
 
 def GetSlivers(data, config, plc = None):
     """
     logger.log("codemux: plugin starting up...")
 
 def GetSlivers(data, config, plc = None):
     """
-    For each sliver with the codemux attribute, parse out "host,port" 
+    For each sliver with the codemux attribute, parse out "host,port"
     and make entry in conf.  Restart service after.
     """
     if 'OVERRIDES' in dir(config):
     and make entry in conf.  Restart service after.
     """
     if 'OVERRIDES' in dir(config):
@@ -30,7 +27,7 @@ def GetSlivers(data, config, plc = None):
     slicesinconf = parseConf()
     # slices that need to be written to the conf
     codemuxslices = {}
     slicesinconf = parseConf()
     # slices that need to be written to the conf
     codemuxslices = {}
-    
+
     # XXX Hack for planetflow
     if slicesinconf.has_key("root"): _writeconf = False
     else: _writeconf = True
     # XXX Hack for planetflow
     if slicesinconf.has_key("root"): _writeconf = False
     else: _writeconf = True
@@ -47,20 +44,25 @@ def GetSlivers(data, config, plc = None):
                 if len(parts)<2:
                     logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
                     continue
                 if len(parts)<2:
                     logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
                     continue
-                params = {'host': parts[0], 'port': parts[1]}
+                if len(parts) == 3:
+                    ip = parts[2]
+                else:
+                    ip = ""
+                params = {'host': parts[0], 'port': parts[1], 'ip': ip}
+
                 try:
                     # Check to see if sliver is running.  If not, continue
                 try:
                     # Check to see if sliver is running.  If not, continue
-                    if vserver.VServer(sliver['name']).is_running():
+                    if slivermanager.is_running(sliver['name']):
                         # Check if new or needs updating
                         if (sliver['name'] not in slicesinconf.keys()) \
                         or (params not in slicesinconf.get(sliver['name'], [])):
                         # Check if new or needs updating
                         if (sliver['name'] not in slicesinconf.keys()) \
                         or (params not in slicesinconf.get(sliver['name'], [])):
-                            logger.log("codemux:  Updaiting slice %s using %s" % \
+                            logger.log("codemux:  Updating slice %s using %s" % \
                                 (sliver['name'], params['host']))
                             #  Toggle write.
                             _writeconf = True
                         # Add to dict of codemuxslices.  Make list to support more than one
                         # codemuxed host per slice.
                                 (sliver['name'], params['host']))
                             #  Toggle write.
                             _writeconf = True
                         # Add to dict of codemuxslices.  Make list to support more than one
                         # codemuxed host per slice.
-                        codemuxslices.setdefault(sliver['name'],[])
+                        codemuxslices.setdefault(sliver['name'], [])
                         codemuxslices[sliver['name']].append(params)
                 except:
                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
                         codemuxslices[sliver['name']].append(params)
                 except:
                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
@@ -68,13 +70,13 @@ def GetSlivers(data, config, plc = None):
                     pass
 
     # Remove slices from conf that no longer have the attribute
                     pass
 
     # Remove slices from conf that no longer have the attribute
-    for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
+    for deadslice in set(slicesinconf.keys()) - set(codemuxslices.keys()):
         # XXX Hack for root slice
         # XXX Hack for root slice
-        if deadslice != "root": 
+        if deadslice != "root":
             logger.log("codemux:  Removing %s" % deadslice)
             logger.log("codemux:  Removing %s" % deadslice)
-            _writeconf = True 
+            _writeconf = True
 
 
-    if _writeconf:  writeConf(sortDomains(codemuxslices))    
+    if _writeconf:  writeConf(sortDomains(codemuxslices))
     # ensure the service is running
     startService()
 
     # ensure the service is running
     startService()
 
@@ -83,16 +85,16 @@ def writeConf(slivers, conf = CODEMUXCONF):
     '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
     f = open(conf, "w")
     # This needs to be the first entry...
     '''Write conf with default entry up top. Elements in [] should have lower order domain names first. Restart service.'''
     f = open(conf, "w")
     # This needs to be the first entry...
-    try: 
+    try:
         f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
         f.write("* root 1080 %s\n" % Config().PLC_PLANETFLOW_HOST)
-    except AttributeError: 
+    except AttributeError:
         logger.log("codemux:  Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
         f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
     # Sort items for like domains
     for mapping in slivers:
         for (host, params) in mapping.iteritems():
             if params['slice'] == "root":  continue
         logger.log("codemux:  Can't find PLC_CONFIG_HOST in config. Using PLC_API_HOST")
         f.write("* root 1080 %s\n" % Config().PLC_API_HOST)
     # Sort items for like domains
     for mapping in slivers:
         for (host, params) in mapping.iteritems():
             if params['slice'] == "root":  continue
-            f.write("%s %s %s\n" % (host, params['slice'], params['port']))
+            f.write("%s %s %s %s\n" % (host, params['slice'], params['port'], params['ip']))
     f.truncate()
     f.close()
     try:  restartService()
     f.truncate()
     f.close()
     try:  restartService()
@@ -104,7 +106,7 @@ def sortDomains(slivers):
     dnames = {} # {host: slice}
     for (slice, params) in slivers.iteritems():
         for mapping in params:
     dnames = {} # {host: slice}
     for (slice, params) in slivers.iteritems():
         for mapping in params:
-            dnames[mapping['host']] = {"slice":slice, "port": mapping['port']}
+            dnames[mapping['host']] = {"slice":slice, "port": mapping['port'], "ip": mapping['ip']}
     hosts = dnames.keys()
     # sort by length
     hosts.sort(key=str.__len__)
     hosts = dnames.keys()
     # sort by length
     hosts.sort(key=str.__len__)
@@ -113,24 +115,29 @@ def sortDomains(slivers):
     # make list of slivers
     sortedslices = []
     for host in hosts: sortedslices.append({host: dnames[host]})
     # make list of slivers
     sortedslices = []
     for host in hosts: sortedslices.append({host: dnames[host]})
-    
+
     return sortedslices
 
     return sortedslices
 
-        
+
 def parseConf(conf = CODEMUXCONF):
     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
     slicesinconf = {} # default
 def parseConf(conf = CODEMUXCONF):
     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
     slicesinconf = {} # default
-    try: 
+    try:
         f = open(conf)
         for line in f.readlines():
         f = open(conf)
         for line in f.readlines():
-            if line.startswith("#") \
-            or (len(line.split()) > 4) \
-            or (len(line.split()) < 3):
+            parts = line.split()
+            if line.startswith("#") or (len(parts) > 4) or (len(parts) < 3):
                 continue
                 continue
-            (host, slice, port) = line.split()[:3]
-            logger.log("codemux:  found %s in conf" % slice, 2)
-            slicesinconf.setdefault(slice, [])
-            slicesinconf[slice].append({"host": host, "port": port})
+            if len(parts) == 4:
+                (host, slice, port, ip) = parts
+                logger.log("codemux:  found %s in conf" % slice, 2)
+                slicesinconf.setdefault(slice, [])
+                slicesinconf[slice].append({"host": host, "port": port, "ip": ip})
+            else:
+                (host, slice, port) = parts[:3]
+                logger.log("codemux:  found %s in conf" % slice, 2)
+                slicesinconf.setdefault(slice, [])
+                slicesinconf[slice].append({"host": host, "port": port})
         f.close()
     except IOError: logger.log_exc("codemux.parseConf got IOError")
     return slicesinconf
         f.close()
     except IOError: logger.log_exc("codemux.parseConf got IOError")
     return slicesinconf
@@ -142,22 +149,26 @@ def isRunning():
     else:
         return False
 
     else:
         return False
 
-
 def restartService():
 def restartService():
+    if not os.path.exists("/etc/init.d/codemux"): return
     logger.log("codemux:  Restarting codemux service")
     if isRunning():
     logger.log("codemux:  Restarting codemux service")
     if isRunning():
-        logger.log_call(["/etc/init.d/codemux","condrestart", ])
+        logger.log_call(["/etc/init.d/codemux", "condrestart", ])
     else:
     else:
-        logger.log_call(["/etc/init.d/codemux","restart", ])
-
+        logger.log_call(["/etc/init.d/codemux", "restart", ])
 
 def startService():
 
 def startService():
+    if not os.path.exists("/etc/init.d/codemux"): return
     if not isRunning():
         logger.log("codemux:  Starting codemux service")
         logger.log_call(["/etc/init.d/codemux", "start", ])
     if not isRunning():
         logger.log("codemux:  Starting codemux service")
         logger.log_call(["/etc/init.d/codemux", "start", ])
+    logger.log_call(["/sbin/chkconfig", "codemux", "on"])
 
 
 def stopService():
 
 
 def stopService():
+    if not os.path.exists("/etc/init.d/codemux"): return
     if isRunning():
         logger.log("codemux:  Stopping codemux service")
         logger.log_call(["/etc/init.d/codemux", "stop", ])
     if isRunning():
         logger.log("codemux:  Stopping codemux service")
         logger.log_call(["/etc/init.d/codemux", "stop", ])
+    logger.log_call(["/sbin/chkconfig", "codemux", "off"])
+