def get_initialization(self):
        if self._initialization is not None:
            return self._initialization

        sysprep = self.param('sysprep')
        cloud_init = self.param('cloud_init')
        cloud_init_nics = self.param('cloud_init_nics') or []
        if cloud_init is not None:
            cloud_init_nics.append(cloud_init)

        if cloud_init or cloud_init_nics:
            self._initialization = otypes.Initialization(nic_configurations=[
                otypes.NicConfiguration(
                    boot_protocol=otypes.BootProtocol(
                        nic.pop('nic_boot_protocol').lower())
                    if nic.get('nic_boot_protocol') else None,
                    name=nic.pop('nic_name', None),
                    on_boot=nic.pop('nic_on_boot', None),
                    ip=otypes.Ip(
                        address=nic.pop('nic_ip_address', None),
                        netmask=nic.pop('nic_netmask', None),
                        gateway=nic.pop('nic_gateway', None),
                    ) if (nic.get('nic_gateway') is not None
                          or nic.get('nic_netmask') is not None
                          or nic.get('nic_ip_address') is not None) else None,
                ) for nic in cloud_init_nics
                if (nic.get('nic_gateway') is not None or nic.get(
                    'nic_netmask') is not None or nic.get('nic_ip_address')
                    is not None or nic.get('nic_boot_protocol') is not None
                    or nic.get('nic_on_boot') is not None)
            ] if cloud_init_nics else None,
                                                         **cloud_init)
        elif sysprep:
            self._initialization = otypes.Initialization(**sysprep)
        return self._initialization
示例#2
0
def _get_initialization(sysprep, cloud_init, cloud_init_nics):
    initialization = None
    if cloud_init or cloud_init_nics:
        initialization = otypes.Initialization(nic_configurations=[
            otypes.NicConfiguration(
                boot_protocol=otypes.BootProtocol(
                    nic.pop('nic_boot_protocol').lower())
                if nic.get('nic_boot_protocol') else None,
                name=nic.pop('nic_name', None),
                on_boot=nic.pop('nic_on_boot', None),
                ip=otypes.Ip(
                    address=nic.pop('nic_ip_address', None),
                    netmask=nic.pop('nic_netmask', None),
                    gateway=nic.pop('nic_gateway', None),
                ) if (nic.get('nic_gateway') is not None
                      or nic.get('nic_netmask') is not None
                      or nic.get('nic_ip_address') is not None) else None,
            ) for nic in cloud_init_nics
            if (nic.get('nic_gateway') is not None or nic.get('nic_netmask')
                is not None or nic.get('nic_ip_address') is not None
                or nic.get('nic_boot_protocol') is not None
                or nic.get('nic_on_boot') is not None)
        ] if cloud_init_nics else None,
                                               **cloud_init)
    elif sysprep:
        initialization = otypes.Initialization(**sysprep)
    return initialization
示例#3
0
 def _cloud_init_vm_definition(self, cloud_init_hostname):
     if cloud_init_hostname:
         return types.Vm(initialization=types.Initialization(
             cloud_init=types.CloudInit(host=types.Host(
                 address=cloud_init_hostname))))
     else:
         return None
示例#4
0
def test_run_vms(assert_vm_is_alive, engine_api, management_gw_ip):
    engine = engine_api.system_service()

    vm_params = types.Vm(initialization=types.Initialization(
        user_name=VM_USER_NAME, root_password=VM_PASSWORD))

    vm_params.initialization.host_name = BACKUP_VM_NAME
    backup_vm_service = test_utils.get_vm_service(engine, BACKUP_VM_NAME)
    backup_vm_service.start(use_cloud_init=True, vm=vm_params)

    vm_params.initialization.host_name = VM2_NAME
    vm2_service = test_utils.get_vm_service(engine, VM2_NAME)
    vm2_service.start(use_cloud_init=True, vm=vm_params)

    # CirrOS cloud-init is different, networking doesn't work since it doesn't support the format oVirt is using
    vm_params.initialization.host_name = VM0_NAME  # hostname seems to work, the others not
    vm_params.initialization.dns_search = 'lago.local'
    vm_params.initialization.domain = 'lago.local'
    vm_params.initialization.dns_servers = management_gw_ip
    vm0_service = test_utils.get_vm_service(engine, VM0_NAME)
    vm0_service.start(use_cloud_init=True, vm=vm_params)

    for vm_name in [VM0_NAME, BACKUP_VM_NAME]:
        _verify_vm_state(engine, vm_name, types.VmStatus.UP)

    assert_vm_is_alive(VM0_NAME)
