Пример #1
0
    def create_vm(self,
                  name: str,
                  host: types.Host,
                  memory: int,
                  cpu_sockets: int,
                  template=None) -> types.Vm:
        """
        Создание виртуальной машины

        :param name: Название ВМ
        :param host: Хост ВМ
        :param memory: Объем памяти ВМ в байтах
        :param cpu_sockets: Количество ядер для ВМ
        :param template: Шаблон ВМ
        :return: Созданная ВМ
        """

        vms_service = self._connection.system_service().vms_service()

        free_memory = self.get_host_free_memory(host)

        if free_memory < memory:
            raise NotEnoughMemoryException(free_memory, memory)

        return vms_service.add(vm=types.Vm(
            name=name,
            cluster=host.cluster,
            template=template or types.Template(name='Blank'),
            cpu=types.Cpu(topology=types.CpuTopology(sockets=cpu_sockets)),
            memory=memory,
            memory_policy=types.MemoryPolicy(guaranteed=memory, max=memory),
            placement_policy=types.VmPlacementPolicy(
                affinity=types.VmAffinity.USER_MIGRATABLE,
                hosts=[host],
            )))
Пример #2
0
 def build_entity(self):
     return otypes.Vm(
         name=self._module.params['name'],
         cluster=otypes.Cluster(name=self._module.params['cluster'])
         if self._module.params['cluster'] else None,
         template=otypes.Template(name=self._module.params['template'])
         if self._module.params['template'] else None,
         stateless=self._module.params['stateless'],
         delete_protected=self._module.params['delete_protected'],
         high_availability=otypes.HighAvailability(
             enabled=self._module.params['high_availability'])
         if self._module.params['high_availability'] is not None else None,
         cpu=otypes.Cpu(topology=otypes.CpuTopology(
             cores=self._module.params['cpu_cores'],
             sockets=self._module.params['cpu_sockets'],
         )) if (self._module.params['cpu_cores']
                or self._module.params['cpu_sockets']) else None,
         cpu_shares=self._module.params['cpu_shares'],
         os=otypes.OperatingSystem(
             type=self._module.params['operating_system'],
             boot=otypes.Boot(devices=[
                 otypes.BootDevice(dev)
                 for dev in self._module.params['boot_devices']
             ], ) if self._module.params['boot_devices'] else None,
         ) if (self._module.params['operating_system']
               or self._module.params['boot_devices']) else None,
         type=otypes.VmType(self._module.params['type'])
         if self._module.params['type'] else None,
         memory=convert_to_bytes(self._module.params['memory'])
         if self._module.params['memory'] else None,
         memory_policy=otypes.MemoryPolicy(guaranteed=convert_to_bytes(
             self._module.params['memory_guaranteed']), )
         if self._module.params['memory_guaranteed'] else None,
     )
Пример #3
0
 def build_entity(self):
     return otypes.Template(
         id=self._module.params['id'],
         name=self._module.params['name'],
         cluster=otypes.Cluster(name=self._module.params['cluster'])
         if self._module.params['cluster'] else None,
         vm=otypes.Vm(name=self._module.params['vm'])
         if self._module.params['vm'] else None,
         description=self._module.params['description'],
         cpu_profile=otypes.CpuProfile(id=search_by_name(
             self._connection.system_service().cpu_profiles_service(),
             self._module.params['cpu_profile'],
         ).id) if self._module.params['cpu_profile'] else None,
         os=otypes.OperatingSystem(type=self.param('operating_system'), )
         if self.param('operating_system') else None,
         memory=convert_to_bytes(self.param('memory'))
         if self.param('memory') else None,
         version=otypes.TemplateVersion(
             base_template=self._get_base_template(),
             version_name=self.param('version').get('name'),
         ) if self.param('version') else None,
         memory_policy=otypes.MemoryPolicy(
             guaranteed=convert_to_bytes(self.param('memory_guaranteed')),
             max=convert_to_bytes(self.param('memory_max')),
         ) if any((self.param('memory_guaranteed'),
                   self.param('memory_max'))) else None,
         io=otypes.Io(threads=self.param('io_threads'), )
         if self.param('io_threads') is not None else None,
     )
