コード例 #1
0
ファイル: ovirt_tags.py プロジェクト: awiddersheim/ansible
    def _update_tag_assignments(self, entity, name):
        if self._module.params[name] is None:
            return

        state = self.param('state')
        entities_service = getattr(self._connection.system_service(), '%s_service' % name)()
        current_vms = [
            vm.name
            for vm in entities_service.list(search='tag=%s' % self._module.params['name'])
        ]
        # Assign tags:
        if state in ['present', 'attached', 'detached']:
            for entity_name in self._module.params[name]:
                entity_id = get_id_by_name(entities_service, entity_name)
                tags_service = entities_service.service(entity_id).tags_service()
                current_tags = [tag.name for tag in tags_service.list()]
                # Assign the tag:
                if state in ['attached', 'present']:
                    if self._module.params['name'] not in current_tags:
                        if not self._module.check_mode:
                            tags_service.add(
                                tag=otypes.Tag(
                                    name=self._module.params['name'],
                                ),
                            )
                        self.changed = True
                # Detach the tag:
                elif state == 'detached':
                    if self._module.params['name'] in current_tags:
                        tag_id = get_id_by_name(tags_service, self.param('name'))
                        if not self._module.check_mode:
                            tags_service.tag_service(tag_id).remove()
                        self.changed = True

        # Unassign tags:
        if state == 'present':
            for entity_name in [e for e in current_vms if e not in self._module.params[name]]:
                if not self._module.check_mode:
                    entity_id = get_id_by_name(entities_service, entity_name)
                    tags_service = entities_service.service(entity_id).tags_service()
                    tag_id = get_id_by_name(tags_service, self.param('name'))
                    tags_service.tag_service(tag_id).remove()
                self.changed = True
