added files related to the ipv6 support on slices
authorGuilherme Sperb Machado <gsm@machados.org>
Fri, 12 Sep 2014 14:38:06 +0000 (16:38 +0200)
committerGuilherme Sperb Machado <gsm@machados.org>
Fri, 12 Sep 2014 14:38:06 +0000 (16:38 +0200)
plugins/ipv6.py [new file with mode: 0644]
plugins/update_ipv6addr_slivertag.py [new file with mode: 0644]
tools.py

diff --git a/plugins/ipv6.py b/plugins/ipv6.py
new file mode 100644 (file)
index 0000000..05b7446
--- /dev/null
@@ -0,0 +1,313 @@
+"""
+IPv6 test! version: 0.3
+"""
+
+import logger
+import os
+import socket
+import re
+
+import tools
+import libvirt
+import uuid
+from sliver_libvirt import Sliver_Libvirt
+from xml.dom.minidom import parseString
+
+priority=4
+
+radvdConfFile = '/etc/radvd.conf'
+ipv6addrtag = 'ipv6_address'
+
+def start():
+    logger.log("ipv6: plugin starting up...")
+
+def buildLibvirtDefaultNetConfig(dom):
+
+       # create the <network> element
+       networkElem = dom.createElement("network")
+       # create <name> element
+       nameElem = dom.createElement("name")
+       textName = dom.createTextNode("default")
+       nameElem.appendChild(textName)
+       # create <uuid> element
+       uuidElem = dom.createElement("uuid")
+       textUUID = dom.createTextNode(str(uuid.uuid1()))
+       uuidElem.appendChild(textUUID)
+       # create <forward> element
+       forwardElem = dom.createElement("forward")
+       forwardElem.setAttribute("mode", "nat")
+       # create <nat> element
+       natElem = dom.createElement("nat")
+       # create <port> element
+       portElem = dom.createElement("port")
+       portElem.setAttribute("end", "65535")
+       portElem.setAttribute("start", "1024")
+       # create the ipv4 <ip> element
+       ipElem0 = dom.createElement("ip")
+       ipElem0.setAttribute("address", "192.168.122.1")
+       ipElem0.setAttribute("netmask", "255.255.255.0")
+       # create the <dhcp> element
+       dhcpElem = dom.createElement("dhcp")
+       # create the <range> element
+       rangeElem = dom.createElement("range")
+       rangeElem.setAttribute("end", "192.168.122.254")
+       rangeElem.setAttribute("start", "192.168.122.2")
+       # create the <bridge> element
+       bridgeElem = dom.createElement("bridge")
+       bridgeElem.setAttribute("delay", "0")
+       bridgeElem.setAttribute("name", "virbr0")
+       bridgeElem.setAttribute("stp", "on")
+
+       # build the whole thing
+       natElem.appendChild(portElem)
+       forwardElem.appendChild(natElem)
+       
+       dhcpElem.appendChild(rangeElem)
+       ipElem0.appendChild(dhcpElem)
+       networkElem.appendChild(nameElem)
+       networkElem.appendChild(uuidElem)
+       networkElem.appendChild(forwardElem)
+       networkElem.appendChild(bridgeElem)
+       networkElem.appendChild(ipElem0)
+       return networkElem
+
+def checkForIPv6(defaultNetworkConfig):
+       netnodes = defaultNetworkConfig.getElementsByTagName('network')
+       hasIPv6 = False
+        for netnode in netnodes:
+                ips = netnode.getElementsByTagName('ip')
+                for ip in ips:
+                        if ip.getAttribute('family')=='ipv6':
+                                logger.log("ipv6: the configuration already have an IPv6 address/prefix set for the slivers! %s/%s" % (ip.getAttribute('address'), ip.getAttribute('prefix')) )
+                               hasIPv6 = True
+       return hasIPv6
+                       
+
+
+def addIPv6(defaultNetworkConfig, ipv6addr, prefix):
+
+       netnodes = defaultNetworkConfig.getElementsByTagName('network')
+       for netnode in netnodes:
+               # create the ipv6 <ip> element 1
+               ipElem1 = defaultNetworkConfig.createElement("ip")
+               ipElem1.setAttribute("family", "ipv6")
+               ipElem1.setAttribute("address", ipv6addr)
+               ipElem1.setAttribute("prefix", prefix)
+               # create the ipv6 <ip> element 2
+               # it's ugly, I know, but we need a link-local address on the interface!
+               ipElem2 = defaultNetworkConfig.createElement("ip")
+               ipElem2.setAttribute("family", "ipv6")
+               ipElem2.setAttribute("address", "fe80:1234::1")
+               ipElem2.setAttribute("prefix", "64")
+               # adding to the 'defaultNetworkConfig'
+               netnode.appendChild(ipElem1)
+               netnode.appendChild(ipElem2)
+       return defaultNetworkConfig
+
+def changeIPv6(dom, ipv6addr, prefix):
+       ips = dom.getElementsByTagName('ip')
+       for ip in ips:
+               if ip.getAttribute("family")=='ipv6' and not(re.match(r'fe80(.*)', ip.getAttribute("address"), re.I)):
+                       ip.setAttribute("address", ipv6addr)
+                       ip.setAttribute("prefix", prefix)
+       return dom
+                       
+
+def removeIPv6(dom):
+       networks = dom.getElementsByTagName('network')
+       for network in networks:
+               ips = network.getElementsByTagName('ip')
+               for ip in ips:
+                       if ip.getAttribute("family")=='ipv6':
+                               network.removeChild(ip)
+       return dom
+       
+
+def checkIfIPv6IsDifferent(dom, ipv6addr, prefix):
+       netnodes = dom.getElementsByTagName('network')
+        for netnode in netnodes:
+                ips = netnode.getElementsByTagName('ip')
+                for ip in ips:
+                       if ip.getAttribute('family')=='ipv6' and not( re.match(r'fe80(.*)', ip.getAttribute("address"), re.I) ) and (ip.getAttribute('address')!=ipv6addr or ip.getAttribute('prefix')!=prefix):
+                               logger.log("ipv6: the IPv6 address or prefix are different. Change detected!")
+                               return True
+
+        return False
+
+
+def setAutostart(network):
+        try:
+               network.setAutostart(1)
+       except:
+               logger.log("ipv6: network could not set to autostart")
+
+
+def setUp(networkLibvirt, connLibvirt, networkElem, ipv6addr, prefix):
+       newXml = networkElem.toxml()
+       #logger.log(networkElem.toxml())
+       #ret = dir(conn)
+       #for method in ret:
+       #       logger.log(repr(method))
+       networkLibvirt.undefine()
+       networkLibvirt.destroy()
+       connLibvirt.networkCreateXML(newXml)
+       networkDefault = connLibvirt.networkDefineXML(newXml)
+       setAutostart(networkDefault)
+       commandForwarding = ['sysctl', '-w', 'net.ipv6.conf.all.forwarding=1']
+       logger.log_call(commandForwarding, timeout=15*60)
+       configRadvd = """
+interface virbr0
+{
+        AdvSendAdvert on;
+        MinRtrAdvInterval 30;
+        MaxRtrAdvInterval 100;
+        prefix %s
+        {
+                AdvOnLink on;
+                AdvAutonomous on;
+                AdvRouterAddr off;
+        };
+
+};
+""" % (ipv6addr+"/"+prefix)
+       f=open(radvdConfFile,'w')
+        f.write(configRadvd)
+       f.close()
+       killRadvd()
+       startRadvd()
+       logger.log("ipv6: set up process finalized. Enabled IPv6 address to the slivers!")
+
+def cleanUp(networkLibvirt, connLibvirt, networkElem):
+       dom = removeIPv6(networkElem)
+       newXml = dom.toxml()
+        networkLibvirt.undefine()
+        networkLibvirt.destroy()
+        # TODO: set autostart for the network
+        connLibvirt.networkCreateXML(newXml)
+        networkDefault = connLibvirt.networkDefineXML(newXml)
+       setAutostart(networkDefault)
+       killRadvd()
+       logger.log("ipv6: cleanup process finalized. The IPv6 support on the slivers was removed.")
+
+def killRadvd():
+       commandKillRadvd = ['killall', 'radvd']
+        logger.log_call(commandKillRadvd, timeout=15*60)
+
+def startRadvd():
+       commandRadvd = ['radvd']
+        logger.log_call(commandRadvd, timeout=15*60)
+
+def getSliverTagId(slivertags):
+       for slivertag in slivertags:
+               if slivertag['tagname']==ipv6addrtag:
+                       return slivertag['slice_tag_id']
+
+
+def SetSliverTag(plc, data, tagname):
+
+    for sliver in data['slivers']:
+       # TODO: what about the prefixlen? should we add on it as well?
+       # here, I'm just taking the ipv6addr (value)
+       value,prefixlen = tools.get_sliver_ipv6(sliver['name'])
+
+       node_id = tools.node_id()
+       logger.log("ipv6: slice %s" % (slice) )
+       logger.log("ipv6: nodeid %s" % (node_id) )
+       slivertags = plc.GetSliceTags({"name":slice['name'],"node_id":node_id,"tagname":tagname})
+       logger.log(repr(str(slivertags)))
+       for tag in slivertags:
+               logger.log(repr(str(tag)))
+
+       ipv6addr = plc.GetSliceIPv6Address(slice['name'])
+       # if the value to set is null...
+       if value is None:
+               if ipv6addr is not None or len(ipv6addr)==0:
+                       # then, let's remove the slice tag
+                       slivertag_id = getSliverTagId(slivertags)
+                       plc.DeleteSliceTag(slivertag_id)
+       else:
+               # if the ipv6 addr set on the slice does not exist yet, so, let's add it
+               if (len(ipv6addr)==0 or ipv6addr is None) and len(value)>0:
+                       try:
+                               slivertag_id=plc.AddSliceTag(slice['name'],tagname,value,node_id)
+                               logger.log("ipv6: slice tag added to slice %s" % (slice['name']) )
+                       except:
+                               logger.log_exc ("ipv6: could not set ipv6 addr tag to the slive. slice=%(slice['name'])s tag=%(tagname)s node_id=%(node_id)d" % locals() )
+               # if the ipv6 addr set on the slice is different on the value provided, let's update it
+               if len(value)>0 and ipv6addr!=value:
+                       #slivertag_id=slivertags[0]['slice_tag_id']
+                       slivertag_id = getSliverTagId(slivertags)
+                       plc.UpdateSliceTag(slivertag_id,value)
+       
+
+def GetSlivers(data, config, plc):
+
+    #return
+    #for sliver in data['slivers']:
+       #ipv6addr,prefixlen = tools.get_sliver_ipv6(sliver['name'])
+       #tools.add_ipv6addr_hosts_line(sliver['name'], data['hostname'], ipv6addr)
+       #result = tools.search_ipv6addr_hosts(sliver['name'], ipv6addr)
+       #logger.log("tools: result=%s" % (str(result)) )
+        #tools.remove_all_ipv6addr_hosts(sliver['name'], data['hostname'])
+    #return
+    
+
+    type = 'sliver.LXC'
+
+    interfaces = data['interfaces']
+    logger.log(repr(interfaces))
+    for interface in interfaces:
+       logger.log('ipv6: get interface 1: %r'%(interface))
+       if 'interface_tag_ids' in interface:
+               interface_tag_ids = "interface_tag_ids"
+               interface_tag_id = "interface_tag_id"
+               settings = plc.GetInterfaceTags({interface_tag_id:interface[interface_tag_ids]})
+               isSliversIPv6PrefixSet = False
+               for setting in settings:
+                       #logger.log(repr(setting))
+                       if setting['tagname']=='sliversipv6prefix':
+                               ipv6addrprefix = setting['value'].split('/', 1)
+                               ipv6addr = ipv6addrprefix[0]
+                               prefix = ipv6addrprefix[1]
+                               logger.log("ipv6: %s" % (ipv6addr) )
+                               validIPv6 = tools.isValidIPv6(ipv6addr)
+                               if not(validIPv6):
+                                       logger.log("ipv6: the 'sliversipv6prefix' tag presented a non-valid IPv6 address!")
+                               else:
+                                       # connecting to the libvirtd
+                                       connLibvirt = Sliver_Libvirt.getConnection(type)
+                                       list = connLibvirt.listAllNetworks()
+                                       for networkLibvirt in list:
+                                               xmldesc = networkLibvirt.XMLDesc()
+                                               dom = parseString(xmldesc)
+                                               hasIPv6 = checkForIPv6(dom)
+                                               if hasIPv6:
+                                                       # let's first check if the IPv6 is different or is it the same...
+                                                       isDifferent = checkIfIPv6IsDifferent(dom, ipv6addr, prefix)
+                                                       if isDifferent:
+                                                               logger.log("ipv6: the tag 'sliversipv6prefix' was modified! Updating the configuration with the new one...")
+                                                               networkElem = changeIPv6(dom, ipv6addr, prefix)
+                                                               setUp(networkLibvirt, connLibvirt, networkElem, ipv6addr, prefix)
+                                                               logger.log("ipv6: trying to reboot the slivers...")
+                                                               tools.reboot_sliver('blah')
+                                               else:
+                                                       logger.log("ipv6: starting to redefine the virtual network...")
+                                                       #networkElem = buildLibvirtDefaultNetConfig(dom,ipv6addr,prefix)
+                                                       networkElem = addIPv6(dom, ipv6addr, prefix)
+                                                       setUp(networkLibvirt, connLibvirt, networkElem, ipv6addr, prefix)
+                                                       logger.log("ipv6: trying to reboot the slivers...")
+                                                       tools.reboot_sliver('blah')
+                               isSliversIPv6PrefixSet = True
+               if not(isSliversIPv6PrefixSet):
+                       # connecting to the libvirtd
+                       connLibvirt = Sliver_Libvirt.getConnection(type)
+                       list = connLibvirt.listAllNetworks()
+                       for networkLibvirt in list:
+                               xmldesc = networkLibvirt.XMLDesc()
+                               dom = parseString(xmldesc)
+                               if checkForIPv6(dom):
+                                       cleanUp(networkLibvirt, connLibvirt, dom)
+                                       logger.log("ipv6: trying to reboot the slivers...")
+                                       tools.reboot_sliver('blah')
+
+    logger.log("ipv6: all done!")
diff --git a/plugins/update_ipv6addr_slivertag.py b/plugins/update_ipv6addr_slivertag.py
new file mode 100644 (file)
index 0000000..a1190cf
--- /dev/null
@@ -0,0 +1,84 @@
+"""
+IPv6 test! version: 0.3
+"""
+
+import logger
+import os
+import socket
+import re
+
+import tools
+import libvirt
+import uuid
+from sliver_libvirt import Sliver_Libvirt
+from xml.dom.minidom import parseString
+
+priority=150
+
+ipv6addrtag = 'ipv6_address'
+
+def start():
+    logger.log("update_ipv6addr_slivertag: plugin starting up...")
+
+
+def getSliverTagId(slivertags):
+        for slivertag in slivertags:
+                       if slivertag['tagname']==ipv6addrtag:
+                        return slivertag['slice_tag_id']
+       return None
+
+def SetSliverTag(plc, data, tagname):
+
+    for slice in data['slivers']:
+       logger.log("update_ipv6addr_slivertag: starting the update procedure for slice=%s" % (slice['name']) )
+
+       # TODO: what about the prefixlen? should we add on it as well?
+       # here, I'm just taking the ipv6addr (value)
+       value,prefixlen = tools.get_sliver_ipv6(slice['name'])
+
+       node_id = tools.node_id()
+       slivertags = plc.GetSliceTags({"name":slice['name'],"node_id":node_id,"tagname":tagname})
+       #logger.log(repr(str(slivertags)))
+       #for tag in slivertags:
+       #       logger.log(repr(str(tag)))
+
+       ipv6addr = plc.GetSliceIPv6Address(slice['name'])
+       logger.log("update_ipv6addr_slivertag: slice=%s getSliceIPv6Address=%s" % (slice['name'],ipv6addr) )
+       # if the value to set is null...
+       if value is None:
+               if ipv6addr is not None:
+                       # then, let's remove the slice tag
+                       slivertag_id = getSliverTagId(slivertags)
+                       if slivertag_id:
+                               try:
+                                       plc.DeleteSliceTag(slivertag_id)
+                                       logger.log("update_ipv6addr_slivertag: slice tag deleted for slice=%s" % (slice['name']) )
+                               except:
+                                       logger.log("update_ipv6addr_slivertag: slice tag not deleted for slice=%s" % (slice['name']) )
+               # if there's no ipv6 address anymore, then remove everything from the /etc/hosts
+               tools.remove_all_ipv6addr_hosts(slice['name'], data['hostname'])
+       else:
+               # if the ipv6 addr set on the slice does not exist yet, so, let's add it
+               if (ipv6addr is None) and len(value)>0:
+                       try:
+                               logger.log("update_ipv6addr_slivertag: slice name=%s" % (slice['name']) )
+                               slivertag_id=plc.AddSliceTag(slice['name'],tagname,value,node_id)
+                               logger.log("update_ipv6addr_slivertag: slice tag added to slice %s" % (slice['name']) )
+                       except:
+                               logger.log("update_ipv6addr_slivertag: could not set ipv6 addr tag to the sliver. slice=%s tag=%s node_id=%d" % (slice['name'],tagname,node_id) )
+               # if the ipv6 addr set on the slice is different on the value provided, let's update it
+               if (ipv6addr is not None) and (len(value)>0) and (ipv6addr!=value):
+                       slivertag_id = getSliverTagId(slivertags)
+                       plc.UpdateSliceTag(slivertag_id,value)
+               # ipv6 entry on /etc/hosts of each slice
+               result = tools.search_ipv6addr_hosts(slice['name'], value)
+               if not result:
+                       tools.remove_all_ipv6addr_hosts(slice['name'], data['hostname'])
+                       tools.add_ipv6addr_hosts_line(slice['name'], data['hostname'], value)
+       logger.log("update_ipv6addr_slivertag: finishing the update process for slice=%s" % (slice['name']) )
+
+def GetSlivers(data, config, plc):
+
+    SetSliverTag(plc, data, ipv6addrtag)
+
+    logger.log("update_ipv6addr_slivertag: all done!")
index 02e2ab9..b90a59e 100644 (file)
--- a/tools.py
+++ b/tools.py
@@ -11,6 +11,24 @@ import shutil
 import sys
 import signal
 
