.. versionadded:: 2018.3.3

    List the contents of the filesystems

    CLI Example:

    .. code-block:: bash

        salt '*' mount.filesystems
977948
def filesystems(config='/etc/filesystems'):
    '''
    
    '''
    ret = {}
    if 'AIX' not in __grains__['kernel']:
        return ret

    ret_dict = _filesystems(config)
    if ret_dict:
        ret_key = next(iter(ret_dict.keys()))
        ret = {ret_key: dict(ret_dict[ret_key])}

    return ret
1252642
def list_extmods():
    '''
    
    '''
    ret = {}
    ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
    mod_types = os.listdir(ext_dir)
    for mod_type in mod_types:
        ret[mod_type] = set()
        for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
            for fh_ in files:
                ret[mod_type].add(fh_.split('.')[0])
        ret[mod_type] = list(ret[mod_type])
    return ret
437376
def command_mount(self, system_id, *system_ids):
        
        system_ids = (system_id,) + system_ids
        has_failed = False
        for system_id in system_ids:
            try:
                system = SystemModel.create_by_id(system_id, self.environment)
                controller = SystemControllerModel(system, self.environment)
                controller.mount()
            except SftpConfigException as e:
                sys.stderr.write('Cannot mount %s: %s\n\n' % (system_id, str(e)))
                has_failed = True
            except SftpMountException as e:
                sys.stderr.write('Cannot mount %s!\n\n' % system_id)
                sys.stderr.write('Mount command: \n%s\n\n' % e.mount_cmd)
                sys.stderr.write('Command output: \n%s\n\n' % e.mount_cmd_output)
                has_failed = True
        if has_failed:
            sys.exit(1)
294369
def cmd_fw_list(self, args):
        ''''''
        stuff = self.filtered_rows_from_args(args)
        if stuff is None:
            return
        (filtered, remainder) = stuff
        print("")
        print(" seq platform frame    major.minor.patch releasetype latest git-sha format")
        for row in filtered:
            print("{seq:>5} {platform:<13} {frame:<10} {version:<10} {releasetype:<9} {latest:<6} {git-sha} {format}".format(**row))
1016228
def cli(env, account_id, content_url):
    

    manager = SoftLayer.CDNManager(env.client)
    content_list = manager.purge_content(account_id, content_url)

    table = formatting.Table(['url', 'status'])

    for content in content_list:
        table.add_row([
            content['url'],
            content['statusCode']
        ])

    env.fout(table)
440743
def dir_list(self, tgt_env):
        '''
        
        '''
        def _traverse(tree, blobs, prefix):
            '''
            Traverse through a pygit2 Tree object recursively, accumulating all
            the empty directories within it in the "blobs" list
            '''
            for entry in iter(tree):
                if entry.oid not in self.repo:
                    # Entry is a submodule, skip it
                    continue
                blob = self.repo[entry.oid]
                if not isinstance(blob, pygit2.Tree):
                    continue
                blobs.append(
                    salt.utils.path.join(prefix, entry.name, use_posixpath=True)
                )
                if blob:
                    _traverse(
                        blob, blobs, salt.utils.path.join(
                            prefix, entry.name, use_posixpath=True)
                    )

        ret = set()
        tree = self.get_tree(tgt_env)
        if not tree:
            return ret
        if self.root(tgt_env):
            try:
                oid = tree[self.root(tgt_env)].oid
                tree = self.repo[oid]
            except KeyError:
                return ret
            if not isinstance(tree, pygit2.Tree):
                return ret
            relpath = lambda path: os.path.relpath(path, self.root(tgt_env))
        else:
            relpath = lambda path: path
        blobs = []
        if tree:
            _traverse(tree, blobs, self.root(tgt_env))
        add_mountpoint = lambda path: salt.utils.path.join(
            self.mountpoint(tgt_env), path, use_posixpath=True)
        for blob in blobs:
            ret.add(add_mountpoint(relpath(blob)))
        if self.mountpoint(tgt_env):
            ret.add(self.mountpoint(tgt_env))
        return ret