Пример #4
0
 def build_vm(self, vm):
     return otypes.Vm(
         comment=vm.get('comment'),
         memory=convert_to_bytes(
             vm.get('memory')
         ) if vm.get('memory') else None,
         memory_policy=otypes.MemoryPolicy(
             guaranteed=convert_to_bytes(vm.get('memory_guaranteed')),
             max=convert_to_bytes(vm.get('memory_max')),
         ) if any((
             vm.get('memory_guaranteed'),
             vm.get('memory_max')
         )) else None,
         initialization=self.get_initialization(vm),
         display=otypes.Display(
             smartcard_enabled=vm.get('smartcard_enabled')
         ) if vm.get('smartcard_enabled') is not None else None,
         sso=(
             otypes.Sso(
                 methods=[otypes.Method(id=otypes.SsoMethod.GUEST_AGENT)] if vm.get('sso') else []
             )
         ) if vm.get('sso') is not None else None,
         time_zone=otypes.TimeZone(
             name=vm.get('timezone'),
         ) if vm.get('timezone') else None,
     )
Пример #5
0
def add_vm_blank(api):

    # Get the vms service
    vms_service=api.system_service().vms_service()

    #Create VM from blank template
    vm_memory=256*MB
    vm=types.Vm(
        name=VM0_NAME,
        memory=vm_memory,
        type=types.VmType.SERVER,
        os=types.OperatingSystem(
            type='other_linux',
            boot=types.Boot(
                devices=[types.BootDevice.HD, types.BootDevice.NETWORK]
            ),
        ),
        high_availability=types.HighAvailability(
            enabled=False
        ),
        cluster=types.Cluster(
            name=TEST_CLUSTER
        ),
        template=types.Template(
            name=TEMPLATE_BLANK
        ),
        display=types.Display(
            smartcard_enabled=True,
            keyboard_layout='en-us',
            file_transfer_enabled=True,
            copy_paste_enabled=True
        ),
        memory_policy=types.MemoryPolicy(
            guaranteed=vm_memory//2
        )
    )

    #Add this VM
    vm=vms_service.add(vm)

    #Check that VM was added
    vm_service=vms_service.vm_service(vm.id)
    testlib.assert_true_within_short(
        lambda: vm_service.get().status == types.VmStatus.DOWN
    )

    #Add another VM
    vm.id=None
    vm.name=VM1_NAME
    vm.initialization=None
    vm=vms_service.add(vm)

    #Check that the second VM was added
    vm_service=vms_service.vm_service(vm.id)
    testlib.assert_true_within_short(
        lambda: vm_service.get().status == types.VmStatus.DOWN
    )
 def build_entity(self):
     return otypes.Template(
         id=self._module.params['id'],
         name=self._module.params['name'],
         cluster=otypes.Cluster(
             name=self._module.params['cluster']
         ) if self._module.params['cluster'] else None,
         vm=otypes.Vm(
             name=self._module.params['vm']
         ) if self._module.params['vm'] else None,
         description=self._module.params['description'],
         cpu_profile=otypes.CpuProfile(
             id=search_by_name(
                 self._connection.system_service().cpu_profiles_service(),
                 self._module.params['cpu_profile'],
             ).id
         ) if self._module.params['cpu_profile'] else None,
         display=otypes.Display(
             smartcard_enabled=self.param('smartcard_enabled')
         ) if self.param('smartcard_enabled') is not None else None,
         os=otypes.OperatingSystem(
             type=self.param('operating_system'),
         ) if self.param('operating_system') else None,
         memory=convert_to_bytes(
             self.param('memory')
         ) if self.param('memory') else None,
         soundcard_enabled=self.param('soundcard_enabled'),
         usb=(
             otypes.Usb(enabled=self.param('usb_support'))
         ) if self.param('usb_support') is not None else None,
         sso=(
             otypes.Sso(
                 methods=[otypes.Method(id=otypes.SsoMethod.GUEST_AGENT)] if self.param('sso') else []
             )
         ) if self.param('sso') is not None else None,
         time_zone=otypes.TimeZone(
             name=self.param('timezone'),
         ) if self.param('timezone') else None,
         version=otypes.TemplateVersion(
             base_template=self._get_base_template(),
             version_name=self.param('version').get('name'),
         ) if self.param('version') else None,
         memory_policy=otypes.MemoryPolicy(
             guaranteed=convert_to_bytes(self.param('memory_guaranteed')),
             ballooning=self.param('ballooning_enabled'),
             max=convert_to_bytes(self.param('memory_max')),
         ) if any((
             self.param('memory_guaranteed'),
             self.param('ballooning_enabled'),
             self.param('memory_max')
         )) else None,
         io=otypes.Io(
             threads=self.param('io_threads'),
         ) if self.param('io_threads') is not None else None,
         initialization=self.get_initialization(),
     )
