示例#1
0
def action(fwobject):
    import os
    import libvirt
    from CloudscalerLibcloud.utils.network import Network, NetworkTool
    internalip = fwobject['host']
    networkid = fwobject['id']
    vlan = fwobject['vlan']
    netinfo = [{
        'type': 'vlan',
        'id': vlan
    }, {
        'type': 'vxlan',
        'id': networkid
    }]

    def protect_interfaces(network, domain):
        for publicip in fwobject['pubips']:
            network.protect_external(domain, publicip)
        network.protect_gwmgmt(domain, internalip)

    network = Network()
    con = network.libvirtutil.connection
    try:
        networkidHex = '%04x' % int(networkid)
        name = 'routeros_%s' % networkidHex
        try:
            domain = con.lookupByName(name)
            if domain.state()[0] == libvirt.VIR_DOMAIN_RUNNING:
                return True
            else:
                with NetworkTool(netinfo, network.libvirtutil):
                    domain.create()
                    protect_interfaces(network, domain)
                    return True
        except:
            bridgename = j.system.ovsnetconfig.getVlanBridge(vlan)
            import jinja2
            networkidHex = '%04x' % int(networkid)
            imagedir = j.system.fs.joinPaths(j.dirs.baseDir,
                                             'apps/routeros/template/')
            xmltemplate = jinja2.Template(
                j.system.fs.fileGetContents(
                    j.system.fs.joinPaths(imagedir, 'routeros-template.xml')))

            destination = '/var/lib/libvirt/images/routeros/%s' % networkidHex
            destinationfile = os.path.join(destination, 'routeros.qcow2')
            xmlsource = xmltemplate.render(networkid=networkidHex,
                                           destinationfile=destinationfile,
                                           publicbridge=bridgename)

            with NetworkTool(netinfo, network.libvirtutil):
                dom = con.defineXML(xmlsource)
                dom.create()
            protect_interfaces(network, dom)
            return True
    finally:
        network.close()
    return True
示例#2
0
def action(xml, machineid, ipcidr=None, vlan=None):
    import libvirt
    from CloudscalerLibcloud.utils.libvirtutil import LibvirtUtil
    from CloudscalerLibcloud.utils.network import Network, NetworkTool
    connection = LibvirtUtil()
    netinfo = []
    if vlan:
        netinfo.append({'id': vlan, 'type': vlan})
    try:
        with NetworkTool(netinfo, connection):
            domain = connection.get_domain_obj(machineid)
            if domain is None:
                return
            flags = 0
            if domain.state()[0] in (libvirt.VIR_DOMAIN_RUNNING,
                                     libvirt.VIR_DOMAIN_PAUSED):
                flags |= libvirt.VIR_DOMAIN_DEVICE_MODIFY_LIVE
            if domain.isPersistent():
                flags |= libvirt.VIR_DOMAIN_DEVICE_MODIFY_CONFIG
            if flags != 0:
                try:
                    domain.attachDeviceFlags(xml, flags)
                except libvirt.libvirtError as e:
                    if e.get_error_code(
                    ) == libvirt.VIR_ERR_CONFIG_UNSUPPORTED:
                        return False
                    raise

            if ipcidr:
                network = Network(connection)
                network.protect_external(domain, ipcidr)
            return domain.XMLDesc()
    finally:
        connection.close()
