예제 #1
0
 def set_boot_device(self, bootdevice):
     if bootdevice == 'network':
         self.server.update(vm=types.Vm(os=types.OperatingSystem(
             boot=types.Boot(devices=[types.BootDevice.NETWORK]))))
     else:
         self.server.update(vm=types.Vm(os=types.OperatingSystem(
             boot=types.Boot(devices=[types.BootDevice.HD]))))
     self.log('Set boot device to', bootdevice)
예제 #2
0
def createVM(session):
    """ Creates a virtual maschine """

    print "\n\n=================[ CREATING VMS ]================="

    try:
        for vm in configFile['vms']:
            hostname    = vm['hostname']
            cluster        = vm['cluster']
            template    = vm['template']
            memory        = vm['memory']

            vmService = session.system_service().vms_service()
                    vm = vmService.add(
                            types.Vm(
                                    name=hostname,
                                    memory = memory * 2**30,
                                    cluster=types.Cluster(
                                            name=cluster),
                                    template=types.Template(
                                            name=template),
                                    os=types.OperatingSystem(
                                            boot=types.Boot(
                                                    devices=[types.BootDevice.HD])),
                                    )
                            )
            print ("Created VM \"%s\" on cluster \"%s\" with template \"%s\"." % (hostname, cluster, template))
    except Exception as e:
        print str(e)
        sys.exit(1)
 def build_entity(self):
     return otypes.Host(
         id=self._module.params.get('id'),
         name=self.param('name'),
         cluster=otypes.Cluster(
             name=self.param('cluster')
         ) if self.param('cluster') else None,
         comment=self.param('comment'),
         address=self.param('address'),
         root_password=self.param('password'),
         ssh=otypes.Ssh(
             authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY if self.param('public_key') else None,
             port=self.param('ssh_port'),
         ),
         spm=otypes.Spm(
             priority=self.param('spm_priority'),
         ) if self.param('spm_priority') else None,
         override_iptables=self.param('override_iptables'),
         display=otypes.Display(
             address=self.param('override_display'),
         ) if self.param('override_display') else None,
         os=otypes.OperatingSystem(
             custom_kernel_cmdline=' '.join(self.param('kernel_params')),
         ) if self.param('kernel_params') else None,
         power_management=otypes.PowerManagement(
             enabled=self.param('power_management_enabled'),
             kdump_detection=self.param('kdump_integration') == 'enabled',
         ) if self.param('power_management_enabled') is not None or self.param('kdump_integration') else None,
         vgpu_placement=otypes.VgpuPlacement(
             self.param('vgpu_placement')
         ) if self.param('vgpu_placement') is not None else None,
     )
예제 #4
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,
     )
예제 #5
0
    def set_boot_device(self, task, device, persistent=False):
        """Set the boot device for a node.

        :param task: a task from TaskManager.
        :param device: ironic.common.boot_devices
        :param persistent: This argument is ignored.
        :raises: MissingParameterValue, if some required parameter(s) are
            missing in the node's driver_info.
        :raises: InvalidParameterValue, if some parameter(s) have invalid
            value(s) in the node's driver_info.
        """
        try:
            boot_dev = IRONIC_TO_OVIRT_DEVICE_MAPPING[device]
        except KeyError:
            raise exception.InvalidParameterValue(
                _("Invalid boot device %s specified.") % device)

        driver_info = _parse_driver_info(task.node)
        vm = _getvm(driver_info)
        try:
            boot = otypes.Boot(devices=[otypes.BootDevice(boot_dev)])
            bootos = otypes.OperatingSystem(boot=boot)
            vm.update(otypes.Vm(os=bootos))
        except sdk.Error as e:
            LOG.error(
                "Setting boot device failed for node %(node_id)s "
                "with error: %(error)s", {
                    'node_id': task.node.uuid,
                    'error': e
                })
            raise staging_exception.OVirtError(err=e)