コード例 #2
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        host=dict(required=True),
        iscsi=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)

        # Get Host
        hosts_service = connection.system_service().hosts_service()
        host_id = get_id_by_name(hosts_service, module.params['host'])
        storage_type = _get_storage_type(module.params)
        host_service = hosts_service.host_service(host_id)

        if storage_type == 'iscsi':
            # Login
            iscsi = module.params.get('iscsi')
            _login(host_service, iscsi)

        # Get LUNs exposed from the specified target
        host_storages = host_service.storage_service().list()

        if storage_type == 'iscsi':
            filterred_host_storages = [host_storage for host_storage in host_storages
                                       if host_storage.type == otypes.StorageType.ISCSI]
            if 'target' in iscsi:
                filterred_host_storages = [host_storage for host_storage in filterred_host_storages
                                           if iscsi.get('target') == host_storage.logical_units[0].target]
        elif storage_type == 'fcp':
            filterred_host_storages = [host_storage for host_storage in host_storages
                                       if host_storage.type == otypes.StorageType.FCP]

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_host_storages=[
                    get_dict_of_struct(
                        struct=c,
                        connection=connection,
                        fetch_nested=module.params.get('fetch_nested'),
                        attributes=module.params.get('nested_attributes'),
                    ) for c in filterred_host_storages
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #3
0
ファイル: ovirt_cluster.py プロジェクト: awiddersheim/ansible
 def update_check(self, entity):
     sched_policy = self._get_sched_policy()
     migration_policy = getattr(entity.migration, 'policy', None)
     cluster_cpu = getattr(entity, 'cpu', dict())
     return (
         equal(self.param('comment'), entity.comment) and
         equal(self.param('description'), entity.description) and
         equal(self.param('switch_type'), str(entity.switch_type)) and
         equal(self.param('cpu_arch'), str(getattr(cluster_cpu, 'architecture', None))) and
         equal(self.param('cpu_type'), getattr(cluster_cpu, 'type', None)) and
         equal(self.param('ballooning'), entity.ballooning_enabled) and
         equal(self.param('gluster'), entity.gluster_service) and
         equal(self.param('virt'), entity.virt_service) and
         equal(self.param('threads_as_cores'), entity.threads_as_cores) and
         equal(self.param('ksm_numa'), not entity.ksm.merge_across_nodes) and
         equal(self.param('ksm'), entity.ksm.enabled) and
         equal(self.param('ha_reservation'), entity.ha_reservation) and
         equal(self.param('trusted_service'), entity.trusted_service) and
         equal(self.param('host_reason'), entity.maintenance_reason_required) and
         equal(self.param('vm_reason'), entity.optional_reason) and
         equal(self.param('spice_proxy'), getattr(entity.display, 'proxy', None)) and
         equal(self.param('fence_enabled'), entity.fencing_policy.enabled) and
         equal(self.param('fence_skip_if_sd_active'), entity.fencing_policy.skip_if_sd_active.enabled) and
         equal(self.param('fence_skip_if_connectivity_broken'), entity.fencing_policy.skip_if_connectivity_broken.enabled) and
         equal(self.param('fence_connectivity_threshold'), entity.fencing_policy.skip_if_connectivity_broken.threshold) and
         equal(self.param('resilience_policy'), str(entity.error_handling.on_error)) and
         equal(self.param('migration_bandwidth'), str(entity.migration.bandwidth.assignment_method)) and
         equal(self.param('migration_auto_converge'), str(entity.migration.auto_converge)) and
         equal(self.param('migration_compressed'), str(entity.migration.compressed)) and
         equal(self.param('serial_policy'), str(getattr(entity.serial_number, 'policy', None))) and
         equal(self.param('serial_policy_value'), getattr(entity.serial_number, 'value', None)) and
         equal(self.param('scheduling_policy'), getattr(self._connection.follow_link(entity.scheduling_policy), 'name', None)) and
         equal(self._get_policy_id(), getattr(migration_policy, 'id', None)) and
         equal(self._get_memory_policy(), entity.memory_policy.over_commit.percent) and
         equal(self.__get_minor(self.param('compatibility_version')), self.__get_minor(entity.version)) and
         equal(self.__get_major(self.param('compatibility_version')), self.__get_major(entity.version)) and
         equal(
             self.param('migration_bandwidth_limit') if self.param('migration_bandwidth') == 'custom' else None,
             entity.migration.bandwidth.custom_value
         ) and
         equal(
             sorted(self.param('rng_sources')) if self.param('rng_sources') else None,
             sorted([
                 str(source) for source in entity.required_rng_sources
             ])
         ) and
         equal(
             get_id_by_name(self._connection.system_service().mac_pools_service(), self.param('mac_pool'), raise_error=False),
             entity.mac_pool.id
         ) and
         self._update_check_external_network_providers(entity)
     )
コード例 #4
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        all_content=dict(default=False, type='bool'),
        case_sensitive=dict(default=True, type='bool'),
        storage_domain=dict(default=None),
        max=dict(default=None, type='int'),
        unregistered=dict(default=False, type='bool'),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        storage_domains_service = connection.system_service().storage_domains_service()
        sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain'])
        storage_domain_service = storage_domains_service.storage_domain_service(sd_id)
        vms_service = storage_domain_service.vms_service()

        # Find the the unregistered VM we want to register:
        if module.params.get('unregistered'):
            vms = vms_service.list(unregistered=True)
        else:
            vms = vms_service.list()
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_storage_vms=[
                    get_dict_of_struct(
                        struct=c,
                        connection=connection,
                        fetch_nested=module.params.get('fetch_nested'),
                        attributes=module.params.get('nested_attributes'),
                    ) for c in vms
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #5
0
ファイル: ovirt_disk.py プロジェクト: awiddersheim/ansible
    def update_storage_domains(self, disk_id):
        changed = False
        disk_service = self._service.service(disk_id)
        disk = disk_service.get()
        sds_service = self._connection.system_service().storage_domains_service()

        # We don't support move&copy for non file based storages:
        if disk.storage_type != otypes.DiskStorageType.IMAGE:
            return changed

        # Initiate move:
        if self._module.params['storage_domain']:
            new_disk_storage_id = get_id_by_name(sds_service, self._module.params['storage_domain'])
            changed = self.action(
                action='move',
                entity=disk,
                action_condition=lambda d: new_disk_storage_id != d.storage_domains[0].id,
                wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                storage_domain=otypes.StorageDomain(
                    id=new_disk_storage_id,
                ),
                post_action=lambda _: time.sleep(self._module.params['poll_interval']),
            )['changed']

        if self._module.params['storage_domains']:
            for sd in self._module.params['storage_domains']:
                new_disk_storage = search_by_name(sds_service, sd)
                changed = changed or self.action(
                    action='copy',
                    entity=disk,
                    action_condition=(
                        lambda disk: new_disk_storage.id not in [sd.id for sd in disk.storage_domains]
                    ),
                    wait_condition=lambda disk: disk.status == otypes.DiskStatus.OK,
                    storage_domain=otypes.StorageDomain(
                        id=new_disk_storage.id,
                    ),
                )['changed']

        return changed
コード例 #6
0
 def _login(self, storage_type, storage):
     if storage_type == 'iscsi':
         hosts_service = self._connection.system_service().hosts_service()
         host_id = get_id_by_name(hosts_service, self.param('host'))
         if storage.get('target'):
             hosts_service.host_service(host_id).iscsi_login(
                 iscsi=otypes.IscsiDetails(
                     username=storage.get('username'),
                     password=storage.get('password'),
                     address=storage.get('address'),
                     target=storage.get('target'),
                 ),
             )
         elif storage.get('target_lun_map'):
             for target in [m['target'] for m in storage.get('target_lun_map')]:
                 hosts_service.host_service(host_id).iscsi_login(
                     iscsi=otypes.IscsiDetails(
                         username=storage.get('username'),
                         password=storage.get('password'),
                         address=storage.get('address'),
                         target=target,
                     ),
                 )
コード例 #7
0
 def _get_external_network_provider_id(self, external_provider):
     return external_provider.get('id') or get_id_by_name(
         self._connection.system_service(
         ).openstack_network_providers_service(),
         external_provider.get('name'))
コード例 #8
0
ファイル: ovirt_host.py プロジェクト: sivakrishnaa/ansible-1
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'upgraded', 'started',
                'restarted', 'stopped', 'reinstalled', 'iscsidiscover',
                'iscsilogin'
            ],
            default='present',
        ),
        name=dict(required=True),
        id=dict(default=None),
        comment=dict(default=None),
        cluster=dict(default=None),
        address=dict(default=None),
        password=dict(default=None, no_log=True),
        public_key=dict(default=False, type='bool',
                        aliases=['ssh_public_key']),
        kdump_integration=dict(default=None, choices=['enabled', 'disabled']),
        spm_priority=dict(default=None, type='int'),
        override_iptables=dict(default=None, type='bool'),
        force=dict(default=False, type='bool'),
        timeout=dict(default=600, type='int'),
        override_display=dict(default=None),
        kernel_params=dict(default=None, type='list'),
        hosted_engine=dict(default=None, choices=['deploy', 'undeploy']),
        power_management_enabled=dict(default=None, type='bool'),
        activate=dict(default=True, type='bool'),
        iscsi=dict(default=None, type='dict'),
        check_upgrade=dict(default=True, type='bool'),
        reboot_after_upgrade=dict(default=True, type='bool'),
        vgpu_placement=dict(default=None,
                            choices=['consolidated', 'separated']),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_if=[['state', 'iscsidiscover', ['iscsi']],
                                        ['state', 'iscsilogin', ['iscsi']]])

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        start_event = connection.system_service().events_service().list(
            max=1)[0]
        hosts_module = HostsModule(
            connection=connection,
            module=module,
            service=hosts_service,
            start_event=start_event,
        )

        state = module.params['state']
        host = control_state(hosts_module)
        if state == 'present':
            ret = hosts_module.create(
                deploy_hosted_engine=(module.params.get('hosted_engine')
                                      == 'deploy')
                if module.params.get('hosted_engine') is not None else None,
                activate=module.params['activate'],
                result_state=(
                    hoststate.MAINTENANCE if module.params['activate'] is False
                    else hoststate.UP) if host is None else None,
                fail_condition=hosts_module.failed_state_after_reinstall
                if host is None else lambda h: False,
            )
            if module.params['activate'] and host is not None:
                ret = hosts_module.action(
                    action='activate',
                    action_condition=lambda h: h.status != hoststate.UP,
                    wait_condition=lambda h: h.status == hoststate.UP,
                    fail_condition=failed_state,
                )
        elif state == 'absent':
            ret = hosts_module.remove()
        elif state == 'maintenance':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status != hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
            )
            ret = hosts_module.create()
        elif state == 'upgraded':
            result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP
            events_service = connection.system_service().events_service()
            last_event = events_service.list(max=1)[0]

            if module.params['check_upgrade']:
                hosts_module.action(
                    action='upgrade_check',
                    action_condition=lambda host: not host.update_available,
                    wait_condition=lambda host: host.update_available or (len([
                        event for event in events_service.list(
                            from_=int(last_event.id),
                            search='type=885',
                            # Uncomment when 4.1 is EOL, and remove the cond:
                            # if host.name in event.description
                            # search='type=885 and host.name=%s' % host.name,
                        ) if host.name in event.description
                    ]) > 0),
                    fail_condition=lambda host: len([
                        event for event in events_service.list(
                            from_=int(last_event.id),
                            search='type=839 or type=887 and host.name=%s' %
                            host.name,
                        )
                    ]) > 0,
                )
                # Set to False, because upgrade_check isn't 'changing' action:
                hosts_module._changed = False
            ret = hosts_module.action(
                action='upgrade',
                action_condition=lambda h: h.update_available,
                wait_condition=lambda h: h.status == result_state,
                post_action=lambda h: time.sleep(module.params['poll_interval']
                                                 ),
                fail_condition=lambda h: hosts_module.
                failed_state_after_reinstall(h) or (len([
                    event for event in events_service.list(
                        from_=int(last_event.id),
                        # Fail upgrade if migration fails:
                        # 17: Failed to switch Host to Maintenance mode
                        # 65, 140: Migration failed
                        # 166: No available host was found to migrate VM
                        search='type=65 or type=140 or type=166 or type=17',
                    ) if host.name in event.description
                ]) > 0),
                reboot=module.params['reboot_after_upgrade'],
            )
        elif state == 'iscsidiscover':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_param = module.params['iscsi']
            iscsi_targets = hosts_service.service(host_id).iscsi_discover(
                iscsi=otypes.IscsiDetails(
                    port=int(iscsi_param.get('port', 3260)),
                    username=iscsi_param.get('username'),
                    password=iscsi_param.get('password'),
                    address=iscsi_param.get('address'),
                ), )
            ret = {
                'changed': False,
                'id': host_id,
                'iscsi_targets': iscsi_targets,
            }
        elif state == 'iscsilogin':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_param = module.params['iscsi']
            ret = hosts_module.action(
                action='iscsi_login',
                iscsi=otypes.IscsiDetails(
                    port=int(iscsi_param.get('port', 3260)),
                    username=iscsi_param.get('username'),
                    password=iscsi_param.get('password'),
                    address=iscsi_param.get('address'),
                    target=iscsi_param.get('target'),
                ),
            )
        elif state == 'started':
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status == hoststate.DOWN,
                wait_condition=lambda h: h.status in
                [hoststate.UP, hoststate.MAINTENANCE],
                fail_condition=hosts_module.failed_state_after_reinstall,
                fence_type='start',
            )
        elif state == 'stopped':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status != hoststate.DOWN,
                wait_condition=lambda h: h.status == hoststate.DOWN
                if module.params['wait'] else True,
                fail_condition=failed_state,
                fence_type='stop',
            )
        elif state == 'restarted':
            ret = hosts_module.action(
                action='fence',
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=hosts_module.failed_state_after_reinstall,
                fence_type='restart',
            )
        elif state == 'reinstalled':
            # Deactivate host if not in maintanence:
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )

            # Reinstall host:
            hosts_module.action(
                action='install',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                post_action=hosts_module.post_reinstall,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=hosts_module.failed_state_after_reinstall,
                host=otypes.Host(
                    override_iptables=module.params['override_iptables'], )
                if module.params['override_iptables'] else None,
                root_password=module.params['password'],
                ssh=otypes.Ssh(authentication_method=otypes.
                               SshAuthenticationMethod.PUBLICKEY, )
                if module.params['public_key'] else None,
                deploy_hosted_engine=(module.params.get('hosted_engine')
                                      == 'deploy')
                if module.params.get('hosted_engine') is not None else None,
                undeploy_hosted_engine=(module.params.get('hosted_engine')
                                        == 'undeploy')
                if module.params.get('hosted_engine') is not None else None,
            )

            # Activate host after reinstall:
            ret = hosts_module.action(
                action='activate',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
            )
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #9
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'exported', 'imported', 'registered'
            ],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        allow_partial_import=dict(default=None, type='bool'),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        template_image_disk_name=dict(default=None),
        seal=dict(type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = templates_module.create(
                result_state=otypes.TemplateStatus.OK,
                clone_permissions=module.params['clone_permissions'],
                seal=module.params['seal'],
            )
        elif state == 'absent':
            ret = templates_module.remove()
        elif state == 'exported':
            template = templates_module.search_entity()
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(
                export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None or module.
                params['exclusive'],
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(
                    id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if template:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK, )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['template_image_disk_name']
                            or module.params['image_disk']),
                        template=otypes.Template(name=module.params['name'], ),
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service(
                    ).images_service().list()

                    glance_service = connection.system_service(
                    ).openstack_image_providers_service()
                    image_provider = search_by_name(
                        glance_service, module.params['image_provider'])
                    images_service = glance_service.service(
                        image_provider.id).images_service()
                else:
                    images_service = templates_module._get_export_domain_service(
                    ).templates_service()
                template_name = module.params['image_disk'] or module.params[
                    'name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." %
                                    template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain'])
                    if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    **kwargs)
                # Wait for template to appear in system:
                template = templates_module.wait_for_import(
                    condition=lambda t: t.status == otypes.TemplateStatus.OK)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }
        elif state == 'registered':
            storage_domains_service = connection.system_service(
            ).storage_domains_service()
            # Find the storage domain with unregistered template:
            sd_id = get_id_by_name(storage_domains_service,
                                   module.params['storage_domain'])
            storage_domain_service = storage_domains_service.storage_domain_service(
                sd_id)
            templates_service = storage_domain_service.templates_service()

            # Find the unregistered Template we want to register:
            templates = templates_service.list(unregistered=True)
            template = next(
                (t for t in templates if (t.id == module.params['id']
                                          or t.name == module.params['name'])),
                None)
            changed = False
            if template is None:
                template = templates_module.search_entity()
                if template is None:
                    raise ValueError(
                        "Template '%s(%s)' wasn't found." %
                        (module.params['name'], module.params['id']))
            else:
                # Register the template into the system:
                changed = True
                template_service = templates_service.template_service(
                    template.id)
                template_service.register(
                    allow_partial_import=module.params['allow_partial_import'],
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None)

                if module.params['wait']:
                    template = templates_module.wait_for_import()
                else:
                    # Fetch template to initialize return.
                    template = template_service.get()
            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #10
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        cluster=dict(default=None, required=True),
        name=dict(default=None, required=True),
        description=dict(default=None),
        vm_enforcing=dict(default=None, type='bool'),
        vm_rule=dict(default=None,
                     choices=['positive', 'negative', 'disabled']),
        host_enforcing=dict(default=None, type='bool'),
        host_rule=dict(default=None, choices=['positive', 'negative']),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    if module._name == 'ovirt_affinity_groups':
        module.deprecate(
            "The 'ovirt_affinity_groups' module is being renamed 'ovirt_affinity_group'",
            version=2.8)

    check_sdk(module)
    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        # Check if unsupported parameters were passed:
        supported_41 = ('host_enforcing', 'host_rule', 'hosts')
        if not check_support(
                version='4.1',
                connection=connection,
                module=module,
                params=supported_41,
        ):
            module.fail_json(
                msg='Following parameters are supported since 4.1: {params}'.
                format(params=supported_41, ))
        clusters_service = connection.system_service().clusters_service()
        vms_service = connection.system_service().vms_service()
        hosts_service = connection.system_service().hosts_service()
        cluster_name = module.params['cluster']
        cluster = search_by_name(clusters_service, cluster_name)
        if cluster is None:
            raise Exception("Cluster '%s' was not found." % cluster_name)
        cluster_service = clusters_service.cluster_service(cluster.id)
        affinity_groups_service = cluster_service.affinity_groups_service()

        # Fetch VM ids which should be assigned to affinity group:
        vm_ids = sorted([
            get_id_by_name(vms_service, vm_name)
            for vm_name in module.params['vms']
        ]) if module.params['vms'] is not None else None
        # Fetch host ids which should be assigned to affinity group:
        host_ids = sorted([
            get_id_by_name(hosts_service, host_name)
            for host_name in module.params['hosts']
        ]) if module.params['hosts'] is not None else None

        affinity_groups_module = AffinityGroupsModule(
            connection=connection,
            module=module,
            service=affinity_groups_service,
            vm_ids=vm_ids,
            host_ids=host_ids,
        )

        state = module.params['state']
        if state == 'present':
            ret = affinity_groups_module.create()
        elif state == 'absent':
            ret = affinity_groups_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #11
