def update_check(self, entity):
     template_display = entity.display
     return (
         equal(self._module.params.get('cluster'),
               get_link_name(self._connection, entity.cluster)) and
         equal(self._module.params.get('description'), entity.description)
         and equal(self.param('operating_system'), str(entity.os.type))
         and equal(self.param('name'), str(entity.name))
         and equal(self.param('smartcard_enabled'),
                   getattr(template_display, 'smartcard_enabled', False))
         and equal(self.param('soundcard_enabled'),
                   entity.soundcard_enabled)
         and equal(self.param('ballooning_enabled'),
                   entity.memory_policy.ballooning)
         and equal(self.param('sso'), True if entity.sso.methods else False)
         and equal(self.param('timezone'),
                   getattr(entity.time_zone, 'name', None))
         and equal(self.param('usb_support'), entity.usb.enabled)
         and equal(convert_to_bytes(self.param('memory_guaranteed')),
                   entity.memory_policy.guaranteed)
         and equal(convert_to_bytes(self.param('memory_max')),
                   entity.memory_policy.max)
         and equal(convert_to_bytes(self.param('memory')), entity.memory)
         and equal(self._module.params.get('cpu_profile'),
                   get_link_name(self._connection, entity.cpu_profile))
         and equal(self.param('io_threads'), entity.io.threads))
Beispiel #2
0
def _permission(module, permissions_service, connection):
    for permission in permissions_service.list():
        user = follow_link(connection, permission.user)
        if (equal(module.params['user_name'], user.principal if user else None)
                and equal(module.params['group_name'],
                          get_link_name(connection, permission.group))
                and equal(module.params['role'],
                          get_link_name(connection, permission.role))):
            return permission
Beispiel #3
0
    def has_update(self, nic_service):
        update = False
        bond = self._module.params['bond']
        networks = self._module.params['networks']
        labels = self._module.params['labels']
        nic = get_entity(nic_service)

        if nic is None:
            return update

        # Check if bond configuration should be updated:
        if bond:
            update = self.__compare_options(
                get_bond_options(bond.get('mode'), bond.get('options')),
                getattr(nic.bonding, 'options', []))
            update = update or not equal(
                sorted(bond.get('interfaces'))
                if bond.get('interfaces') else None,
                sorted(
                    get_link_name(self._connection, s)
                    for s in nic.bonding.slaves))

        # Check if labels need to be updated on interface/bond:
        if labels:
            net_labels = nic_service.network_labels_service().list()
            # If any labels which user passed aren't assigned, relabel the interface:
            if sorted(labels) != sorted([lbl.id for lbl in net_labels]):
                return True

        if not networks:
            return update

        # Check if networks attachments configuration should be updated:
        attachments_service = nic_service.network_attachments_service()
        network_names = [network.get('name') for network in networks]

        attachments = {}
        for attachment in attachments_service.list():
            name = get_link_name(self._connection, attachment.network)
            if name in network_names:
                attachments[name] = attachment

        for network in networks:
            attachment = attachments.get(network.get('name'))
            # If attachment don't exists, we need to create it:
            if attachment is None:
                return True
            self.update_custom_properties(attachments_service, attachment,
                                          network)
            self.update_address(attachments_service, attachment, network)

        return update
Beispiel #4
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        authz_name=dict(required=True, aliases=['domain']),
        user_name=dict(default=None),
        group_name=dict(default=None),
        namespace=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        permissions_service = _permissions_service(connection, module)
        permissions = []
        for p in permissions_service.list():
            newperm = dict()
            for key, value in p.__dict__.items():
                if value and isinstance(value, sdk.Struct):
                    newperm[key[1:]] = get_link_name(connection, value)
                    newperm['%s_id' % key[1:]] = value.id
            permissions.append(newperm)

        result = dict(ovirt_permissions=permissions)
        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)
Beispiel #5
0
 def update_check(self, entity):
     return (
         equal(self._module.params.get('name'), entity.name) and
         equal(self._module.params.get('cluster'), get_link_name(self._connection, entity.cluster)) and
         equal(self._module.params.get('description'), entity.description) and
         equal(self._module.params.get('comment'), entity.comment) and
         equal(self._module.params.get('vm_per_user'), entity.max_user_vms) and
         equal(self._module.params.get('prestarted'), entity.prestarted_vms) and
         equal(self._module.params.get('vm_count'), entity.size)
     )
 def update_check(self, entity):
     if self._module.params.get('vm'):
         return (
             equal(self._module.params.get('interface'),
                   str(entity.interface))
             and equal(self._module.params.get('linked'), entity.linked)
             and equal(self._module.params.get('name'), str(entity.name))
             and equal(self._module.params.get('profile'),
                       get_link_name(self._connection, entity.vnic_profile))
             and equal(self._module.params.get('mac_address'),
                       entity.mac.address))
     elif self._module.params.get('template'):
         return (equal(self._module.params.get('interface'),
                       str(entity.interface))
                 and equal(self._module.params.get('linked'), entity.linked)
                 and equal(self._module.params.get('name'), str(
                     entity.name))
                 and equal(
                     self._module.params.get('profile'),
                     get_link_name(self._connection, entity.vnic_profile)))
    def update_storage_limits(self, entity):
        new_limits = {}
        for storage in self._module.params.get('storages'):
            new_limits[storage.get('name', '')] = {
                'size': storage.get('size'),
            }

        old_limits = {}
        sd_limit_service = self._service.service(
            entity.id).quota_storage_limits_service()
        for limit in sd_limit_service.list():
            storage = get_link_name(
                self._connection,
                limit.storage_domain) if limit.storage_domain else ''
            old_limits[storage] = {
                'size': limit.limit,
            }
            sd_limit_service.service(limit.id).remove()

        return new_limits == old_limits
    def update_cluster_limits(self, entity):
        new_limits = {}
        for cluster in self._module.params.get('clusters'):
            new_limits[cluster.get('name', '')] = {
                'cpu': cluster.get('cpu'),
                'memory': float(cluster.get('memory')),
            }

        old_limits = {}
        cl_limit_service = self._service.service(
            entity.id).quota_cluster_limits_service()
        for limit in cl_limit_service.list():
            cluster = get_link_name(self._connection,
                                    limit.cluster) if limit.cluster else ''
            old_limits[cluster] = {
                'cpu': limit.vcpu_limit,
                'memory': limit.memory_limit,
            }
            cl_limit_service.service(limit.id).remove()

        return new_limits == old_limits