示例#5
0
 def startVMWithClouldinit(self,
                           vmname,
                           fqdn,
                           address,
                           netmask,
                           gateway,
                           dns_server,
                           dns_search,
                           nicname="eth0"):
     vms_service = self.connection.system_service().vms_service()
     vm = vms_service.list(search='name=%s' % vmname)[0]
     vm_service = vms_service.vm_service(vm.id)
     vm_service.start(
         use_cloud_init=True,
         vm=types.Vm(initialization=types.Initialization(
             # user_name='root',
             # root_password='******',
             host_name=fqdn,  # 虚拟机的hostname
             nic_configurations=[
                 types.NicConfiguration(
                     name=nicname,  # 默认网卡名为eth0 ,如果多网卡指定名称,目前不支持多网卡配置地址
                     on_boot=True,  # 网卡onboot=yes
                     boot_protocol=types.BootProtocol.STATIC,
                     ip=types.Ip(
                         version=types.IpVersion.V4,
                         address=address,  # 虚拟机的ip地址
                         netmask=netmask,  # 虚拟机的地址掩码
                         gateway=gateway  # 虚拟机的网关
                     ))
             ],
             dns_servers=dns_server,  # 虚拟机DNS服务器地址
             dns_search=dns_search,  # 虚拟机dns 查找域
         )))
def bucle2():
    try:
        vm_service.start(
            use_cloud_init=True,
            vm=types.Vm(
                initialization=types.Initialization(
                    nic_configurations=[
                        types.NicConfiguration(
                            name='eth0',
                            on_boot=True,
                            boot_protocol=types.BootProtocol.STATIC,
                            ip=types.Ip(
                                version=types.IpVersion.V4,
                                address=sys.argv[2],
                                netmask='255.255.255.0',
                                gateway='10.6.134.50'
                            )
                        )
                    ]
                )
            )
        )
    except:
	    time.sleep(100)
        bucle2()
def vm_run(prefix, api):
    host_names = [h.name() for h in prefix.virt_env.host_vms()]

    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]

    gw_ip = test_utils.get_management_net(prefix).gw()
    vm_params = types.Vm(
        placement_policy=types.VmPlacementPolicy(hosts=[
            types.Host(name="{}.{}".format(sorted(host_names)[0], DOMAIN_NAME))
        ], ),
        initialization=types.Initialization(user_name=VM_USER_NAME,
                                            root_password=VM_PASSWORD))

    vm_params.initialization.host_name = 'VM0'
    vm_params.initialization.dns_search = DOMAIN_NAME
    vm_params.initialization.domain = DOMAIN_NAME
    vm_params.initialization.dns_servers = gw_ip
    vm_params.initialization.nic_configurations = [
        types.NicConfiguration(
            name='eth0',
            boot_protocol=types.BootProtocol.STATIC,
            on_boot=True,
            ip=types.Ip(address=test_utils.get_vm0_ip_address(prefix),
                        netmask='255.255.255.0',
                        gateway=gw_ip))
    ]

    vm_service = vms_service.vm_service(vm.id)
    vm_service.start(use_cloud_init=True, vm=vm_params)

    testlib.assert_true_within_long(
        lambda: (vms_service.list(search='name=%s' % VM0_NAME)[0]).status ==
        types.VmStatus.UP, )