예제 #6
0
 def build_entity(self):
     return otypes.Host(
         name=self._module.params['name'],
         cluster=otypes.Cluster(
             name=self._module.params['cluster']
         ) if self._module.params['cluster'] else None,
         comment=self._module.params['comment'],
         address=self._module.params['address'],
         root_password=self._module.params['password'],
         ssh=otypes.Ssh(
             authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY,
         ) if self._module.params['public_key'] else None,
         kdump_status=otypes.KdumpStatus(
             self._module.params['kdump_integration']
         ) if self._module.params['kdump_integration'] else None,
         spm=otypes.Spm(
             priority=self._module.params['spm_priority'],
         ) if self._module.params['spm_priority'] else None,
         override_iptables=self._module.params['override_iptables'],
         display=otypes.Display(
             address=self._module.params['override_display'],
         ) if self._module.params['override_display'] else None,
         os=otypes.OperatingSystem(
             custom_kernel_cmdline=' '.join(self._module.params['kernel_params']),
         ) if self._module.params['kernel_params'] else None,
     )
예제 #7
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,
     )
 def build_entity(self):
     return otypes.Host(
         name=self.param('name'),
         cluster=otypes.Cluster(
             name=self.param('cluster')
         ) if self.param('cluster') else None,
         comment=self.param('comment'),
         address=self.param('address'),
         root_password=self.param('password'),
         ssh=otypes.Ssh(
             authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY,
         ) if self.param('public_key') else None,
         kdump_status=otypes.KdumpStatus(
             self.param('kdump_integration')
         ) if self.param('kdump_integration') else None,
         spm=otypes.Spm(
             priority=self.param('spm_priority'),
         ) if self.param('spm_priority') else None,
         override_iptables=self.param('override_iptables'),
         display=otypes.Display(
             address=self.param('override_display'),
         ) if self.param('override_display') else None,
         os=otypes.OperatingSystem(
             custom_kernel_cmdline=' '.join(self.param('kernel_params')),
         ) if self.param('kernel_params') else None,
         power_management=otypes.PowerManagement(
             enabled=self.param('power_management_enabled'),
         ) if self.param('power_management_enabled') is not None else None,
     )
예제 #9
0
 def boot_device(self, vmname, bootdevice):
     if bootdevice == "network":
         vm = self.find_vm(vmname)
         vm_service = self.vms_service.vm_service(vm.id)
         vm_service.update(vm=types.Vm(os=types.OperatingSystem(
             boot=types.Boot(devices=[types.BootDevice.NETWORK]))))
     if bootdevice == "hd":
         vm = self.find_vm(vmname)
         vm_service = self.vms_service.vm_service(vm.id)
         vm_service.update(vm=types.Vm(os=types.OperatingSystem(
             boot=types.Boot(devices=[types.BootDevice.HD]))))
     if bootdevice == "optical":
         vm = self.find_vm(vmname)
         vm_service = self.vms_service.vm_service(vm.id)
         vm_service.update(vm=types.Vm(os=types.OperatingSystem(
             boot=types.Boot(devices=[types.BootDevice.CDROM]))))
     return
예제 #10
0
def start_vm_with_pxe(api, options):
    """Add PXE Boot option to vm."""
    search_name = "name=" + options['vm_name']
    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search=search_name)[0]
    vm_service = vms_service.vm_service(vm.id)
    vm_service.start(vm=types.Vm(os=types.OperatingSystem(boot=types.Boot(
        devices=[types.BootDevice.HD, types.BootDevice.NETWORK]))))
예제 #11
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(),
     )
예제 #13
0
def start_vm_with_cdrom(api, vm_id, isoname='ks.iso'):
    """Add CDROM and boot vm."""
    vms_service = api.system_service().vms_service()
    vm_service = vms_service.vm_service(vm_id)
    cdroms_service = vm_service.cdroms_service()
    cdrom = cdroms_service.list()[0]
    cdrom_service = cdroms_service.cdrom_service(cdrom.id)
    cdrom_service.update(
        cdrom=types.Cdrom(file=types.File(id=isoname), ),
        current=False,
    )
    vm_service.start(vm=types.Vm(os=types.OperatingSystem(boot=types.Boot(
        devices=[types.BootDevice.HD, types.BootDevice.CDROM]))))
예제 #14
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,
     )
예제 #15
0
def start_vm_with_cdrom(api, options):
    """Add CDROM and boot vm."""
    search_name = "name=" + options['vm_name']
    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search=search_name)[0]
    vm_service = vms_service.vm_service(vm.id)
    cdroms_service = vm_service.cdroms_service()
    cdrom = cdroms_service.list()[0]
    cdrom_service = cdroms_service.cdrom_service(cdrom.id)
    cdrom_service.update(
        cdrom=types.Cdrom(file=types.File(id=options['cdrom']), ),
        current=False,
    )
    vm_service.start(vm=types.Vm(os=types.OperatingSystem(boot=types.Boot(
        devices=[types.BootDevice.HD, types.BootDevice.CDROM]))))
