def test_add_nic(engine_api):
    NIC_NAME = 'eth0'
    # Locate the vnic profiles service and use it to find the ovirmgmt
    # network's profile id:
    profiles_service = engine_api.system_service().vnic_profiles_service()
    profile_id = next((profile.id for profile in profiles_service.list()
                       if profile.name == MANAGEMENT_NETWORK), None)

    # Empty profile id would cause fail in later tests (e.g. add_filter):
    assert profile_id is not None

    # Locate the virtual machines service and use it to find the virtual
    # machine:
    vms_service = engine_api.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]

    # Locate the service that manages the network interface cards of the
    # virtual machine:
    nics_service = vms_service.vm_service(vm.id).nics_service()

    # Use the "add" method of the network interface cards service to add the
    # new network interface card:
    nics_service.add(
        types.Nic(
            name=NIC_NAME,
            interface=types.NicInterface.VIRTIO,
            vnic_profile=types.VnicProfile(id=profile_id),
        ), )
Beispiel #2
0
    def create(self,
               name,
               vnic_profile,
               interface=VnicInterfaceType.VIRTIO,
               mac_addr=None):
        """
        :type name: string
        :type vnic_profile: netlib.VnicProfile
        :type interface: netlib.VnicInterfaceType
        :type mac_addr: string
        """

        sdk_type = types.Nic(name=name,
                             interface=interface,
                             vnic_profile=vnic_profile.get_sdk_type())
        if mac_addr is not None:
            sdk_type.mac = types.Mac(address=mac_addr)
        try:
            self._create_sdk_entity(sdk_type)
        except EntityCreationError as err:
            message = err.args[0]
            if 'MAC Address' in message and 'in use' in message:
                raise MacAddrInUseError(message)
            elif 'Not enough MAC addresses' in message:
                raise MacPoolIsInFullCapacityError(message)
            raise
Beispiel #3
0
def attach_network(params, vm_name):

    system_service = connection.system_service()
    vms_service = connection.system_service().vms_service()
    name_of_VM = 'name=' + str(vm_name)
    vm = vms_service.list(search=str(name_of_VM))[0]

    cluster = system_service.clusters_service().cluster_service(
        vm.cluster.id).get()
    dcs_service = connection.system_service().data_centers_service()
    dc = dcs_service.list(search='Clusters.name=%s' % cluster.name)[0]
    networks_service = dcs_service.service(dc.id).networks_service()
    network = next(
        (n for n in networks_service.list() if n.name == params["network"]),
        None)
    profiles_service = connection.system_service().vnic_profiles_service()
    profile_id = None
    for profile in profiles_service.list():
        if profile.name == params["network"]:
            profile_id = profile.id
            break

    nics_service = vms_service.vm_service(vm.id).nics_service()

    # Use the "add" method of the network interface cards service to add the
    # new network interface card:
    nics_service.add(
        types.Nic(
            name=params["name"],
            description=params["description"]
            if "description" in params else "Not provided",
            vnic_profile=types.VnicProfile(id=profile_id, ),
        ), )
Beispiel #4
0
 def __attach_nics(self, entity):
     # Attach NICs to VM, if specified:
     vnic_profiles_service = self._connection.system_service().vnic_profiles_service()
     nics_service = self._service.service(entity.id).nics_service()
     for nic in self._module.params['nics']:
         if search_by_name(nics_service, nic.get('name')) is None:
             if not self._module.check_mode:
                 nics_service.add(
                     otypes.Nic(
                         name=nic.get('name'),
                         interface=otypes.NicInterface(
                             nic.get('interface', 'virtio')
                         ),
                         vnic_profile=otypes.VnicProfile(
                             id=search_by_name(
                                 vnic_profiles_service,
                                 nic.get('profile_name'),
                             ).id
                         ) if nic.get('profile_name') else None,
                         mac=otypes.Mac(
                             address=nic.get('mac_address')
                         ) if nic.get('mac_address') else None,
                     )
                 )
             self.changed = True
Beispiel #5
0
    def add_nic(self,
                network_name,
                nic_name='nic1',
                interface='VIRTIO',
                on_boot=True,
                vnic_profile=None):
        """Add a nic to VM/Template

        Args:
            network_name: string name of the network, also default for vnic_profile name if empty
            nic_name: string name of the nic to add
            interface: string interface type for ovirt, interfaces are resolved to a specific type
            on_boot: boolean, kwarg for nic options
            vnic_profile: string name of the vnic_profile, network_name is used if empty

        Raises:
            ResourceAlreadyExistsException: method checks if the nic already exists
        """
        try:
            self._get_nic_service(nic_name)
        except NotFoundError:
            pass
        else:
            raise ResourceAlreadyExistsException(
                'Nic with name {} already exists on {}'.format(
                    nic_name, self.name))
        nics_service = self.api.nics_service()
        nic = types.Nic(name=nic_name)
        self._nic_action(nic,
                         network_name,
                         interface,
                         on_boot,
                         vnic_profile,
                         nics_service,
                         action='add')