示例#8
0
    def start_vm(self, vm_service, cloud_init=True, scontent=None):

        vm_service.start(
            use_cloud_init=cloud_init,
            vm=types.Vm(
                initialization=types.Initialization(custom_script=scontent, )))

        #if vm no start down
        while True:
            break
def create_vm_from_ovf(ovf_file_path, vms_service):
    """
    Creates a new VM from the specified OVF
    """
    ovf_data = open(ovf_file_path, 'r').read()
    vm = vms_service.add(
        types.Vm(
            cluster=types.Cluster(name='Default', ),
            initialization=types.Initialization(
                configuration=types.Configuration(
                    type=types.ConfigurationType.OVF, data=ovf_data)),
        ), )
    return vm.id
示例#10
0
 def start_vm_cloud_init(self, vm_service, vm, use_cloud_init=True):
     vm_service.start(use_cloud_init=use_cloud_init,
                      vm=types.Vm(initialization=types.Initialization(
                          nic_configurations=[
                              types.NicConfiguration(
                                  name='eth0',
                                  on_boot=True,
                                  boot_protocol=types.BootProtocol.STATIC,
                                  ip=types.Ip(version=types.IpVersion.V4,
                                              address=vm.ip.ip,
                                              netmask=vm.ip.netmask,
                                              gateway=vm.ip.gateway))
                          ],
                          dns_servers='8.8.8.8',
                      )))
示例#11
0
def vm_run(prefix):
    engine = prefix.virt_env.engine_vm()
    api = engine.get_api_v4()
    host_names = [h.name() for h in prefix.virt_env.host_vms()]

    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]
    vm_service = vms_service.vm_service(vm.id)
    vm_service.start(use_cloud_init=True,
                     vm=types.Vm(placement_policy=types.VmPlacementPolicy(
                         hosts=[types.Host(name=sorted(host_names)[0])], ),
                                 initialization=types.Initialization(
                                     domain='lago.example.com',
                                     cloud_init=types.CloudInit(
                                         host=types.Host(address='VM0'), ),
                                 )))
    testlib.assert_true_within_long(
        lambda: (vms_service.list(search='name=%s' % VM0_NAME)[0]).status ==
        types.VmStatus.UP, )
示例#12
0
def test_ovf_import(api_v4):
    # Read the OVF file and replace the disk id
    engine = api_v4.system_service()
    disk_service = test_utils.get_disk_service(engine, DISK0_NAME)
    disk_id = disk_service.get().id
    ovf_file = os.path.join(os.environ['SUITE'], 'files', 'test-vm.ovf')
    ovf_text = open(ovf_file).read()
    ovf_text = ovf_text.replace(
        "ovf:diskId='52df5324-2230-40d9-9d3d-8cbb2aa33ba6'",
        "ovf:diskId='%s'" % (disk_id, ))
    # Upload OVF
    vms_service = engine.vms_service()
    vms_service.add(
        types.Vm(name=OVF_VM_NAME,
                 cluster=types.Cluster(name=TEST_CLUSTER, ),
                 initialization=types.Initialization(
                     configuration=types.Configuration(
                         type=types.ConfigurationType.OVA, data=ovf_text))))
    # Check the VM exists
    assert test_utils.get_vm_service(engine, OVF_VM_NAME) is not None