예제 #16
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,
                ),
            ),
        ))
예제 #17
0
def add_vm(api, options):
    """Adding a VM."""
    vms_service = api.system_service().vms_service()
    try:
        vms_service.add(
            types.Vm(
                name=options['vm_name'],
                memory=options['vmem'],
                cpu=types.Cpu(topology=options['vcpus']),
                type=types.VmType('server'),
                os=types.OperatingSystem(type=options['os_type']),
                cluster=types.Cluster(name=options['vm_dc'], ),
                template=types.Template(name='Blank', ),
            ), )
    except Exception as e:
        print "Can't add VM: %s" % str(e)
        api.close()
        sys.exit(1)
예제 #18
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,
                ),
            ),
        ))
예제 #19
0
def add_vm_blank(api):
    engine = api.system_service()
    vms = engine.vms_service()

    new_vm = types.Vm(
        os=types.OperatingSystem(
            type='other_linux',
            boot=types.Boot(devices=[types.BootDevice.NETWORK])
        ),
        type=types.VmType.SERVER,
        cluster=types.Cluster(name=TEST_CLUSTER),
        template=types.Template(name=TEMPLATE_BLANK),
        name=VM_NAME
    )
    new_vm = vms.add(new_vm)

    vm_service = vms.vm_service(new_vm.id)
    testlib.assert_true_within_short(
        lambda: vm_service.get().status == types.VmStatus.DOWN
    )
예제 #20
0
def startVMOverNetwork(session):
    """ Starts created virtual machines via pxe"""
        print "\n\n=================[ BOOTING VMS OVER NETWORK ]================="

        for vm in configFile['vms']:
        hostname        = vm['hostname']
                vmService       = session.system_service().vms_service()
                machine         = vmService.list(search='name=%s' % str(hostname))[0]
        startService    = vmService.vm_service(machine.id)


        startService.start(
                vm=types.Vm(
                os=types.OperatingSystem(
                    boot=types.Boot(
                    devices=[
                            types.BootDevice.NETWORK,
                            types.BootDevice.CDROM
                        ]
                    )
                )
                )
        )
        print "Booting \"%s\"." % (hostname)
