def build_entity(self):
        storage_type = self._get_storage_type()
        storage = self._get_storage()
        self._login(storage_type, storage)

        return otypes.StorageDomain(
            name=self.param('name'),
            description=self.param('description'),
            comment=self.param('comment'),
            wipe_after_delete=self.param('wipe_after_delete'),
            backup=self.param('backup'),
            critical_space_action_blocker=self.param('critical_space_action_blocker'),
            warning_low_space_indicator=self.param('warning_low_space'),
            import_=True if self.param('state') == 'imported' else None,
            id=self.param('id') if self.param('state') == 'imported' else None,
            type=otypes.StorageDomainType(storage_type if storage_type == 'managed_block_storage' else self.param('domain_function')),
            host=otypes.Host(name=self.param('host')),
            discard_after_delete=self.param('discard_after_delete'),
            storage=otypes.HostStorage(
                driver_options=[
                    otypes.Property(
                        name=do.get('name'),
                        value=do.get('value')
                    ) for do in storage.get('driver_options')
                ] if storage.get('driver_options') else None,
                driver_sensitive_options=[
                    otypes.Property(
                        name=dso.get('name'),
                        value=dso.get('value')
                    ) for dso in storage.get('driver_sensitive_options')
                ] if storage.get('driver_sensitive_options') else None,
                type=otypes.StorageType(storage_type),
                logical_units=[
                    otypes.LogicalUnit(
                        id=lun_id,
                        address=storage.get('address'),
                        port=int(storage.get('port', 3260)),
                        target=target,
                        username=storage.get('username'),
                        password=storage.get('password'),
                    ) for lun_id, target in self.__target_lun_map(storage)
                ] if storage_type in ['iscsi', 'fcp'] else None,
                override_luns=storage.get('override_luns'),
                mount_options=storage.get('mount_options'),
                vfs_type=(
                    'glusterfs'
                    if storage_type in ['glusterfs'] else storage.get('vfs_type')
                ),
                address=storage.get('address'),
                path=storage.get('path'),
                nfs_retrans=storage.get('retrans'),
                nfs_timeo=storage.get('timeout'),
                nfs_version=otypes.NfsVersion(
                    storage.get('version')
                ) if storage.get('version') else None,
            ) if storage_type is not None else None,
            storage_format=self._get_storage_format(),
        )
Пример #2
0
 def update_custom_properties(self, attachments_service, attachment, network):
     if network.get('custom_properties'):
         current = []
         if attachment.properties:
             current = [(cp.name, str(cp.value)) for cp in attachment.properties]
         passed = [(cp.get('name'), str(cp.get('value'))) for cp in network.get('custom_properties') if cp]
         if sorted(current) != sorted(passed):
             attachment.properties = [
                 otypes.Property(
                     name=prop.get('name'),
                     value=prop.get('value')
                 ) for prop in network.get('custom_properties')
             ]
             if not self._module.check_mode:
                 attachments_service.service(attachment.id).update(attachment)
             self.changed = True
 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'),
     )