0
 def _get_network_filter_id(self):
     nf_service = self._connection.system_service().network_filters_service(
     )
     return get_id_by_name(nf_service, self.param(
         'network_filter')) if self.param('network_filter') else None
コード例 #12
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'exported', 'imported', 'registered'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        allow_partial_import=dict(default=None, type='bool'),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        template_image_disk_name=dict(default=None),
        seal=dict(type='bool'),
        vnic_profile_mappings=dict(default=[], type='list'),
        cluster_mappings=dict(default=[], type='list'),
        role_mappings=dict(default=[], type='list'),
        domain_mappings=dict(default=[], type='list'),
        operating_system=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = templates_module.create(
                result_state=otypes.TemplateStatus.OK,
                clone_permissions=module.params['clone_permissions'],
                seal=module.params['seal'],
            )
        elif state == 'absent':
            ret = templates_module.remove()
        elif state == 'exported':
            template = templates_module.search_entity()
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None or module.params['exclusive'],
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if template:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK,
                )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['template_image_disk_name'] or module.params['image_disk']
                        ),
                        template=otypes.Template(
                            name=module.params['name'],
                        ),
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service().images_service().list()

                    glance_service = connection.system_service().openstack_image_providers_service()
                    image_provider = search_by_name(glance_service, module.params['image_provider'])
                    images_service = glance_service.service(image_provider.id).images_service()
                else:
                    images_service = templates_module._get_export_domain_service().templates_service()
                template_name = module.params['image_disk'] or module.params['name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." % template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain']
                    ) if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(
                        name=module.params['cluster']
                    ) if module.params['cluster'] else None,
                    **kwargs
                )
                # Wait for template to appear in system:
                template = templates_module.wait_for_import(
                    condition=lambda t: t.status == otypes.TemplateStatus.OK
                )
                ret = templates_module.create(result_state=otypes.TemplateStatus.OK)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }
        elif state == 'registered':
            storage_domains_service = connection.system_service().storage_domains_service()
            # Find the storage domain with unregistered template:
            sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain'])
            storage_domain_service = storage_domains_service.storage_domain_service(sd_id)
            templates_service = storage_domain_service.templates_service()

            # Find the unregistered Template we want to register:
            templates = templates_service.list(unregistered=True)
            template = next(
                (t for t in templates if (t.id == module.params['id'] or t.name == module.params['name'])),
                None
            )
            changed = False
            if template is None:
                template = templates_module.search_entity()
                if template is None:
                    raise ValueError(
                        "Template '%s(%s)' wasn't found." % (module.params['name'], module.params['id'])
                    )
            else:
                # Register the template into the system:
                changed = True
                template_service = templates_service.template_service(template.id)
                template_service.register(
                    allow_partial_import=module.params['allow_partial_import'],
                    cluster=otypes.Cluster(
                        name=module.params['cluster']
                    ) if module.params['cluster'] else None,
                    vnic_profile_mappings=_get_vnic_profile_mappings(module)
                    if module.params['vnic_profile_mappings'] else None,
                    registration_configuration=otypes.RegistrationConfiguration(
                        cluster_mappings=_get_cluster_mappings(module),
                        role_mappings=_get_role_mappings(module),
                        domain_mappings=_get_domain_mappings(module),
                    ) if (module.params['cluster_mappings']
                          or module.params['role_mappings']
                          or module.params['domain_mappings']) else None
                )

                if module.params['wait']:
                    template = templates_module.wait_for_import()
                else:
                    # Fetch template to initialize return.
                    template = template_service.get()
                ret = templates_module.create(result_state=otypes.TemplateStatus.OK)
            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #13
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'exported', 'imported', 'registered'
            ],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        vm=dict(default=None),
        timezone=dict(type='str'),
        description=dict(default=None),
        sso=dict(type='bool'),
        ballooning_enabled=dict(type='bool', default=None),
        cluster=dict(default=None),
        usb_support=dict(type='bool'),
        allow_partial_import=dict(default=None, type='bool'),
        cpu_profile=dict(default=None),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        clone_name=dict(default=None),
        image_provider=dict(default=None),
        soundcard_enabled=dict(type='bool', default=None),
        smartcard_enabled=dict(type='bool', default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        io_threads=dict(type='int', default=None),
        template_image_disk_name=dict(default=None),
        version=dict(default=None, type='dict'),
        seal=dict(type='bool'),
        vnic_profile_mappings=dict(default=[], type='list'),
        cluster_mappings=dict(default=[], type='list'),
        role_mappings=dict(default=[], type='list'),
        domain_mappings=dict(default=[], type='list'),
        operating_system=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
        nics=dict(type='list', default=[]),
        cloud_init=dict(type='dict'),
        cloud_init_nics=dict(type='list', default=[]),
        sysprep=dict(type='dict'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        entity = None
        if module.params['version'] is not None and module.params[
                'version'].get('number') is not None:
            entity = find_subversion_template(module, templates_service)

        state = module.params['state']
        if state == 'present':
            force_create = False
            if entity is None and module.params['version'] is not None:
                force_create = True

            ret = templates_module.create(
                entity=entity,
                # When user want to create new template subversion, we must make sure
                # template is force created as it already exists, but new version should be created.
                force_create=force_create,
                result_state=otypes.TemplateStatus.OK,
                search_params=searchable_attributes(module),
                clone_permissions=module.params['clone_permissions'],
                seal=module.params['seal'],
            )
        elif state == 'absent':
            ret = templates_module.remove(entity=entity)
        elif state == 'exported':
            template = templates_module.search_entity()
            if entity is not None:
                template = entity
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(
                export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None or module.
                params['exclusive'],
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(
                    id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if entity is not None:
                template = entity
            if template and module.params['clone_name'] is None:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK, )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['template_image_disk_name']
                            or module.params['image_disk']),
                        template=otypes.Template(
                            name=module.params['name']
                            if module.params['clone_name'] is None else
                            module.params['clone_name'], ),
                        clone=True
                        if module.params['clone_name'] is not None else False,
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service(
                    ).images_service().list()

                    glance_service = connection.system_service(
                    ).openstack_image_providers_service()
                    image_provider = search_by_name(
                        glance_service, module.params['image_provider'])
                    images_service = glance_service.service(
                        image_provider.id).images_service()
                else:
                    images_service = templates_module._get_export_domain_service(
                    ).templates_service()
                template_name = module.params['image_disk'] or module.params[
                    'name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." %
                                    template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain'])
                    if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    **kwargs)
                # Wait for template to appear in system:
                template = templates_module.wait_for_import(
                    condition=lambda t: t.status == otypes.TemplateStatus.OK)
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }
        elif state == 'registered':
            storage_domains_service = connection.system_service(
            ).storage_domains_service()
            # Find the storage domain with unregistered template:
            sd_id = get_id_by_name(storage_domains_service,
                                   module.params['storage_domain'])
            storage_domain_service = storage_domains_service.storage_domain_service(
                sd_id)
            templates_service = storage_domain_service.templates_service()

            # Find the unregistered Template we want to register:
            templates = templates_service.list(unregistered=True)
            template = next(
                (t for t in templates if (t.id == module.params['id']
                                          or t.name == module.params['name'])),
                None)
            changed = False
            if template is None:
                template = templates_module.search_entity()
                if template is None:
                    raise ValueError(
                        "Template '%s(%s)' wasn't found." %
                        (module.params['name'], module.params['id']))
            else:
                # Register the template into the system:
                changed = True
                template_service = templates_service.template_service(
                    template.id)
                template_service.register(
                    allow_partial_import=module.params['allow_partial_import'],
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    vnic_profile_mappings=_get_vnic_profile_mappings(module)
                    if module.params['vnic_profile_mappings'] else None,
                    registration_configuration=otypes.
                    RegistrationConfiguration(
                        cluster_mappings=_get_cluster_mappings(module),
                        role_mappings=_get_role_mappings(module),
                        domain_mappings=_get_domain_mappings(module),
                    ) if (module.params['cluster_mappings']
                          or module.params['role_mappings']
                          or module.params['domain_mappings']) else None)

                if module.params['wait']:
                    template = templates_module.wait_for_import()
                else:
                    # Fetch template to initialize return.
                    template = template_service.get()
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK)
            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #14
