Ejemplo n.º 1
0
def main():
    if 'spiceoptions' in os.environ:
        try:
            spiceConfig = ast.literal_eval(os.environ['spiceoptions'])
            spiceConfig = dict(
                (k.lower(), v) for k, v in spiceConfig.iteritems())

            domxml = hooking.read_domxml()
            for graphDev in domxml.getElementsByTagName('graphics'):
                if graphDev.getAttribute('type') == 'spice':
                    for elmt, value in spiceConfig.items():
                        if elmt not in spiceOpts:
                            sys.stderr.write(" Invalid ELEMENT"
                                             " [%s] " % elmt)
                        else:
                            for attr, attrValue in value.items():
                                if attr not in spiceOpts[elmt]:
                                    sys.stderr.write(" Invalid ATTRIBUTE"
                                                     " [%s]" % attr)
                                elif attrValue not in spiceOpts[elmt][attr]:
                                    sys.stderr.write(" Invalid VALUE"
                                                     " [%s]" % attrValue)
                                else:
                                    returnElmt = createElement(
                                        domxml, elmt, attr, attrValue)
                                    if returnElmt:
                                        graphDev.appendChild(returnElmt)

            hooking.write_domxml(domxml)

        except:
            hooking.exit_hook('spiceoptions: [unexpected error]: %s\n' %
                              traceback.format_exc())
            sys.exit(2)
Ejemplo n.º 2
0
def main():
    if "spiceoptions" in os.environ:
        try:
            spiceConfig = ast.literal_eval(os.environ["spiceoptions"])
            spiceConfig = dict((k.lower(), v) for k, v in spiceConfig.iteritems())

            domxml = hooking.read_domxml()
            for graphDev in domxml.getElementsByTagName("graphics"):
                if graphDev.getAttribute("type") == "spice":
                    for elmt, value in spiceConfig.items():
                        if elmt not in spiceOpts:
                            sys.stderr.write(" Invalid ELEMENT" " [%s] " % elmt)
                        else:
                            for attr, attrValue in value.items():
                                if attr not in spiceOpts[elmt]:
                                    sys.stderr.write(" Invalid ATTRIBUTE" " [%s]" % attr)
                                elif attrValue not in spiceOpts[elmt][attr]:
                                    sys.stderr.write(" Invalid VALUE" " [%s]" % attrValue)
                                else:
                                    returnElmt = createElement(domxml, elmt, attr, attrValue)
                                    if returnElmt:
                                        graphDev.appendChild(returnElmt)

            hooking.write_domxml(domxml)

        except:
            hooking.exit_hook("spiceoptions: [unexpected error]: %s\n" % traceback.format_exc())
            sys.exit(2)
Ejemplo n.º 3
0
def create_https_iso_element(domxml, protocol, hostname, port, url_path):
    '''
    <disk type='network' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <source protocol="https" name="url_path">
        <host name="hostname" port="80"/>
      </source>
      <target dev='hdc' bus='ide' tray='closed'/>
      <readonly/>
      <boot order='1'/>
    </disk>
    '''

    disk = domxml.createElement('disk')
    disk.setAttribute('type', 'network')
    disk.setAttribute('device', 'cdrom')

    driver = domxml.createElement('driver')
    driver.setAttribute('name', 'qemu')
    driver.setAttribute('type', 'raw')
    disk.appendChild(driver)

    source = domxml.createElement('source')
    source.setAttribute('protocol', protocol)
    source.setAttribute('name', url_path)

    host = domxml.createElement('host')
    host.setAttribute('name', hostname)
    host.setAttribute('port', port)
    source.appendChild(host)
    disk.appendChild(source)

    readonly = domxml.createElement('readonly')
    disk.appendChild(readonly)

    # find a name for hdX
    target = domxml.createElement('target')
    target.setAttribute('bus', 'ide')
    target.setAttribute('tray', 'closed')
    xmldisks = domxml.getElementsByTagName('disk')
    disks = []
    for d in xmldisks:
        disks.append(d.getElementsByTagName('target')[0].getAttribute('dev'))
    found = False
    for i in range(0, 4):
        dname = _DISK_BY_INDEX.get(i)
        if dname and dname not in disks:
            target.setAttribute('dev', dname)
            found = True
            break
    if not found:
        hooking.exit_hook('httpsisoboot: unable to attach another ide cdrom\n')
    disk.appendChild(target)

    boot = domxml.createElement('boot')
    boot.setAttribute('order', '1')
    disk.appendChild(boot)

    return disk