def add_nic(pname, pnetwork, pnicname, pnic_description):
    print('Adding Nic : ' + pnicname + ' to VM ' + pname + '...')
    vm = vms_service.list(search='name=' + pname)[0]
    # In order to specify the network that the new interface will be
    # connected to we need to specify the identifier of the virtual network
    # interface profile, so we need to find it:
    profiles_service = connection.system_service().vnic_profiles_service()
    profile_id = None
    for profile in profiles_service.list():
        if profile.name == pnetwork:
            profile_id = profile.id
            break

    # Locate the service that manages the network interface cards of the
    # virtual machine:
    nics_service = vms_service.vm_service(vm.id).nics_service()

    # Use the "add" method of the network interface cards service to add the
    # new network interface card:
    nics_service.add(
        types.Nic(
            name=pnicname,
            description=pnic_description,
            vnic_profile=types.VnicProfile(id=profile_id, ),
        ), )
Beispiel #7
0
    def net_rm(self, args):
        vms_service = self.c.system_service().vms_service()
        vm = vms_service.list(search=args.vm_name)[0]
        nic_service = vms_service.vm_service(vm.id).nics_service().nic_service(args.port_id)

        #nics_service = vms_service.vm_service(vm.id).nics_service()
        #VmNicService got remove function
        # http://ovirt.github.io/ovirt-engine-sdk/master/services.m.html#ovirtsdk4.services.HostService.nics_service
        # nics_service.add method takes vnic profile id as the variable,
        # not the network id. So we have to find out the vnic profile id
        # by using network id
        # https://lab-rhevm.gsslab.pek2.redhat.com/ovirt-engine/api/vnicprofiles/00e3cad9-5383-494c-9524-f353b5e2c8be

        try:
            nic_service.remove(
                types.Nic(
                    name=nic_name,
                    description='My network interface card',
                    vnic_profile=types.VnicProfile(
                        id=profile_id,
                    ),
                ),
            )
            self.c.close()
        except sdk.Error as err:
            print "Failed to add NICs to %s, %s" % (args.vm_name, str(err))
Beispiel #8
0
 def net_add(self, args):
     vms_service = self.c.system_service().vms_service()
     vm = vms_service.list(search=args.vm_name)[0]
     nics_service = vms_service.vm_service(vm.id).nics_service()
     index = len(nics_service.list())
     # nics_service.add method takes vnic profile id as the variable,
     # not the network id. So we have to find out the vnic profile id
     # by using network id
     # https://lab-rhevm.gsslab.pek2.redhat.com/ovirt-engine/api/vnicprofiles/00e3cad9-5383-494c-9524-f353b5e2c8be
     profiles_service = self.c.system_service().vnic_profiles_service()
     profile_id = None
     for profile in profiles_service.list():
         if profile.network.id == args.net_id:
             profile_id = profile.id
             break
     nic_name = 'nic'+str(index)
     try:
         nics_service.add(
             types.Nic(
                 name=nic_name,
                 description='My network interface card',
                 vnic_profile=types.VnicProfile(
                     id=profile_id,
                 ),
             ),
         )
         self.c.close()
     except sdk.Error as err:
         print "Failed to add NICs to %s, %s" % (args.vm_name, str(err))
Beispiel #9
0
def test_hotplug_nic(assert_vm_is_alive, engine_api):
    vms_service = engine_api.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]
    nics_service = vms_service.vm_service(vm.id).nics_service()
    nics_service.add(
        types.Nic(name='eth1', interface=types.NicInterface.VIRTIO), )
    assert_vm_is_alive(VM0_NAME)
Beispiel #10
0
def _refresh_nic(vms_service, vm):
    nics_service = vms_service.vm_service(vm.vm_id).nics_service()
    nic = nics_service.nic_service(vm.nic_id).get()
    nics_service.nic_service(nic.id).remove()
    nics_service.add(
        types.Nic(name=nic.name,
                  description=nic.description,
                  vnic_profile=nic.vnic_profile), )