0
 def __get_dcs_id(self):
     return get_id_by_name(self.__get_dcs_service(), self.param('data_center'))
コード例 #15
0
ファイル: ovirt_vms.py プロジェクト: nilanshakya/ansible
 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,
     )
コード例 #16
0
ファイル: ovirt_cluster.py プロジェクト: awiddersheim/ansible
 def _get_external_network_provider_id(self, external_provider):
     return external_provider.get('id') or get_id_by_name(
         self._connection.system_service().openstack_network_providers_service(),
         external_provider.get('name')
     )
コード例 #17
0
 def update_check(self, entity):
     sched_policy = self._get_sched_policy()
     migration_policy = getattr(entity.migration, 'policy', None)
     return (
         equal(self.param('comment'), entity.comment)
         and equal(self.param('description'), entity.description)
         and equal(self.param('switch_type'), str(entity.switch_type))
         and equal(self.param('cpu_arch'), str(entity.cpu.architecture))
         and equal(self.param('cpu_type'), entity.cpu.type)
         and equal(self.param('ballooning'), entity.ballooning_enabled)
         and equal(self.param('gluster'), entity.gluster_service)
         and equal(self.param('virt'), entity.virt_service)
         and equal(self.param('threads_as_cores'), entity.threads_as_cores)
         and equal(self.param('ksm_numa'), not entity.ksm.merge_across_nodes
                   and entity.ksm.enabled)
         and equal(self.param('ksm'), entity.ksm.merge_across_nodes
                   and entity.ksm.enabled)
         and equal(self.param('ha_reservation'), entity.ha_reservation)
         and equal(self.param('trusted_service'), entity.trusted_service)
         and equal(self.param('host_reason'),
                   entity.maintenance_reason_required)
         and equal(self.param('vm_reason'), entity.optional_reason)
         and equal(self.param('spice_proxy'),
                   getattr(entity.display, 'proxy', None)) and
         equal(self.param('fence_enabled'), entity.fencing_policy.enabled)
         and equal(self.param('fence_skip_if_sd_active'),
                   entity.fencing_policy.skip_if_sd_active.enabled)
         and equal(
             self.param('fence_skip_if_connectivity_broken'),
             entity.fencing_policy.skip_if_connectivity_broken.enabled)
         and equal(
             self.param('fence_connectivity_threshold'),
             entity.fencing_policy.skip_if_connectivity_broken.threshold)
         and equal(self.param('resilience_policy'),
                   str(entity.error_handling.on_error))
         and equal(self.param('migration_bandwidth'),
                   str(entity.migration.bandwidth.assignment_method))
         and equal(self.param('migration_auto_converge'),
                   str(entity.migration.auto_converge))
         and equal(self.param('migration_compressed'),
                   str(entity.migration.compressed))
         and equal(self.param('serial_policy'),
                   str(getattr(entity.serial_number, 'policy', None)))
         and equal(self.param('serial_policy_value'),
                   getattr(entity.serial_number, 'value', None))
         and equal(
             self.param('scheduling_policy'),
             getattr(self._connection.follow_link(entity.scheduling_policy),
                     'name', None))
         and equal(self._get_policy_id(),
                   getattr(migration_policy, 'id', None))
         and equal(self._get_memory_policy(),
                   entity.memory_policy.over_commit.percent)
         and equal(self.__get_minor(self.param('compatibility_version')),
                   self.__get_minor(entity.version))
         and equal(self.__get_major(self.param('compatibility_version')),
                   self.__get_major(entity.version))
         and equal(
             self.param('migration_bandwidth_limit')
             if self.param('migration_bandwidth') == 'custom' else None,
             entity.migration.bandwidth.custom_value)
         and equal(
             sorted(self.param('rng_sources'))
             if self.param('rng_sources') else None,
             sorted([str(source)
                     for source in entity.required_rng_sources]))
         and equal(
             get_id_by_name(
                 self._connection.system_service().mac_pools_service(),
                 self.param('mac_pool')), entity.mac_pool.id))