Ejemplo n.º 4
0
def create_https_iso_element(domxml, protocol, hostname, port, url_path):
    '''
    <disk type='network' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <source protocol="https" name="url_path">
        <host name="hostname" port="80"/>
      </source>
      <target dev='hdc' bus='ide' tray='closed'/>
      <readonly/>
      <boot order='1'/>
    </disk>
    '''

    disk = domxml.createElement('disk')
    disk.setAttribute('type', 'network')
    disk.setAttribute('device', 'cdrom')

    driver = domxml.createElement('driver')
    driver.setAttribute('name', 'qemu')
    driver.setAttribute('type', 'raw')
    disk.appendChild(driver)

    source = domxml.createElement('source')
    source.setAttribute('protocol', protocol)
    source.setAttribute('name', url_path)

    host = domxml.createElement('host')
    host.setAttribute('name', hostname)
    host.setAttribute('port', port)
    source.appendChild(host)
    disk.appendChild(source)

    readonly = domxml.createElement('readonly')
    disk.appendChild(readonly)

    # find a name for hdX
    target = domxml.createElement('target')
    target.setAttribute('bus', 'ide')
    target.setAttribute('tray', 'closed')
    xmldisks = domxml.getElementsByTagName('disk')
    disks = []
    for d in xmldisks:
        disks.append(d.getElementsByTagName('target')[0].getAttribute('dev'))
    found = False
    for i in range(0, 4):
        dname = _DISK_BY_INDEX.get(i)
        if dname and dname not in disks:
            target.setAttribute('dev', dname)
            found = True
            break
    if not found:
        hooking.exit_hook('httpsisoboot: unable to attach another ide cdrom\n')
    disk.appendChild(target)

    boot = domxml.createElement('boot')
    boot.setAttribute('order', '1')
    disk.appendChild(boot)

    return disk
Ejemplo n.º 5
0
def create_https_iso_element(domxml, protocol, hostname, port, url_path):
    """
    <disk type='network' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <source protocol="https" name="url_path">
        <host name="hostname" port="80"/>
      </source>
      <target dev='hdc' bus='ide' tray='closed'/>
      <readonly/>
      <boot order='1'/>
    </disk>
    """

    disk = domxml.createElement("disk")
    disk.setAttribute("type", "network")
    disk.setAttribute("device", "cdrom")

    driver = domxml.createElement("driver")
    driver.setAttribute("name", "qemu")
    driver.setAttribute("type", "raw")
    disk.appendChild(driver)

    source = domxml.createElement("source")
    source.setAttribute("protocol", protocol)
    source.setAttribute("name", url_path)

    host = domxml.createElement("host")
    host.setAttribute("name", hostname)
    host.setAttribute("port", port)
    source.appendChild(host)
    disk.appendChild(source)

    readonly = domxml.createElement("readonly")
    disk.appendChild(readonly)

    # find a name for hdX
    target = domxml.createElement("target")
    target.setAttribute("bus", "ide")
    target.setAttribute("tray", "closed")
    xmldisks = domxml.getElementsByTagName("disk")
    disks = []
    for d in xmldisks:
        disks.append(d.getElementsByTagName("target")[0].getAttribute("dev"))
    found = False
    for i in range(0, 4):
        dname = _DISK_BY_INDEX.get(i)
        if dname and dname not in disks:
            target.setAttribute("dev", dname)
            found = True
            break
    if not found:
        hooking.exit_hook("httpsisoboot: unable to attach another ide cdrom\n")
    disk.appendChild(target)

    boot = domxml.createElement("boot")
    boot.setAttribute("order", "1")
    disk.appendChild(boot)

    return disk
Ejemplo n.º 6
0
def addOpenstackVnic(domxml, pluginType, portId, hasSecurityGroups):
    iface = domxml.getElementsByTagName('interface')[0]
    if pluginType == PT_BRIDGE:
        addLinuxBridgeVnic(domxml, iface, portId)
    elif pluginType == PT_OVS:
        addOvsVnic(domxml, iface, portId, hasSecurityGroups)
    else:
        hooking.exit_hook("Unknown plugin type: %s" % pluginType)
Ejemplo n.º 7
0
def disconnectVnic(portId):
    tapName = ('tap' + portId)[:DEV_MAX_LENGTH]
    command = [EXT_BRCTL, 'delif', DUMMY_BRIDGE, tapName]
    retcode, out, err = hooking.execCmd(command, sudo=True, raw=True)

    if retcode != 0:
        hooking.exit_hook("Can't disconnect %s from %s, due to: %s"
                          % (tapName, DUMMY_BRIDGE, err))
Ejemplo n.º 8
0
def addOpenstackVnic(domxml, pluginType, portId):
    iface = domxml.getElementsByTagName('interface')[0]
    if pluginType == PT_BRIDGE:
        addLinuxBridgeVnic(domxml, iface, portId)
    elif pluginType == PT_OVS:
        addOvsVnic(domxml, iface, portId)
    else:
        hooking.exit_hook("Unknown plugin type: %s" % pluginType)
Ejemplo n.º 9
0
def _get_stp(iface):
    if iface != BRIDGE_NAME:
        return "off"

    rc, out, err = execCmd([EXT_OVS_VSCTL, "get", "Bridge", BRIDGE_NAME, "stp_enable"], sudo=True)
    if rc != 0:
        hooking.exit_hook("\n".join(err))
    if out[0] == "true":
        return "on"
    else:
        return "off"
