Beispiel #1
0
def create_fs(module, blade):
    """Create Filesystem"""
    changed = True
    if not module.check_mode:
        try:

            if not module.params['size']:
                module.params['size'] = '32G'

            size = human_to_bytes(module.params['size'])
            nfsv3 = module.params['nfs'] if module.params['nfsv3'] is None else module.params['nfsv3']

            if module.params['user_quota']:
                user_quota = human_to_bytes(module.params['user_quota'])
            else:
                user_quota = None
            if module.params['group_quota']:
                group_quota = human_to_bytes(module.params['group_quota'])
            else:
                group_quota = None

            api_version = blade.api_version.list_versions().versions
            if HARD_LIMIT_API_VERSION in api_version:
                if NFSV4_API_VERSION in api_version:
                    fs_obj = FileSystem(name=module.params['name'],
                                        provisioned=size,
                                        fast_remove_directory_enabled=module.params['fastremove'],
                                        hard_limit_enabled=module.params['hard_limit'],
                                        snapshot_directory_enabled=module.params['snapshot'],
                                        nfs=NfsRule(v3_enabled=nfsv3,
                                                    v4_1_enabled=module.params['nfsv4'],
                                                    rules=module.params['nfs_rules']),
                                        smb=ProtocolRule(enabled=module.params['smb']),
                                        http=ProtocolRule(enabled=module.params['http']),
                                        default_user_quota=user_quota,
                                        default_group_quota=group_quota
                                        )
                else:
                    fs_obj = FileSystem(name=module.params['name'],
                                        provisioned=size,
                                        fast_remove_directory_enabled=module.params['fastremove'],
                                        hard_limit_enabled=module.params['hard_limit'],
                                        snapshot_directory_enabled=module.params['snapshot'],
                                        nfs=NfsRule(enabled=nfsv3, rules=module.params['nfs_rules']),
                                        smb=ProtocolRule(enabled=module.params['smb']),
                                        http=ProtocolRule(enabled=module.params['http'])
                                        )
            else:
                fs_obj = FileSystem(name=module.params['name'],
                                    provisioned=size,
                                    fast_remove_directory_enabled=module.params['fastremove'],
                                    snapshot_directory_enabled=module.params['snapshot'],
                                    nfs=NfsRule(enabled=module.params['nfs'], rules=module.params['nfs_rules']),
                                    smb=ProtocolRule(enabled=module.params['smb']),
                                    http=ProtocolRule(enabled=module.params['http'])
                                    )
            blade.file_systems.create_file_systems(fs_obj)
        except Exception:
            module.fail_json(msg="Failed to create filesystem {0}.".format(module.params['name']))
    module.exit_json(changed=changed)
Beispiel #2
0
def modify_fs(module, blade):
    """Modify Filesystem"""
    changed = False
    attr = {}
    if not module.check_mode:
        fs = get_fs(module, blade)
        if fs.destroyed:
            attr['destroyed'] = False
            changed = True
        if module.params['size']:
            if human_to_bytes(module.params['size']) > fs.provisioned:
                attr['provisioned'] = human_to_bytes(module.params['size'])
                changed = True
        if module.params['nfs'] and not fs.nfs.enabled:
            attr['nfs'] = NfsRule(enabled=module.params['nfs'])
            changed = True
        if not module.params['nfs'] and fs.nfs.enabled:
            attr['nfs'] = NfsRule(enabled=module.params['nfs'])
            changed = True
        if module.params['nfs'] and fs.nfs.enabled:
            if fs.nfs.rules != module.params['nfs_rules']:
                attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])
                changed = True
        if module.params['smb'] and not fs.smb.enabled:
            attr['smb'] = ProtocolRule(enabled=module.params['smb'])
            changed = True
        if not module.params['smb'] and fs.smb.enabled:
            attr['smb'] = ProtocolRule(enabled=module.params['smb'])
            changed = True
        if module.params['http'] and not fs.http.enabled:
            attr['http'] = ProtocolRule(enabled=module.params['http'])
            changed = True
        if not module.params['http'] and fs.http.enabled:
            attr['http'] = ProtocolRule(enabled=module.params['http'])
            changed = True
        if module.params['snapshot'] and not fs.snapshot_directory_enabled:
            attr['snapshot_directory_enabled'] = module.params['snapshot']
            changed = True
        if not module.params['snapshot'] and fs.snapshot_directory_enabled:
            attr['snapshot_directory_enabled'] = module.params['snapshot']
            changed = True
        if module.params['fastremove'] and not fs.fast_remove_directory_enabled:
            attr['fast_remove_directory_enabled'] = module.params['fastremove']
            changed = True
        if not module.params['fastremove'] and fs.fast_remove_directory_enabled:
            attr['fast_remove_directory_enabled'] = module.params['fastremove']
            changed = True
        api_version = blade.api_version.list_versions().versions
        if HARD_LIMIT_API_VERSION in api_version:
            if not module.params['hard_limit'] and fs.hard_limit_enabled:
                attr['hard_limit_enabled'] = module.params['hard_limit']
                changed = True
        if changed:
            n_attr = FileSystem(**attr)
            try:
                blade.file_systems.update_file_systems(
                    name=module.params['name'], attributes=n_attr)
            except:
                changed = False
    module.exit_json(changed=changed)
Beispiel #3
0
def human_to_bytes(size, default_unit=None, isbits=False):
    ''' Return bytes count from a human readable string '''
    try:
        return basic.human_to_bytes(size, default_unit, isbits)
    except Exception:
        raise AnsibleFilterError(
            "human_to_bytes() can't interpret following string: %s" % size)
def convert_to_binary_multiple(size, size_unit):
    if size_unit == 'GiB':
        suffix = 'G'
    if size_unit == 'MiB':
        suffix = 'M'
    if size_unit == 'TiB':
        suffix = 'T'

    size_kib = basic.human_to_bytes(str(size) + suffix)
    return int(size_kib / (1024 * 1024))
Beispiel #5
0
def convert_to_binary_multiple(size_with_unit):
    if size_with_unit is None:
        return -1
    valid_units = ['MiB', 'GiB', 'TiB']
    valid_unit = False
    for unit in valid_units:
        if size_with_unit.strip().endswith(unit):
            valid_unit = True
            size = size_with_unit.split(unit)[0]
            if float(size) < 0:
                return -1
    if not valid_unit:
        raise ValueError("%s does not have a valid unit. The unit must be one of %s" % (size_with_unit, valid_units))

    size = size_with_unit.replace(" ", "").split('iB')[0]
    size_kib = basic.human_to_bytes(size)
    return int(size_kib / (1024 * 1024))
Beispiel #6
0
        def namespace_check(self):
            command = ['list', '-R']
            out = self.pmem_run_ndctl(command)
            if not out:
                return 'Available region(s) is not in this system.'
            region = json.loads(out)

            aligns = self.pmem_get_region_align_size(region)
            if len(aligns) != 1:
                return 'Not supported the regions whose alignment size is different.'

            available_size = self.pmem_get_available_region_size(region)
            types = self.pmem_get_available_region_type(region)
            for ns in self.namespace:
                if ns['size']:
                    try:
                        size_byte = human_to_bytes(ns['size'])
                    except ValueError:
                        return 'The format of size: NNN TB|GB|MB|KB|T|G|M|K|B'

                    if size_byte % aligns[0] != 0:
                        return 'size: %s should be align with %d' % (
                            ns['size'], aligns[0])

                    is_space_enough = False
                    for i, avail in enumerate(available_size):
                        if avail > size_byte:
                            available_size[i] -= size_byte
                            is_space_enough = True
                            break

                    if is_space_enough is False:
                        return 'There is not available region for size: %s' % ns[
                            'size']

                    ns['size_byte'] = size_byte

                elif len(self.namespace) != 1:
                    return 'size option is required to configure multiple namespaces'

                if ns['type'] not in types:
                    return 'type %s is not supported in this system. Supported type: %s' % (
                        ns['type'], types)

            return None