コード例 #18
0
ファイル: ovirt_hosts.py プロジェクト: ernstp/ansible
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'upgraded', 'started',
                'restarted', 'stopped', 'reinstalled', 'iscsidiscover', 'iscsilogin'
            ],
            default='present',
        ),
        name=dict(required=True),
        comment=dict(default=None),
        cluster=dict(default=None),
        address=dict(default=None),
        password=dict(default=None, no_log=True),
        public_key=dict(default=False, type='bool', aliases=['ssh_public_key']),
        kdump_integration=dict(default=None, choices=['enabled', 'disabled']),
        spm_priority=dict(default=None, type='int'),
        override_iptables=dict(default=None, type='bool'),
        force=dict(default=False, type='bool'),
        timeout=dict(default=600, type='int'),
        override_display=dict(default=None),
        kernel_params=dict(default=None, type='list'),
        hosted_engine=dict(default=None, choices=['deploy', 'undeploy']),
        power_management_enabled=dict(default=None, type='bool'),
        activate=dict(default=True, type='bool'),
        iscsi=dict(default=None, type='dict'),
        check_upgrade=dict(default=True, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'iscsidiscover', ['iscsi']],
            ['state', 'iscsilogin', ['iscsi']]
        ]
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        hosts_module = HostsModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        state = module.params['state']
        host = control_state(hosts_module)
        if state == 'present':
            ret = hosts_module.create(
                deploy_hosted_engine=(
                    module.params.get('hosted_engine') == 'deploy'
                ) if module.params.get('hosted_engine') is not None else None,
                result_state=hoststate.UP if host is None else None,
                fail_condition=failed_state if host is None else lambda h: False,
            )
            if module.params['activate'] and host is not None:
                ret = hosts_module.action(
                    action='activate',
                    action_condition=lambda h: h.status != hoststate.UP,
                    wait_condition=lambda h: h.status == hoststate.UP,
                    fail_condition=failed_state,
                )
        elif state == 'absent':
            ret = hosts_module.remove()
        elif state == 'maintenance':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status != hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
            )
            ret = hosts_module.create()
        elif state == 'upgraded':
            result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP
            events_service = connection.system_service().events_service()
            last_event = events_service.list(max=1)[0]

            if module.params['check_upgrade']:
                hosts_module.action(
                    action='upgrade_check',
                    action_condition=lambda host: not host.update_available,
                    wait_condition=lambda host: host.update_available or (
                        len([
                            event
                            for event in events_service.list(
                                from_=int(last_event.id),
                                search='type=885 and host.name=%s' % host.name,
                            )
                        ]) > 0
                    ),
                    fail_condition=lambda host: len([
                        event
                        for event in events_service.list(
                            from_=int(last_event.id),
                            search='type=839 or type=887 and host.name=%s' % host.name,
                        )
                    ]) > 0,
                )
                # Set to False, because upgrade_check isn't 'changing' action:
                hosts_module._changed = False
            ret = hosts_module.action(
                action='upgrade',
                action_condition=lambda h: h.update_available,
                wait_condition=lambda h: h.status == result_state,
                post_action=lambda h: time.sleep(module.params['poll_interval']),
                fail_condition=failed_state,
            )
        elif state == 'iscsidiscover':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_targets = hosts_service.service(host_id).iscsi_discover(
                iscsi=otypes.IscsiDetails(
                    port=int(module.params['iscsi']['port']) if module.params['iscsi']['port'].isdigit() else None,
                    username=module.params['iscsi']['username'],
                    password=module.params['iscsi']['password'],
                    address=module.params['iscsi']['address'],
                ),
            )
            ret = {
                'changed': False,
                'id': host_id,
                'iscsi_targets': iscsi_targets,
            }
        elif state == 'iscsilogin':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            ret = hosts_module.action(
                action='iscsi_login',
                iscsi=otypes.IscsiDetails(
                    port=int(module.params['iscsi']['port']) if module.params['iscsi']['port'].isdigit() else None,
                    username=module.params['iscsi']['username'],
                    password=module.params['iscsi']['password'],
                    address=module.params['iscsi']['address'],
                    target=module.params['iscsi']['target'],
                ),
            )
        elif state == 'started':
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status == hoststate.DOWN,
                wait_condition=lambda h: h.status in [hoststate.UP, hoststate.MAINTENANCE],
                fail_condition=failed_state,
                fence_type='start',
            )
        elif state == 'stopped':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status != hoststate.DOWN,
                wait_condition=lambda h: h.status == hoststate.DOWN if module.params['wait'] else True,
                fail_condition=failed_state,
                fence_type='stop',
            )
        elif state == 'restarted':
            ret = hosts_module.action(
                action='fence',
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
                fence_type='restart',
            )
        elif state == 'reinstalled':
            # Deactivate host if not in maintanence:
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )

            # Reinstall host:
            hosts_module.action(
                action='install',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                post_action=hosts_module.post_reinstall,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
                host=otypes.Host(
                    override_iptables=module.params['override_iptables'],
                ) if module.params['override_iptables'] else None,
                root_password=module.params['password'],
                ssh=otypes.Ssh(
                    authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY,
                ) if module.params['public_key'] else None,
                deploy_hosted_engine=(
                    module.params.get('hosted_engine') == 'deploy'
                ) if module.params.get('hosted_engine') is not None else None,
                undeploy_hosted_engine=(
                    module.params.get('hosted_engine') == 'undeploy'
                ) if module.params.get('hosted_engine') is not None else None,
            )

            # Activate host after reinstall:
            ret = hosts_module.action(
                action='activate',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
            )
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #19
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        data_center=dict(required=True),
        id=dict(default=None),
        name=dict(required=True),
        description=dict(default=None),
        comment=dict(default=None),
        external_provider=dict(default=None),
        vlan_tag=dict(default=None, type='int'),
        vm_network=dict(default=None, type='bool'),
        mtu=dict(default=None, type='int'),
        clusters=dict(default=None, type='list'),
        label=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        clusters_service = connection.system_service().clusters_service()
        networks_service = connection.system_service().networks_service()
        networks_module = NetworksModule(
            connection=connection,
            module=module,
            service=networks_service,
        )
        state = module.params['state']
        search_params = {
            'name': module.params['name'],
            'datacenter': module.params['data_center'],
        }
        if state == 'present':
            imported = False
            if module.params.get('external_provider') and module.params.get('name') not in [net.name for net in networks_service.list()]:
                # Try to import network
                ons_service = connection.system_service().openstack_network_providers_service()
                on_service = ons_service.provider_service(get_id_by_name(ons_service, module.params.get('external_provider')))
                on_networks_service = on_service.networks_service()
                if module.params.get('name') in [net.name for net in on_networks_service.list()]:
                    network_service = on_networks_service.network_service(get_id_by_name(on_networks_service, module.params.get('name')))
                    network_service.import_(data_center=otypes.DataCenter(name=module.params.get('data_center')))
                    imported = True

            ret = networks_module.create(search_params=search_params)
            ret['changed'] = ret['changed'] or imported
            # Update clusters networks:
            if module.params.get('clusters') is not None:
                for param_cluster in module.params.get('clusters'):
                    cluster = search_by_name(clusters_service, param_cluster.get('name'))
                    if cluster is None:
                        raise Exception("Cluster '%s' was not found." % param_cluster.get('name'))
                    cluster_networks_service = clusters_service.service(cluster.id).networks_service()
                    cluster_networks_module = ClusterNetworksModule(
                        network_id=ret['id'],
                        cluster_network=param_cluster,
                        connection=connection,
                        module=module,
                        service=cluster_networks_service,
                    )
                    if param_cluster.get('assigned', True):
                        ret = cluster_networks_module.create()
                    else:
                        ret = cluster_networks_module.remove()

        elif state == 'absent':
            ret = networks_module.remove(search_params=search_params)

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #20
0
 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'),
     )