Ejemplo n.º 10
0
def _get_stp(iface):
    if iface != BRIDGE_NAME:
        return 'off'

    rc, out, err = execCmd([EXT_OVS_VSCTL, 'get', 'Bridge', BRIDGE_NAME,
                            'stp_enable'], sudo=True)
    if rc != 0:
        hooking.exit_hook('\n'.join(err))
    if out[0] == 'true':
        return 'on'
    else:
        return 'off'
Ejemplo n.º 11
0
def _get_stp(iface):
    if iface != BRIDGE_NAME:
        return 'off'

    rc, out, err = execCmd(
        [EXT_OVS_VSCTL, 'get', 'Bridge', BRIDGE_NAME, 'stp_enable'], sudo=True)
    if rc != 0:
        hooking.exit_hook('\n'.join(err))
    if out[0] == 'true':
        return 'on'
    else:
        return 'off'
Ejemplo n.º 12
0
def _reconfigure_fcoe(configured, changed_fcoe, custom_params):
    """
    Configure all fcoe interfaces and unconfigure NIC which are not longer
    fcoe enabled
    Example: Moved from one NIC to another
    """
    for net, net_nic in six.iteritems(changed_fcoe):
        if net in configured and configured[net] != net_nic:
            _unconfigure(configured[net])
        if net_nic:
            _configure(net_nic, custom_params.get(net, {}))
        else:
            hooking.exit_hook("Failed to configure fcoe "
                              "on %s with no physical nic" % (net))
Ejemplo n.º 13
0
def _reconfigure_fcoe(configured, changed_fcoe, custom_params):
    """
    Configure all fcoe interfaces and unconfigure NIC which are not longer
    fcoe enabled
    Example: Moved from one NIC to another
    """
    for net, net_nic in six.iteritems(changed_fcoe):
        if net in configured and configured[net] != net_nic:
            _unconfigure(configured[net])
        if net_nic:
            _configure(net_nic, custom_params.get(net, {}))
        else:
            hooking.exit_hook("Failed to configure fcoe "
                              "on %s with no physical nic" % (net))
Ejemplo n.º 14
0
def _get_active_slave(bonding):
    """ Get OVS bond's active slave if there is any. Match:
    slave iface_name: enabled
        active slave

    TODO: since openvswitch 2.3.1, active slave is also listed in header of
    command output.
    """
    rc, out, err = execCmd([EXT_OVS_APPCTL, "bond/show", bonding], sudo=True)
    if rc != 0:
        hooking.exit_hook("\n".join(err))
    active_slave_regex = re.compile("\nslave (.*):.*\n.*active slave\n")
    active_slaves = active_slave_regex.findall("\n".join(out))
    active_slave = active_slaves[0] if len(active_slaves) > 0 else ""
    return active_slave
Ejemplo n.º 15
0
def _get_active_slave(bonding):
    """ Get OVS bond's active slave if there is any. Match:
    slave iface_name: enabled
        active slave

    TODO: since openvswitch 2.3.1, active slave is also listed in header of
    command output.
    """
    rc, out, err = execCmd([EXT_OVS_APPCTL, 'bond/show', bonding], sudo=True)
    if rc != 0:
        hooking.exit_hook('\n'.join(err))
    active_slave_regex = re.compile('\nslave (.*):.*\n.*active slave\n')
    active_slaves = active_slave_regex.findall('\n'.join(out))
    active_slave = active_slaves[0] if len(active_slaves) > 0 else ''
    return active_slave
Ejemplo n.º 16
0
def ovs_device(domxml):
    """ Modify interface XML in Libvirt to proper OVS configuration if OVS
    network is set as a source.
    """
    running_config = RunningConfig()

    iface = domxml.getElementsByTagName('interface')[0]
    source = iface.getElementsByTagName('source')[0]
    source_bridge = source.getAttribute('bridge')

    network = running_config.networks.get(source_bridge)
    if network is None:
        hooking.exit_hook('Network %s does not exist' % source_bridge)

    if is_ovs_network(network):
        virtualport = domxml.createElement('virtualport')
        virtualport.setAttribute('type', 'openvswitch')
        iface.appendChild(virtualport)
        if network.get('vlan') is None:
            source.setAttribute('bridge', BRIDGE_NAME)
Ejemplo n.º 17
0
def ovs_device(domxml):
    """ Modify interface XML in Libvirt to proper OVS configuration if OVS
    network is set as a source.
    """
    running_config = RunningConfig()

    iface = domxml.getElementsByTagName('interface')[0]
    source = iface.getElementsByTagName('source')[0]
    source_bridge = source.getAttribute('bridge')

    network = running_config.networks.get(source_bridge)
    if network is None:
        hooking.exit_hook('Network %s does not exist' % source_bridge)

    if is_ovs_network(network):
        virtualport = domxml.createElement('virtualport')
        virtualport.setAttribute('type', 'openvswitch')
        iface.appendChild(virtualport)
        if network.get('vlan') is None:
            source.setAttribute('bridge', BRIDGE_NAME)