示例#3
0
def action(vm_id, sourceurl, domainxml, force, vmlog_dir, netinfo):
    import libvirt
    from xml.etree import ElementTree
    from urlparse import urlparse
    from CloudscalerLibcloud.utils.network import NetworkTool
    j.system.fs.createDir(vmlog_dir)
    try:
        source_con = libvirt.open(sourceurl)
    except:
        # source machine is not available
        source_con = None

    with NetworkTool(netinfo):
        if source_con:
            parsedsourceurl = urlparse(sourceurl)
            localip = j.system.net.getReachableIpAddress(
                parsedsourceurl.hostname, 22)
            target_con = libvirt.open(
                sourceurl.replace(parsedsourceurl.hostname, localip))  # local
            targeturl = "tcp://{}".format(localip)
            try:
                domain = source_con.lookupByUUIDString(vm_id)
            except libvirt.libvirtError as e:
                if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
                    return -1  # nothing to do domain is not running
                raise

            if domain.state()[0] in (libvirt.VIR_DOMAIN_RUNNING,
                                     libvirt.VIR_DOMAIN_PAUSED):
                srcdom = ElementTree.fromstring(
                    domain.XMLDesc(libvirt.VIR_DOMAIN_XML_MIGRATABLE))
                seclabel = srcdom.find('seclabel')
                if seclabel is not None:
                    srcdom.remove(seclabel)
                flags = libvirt.VIR_MIGRATE_LIVE | libvirt.VIR_MIGRATE_UNDEFINE_SOURCE | \
                        libvirt.VIR_MIGRATE_PEER2PEER
                try:
                    domain.migrate2(target_con,
                                    flags=flags,
                                    dxml=ElementTree.tostring(srcdom),
                                    uri=targeturl)
                    return 0
                except:
                    if force:
                        try:
                            domain.destroy()
                        except Exception as e:
                            j.errorconditionhandler.processPythonExceptionObject(
                                e)
                        target_con.createXML(domainxml)
                    else:
                        raise

            else:
                domain.undefine()
                target_con.createXML(domainxml)
        else:
            target_con = libvirt.open()  # local
            target_con.createXML(domainxml)
    return 1
示例#4
0
def action(machinexml, vmlog_dir, netinfo):
    from CloudscalerLibcloud.utils.network import NetworkTool
    j.system.fs.createDir(vmlog_dir)
    with NetworkTool(netinfo) as net:
        if not net.connection.check_machine(machinexml):
            return -1
        return net.connection.create_machine(machinexml)
示例#5
0
def action(machineid, xml, netinfo):
    from CloudscalerLibcloud.utils.network import NetworkTool

    with NetworkTool(netinfo) as net:
        return net.connection.reboot(machineid, xml)
示例#6
0
def action(networkid, publicip, publicgwip, publiccidr, password, vlan, privatenetwork):
    from CloudscalerLibcloud.utils import libvirtutil
    from CloudscalerLibcloud.utils.network import Network, NetworkTool
    import pexpect
    import netaddr
    import jinja2
    import time
    import os

    hrd = j.atyourservice.get(name='vfwnode', instance='main').hrd
    netrange = hrd.get("instance.vfw.netrange.internal")
    defaultpasswd = hrd.get("instance.vfw.admin.passwd")
    username = hrd.get("instance.vfw.admin.login")
    newpassword = hrd.get("instance.vfw.admin.newpasswd")
    destinationfile = None

    data = {'nid': j.application.whoAmI.nid,
            'gid': j.application.whoAmI.gid,
            'username': username,
            'password': newpassword
            }


    networkidHex = '%04x' % int(networkid)
    internalip = str(netaddr.IPAddress(netaddr.IPNetwork(netrange).first + int(networkid)))
    privatenet = netaddr.IPNetwork(privatenetwork)
    name = 'routeros_%s' % networkidHex

    j.clients.redisworker.execFunction(cleanup, _queue='hypervisor', name=name,
                                       networkid=networkid)
    print 'Testing network'
    if not j.system.net.tcpPortConnectionTest(internalip, 22, 1):
        print "OK no other router found."
    else:
        raise RuntimeError("IP conflict there is router with %s" % internalip)

    connection = libvirtutil.LibvirtUtil()
    network = Network(connection)
    netinfo = [{'type': 'vlan', 'id': vlan}, {'type': 'vxlan', 'id': networkid}]
    try:
        templatepath = '/var/lib/libvirt/images/routeros/template/routeros.qcow2'
        destination = '/var/lib/libvirt/images/routeros/%s/' % networkidHex
        destinationfile = os.path.join(destination, 'routeros.qcow2')
        print 'Creating image snapshot %s -> %s' % (templatepath, destination)
        if j.system.fs.exists(destinationfile):
            raise RuntimeError("Path %s already exists" % destination)
        j.system.fs.createDir(destination)
        j.system.fs.copyFile(templatepath, destinationfile)

        imagedir = j.system.fs.joinPaths(j.dirs.baseDir, 'apps/routeros/template/')
        xmltemplate = jinja2.Template(j.system.fs.fileGetContents(j.system.fs.joinPaths(imagedir, 'routeros-template.xml')))

        with NetworkTool(netinfo, connection):
            # setup network vxlan
            print('Creating network')
            bridgename = j.system.ovsnetconfig.getVlanBridge(vlan)
            xmlsource = xmltemplate.render(networkid=networkidHex, destinationfile=destinationfile, publicbridge=bridgename)

            print 'Starting VM'
            try:
                domuuid = j.clients.redisworker.execFunction(createVM, _queue='hypervisor', xml=xmlsource, _timeout=180)
            except Exception, e:
                raise RuntimeError("Could not create VFW vm from template, network id:%s:%s\n%s" % (networkid, networkidHex, e))
        print 'Protect network'
        domain = connection.get_domain_obj(domuuid)
        network.protect_external(domain, publicip)
        network.protect_gwmgmt(domain, internalip)

        data['internalip'] = internalip
        run = pexpect.spawn("virsh console %s" % name, timeout=300)
        try:
            print "Waiting to attach to console"
            run.expect("Connected to domain", timeout=10)
            run.sendline()  # first enter to clear welcome message of kvm console
            print 'Waiting for Login'
            run.expect("Login:"******"Password:"******"\] >", timeout=120)  # wait for primpt
            run.send("/ip addr add address=%s/22 interface=ether3\r\n" % internalip)
            print 'waiting for end of command'
            run.expect("\] >", timeout=10)  # wait for primpt
            run.send("/quit\r\n")
            run.expect("Login:"******"Could not set internal ip on VFW, network id:%s:%s\n%s" % (networkid, networkidHex, e))
