reguire gnupg1 on f>=31; sense the system to use gpg1 when installed
[nodemanager.git] / plugins / codemux.py
index 7f2200d..7ad0039 100644 (file)
@@ -1,9 +1,21 @@
-"""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."""
+"""
+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.
+"""
+
+# NOTE
+# in November 2015 it was established that this plugin is the culprit
+# for our long standing slice re-creation issue
+# for this reason this is now turned off on lxc-based hosts
+# as per the spec file this plugin gets packaged as part of
+# nodemanager-vs and not nodemanager-lib anymore
 
 import logger
 import os
-import libvirt
+
 from config import Config
+import slivermanager
 
 CODEMUXCONF="/etc/codemux/codemux.conf"
 
@@ -28,8 +40,10 @@ def GetSlivers(data, config, plc = None):
     codemuxslices = {}
 
     # XXX Hack for planetflow
-    if slicesinconf.has_key("root"): _writeconf = False
-    else: _writeconf = True
+    if "root" in slicesinconf:
+        _writeconf = False
+    else:
+        _writeconf = True
 
     # Parse attributes and update dict of scripts
     if 'slivers' not in data:
@@ -40,8 +54,9 @@ def GetSlivers(data, config, plc = None):
             if attribute['tagname'] == 'codemux':
                 # add to conf.  Attribute is [host, port]
                 parts = attribute['value'].split(",")
-                if len(parts)<2:
-                    logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."%attribute['value'])
+                if len(parts) < 2:
+                    logger.log("codemux: attribute value (%s) for codemux not separated by comma. Skipping."
+                               %attribute['value'])
                     continue
                 if len(parts) == 3:
                     ip = parts[2]
@@ -51,9 +66,9 @@ def GetSlivers(data, config, plc = None):
 
                 try:
                     # Check to see if sliver is running.  If not, continue
-                    if isLXCDomRunning(sliver['name']):
+                    if slivermanager.is_running(sliver['name']):
                         # Check if new or needs updating
-                        if (sliver['name'] not in slicesinconf.keys()) \
+                        if (sliver['name'] not in list(slicesinconf.keys())) \
                         or (params not in slicesinconf.get(sliver['name'], [])):
                             logger.log("codemux:  Updating slice %s using %s" % \
                                 (sliver['name'], params['host']))
@@ -61,10 +76,10 @@ def GetSlivers(data, config, plc = None):
                             _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."\
+                    logger.log("codemux:  sliver %s not running yet.  Deferring."
                                 % sliver['name'])
                     pass
 
@@ -75,7 +90,8 @@ def GetSlivers(data, config, plc = None):
             logger.log("codemux:  Removing %s" % deadslice)
             _writeconf = True
 
-    if _writeconf:  writeConf(sortDomains(codemuxslices))
+    if _writeconf:
+        writeConf(sortDomains(codemuxslices))
     # ensure the service is running
     startService()
 
@@ -91,29 +107,32 @@ def writeConf(slivers, conf = CODEMUXCONF):
         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():
+        for (host, params) in mapping.items():
             if params['slice'] == "root":  continue
             f.write("%s %s %s %s\n" % (host, params['slice'], params['port'], params['ip']))
     f.truncate()
     f.close()
-    try:  restartService()
-    except:  logger.log_exc("codemux.writeConf failed to restart service")
+    try:
+        restartService()
+    except:
+        logger.log_exc("codemux.writeConf failed to restart service")
 
 
 def sortDomains(slivers):
     '''Given a dict of {slice: {domainname, port}}, return array of slivers with lower order domains first'''
     dnames = {} # {host: slice}
-    for (slice, params) in slivers.iteritems():
+    for (slice, params) in slivers.items():
         for mapping in params:
             dnames[mapping['host']] = {"slice":slice, "port": mapping['port'], "ip": mapping['ip']}
-    hosts = dnames.keys()
+    hosts = list(dnames.keys())
     # sort by length
     hosts.sort(key=str.__len__)
     # longer first
     hosts.reverse()
     # make list of slivers
     sortedslices = []
-    for host in hosts: sortedslices.append({host: dnames[host]})
+    for host in hosts:
+        sortedslices.append({host: dnames[host]})
 
     return sortedslices
 
@@ -124,14 +143,19 @@ def parseConf(conf = CODEMUXCONF):
     try:
         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
-            (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
@@ -147,9 +171,9 @@ def restartService():
     if not os.path.exists("/etc/init.d/codemux"): return
     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:
-        logger.log_call(["/etc/init.d/codemux","restart", ])
+        logger.log_call(["/etc/init.d/codemux", "restart", ])
 
 def startService():
     if not os.path.exists("/etc/init.d/codemux"): return
@@ -166,13 +190,3 @@ def stopService():
         logger.log_call(["/etc/init.d/codemux", "stop", ])
     logger.log_call(["/sbin/chkconfig", "codemux", "off"])
 
-def isLXCDomRunning(domName):
-    try:
-        running = False
-        conn = libvirt.open('lxc://')
-        dom  = conn.lookupByName(domName)
-        running = dom.info()[0] == libvirt.VIR_DOMAIN_RUNNING
-    finally:
-        conn.close()
-    return running
-