示例#13
0
def test_run_vms(prefix):
    engine = prefix.virt_env.engine_vm().get_api_v4().system_service()

    vm_params = types.Vm(initialization=types.Initialization(
        user_name=VM_USER_NAME, root_password=VM_PASSWORD))

    vm_params.initialization.host_name = BACKUP_VM_NAME
    backup_vm_service = test_utils.get_vm_service(engine, BACKUP_VM_NAME)
    backup_vm_service.start(use_cloud_init=True, vm=vm_params)

    vm_params.initialization.host_name = VM2_NAME
    vm2_service = test_utils.get_vm_service(engine, VM2_NAME)
    vm2_service.start(use_cloud_init=True, vm=vm_params)

    gw_ip = test_utils.get_management_net(prefix).gw()

    vm_params.initialization.host_name = VM0_NAME
    vm_params.initialization.dns_search = 'lago.local'
    vm_params.initialization.domain = 'lago.local'
    vm_params.initialization.dns_servers = gw_ip
    vm_params.initialization.nic_configurations = [
        types.NicConfiguration(
            name='eth0',
            boot_protocol=types.BootProtocol.STATIC,
            on_boot=True,
            ip=types.Ip(address=test_utils.get_vm0_ip_address(prefix),
                        netmask='255.255.255.0',
                        gateway=gw_ip))
    ]
    vm0_service = test_utils.get_vm_service(engine, VM0_NAME)
    vm0_service.start(use_cloud_init=True, vm=vm_params)

    for vm_name in [VM0_NAME, BACKUP_VM_NAME]:
        _verify_vm_state(engine, vm_name, types.VmStatus.UP)

    assert_vm0_is_alive(prefix)