Beispiel #7
0
def create_fs(module, blade):
    """Create Filesystem"""

    if not module.params['size']:
        module.params['size'] = '32G'

    size = human_to_bytes(module.params['size'])

    if not module.check_mode:
        try:
            api_version = blade.api_version.list_versions().versions
            if HARD_LIMIT_API_VERSION in api_version:
                fs_obj = FileSystem(
                    name=module.params['name'],
                    provisioned=size,
                    fast_remove_directory_enabled=module.params['fastremove'],
                    hard_limit_enabled=module.params['hard_limit'],
                    snapshot_directory_enabled=module.params['snapshot'],
                    nfs=NfsRule(enabled=module.params['nfs'],
                                rules=module.params['nfs_rules']),
                    smb=ProtocolRule(enabled=module.params['smb']),
                    http=ProtocolRule(enabled=module.params['http']))
            else:
                fs_obj = FileSystem(
                    name=module.params['name'],
                    provisioned=size,
                    fast_remove_directory_enabled=module.params['fastremove'],
                    snapshot_directory_enabled=module.params['snapshot'],
                    nfs=NfsRule(enabled=module.params['nfs'],
                                rules=module.params['nfs_rules']),
                    smb=ProtocolRule(enabled=module.params['smb']),
                    http=ProtocolRule(enabled=module.params['http']))
            blade.file_systems.create_file_systems(fs_obj)
            changed = True
        except:
            changed = False
    module.exit_json(changed=changed)
Beispiel #8
0
    def from_ansible_params(ap, old_service):
        s = DockerService()
        s.constraints = ap['constraints']
        s.image = ap['image']
        s.args = ap['args']
        s.endpoint_mode = ap['endpoint_mode']
        s.dns = ap['dns']
        s.dns_search = ap['dns_search']
        s.dns_options = ap['dns_options']
        s.hostname = ap['hostname']
        s.tty = ap['tty']
        s.env = ap['env']
        s.log_driver = ap['log_driver']
        s.log_driver_options = ap['log_driver_options']
        s.labels = ap['labels']
        s.container_labels = ap['container_labels']
        s.limit_cpu = ap['limit_cpu']
        s.reserve_cpu = ap['reserve_cpu']
        s.mode = ap['mode']
        s.networks = ap['networks']
        s.restart_policy = ap['restart_policy']
        s.restart_policy_attempts = ap['restart_policy_attempts']
        s.restart_policy_delay = ap['restart_policy_delay']
        s.restart_policy_window = ap['restart_policy_window']
        s.update_delay = ap['update_delay']
        s.update_parallelism = ap['update_parallelism']
        s.update_failure_action = ap['update_failure_action']
        s.update_monitor = ap['update_monitor']
        s.update_max_failure_ratio = ap['update_max_failure_ratio']
        s.update_order = ap['update_order']
        s.user = ap['user']

        if ap['force_update']:
            s.force_update = int(str(time.time()).replace('.', ''))

        if ap['replicas'] == -1:
            if old_service:
                s.replicas = old_service.replicas
            else:
                s.replicas = 1
        else:
            s.replicas = ap['replicas']

        for param_name in ['reserve_memory', 'limit_memory']:
            if ap.get(param_name):
                try:
                    setattr(s, param_name, human_to_bytes(ap[param_name]))
                except ValueError as exc:
                    raise Exception("Failed to convert %s to bytes: %s" %
                                    (param_name, exc))

        s.publish = []
        for param_p in ap['publish']:
            service_p = {}
            service_p['protocol'] = param_p.get('protocol', 'tcp')
            service_p['mode'] = param_p.get('mode', 'ingress')
            service_p['published_port'] = int(param_p['published_port'])
            service_p['target_port'] = int(param_p['target_port'])
            if service_p['protocol'] not in ['tcp', 'udp']:
                raise ValueError(
                    "got publish.protocol '%s', valid values:'tcp', 'udp'" %
                    service_p['protocol'])
            if service_p['mode'] not in ['ingress', 'host']:
                raise ValueError(
                    "got publish.mode '%s', valid values:'ingress', 'host'" %
                    service_p['mode'])
            s.publish.append(service_p)
        s.mounts = []
        for param_m in ap['mounts']:
            service_m = {}
            service_m['readonly'] = bool(param_m.get('readonly', False))
            service_m['type'] = param_m.get('type', 'bind')
            service_m['source'] = param_m['source']
            service_m['target'] = param_m['target']
            s.mounts.append(service_m)

        s.configs = []
        for param_m in ap['configs']:
            service_c = {}
            service_c['config_id'] = param_m['config_id']
            service_c['config_name'] = str(param_m['config_name'])
            service_c['filename'] = param_m.get('filename',
                                                service_c['config_name'])
            service_c['uid'] = int(param_m.get('uid', "0"))
            service_c['gid'] = int(param_m.get('gid', "0"))
            service_c['mode'] = param_m.get('mode', 0o444)
            s.configs.append(service_c)

        s.secrets = []
        for param_m in ap['secrets']:
            service_s = {}
            service_s['secret_id'] = param_m['secret_id']
            service_s['secret_name'] = str(param_m['secret_name'])
            service_s['filename'] = param_m.get('filename',
                                                service_s['secret_name'])
            service_s['uid'] = int(param_m.get('uid', "0"))
            service_s['gid'] = int(param_m.get('gid', "0"))
            service_s['mode'] = param_m.get('mode', 0o444)
            s.secrets.append(service_s)
        return s