Пример #7
0
def test_hotunplug_memory(assert_vm_is_alive, engine_api,
                          get_vm_libvirt_memory_amount, hotplug_mem_amount):
    engine = engine_api.system_service()
    vm_service = test_utils.get_vm_service(engine, VM0_NAME)
    new_memory = vm_service.get().memory - hotplug_mem_amount
    with engine_utils.wait_for_event(
            engine, 2046):  # MEMORY_HOT_UNPLUG_SUCCESSFULLY_REQUESTED(2,046)
        vm_service.update(vm=types.Vm(memory=new_memory,
                                      memory_policy=types.MemoryPolicy(
                                          guaranteed=new_memory, )))
        assert vm_service.get().memory == new_memory

    assert_vm_is_alive(VM0_NAME)
    assert get_vm_libvirt_memory_amount(VM0_NAME) // KB == new_memory // MB
Пример #8
0
 def build_entity(self):
     template = self.__get_template_with_version()
     return otypes.Vm(
         name=self.param('name'),
         cluster=otypes.Cluster(
             name=self.param('cluster')) if self.param('cluster') else None,
         template=otypes.Template(id=template.id, ) if template else None,
         use_latest_template_version=self.param(
             'use_latest_template_version'),
         stateless=self.param('stateless')
         or self.param('use_latest_template_version'),
         delete_protected=self.param('delete_protected'),
         high_availability=otypes.HighAvailability(
             enabled=self.param('high_availability'))
         if self.param('high_availability') is not None else None,
         cpu=otypes.Cpu(topology=otypes.CpuTopology(
             cores=self.param('cpu_cores'),
             sockets=self.param('cpu_sockets'),
         )) if
         (self.param('cpu_cores') or self.param('cpu_sockets')) else None,
         cpu_shares=self.param('cpu_shares'),
         os=otypes.OperatingSystem(
             type=self.param('operating_system'),
             boot=otypes.Boot(devices=[
                 otypes.BootDevice(dev)
                 for dev in self.param('boot_devices')
             ], ) if self.param('boot_devices') else None,
         ) if (self.param('operating_system')
               or self.param('boot_devices')) else None,
         type=otypes.VmType(self.param('type'))
         if self.param('type') else None,
         memory=convert_to_bytes(self.param('memory'))
         if self.param('memory') else None,
         memory_policy=otypes.MemoryPolicy(guaranteed=convert_to_bytes(
             self.param('memory_guaranteed')), )
         if self.param('memory_guaranteed') else None,
         instance_type=otypes.InstanceType(id=get_id_by_name(
             self._connection.system_service().instance_types_service(),
             self.param('instance_type'),
         ), ) if self.param('instance_type') else None,
         description=self.param('description'),
         comment=self.param('comment'),
         time_zone=otypes.TimeZone(name=self.param('timezone'), )
         if self.param('timezone') else None,
         serial_number=otypes.SerialNumber(
             policy=otypes.SerialNumberPolicy(self.param('serial_policy')),
             value=self.param('serial_policy_value'),
         ) if (self.param('serial_policy') is not None
               or self.param('serial_policy_value') is not None) else None,
     )