示例#14
0
文件: __init__.py 项目: openpabz/kcli
    def create(self,
               name,
               virttype='kvm',
               profile='',
               flavor=None,
               plan='kvirt',
               cpumodel='Westmere',
               cpuflags=[],
               numcpus=2,
               memory=512,
               guestid='guestrhel764',
               pool='default',
               template=None,
               disks=[{
                   'size': 10
               }],
               disksize=10,
               diskthin=True,
               diskinterface='virtio',
               nets=['default'],
               iso=None,
               vnc=False,
               cloudinit=True,
               reserveip=False,
               reservedns=False,
               reservehost=False,
               start=True,
               keys=None,
               cmds=[],
               ips=None,
               netmasks=None,
               gateway=None,
               nested=True,
               dns=None,
               domain=None,
               tunnel=False,
               files=[],
               enableroot=True,
               alias=[],
               overrides={},
               tags=None):
        """

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

# Add the virtual machine, the transfered disks will be
# attached to this virtual machine:
print ("adding the virtual machine %s" % vm_name)
vms_service = connection.system_service().vms_service()
vm = vms_service.add(
    types.Vm(
        cluster=types.Cluster(
            name=target_cluster_name,
        ),
        initialization=types.Initialization(
            configuration=types.Configuration(
                type=types.ConfigurationType.OVA,
                data=ovf_str
            )
        ),
    ),
)

# Close the OVA file
ova_file.close()

# Close the connection:
connection.close()
import ovirtsdk4.types as types
import conexion as conn
import sys

connection = conn.createconnection()

# Find the virtual machine:
vms_service = connection.system_service().vms_service()
vm = vms_service.list(search='name=' + sys.argv[1])[0]

# Find the service that manages the virtual machine:
vm_service = vms_service.vm_service(vm.id)

# Start the virtual machine enabling cloud-init and providing the
# password for the `root` user and the network configuration:
vm_service.start(
    use_cloud_init=True,
    vm=types.Vm(initialization=types.Initialization(nic_configurations=[
        types.NicConfiguration(name='eth0',
                               on_boot=True,
                               boot_protocol=types.BootProtocol.STATIC,
                               ip=types.Ip(version=types.IpVersion.V4,
                                           address=sys.argv[2],
                                           netmask='255.255.255.0',
                                           gateway='10.6.134.50'))
    ])))

# Close the connection to the server:
connection.close()
def create_vms(cluster_nodes, args):
    """ creates the vms in cluster_nodes list, and skipps if they exist """
    vm_dict = {}
    to_create = []

    # Figure out which nodes we need to create, and which are already running
    for node in cluster_nodes:
        print("node=%s" % (node), file=sys.stderr)
        tmp = vms_service.list(search=construct_search_by_name_query(node))
        if len(tmp) == 1:
            vm_dict[node] = vms_service.vm_service(tmp[0].id)
            print("VM %s was found ... skipping creation" % (node),
                  file=sys.stderr)
        else:
            to_create.append(node)

    # Create the VM in "blocks"
    for block in chunks(to_create, args.block_size):
        block_futures = []
        for node in block:
            vm_future = vms_service.add(types.Vm(
                name=node,
                cluster=types.Cluster(name=args.ovirt_cluster),
                template=types.Template(name=args.ovirt_template)),
                                        wait=False)
            block_futures.append((node, vm_future))
        # wait for all the VMs from this block to be created
        for node_name, future_vm in block_futures:
            vm = future_vm.wait()
            vm_dict[node_name] = vms_service.vm_service(vm.id)
        # sleep before the next block
        time.sleep(args.sleep_between_iterations)

    # Start each VM when it's created, but try to batch the calls
    counter = 1
    starting = set()
    pub_sshkey = os.environ[args.pub_sshkey]
    # number of attempts is bigger here because it's not attempts per VM
    # like in the other nodes.
    while counter < args.num_of_iterations * len(cluster_nodes):
        start_futures = []
        for node_name, vm_service in vm_dict.items():
            if node_name in starting:
                continue
            vm = vm_service.get()
            print("%s: vm.status = %s" % (node_name, vm.status),
                  file=sys.stderr)
            if vm.status == types.VmStatus.DOWN:
                print("%s: starting" % (node_name), file=sys.stderr)
                future = vm_service.start(
                    use_cloud_init=True,
                    wait=False,
                    vm=types.Vm(initialization=types.Initialization(
                        authorized_ssh_keys=pub_sshkey)))
                start_futures.append(future)
                starting.add(node_name)
            elif vm.status == types.VmStatus.UP:
                # make sure we don't wait forever for VMs to be down when they're
                # already up.
                starting.add(node_name)

        # wait for this batch of VMs
        print("batch size = %s" % len(start_futures))
        for future in start_futures:
            future.wait()

        if len(starting) == len(cluster_nodes):
            # We called .start() on all VMs
            break

        time.sleep(args.sleep_between_iterations)
        counter += 1
    else:
        # else clause on while will run when while is finished without "break".
        # This means not all VMs were created, and that's an error
        not_started = set(cluster_nodes) - set(starting)
        total_time_waited = args.num_of_iterations * args.sleep_between_iterations
        print("ERROR - VMs {0} still not created after {1} seconds".format(
            not_started, total_time_waited),
              file=sys.stderr)
        sys.exit(-1)

    # Wait for all the VMs to be up before we wait for IPs,
    # this serves two functions:
    # 1) a more useful error message if the VM takes too long to start
    # 2) effectively a more graceful timeout waiting for IPs
    for node, vm_service in vm_dict.items():
        counter = 1
        while counter < args.num_of_iterations:
            vm = vm_service.get()
            print("%s: vm.status = %s, vm.fqdn= '%s'" %
                  (node, vm.status, vm.fqdn),
                  file=sys.stderr)
            if vm.status == types.VmStatus.UP:
                break
            counter += 1
            time.sleep(args.sleep_between_iterations)

        if vm.status != types.VmStatus.UP:
            print("ERROR - VM {0} still not up after {1} retries".format(
                node, args.num_of_iterations),
                  file=sys.stderr)
            sys.exit(-1)

    ips_dict = {}
    for node, vm_service in vm_dict.items():
        ip = None
        counter = 1
        while counter < args.num_of_iterations:
            ip = find_vm_ip(vm_service)
            if ip is not None:
                break
            counter += 1
            msg = "{0} waiting for ip... {1}/{2} attempts".format(
                node, counter, args.num_of_iterations)
            print(msg, file=sys.stderr)
            time.sleep(args.sleep_between_iterations)

        if ip is None:
            print("ERROR - Node {0} still has no IP after {1} retries".format(
                node, args.num_of_iterations),
                  file=sys.stderr)
            sys.exit(-1)
        ips_dict[node] = ip

    print_ips(ips_dict)
#open the sysprep template file
f = open("~/ansible/roles/ovirt_windows/library/sysprep_2k12R2", "r")

#get and split dns retrieved from ansible params
dns = module.params['dns_servers'].split()

#read the sysprep template
sysprep_template = Template(f.read())

#replace sysprep template variables with vm paramenters retrieved from the playbook
d = {
    'hostname': module.params['hostname'],
    'admin_password': module.params['admin_password'],
    'dns_server1': dns[0],
    'dns_server2': dns[1],
    'dns_search': module.params['dns_search'],
    'nic_ip_address': module.params['nic_ip_address'],
    'nic_netmask': module.params['nic_netmask'],
    'nic_gateway': module.params['nic_gateway']
}

sysprep = sysprep_template.substitute(d)

# Start the virtual machine passing the sysprep
vm_service.start(
    use_sysprep=True,
    vm=types.Vm(initialization=types.Initialization(custom_script=sysprep, )))

module.exit_json(changed=True, msg="VM initialized with sysprep done")
connection.close(logout=False)
示例#20
0
        vm_or_template_name = ovf.xpath(
            '/ovf:Envelope/ovf:VirtualSystem/ovf:Name',
            namespaces=namespaces)[0].text

        # Add the virtual machine or template, the transferred disks will be attached to
        # this virtual machine or template:
        progress("Adding {} {}".format(
            'template' if args.template else 'virtual machine',
            vm_or_template_name))

        if args.template:
            templates_service = connection.system_service().templates_service()
            template = templates_service.add(
                types.Template(
                    cluster=types.Cluster(name=args.cluster_name, ),
                    initialization=types.Initialization(
                        configuration=types.Configuration(
                            type=types.ConfigurationType.OVA,
                            data=ovf_str.decode("utf-8"))),
                ), )
        else:
            vms_service = connection.system_service().vms_service()
            vm = vms_service.add(
                types.Vm(
                    cluster=types.Cluster(name=args.cluster_name, ),
                    initialization=types.Initialization(
                        configuration=types.Configuration(
                            type=types.ConfigurationType.OVA,
                            data=ovf_str.decode("utf-8"))),
                ), )
示例#21
0
logging.basicConfig(level=logging.DEBUG, filename='example.log')

# This example will connect to the server and create a new virtual machine:

# Create the connection to the server:
connection = sdk.Connection(
    url='https://engine.localdomain/ovirt-engine/api',
    username='******',
    password='******',
    ca_file='ca.crt',
    debug=True,
    log=logging.getLogger(),
)

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

# Use the "add" method to create a new virtual machine:

ovf_file_path = '/data/ovirtbackup/winxp-e55cebcc-f354-4b66-b858-a11e1c647f1a.ovf'
ovf_data = open(ovf_file_path, 'r').read()
vm = vms_service.add(
    types.Vm(
        cluster=types.Cluster(name='Default', ),
        initialization=types.Initialization(configuration=types.Configuration(
            type=types.ConfigurationType.OVF, data=ovf_data)),
    ), )

# Close the connection to the server:
connection.close()
示例#22
0
  - content: |
      Hello, world!
    path: /tmp/greeting.txt
    permissions: '0644'
"""

# Start the virtual machine enabling cloud-init and providing the
# password for the `root` user and the network configuration:
vm_service.start(
    use_cloud_init=True,
    vm=types.Vm(initialization=types.Initialization(
        user_name='root',
        root_password='******',
        host_name='myvm.example.com',
        nic_configurations=[
            types.NicConfiguration(name='eth0',
                                   on_boot=True,
                                   boot_protocol=types.BootProtocol.STATIC,
                                   ip=types.Ip(version=types.IpVersion.V4,
                                               address='192.168.0.100',
                                               netmask='255.255.255.0',
                                               gateway='192.168.0.1'))
        ],
        dns_servers='192.168.0.1 192.168.0.2 192.168.0.3',
        dns_search='example.com',
        custom_script=my_script,
    )))

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