166054
def _restripe(mountpoint, direction, *devices, **kwargs):
    '''
    
    '''
    fs_log = []

    if salt.utils.fsutils._is_device(mountpoint):
        raise CommandExecutionError(
            "Mountpount expected, while device \"{0}\" specified".format(mountpoint))

    mounted = False
    for device, mntpoints in six.iteritems(salt.utils.fsutils._get_mounts("btrfs")):
        for mntdata in mntpoints:
            if mntdata['mount_point'] == mountpoint:
                mounted = True
                break

    if not mounted:
        raise CommandExecutionError(
            "No BTRFS device mounted on \"{0}\" mountpoint".format(mountpoint))

    if not devices:
        raise CommandExecutionError("No devices specified.")

    available_devices = __salt__['btrfs.devices']()
    for device in devices:
        if device not in six.iterkeys(available_devices):
            raise CommandExecutionError("Device \"{0}\" is not recognized".format(device))

    cmd = ['btrfs device {0}'.format(direction)]
    for device in devices:
        cmd.append(device)

    if direction == 'add':
        if kwargs.get("nodiscard"):
            cmd.append("-K")
        if kwargs.get("force"):
            cmd.append("-f")

    cmd.append(mountpoint)

    out = __salt__['cmd.run_all'](' '.join(cmd))
    salt.utils.fsutils._verify_run(out)
    if out['stdout']:
        fs_log.append(out['stdout'])

    if direction == 'add':
        out = None
        data_conversion = kwargs.get("dc")
        meta_conversion = kwargs.get("mc")
        if data_conversion and meta_conversion:
            out = __salt__['cmd.run_all'](
                "btrfs balance start -dconvert={0} -mconvert={1} {2}".format(
                    data_conversion, meta_conversion, mountpoint))
        else:
            out = __salt__['cmd.run_all']("btrfs filesystem balance {0}".format(mountpoint))
        salt.utils.fsutils._verify_run(out)
        if out['stdout']:
            fs_log.append(out['stdout'])

    # Summarize the result
    ret = {}
    if fs_log:
        ret.update({'log': '\n'.join(fs_log)})
    ret.update(__salt__['btrfs.info'](mountpoint))

    return ret
245061
def file_list(self, saltenv='base', prefix=''):
        '''
        
        '''
        ret = []
        prefix = prefix.strip('/')
        for path in self.opts['pillar_roots'].get(saltenv, []):
            for root, dirs, files in salt.utils.path.os_walk(
                os.path.join(path, prefix), followlinks=True
            ):
                # Don't walk any directories that match file_ignore_regex or glob
                dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)]
                for fname in files:
                    relpath = os.path.relpath(os.path.join(root, fname), path)
                    ret.append(salt.utils.data.decode(relpath))
        return ret
1338993
def _get_filesystem_types(args, sample_file):
    
    out = set([])
    ext = "" if args.no_container else "_container"
    with open(sample_file) as in_handle:
        for f in _get_file_paths(json.load(in_handle)):
            if f.startswith("gs:"):
                out.add("gcp%s" % ext)
            elif f.startswith("s3:"):
                out.add("s3%s" % ext)
            elif f.startswith(("https:", "http:")):
                out.add("http%s" % ext)
            else:
                out.add("local%s" % ext)
    return out
289965
def dir():
        
        dir = [
            'access', 'chdir', 'chmod', 'chown', 'close', 'fstat', 'fsync',
            'getcwd', 'lchmod', 'link', 'listdir', 'lstat', 'makedirs',
            'mkdir', 'mknod', 'open', 'read', 'readlink', 'remove',
            'removedirs', 'rename', 'rmdir', 'stat', 'symlink', 'umask',
            'unlink', 'utime', 'walk', 'write'
        ]
        if IS_PY2:
            dir += ['getcwdu']
        else:
            dir += ['getcwdb', 'replace']
            if sys.platform.startswith('linux'):
                dir += [
                    'fdatasync', 'getxattr', 'listxattr',
                    'removexattr', 'setxattr'
                ]
        if use_scandir:
            dir += ['scandir']
        return dir