コード例 #21
0
    def update_check(self, entity):
        sched_policy = self._get_sched_policy()
        migration_policy = getattr(entity.migration, 'policy', None)
        cluster_cpu = getattr(entity, 'cpu', dict())

        def check_custom_scheduling_policy_properties():
            if self.param('scheduling_policy_properties'):
                current = []
                if entity.custom_scheduling_policy_properties:
                    current = [
                        (sp.name, str(sp.value))
                        for sp in entity.custom_scheduling_policy_properties
                    ]
                passed = [(sp.get('name'), str(sp.get('value')))
                          for sp in self.param('scheduling_policy_properties')
                          if sp]
                for p in passed:
                    if p not in current:
                        return False
            return True

        return (check_custom_scheduling_policy_properties()
                and equal(self.param('name'), entity.name)
                and equal(self.param('comment'), entity.comment)
                and equal(self.param('description'), entity.description)
                and equal(self.param('switch_type'), str(entity.switch_type))
                and equal(self.param('cpu_arch'),
                          str(getattr(cluster_cpu, 'architecture', None)))
                and equal(self.param('cpu_type'),
                          getattr(cluster_cpu, 'type', None))
                and equal(self.param('ballooning'), entity.ballooning_enabled)
                and equal(self.param('gluster'), entity.gluster_service)
                and equal(self.param('virt'), entity.virt_service) and equal(
                    self.param('threads_as_cores'), entity.threads_as_cores)
                and equal(self.param('ksm_numa'),
                          not entity.ksm.merge_across_nodes)
                and equal(self.param('ksm'), entity.ksm.enabled)
                and equal(self.param('ha_reservation'), entity.ha_reservation)
                and equal(self.param('trusted_service'),
                          entity.trusted_service)
                and equal(self.param('host_reason'),
                          entity.maintenance_reason_required)
                and equal(self.param('vm_reason'), entity.optional_reason)
                and equal(self.param('spice_proxy'),
                          getattr(entity.display, 'proxy', None))
                and equal(self.param('fence_enabled'),
                          entity.fencing_policy.enabled)
                and equal(self.param('fence_skip_if_gluster_bricks_up'),
                          entity.fencing_policy.skip_if_gluster_bricks_up)
                and equal(self.param('fence_skip_if_gluster_quorum_not_met'),
                          entity.fencing_policy.skip_if_gluster_quorum_not_met)
                and equal(self.param('fence_skip_if_sd_active'),
                          entity.fencing_policy.skip_if_sd_active.enabled)
                and equal(
                    self.param('fence_skip_if_connectivity_broken'),
                    entity.fencing_policy.skip_if_connectivity_broken.enabled)
                and equal(
                    self.param('fence_connectivity_threshold'), entity.
                    fencing_policy.skip_if_connectivity_broken.threshold)
                and equal(self.param('resilience_policy'),
                          str(entity.error_handling.on_error))
                and equal(self.param('migration_bandwidth'),
                          str(entity.migration.bandwidth.assignment_method))
                and equal(self.param('migration_auto_converge'),
                          str(entity.migration.auto_converge))
                and equal(self.param('migration_compressed'),
                          str(entity.migration.compressed))
                and equal(self.param('serial_policy'),
                          str(getattr(entity.serial_number, 'policy', None)))
                and equal(self.param('serial_policy_value'),
                          getattr(entity.serial_number, 'value', None))
                and equal(
                    self.param('scheduling_policy'),
                    getattr(
                        self._connection.follow_link(entity.scheduling_policy),
                        'name', None)) and equal(self.param('firewall_type'),
                                                 str(entity.firewall_type))
                and equal(self.param('gluster_tuned_profile'),
                          getattr(entity, 'gluster_tuned_profile', None))
                and equal(self._get_policy_id(),
                          getattr(migration_policy, 'id', None))
                and equal(self._get_memory_policy(),
                          entity.memory_policy.over_commit.percent)
                and equal(
                    self.__get_minor(self.param('compatibility_version')),
                    self.__get_minor(entity.version)) and equal(
                        self.__get_major(self.param('compatibility_version')),
                        self.__get_major(entity.version))
                and equal(
                    self.param('migration_bandwidth_limit')
                    if self.param('migration_bandwidth') == 'custom' else None,
                    entity.migration.bandwidth.custom_value) and equal(
                        sorted(self.param('rng_sources'))
                        if self.param('rng_sources') else None,
                        sorted([
                            str(source)
                            for source in entity.required_rng_sources
                        ]))
                and equal(
                    get_id_by_name(
                        self._connection.system_service().mac_pools_service(),
                        self.param('mac_pool'),
                        raise_error=False), entity.mac_pool.id)
                and self._update_check_external_network_providers(entity))