Пример #9
0
def add_instance_type(api):
    instance_types_service = api.system_service().instance_types_service()
    nt.assert_true(
        instance_types_service.add(
            types.InstanceType(
                name='myinstancetype',
                description='My instance type',
                memory=1 * 2**30,
                memory_policy=types.MemoryPolicy(max=1 * 2**30, ),
                high_availability=types.HighAvailability(enabled=True, ),
                cpu=types.Cpu(topology=types.CpuTopology(
                    cores=2,
                    sockets=2,
                ), ),
            ), ))
Пример #10
0
    def set_vm_memory(self, vm: types.Vm, memory: int):
        """
        Установить количество ОЗУ

        :param vm: ВМ
        :param memory: Количество ОЗУ
        """
        vm_service = self._connection.system_service().vms_service(
        ).vm_service(vm.id)
        vm_service.update(
            types.Vm(
                memory=memory,
                memory_policy=types.MemoryPolicy(guaranteed=memory,
                                                 max=memory),
            ))
Пример #11
0
def test_add_vm1_from_template(engine_api, cirros_image_glance_template_name):
    engine = engine_api.system_service()
    templates_service = engine.templates_service()
    glance_template = templates_service.list(
        search='name=%s' % cirros_image_glance_template_name)[0]
    if glance_template is None:
        pytest.skip('%s: template %s not available.' %
                    (add_vm1_from_template.__name__,
                     cirros_image_glance_template_name))

    vm_memory = 128 * MB  # runs with 64 ok, but we need to do a hotplug later (64+256 is too much difference)
    vms_service = engine.vms_service()
    vms_service.add(
        types.Vm(
            name=VM1_NAME,
            description='CirrOS imported from Glance as Template',
            memory=vm_memory,
            cluster=types.Cluster(name=TEST_CLUSTER, ),
            template=types.Template(name=cirros_image_glance_template_name, ),
            use_latest_template_version=True,
            stateless=True,
            display=types.Display(type=types.DisplayType.VNC, ),
            memory_policy=types.MemoryPolicy(
                guaranteed=
                vm_memory,  # with so little memory we don't want guaranteed to be any lower
                ballooning=False,
            ),
            os=types.OperatingSystem(
                type=
                'rhel_7x64',  # even though it's CirrOS we want to check a non-default OS type
            ),
            time_zone=types.TimeZone(name='Etc/GMT', ),
            type=types.VmType.SERVER,
            serial_number=types.SerialNumber(
                policy=types.SerialNumberPolicy.CUSTOM,
                value='12345678',
            ),
            cpu=types.Cpu(
                architecture=types.Architecture.X86_64,
                topology=types.CpuTopology(
                    sockets=1,
                    cores=1,
                    threads=2,
                ),
            ),
        ))
