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
%{_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
--- /dev/null
+# -*- 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!")
--- /dev/null
+"""
+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!")
'plugins.syndicate',
'plugins.vsys',
'plugins.vsys_privs',
+ 'plugins.ipv6',
+ 'plugins.update_ipv6addr_slivertag',
# lxc
'sliver_libvirt',
'sliver_lxc',
# 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
# # 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]
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")
# 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
# 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
+# -*- python-indent: 4 -*-
+
"""A few things that didn't seem to fit anywhere else."""
import os, os.path
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:
####################
# 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
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):
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:
if chmod: os.chmod(target,chmod)
return True
-
####################
# utilities functions to get (cached) information from the node
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
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.
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
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:
_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
# 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()