Ejemplo n.º 18
0
def validate_URL(url):
    parsed = urlparse.urlsplit(url)
    protocol = parsed.scheme
    if protocol != 'https':
        hooking.exit_hook(
            (
                "httpsisoboot: '{protocol}' is not supported, "
                "please use https\n"
            ).format(protocol=protocol)
        )

    hostname = parsed.netloc.split(':')[0]
    if not hostname:
        hooking.exit_hook(
            (
                "httpsisoboot: invalid hostname in the URL '{url}'\n"
            ).format(url=url)
        )

    port = 443  # https only
    if parsed.port is not None:
        port = parsed.port
    if not port >= 1 and port <= 65535:
        hooking.exit_hook(
            (
                "httpsisoboot: invalid port in the URL '{url}'\n"
            ).format(url=url)
        )
    port_s = str(port)

    url_path = parsed.path
    if parsed.query:
        url_path += '?' + parsed.query

    return protocol, hostname, port_s, url_path
Ejemplo n.º 19
0
def validate_URL(url):
    parsed = urlparse.urlsplit(url)
    protocol = parsed.scheme
    if protocol != 'https':
        hooking.exit_hook(("httpsisoboot: '{protocol}' is not supported, "
                           "please use https\n").format(protocol=protocol))

    hostname = parsed.netloc.split(':')[0]
    if not hostname:
        hooking.exit_hook(
            ("httpsisoboot: invalid hostname in the URL '{url}'\n").format(
                url=url))

    port = 443  # https only
    if parsed.port is not None:
        port = parsed.port
    if not port >= 1 and port <= 65535:
        hooking.exit_hook(
            ("httpsisoboot: invalid port in the URL '{url}'\n").format(
                url=url))
    port_s = str(port)

    url_path = parsed.path
    if parsed.query:
        url_path += '?' + parsed.query

    return protocol, hostname, port_s, url_path
Ejemplo n.º 20
0
import hooking

import ovs_utils

log = partial(ovs_utils.log, tag='ovs_after_network_setup_fail: ')


def main():
    setup_nets_config = hooking.read_json()

    in_rollback = setup_nets_config['request']['options'].get('_inRollback')

    if in_rollback:
        log('Configuration failed with _inRollback=True.')
    else:
        log('Configuration failed. At this point, non-OVS rollback should be '
            'done. Executing OVS rollback.')
        supervdsm.getProxy().setupNetworks({}, {}, {
            'connectivityCheck': False,
            '_inRollback': True,
            '_inOVSRollback': True
        })


if __name__ == '__main__':
    try:
        main()
    except:
        hooking.exit_hook(traceback.format_exc())