コード例 #22
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'upgraded', 'started',
                'restarted', 'stopped', 'reinstalled', 'iscsidiscover',
                'iscsilogin'
            ],
            default='present',
        ),
        name=dict(required=True),
        comment=dict(default=None),
        cluster=dict(default=None),
        address=dict(default=None),
        password=dict(default=None, no_log=True),
        public_key=dict(default=False, type='bool',
                        aliases=['ssh_public_key']),
        kdump_integration=dict(default=None, choices=['enabled', 'disabled']),
        spm_priority=dict(default=None, type='int'),
        override_iptables=dict(default=None, type='bool'),
        force=dict(default=False, type='bool'),
        timeout=dict(default=600, type='int'),
        override_display=dict(default=None),
        kernel_params=dict(default=None, type='list'),
        hosted_engine=dict(default=None, choices=['deploy', 'undeploy']),
        power_management_enabled=dict(default=None, type='bool'),
        activate=dict(default=True, type='bool'),
        iscsi=dict(default=None, type='dict'),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_if=[['state', 'iscsidiscover', ['iscsi']],
                                        ['state', 'iscsilogin', ['iscsi']]])
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        hosts_module = HostsModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        state = module.params['state']
        host = control_state(hosts_module)
        if state == 'present':
            ret = hosts_module.create(
                deploy_hosted_engine=(module.params.get('hosted_engine')
                                      == 'deploy')
                if module.params.get('hosted_engine') is not None else None,
                result_state=(lambda h: h.status == hoststate.UP)
                if host is None else None,
                fail_condition=failed_state
                if host is None else lambda h: False,
            )
            if module.params['activate'] and host is not None:
                ret = hosts_module.action(
                    action='activate',
                    action_condition=lambda h: h.status != hoststate.UP,
                    wait_condition=lambda h: h.status == hoststate.UP,
                    fail_condition=failed_state,
                )
        elif state == 'absent':
            ret = hosts_module.remove()
        elif state == 'maintenance':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status != hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
            )
            ret = hosts_module.create()
        elif state == 'upgraded':
            result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP
            ret = hosts_module.action(
                action='upgrade',
                action_condition=lambda h: h.update_available,
                wait_condition=lambda h: h.status == result_state,
                post_action=lambda h: time.sleep(module.params['poll_interval']
                                                 ),
                fail_condition=failed_state,
            )
        elif state == 'iscsidiscover':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_targets = hosts_service.service(host_id).iscsi_discover(
                iscsi=otypes.IscsiDetails(
                    port=int(module.params['iscsi']['port'])
                    if module.params['iscsi']['port'].isdigit() else None,
                    username=module.params['iscsi']['username'],
                    password=module.params['iscsi']['password'],
                    address=module.params['iscsi']['address'],
                ), )
            ret = {
                'changed': False,
                'id': host_id,
                'iscsi_targets': iscsi_targets,
            }
        elif state == 'iscsilogin':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            ret = hosts_module.action(
                action='iscsi_login',
                iscsi=otypes.IscsiDetails(
                    port=int(module.params['iscsi']['port'])
                    if module.params['iscsi']['port'].isdigit() else None,
                    username=module.params['iscsi']['username'],
                    password=module.params['iscsi']['password'],
                    address=module.params['iscsi']['address'],
                    target=module.params['iscsi']['target'],
                ),
            )
        elif state == 'started':
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status == hoststate.DOWN,
                wait_condition=lambda h: h.status in
                [hoststate.UP, hoststate.MAINTENANCE],
                fail_condition=failed_state,
                fence_type='start',
            )
        elif state == 'stopped':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status != hoststate.DOWN,
                wait_condition=lambda h: h.status == hoststate.DOWN
                if module.params['wait'] else True,
                fail_condition=failed_state,
                fence_type='stop',
            )
        elif state == 'restarted':
            ret = hosts_module.action(
                action='fence',
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
                fence_type='restart',
            )
        elif state == 'reinstalled':
            # Deactivate host if not in maintanence:
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )

            # Reinstall host:
            hosts_module.action(
                action='install',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                post_action=hosts_module.post_reinstall,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
                host=otypes.Host(
                    override_iptables=module.params['override_iptables'], )
                if module.params['override_iptables'] else None,
                root_password=module.params['password'],
                ssh=otypes.Ssh(authentication_method=otypes.
                               SshAuthenticationMethod.PUBLICKEY, )
                if module.params['public_key'] else None,
                deploy_hosted_engine=(module.params.get('hosted_engine')
                                      == 'deploy')
                if module.params.get('hosted_engine') is not None else None,
                undeploy_hosted_engine=(module.params.get('hosted_engine')
                                        == 'undeploy')
                if module.params.get('hosted_engine') is not None else None,
            )

            # Activate host after reinstall:
            ret = hosts_module.action(
                action='activate',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
            )
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #23
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached', 'exported'],
            default='present'),
        id=dict(default=None),
        name=dict(default=None, aliases=['alias']),
        description=dict(default=None),
        vm_name=dict(default=None),
        vm_id=dict(default=None),
        size=dict(default=None),
        interface=dict(default=None, ),
        storage_domain=dict(default=None),
        storage_domains=dict(default=None, type='list'),
        profile=dict(default=None),
        quota_id=dict(default=None),
        format=dict(default='cow', choices=['raw', 'cow']),
        sparse=dict(default=None, type='bool'),
        bootable=dict(default=None, type='bool'),
        shareable=dict(default=None, type='bool'),
        logical_unit=dict(default=None, type='dict'),
        download_image_path=dict(default=None),
        upload_image_path=dict(default=None, aliases=['image_path']),
        force=dict(default=False, type='bool'),
        sparsify=dict(default=None, type='bool'),
        openstack_volume_type=dict(default=None),
        image_provider=dict(default=None),
        host=dict(default=None),
        wipe_after_delete=dict(type='bool', default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    lun = module.params.get('logical_unit')
    host = module.params['host']
    # Fail when host is specified with the LUN id. Lun id is needed to identify
    # an existing disk if already available inthe environment.
    if (host and lun is None) or (host and lun.get("id") is None):
        module.fail_json(msg="Can not use parameter host ({0!s}) without "
                         "specifying the logical_unit id".format(host))

    check_sdk(module)
    check_params(module)

    try:
        disk = None
        state = module.params['state']
        auth = module.params.get('auth')
        connection = create_connection(auth)
        disks_service = connection.system_service().disks_service()
        disks_module = DisksModule(
            connection=connection,
            module=module,
            service=disks_service,
        )

        if lun:
            disk = _search_by_lun(disks_service, lun.get('id'))

        ret = None
        # First take care of creating the VM, if needed:
        if state in ('present', 'detached', 'attached'):
            ret = disks_module.create(
                entity=disk,
                search_params=searchable_attributes(module),
                result_state=otypes.DiskStatus.OK if lun is None else None,
                fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL
                if lun is None else False,
            )
            is_new_disk = ret['changed']
            ret['changed'] = ret[
                'changed'] or disks_module.update_storage_domains(ret['id'])
            # We need to pass ID to the module, so in case we want detach/attach disk
            # we have this ID specified to attach/detach method:
            module.params['id'] = ret['id'] if disk is None else disk.id

            # Upload disk image in case it's new disk or force parameter is passed:
            if module.params['upload_image_path'] and (is_new_disk or
                                                       module.params['force']):
                uploaded = upload_disk_image(connection, module)
                ret['changed'] = ret['changed'] or uploaded
            # Download disk image in case it's file don't exist or force parameter is passed:
            if (module.params['download_image_path'] and
                (not os.path.isfile(module.params['download_image_path'])
                 or module.params['force'])):
                downloaded = download_disk_image(connection, module)
                ret['changed'] = ret['changed'] or downloaded

            # Disk sparsify, only if disk is of image type:
            disk = disks_service.disk_service(module.params['id']).get()
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='sparsify',
                    action_condition=lambda d: module.params['sparsify'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                )

        # Export disk as image to glance domain
        elif state == 'exported':
            disk = disks_module.search_entity()
            if disk is None:
                module.fail_json(
                    msg="Can not export given disk '%s', it doesn't exist" %
                    module.params.get('name') or module.params.get('id'))
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='export',
                    action_condition=lambda d: module.params['image_provider'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                    storage_domain=otypes.StorageDomain(
                        name=module.params['image_provider']),
                )
        elif state == 'absent':
            ret = disks_module.remove()

        # If VM was passed attach/detach disks to/from the VM:
        if module.params.get('vm_id') is not None or module.params.get(
                'vm_name') is not None and state != 'absent':
            vms_service = connection.system_service().vms_service()

            # If `vm_id` isn't specified, find VM by name:
            vm_id = module.params['vm_id']
            if vm_id is None:
                vm_id = getattr(
                    search_by_name(vms_service, module.params['vm_name']),
                    'id', None)

            if vm_id is None:
                module.fail_json(
                    msg="VM don't exists, please create it first.")

            disk_attachments_service = vms_service.vm_service(
                vm_id).disk_attachments_service()
            disk_attachments_module = DiskAttachmentsModule(
                connection=connection,
                module=module,
                service=disk_attachments_service,
                changed=ret['changed'] if ret else False,
            )

            if state == 'present' or state == 'attached':
                ret = disk_attachments_module.create()
                if lun is None:
                    wait(
                        service=disk_attachments_service.service(ret['id']),
                        condition=lambda d: follow_link(connection, d.disk).
                        status == otypes.DiskStatus.OK,
                        wait=module.params['wait'],
                        timeout=module.params['timeout'],
                    )
            elif state == 'detached':
                ret = disk_attachments_module.remove()

        # When the host parameter is specified and the disk is not being
        # removed, refresh the information about the LUN.
        if state != 'absent' and host:
            hosts_service = connection.system_service().hosts_service()
            host_id = get_id_by_name(hosts_service, host)
            disks_service.disk_service(disk.id).refresh_lun(
                otypes.Host(id=host_id))

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #24
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        host=dict(required=True),
        iscsi=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_host_storage_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_host_storage_facts' module has been renamed to 'ovirt_host_storage_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)

        # Get Host
        hosts_service = connection.system_service().hosts_service()
        host_id = get_id_by_name(hosts_service, module.params['host'])
        storage_type = _get_storage_type(module.params)
        host_service = hosts_service.host_service(host_id)

        if storage_type == 'iscsi':
            # Login
            iscsi = module.params.get('iscsi')
            _login(host_service, iscsi)

        # Get LUNs exposed from the specified target
        host_storages = host_service.storage_service().list()

        if storage_type == 'iscsi':
            filterred_host_storages = [
                host_storage for host_storage in host_storages
                if host_storage.type == otypes.StorageType.ISCSI
            ]
            if 'target' in iscsi:
                filterred_host_storages = [
                    host_storage for host_storage in filterred_host_storages if
                    iscsi.get('target') == host_storage.logical_units[0].target
                ]
        elif storage_type == 'fcp':
            filterred_host_storages = [
                host_storage for host_storage in host_storages
                if host_storage.type == otypes.StorageType.FCP
            ]

        result = dict(ovirt_host_storages=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in filterred_host_storages
        ], )
        if is_old_facts:
            module.exit_json(changed=False, ansible_facts=result)
        else:
            module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
