Merge branch 'ipv6'
authorThierry Parmentelat <thierry.parmentelat@inria.fr>
Thu, 30 Oct 2014 08:58:39 +0000 (09:58 +0100)
committerThierry Parmentelat <thierry.parmentelat@inria.fr>
Thu, 30 Oct 2014 08:59:18 +0000 (09:59 +0100)
only one minor conflict found in a comment in Makefile

Makefile
nodemanager.spec
plugins/ipv6.py [new file with mode: 0644]
plugins/update_ipv6addr_slivertag.py [new file with mode: 0644]
setup.py
sliver_lxc.py
tools.py

index 824138e..5221fa8 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -135,7 +135,7 @@ NODEURL:=root@$(NODE):/
 endif
 
 # this is for lxc only, we need to exclude the vs stuff that otherwise messes up everything on node
-# xxx keep this in sync with setup.spec
+# WARNING: keep this in sync with setup.spec
 LXC_EXCLUDES= --exclude sliver_vs.py --exclude coresched_vs.py --exclude drl.py
 
 # run with make SYNC_RESTART=false if you want to skip restarting nm
index 19b2621..f43c98a 100644 (file)
@@ -175,6 +175,8 @@ rm -rf $RPM_BUILD_ROOT
 %{_datadir}/NodeManager/plugins/syndicate.*
 %{_datadir}/NodeManager/plugins/vsys.*
 %{_datadir}/NodeManager/plugins/vsys_privs.*
+%{_datadir}/NodeManager/plugins/ipv6.*
+%{_datadir}/NodeManager/plugins/update_ipv6addr_slivertag.*
 %{_datadir}/NodeManager/sliver-initscripts/
 %{_datadir}/NodeManager/sliver-systemd/
 %{_bindir}/forward_api_calls