Ejemplo n.º 21
0
        <boot order="1"/>
    </interface>
    """).getElementsByTagName('interface')[0]

    print("Interface before removing filter: %s" %
          interface.toxml(encoding='UTF-8'))

    allocate_random_network(interface)
    print("Interface after removing filter: %s" %
          interface.toxml(encoding='UTF-8'))


def main():
    device_xml = hooking.read_domxml()
    allocate_random_network(device_xml)
    hooking.write_domxml(device_xml)


if __name__ == '__main__':
    if HELP_ARG in sys.argv:
        hooking.exit_hook(HELP_TEXT)

    try:
        if TEST_ARG in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('vm net allocation hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 22
0
def _parse_into_subcommands(tokens):
    current = []
    for token in tokens:
        if token.startswith('-') and current:
            yield Subcommand(current[0], current[1], current[2:])
            current = []
        current.append(token)
    if current:
        yield Subcommand(current[0], current[1], current[2:])


def _set_ethtool_opts(network, options):
    """Takes an iterable of the tokenized ethtool command line arguments and
    applies them to the network devices"""
    command = [ETHTOOL_BINARY.cmd] + options
    rc, _, err = hooking.execCmd(command)
    if rc != 0:
        raise EthtoolError('Failed to set ethtool opts (%s) for network %s. '
                           'Err: %s' % (' '.join(options), network, err))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('ethtool_options hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
from vdsm import supervdsm

import hooking

import ovs_utils

log = partial(ovs_utils.log, tag='ovs_after_network_setup_fail: ')


def main():
    setup_nets_config = hooking.read_json()

    in_rollback = setup_nets_config['request']['options'].get('_inRollback')

    if in_rollback:
        log('Configuration failed with _inRollback=True.')
    else:
        log('Configuration failed. At this point, non-OVS rollback should be '
            'done. Executing OVS rollback.')
        supervdsm.getProxy().setupNetworks(
            {}, {}, {'connectivityCheck': False, '_inRollback': True,
                     '_inOVSRollback': True})


if __name__ == '__main__':
    try:
        main()
    except:
        hooking.exit_hook(traceback.format_exc())
Ejemplo n.º 24
0
def _list_ports(bridge):
    rc, out, err = execCmd([EXT_OVS_VSCTL, 'list-ports', bridge], sudo=True)
    if rc != 0:
        hooking.exit_hook('\n'.join(err))
    return out
Ejemplo n.º 25
0
        top_dev = _top_dev(network, attrs)
        for cmd in _generate_commands(options, top_dev):
            hooking.execCmd(cmd, sudo=True)


def _generate_commands(options, top_level_device):
    for addr in options.split(','):
        yield [ipwrapper._IP_BINARY.cmd, '-4', 'addr', 'add', 'dev',
               top_level_device, addr.strip()]


def _top_dev(network, attrs):
    if hooking.tobool(attrs.get('bridged')):
        return network
    # bridgeless
    nics, vlan, _, bonding = netinfo.cache.NetInfo(
        netswitch.configurator.netinfo()).getNicsVlanAndBondingForNetwork(
            network)
    return vlan or bonding or nics[0]


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('extra ipv4 addrs hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 26
0
#!/usr/bin/python

import hooking
import os
import sys
sys.path.append("/usr/libexec/vdsm/hooks/vifdriver")
import vif_driver_hooking

reply = vif_driver_hooking.after_vm_start(os.environ, hooking.read_domxml())
if reply:
    hooking.write_domxml(reply)
hooking.exit_hook("", return_code=0)
Ejemplo n.º 27
0
        openstack_binding_host_ids[openstacknet_utils.PT_OVS] = \
            openstack_binding_host_id
        openstack_binding_host_ids[openstacknet_utils.PT_OPENSTACK_OVN] = \
            openstack_binding_host_id
        caps[CAPS_BINDING_KEY] = openstack_binding_host_ids
    return caps


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'ht', ['help', 'test'])
    except getopt.GetoptError as err:
        print(str(err))
        _usage()
        sys.exit(1)

    for option, _ in opts:
        if option in ('-h', '--help'):
            _usage()
            sys.exit()
        elif option in ('-t', '--test'):
            _test()
            sys.exit()

    if not _is_ovs_service_running():
        hooking.exit_hook('OVS is not running', return_code=0)

    caps = hooking.read_json()
    caps = _update_openstack_binding_host_ids(caps)
    hooking.write_json(caps)
Ejemplo n.º 28
0
<source dev="/rhev/data-center/mnt/blockSD/
b4cf7d74-6a07-4138-9d4f-80b14c3acefd/images/
1580607a-b240-4199-99ac-3d2162934ba6/e5ba276f-dcba-4582-b13f-c165afa2f575"/>
<target bus="ide" dev="hda"/>
<serial>1580607a-b240-4199-99ac-3d2162934ba6</serial>
<driver cache="none" error_policy="stop" io="native"
name="qemu" type="raw"/>
</disk>'''

    xmldom = minidom.parseString(text)

    disk = xmldom.getElementsByTagName('disk')[0]
    print("\nDisk device definition before execution: \n%s"
          % disk.toxml(encoding='UTF-8'))

    addDiscardUnmap(xmldom)

    print("\nDisk device after setting discard attribute: \n%s"
          % disk.toxml(encoding='UTF-8'))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook(' diskunmap hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 29
0
    """
    url = "https://server.example.com:8080/path/to/disk.iso"
    domxml = minidom.parseString(text)
    devices = domxml.getElementsByTagName("devices")[0]
    print("\n Devices definition before increase_devices_boot_order \n %s" % pretty_print(devices))
    increase_devices_boot_order(devices)
    print("\n Devices definition after increase_devices_boot_order \n %s" % pretty_print(devices))
    protocol, hostname, port_s, url_path = validate_URL(url)
    print(
        (
            "\n Validated URL \n"
            " protocol: '{protocol}'\n"
            " hostname: '{hostname}'\n"
            " port: '{port_s}'\n"
            " path: '{url_path}'\n"
        ).format(protocol=protocol, hostname=hostname, port_s=port_s, url_path=url_path)
    )
    diskdev = create_https_iso_element(domxml, protocol, hostname, port_s, url_path)
    devices.appendChild(diskdev)
    print("\n Devices definition after setting httpsIsoElement \n %s" % pretty_print(devices))


if __name__ == "__main__":
    try:
        if "--test" in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook("httpsisoboot: [unexpected error]: %s\n" % traceback.format_exc())