Beispiel #9
0
def modify_fs(module, blade):
    """Modify Filesystem"""
    changed = True
    if not module.check_mode:
        mod_fs = False
        attr = {}
        if module.params['user_quota']:
            user_quota = human_to_bytes(module.params['user_quota'])
        if module.params['group_quota']:
            group_quota = human_to_bytes(module.params['group_quota'])
        fsys = get_fs(module, blade)
        if fsys.destroyed:
            attr['destroyed'] = False
            mod_fs = True
        if module.params['size']:
            if human_to_bytes(module.params['size']) != fsys.provisioned:
                attr['provisioned'] = human_to_bytes(module.params['size'])
                mod_fs = True
        api_version = blade.api_version.list_versions().versions
        if NFSV4_API_VERSION in api_version:
            if module.params['nfsv3'] and not fsys.nfs.v3_enabled:
                attr['nfs'] = NfsRule(v3_enabled=module.params['nfsv3'])
                mod_fs = True
            if not module.params['nfsv3'] and fsys.nfs.v3_enabled:
                attr['nfs'] = NfsRule(v3_enabled=module.params['nfsv3'])
                mod_fs = True
            if module.params['nfsv4'] and not fsys.nfs.v4_1_enabled:
                attr['nfs'] = NfsRule(v4_1_enabled=module.params['nfsv4'])
                mod_fs = True
            if not module.params['nfsv4'] and fsys.nfs.v4_1_enabled:
                attr['nfs'] = NfsRule(v4_1_enabled=module.params['nfsv4'])
                mod_fs = True
            if module.params['nfsv3'] or module.params['nfsv4'] and fsys.nfs.v3_enabled or fsys.nfs.v4_1_enabled:
                if fsys.nfs.rules != module.params['nfs_rules']:
                    attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])
                    mod_fs = True
            if module.params['user_quota'] and user_quota != fsys.default_user_quota:
                attr['default_user_quota'] = user_quota
                mod_fs = True
            if module.params['group_quota'] and group_quota != fsys.default_group_quota:
                attr['default_group_quota'] = group_quota
                mod_fs = True
        else:
            if module.params['nfsv3'] and not fsys.nfs.enabled:
                attr['nfs'] = NfsRule(enabled=module.params['nfsv3'])
                mod_fs = True
            if not module.params['nfsv3'] and fsys.nfs.enabled:
                attr['nfs'] = NfsRule(enabled=module.params['nfsv3'])
                mod_fs = True
            if module.params['nfsv3'] and fsys.nfs.enabled:
                if fsys.nfs.rules != module.params['nfs_rules']:
                    attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])
                    mod_fs = True
        if module.params['smb'] and not fsys.smb.enabled:
            attr['smb'] = ProtocolRule(enabled=module.params['smb'])
            mod_fs = True
        if not module.params['smb'] and fsys.smb.enabled:
            attr['smb'] = ProtocolRule(enabled=module.params['smb'])
            mod_fs = True
        if module.params['http'] and not fsys.http.enabled:
            attr['http'] = ProtocolRule(enabled=module.params['http'])
            mod_fs = True
        if not module.params['http'] and fsys.http.enabled:
            attr['http'] = ProtocolRule(enabled=module.params['http'])
            mod_fs = True
        if module.params['snapshot'] and not fsys.snapshot_directory_enabled:
            attr['snapshot_directory_enabled'] = module.params['snapshot']
            mod_fs = True
        if not module.params['snapshot'] and fsys.snapshot_directory_enabled:
            attr['snapshot_directory_enabled'] = module.params['snapshot']
            mod_fs = True
        if module.params['fastremove'] and not fsys.fast_remove_directory_enabled:
            attr['fast_remove_directory_enabled'] = module.params['fastremove']
            mod_fs = True
        if not module.params['fastremove'] and fsys.fast_remove_directory_enabled:
            attr['fast_remove_directory_enabled'] = module.params['fastremove']
            mod_fs = True
        api_version = blade.api_version.list_versions().versions
        if HARD_LIMIT_API_VERSION in api_version:
            if not module.params['hard_limit'] and fsys.hard_limit_enabled:
                attr['hard_limit_enabled'] = module.params['hard_limit']
                mod_fs = True
            if module.params['hard_limit'] and not fsys.hard_limit_enabled:
                attr['hard_limit_enabled'] = module.params['hard_limit']
                mod_fs = True
        if mod_fs:
            n_attr = FileSystem(**attr)
            try:
                blade.file_systems.update_file_systems(name=module.params['name'], attributes=n_attr)
            except Exception:
                module.fail_json(msg="Failed to update filesystem {0}.".format(module.params['name']))
        else:
            changed = False
    module.exit_json(changed=changed)
Beispiel #10
0
def modify_fs(module, blade):
    """Modify Filesystem"""
    changed = True
    if not module.check_mode:
        changed = False
        mod_fs = False
        attr = {}
        if module.params['policy'] and module.params[
                'policy_state'] == 'present':
            try:
                policy = blade.policies.list_policy_filesystems(
                    policy_names=[module.params['policy']],
                    member_names=[module.params['name']])
            except Exception:
                module.fail_json(msg='Policy {0} does not exist.'.format(
                    module.params['policy']))
            if not policy.items:
                try:
                    blade.policies.create_policy_filesystems(
                        policy_names=[module.params['policy']],
                        member_names=[module.params['name']])
                    mod_fs = True
                except Exception:
                    module.fail_json(
                        msg='Failed to add filesystem {0} to policy {1}.'.
                        format(module.params['name'], module.params['polict']))
        if module.params['policy'] and module.params[
                'policy_state'] == 'absent':
            try:
                policy = blade.policies.list_policy_filesystems(
                    policy_names=[module.params['policy']],
                    member_names=[module.params['name']])
            except Exception:
                module.fail_json(msg='Policy {0} does not exist.'.format(
                    module.params['policy']))
            if len(policy.items) == 1:
                try:
                    blade.policies.delete_policy_filesystems(
                        policy_names=[module.params['policy']],
                        member_names=[module.params['name']])
                    mod_fs = True
                except Exception:
                    module.fail_json(
                        msg='Failed to remove filesystem {0} to policy {1}.'.
                        format(module.params['name'], module.params['polict']))
        if module.params['user_quota']:
            user_quota = human_to_bytes(module.params['user_quota'])
        if module.params['group_quota']:
            group_quota = human_to_bytes(module.params['group_quota'])
        fsys = get_fs(module, blade)
        if fsys.destroyed:
            attr['destroyed'] = False
            mod_fs = True
        if module.params['size']:
            if human_to_bytes(module.params['size']) != fsys.provisioned:
                attr['provisioned'] = human_to_bytes(module.params['size'])
                mod_fs = True
        api_version = blade.api_version.list_versions().versions
        if NFSV4_API_VERSION in api_version:
            if module.params['nfsv3'] and not fsys.nfs.v3_enabled:
                attr['nfs'] = NfsRule(v3_enabled=module.params['nfsv3'])
                mod_fs = True
            if not module.params['nfsv3'] and fsys.nfs.v3_enabled:
                attr['nfs'] = NfsRule(v3_enabled=module.params['nfsv3'])
                mod_fs = True
            if module.params['nfsv4'] and not fsys.nfs.v4_1_enabled:
                attr['nfs'] = NfsRule(v4_1_enabled=module.params['nfsv4'])
                mod_fs = True
            if not module.params['nfsv4'] and fsys.nfs.v4_1_enabled:
                attr['nfs'] = NfsRule(v4_1_enabled=module.params['nfsv4'])
                mod_fs = True
            if module.params['nfsv3'] or module.params[
                    'nfsv4'] and fsys.nfs.v3_enabled or fsys.nfs.v4_1_enabled:
                if module.params['nfs_rules'] is not None:
                    if fsys.nfs.rules != module.params['nfs_rules']:
                        attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])
                        mod_fs = True
            if module.params[
                    'user_quota'] and user_quota != fsys.default_user_quota:
                attr['default_user_quota'] = user_quota
                mod_fs = True
            if module.params[
                    'group_quota'] and group_quota != fsys.default_group_quota:
                attr['default_group_quota'] = group_quota
                mod_fs = True
        else:
            if module.params['nfsv3'] and not fsys.nfs.enabled:
                attr['nfs'] = NfsRule(enabled=module.params['nfsv3'])
                mod_fs = True
            if not module.params['nfsv3'] and fsys.nfs.enabled:
                attr['nfs'] = NfsRule(enabled=module.params['nfsv3'])
                mod_fs = True
            if module.params['nfsv3'] and fsys.nfs.enabled:
                if fsys.nfs.rules != module.params['nfs_rules']:
                    attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])
                    mod_fs = True
        if REPLICATION_API_VERSION in api_version:
            if module.params['smb'] and not fsys.smb.enabled:
                attr['smb'] = SmbRule(enabled=module.params['smb'],
                                      acl_mode=module.params['smb_aclmode'])
                mod_fs = True
            if not module.params['smb'] and fsys.smb.enabled:
                attr['smb'] = ProtocolRule(enabled=module.params['smb'])
                mod_fs = True
            if module.params['smb'] and fsys.smb.enabled:
                if fsys.smb.acl_mode != module.params['smb_aclmode']:
                    attr['smb'] = SmbRule(
                        enabled=module.params['smb'],
                        acl_mode=module.params['smb_aclmode'])
                    mod_fs = True
        else:
            if module.params['smb'] and not fsys.smb.enabled:
                attr['smb'] = ProtocolRule(enabled=module.params['smb'])
                mod_fs = True
            if not module.params['smb'] and fsys.smb.enabled:
                attr['smb'] = ProtocolRule(enabled=module.params['smb'])
                mod_fs = True
        if module.params['http'] and not fsys.http.enabled:
            attr['http'] = ProtocolRule(enabled=module.params['http'])
            mod_fs = True
        if not module.params['http'] and fsys.http.enabled:
            attr['http'] = ProtocolRule(enabled=module.params['http'])
            mod_fs = True
        if module.params['snapshot'] and not fsys.snapshot_directory_enabled:
            attr['snapshot_directory_enabled'] = module.params['snapshot']
            mod_fs = True
        if not module.params['snapshot'] and fsys.snapshot_directory_enabled:
            attr['snapshot_directory_enabled'] = module.params['snapshot']
            mod_fs = True
        if module.params[
                'fastremove'] and not fsys.fast_remove_directory_enabled:
            attr['fast_remove_directory_enabled'] = module.params['fastremove']
            mod_fs = True
        if not module.params[
                'fastremove'] and fsys.fast_remove_directory_enabled:
            attr['fast_remove_directory_enabled'] = module.params['fastremove']
            mod_fs = True
        if HARD_LIMIT_API_VERSION in api_version:
            if not module.params['hard_limit'] and fsys.hard_limit_enabled:
                attr['hard_limit_enabled'] = module.params['hard_limit']
                mod_fs = True
            if module.params['hard_limit'] and not fsys.hard_limit_enabled:
                attr['hard_limit_enabled'] = module.params['hard_limit']
                mod_fs = True
        if REPLICATION_API_VERSION in api_version:
            if module.params['writable'] is not None:
                if not module.params['writable'] and fsys.writable:
                    attr['writable'] = module.params['writable']
                    mod_fs = True
                if module.params[
                        'writable'] and not fsys.writable and fsys.promotion_status == 'promoted':
                    attr['writable'] = module.params['writable']
                    mod_fs = True
            if module.params['promote'] is not None:
                if module.params[
                        'promote'] and fsys.promotion_status != 'promoted':
                    attr['requested_promotion_state'] = 'promoted'
                    mod_fs = True
                if not module.params[
                        'promote'] and fsys.promotion_status == 'promoted':
                    # Demotion only allowed on filesystems in a replica-link
                    try:
                        blade.file_system_replica_links.list_file_system_replica_links(
                            local_file_system_names=[module.params['name']
                                                     ]).items[0]
                    except Exception:
                        module.fail_json(
                            msg=
                            'Filesystem {0} not demoted. Not in a replica-link'
                            .format(module.params['name']))
                    attr['requested_promotion_state'] = module.params[
                        'promote']
                    mod_fs = True
        if mod_fs:
            n_attr = FileSystem(**attr)
            try:
                blade.file_systems.update_file_systems(
                    name=module.params['name'], attributes=n_attr)
                changed = True
            except Exception:
                module.fail_json(msg="Failed to update filesystem {0}.".format(
                    module.params['name']))
    module.exit_json(changed=changed)