diff --git a/plugins/ipv6.py b/plugins/ipv6.py
new file mode 100644 (file)
index 0000000..c97f2ff
--- /dev/null
@@ -0,0 +1,298 @@
+# -*- python-indent: 4 -*-
+
+"""
+Description: IPv6 Support and Management to Slices
+ipv6 nodemanager plugin
+Version: 0.7
+Author: Guilherme Sperb Machado <gsm@machados.org>
+
+Requirements:
+* The 'sliversipv6prefix' tag must have this format:
+  ipv6_address/prefix -- e.g., 2002:1000::1/64
+* The prefix specified on 'sliversipv6prefix' tag must be at least 64
+  It should vary between 1 and 64, since it is the minimum amount of bits to
+  have native IPv6 auto-configuration.
+* The ipv6_address in 'sliversipv6prefix' tag value can be any valid IPv6 address.
+  E.g., 2002:1000:: or 2002:1000::1
+* It is the node manager/admin responsibility to properly set the IPv6 routing,
+  since slivers should receive/send any kind of traffic.
+"""
+
+import logger
+import os
+import socket
+import re
+
+import tools
+import uuid
+from xml.dom.minidom import parseString
+
+# TODO: is there anything better to do if the "libvirt", "sliver_libvirt",
+# and are not in place in the VS distro?
+try:
+    import libvirt
+    from sliver_libvirt import Sliver_Libvirt
+except:
+    logger.log("Could not import 'sliver_lxc' or 'libvirt'.")
+
+priority=4
+
+radvd_conf_file = '/etc/radvd.conf'
+sliversipv6prefixtag = 'sliversipv6prefix'
+
+def start():
+    logger.log("ipv6: plugin starting up...")
+
+def build_libvirt_default_net_config(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 check_for_ipv6(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: IPv6 address/prefix already set for slivers! %s/%s" % \
+                           (ip.getAttribute('address'), ip.getAttribute('prefix')) )
+                hasIPv6 = True
+    return hasIPv6
+
+
+def add_ipv6(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 change_ipv6(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 remove_ipv6(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 check_if_ipv6_is_different(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: IPv6 address or prefix are different. Change detected!")
+                return True
+    return False
+
+
+def set_autostart(network):
+    try:
+        network.setAutostart(1)
+    except:
+        logger.log("ipv6: network could not set to autostart")
+
+
+def set_up(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)
+    set_autostart(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 %(ipv6addr)s/%(prefix)s
+        {
+                AdvOnLink on;
+                AdvAutonomous on;
+                AdvRouterAddr off;
+        };
+
+};
+""" % locals()
+    with open(radvd_conf_file,'w') as f:
+        f.write(configRadvd)
+    kill_radvd()
+    start_radvd()
+    logger.log("ipv6: set up process finalized -- enabled IPv6 address to the slivers!")
+
+def clean_up(networkLibvirt, connLibvirt, networkElem):
+    dom = remove_ipv6(networkElem)
+    newXml = dom.toxml()
+    networkLibvirt.undefine()
+    networkLibvirt.destroy()
+    # TODO: set autostart for the network
+    connLibvirt.networkCreateXML(newXml)
+    networkDefault = connLibvirt.networkDefineXML(newXml)
+    set_autostart(networkDefault)
+    kill_radvd()
+    logger.log("ipv6: cleanup process finalized. The IPv6 support on the slivers was removed.")
+
+def kill_radvd():
+    command_kill_radvd = ['killall', 'radvd']
+    logger.log_call(command_kill_radvd, timeout=15*60)
+
+def start_radvd():
+    commandRadvd = ['radvd']
+    logger.log_call(commandRadvd, timeout=15*60)
+
+def GetSlivers(data, config, plc):
+
+    type = 'sliver.LXC'
+    virt=tools.get_node_virt()
+    if virt!='lxc':
+        return
+
+    interfaces = data['interfaces']
+    logger.log(repr(interfaces))
+    for interface in interfaces:
+        logger.log('ipv6: get interface: %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]})
+            is_slivers_ipv6_prefix_set = False
+            for setting in settings:
+                if setting['tagname']==sliversipv6prefixtag:
+                    ipv6addrprefix = setting['value'].split('/', 1)
+                    ipv6addr = ipv6addrprefix[0]
+                    valid_prefix = False
+                    logger.log("ipv6: len(ipv6addrprefix)=%s" % (len(ipv6addrprefix)) )
+                    if len(ipv6addrprefix)>1:
+                        prefix = ipv6addrprefix[1]
+                        logger.log("ipv6: prefix=%s" % (prefix) )
+                        if int(prefix)>0 and int(prefix)<=64:
+                            valid_prefix = True
+                        else:
+                            valid_prefix = False
+                    else:
+                        valid_prefix = False
+                    logger.log("ipv6: '%s'=%s" % (sliversipv6prefixtag,ipv6addr) )
+                    valid_ipv6 = tools.is_valid_ipv6(ipv6addr)
+                    if not(valid_ipv6):
+                        logger.log("ipv6: the 'sliversipv6prefix' tag presented a non-valid IPv6 address!")
+                    elif not(valid_prefix):
+                            logger.log("ipv6: the '%s' tag does not present a valid prefix (e.g., '/64', '/58')!" % \
+                                       (sliversipv6prefixtag))
+                    else:
+                        # connecting to the libvirtd
+                        connLibvirt = Sliver_Libvirt.getConnection(type)
+                        list = connLibvirt.listAllNetworks()
+                        for networkLibvirt in list:
+                            xmldesc = networkLibvirt.XMLDesc()
+                            dom = parseString(xmldesc)
+                            has_ipv6 = check_for_ipv6(dom)
+                            if has_ipv6:
+                                # let's first check if the IPv6 is different or is it the same...
+                                is_different = check_if_ipv6_is_different(dom, ipv6addr, prefix)
+                                if is_different:
+                                    logger.log("ipv6: tag 'sliversipv6prefix' was modified! " +
+                                           "Updating configuration with the new one...")
+                                    network_elem = change_ipv6(dom, ipv6addr, prefix)
+                                    set_up(networkLibvirt, connLibvirt, network_elem, ipv6addr, prefix)
+                                    logger.log("ipv6: trying to reboot the slivers...")
+                                    tools.reboot_slivers()
+                            else:
+                                logger.log("ipv6: starting to redefine the virtual network...")
+                                #network_elem = buildLibvirtDefaultNetConfig(dom,ipv6addr,prefix)
+                                network_elem = add_ipv6(dom, ipv6addr, prefix)
+                                set_up(networkLibvirt, connLibvirt, network_elem, ipv6addr, prefix)
+                                logger.log("ipv6: trying to reboot the slivers...")
+                                tools.reboot_slivers()
+                        is_slivers_ipv6_prefix_set = True
+            if not(is_slivers_ipv6_prefix_set):
+                # connecting to the libvirtd
+                connLibvirt = Sliver_Libvirt.getConnection(type)
+                list = connLibvirt.listAllNetworks()
+                for networkLibvirt in list:
+                    xmldesc = networkLibvirt.XMLDesc()
+                    dom = parseString(xmldesc)
+                    if check_for_ipv6(dom):
+                        clean_up(networkLibvirt, connLibvirt, dom)
+                        logger.log("ipv6: trying to reboot the slivers...")
+                        tools.reboot_slivers()
+
+    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..ccf9490
--- /dev/null
@@ -0,0 +1,103 @@
+"""
+Description: Update the IPv6 Address sliver tag accordingly to the IPv6 address set
+update_ipv6addr_slivertag nodemanager plugin
+Version: 0.5
+Author: Guilherme Sperb Machado <gsm@machados.org>
+"""
+
+import logger
+import os
+import socket
+import re
+
+import tools
+import uuid
+from xml.dom.minidom import parseString
+
+# TODO: is there anything better to do if the "libvirt", "sliver_libvirt",
+# and are not in place in the VS distro?
+try:
+    import libvirt
+    from sliver_libvirt import Sliver_Libvirt
+except:
+    logger.log("Could not import 'sliver_lxc' or 'libvirt'.")
+
+priority=150
+
+ipv6addrtag = 'ipv6_address'
+
+def start():
+    logger.log("update_ipv6addr_slivertag: plugin starting up...")
+
+
+def get_sliver_tag_id_value(slivertags):
+    for slivertag in slivertags:
+        if slivertag['tagname']==ipv6addrtag:
+            return slivertag['slice_tag_id'], slivertag['value']
+
+def SetSliverTag(plc, data, tagname):
+
+    virt=tools.get_node_virt()
+    if virt!='lxc':
+        return
+
+    for slice in data['slivers']:
+        logger.log("update_ipv6addr_slivertag: starting with 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)))
+
+        try:
+            slivertag_id,ipv6addr = get_sliver_tag_id_value(slivertags)
+        except:
+            slivertag_id,ipv6addr = None,None
+        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
+                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']) )
+            result = tools.search_ipv6addr_hosts(slice['name'], value)
+            if result:
+                # if there's any ipv6 address, 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 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):
+                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 db3f6b4..097c5f2 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -41,6 +41,8 @@ setup(
         'plugins.syndicate',
         'plugins.vsys',
         'plugins.vsys_privs',
+        'plugins.ipv6',
+        'plugins.update_ipv6addr_slivertag', 
 # lxc
         'sliver_libvirt',
         'sliver_lxc',
index bc546ac..44194ed 100644 (file)
@@ -13,7 +13,7 @@ from string import Template
 # vsys probably should not be a plugin
 # the thing is, the right way to handle stuff would be that
 # if slivers get created by doing a,b,c
-# then they sohuld be delted by doing c,b,a
+# then they should be deleted by doing c,b,a
 # the current ordering model for vsys plugins completely fails to capture that
 from plugins.vsys import removeSliverFromVsys, startService as vsysStartService
 
@@ -122,7 +122,7 @@ class Sliver_LXC(Sliver_Libvirt, Initscript):
 #        # if /vservers/foo does not exist, it creates /vservers/foo
 #        # but if it does exist, then       it creates /vservers/foo/image !!
 #        # so we need to check the expected container rootfs does not exist yet
-#        # this hopefully could be removed in a future release 
+#        # this hopefully could be removed in a future release
 #        if os.path.exists (containerDir):
 #            logger.log("sliver_lxc: %s: WARNING cleaning up pre-existing %s"%(name,containerDir))
 #            command = ['btrfs', 'subvolume', 'delete', containerDir]
@@ -222,7 +222,7 @@ class Sliver_LXC(Sliver_Libvirt, Initscript):
                     logger.log_exc("exception while updating /etc/sudoers")
 
         # customizations for the user environment - root or slice uid
-        # we save the whole business in /etc/planetlab.profile 
+        # we save the whole business in /etc/planetlab.profile
         # and source this file for both root and the slice uid's .profile
         # prompt for slice owner, + LD_PRELOAD for transparently wrap bind
         pl_profile=os.path.join(containerDir,"etc/planetlab.profile")
@@ -258,7 +258,7 @@ unset pathmunge
             # if dir is not yet existing let's forget it for now
             if not os.path.isdir(os.path.dirname(from_root)): continue
             found=False
-            try: 
+            try:
                 contents=file(from_root).readlines()
                 for content in contents:
                     if content==enforced_line: found=True
@@ -342,7 +342,7 @@ unset pathmunge
         # Remove rootfs of destroyed domain
         command = ['btrfs', 'subvolume', 'delete', containerDir]
         logger.log_call(command, timeout=BTRFS_TIMEOUT)
-        
+
         # For some reason I am seeing this :
         #log_call: running command btrfs subvolume delete /vservers/inri_sl1
         #log_call: ERROR: cannot delete '/vservers/inri_sl1' - Device or resource busy
index 02e2ab9..e88a1b2 100644 (file)
--- a/tools.py
+++ b/tools.py
@@ -1,3 +1,5 @@
+# -*- python-indent: 4 -*-
+
 """A few things that didn't seem to fit anywhere else."""
 
 import os, os.path
@@ -69,7 +71,14 @@ def daemon():
     os.dup2(crashlog, 2)
 
 def fork_as(su, function, *args):
-    """fork(), cd / to avoid keeping unused directories open, close all nonstandard file descriptors (to avoid capturing open sockets), fork() again (to avoid zombies) and call <function> with arguments <args> in the grandchild process.  If <su> is not None, set our group and user ids appropriately in the child process."""
+    """
+fork(), cd / to avoid keeping unused directories open,
+close all nonstandard file descriptors (to avoid capturing open sockets),
+fork() again (to avoid zombies) and call <function>
+with arguments <args> in the grandchild process.
+If <su> is not None, set our group and user ids
+ appropriately in the child process.
+    """
     child_pid = os.fork()
     if child_pid == 0:
         try:
@@ -91,9 +100,11 @@ def fork_as(su, function, *args):
 ####################
 # manage files
 def pid_file():
-    """We use a pid file to ensure that only one copy of NM is running at a given time.
+    """
+We use a pid file to ensure that only one copy of NM is running at a given time.
 If successful, this function will write a pid file containing the pid of the current process.
-The return value is the pid of the other running process, or None otherwise."""
+The return value is the pid of the other running process, or None otherwise.
+    """
     other_pid = None
     if os.access(PID_FILE, os.F_OK):  # check for a pid file
         handle = open(PID_FILE)  # pid file exists, read it
@@ -110,7 +121,10 @@ The return value is the pid of the other running process, or None otherwise."""
     return other_pid
 
 def write_file(filename, do_write, **kw_args):
-    """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
+    """
+Write file <filename> atomically by opening a temporary file,
+using <do_write> to write that file, and then renaming the temporary file.
+    """
     shutil.move(write_temp_file(do_write, **kw_args), filename)
 
 def write_temp_file(do_write, mode=None, uidgid=None):
@@ -122,13 +136,16 @@ def write_temp_file(do_write, mode=None, uidgid=None):
     finally: f.close()
     return temporary_filename
 
-# replace a target file with a new contents - checks for changes
-# can handle chmod if requested
-# can also remove resulting file if contents are void, if requested
-# performs atomically:
-#    writes in a tmp file, which is then renamed (from sliverauth originally)
-# returns True if a change occurred, or the file is deleted
 def replace_file_with_string (target, new_contents, chmod=None, remove_if_empty=False):
+    """
+Replace a target file with a new contents
+checks for changes: does not do anything if previous state was already right
+can handle chmod if requested
+can also remove resulting file if contents are void, if requested
+performs atomically:
+writes in a tmp file, which is then renamed (from sliverauth originally)
+returns True if a change occurred, or the file is deleted
+    """
     try:
         current=file(target).read()
     except:
@@ -152,7 +169,6 @@ def replace_file_with_string (target, new_contents, chmod=None, remove_if_empty=
     if chmod: os.chmod(target,chmod)
     return True
 
-
 ####################
 # utilities functions to get (cached) information from the node
 
@@ -220,6 +236,11 @@ def get_sliver_process(slice_name, process_cmdline):
             path = l.split(':')[0]
             comp = l.rsplit(':')[-1]
             slice_name_check = comp.rsplit('/')[-1]
+            # the lines below were added by Guilherme <gsm@machados.org>
+            # due to the ipv6 plugin requirements (LXC)
+            virt=get_node_virt()
+            if virt=='lxc':
+                slice_name_check = slice_name_check.rsplit('.')[0]
 
             if (slice_name_check == slice_name):
                 slice_path = path
@@ -237,6 +258,27 @@ def get_sliver_process(slice_name, process_cmdline):
 
     return (cgroup_fn, pid)
 
+###################################################
+# Added by Guilherme Sperb Machado <gsm@machados.org>
+###################################################
+
+try:
+    import re
+    import socket
+    import fileinput
+except:
+    logger.log("Could not import 're', 'socket', or 'fileinput' python packages.")
+
+# 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'.")
+###################################################
+
 def get_sliver_ifconfig(slice_name, device="eth0"):
     """ return the output of "ifconfig" run from inside the sliver.
 
@@ -290,6 +332,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(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 is_valid_ipv6(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
@@ -301,9 +376,9 @@ def get_node_virt ():
     except:
         pass
     logger.log("Computing virt..")
-    try: 
+    try:
         if subprocess.call ([ 'vserver', '--help' ]) ==0: virt='vs'
-        else:                                             virt='lxc'      
+        else:                                             virt='lxc'
     except:
         virt='lxc'
     with file(virt_stamp,"w") as f:
@@ -319,6 +394,112 @@ 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_slivers():
+    type = 'sliver.LXC'
+    # connecting to the libvirtd
+    connLibvirt = Sliver_Libvirt.getConnection(type)
+    domains = connLibvirt.listAllDomains()
+    for domain in domains:
+        try:
+            domain.destroy()
+            logger.log("tools: DESTROYED %s" % (domain.name()) )
+            domain.create()
+            logger.log("tools: CREATED %s" % (domain.name()) )
+        except:
+            logger.log("tools: FAILED to reboot %s" % (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)
+    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
+# If the parameter 'ipv6addr' is None, then search
+# for any ipv6 address
+###################################################
+def search_ipv6addr_hosts(slicename, ipv6addr):
+    hostsFilePath = get_hosts_file_path(slicename)
+    found=False
+    try:
+        for line in fileinput.input(r'%s' % (hostsFilePath)):
+            if ipv6addr is not None:
+                if re.search(r'%s' % (ipv6addr), line):
+                    found=True
+            else:
+                search = re.search(r'^(.*)\s+.*$', line)
+                if search:
+                    ipv6candidate = search.group(1)
+                    ipv6candidatestrip = ipv6candidate.strip()
+                    valid = is_valid_ipv6(ipv6candidatestrip)
+                    if valid:
+                        found=True
+            fileinput.close()
+            return found
+    except:
+        logger.log("tools: FAILED to search %s in /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):
+            search = re.search(r'^(.*)\s+(%s|%s)$' % (node,'localhost'), line)
+            if search:
+                ipv6candidate = search.group(1)
+                ipv6candidatestrip = ipv6candidate.strip()
+                valid = is_valid_ipv6(ipv6candidatestrip)
+                if not valid:
+                    print line,
+        fileinput.close()
+        logger.log("tools: REMOVED IPv6 address from /etc/hosts file of slice=%s" % \
+                   (slicename) )
+    except:
+        logger.log("tools: FAILED to remove the IPv6 address from /etc/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:
+            file.write(ipv6addr + " " + node + "\n")
+            file.close()
+        logger.log("tools: ADDED IPv6 address to /etc/hosts file of slice=%s" % \
+                   (slicename) )
+    except:
+        logger.log("tools: FAILED to add the IPv6 address to /etc/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
@@ -326,7 +507,7 @@ def has_systemctl ():
 # bottom line is, what actually needs to be called is
 # vs:  vserver exec slicename command and its arguments
 # lxc: lxcsu slicename "command and its arguments"
-# which, OK, is no big deal as long as the command is simple enough, 
+# which, OK, is no big deal as long as the command is simple enough,
 # but do not stretch it with arguments that have spaces or need quoting as that will become a nightmare
 def command_in_slice (slicename, argv):
     virt=get_node_virt()