Beispiel #11
0
def test_hotplug_nic(prefix):
    pytest.skip('https://bugzilla.redhat.com/1776317')
    api_v4 = prefix.virt_env.engine_vm().get_api_v4()
    vms_service = api_v4.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]
    nics_service = vms_service.vm_service(vm.id).nics_service()
    nics_service.add(
        types.Nic(name='eth1', interface=types.NicInterface.VIRTIO), )
    assert_vm0_is_alive(prefix)
Beispiel #12
0
 def build_entity(self):
     return otypes.Nic(
         name=self._module.params.get('name'),
         interface=otypes.NicInterface(self._module.params.get('interface'))
         if self._module.params.get('interface') else None,
         vnic_profile=otypes.VnicProfile(id=self.vnic_id, )
         if self.vnic_id else None,
         mac=otypes.Mac(address=self._module.params.get('mac_address'))
         if self._module.params.get('mac_address') else None,
     )
Beispiel #13
0
def add_nic(api):
    engine = api.system_service()
    vms = engine.vms_service()
    vm = vms.list(search=VM_NAME)[0]

    new_nic = types.Nic(
        name='eth0',
        interface=types.NicInterface.VIRTIO,
        network=types.Network(name=MGMT_NETWORK)
    )
    vms.vm_service(vm.id).nics_service().add(new_nic)
Beispiel #14
0
def _hotplug_network_to_vm(api, vm_name, network_name, iface_name):
    engine = api.system_service()

    profiles_service = engine.vnic_profiles_service()
    profile = next(profile for profile in profiles_service.list()
                   if profile.name == network_name)

    nics_service = test_utils.get_nics_service(engine, vm_name)
    nics_service.add(
        types.Nic(
            name=iface_name,
            vnic_profile=types.VnicProfile(id=profile.id, ),
        ), )
Beispiel #15
0
def add_nic(api):
    NIC_NAME = 'eth0'
    # Locate the vnic profiles service and use it to find the ovirmgmt
    # network's profile id:
    profiles_service = api.system_service().vnic_profiles_service()
    profile_id = next((profile.id for profile in profiles_service.list()
                       if profile.name == MANAGEMENT_NETWORK), None)

    # Empty profile id would cause fail in later tests (e.g. add_filter):
    nt.assert_is_not_none(profile_id)

    # Locate the virtual machines service and use it to find the virtual
    # machine:
    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]

    # Locate the service that manages the network interface cards of the
    # virtual machine:
    nics_service = vms_service.vm_service(vm.id).nics_service()

    # Use the "add" method of the network interface cards service to add the
    # new network interface card:
    nics_service.add(
        types.Nic(
            name=NIC_NAME,
            interface=types.NicInterface.VIRTIO,
            vnic_profile=types.VnicProfile(id=profile_id),
        ), )

    vm = vms_service.list(search='name=%s' % VM2_NAME)[0]
    nics_service = vms_service.vm_service(vm.id).nics_service()
    nics_service.add(
        types.Nic(
            name=NIC_NAME,
            interface=types.NicInterface.E1000,
            mac=types.Mac(address=UNICAST_MAC_OUTSIDE_POOL),
            vnic_profile=types.VnicProfile(id=profile_id),
        ), )
Beispiel #16
0
def add_nic_to_instance(api, vm_id, vnic_id, nic_name='nic1'):
    """Add nic to vm."""
    vms_service = api.system_service().vms_service()
    """Get id of network."""
    nics_service = vms_service.vm_service(vm_id).nics_service()
    try:
        nics_service.add(
            types.Nic(
                name=nic_name,
                description='My network interface card',
                vnic_profile=types.VnicProfile(id=vnic_id, ),
            ), )
    except Exception as e:
        print "Can't add NIC: %s" % str(e)
        api.close()
        sys.exit(1)
Beispiel #17
0
 def __attach_nics(self, entity):
     # Attach NICs to instance type, if specified:
     nics_service = self._service.service(entity.id).nics_service()
     for nic in self.param('nics'):
         if search_by_name(nics_service, nic.get('name')) is None:
             if not self._module.check_mode:
                 nics_service.add(
                     otypes.Nic(
                         name=nic.get('name'),
                         interface=otypes.NicInterface(
                             nic.get('interface', 'virtio')),
                         vnic_profile=otypes.VnicProfile(
                             id=self.__get_vnic_profile_id(nic), )
                         if nic.get('profile_name') else None,
                         mac=otypes.Mac(address=nic.get('mac_address'))
                         if nic.get('mac_address') else None,
                     ))
             self.changed = True