Beispiel #11
0
def create_fs(module, blade):
    """Create Filesystem"""
    changed = True
    if not module.check_mode:
        try:
            if not module.params['nfs_rules']:
                module.params['nfs_rules'] = '*(rw,no_root_squash)'
            if not module.params['size']:
                module.params['size'] = '32G'

            size = human_to_bytes(module.params['size'])

            if module.params['user_quota']:
                user_quota = human_to_bytes(module.params['user_quota'])
            else:
                user_quota = None
            if module.params['group_quota']:
                group_quota = human_to_bytes(module.params['group_quota'])
            else:
                group_quota = None

            api_version = blade.api_version.list_versions().versions
            if HARD_LIMIT_API_VERSION in api_version:
                if NFSV4_API_VERSION in api_version:
                    if REPLICATION_API_VERSION in api_version:
                        fs_obj = FileSystem(
                            name=module.params['name'],
                            provisioned=size,
                            fast_remove_directory_enabled=module.
                            params['fastremove'],
                            hard_limit_enabled=module.params['hard_limit'],
                            snapshot_directory_enabled=module.
                            params['snapshot'],
                            nfs=NfsRule(v3_enabled=module.params['nfsv3'],
                                        v4_1_enabled=module.params['nfsv4'],
                                        rules=module.params['nfs_rules']),
                            smb=SmbRule(enabled=module.params['smb'],
                                        acl_mode=module.params['smb_aclmode']),
                            http=ProtocolRule(enabled=module.params['http']),
                            default_user_quota=user_quota,
                            default_group_quota=group_quota)
                    else:
                        fs_obj = FileSystem(
                            name=module.params['name'],
                            provisioned=size,
                            fast_remove_directory_enabled=module.
                            params['fastremove'],
                            hard_limit_enabled=module.params['hard_limit'],
                            snapshot_directory_enabled=module.
                            params['snapshot'],
                            nfs=NfsRule(v3_enabled=module.params['nfsv3'],
                                        v4_1_enabled=module.params['nfsv4'],
                                        rules=module.params['nfs_rules']),
                            smb=ProtocolRule(enabled=module.params['smb']),
                            http=ProtocolRule(enabled=module.params['http']),
                            default_user_quota=user_quota,
                            default_group_quota=group_quota)
                else:
                    fs_obj = FileSystem(
                        name=module.params['name'],
                        provisioned=size,
                        fast_remove_directory_enabled=module.
                        params['fastremove'],
                        hard_limit_enabled=module.params['hard_limit'],
                        snapshot_directory_enabled=module.params['snapshot'],
                        nfs=NfsRule(enabled=module.params['nfsv3'],
                                    rules=module.params['nfs_rules']),
                        smb=ProtocolRule(enabled=module.params['smb']),
                        http=ProtocolRule(enabled=module.params['http']))
            else:
                fs_obj = FileSystem(
                    name=module.params['name'],
                    provisioned=size,
                    fast_remove_directory_enabled=module.params['fastremove'],
                    snapshot_directory_enabled=module.params['snapshot'],
                    nfs=NfsRule(enabled=module.params['nfs'],
                                rules=module.params['nfs_rules']),
                    smb=ProtocolRule(enabled=module.params['smb']),
                    http=ProtocolRule(enabled=module.params['http']))
            blade.file_systems.create_file_systems(fs_obj)
        except Exception:
            module.fail_json(msg="Failed to create filesystem {0}.".format(
                module.params['name']))
        if REPLICATION_API_VERSION in api_version:
            if module.params['policy']:
                try:
                    blade.policies.list_policies(
                        names=[module.params['policy']])
                except Exception:
                    _delete_fs(module, blade)
                    module.fail_json(msg="Policy {0} doesn't exist.".format(
                        module.params['policy']))
                try:
                    blade.policies.create_policy_filesystems(
                        policy_names=[module.params['policy']],
                        member_names=[module.params['name']])
                except Exception:
                    _delete_fs(module, blade)
                    module.fail_json(
                        msg=
                        "Failed to apply policy {0} when creating filesystem {1}."
                        .format(module.params['policy'],
                                module.params['name']))
    module.exit_json(changed=changed)