예제 #21
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()
예제 #22
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'running', 'stopped', 'present', 'absent', 'suspended',
                'next_run'
            ],
            default='present',
        ),
        name=dict(default=None),
        id=dict(default=None),
        cluster=dict(default=None),
        template=dict(default=None),
        template_version=dict(default=None, type='int'),
        use_latest_template_version=dict(default=None, type='bool'),
        disks=dict(default=[], type='list'),
        memory=dict(default=None),
        memory_guaranteed=dict(default=None),
        cpu_sockets=dict(default=None, type='int'),
        cpu_cores=dict(default=None, type='int'),
        cpu_shares=dict(default=None, type='int'),
        type=dict(choices=['server', 'desktop']),
        operating_system=dict(
            default=None,
            choices=[
                'rhel_6_ppc64',
                'other',
                'freebsd',
                'windows_2003x64',
                'windows_10',
                'rhel_6x64',
                'rhel_4x64',
                'windows_2008x64',
                'windows_2008R2x64',
                'debian_7',
                'windows_2012x64',
                'ubuntu_14_04',
                'ubuntu_12_04',
                'ubuntu_13_10',
                'windows_8x64',
                'other_linux_ppc64',
                'windows_2003',
                'other_linux',
                'windows_10x64',
                'windows_2008',
                'rhel_3',
                'rhel_5',
                'rhel_4',
                'other_ppc64',
                'sles_11',
                'rhel_6',
                'windows_xp',
                'rhel_7x64',
                'freebsdx64',
                'rhel_7_ppc64',
                'windows_7',
                'rhel_5x64',
                'ubuntu_14_04_ppc64',
                'sles_11_ppc64',
                'windows_8',
                'windows_2012R2x64',
                'windows_2008r2x64',
                'ubuntu_13_04',
                'ubuntu_12_10',
                'windows_7x64',
            ],
        ),
        cd_iso=dict(default=None),
        boot_devices=dict(default=None, type='list'),
        high_availability=dict(type='bool'),
        stateless=dict(type='bool'),
        delete_protected=dict(type='bool'),
        force=dict(type='bool', default=False),
        nics=dict(default=[], type='list'),
        cloud_init=dict(type='dict'),
        cloud_init_nics=dict(defaul=[], type='list'),
        sysprep=dict(type='dict'),
        host=dict(default=None),
        clone=dict(type='bool', default=False),
        clone_permissions=dict(type='bool', default=False),
        kernel_path=dict(default=None),
        initrd_path=dict(default=None),
        kernel_params=dict(default=None),
        instance_type=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        timezone=dict(default=None),
        serial_policy=dict(default=None, choices=['vm', 'host', 'custom']),
        serial_policy_value=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        state = module.params['state']
        connection = create_connection(module.params.pop('auth'))
        vms_service = connection.system_service().vms_service()
        vms_module = VmsModule(
            connection=connection,
            module=module,
            service=vms_service,
        )
        vm = vms_module.search_entity()

        control_state(vm, vms_service, module)
        if state == 'present' or state == 'running' or state == 'next_run':
            sysprep = module.params['sysprep']
            cloud_init = module.params['cloud_init']
            cloud_init_nics = module.params['cloud_init_nics'] or []
            if cloud_init is not None:
                cloud_init_nics.append(cloud_init)

            # In case VM don't exist, wait for VM DOWN state,
            # otherwise don't wait for any state, just update VM:
            vms_module.create(
                entity=vm,
                result_state=otypes.VmStatus.DOWN if vm is None else None,
                clone=module.params['clone'],
                clone_permissions=module.params['clone_permissions'],
            )
            ret = vms_module.action(
                action='start',
                post_action=vms_module._post_start_action,
                action_condition=lambda vm: (vm.status not in [
                    otypes.VmStatus.MIGRATING,
                    otypes.VmStatus.POWERING_UP,
                    otypes.VmStatus.REBOOT_IN_PROGRESS,
                    otypes.VmStatus.WAIT_FOR_LAUNCH,
                    otypes.VmStatus.UP,
                    otypes.VmStatus.RESTORING_STATE,
                ]),
                wait_condition=lambda vm: vm.status == otypes.VmStatus.UP,
                # Start action kwargs:
                use_cloud_init=cloud_init is not None
                or len(cloud_init_nics) > 0,
                use_sysprep=sysprep is not None,
                vm=otypes.Vm(
                    placement_policy=otypes.VmPlacementPolicy(
                        hosts=[otypes.Host(name=module.params['host'])])
                    if module.params['host'] else None,
                    initialization=_get_initialization(sysprep, cloud_init,
                                                       cloud_init_nics),
                    os=otypes.OperatingSystem(
                        cmdline=module.params.get('kernel_params'),
                        initrd=module.params.get('initrd_path'),
                        kernel=module.params.get('kernel_path'),
                    ),
                ),
            )

            if state == 'next_run':
                # Apply next run configuration, if needed:
                vm = vms_service.vm_service(ret['id']).get()
                if vm.next_run_configuration_exists:
                    ret = vms_module.action(
                        action='reboot',
                        entity=vm,
                        action_condition=lambda vm: vm.status == otypes.
                        VmStatus.UP,
                        wait_condition=lambda vm: vm.status == otypes.VmStatus.
                        UP,
                    )
        elif state == 'stopped':
            vms_module.create(
                result_state=otypes.VmStatus.DOWN if vm is None else None,
                clone=module.params['clone'],
                clone_permissions=module.params['clone_permissions'],
            )
            if module.params['force']:
                ret = vms_module.action(
                    action='stop',
                    post_action=vms_module._attach_cd,
                    action_condition=lambda vm: vm.status != otypes.VmStatus.
                    DOWN,
                    wait_condition=lambda vm: vm.status == otypes.VmStatus.
                    DOWN,
                )
            else:
                ret = vms_module.action(
                    action='shutdown',
                    pre_action=vms_module._pre_shutdown_action,
                    post_action=vms_module._attach_cd,
                    action_condition=lambda vm: vm.status != otypes.VmStatus.
                    DOWN,
                    wait_condition=lambda vm: vm.status == otypes.VmStatus.
                    DOWN,
                )
        elif state == 'suspended':
            vms_module.create(
                result_state=otypes.VmStatus.DOWN if vm is None else None,
                clone=module.params['clone'],
                clone_permissions=module.params['clone_permissions'],
            )
            ret = vms_module.action(
                action='suspend',
                pre_action=vms_module._pre_suspend_action,
                action_condition=lambda vm: vm.status != otypes.VmStatus.
                SUSPENDED,
                wait_condition=lambda vm: vm.status == otypes.VmStatus.
                SUSPENDED,
            )
        elif state == 'absent':
            ret = vms_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