Beispiel #18
0
    def create_vm_nic(self, vlan, logger):
        try:
            network = next((i for i in self.networks_service.list()
                            if i.vlan is not None and i.vlan.id == vlan), None)
            if network is None:
                raise Exception(
                    'Can not find network with vlan{}'.format(vlan))
            profile = next((i for i in self.profiles_service.list()
                            if i.name == network.name), None)
            if profile is None:
                raise Exception('Can not find profiles name {}'.format(
                    network.name))

            # create nic template
            return types.Nic(name='nic',
                             interface=types.NicInterface.VIRTIO,
                             vnic_profile=types.VnicProfile(id=profile.id))
        except Exception as e:
            raise Exception(e)
Beispiel #19
0
def mac_change(kvm_vnic):
    # Initiate oVirt SDK Connection
    try:
        connection = ovirt_connection()
        connection.authenticate()
    except:
        print("Failed to connect to oVirt engine!")
        exit(1)

    # Get the reference to the "vms" service:
    try:
        vms_service = connection.system_service().vms_service()
    except:
        print("Unable to establish OLVM system connection")
        exit(1)

    for i in range(len(kvm_vnic)):
        if "kvm" in kvm_vnic[i]['display_name']:
            try:
                # Find the virtual machine:
                vm = vms_service.list(
                    search="name={}".format(kvm_vnic[i]['display_name']))[0]
                # Locate the service that manages the virtual machine:
                vm_service = vms_service.vm_service(vm.id)
                # Locate the service that manages the NICS devices of the VM:
                nics_service = vm_service.nics_service()
                # Get the first found NIC:
                nic = nics_service.list()[0]
                # Locate the service that manages the NIC device found in previous step
                nic_service = nics_service.nic_service(nic.id)
                # Update the NIC MAC address
                nic_service.update(nic=types.Nic(
                    mac=types.Mac(address=kvm_vnic[i]['mac_address']), ), )
                print("VM " + kvm_vnic[i]['display_name'] +
                      " NIC MAC address was changed to: " +
                      kvm_vnic[i]['mac_address'])
            except:
                print("Unable to change MAC address to " +
                      kvm_vnic[i]['mac_address'] + " for VM " +
                      kvm_vnic[i]['display_name'])

    connection.close()
Beispiel #20
0
    def add_vm_network(
        self,
        vm: types.Vm,
        name: str,
        profile_name: str,
        mac: str,
        interface_type: types.NicInterface = types.NicInterface.VIRTIO
    ) -> types.Nic:
        profiles_service = self._connection.system_service(
        ).vnic_profiles_service()
        profile = find_one_in_list_by_name(profiles_service.list(),
                                           profile_name)

        nics_service = self._connection.system_service().vms_service(
        ).vm_service(vm.id).nics_service()
        return nics_service.add(
            types.Nic(
                name=name,
                mac=types.Mac(address=mac),
                interface=interface_type,
                vnic_profile=types.VnicProfile(id=profile.id, ),
            ))
Beispiel #21
0
def addNICs(session):
    """ Adds NICs to an existing VM """

    print "\n\n=================[ ADDING NICS ]================="

        for vm in configFile['vms']:
                hostname        = vm['hostname']
                cluster         = vm['cluster']
                for nic in vm['interfaces']:
                        network = vm['interfaces'][nic]
                        profileId = None
                        profileName = None

                        systemService   = session.system_service()
                        vmService       = systemService.vms_service()
                        machine         = vmService.list(search='name=%s' % str(hostname))[0]
                        dcService       = session.system_service().data_centers_service()
                        dc              = dcService.list(search='Clusters.name=%s' % str(cluster))[0]
                        networkService  = dcService.service(dc.id).networks_service()

            # logical networks in respective cluster
                        for net in networkService.list():
                if net.name == str(network):
                    # logical network if of specified nic network in configfile
                    profileService = session.system_service().vnic_profiles_service()
                                for profile in profileService.list():
                        if profile.name == str(network):
                            try:
                                nicService = vmService.vm_service(machine.id).nics_service()
                                                    nicService.add(
                                                            types.Nic(
                                                            name=nic,
                                                            vnic_profile=types.VnicProfile(
                                                                id=profile.id),
                                                            ),
                                                    )
                                print "Adding logical network \"%s\" to \"%s\" as NIC \"%s\"." % (str(network), hostname, nic)
                            except Exception as e:
                                pass