Beispiel #12
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            bhard=dict(type="str"),
            bsoft=dict(type="str"),
            ihard=dict(type="int"),
            isoft=dict(type="int"),
            mountpoint=dict(type="str", required=True),
            name=dict(type="str"),
            rtbhard=dict(type="str"),
            rtbsoft=dict(type="str"),
            state=dict(type="str",
                       default="present",
                       choices=["absent", "present"]),
            type=dict(type="str",
                      required=True,
                      choices=["group", "project", "user"]),
        ),
        supports_check_mode=True,
    )

    quota_type = module.params["type"]
    name = module.params["name"]
    mountpoint = module.params["mountpoint"]
    bhard = module.params["bhard"]
    bsoft = module.params["bsoft"]
    ihard = module.params["ihard"]
    isoft = module.params["isoft"]
    rtbhard = module.params["rtbhard"]
    rtbsoft = module.params["rtbsoft"]
    state = module.params["state"]

    xfs_quota_bin = module.get_bin_path("xfs_quota", True)

    if bhard is not None:
        bhard = human_to_bytes(bhard)

    if bsoft is not None:
        bsoft = human_to_bytes(bsoft)

    if rtbhard is not None:
        rtbhard = human_to_bytes(rtbhard)

    if rtbsoft is not None:
        rtbsoft = human_to_bytes(rtbsoft)

    result = dict(changed=False, )

    if not os.path.ismount(mountpoint):
        module.fail_json(msg="Path '%s' is not a mount point" % mountpoint,
                         **result)

    mp = get_fs_by_mountpoint(mountpoint)
    if mp is None:
        module.fail_json(
            msg=
            "Path '%s' is not a mount point or not located on an xfs file system."
            % mountpoint,
            **result)

    if quota_type == "user":
        type_arg = "-u"
        quota_default = "root"
        if name is None:
            name = quota_default

        if ("uquota" not in mp["mntopts"] and "usrquota" not in mp["mntopts"]
                and "quota" not in mp["mntopts"]
                and "uqnoenforce" not in mp["mntopts"]
                and "qnoenforce" not in mp["mntopts"]):
            module.fail_json(
                msg=
                "Path '%s' is not mounted with the uquota/usrquota/quota/uqnoenforce/qnoenforce option."
                % mountpoint,
                **result)
        try:
            pwd.getpwnam(name)
        except KeyError as e:
            module.fail_json(msg="User '%s' does not exist." % name, **result)

    elif quota_type == "group":
        type_arg = "-g"
        quota_default = "root"
        if name is None:
            name = quota_default

        if ("gquota" not in mp["mntopts"] and "grpquota" not in mp["mntopts"]
                and "gqnoenforce" not in mp["mntopts"]):
            module.fail_json(
                msg=
                "Path '%s' is not mounted with the gquota/grpquota/gqnoenforce option. (current options: %s)"
                % (mountpoint, mp["mntopts"]),
                **result)
        try:
            grp.getgrnam(name)
        except KeyError as e:
            module.fail_json(msg="User '%s' does not exist." % name, **result)

    elif quota_type == "project":
        type_arg = "-p"
        quota_default = "#0"
        if name is None:
            name = quota_default

        if ("pquota" not in mp["mntopts"] and "prjquota" not in mp["mntopts"]
                and "pqnoenforce" not in mp["mntopts"]):
            module.fail_json(
                msg=
                "Path '%s' is not mounted with the pquota/prjquota/pqnoenforce option."
                % mountpoint,
                **result)

        if name != quota_default and not os.path.isfile("/etc/projects"):
            module.fail_json(msg="Path '/etc/projects' does not exist.",
                             **result)

        if name != quota_default and not os.path.isfile("/etc/projid"):
            module.fail_json(msg="Path '/etc/projid' does not exist.",
                             **result)

        if name != quota_default and name is not None and get_project_id(
                name) is None:
            module.fail_json(
                msg="Entry '%s' has not been defined in /etc/projid." % name,
                **result)

        prj_set = True
        if name != quota_default:
            cmd = "project %s" % name
            rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd,
                                            mountpoint)
            if rc != 0:
                result["cmd"] = cmd
                result["rc"] = rc
                result["stdout"] = stdout
                result["stderr"] = stderr
                module.fail_json(msg="Could not get project state.", **result)
            else:
                for line in stdout.split("\n"):
                    if ("Project Id '%s' - is not set." in line
                            or "project identifier is not set" in line):
                        prj_set = False
                        break

        if not prj_set and not module.check_mode:
            cmd = "project -s"
            rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd,
                                            mountpoint)
            if rc != 0:
                result["cmd"] = cmd
                result["rc"] = rc
                result["stdout"] = stdout
                result["stderr"] = stderr
                module.fail_json(
                    msg="Could not get quota realtime block report.", **result)

            result["changed"] = True

        elif not prj_set and module.check_mode:
            result["changed"] = True

    # Set limits
    if state == "absent":
        bhard = 0
        bsoft = 0
        ihard = 0
        isoft = 0
        rtbhard = 0
        rtbsoft = 0

    current_bsoft, current_bhard = quota_report(module, xfs_quota_bin,
                                                mountpoint, name, quota_type,
                                                "b")
    current_isoft, current_ihard = quota_report(module, xfs_quota_bin,
                                                mountpoint, name, quota_type,
                                                "i")
    current_rtbsoft, current_rtbhard = quota_report(module, xfs_quota_bin,
                                                    mountpoint, name,
                                                    quota_type, "rtb")

    result["xfs_quota"] = dict(
        bsoft=current_bsoft,
        bhard=current_bhard,
        isoft=current_isoft,
        ihard=current_ihard,
        rtbsoft=current_rtbsoft,
        rtbhard=current_rtbhard,
    )

    limit = []
    if bsoft is not None and int(bsoft) != current_bsoft:
        limit.append("bsoft=%s" % bsoft)
        result["bsoft"] = int(bsoft)

    if bhard is not None and int(bhard) != current_bhard:
        limit.append("bhard=%s" % bhard)
        result["bhard"] = int(bhard)

    if isoft is not None and isoft != current_isoft:
        limit.append("isoft=%s" % isoft)
        result["isoft"] = isoft

    if ihard is not None and ihard != current_ihard:
        limit.append("ihard=%s" % ihard)
        result["ihard"] = ihard

    if rtbsoft is not None and int(rtbsoft) != current_rtbsoft:
        limit.append("rtbsoft=%s" % rtbsoft)
        result["rtbsoft"] = int(rtbsoft)

    if rtbhard is not None and int(rtbhard) != current_rtbhard:
        limit.append("rtbhard=%s" % rtbhard)
        result["rtbhard"] = int(rtbhard)

    if len(limit) > 0 and not module.check_mode:
        if name == quota_default:
            cmd = "limit %s -d %s" % (type_arg, " ".join(limit))
        else:
            cmd = "limit %s %s %s" % (type_arg, " ".join(limit), name)

        rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd, mountpoint)
        if rc != 0:
            result["cmd"] = cmd
            result["rc"] = rc
            result["stdout"] = stdout
            result["stderr"] = stderr
            module.fail_json(msg="Could not set limits.", **result)

        result["changed"] = True

    elif len(limit) > 0 and module.check_mode:
        result["changed"] = True

    module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(bhard=dict(type='str'),
                           bsoft=dict(type='str'),
                           ihard=dict(type='int'),
                           isoft=dict(type='int'),
                           mountpoint=dict(type='str', required=True),
                           name=dict(type='str'),
                           rtbhard=dict(type='str'),
                           rtbsoft=dict(type='str'),
                           state=dict(type='str',
                                      default='present',
                                      choices=['absent', 'present']),
                           type=dict(type='str',
                                     required=True,
                                     choices=['group', 'project', 'user'])),
        supports_check_mode=True,
    )

    quota_type = module.params['type']
    name = module.params['name']
    mountpoint = module.params['mountpoint']
    bhard = module.params['bhard']
    bsoft = module.params['bsoft']
    ihard = module.params['ihard']
    isoft = module.params['isoft']
    rtbhard = module.params['rtbhard']
    rtbsoft = module.params['rtbsoft']
    state = module.params['state']

    if bhard is not None:
        bhard = human_to_bytes(bhard)

    if bsoft is not None:
        bsoft = human_to_bytes(bsoft)

    if rtbhard is not None:
        rtbhard = human_to_bytes(rtbhard)

    if rtbsoft is not None:
        rtbsoft = human_to_bytes(rtbsoft)

    result = dict(changed=False, )

    if not os.path.ismount(mountpoint):
        module.fail_json(msg="Path '%s' is not a mount point" % mountpoint,
                         **result)

    mp = get_fs_by_mountpoint(mountpoint)
    if mp is None:
        module.fail_json(
            msg=
            "Path '%s' is not a mount point or not located on an xfs file system."
            % mountpoint,
            **result)

    if quota_type == 'user':
        type_arg = '-u'
        quota_default = 'root'
        if name is None:
            name = quota_default

        if 'uquota' not in mp['mntopts'] and 'usrquota' not in mp['mntopts'] and 'quota' not in mp['mntopts'] and 'uqnoenforce' not in mp['mntopts'] and \
                'qnoenforce' not in mp['mntopts']:
            module.fail_json(
                msg=
                "Path '%s' is not mounted with the uquota/usrquota/quota/uqnoenforce/qnoenforce option."
                % mountpoint,
                **result)
        try:
            pwd.getpwnam(name)
        except KeyError as e:
            module.fail_json(msg="User '%s' does not exist." % name, **result)

    elif quota_type == 'group':
        type_arg = '-g'
        quota_default = 'root'
        if name is None:
            name = quota_default

        if 'gquota' not in mp['mntopts'] and 'grpquota' not in mp[
                'mntopts'] and 'gqnoenforce' not in mp['mntopts']:
            module.fail_json(
                msg=
                "Path '%s' is not mounted with the gquota/grpquota/gqnoenforce option. (current options: %s)"
                % (mountpoint, mp['mntopts']),
                **result)
        try:
            grp.getgrnam(name)
        except KeyError as e:
            module.fail_json(msg="User '%s' does not exist." % name, **result)

    elif quota_type == 'project':
        type_arg = '-p'
        quota_default = '#0'
        if name is None:
            name = quota_default

        if 'pquota' not in mp['mntopts'] and 'prjquota' not in mp[
                'mntopts'] and 'pqnoenforce' not in mp['mntopts']:
            module.fail_json(
                msg=
                "Path '%s' is not mounted with the pquota/prjquota/pqnoenforce option."
                % mountpoint,
                **result)

        if name != quota_default and not os.path.isfile('/etc/projects'):
            module.fail_json(msg="Path '/etc/projects' does not exist.",
                             **result)

        if name != quota_default and not os.path.isfile('/etc/projid'):
            module.fail_json(msg="Path '/etc/projid' does not exist.",
                             **result)

        if name != quota_default and name is not None and get_project_id(
                name) is None:
            module.fail_json(
                msg="Entry '%s' has not been defined in /etc/projid." % name,
                **result)

        prj_set = True
        if name != quota_default:
            cmd = 'project %s' % name
            rc, stdout, stderr = exec_quota(module, cmd, mountpoint)
            if rc != 0:
                result['cmd'] = cmd
                result['rc'] = rc
                result['stdout'] = stdout
                result['stderr'] = stderr
                module.fail_json(msg='Could not get project state.', **result)
            else:
                for line in stdout.split('\n'):
                    if "Project Id '%s' - is not set." % name in line or 'project identifier is not set' in line:
                        prj_set = False
                        break

        if not prj_set and not module.check_mode:
            cmd = 'project -s %s' % name
            rc, stdout, stderr = exec_quota(module, cmd, mountpoint)
            if rc != 0:
                result['cmd'] = cmd
                result['rc'] = rc
                result['stdout'] = stdout
                result['stderr'] = stderr
                module.fail_json(
                    msg='Could not get quota realtime block report.', **result)

            result['changed'] = True

        elif not prj_set and module.check_mode:
            result['changed'] = True

    # Set limits
    if state == 'absent':
        bhard = 0
        bsoft = 0
        ihard = 0
        isoft = 0
        rtbhard = 0
        rtbsoft = 0

    current_bsoft, current_bhard = quota_report(module, mountpoint, name,
                                                quota_type, 'b')
    current_isoft, current_ihard = quota_report(module, mountpoint, name,
                                                quota_type, 'i')
    current_rtbsoft, current_rtbhard = quota_report(module, mountpoint, name,
                                                    quota_type, 'rtb')

    result['xfs_quota'] = dict(bsoft=current_bsoft,
                               bhard=current_bhard,
                               isoft=current_isoft,
                               ihard=current_ihard,
                               rtbsoft=current_rtbsoft,
                               rtbhard=current_rtbhard)

    limit = []
    if bsoft is not None and int(bsoft) != current_bsoft:
        limit.append('bsoft=%s' % bsoft)
        result['bsoft'] = int(bsoft)

    if bhard is not None and int(bhard) != current_bhard:
        limit.append('bhard=%s' % bhard)
        result['bhard'] = int(bhard)

    if isoft is not None and isoft != current_isoft:
        limit.append('isoft=%s' % isoft)
        result['isoft'] = isoft

    if ihard is not None and ihard != current_ihard:
        limit.append('ihard=%s' % ihard)
        result['ihard'] = ihard

    if rtbsoft is not None and int(rtbsoft) != current_rtbsoft:
        limit.append('rtbsoft=%s' % rtbsoft)
        result['rtbsoft'] = int(rtbsoft)

    if rtbhard is not None and int(rtbhard) != current_rtbhard:
        limit.append('rtbhard=%s' % rtbhard)
        result['rtbhard'] = int(rtbhard)

    if len(limit) > 0 and not module.check_mode:
        if name == quota_default:
            cmd = 'limit %s -d %s' % (type_arg, ' '.join(limit))
        else:
            cmd = 'limit %s %s %s' % (type_arg, ' '.join(limit), name)

        rc, stdout, stderr = exec_quota(module, cmd, mountpoint)
        if rc != 0:
            result['cmd'] = cmd
            result['rc'] = rc
            result['stdout'] = stdout
            result['stderr'] = stderr
            module.fail_json(msg='Could not set limits.', **result)

        result['changed'] = True

    elif len(limit) > 0 and module.check_mode:
        result['changed'] = True

    module.exit_json(**result)