Пример #12
0
    def create(self, vm_name, cluster, template, stateless=False):
        """
        :type vm_name: string
        :type cluster: clusterlib.Cluster
        :type template: string
        :type stateless: boolean
        """
        MB256 = 256 * 2**20

        sdk_type = types.Vm(
            name=vm_name,
            cluster=cluster.get_sdk_type(),
            template=types.Template(name=template),
            stateless=stateless,
            memory=MB256,
            memory_policy=types.MemoryPolicy(guaranteed=MB256 // 2))
        self._create_sdk_entity(sdk_type)
Пример #13
0
def test_hotplug_memory(assert_vm_is_alive, engine_api,
                        get_vm_libvirt_memory_amount, hotplug_mem_amount):
    engine = engine_api.system_service()
    vm_service = test_utils.get_vm_service(engine, VM0_NAME)
    new_memory = vm_service.get().memory + hotplug_mem_amount
    with engine_utils.wait_for_event(engine, 2039):  # HOT_SET_MEMORY(2,039)
        vm_service.update(vm=types.Vm(
            memory=new_memory,
            # Need to avoid OOM scenario where ballooning would immediately try to claim some memory.
            # CirrOS is lacking memory onlining rules so the guest memory doesn't really increase and
            # balloon inflation just crashes the guest instead. Balloon gets inflated because MOM
            # does not know that guest size didn't increase and just assumes it did, and the host
            # OST VM is likely under memory pressure, there's not much free RAM in OST environment.
            # Setting minimum guaranteed to new memory size keeps MOM from inflating balloon.
            memory_policy=types.MemoryPolicy(guaranteed=new_memory, )))
        assert vm_service.get().memory == new_memory

    assert_vm_is_alive(VM0_NAME)
    assert get_vm_libvirt_memory_amount(VM0_NAME) // KB == new_memory // MB
Пример #14
0
def add_vm1_from_template(api):
    engine = api.system_service()
    templates_service = engine.templates_service()
    glance_template = templates_service.list(search='name=%s' %
                                             TEMPLATE_CIRROS)[0]
    if glance_template is None:
        raise SkipTest('%s: template %s not available.' % (
            add_vm1_from_template.__name__,
            TEMPLATE_CIRROS,
        ))

    vm_memory = 512 * MB
    vms_service = engine.vms_service()
    vms_service.add(
        types.Vm(
            name=VM1_NAME,
            description='CirrOS imported from Glance as Template',
            memory=512 * MB,
            cluster=types.Cluster(name=TEST_CLUSTER, ),
            template=types.Template(name=TEMPLATE_CIRROS, ),
            use_latest_template_version=True,
            stateless=True,
            display=types.Display(type=types.DisplayType.VNC, ),
            memory_policy=types.MemoryPolicy(
                guaranteed=vm_memory / 2,
                ballooning=False,
            ),
            os=types.OperatingSystem(type='other_lnux', ),
            time_zone=types.TimeZone(name='Etc/GMT', ),
            type=types.VmType.SERVER,
            serial_number=types.SerialNumber(
                policy=types.SerialNumberPolicy.CUSTOM,
                value='12345678',
            ),
            cpu=types.Cpu(
                architecture=types.Architecture.X86_64,
                topology=types.CpuTopology(
                    sockets=1,
                    cores=1,
                    threads=2,
                ),
            ),
        ))
Пример #15
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()
 def build_entity(self):
     sched_policy = self._get_sched_policy()
     return otypes.Cluster(
         id=self.param('id'),
         name=self.param('name'),
         comment=self.param('comment'),
         description=self.param('description'),
         ballooning_enabled=self.param('ballooning'),
         gluster_service=self.param('gluster'),
         virt_service=self.param('virt'),
         threads_as_cores=self.param('threads_as_cores'),
         ha_reservation=self.param('ha_reservation'),
         trusted_service=self.param('trusted_service'),
         optional_reason=self.param('vm_reason'),
         maintenance_reason_required=self.param('host_reason'),
         scheduling_policy=otypes.SchedulingPolicy(id=sched_policy.id, )
         if sched_policy else None,
         serial_number=otypes.SerialNumber(
             policy=otypes.SerialNumberPolicy(self.param('serial_policy')),
             value=self.param('serial_policy_value'),
         ) if (self.param('serial_policy') is not None
               or self.param('serial_policy_value') is not None) else None,
         migration=otypes.MigrationOptions(
             auto_converge=otypes.InheritableBoolean(
                 self.param('migration_auto_converge'), )
             if self.param('migration_auto_converge') else None,
             bandwidth=otypes.MigrationBandwidth(
                 assignment_method=otypes.
                 MigrationBandwidthAssignmentMethod(
                     self.param('migration_bandwidth'), )
                 if self.param('migration_bandwidth') else None,
                 custom_value=self.param('migration_bandwidth_limit'),
             ) if (self.param('migration_bandwidth')
                   or self.param('migration_bandwidth_limit')) else None,
             compressed=otypes.InheritableBoolean(
                 self.param('migration_compressed'), )
             if self.param('migration_compressed') else None,
             policy=otypes.MigrationPolicy(id=self._get_policy_id())
             if self.param('migration_policy') else None,
         ) if (self.param('migration_bandwidth') is not None
               or self.param('migration_bandwidth_limit') is not None
               or self.param('migration_auto_converge') is not None
               or self.param('migration_compressed') is not None
               or self.param('migration_policy') is not None) else None,
         error_handling=otypes.ErrorHandling(on_error=otypes.MigrateOnError(
             self.param('resilience_policy')), )
         if self.param('resilience_policy') else None,
         fencing_policy=otypes.FencingPolicy(
             enabled=self.param('fence_enabled'),
             skip_if_gluster_bricks_up=self.param(
                 'fence_skip_if_gluster_bricks_up'),
             skip_if_gluster_quorum_not_met=self.param(
                 'fence_skip_if_gluster_quorum_not_met'),
             skip_if_connectivity_broken=otypes.SkipIfConnectivityBroken(
                 enabled=self.param('fence_skip_if_connectivity_broken'),
                 threshold=self.param('fence_connectivity_threshold'),
             ) if
             (self.param('fence_skip_if_connectivity_broken') is not None
              or self.param('fence_connectivity_threshold') is not None)
             else None,
             skip_if_sd_active=otypes.SkipIfSdActive(
                 enabled=self.param('fence_skip_if_sd_active'), )
             if self.param('fence_skip_if_sd_active') is not None else None,
         ) if
         (self.param('fence_enabled') is not None
          or self.param('fence_skip_if_sd_active') is not None
          or self.param('fence_skip_if_connectivity_broken') is not None
          or self.param('fence_skip_if_gluster_bricks_up') is not None
          or self.param('fence_skip_if_gluster_quorum_not_met') is not None
          or self.param('fence_connectivity_threshold') is not None) else
         None,
         display=otypes.Display(proxy=self.param('spice_proxy'), )
         if self.param('spice_proxy') else None,
         required_rng_sources=[
             otypes.RngSource(rng) for rng in self.param('rng_sources')
         ] if self.param('rng_sources') else None,
         memory_policy=otypes.MemoryPolicy(
             over_commit=otypes.MemoryOverCommit(
                 percent=self._get_memory_policy(), ), )
         if self.param('memory_policy') else None,
         ksm=otypes.Ksm(
             enabled=self.param('ksm'),
             merge_across_nodes=not self.param('ksm_numa'),
         ) if (self.param('ksm_numa') is not None
               or self.param('ksm') is not None) else None,
         data_center=otypes.DataCenter(name=self.param('data_center'), )
         if self.param('data_center') else None,
         management_network=otypes.Network(name=self.param('network'), )
         if self.param('network') else None,
         cpu=otypes.Cpu(
             architecture=otypes.Architecture(self.param('cpu_arch'))
             if self.param('cpu_arch') else None,
             type=self.param('cpu_type'),
         ) if (self.param('cpu_arch') or self.param('cpu_type')) else None,
         version=otypes.Version(
             major=self.__get_major(self.param('compatibility_version')),
             minor=self.__get_minor(self.param('compatibility_version')),
         ) if self.param('compatibility_version') else None,
         switch_type=otypes.SwitchType(self.param('switch_type'))
         if self.param('switch_type') else None,
         mac_pool=otypes.MacPool(id=get_id_by_name(
             self._connection.system_service().mac_pools_service(),
             self.param('mac_pool'))) if self.param('mac_pool') else None,
         external_network_providers=self.
         _get_external_network_providers_entity(),
         custom_scheduling_policy_properties=[
             otypes.Property(
                 name=sp.get('name'),
                 value=str(sp.get('value')),
             ) for sp in self.param('scheduling_policy_properties') if sp
         ] if self.param('scheduling_policy_properties') is not None else
         None,
         firewall_type=otypes.FirewallType(self.param('firewall_type'))
         if self.param('firewall_type') else None,
         gluster_tuned_profile=self.param('gluster_tuned_profile'),
     )
Пример #17
0
def create_vm(kwargs, call=None):
    '''
    Create VM based on YAML file (must include parameter @ filename = "path/to/file" @ )
    - If C(cow) format is used, disk will by created as sparse, so space will be allocated for the volume as needed, also known as I(thin provision).
    - If C(raw) format is used, disk storage will be allocated right away, also known as I(preallocated).
    '''
    assert "filename" in kwargs, "Can't find filename parameter in function call"

    vm_info = parse_yaml(kwargs["filename"])

    boot_devices = []
    if "boot_first_device" in vm_info["common"]:
        if vm_info["common"]["boot_first_device"].lower() in [
                "hd", "network", "cdrom"
        ]:
            if vm_info["common"]["boot_first_device"].lower() == "hd":
                boot_devices.append(types.BootDevice.HD)
            elif vm_info["common"]["boot_first_device"].lower() == "cdrom":
                boot_devices.append(types.BootDevice.CDROM)
            elif vm_info["common"]["boot_first_device"].lower() == "network":
                boot_devices.append(types.BootDevice.NETWORK)
        else:
            boot_devices.append(None)
    if "boot_second_device" in vm_info["common"]:
        if vm_info["common"]["boot_second_device"].lower() in [
                "hd", "network", "cdrom"
        ]:
            if vm_info["common"]["boot_second_device"].lower() == "hd":
                boot_devices.append(types.BootDevice.HD)
            elif vm_info["common"]["boot_second_device"].lower() == "cdrom":
                boot_devices.append(types.BootDevice.CDROM)
            elif vm_info["common"]["boot_second_device"].lower() == "network":
                boot_devices.append(types.BootDevice.NETWORK)
        else:
            boot_devices.append(None)

    connection()
    vms_service = connection.system_service().vms_service()
    vms_service.add(
        types.Vm(
            name=vm_info["name"],
            os=types.OperatingSystem(
                type=vm_info["os_type"] if "os_type" in vm_info else "Other",
                boot=types.Boot(devices=boot_devices)),
            # type=vm_info["common"]["type"],
            placement_policy=types.VmPlacementPolicy(
                hosts=[types.Host(name=vm_info["common"]["host"])]),
            cpu=types.Cpu(topology=types.CpuTopology(
                cores=vm_info["CPU"]["cores"]
                if "cores" in vm_info["CPU"] else 1,
                sockets=vm_info["CPU"]["sockets"]
                if "sockets" in vm_info["CPU"] else 1,
                threads=vm_info["CPU"]["threads"]
                if "threads" in vm_info["CPU"] else 1,
            ), ),
            memory=1024 * 1024 * 1024 * int(vm_info["memory"]["memory"]),
            memory_policy=types.MemoryPolicy(
                guaranteed=1024 * 1024 * 1024 * vm_info["memory"]["guaranteed"]
                if "guaranteed" in vm_info["memory"] else 512 * 1024 * 1024 *
                int(vm_info["memory"]["memory"]),
                ballooning=vm_info["memory"]["ballooning"]
                if "ballooning" in vm_info["memory"] else True,
                max=1024 * 1024 * 1024 * vm_info["memory"]["maximum"]
                if "maximum" in vm_info["memory"] else 2048 * 1024 * 1024 *
                int(vm_info["memory"]["memory"]),
            ),
            cluster=types.Cluster(name=vm_info["common"]["cluster"], ),
            template=types.Template(
                name=vm_info["common"]["template"]
                if "template" in vm_info["common"] else "Blank", ),
            description=vm_info["common"]["description"]
            if "description" in vm_info["common"] else "Not provided",
            comment=vm_info["common"]["comment"]
            if "comment" in vm_info["common"] else "Not provided",
            soundcard_enabled=vm_info["common"]["soundcard_enabled"]
            if "soundcard_enabled" in vm_info["common"] else False,
        ), )

    if "disks" in vm_info:
        for disk in vm_info["disks"]:
            attach_disk(disk, vm_info["name"])
    if "networks" in vm_info:
        for network in vm_info["networks"]:
            attach_network(network, vm_info["name"])
    # Check according to salt:
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -f or --function.')
    connection.close()
    return {'Created': '{0} was created.'.format(vm_info["name"])}
Пример #18
0
 def build_entity(self):
     return otypes.InstanceType(
         id=self.param('id'),
         name=self.param('name'),
         console=(
             otypes.Console(enabled=self.param('serial_console'))
         ) if self.param('serial_console') is not None else None,
         usb=(
             otypes.Usb(enabled=self.param('usb_support'))
         ) if self.param('usb_support') is not None else None,
         high_availability=otypes.HighAvailability(
             enabled=self.param('high_availability'),
             priority=self.param('high_availability_priority'),
         ) if self.param('high_availability') is not None or self.param('high_availability_priority') else None,
         cpu=otypes.Cpu(
             topology=otypes.CpuTopology(
                 cores=self.param('cpu_cores'),
                 sockets=self.param('cpu_sockets'),
                 threads=self.param('cpu_threads'),
             ) if any((
                 self.param('cpu_cores'),
                 self.param('cpu_sockets'),
                 self.param('cpu_threads')
             )) else None,
             cpu_tune=otypes.CpuTune(
                 vcpu_pins=[
                     otypes.VcpuPin(vcpu=int(pin['vcpu']), cpu_set=str(pin['cpu'])) for pin in self.param('cpu_pinning')
                 ],
             ) if self.param('cpu_pinning') else None,
             mode=otypes.CpuMode(self.param('cpu_mode')) if self.param(
                 'cpu_mode') else None,
         ) if any((
             self.param('cpu_cores'),
             self.param('cpu_sockets'),
             self.param('cpu_threads'),
             self.param('cpu_mode'),
             self.param('cpu_pinning')
         )) else None,
         os=otypes.OperatingSystem(
             type=self.param('operating_system'),
             boot=otypes.Boot(
                 devices=[
                     otypes.BootDevice(dev) for dev in self.param('boot_devices')
                 ],
             ) if self.param('boot_devices') else None
         ),
         rng_device=otypes.RngDevice(
             source=otypes.RngSource(self.param('rng_device')),
             rate=otypes.Rate(
                 bytes=self.param('rng_bytes'),
                 period=self.param('rng_period')
             )
         ) if self.param('rng_device') else None,
         memory=convert_to_bytes(
             self.param('memory')
         ) if self.param('memory') else None,
         virtio_scsi=otypes.VirtioScsi(
             enabled=self.param('virtio_scsi')
         ) if self.param('virtio_scsi') else None,
         memory_policy=otypes.MemoryPolicy(
             guaranteed=convert_to_bytes(self.param('memory_guaranteed')),
             ballooning=self.param('ballooning_enabled'),
             max=convert_to_bytes(self.param('memory_max')),
         ) if any((
             self.param('memory_guaranteed'),
             self.param('ballooning_enabled') is not None,
             self.param('memory_max')
         )) else None,
         description=self.param('description'),
         placement_policy=otypes.VmPlacementPolicy(
             affinity=otypes.VmAffinity(self.param('placement_policy')),
             hosts=[
                 otypes.Host(name=self.param('host')),
             ] if self.param('host') else None,
         ) if self.param('placement_policy') else None,
         soundcard_enabled=self.param('soundcard_enabled'),
         display=otypes.Display(
             smartcard_enabled=self.param('smartcard_enabled')
         ) if self.param('smartcard_enabled') is not None else None,
         io=otypes.Io(
             threads=self.param('io_threads'),
         ) if self.param('io_threads') is not None else None,
     )