Beispiel #22
0
def add_nic_to_vm(api, options):
    """Add nic to vm."""
    search_name = "name=" + options['vm_name']
    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search=search_name)[0]
    """Get id of network."""
    profiles_service = api.system_service().vnic_profiles_service()
    profile_id = None
    for profile in profiles_service.list():
        if profile.name == options['network_name']:
            profile_id = profile.id
            break
    nics_service = vms_service.vm_service(vm.id).nics_service()
    try:
        nics_service.add(
            types.Nic(
                name='nic1',
                description='My network interface card',
                vnic_profile=types.VnicProfile(id=profile_id, ),
            ), )
    except Exception as e:
        print "Can't add NIC: %s" % str(e)
        api.close()
        sys.exit(1)
Beispiel #23
0
 def addVMNIC(self, vmname, network, nicname):
     vms_service = self.connection.system_service().vms_service()
     vm = vms_service.list(search='name=%s' % vmname)[0]
     profiles_service = self.connection.system_service(
     ).vnic_profiles_service()
     profile_id = None  # network的网卡编号UUID
     network_list = profiles_service.list()
     for profile in network_list:
         if profile.name == network:  # 判断网卡名是否是network传来的名称
             profile_id = profile.id  # 获取network对应网卡名的UUID
             try:
                 nics_service = vms_service.vm_service(vm.id).nics_service()
                 nics_service.add(
                     types.Nic(
                         name=nicname,  # 虚拟机新增网卡
                         description='My network interface',  # 描述
                         vnic_profile=types.VnicProfile(
                             id=
                             profile_id,  # 选择添加网卡关联的nic,这个与ovirt的网络关联,网络关联的是vlanid
                         ),
                     ), )
                 break  # 停止查找
             except:
                 pass
Beispiel #24
0
disk_attachment = disk_attachments_service.add(
    types.DiskAttachment(
        disk=types.Disk(
            format=types.DiskFormat.COW,
            provisioned_size=VMCapacity,
            storage_domains=[
                types.StorageDomain(name=VMDomain, ),
            ],
        ),
        interface=types.DiskInterface.VIRTIO_SCSI,
        bootable=True,
        active=True,
    ), )
###################################
netlist = connection.system_service().vnic_profiles_service().list(
    search=VMNetwork)[0]
nics_service = vms_service.vm_service(vm.id).nics_service()
nics_service.add(
    types.Nic(
        name='nic1',
        interface=types.NicInterface.VIRTIO,
        #        network=types.Network(name='ovirtmgmt'),
        vnic_profile=types.VnicProfile(id=netlist.id),
    ), )
#################################

print("Virtual machine '%s' added." % vm.name)
print("myinfo: '%s' " % vm.id)

connection.close()
Beispiel #25
0
# network by datacenter and cluster:
cluster = system_service.clusters_service().cluster_service(
    vm.cluster.id).get()
dcs_service = connection.system_service().data_centers_service()
dc = dcs_service.list(search='Clusters.name=%s' % cluster.name)[0]
networks_service = dcs_service.service(dc.id).networks_service()
network = next((n for n in networks_service.list() if n.name == 'mynetwork'),
               None)
profiles_service = connection.system_service().vnic_profiles_service()
profile_id = None
for profile in profiles_service.list():
    if profile.name == 'mynetwork':
        profile_id = profile.id
        break

# Locate the service that manages the network interface cards of the
# virtual machine:
nics_service = vms_service.vm_service(vm.id).nics_service()

# Use the "add" method of the network interface cards service to add the
# new network interface card:
nics_service.add(
    types.Nic(
        name='mynic',
        description='My network interface card',
        vnic_profile=types.VnicProfile(id=profile_id, ),
    ), )