Beispiel #14
0
def human_to_bytes(size, default_unit=None, isbits=False):
    ''' Return bytes count from a human readable string '''
    try:
        return basic.human_to_bytes(size, default_unit, isbits)
    except:
        raise errors.AnsibleFilterError("human_to_bytes() can't interpret following string: %s" % size)
Beispiel #15
0
def modify_fs(module, blade):
    """Modify Filesystem"""
    changed = False
    mod_fs = False
    attr = {}
    if module.params["policy"] and module.params["policy_state"] == "present":
        try:
            policy = blade.policies.list_policy_filesystems(
                policy_names=[module.params["policy"]],
                member_names=[module.params["name"]],
            )
        except Exception:
            module.fail_json(msg="Policy {0} does not exist.".format(
                module.params["policy"]))
        if not policy.items:
            try:
                blade.policies.create_policy_filesystems(
                    policy_names=[module.params["policy"]],
                    member_names=[module.params["name"]],
                )
                mod_fs = True
            except Exception:
                module.fail_json(
                    msg="Failed to add filesystem {0} to policy {1}.".format(
                        module.params["name"], module.params["polict"]))
    if module.params["policy"] and module.params["policy_state"] == "absent":
        try:
            policy = blade.policies.list_policy_filesystems(
                policy_names=[module.params["policy"]],
                member_names=[module.params["name"]],
            )
        except Exception:
            module.fail_json(msg="Policy {0} does not exist.".format(
                module.params["policy"]))
        if len(policy.items) == 1:
            try:
                blade.policies.delete_policy_filesystems(
                    policy_names=[module.params["policy"]],
                    member_names=[module.params["name"]],
                )
                mod_fs = True
            except Exception:
                module.fail_json(
                    msg="Failed to remove filesystem {0} to policy {1}.".
                    format(module.params["name"], module.params["polict"]))
    if module.params["user_quota"]:
        user_quota = human_to_bytes(module.params["user_quota"])
    if module.params["group_quota"]:
        group_quota = human_to_bytes(module.params["group_quota"])
    fsys = get_fs(module, blade)
    if fsys.destroyed:
        attr["destroyed"] = False
        mod_fs = True
    if module.params["size"]:
        if human_to_bytes(module.params["size"]) != fsys.provisioned:
            attr["provisioned"] = human_to_bytes(module.params["size"])
            mod_fs = True
    api_version = blade.api_version.list_versions().versions
    if NFSV4_API_VERSION in api_version:
        if module.params["nfsv3"] and not fsys.nfs.v3_enabled:
            attr["nfs"] = NfsRule(v3_enabled=module.params["nfsv3"])
            mod_fs = True
        if not module.params["nfsv3"] and fsys.nfs.v3_enabled:
            attr["nfs"] = NfsRule(v3_enabled=module.params["nfsv3"])
            mod_fs = True
        if module.params["nfsv4"] and not fsys.nfs.v4_1_enabled:
            attr["nfs"] = NfsRule(v4_1_enabled=module.params["nfsv4"])
            mod_fs = True
        if not module.params["nfsv4"] and fsys.nfs.v4_1_enabled:
            attr["nfs"] = NfsRule(v4_1_enabled=module.params["nfsv4"])
            mod_fs = True
        if (module.params["nfsv3"]
                or module.params["nfsv4"] and fsys.nfs.v3_enabled
                or fsys.nfs.v4_1_enabled):
            if module.params["nfs_rules"] is not None:
                if fsys.nfs.rules != module.params["nfs_rules"]:
                    attr["nfs"] = NfsRule(rules=module.params["nfs_rules"])
                    mod_fs = True
        if module.params[
                "user_quota"] and user_quota != fsys.default_user_quota:
            attr["default_user_quota"] = user_quota
            mod_fs = True
        if module.params[
                "group_quota"] and group_quota != fsys.default_group_quota:
            attr["default_group_quota"] = group_quota
            mod_fs = True
    else:
        if module.params["nfsv3"] and not fsys.nfs.enabled:
            attr["nfs"] = NfsRule(enabled=module.params["nfsv3"])
            mod_fs = True
        if not module.params["nfsv3"] and fsys.nfs.enabled:
            attr["nfs"] = NfsRule(enabled=module.params["nfsv3"])
            mod_fs = True
        if module.params["nfsv3"] and fsys.nfs.enabled:
            if fsys.nfs.rules != module.params["nfs_rules"]:
                attr["nfs"] = NfsRule(rules=module.params["nfs_rules"])
                mod_fs = True
    if REPLICATION_API_VERSION in api_version:
        if module.params["smb"] and not fsys.smb.enabled:
            if MULTIPROTOCOL_API_VERSION in api_version:
                attr["smb"] = SmbRule(enabled=module.params["smb"])
            else:
                attr["smb"] = SmbRule(enabled=module.params["smb"],
                                      acl_mode=module.params["smb_aclmode"])
            mod_fs = True
        if not module.params["smb"] and fsys.smb.enabled:
            attr["smb"] = ProtocolRule(enabled=module.params["smb"])
            mod_fs = True
        if (module.params["smb"] and fsys.smb.enabled
                and MULTIPROTOCOL_API_VERSION not in api_version):
            if fsys.smb.acl_mode != module.params["smb_aclmode"]:
                attr["smb"] = SmbRule(enabled=module.params["smb"],
                                      acl_mode=module.params["smb_aclmode"])
                mod_fs = True
    else:
        if module.params["smb"] and not fsys.smb.enabled:
            attr["smb"] = ProtocolRule(enabled=module.params["smb"])
            mod_fs = True
        if not module.params["smb"] and fsys.smb.enabled:
            attr["smb"] = ProtocolRule(enabled=module.params["smb"])
            mod_fs = True
    if module.params["http"] and not fsys.http.enabled:
        attr["http"] = ProtocolRule(enabled=module.params["http"])
        mod_fs = True
    if not module.params["http"] and fsys.http.enabled:
        attr["http"] = ProtocolRule(enabled=module.params["http"])
        mod_fs = True
    if module.params["snapshot"] and not fsys.snapshot_directory_enabled:
        attr["snapshot_directory_enabled"] = module.params["snapshot"]
        mod_fs = True
    if not module.params["snapshot"] and fsys.snapshot_directory_enabled:
        attr["snapshot_directory_enabled"] = module.params["snapshot"]
        mod_fs = True
    if module.params["fastremove"] and not fsys.fast_remove_directory_enabled:
        attr["fast_remove_directory_enabled"] = module.params["fastremove"]
        mod_fs = True
    if not module.params["fastremove"] and fsys.fast_remove_directory_enabled:
        attr["fast_remove_directory_enabled"] = module.params["fastremove"]
        mod_fs = True
    if HARD_LIMIT_API_VERSION in api_version:
        if not module.params["hard_limit"] and fsys.hard_limit_enabled:
            attr["hard_limit_enabled"] = module.params["hard_limit"]
            mod_fs = True
        if module.params["hard_limit"] and not fsys.hard_limit_enabled:
            attr["hard_limit_enabled"] = module.params["hard_limit"]
            mod_fs = True
    if MULTIPROTOCOL_API_VERSION in api_version:
        if module.params[
                "safeguard_acls"] and not fsys.multi_protocol.safeguard_acls:
            attr["multi_protocol"] = MultiProtocolRule(safeguard_acls=True)
            mod_fs = True
        if not module.params[
                "safeguard_acls"] and fsys.multi_protocol.safeguard_acls:
            attr["multi_protocol"] = MultiProtocolRule(safeguard_acls=False)
            mod_fs = True
        if module.params[
                "access_control"] != fsys.multi_protocol.access_control_style:
            attr["multi_protocol"] = MultiProtocolRule(
                access_control_style=module.params["access_control"])
            mod_fs = True
    if REPLICATION_API_VERSION in api_version:
        if module.params["writable"] is not None:
            if not module.params["writable"] and fsys.writable:
                attr["writable"] = module.params["writable"]
                mod_fs = True
            if (module.params["writable"] and not fsys.writable
                    and fsys.promotion_status == "promoted"):
                attr["writable"] = module.params["writable"]
                mod_fs = True
        if module.params["promote"] is not None:
            if module.params["promote"] and fsys.promotion_status != "promoted":
                attr["requested_promotion_state"] = "promoted"
                mod_fs = True
            if not module.params[
                    "promote"] and fsys.promotion_status == "promoted":
                # Demotion only allowed on filesystems in a replica-link
                try:
                    blade.file_system_replica_links.list_file_system_replica_links(
                        local_file_system_names=[module.params["name"]
                                                 ]).items[0]
                except Exception:
                    module.fail_json(
                        msg="Filesystem {0} not demoted. Not in a replica-link"
                        .format(module.params["name"]))
                attr["requested_promotion_state"] = module.params["promote"]
                mod_fs = True
    if mod_fs:
        changed = True
        if not module.check_mode:
            n_attr = FileSystem(**attr)
            if REPLICATION_API_VERSION in api_version:
                try:
                    blade.file_systems.update_file_systems(
                        name=module.params["name"],
                        attributes=n_attr,
                        discard_non_snapshotted_data=module.
                        params["discard_snaps"],
                    )
                except rest.ApiException as err:
                    message = json.loads(err.body)["errors"][0]["message"]
                    module.fail_json(
                        msg="Failed to update filesystem {0}. Error {1}".
                        format(module.params["name"], message))
            else:
                try:
                    blade.file_systems.update_file_systems(
                        name=module.params["name"], attributes=n_attr)
                except rest.ApiException as err:
                    message = json.loads(err.body)["errors"][0]["message"]
                    module.fail_json(
                        msg="Failed to update filesystem {0}. Error {1}".
                        format(module.params["name"], message))
    module.exit_json(changed=changed)