892261
def show(config_file=False):
    '''
    
    '''
    roots = (
        'compat',
        'debug',
        'dev',
        'hptmv',
        'hw',
        'kern',
        'machdep',
        'net',
        'p1003_1b',
        'security',
        'user',
        'vfs',
        'vm'
    )
    cmd = 'sysctl -ae'
    ret = {}
    comps = ['']

    if config_file:
        # If the file doesn't exist, return an empty list
        if not os.path.exists(config_file):
            return []

        try:
            with salt.utils.files.fopen(config_file, 'r') as f:
                for line in f.readlines():
                    l = line.strip()
                    if l != "" and not l.startswith("#"):
                        comps = line.split('=', 1)
                        ret[comps[0]] = comps[1]
            return ret
        except (OSError, IOError):
            log.error('Could not open sysctl config file')
            return None
    else:
        out = __salt__['cmd.run'](cmd, output_loglevel='trace')
        for line in out.splitlines():
            if any([line.startswith('{0}.'.format(root)) for root in roots]):
                comps = line.split('=', 1)
                ret[comps[0]] = comps[1]
            elif comps[0]:
                ret[comps[0]] += '{0}\n'.format(line)
            else:
                continue
        return ret
136246
def hash_filesystem(filesystem, hashtype='sha1'):
    
    try:
        return dict(filesystem.checksums('/'))
    except RuntimeError:
        results = {}

        logging.warning("Error hashing disk %s contents, iterating over files.",
                        filesystem.disk_path)

        for path in filesystem.nodes('/'):
            try:
                regular = stat.S_ISREG(filesystem.stat(path)['mode'])
            except RuntimeError:
                continue  # unaccessible node

            if regular:
                try:
                    results[path] = filesystem.checksum(path, hashtype=hashtype)
                except RuntimeError:
                    logging.debug("Unable to hash %s.", path)

        return results
443860
def _file_lists(load, form):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    saltenv = load['saltenv']
    if saltenv not in __opts__['file_roots']:
        if '__env__' in __opts__['file_roots']:
            log.debug("salt environment '%s' maps to __env__ file_roots directory", saltenv)
            saltenv = '__env__'
        else:
            return []

    list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists', 'roots')
    if not os.path.isdir(list_cachedir):
        try:
            os.makedirs(list_cachedir)
        except os.error:
            log.critical('Unable to make cachedir %s', list_cachedir)
            return []
    list_cache = os.path.join(list_cachedir, '{0}.p'.format(salt.utils.files.safe_filename_leaf(saltenv)))
    w_lock = os.path.join(list_cachedir, '.{0}.w'.format(salt.utils.files.safe_filename_leaf(saltenv)))
    cache_match, refresh_cache, save_cache = \
        salt.fileserver.check_file_list_cache(
            __opts__, form, list_cache, w_lock
        )
    if cache_match is not None:
        return cache_match
    if refresh_cache:
        ret = {
            'files': set(),
            'dirs': set(),
            'empty_dirs': set(),
            'links': {}
        }

        def _add_to(tgt, fs_root, parent_dir, items):
            '''
            Add the files to the target set
            '''
            def _translate_sep(path):
                '''
                Translate path separators for Windows masterless minions
                '''
                return path.replace('\\', '/') if os.path.sep == '\\' else path

            for item in items:
                abs_path = os.path.join(parent_dir, item)
                log.trace('roots: Processing %s', abs_path)
                is_link = salt.utils.path.islink(abs_path)
                log.trace(
                    'roots: %s is %sa link',
                    abs_path, 'not ' if not is_link else ''
                )
                if is_link and __opts__['fileserver_ignoresymlinks']:
                    continue
                rel_path = _translate_sep(os.path.relpath(abs_path, fs_root))
                log.trace('roots: %s relative path is %s', abs_path, rel_path)
                if salt.fileserver.is_file_ignored(__opts__, rel_path):
                    continue
                tgt.add(rel_path)
                try:
                    if not os.listdir(abs_path):
                        ret['empty_dirs'].add(rel_path)
                except Exception:
                    # Generic exception because running os.listdir() on a
                    # non-directory path raises an OSError on *NIX and a
                    # WindowsError on Windows.
                    pass
                if is_link:
                    link_dest = salt.utils.path.readlink(abs_path)
                    log.trace(
                        'roots: %s symlink destination is %s',
                        abs_path, link_dest
                    )
                    if salt.utils.platform.is_windows() \
                            and link_dest.startswith('\\\\'):
                        # Symlink points to a network path. Since you can't
                        # join UNC and non-UNC paths, just assume the original
                        # path.
                        log.trace(
                            'roots: %s is a UNC path, using %s instead',
                            link_dest, abs_path
                        )
                        link_dest = abs_path
                    if link_dest.startswith('..'):
                        joined = os.path.join(abs_path, link_dest)
                    else:
                        joined = os.path.join(
                            os.path.dirname(abs_path), link_dest
                        )
                    rel_dest = _translate_sep(
                        os.path.relpath(
                            os.path.realpath(os.path.normpath(joined)),
                            fs_root
                        )
                    )
                    log.trace(
                        'roots: %s relative path is %s',
                        abs_path, rel_dest
                    )
                    if not rel_dest.startswith('..'):
                        # Only count the link if it does not point
                        # outside of the root dir of the fileserver
                        # (i.e. the "path" variable)
                        ret['links'][rel_path] = link_dest

        for path in __opts__['file_roots'][saltenv]:
            for root, dirs, files in salt.utils.path.os_walk(
                    path,
                    followlinks=__opts__['fileserver_followsymlinks']):
                _add_to(ret['dirs'], path, root, dirs)
                _add_to(ret['files'], path, root, files)

        ret['files'] = sorted(ret['files'])
        ret['dirs'] = sorted(ret['dirs'])
        ret['empty_dirs'] = sorted(ret['empty_dirs'])

        if save_cache:
            try:
                salt.fileserver.write_file_list_cache(
                    __opts__, ret, list_cache, w_lock
                )
            except NameError:
                # Catch msgpack error in salt-ssh
                pass
        return ret.get(form, [])
    # Shouldn't get here, but if we do, this prevents a TypeError
    return []