# Close the connection to the server:
connection.close()
Beispiel #26
0
    def create(self,
               name,
               virttype='kvm',
               profile='',
               flavor=None,
               plan='kvirt',
               cpumodel='Westmere',
               cpuflags=[],
               numcpus=2,
               memory=512,
               guestid='guestrhel764',
               pool='default',
               template=None,
               disks=[{
                   'size': 10
               }],
               disksize=10,
               diskthin=True,
               diskinterface='virtio',
               nets=['default'],
               iso=None,
               vnc=False,
               cloudinit=True,
               reserveip=False,
               reservedns=False,
               reservehost=False,
               start=True,
               keys=None,
               cmds=[],
               ips=None,
               netmasks=None,
               gateway=None,
               nested=True,
               dns=None,
               domain=None,
               tunnel=False,
               files=[],
               enableroot=True,
               alias=[],
               overrides={},
               tags=None):
        """

        :param name:
        :param virttype:
        :param profile:
        :param flavor:
        :param plan:
        :param cpumodel:
        :param cpuflags:
        :param numcpus:
        :param memory:
        :param guestid:
        :param pool:
        :param template:
        :param disks:
        :param disksize:
        :param diskthin:
        :param diskinterface:
        :param nets:
        :param iso:
        :param vnc:
        :param cloudinit:
        :param reserveip:
        :param reservedns:
        :param reservehost:
        :param start:
        :param keys:
        :param cmds:
        :param ips:
        :param netmasks:
        :param gateway:
        :param nested:
        :param dns:
        :param domain:
        :param tunnel:
        :param files:
        :param enableroot:
        :param alias:
        :param overrides:
        :param tags:
        :return:
        """
        clone = not diskthin
        templateobject = types.Template(name=template) if template else None
        console = types.Console(enabled=True)
        try:
            vm = self.vms_service.add(types.Vm(
                name=name,
                cluster=types.Cluster(name=self.cluster),
                template=templateobject,
                console=console),
                                      clone=clone)
            vm_service = self.vms_service.vm_service(vm.id)
        except Exception as e:
            if self.debug:
                print(e)
            return {'result': 'failure', 'reason': e}
        timeout = 0
        while True:
            vm = vm_service.get()
            if vm.status == types.VmStatus.DOWN:
                break
            else:
                timeout += 5
                sleep(5)
                common.pprint("Waiting for vm to be ready", color='green')
            if timeout > 60:
                return {
                    'result': 'failure',
                    'reason': 'timeout waiting for vm to be ready'
                }
        profiles_service = self.conn.system_service().vnic_profiles_service()
        netprofiles = {}
        for prof in profiles_service.list():
            netprofiles[prof.name] = prof.id
        if 'default' not in netprofiles and 'ovirtmgmt' in netprofiles:
            netprofiles['default'] = netprofiles['ovirtmgmt']
        nics_service = self.vms_service.vm_service(vm.id).nics_service()
        nic_configurations = []
        for index, net in enumerate(nets):
            netname = None
            netmask = None
            mac = None
            if isinstance(net, str):
                netname = net
            elif isinstance(net, dict) and 'name' in net:
                netname = net['name']
                ip = None
                mac = net.get('mac')
                netmask = next(
                    (e for e in [net.get('mask'),
                                 net.get('netmask')] if e is not None), None)
                gateway = net.get('gateway')
                noconf = net.get('noconf')
                if noconf is not None:
                    continue
                if 'ip' in net:
                    ip = net['ip']
                # if 'alias' in net:
                #    alias = net['alias']
                if ips and len(ips) > index and ips[index] is not None:
                    ip = ips[index]
                if ip is not None and netmask is not None and gateway is not None:
                    nic_configuration = types.NicConfiguration(
                        name='eth%s' % index,
                        on_boot=True,
                        boot_protocol=types.BootProtocol.STATIC,
                        ip=types.Ip(version=types.IpVersion.V4,
                                    address=ip,
                                    netmask=netmask,
                                    gateway=gateway))
                    nic_configurations.append(nic_configuration)
            if netname is not None and netname in netprofiles:
                profile_id = netprofiles[netname]
                nics_service.add(
                    types.Nic(name='eth%s' % index,
                              mac=mac,
                              vnic_profile=types.VnicProfile(id=profile_id)))
        for index, disk in enumerate(disks):
            diskpool = pool
            diskthin = True
            disksize = '10'
            if index == 0 and template is not None:
                continue
            if isinstance(disk, int):
                disksize = disk
            elif isinstance(disk, str) and disk.isdigit():
                disksize = int(disk)
            elif isinstance(disk, dict):
                disksize = disk.get('size', disksize)
                diskpool = disk.get('pool', pool)
                diskthin = disk.get('thin', diskthin)
            self.add_disk(name, disksize, pool=diskpool, thin=diskthin)
        initialization = None
        if cloudinit:
            custom_script = ''
            if files:
                data = common.process_files(files=files, overrides=overrides)
                if data != '':
                    custom_script += "write_files:\n"
                    custom_script += data
            cmds.append('sleep 60')
            if template.lower().startswith('centos'):
                cmds.append('yum -y install centos-release-ovirt42')
            if template.lower().startswith('centos') or template.lower().startswith('fedora')\
                    or template.lower().startswith('rhel'):
                cmds.append('yum -y install ovirt-guest-agent-common')
                cmds.append('systemctl enable ovirt-guest-agent')
                cmds.append('systemctl start ovirt-guest-agent')
            if template.lower().startswith('debian'):
                cmds.append(
                    'echo "deb http://download.opensuse.org/repositories/home:/evilissimo:/deb/Debian_7.0/ ./" '
                    '>> /etc/apt/sources.list')
                cmds.append(
                    'gpg -v -a --keyserver http://download.opensuse.org/repositories/home:/evilissimo:/deb/'
                    'Debian_7.0/Release.key --recv-keys D5C7F7C373A1A299')
                cmds.append('gpg --export --armor 73A1A299 | apt-key add -')
                cmds.append('apt-get update')
                cmds.append('apt-get -Y install ovirt-guest-agent')
                cmds.append('service ovirt-guest-agent enable')
                cmds.append('service ovirt-guest-agent start')
            if [x for x in common.ubuntus if x in template.lower()]:
                cmds.append(
                    'echo deb http://download.opensuse.org/repositories/home:/evilissimo:/ubuntu:/16.04/'
                    'xUbuntu_16.04/ /')
                cmds.append(
                    'wget http://download.opensuse.org/repositories/home:/evilissimo:/ubuntu:/16.04/'
                    'xUbuntu_16.04//Release.key')
                cmds.append('apt-key add - < Release.key')
                cmds.append('apt-get update')
                cmds.append('apt-get -Y install ovirt-guest-agent')
            data = common.process_cmds(cmds=cmds, overrides=overrides)
            custom_script += "runcmd:\n"
            custom_script += data
            custom_script = None if custom_script == '' else custom_script
            user_name = common.get_user(template)
            root_password = None
            dns_servers = '8.8.8.8 1.1.1.1'
            key = get_home_ssh_key()
            initialization = types.Initialization(
                user_name=user_name,
                root_password=root_password,
                regenerate_ssh_keys=True,
                authorized_ssh_keys=key,
                host_name=name,
                nic_configurations=nic_configurations,
                dns_servers=dns_servers,
                dns_search=domain,
                custom_script=custom_script)
            tags_service = self.conn.system_service().tags_service()
            existing_tags = [tag.name for tag in tags_service.list()]
            if "profile_%s" % profile not in existing_tags:
                tags_service.add(types.Tag(name="profile_%s" % profile))
            if "plan_%s" % plan not in existing_tags:
                tags_service.add(types.Tag(name="plan_%s" % plan))
            tags_service = vm_service.tags_service()
            tags_service.add(tag=types.Tag(name="profile_%s" % profile))
            tags_service.add(tag=types.Tag(name="plan_%s" % plan))
        vm_service.start(use_cloud_init=cloudinit,
                         vm=types.Vm(initialization=initialization))
        return {'result': 'success'}