Пример #4
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list', elements='dict'),
        labels=dict(default=None, type='list', elements='str'),
        check=dict(default=None, type='bool'),
        save=dict(default=True, type='bool'),
        sync_networks=dict(default=False, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    check_sdk(module)

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

        host = host_networks_module.search_entity()
        if host is None:
            raise Exception("Host '%s' was not found." % module.params['name'])

        bond = module.params['bond']
        interface = module.params['interface']
        networks = module.params['networks']
        labels = module.params['labels']
        nic_name = bond.get('name') if bond else module.params['interface']

        host_service = hosts_service.host_service(host.id)
        nics_service = host_service.nics_service()
        nic = search_by_name(nics_service, nic_name)

        if module.params["sync_networks"]:
            if needs_sync(nics_service):
                if not module.check_mode:
                    host_service.sync_all_networks()
                host_networks_module.changed = True

        network_names = [network['name'] for network in networks or []]
        state = module.params['state']

        if (
            state == 'present' and
            (nic is None or host_networks_module.has_update(nics_service.service(nic.id)))
        ):
            # Remove networks which are attached to different interface then user want:
            attachments_service = host_service.network_attachments_service()

            # Append attachment ID to network if needs update:
            for a in attachments_service.list():
                current_network_name = get_link_name(connection, a.network)
                if current_network_name in network_names:
                    for n in networks:
                        if n['name'] == current_network_name:
                            n['id'] = a.id

            # Check if we have to break some bonds:
            removed_bonds = []
            if nic is not None:
                for host_nic in nics_service.list():
                    if host_nic.bonding and nic.id in [slave.id for slave in host_nic.bonding.slaves]:
                        removed_bonds.append(otypes.HostNic(id=host_nic.id))

            # Assign the networks:
            setup_params = dict(
                entity=host,
                action='setup_networks',
                check_connectivity=module.params['check'],
                removed_bonds=removed_bonds if removed_bonds else None,
                modified_bonds=[
                    otypes.HostNic(
                        name=bond.get('name'),
                        bonding=otypes.Bonding(
                            options=get_bond_options(bond.get('mode'), bond.get('options')),
                            slaves=[
                                otypes.HostNic(name=i) for i in bond.get('interfaces', [])
                            ],
                        ),
                    ),
                ] if bond else None,
                modified_labels=[
                    otypes.NetworkLabel(
                        id=str(name),
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface
                        ),
                    ) for name in labels
                ] if labels else None,
                modified_network_attachments=[
                    otypes.NetworkAttachment(
                        id=network.get('id'),
                        network=otypes.Network(
                            name=network['name']
                        ) if network['name'] else None,
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface
                        ),
                        ip_address_assignments=[
                            otypes.IpAddressAssignment(
                                assignment_method=otypes.BootProtocol(
                                    network.get('boot_protocol', 'none')
                                ),
                                ip=otypes.Ip(
                                    address=network.get('address'),
                                    gateway=network.get('gateway'),
                                    netmask=network.get('netmask'),
                                    version=otypes.IpVersion(
                                        network.get('version')
                                    ) if network.get('version') else None,
                                ),
                            ),
                        ],
                        properties=[
                            otypes.Property(
                                name=prop.get('name'),
                                value=prop.get('value')
                            ) for prop in network.get('custom_properties', [])
                        ]
                    ) for network in networks
                ] if networks else None,
            )
            if engine_supported(connection, '4.3'):
                setup_params['commit_on_success'] = module.params['save']
            elif module.params['save']:
                setup_params['post_action'] = host_networks_module._action_save_configuration
            host_networks_module.action(**setup_params)
        elif state == 'absent' and nic:
            attachments = []
            nic_service = nics_service.nic_service(nic.id)

            attached_labels = set([str(lbl.id) for lbl in nic_service.network_labels_service().list()])
            if networks:
                attachments_service = nic_service.network_attachments_service()
                attachments = attachments_service.list()
                attachments = [
                    attachment for attachment in attachments
                    if get_link_name(connection, attachment.network) in network_names
                ]

            # Remove unmanaged networks:
            unmanaged_networks_service = host_service.unmanaged_networks_service()
            unmanaged_networks = [(u.id, u.name) for u in unmanaged_networks_service.list()]
            for net_id, net_name in unmanaged_networks:
                if net_name in network_names:
                    if not module.check_mode:
                        unmanaged_networks_service.unmanaged_network_service(net_id).remove()
                    host_networks_module.changed = True

            # Need to check if there are any labels to be removed, as backend fail
            # if we try to send remove non existing label, for bond and attachments it's OK:
            if (labels and set(labels).intersection(attached_labels)) or bond or attachments:
                setup_params = dict(
                    entity=host,
                    action='setup_networks',
                    check_connectivity=module.params['check'],
                    removed_bonds=[
                        otypes.HostNic(
                            name=bond.get('name'),
                        ),
                    ] if bond else None,
                    removed_labels=[
                        otypes.NetworkLabel(id=str(name)) for name in labels
                    ] if labels else None,
                    removed_network_attachments=attachments if attachments else None,
                )
                if engine_supported(connection, '4.4'):
                    setup_params['commit_on_success'] = module.params['save']
                elif module.params['save']:
                    setup_params['post_action'] = host_networks_module._action_save_configuration
                host_networks_module.action(**setup_params)

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(**{
            'changed': host_networks_module.changed,
            'id': nic.id if nic else None,
            'host_nic': get_dict_of_struct(nic),
        })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)