コード例 #25
0
 def _get_network_id(self):
     networks_service = self._get_dcs_service().service(
         self._get_dcs_id()).networks_service()
     return get_id_by_name(networks_service, self.param('network'))
コード例 #26
0
 def _get_qos_id(self):
     qoss_service = self._get_dcs_service().service(
         self._get_dcs_id()).qoss_service()
     return get_id_by_name(qoss_service, self.param('qos'))
コード例 #27
0
ファイル: ovirt_cluster.py プロジェクト: ernstp/ansible
 def build_entity(self):
     sched_policy = self._get_sched_policy()
     return otypes.Cluster(
         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') or
                 self.param('fence_skip_if_connectivity_broken') or
                 self.param('fence_skip_if_sd_active')
             ),
             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') 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_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') or self.param('ksm_numa'),
             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=self.param('cpu_arch'),
             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,
     )
コード例 #28
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        cluster=dict(default=None, required=True),
        name=dict(default=None, required=True),
        description=dict(default=None),
        vm_enforcing=dict(default=None, type='bool'),
        vm_rule=dict(default=None, choices=['positive', 'negative', 'disabled']),
        host_enforcing=dict(default=None, type='bool'),
        host_rule=dict(default=None, choices=['positive', 'negative']),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    if module._name == 'ovirt_affinity_groups':
        module.deprecate("The 'ovirt_affinity_groups' module is being renamed 'ovirt_affinity_group'", version=2.8)

    check_sdk(module)
    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        # Check if unsupported parameters were passed:
        supported_41 = ('host_enforcing', 'host_rule', 'hosts')
        if not check_support(
            version='4.1',
            connection=connection,
            module=module,
            params=supported_41,
        ):
            module.fail_json(
                msg='Following parameters are supported since 4.1: {params}'.format(
                    params=supported_41,
                )
            )
        clusters_service = connection.system_service().clusters_service()
        vms_service = connection.system_service().vms_service()
        hosts_service = connection.system_service().hosts_service()
        cluster_name = module.params['cluster']
        cluster = search_by_name(clusters_service, cluster_name)
        if cluster is None:
            raise Exception("Cluster '%s' was not found." % cluster_name)
        cluster_service = clusters_service.cluster_service(cluster.id)
        affinity_groups_service = cluster_service.affinity_groups_service()

        # Fetch VM ids which should be assigned to affinity group:
        vm_ids = sorted([
            get_id_by_name(vms_service, vm_name)
            for vm_name in module.params['vms']
        ]) if module.params['vms'] is not None else None
        # Fetch host ids which should be assigned to affinity group:
        host_ids = sorted([
            get_id_by_name(hosts_service, host_name)
            for host_name in module.params['hosts']
        ]) if module.params['hosts'] is not None else None

        affinity_groups_module = AffinityGroupsModule(
            connection=connection,
            module=module,
            service=affinity_groups_service,
            vm_ids=vm_ids,
            host_ids=host_ids,
        )

        state = module.params['state']
        if state == 'present':
            ret = affinity_groups_module.create()
        elif state == 'absent':
            ret = affinity_groups_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)