def main():
    argument_spec = ovirt_info_full_argument_spec(
        authz_name=dict(required=True, aliases=['domain']),
        user_name=dict(default=None),
        group_name=dict(default=None),
        namespace=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name in ('ovirt_permission_facts',
                                    'community.general.ovirt_permission_facts')
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_permission_facts' module has been renamed to 'ovirt_permission_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)
        permissions_service = _permissions_service(connection, module)
        permissions = []
        for p in permissions_service.list():
            newperm = dict()
            for key, value in p.__dict__.items():
                if value and isinstance(value, sdk.Struct):
                    newperm[key[1:]] = get_link_name(connection, value)
                    newperm['%s_id' % key[1:]] = value.id
            permissions.append(newperm)

        result = dict(ovirt_permissions=permissions)
        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)
Beispiel #10
0
def get_disk_attachment(disk, disk_attachments, connection):
    for disk_attachment in disk_attachments:
        if get_link_name(connection, disk_attachment.disk) == disk.get('name') or\
                disk_attachment.disk.id == disk.get('id'):
            return disk_attachment
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'plugged', 'present', 'unplugged']),
        vm=dict(type='str'),
        id=dict(default=None),
        template=dict(type='str'),
        name=dict(type='str', required=True),
        interface=dict(type='str'),
        template_version=dict(type='int', default=None),
        profile=dict(type='str'),
        network=dict(type='str'),
        mac_address=dict(type='str'),
        linked=dict(type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['vm', 'template']],
    )

    check_sdk(module)

    try:
        # Locate the service that manages the virtual machines and use it to
        # search for the NIC:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        entity_name = None

        if module.params.get('vm'):
            # Locate the VM, where we will manage NICs:
            entity_name = module.params.get('vm')
            collection_service = connection.system_service().vms_service()
        elif module.params.get('template'):
            entity_name = module.params.get('template')
            collection_service = connection.system_service().templates_service(
            )

        # TODO: We have to modify the search_by_name function to accept raise_error=True/False,
        if module.params['template_version'] is not None:
            entity = [
                t for t in collection_service.list() if
                t.version.version_number == module.params['template_version']
            ]
            if not entity:
                raise ValueError(
                    "Template with name '%s' and version '%s' was not found'" %
                    (module.params['template'],
                     module.params['template_version']))
            entity = entity[0]
        else:
            entity = search_by_name(collection_service, entity_name)
        if entity is None:
            raise Exception("Vm/Template '%s' was not found." % entity_name)

        service = collection_service.service(entity.id)
        cluster_id = entity.cluster

        nics_service = service.nics_service()
        entitynics_module = EntityNicsModule(
            connection=connection,
            module=module,
            service=nics_service,
        )

        # Find vNIC id of the network interface (if any):
        if module.params['network']:
            profile = module.params.get('profile')
            cluster_name = get_link_name(connection, cluster_id)
            dcs_service = connection.system_service().data_centers_service()
            dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0]
            networks_service = dcs_service.service(dc.id).networks_service()
            network = next((n for n in networks_service.list()
                            if n.name == module.params['network']), None)
            if network is None:
                raise Exception(
                    "Network '%s' was not found in datacenter '%s'." %
                    (module.params['network'], dc.name))
            if profile:
                for vnic in connection.system_service().vnic_profiles_service(
                ).list():
                    if vnic.name == profile and vnic.network.id == network.id:
                        entitynics_module.vnic_id = vnic.id
            else:
                # When not specified which vnic use ovirtmgmt/ovirtmgmt
                vnics = get_vnics(networks_service, network, connection)
                if len(vnics) == 1:
                    entitynics_module.vnic_id = vnics[0].id
                else:
                    raise Exception(
                        "You didn't specify any vnic profile. "
                        "Following vnic profiles are in system: '%s', please specify one of them"
                        % ([vnic.name for vnic in vnics]))
        # Handle appropriate action:
        state = module.params['state']
        if state == 'present':
            ret = entitynics_module.create()
        elif state == 'absent':
            ret = entitynics_module.remove()
        elif state == 'plugged':
            entitynics_module.create()
            ret = entitynics_module.action(
                action='activate',
                action_condition=lambda nic: not nic.plugged,
                wait_condition=lambda nic: nic.plugged,
            )
        elif state == 'unplugged':
            entitynics_module.create()
            ret = entitynics_module.action(
                action='deactivate',
                action_condition=lambda nic: nic.plugged,
                wait_condition=lambda nic: not nic.plugged,
            )

        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)
Beispiel #12
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.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)

        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)