Beispiel #16
0
def create_fs(module, blade):
    """Create Filesystem"""
    changed = True
    if not module.check_mode:
        try:
            if not module.params["nfs_rules"]:
                module.params["nfs_rules"] = "*(rw,no_root_squash)"
            if module.params["size"]:
                size = human_to_bytes(module.params["size"])
            else:
                size = 0

            if module.params["user_quota"]:
                user_quota = human_to_bytes(module.params["user_quota"])
            else:
                user_quota = None
            if module.params["group_quota"]:
                group_quota = human_to_bytes(module.params["group_quota"])
            else:
                group_quota = None

            api_version = blade.api_version.list_versions().versions
            if HARD_LIMIT_API_VERSION in api_version:
                if NFSV4_API_VERSION in api_version:
                    if REPLICATION_API_VERSION in api_version:
                        if MULTIPROTOCOL_API_VERSION in api_version:
                            if module.params[
                                    "access_control"] == "nfs" and not (
                                        module.params["nfsv3"]
                                        or module.params["nfsv4"]):
                                module.fail_json(
                                    msg=
                                    "Cannot set access_control to nfs when NFS is not enabled."
                                )
                            if (module.params["access_control"]
                                    in ["smb", "independent"]
                                    and not module.params["smb"]):
                                module.fail_json(
                                    msg=
                                    "Cannot set access_control to smb or independent when SMB is not enabled."
                                )
                            if module.params["safeguard_acls"] and (
                                    module.params["access_control"]
                                    in ["mode-bits", "independent"]
                                    or module.params["smb"]):
                                module.fail_json(
                                    msg=
                                    "ACL Safeguarding cannot be enabled with SMB or if access_control is mode-bits or independent."
                                )
                            fs_obj = FileSystem(
                                name=module.params["name"],
                                provisioned=size,
                                fast_remove_directory_enabled=module.
                                params["fastremove"],
                                hard_limit_enabled=module.params["hard_limit"],
                                snapshot_directory_enabled=module.
                                params["snapshot"],
                                nfs=NfsRule(
                                    v3_enabled=module.params["nfsv3"],
                                    v4_1_enabled=module.params["nfsv4"],
                                    rules=module.params["nfs_rules"],
                                ),
                                smb=SmbRule(enabled=module.params["smb"]),
                                http=ProtocolRule(
                                    enabled=module.params["http"]),
                                multi_protocol=MultiProtocolRule(
                                    safeguard_acls=module.
                                    params["safeguard_acls"],
                                    access_control_style=module.
                                    params["access_control"],
                                ),
                                default_user_quota=user_quota,
                                default_group_quota=group_quota,
                            )
                        else:
                            fs_obj = FileSystem(
                                name=module.params["name"],
                                provisioned=size,
                                fast_remove_directory_enabled=module.
                                params["fastremove"],
                                hard_limit_enabled=module.params["hard_limit"],
                                snapshot_directory_enabled=module.
                                params["snapshot"],
                                nfs=NfsRule(
                                    v3_enabled=module.params["nfsv3"],
                                    v4_1_enabled=module.params["nfsv4"],
                                    rules=module.params["nfs_rules"],
                                ),
                                smb=SmbRule(
                                    enabled=module.params["smb"],
                                    acl_mode=module.params["smb_aclmode"],
                                ),
                                http=ProtocolRule(
                                    enabled=module.params["http"]),
                                default_user_quota=user_quota,
                                default_group_quota=group_quota,
                            )
                    else:
                        fs_obj = FileSystem(
                            name=module.params["name"],
                            provisioned=size,
                            fast_remove_directory_enabled=module.
                            params["fastremove"],
                            hard_limit_enabled=module.params["hard_limit"],
                            snapshot_directory_enabled=module.
                            params["snapshot"],
                            nfs=NfsRule(
                                v3_enabled=module.params["nfsv3"],
                                v4_1_enabled=module.params["nfsv4"],
                                rules=module.params["nfs_rules"],
                            ),
                            smb=ProtocolRule(enabled=module.params["smb"]),
                            http=ProtocolRule(enabled=module.params["http"]),
                            default_user_quota=user_quota,
                            default_group_quota=group_quota,
                        )
                else:
                    fs_obj = FileSystem(
                        name=module.params["name"],
                        provisioned=size,
                        fast_remove_directory_enabled=module.
                        params["fastremove"],
                        hard_limit_enabled=module.params["hard_limit"],
                        snapshot_directory_enabled=module.params["snapshot"],
                        nfs=NfsRule(
                            enabled=module.params["nfsv3"],
                            rules=module.params["nfs_rules"],
                        ),
                        smb=ProtocolRule(enabled=module.params["smb"]),
                        http=ProtocolRule(enabled=module.params["http"]),
                    )
            else:
                fs_obj = FileSystem(
                    name=module.params["name"],
                    provisioned=size,
                    fast_remove_directory_enabled=module.params["fastremove"],
                    snapshot_directory_enabled=module.params["snapshot"],
                    nfs=NfsRule(enabled=module.params["nfs"],
                                rules=module.params["nfs_rules"]),
                    smb=ProtocolRule(enabled=module.params["smb"]),
                    http=ProtocolRule(enabled=module.params["http"]),
                )
            blade.file_systems.create_file_systems(fs_obj)
        except rest.ApiException as err:
            message = json.loads(err.body)["errors"][0]["message"]
            module.fail_json(
                msg="Failed to create filesystem {0}. Error: {1}".format(
                    module.params["name"], message))
        if REPLICATION_API_VERSION in api_version:
            if module.params["policy"]:
                try:
                    blade.policies.list_policies(
                        names=[module.params["policy"]])
                except Exception:
                    _delete_fs(module, blade)
                    module.fail_json(msg="Policy {0} doesn't exist.".format(
                        module.params["policy"]))
                try:
                    blade.policies.create_policy_filesystems(
                        policy_names=[module.params["policy"]],
                        member_names=[module.params["name"]],
                    )
                except Exception:
                    _delete_fs(module, blade)
                    module.fail_json(
                        msg=
                        "Failed to apply policy {0} when creating filesystem {1}."
                        .format(module.params["policy"],
                                module.params["name"]))
    module.exit_json(changed=changed)