Beispiel #27
0
def main():

    parser = option_parser()
    args = parser.parse_args()

    if not early_option_check(args):
        sys.exit(-1)

    # Create the connection to the server:
    connection = sdk.Connection(
        url='https://@ENGINE_FQDN@/ovirt-engine/api',
        username='******',
        password=base64.b64decode('@ENGINEPASS_BASE64@'),
        ca_file='@CA_PEM@',
        debug=False,
    )

    vms_service = connection.system_service().vms_service()
    cluster = connection.system_service().clusters_service().list()[0]
    clustername = cluster.name
    dcs_service = connection.system_service().data_centers_service()
    dc = dcs_service.list(search='Clusters.name=%s' % cluster.name)[0]
    networks_service = dcs_service.service(dc.id).networks_service()
    profiles_service = connection.system_service().vnic_profiles_service()

    if not later_option_check(args, connection):
        connection.close()
        sys.exit(-1)

    shorthand = {
        'rhel6': 'rhel_6x64',
        'rhel7': 'rhel_7x64',
        'rhel8': 'rhel_8x64',
        'ubuntu': 'ubuntu_14_04',
        'debian': 'debian_7',
    }

    vmtype = {
        'server': types.VmType.SERVER,
        'desktop': types.VmType.DESKTOP,
        'high_performance': types.VmType.HIGH_PERFORMANCE
    }

    # Creating new virtual machine
    vm = types.Vm()
    vm.name = args.name
    vm.cluster = types.Cluster(name=clustername)
    vm.template = types.Template(name=args.template)
    if args.os in shorthand.keys():
        vm.os = types.OperatingSystem(type=shorthand[args.os])
    else:
        vm.os = types.OperatingSystem(type=args.os)
    vm.memory = args.memory * 1024 * 1024
    if args.balloon == 0:
        vm.memory_policy = types.MemoryPolicy(
            max=args.max_memory * 1024 * 1024,
            guaranteed=args.guaranteed_memory * 1024 * 1024)
    else:
        vm.memory_policy = types.MemoryPolicy(
            max=args.max_memory * 1024 * 1024,
            guaranteed=args.guaranteed_memory * 1024 * 1024,
            ballooning=True if args.balloon == 1 else False)

    vm.cpu = types.Cpu()
    vm.cpu.architecture = types.Architecture.X86_64
    vm.cpu.topology = types.CpuTopology(cores=1, sockets=args.cpu, threads=1)
    if args.sound != 0:
        vm.soundcard_enabled = True if args.sound == 1 else False
    vm.type = vmtype[args.type]

    print("Creating New Virtual Machine:{0}".format(args.name))
    vm = vms_service.add(vm)

    while vms_service.list(search=args.name)[0].status != types.VmStatus.DOWN:
        time.sleep(1)

    # Attach network interface(s)
    nics_service = vms_service.vm_service(vm.id).nics_service()
    nicnum = 0

    for netname in args.vmnet:
        network = next(
            (n for n in networks_service.list() if n.name == netname), None)
        profile_id = None
        for profile in profiles_service.list():
            if profile.name == netname:
                profile_id = profile.id
                break

        if profile_id != None:
            nicnum = nicnum + 1
            print("Attaching nic{0}(Network:{1})".format(nicnum, netname))
            nics_service.add(
                types.Nic(
                    name="nic{0}".format(nicnum),
                    vnic_profile=types.VnicProfile(id=profile_id, ),
                ), )

    # Create and attach disk(s)
    disk_attachments_service = vms_service.vm_service(
        vm.id).disk_attachments_service()
    disks_service = connection.system_service().disks_service()
    disknum = 0
    for d in args.vmdisk:
        disknum += 1
        new_disk = types.DiskAttachment()
        new_disk.disk = types.Disk()
        new_disk.disk.name = "{0}_Disk{1}".format(args.name, disknum)
        new_disk.disk.provisioned_size = int(d.split(':')[1]) * 2**30
        new_disk.disk.storage_domains = [
            types.StorageDomain(name=d.split(':')[0])
        ]
        if d.split(':')[2] == "RAW":
            new_disk.disk.format = types.DiskFormat.RAW
        else:
            new_disk.disk.format = types.DiskFormat.COW

        new_disk.interface = types.DiskInterface.VIRTIO_SCSI
        new_disk.active = True
        if disknum == 1:
            new_disk.bootable = True

        print(
            "Attaching Disk{0}(Domain:{1}, Size:{2}GB, DiskFormat:{3})".format(
                disknum,
                d.split(':')[0],
                d.split(':')[1],
                d.split(':')[2]))
        disk_attachment = disk_attachments_service.add(new_disk)
        disk_service = disks_service.disk_service(disk_attachment.disk.id)
        # wait disk attach finish
        time.sleep(5)
        while disk_service.get().status != types.DiskStatus.OK:
            print("Waiting disk attach complete")
            time.sleep(5)

    if args.ks != None or args.ps != None or args.ai != None:
        # one-shot VM configuration for Kickstart/preseed
        one_vm = types.Vm()
        one_vm.os = types.OperatingSystem()
        one_vm.os.kernel = 'iso://' + args.kernel
        one_vm.os.initrd = 'iso://' + args.initrd
        one_vm.run_once = True
        one_vm.cdroms = list()
        one_vm.cdroms.append(types.Cdrom())
        one_vm.cdroms[0].file = types.File()
        one_vm.cdroms[0].file.id = args.iso
        if args.dns == None:
            args.dns = ""
        elif args.os == 'rhel6':
            args.dns = 'dns=' + args.dns
        else:
            args.dns = 'nameserver=' + args.dns

        if args.os == 'rhel6':
            ksdev = args.network.split(':')[5]
            ksip = args.network.split(':')[0]
            ksnm = calc_netmask(int(args.network.split(':')[3]))
            ksgw = args.network.split(':')[2]
            args.network = "ksdevice={0} ip={1} netmask={2} gateway={3}".format(
                ksdev, ksip, ksnm, ksgw)

        if args.ks != None:
            if args.os == 'rhel6':
                one_vm.os.cmdline = args.network + " " + args.dns + " ks=" + args.ks
            else:
                one_vm.os.cmdline = args.network + " " + args.dns + " inst.ks=" + args.ks
        if args.ps != None:
            one_vm.os.cmdline = "auto=true url=" + args.ps
        if args.ai != None:
            one_vm.os.cmdline = "autoinstall ds=nocloud-net;s=" + args.ai

        vm_service = vms_service.vm_service(vm.id)
        print("Starting automatic OS installation on {0}".format(args.name))
        vm_service.start(vm=one_vm, volatile=True)

    # Close the connection to the server:
    connection.close()