示例#7
0
def action(networkid, sourceip, vlan, externalip):
    from CloudscalerLibcloud.utils.network import Network, NetworkTool
    import libvirt
    import netaddr
    from xml.etree import ElementTree
    import re
    target_con = libvirt.open()
    try:
        source_con = libvirt.open('qemu+ssh://%s/system' % sourceip)
    except:
        source_con = None
    network = Network()
    hrd = j.atyourservice.get(name='vfwnode', instance='main').hrd
    netrange = hrd.get("instance.vfw.netrange.internal")
    internalip = str(
        netaddr.IPAddress(netaddr.IPNetwork(netrange).first + int(networkid)))

    netinfo = [{
        'type': 'vlan',
        'id': vlan
    }, {
        'type': 'vxlan',
        'id': networkid
    }]
    extbridge = j.system.ovsnetconfig.getVlanBridge(vlan)
    name = 'routeros_%04x' % networkid

    with NetworkTool(netinfo):
        if source_con:
            templatepath = '/var/lib/libvirt/images/routeros/template/routeros.qcow2'
            destination = '/var/lib/libvirt/images/routeros/{0:04x}'.format(
                networkid)
            destinationfile = j.system.fs.joinPaths(destination,
                                                    'routeros.qcow2')
            try:
                domain = source_con.lookupByName(name)
            except libvirt.libvirtError:
                domain = None
            if domain:
                if domain.state()[0] == libvirt.VIR_DOMAIN_RUNNING:
                    localip = j.system.net.getReachableIpAddress(sourceip, 22)
                    targeturl = "tcp://{}".format(localip)
                    if not j.system.fs.exists(destination):
                        j.system.fs.createDir(destination)
                    if not j.system.fs.exists(destinationfile):
                        j.system.fs.copyFile(templatepath, destinationfile)
                    xmldom = ElementTree.fromstring(domain.XMLDesc())
                    seclabel = xmldom.find('seclabel')
                    if seclabel is not None:
                        xmldom.remove(seclabel)
                    xml = ElementTree.tostring(xmldom)
                    xml = re.sub(r"bridge='(public|ext-\w+)'",
                                 r"bridge='{}'".format(extbridge), xml)
                    flags = libvirt.VIR_MIGRATE_LIVE | libvirt.VIR_MIGRATE_PERSIST_DEST | libvirt.VIR_MIGRATE_UNDEFINE_SOURCE | libvirt.VIR_MIGRATE_NON_SHARED_DISK
                    try:
                        domain.migrate2(target_con,
                                        flags=flags,
                                        dxml=xml,
                                        uri=targeturl)
                    except Exception as e:
                        try:
                            target_domain = target_con.lookupByName(name)
                            target_domain.undefine()
                        except:
                            pass  # vm wasn't created on target
                        raise e
                    domain = target_con.lookupByName(name)
                    network.protect_external(domain, externalip)
                    network.protect_gwmgmt(domain, internalip)
                    return domain.XMLDesc()
                else:
                    domain.undefine()
                    return False
            else:
                return False
        else:
            # source is not available caller should probable do a restore from scratch
            return False