1175193
def _active_mounts_freebsd(ret):
    '''
    
    '''
    for line in __salt__['cmd.run_stdout']('mount -p').split('\n'):
        comps = re.sub(r"\s+", " ", line).split()
        ret[comps[1]] = {'device': comps[0],
                         'fstype': comps[2],
                         'opts': _resolve_user_group_names(comps[3].split(','))}
    return ret
74120
def _active_mounts(ret):
    '''
    
    '''
    _list = _list_mounts()
    filename = '/proc/self/mounts'
    if not os.access(filename, os.R_OK):
        msg = 'File not readable {0}'
        raise CommandExecutionError(msg.format(filename))

    with salt.utils.files.fopen(filename) as ifile:
        for line in ifile:
            comps = salt.utils.stringutils.to_unicode(line).split()
            ret[comps[1]] = {'device': comps[0],
                             'alt_device': _list.get(comps[1], None),
                             'fstype': comps[2],
                             'opts': _resolve_user_group_names(comps[3].split(','))}
    return ret
61468
def show(name, root=None):
    '''
    
    '''
    ret = {}
    out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root),
                              python_shell=False)
    for line in salt.utils.itertools.split(out, '\n'):
        comps = line.split('=')
        name = comps[0]
        value = '='.join(comps[1:])
        if value.startswith('{'):
            value = value.replace('{', '').replace('}', '')
            ret[name] = {}
            for item in value.split(' ; '):
                comps = item.split('=')
                ret[name][comps[0].strip()] = comps[1].strip()
        elif name in ('Before', 'After', 'Wants'):
            ret[name] = value.split()
        else:
            ret[name] = value

    return ret
898778
def mounts():
    """"""
    with open('/proc/mounts') as f:
        # [['/mount/point','/dev/path'],[...]]
        system_mounts = [m[1::-1] for m in [l.strip().split()
                                            for l in f.readlines()]]
    return system_mounts