Ejemplo n.º 30
0
    increase_devices_boot_order(devices)
    print("\n Devices definition after increase_devices_boot_order \n %s" %
          pretty_print(devices))
    protocol, hostname, port_s, url_path = validate_URL(url)
    print(("\n Validated URL \n"
           " protocol: '{protocol}'\n"
           " hostname: '{hostname}'\n"
           " port: '{port_s}'\n"
           " path: '{url_path}'\n").format(
               protocol=protocol,
               hostname=hostname,
               port_s=port_s,
               url_path=url_path,
           ))
    diskdev = create_https_iso_element(domxml, protocol, hostname, port_s,
                                       url_path)
    devices.appendChild(diskdev)
    print("\n Devices definition after setting httpsIsoElement \n %s" %
          pretty_print(devices))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('httpsisoboot: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 31
0
        hooking.write_domxml(domxml)


def test():
    text = """<interface type="bridge">
<address bus="0x00" domain="0x0000" function="0x0" slot="0x03" type="pci"/>
<mac address="00:1a:4a:60:d1:9a"/>
<model type="virtio"/>
<filterref filter="vdsm-no-mac-spoofing"/>
<link state="up"/>
<source bridge="ovirtmgmt"/>
</interface>"""

    domxml = xml.dom.minidom.parseString(text)

    print("Interface before forcing device: %s" % domxml.toxml(encoding="UTF-8"))

    replaceSourceBridge(domxml, {"00:1a:4a:60:d1:9a": "br0"}, "bridge")

    print("Interface after forcing device: %s" % domxml.toxml(encoding="UTF-8"))


if __name__ == "__main__":
    try:
        if "--test" in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook(" macbind hook: [unexpected error]: %s\n" % traceback.format_exc())
Ejemplo n.º 32
0
def test():
    text = '''<interface type="bridge">
<address bus="0x00" domain="0x0000" function="0x0" slot="0x03" type="pci"/>
<mac address="00:1a:4a:60:d1:9a"/>
<model type="virtio"/>
<filterref filter="vdsm-no-mac-spoofing"/>
<link state="up"/>
<source bridge="ovirtmgmt"/>
</interface>'''

    domxml = xml.dom.minidom.parseString(text)

    print("Interface before forcing device: %s" %
          domxml.toxml(encoding='UTF-8'))

    replaceSourceBridge(domxml, {'00:1a:4a:60:d1:9a': 'br0'}, "bridge")

    print("Interface after forcing device: %s" %
          domxml.toxml(encoding='UTF-8'))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook(' macbind hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 33
0
Archivo: ipv6.py Proyecto: Caez83/vdsm
#
import hooking
import traceback


def main():
    """Forward IPv6 configuration from the network 'custom' properties
       to VDSM API."""
    setup_nets_config = hooking.read_json()
    for network, attrs in setup_nets_config['request']['networks'].items():
        if 'remove' in attrs:
            continue
        elif 'custom' in attrs:
            _process_network(attrs)
    hooking.write_json(setup_nets_config)


def _process_network(attrs):
    for property_name in ('ipv6addr', 'ipv6gateway', 'ipv6autoconf', 'dhcpv6'):
        value = attrs['custom'].get(property_name)
        if value is not None:
            attrs[property_name] = value


if __name__ == '__main__':
    try:
        main()
    except:
        hooking.exit_hook('ipv6 hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 34
0
      <driver name='vfio'/>
      <source>
        <address domain='0x0000' bus='0x04' slot='0x10' function='0x2'/>
      </source>
      <alias name='igbxe'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x08' function='0x0' multifunction='on'/>
</hostdev>
"""

def main():
    #newnet = os.environ.get('extnet')
    doc = hooking.read_domxml()
    uuid = doc.getElementsByTagName('uuid')[0]
    UUID = uuid.childNodes[0].nodeValue
    if UUID == "f60cba97-e09f-4515-bdef-a7af3d93e6e5":
        pass
    else:
        return 0
    devices_dom = doc.getElementsByTagName("devices")[0]
    ext_dom = minidom.parseString(ext_string)
    ext_elements = ext_dom.getElementsByTagName("hostdev")[0]
    devices_dom.appendChild(ext_elements)
    hooking.write_domxml(doc)

if __name__ == '__main__':
    try:
        main()
    except:
        hooking.exit_hook('ext_xml hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 35
0

def _migration_script():
    """Return true if this script runs as a migration destination script"""
    dirname = os.path.split(
        os.path.dirname(os.path.abspath(__file__)))[1]
    return dirname == 'before_device_migrate_destination'


def main():
    portProfile = os.environ.get('vmfex')
    if portProfile is not None:
        handleDirectPool(libvirtconnection.get())
        if not _migration_script():
            doc = hooking.read_domxml()
            interface, = doc.getElementsByTagName('interface')
            attachProfileToInterfaceXml(interface, portProfile)
            removeFilter(interface)
            hooking.write_domxml(doc)


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('vmfex_dev hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 36
0
<source dev="/rhev/data-center/mnt/blockSD/
b4cf7d74-6a07-4138-9d4f-80b14c3acefd/images/
1580607a-b240-4199-99ac-3d2162934ba6/e5ba276f-dcba-4582-b13f-c165afa2f575"/>
<target bus="ide" dev="hda"/>
<serial>1580607a-b240-4199-99ac-3d2162934ba6</serial>
<driver cache="none" error_policy="stop" io="native"
name="qemu" type="raw"/>
</disk>'''

    xmldom = minidom.parseString(text)

    disk = xmldom.getElementsByTagName('disk')[0]
    print("\nDisk device definition before execution: \n%s"
          % disk.toxml(encoding='UTF-8'))

    addDiscardUnmap(xmldom)

    print("\nDisk device after setting discard attribute: \n%s"
          % disk.toxml(encoding='UTF-8'))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook(' diskunmap hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 37
0
from openstacknet_utils import PLUGIN_TYPE_KEY
from openstacknet_utils import PROVIDER_TYPE_KEY
from openstacknet_utils import PT_BRIDGE
from openstacknet_utils import VNIC_ID_KEY
from openstacknet_utils import devName
from openstacknet_utils import executeOrExit
from vdsm.constants import EXT_BRCTL


def disconnectVnic(portId):
    executeOrExit([EXT_BRCTL, "delif", DUMMY_BRIDGE, devName("tap", portId)])


def main():
    if PROVIDER_TYPE_KEY not in os.environ:
        return

    providerType = os.environ[PROVIDER_TYPE_KEY]
    pluginType = os.environ[PLUGIN_TYPE_KEY]
    if providerType == OPENSTACK_NET_PROVIDER_TYPE and pluginType == PT_BRIDGE:
        vNicId = os.environ[VNIC_ID_KEY]
        sys.stderr.write("Removing vNIC %s from %s for provider type %s" % (vNicId, DUMMY_BRIDGE, providerType))
        disconnectVnic(vNicId)


if __name__ == "__main__":
    try:
        main()
    except:
        hooking.exit_hook("openstacknet hook: [unexpected error]: %s\n" % traceback.format_exc())
Ejemplo n.º 38
0
def _parse_into_subcommands(tokens):
    current = []
    for token in tokens:
        if token.startswith('-') and current:
            yield Subcommand(current[0], current[1], current[2:])
            current = []
        current.append(token)
    if current:
        yield Subcommand(current[0], current[1], current[2:])


def _set_ethtool_opts(network, options):
    """Takes an iterable of the tokenized ethtool command line arguments and
    applies them to the network devices"""
    command = [ETHTOOL_BINARY.cmd] + options
    rc, _, err = hooking.execCmd(command)
    if rc != 0:
        raise EthtoolError('Failed to set ethtool opts (%s) for network %s. '
                           'Err: %s' % (' '.join(options), network, err))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('ethtool_options hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 39
0

def _generate_commands(options, top_level_device):
    for addr in options.split(','):
        yield [
            ipwrapper._IP_BINARY.cmd, '-4', 'addr', 'add', 'dev',
            top_level_device,
            addr.strip()
        ]


def _top_dev(network, attrs):
    if hooking.tobool(attrs.get('bridged')):
        return network
    # bridgeless
    nics, vlan, _, bonding = netinfo.cache.NetInfo(
        netswitch.configurator.netinfo()).getNicsVlanAndBondingForNetwork(
            network)
    return vlan or bonding or nics[0]


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('extra ipv4 addrs hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 40
0
                'test %s: interface %s has state %s' %
                (test_msg, interface, state)
            )
    finally:
        os.unlink(os.path.join(temp_dir, 'check_ipv4'))
        os.unlink(os.path.join(temp_dir, 'check_ipv6'))
        os.rmdir(temp_dir)


def main():
    stats_json = hooking.read_json()
    networks = persist_net.PersistentConfig().networks
    update_networks_state(stats_json, networks, constants.P_VDSM_RUN)
    hooking.write_json(stats_json)


if __name__ == '__main__':
    if HELP_ARG in sys.argv:
        hooking.exit_hook(HELP_TEXT)

    try:
        if TEST_ARG in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook(
            'checkips hook: [unexpected error]: %s\n' %
            traceback.format_exc()
        )
#!/usr/bin/python

import hooking
import os
import sys
sys.path.append("/usr/libexec/vdsm/hooks/vifdriver")
import vif_driver_hooking

reply = vif_driver_hooking.before_network_setup(os.environ, hooking.read_json())
if reply:
    hooking.write_json(reply)
hooking.exit_hook("", return_code=0)
Ejemplo n.º 42
0
        <boot order="1"/>
    </interface>
    """).getElementsByTagName('interface')[0]

    print("Interface before removing filter: %s" %
          interface.toxml(encoding='UTF-8'))

    allocate_random_network(interface)
    print("Interface after removing filter: %s" %
          interface.toxml(encoding='UTF-8'))


def main():
    device_xml = hooking.read_domxml()
    allocate_random_network(device_xml)
    hooking.write_domxml(device_xml)


if __name__ == '__main__':
    if HELP_ARG in sys.argv:
        hooking.exit_hook(HELP_TEXT)

    try:
        if TEST_ARG in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('vm net allocation hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 43
0
def resume_paused_vm(vm_id):
    unpause_file = MARK_FOR_UNPAUSE_PATH % vm_id
    if os.path.isfile(unpause_file):
        with closing(jsonrpcvdscli.connect()) as server:
            server.cont(vm_id)
        os.remove(unpause_file)


def main():

    # TODO (HACK):
    # This code waits for the nic to be attached to neutron for a
    # certain amount of time. This is one way of going around the
    # race between the code and the vm nic becoming active. It is
    # a very fragile hack, as there is no guarantee the nic will
    # actually be ready after this.
    vm_id = os.environ[VM_ID_KEY]
    launch_flags = hooking.load_vm_launch_flags_from_file(vm_id)
    if launch_flags == libvirt.VIR_DOMAIN_START_PAUSED:
        time.sleep(OPENSTACK_NIC_WAIT_TIME)
        resume_paused_vm(vm_id)


if __name__ == '__main__':
    try:
        main()
    except:
        hooking.exit_hook('openstacknet hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 44
0
def _list_ports(bridge):
    rc, out, err = execCmd([EXT_OVS_VSCTL, 'list-ports', bridge], sudo=True)
    if rc != 0:
        hooking.exit_hook('\n'.join(err))
    return out
Ejemplo n.º 45
0
            test_msg = 'pass'
            if network_stats['network'][interface]['state'] != state:
                test_msg = 'fail'
            print('test %s: interface %s has state %s' %
                  (test_msg, interface, state))
    finally:
        os.unlink(os.path.join(temp_dir, 'check_ipv4'))
        os.unlink(os.path.join(temp_dir, 'check_ipv6'))
        os.rmdir(temp_dir)


def main():
    stats_json = hooking.read_json()
    networks = persist_net.PersistentConfig().networks
    update_networks_state(stats_json, networks, constants.P_VDSM_RUN)
    hooking.write_json(stats_json)


if __name__ == '__main__':
    if HELP_ARG in sys.argv:
        hooking.exit_hook(HELP_TEXT)

    try:
        if TEST_ARG in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('checkips hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 46
0
    if ovs:
        pluginType = PT_OVS
    else:
        pluginType = PT_BRIDGE

    import openstacknet_utils
    openstacknet_utils.executeOrExit = openstacknet_utils.mockExecuteOrExit
    openstacknet_utils.deviceExists = openstacknet_utils.mockDeviceExists
    addOpenstackVnic(domxml,
                     pluginType,
                     'test_port_id',
                     withSecurityGroups)
    print(domxml.toxml(encoding='utf-8'))


if __name__ == '__main__':
    if HELP_ARG in sys.argv:
        hooking.exit_hook(HELP_TEXT)

    try:
        if TEST_ARG in sys.argv:
            useOvs = OVS_ARG in sys.argv
            useSecGroups = SECGROUPS_ARG in sys.argv
            test(useOvs, useSecGroups)
        else:
            main()
    except:
        hooking.exit_hook('openstacknet hook: [unexpected error]: %s\n' %
                          traceback.format_exc())
Ejemplo n.º 47
0
def test():
    text = '''<graphics type='spice' port='-1' tlsPort='-1' autoport='yes'>
       <channel name='main' mode='secure'/>
       <channel name='record' mode='insecure'/>
       <streaming mode='filter'/>
       <mouse mode='client'/>
        </graphics>'''

    xmldom = minidom.parseString(text)
    graphics = xmldom.getElementsByTagName('graphics')[0]
    print("\n Graphic device definition before execution \n %s"
          % graphics.toxml(encoding='UTF-8'))
    returnEle = createElement(xmldom, 'image', 'compression', 'glz')
    if returnEle:
        graphics.appendChild(returnEle)
    print("\n Graphic device after setting image element \n %s"
          % graphics.toxml(encoding='UTF-8'))


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('spiceoptions: [unexpected error]: %s\n'
                          % traceback.format_exc())
        sys.exit(2)
Ejemplo n.º 48
0
          'host: %s' % getUsableNics())


def _migration_script():
    """Return true if this script runs as a migration destination script"""
    dirname = os.path.split(
        os.path.dirname(os.path.abspath(__file__)))[1]
    return dirname == 'before_device_migrate_destination'


def main():
    portProfile = os.environ.get('vmfex')
    if portProfile is not None:
        handleDirectPool(libvirtconnection.get())
        if not _migration_script():
            doc = hooking.read_domxml()
            interface, = doc.getElementsByTagName('interface')
            attachProfileToInterfaceXml(interface, portProfile)
            hooking.write_domxml(doc)


if __name__ == '__main__':
    try:
        if '--test' in sys.argv:
            test()
        else:
            main()
    except:
        hooking.exit_hook('vmfex_dev hook: [unexpected error]: %s\n' %
                          traceback.format_exc())