예제 #23
0
    password=RHVMPass,
    ca_file='/etc/pki/vdsm/certs/cacert.pem',
)

# Get the reference to the "vms" service:
vms_service = connection.system_service().vms_service()

vm = types.Vm()
vm.name = VMName
vm.comment = VMComment
vm.description = VMDescription
cpu = types.CpuTopology(cores=VMCores, sockets=VMSockets)
vm.cpu = types.Cpu(topology=cpu)
vm.cluster = types.Cluster(name=VMCluster)
vm.template = types.Template(name=VMTemplate)
vm.os = types.OperatingSystem(boot=types.Boot(devices=[types.BootDevice.HD]),
                              type='rhel_8x64')
#vm.instance_type = types.InstanceType(id="00000003-0003-0003-0003-0000000000be")
vm.memory = VMMemory
vm.time_zone = types.TimeZone(name='Asia/Tehran')
netlist = connection.system_service().operating_systems_service().list()
for host in netlist:
    if host.name == 'rhel_8x64':
        myos = host
        print("%s (%s)" % (host.name, host.id))
vm.type = types.VmType.SERVER
vm.soundcard_enabled = False
provider = connection.system_service().external_host_providers_service().list(
)[0]
#vm.externalhostproviders = types.ExternalHostProvider(id='d78051b5-37c8-43bc-8eeb-04e49e59bf3')
#vm.memory_policy=types.MemoryPolicy( guaranteed=VMMemoryGuaranteed )
vms_service.add(vm)
예제 #24
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,
     )
예제 #25
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"])}
예제 #26
0
)

# Get the reference to the "vms" service:
vms_service = connection.system_service().vms_service()

# Find the virtual machine:
vm = vms_service.list(search='name=myvm')[0]

# Locate the service that manages the virtual machine, as that is where
# the action methods are defined:
vm_service = vms_service.vm_service(vm.id)

# Call the "start" method of the service to start it with
# additional properties in a run once configuration

vm_service.start(vm=types.Vm(os=types.OperatingSystem(boot=types.Boot(
    devices=[types.BootDevice.NETWORK, types.BootDevice.CDROM]))))

# additional documentation about attributes and types that can be changed:
# https://your.rhv.host/ovirt-engine/api/model#types/vm
# https://your.rhv.host/ovirt-engine/api/model#types/operating_system
# https://your.rhv.host/ovirt-engine/api/model#types/boot
# https://your.rhv.host/ovirt-engine/api/model#types/boot_device

# Wait till the virtual machine is up:
while True:
    time.sleep(5)
    vm = vm_service.get()
    if vm.status == types.VmStatus.UP:
        break

# Close the connection to the server:
예제 #27
0
vm_service = vms_service.vm_service(vm.id)

# Wait till the virtual machine is down, which indicats that all the
# disks have been created:
while True:
    time.sleep(5)
    vm = vm_service.get()
    if vm.status == types.VmStatus.DOWN:
        break

# The content of the Unattend.xml file. Note that this is an incomplete
# file, make sure to use a complete one, maybe
# reading it from an external file.
unattend_xml = '''\
<?xml version="1.0" encoding="UTF-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
  ...
</unattend>
'''

# Start the virtual machine enabling sysprep. Make sure to use a Windows
# operating system, either in the template, or overriding it explicitly
# here. Without that the Sysprep logic won't be triggered.
vm_service.start(use_sysprep=True,
                 vm=types.Vm(os=types.OperatingSystem(type='windows_7x64'),
                             initialization=types.Initialization(
                                 custom_script=unattend_xml)))

# Close the connection to the server:
connection.close()
예제 #28
0
def start_vm_with_pxe(api, vm_id):
    """Add PXE Boot option to vm."""
    vms_service = api.system_service().vms_service()
    vm_service = vms_service.vm_service(vm_id)
    vm_service.start(vm=types.Vm(os=types.OperatingSystem(boot=types.Boot(
        devices=[types.BootDevice.HD, types.BootDevice.NETWORK]))))