+###################################################
+# Added by Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+
+import re
+import socket
+import fileinput
+
+# TODO: is there anything better to do if the "libvirt", "sliver_libvirt",
+# and "sliver_lxc" are not in place?
+try:
+       import libvirt
+       from sliver_libvirt import Sliver_Libvirt
+    import sliver_lxc
+except:
+    logger.log("Could not import sliver_lxc or libvirt or sliver_libvirt -- which is required here.")
+###################################################
+
 import logger
 
 PID_FILE = '/var/run/nodemanager.pid'
@@ -237,6 +255,65 @@ def get_sliver_process(slice_name, process_cmdline):
 
     return (cgroup_fn, pid)
 
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Basically this method is just a copy from "get_process()", just
+# adding one more split() to correctly parse the processes for LXC.
+# Only for LXC!
+# TODO: maybe merge both methods, and put the type as an argument, if
+# it is LXC or vserver
+###################################################
+def get_sliver_process_lxc(slice_name, process_cmdline):
+    """ Utility function to find a process inside of an LXC sliver. Returns
+        (cgroup_fn, pid). cgroup_fn is the filename of the cgroup file for
+        the process, for example /proc/2592/cgroup. Pid is the process id of
+        the process. If the process is not found then (None, None) is returned.
+    """
+    try:
+        cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
+        output = os.popen(cmd).readlines()
+    except:
+        # the slice couldn't be found
+        logger.log("get_sliver_process: couldn't find slice %s" % slice_name)
+        return (None, None)
+
+    cgroup_fn = None
+    pid = None
+    for e in output:
+        try:
+            l = e.rstrip()
+               #logger.log("tools: l=%s" % (l) )
+            path = l.split(':')[0]
+                       #logger.log("tools: path=%s" % (path) )
+            comp = l.rsplit(':')[-1]
+            #logger.log("tools: comp=%s" % (comp) )
+            slice_name_check1 = comp.rsplit('/')[-1]
+            #logger.log("tools: slice_name_check1=%s" % (slice_name_check1) )
+               slice_name_check2 = slice_name_check1.rsplit('.')[0]
+               #logger.log("tools: slice_name_check2=%s" % (slice_name_check2) )
+
+            if (slice_name_check2 == slice_name):
+               slice_path = path
+                       pid = slice_path.split('/')[2]
+                               #logger.log("tools: pid=%s" % (pid) )
+                       cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
+                               #logger.log("tools: cmdline=%s" % (cmdline) )
+                               #logger.log("tools: process_cmdline=%s" % (process_cmdline) )
+                               if (cmdline == process_cmdline):
+                               cgroup_fn = slice_path
+                               break
+        except:
+           #logger.log("tools: break!")
+            break
+
+    if (not cgroup_fn) or (not pid):
+        logger.log("get_sliver_process: process %s not running in slice %s" % (process_cmdline, slice_name))
+        return (None, None)
+
+    return (cgroup_fn, pid)
+
+
 def get_sliver_ifconfig(slice_name, device="eth0"):
     """ return the output of "ifconfig" run from inside the sliver.
 
@@ -276,6 +353,55 @@ def get_sliver_ifconfig(slice_name, device="eth0"):
 
     return result
 
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Basically this method is just a copy from "get_sliver_ifconfig()", but,
+# instead, calls the "get_sliver_process_lxc()" method.
+# Only for LXC!
+# TODO: maybe merge both methods, and put the type as an argument, if
+# it is LXC or vserver
+###################################################
+def get_sliver_ifconfig_lxc(slice_name, device="eth0"):
+    """ return the output of "ifconfig" run from inside the sliver.
+
+        side effects: adds "/usr/sbin" to sys.path
+    """
+
+    # See if setns is installed. If it's not then we're probably not running
+    # LXC.
+    if not os.path.exists("/usr/sbin/setns.so"):
+        return None
+
+    # setns is part of lxcsu and is installed to /usr/sbin
+    if not "/usr/sbin" in sys.path:
+        sys.path.append("/usr/sbin")
+    import setns
+
+    (cgroup_fn, pid) = get_sliver_process_lxc(slice_name, "/sbin/init")
+    if (not cgroup_fn) or (not pid):
+        return None
+
+    path = '/proc/%s/ns/net'%pid
+
+    result = None
+    try:
+        setns.chcontext(path)
+
+        args = ["/sbin/ifconfig", device]
+        sub = subprocess.Popen(args, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
+        sub.wait()
+
+        if (sub.returncode != 0):
+            logger.log("get_slice_ifconfig: error in ifconfig: %s" % sub.stderr.read())
+
+        result = sub.stdout.read()
+    finally:
+        setns.chcontext("/proc/1/ns/net")
+
+    return result
+
+
 def get_sliver_ip(slice_name):
     ifconfig = get_sliver_ifconfig(slice_name)
     if not ifconfig:
@@ -290,6 +416,39 @@ def get_sliver_ip(slice_name):
 
     return None
 
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Get the slice ipv6 address
+# Only for LXC!
+###################################################
+def get_sliver_ipv6(slice_name):
+    ifconfig = get_sliver_ifconfig_lxc(slice_name)
+    if not ifconfig:
+        return None,None
+    
+    # example: 'inet6 2001:67c:16dc:1302:5054:ff:fea7:7882  prefixlen 64  scopeid 0x0<global>'
+    prog = re.compile(r'inet6\s+(.*)\s+prefixlen\s+(\d+)\s+scopeid\s+(.+)<global>')
+    for line in ifconfig.split("\n"):
+       search = prog.search(line)
+       if search:
+               ipv6addr = search.group(1)
+               prefixlen = search.group(2)
+               return (ipv6addr,prefixlen)
+    return None,None
+
+################################################### 
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Check if the address is a AF_INET6 family address
+###################################################
+def isValidIPv6(ipv6addr):
+        try:
+                socket.inet_pton(socket.AF_INET6, ipv6addr)
+        except socket.error:
+                return False
+       return True
+
 ### this returns the kind of virtualization on the node
 # either 'vs' or 'lxc'
 # also caches it in /etc/planetlab/virt for next calls
@@ -319,6 +478,102 @@ def has_systemctl ():
         _has_systemctl = (subprocess.call([ 'systemctl', '--help' ]) == 0)
     return _has_systemctl
 
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# This method was developed to support the ipv6 plugin
+# Only for LXC!
+###################################################
+def reboot_sliver(name):
+       type = 'sliver.LXC'
+       # connecting to the libvirtd
+       connLibvirt = Sliver_Libvirt.getConnection(type)
+       domains = connLibvirt.listAllDomains()
+       for domain in domains:
+               #ret = dir(domain)
+               #for method in ret:
+               #       logger.log("ipv6: " + repr(method))
+               #logger.log("tools: " + str(domain.name()) )
+               try:
+                       domain.destroy()
+                       logger.log("tools: %s destroyed" % (domain.name()) )
+                       domain.create()
+                       logger.log("tools: %s created" % (domain.name()) )
+               except:
+                       logger.log("tools: %s could not be rebooted" % (domain.name()) )
+
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Get the /etc/hosts file path
+###################################################
+def get_hosts_file_path(slicename):
+    containerDir = os.path.join(sliver_lxc.Sliver_LXC.CON_BASE_DIR, slicename)
+    logger.log("tools: %s" % (containerDir) )
+    return os.path.join(containerDir, 'etc', 'hosts')
+
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Search if there is a specific ipv6 address in the /etc/hosts file of a given slice
+###################################################
+def search_ipv6addr_hosts(slicename, ipv6addr):
+    hostsFilePath = get_hosts_file_path(slicename)
+    found=False
+    try:
+       for line in fileinput.input(r'%s' % (hostsFilePath)):
+               if re.search(r'%s' % (ipv6addr), line):
+                       found=True
+       fileinput.close()
+       return found
+    except:
+        logger.log("tools: error when finding ipv6 address %s in the /etc/hosts file of slice=%s" % (ipv6addr, slicename) )
+
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Removes all ipv6 addresses from the /etc/hosts file of a given slice
+###################################################
+def remove_all_ipv6addr_hosts(slicename, node):
+    hostsFilePath = get_hosts_file_path(slicename)
+    try:
+       for line in fileinput.input(r'%s' % (hostsFilePath), inplace=True):
+               logger.log("tools: line=%s" % (line) )
+               search = re.search(r'^(.*)\s+(%s|%s)$' % (node,'localhost'), line)
+               if search:
+                       ipv6candidate = search.group(1)
+                       ipv6candidatestrip = ipv6candidate.strip()
+                       logger.log("tools: group1=%s" % (ipv6candidatestrip) )
+                       valid = isValidIPv6(ipv6candidatestrip)
+                       if not valid:
+                               logger.log("tools: address=%s not valid" % (ipv6candidatestrip) )
+                               print line,
+       fileinput.close()
+    except:
+       logger.log("tools: could not delete the ipv6 address from the hosts file of slice=%s" % (slicename) )
+
+###################################################
+# Author: Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+# Adds an ipv6 address to the /etc/hosts file within a slice
+###################################################
+def add_ipv6addr_hosts_line(slicename, node, ipv6addr):
+    hostsFilePath = get_hosts_file_path(slicename)
+    logger.log("tools: %s" % (hostsFilePath) )
+    # debugging purposes:
+    #string = "127.0.0.1\tlocalhost\n192.168.100.179\tmyplc-node1-vm.mgmt.local\n"
+    #string = "127.0.0.1\tlocalhost\n"
+    try:
+               with open(hostsFilePath, "a") as file:
+                       # debugging purposes only:
+                       #file.write(string)
+                       file.write(ipv6addr + " " + node + "\n")
+                       file.close()
+    except:
+               logger.log("tools: could not add the IPv6 address to the hosts file of slice=%s" % (slicename) )
+
+
+
 # how to run a command in a slice
 # now this is a painful matter
 # the problem is with capsh that forces a bash command to be injected in its exec'ed command