Defragment mounted XFS filesystem.
    In order to mount a filesystem, device should be properly mounted and writable.

    CLI Example:

    .. code-block:: bash

        salt '*' xfs.defragment /dev/sda1
550751
def defragment(device):
    '''
    
    '''
    if device == '/':
        raise CommandExecutionError("Root is not a device.")

    if not _get_mounts().get(device):
        raise CommandExecutionError("Device \"{0}\" is not mounted".format(device))

    out = __salt__['cmd.run_all']("xfs_fsr {0}".format(device))
    _verify_run(out)

    return {
        'log': out['stdout']
    }
1344900
def zap_disk(block_device):
    '''
    
    '''
    # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b
    # sometimes sgdisk exits non-zero; this is OK, dd will clean up
    call(['sgdisk', '--zap-all', '--', block_device])
    call(['sgdisk', '--clear', '--mbrtogpt', '--', block_device])
    dev_end = check_output(['blockdev', '--getsz',
                            block_device]).decode('UTF-8')
    gpt_end = int(dev_end.split()[0]) - 100
    check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device),
                'bs=1M', 'count=1'])
    check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device),
                'bs=512', 'count=100', 'seek=%s' % (gpt_end)])
95498
def bindmount(self, mountpoint):
        

        if not self.mountpoint:
            raise NotMountedError(self)
        try:
            _util.check_call_(['mount', '--bind', self.mountpoint, mountpoint], stdout=subprocess.PIPE)
            if 'bindmounts' in self._paths:
                self._paths['bindmounts'].append(mountpoint)
            else:
                self._paths['bindmounts'] = [mountpoint]
            return True
        except Exception as e:
            logger.exception("Error bind mounting {0}.".format(self))
            raise SubsystemError(e)
423284
def is_removable(self, device):
        """"""
        if not self.is_handleable(device):
            return False
        if device.is_filesystem:
            return device.is_mounted
        if device.is_crypto:
            return device.is_unlocked
        if device.is_partition_table or device.is_drive:
            return any(self.is_removable(dev)
                       for dev in self.get_all_handleable()
                       if _is_parent_of(device, dev))
        return False
160728
async def unmount(self, device):
        
        device = self._find_device(device)
        if not self.is_handleable(device) or not device.is_filesystem:
            self._log.warn(_('not unmounting {0}: unhandled device', device))
            return False
        if not device.is_mounted:
            self._log.info(_('not unmounting {0}: not mounted', device))
            return True
        self._log.debug(_('unmounting {0}', device))
        await device.unmount()
        self._log.info(_('unmounted {0}', device))
        return True
190894
def _linux_disks():
    '''
    
    '''
    ret = {'disks': [], 'SSDs': []}

    for entry in glob.glob('/sys/block/*/queue/rotational'):
        try:
            with salt.utils.files.fopen(entry) as entry_fp:
                device = entry.split('/')[3]
                flag = entry_fp.read(1)
                if flag == '0':
                    ret['SSDs'].append(device)
                    log.trace('Device %s reports itself as an SSD', device)
                elif flag == '1':
                    ret['disks'].append(device)
                    log.trace('Device %s reports itself as an HDD', device)
                else:
                    log.trace(
                        'Unable to identify device %s as an SSD or HDD. It does '
                        'not report 0 or 1', device
                    )
        except IOError:
            pass
    return ret
441349
private function _filesystems()
    {
        if (CommonFunctions::executeProgram('df', '-k', $df, PSI_DEBUG)) {
            $df = preg_replace('/\n\s/m', ' ', $df);
            $mounts = preg_split("/\n/", $df, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($mounts as $mount) {
                $ar_buf = preg_split('/\s+/', $mount, 6);
                if (!empty($ar_buf[0]) && $ar_buf[0] !== 'Filesystem') {
                    $dev = new DiskDevice();
                    $dev->setName($ar_buf[0]);
                    $dev->setTotal($ar_buf[1] * 1024);
                    $dev->setUsed($ar_buf[2] * 1024);
                    $dev->setFree($ar_buf[3] * 1024);
                    $dev->setMountPoint($ar_buf[5]);
                    if (CommonFunctions::executeProgram('df', '-n', $dftypes, PSI_DEBUG)) {
                        $mounttypes = preg_split("/\n/", $dftypes, -1, PREG_SPLIT_NO_EMPTY);
                        foreach ($mounttypes as $type) {
                            $ty_buf = preg_split('/:/', $type, 2);
                            if (trim($ty_buf[0]) == $dev->getMountPoint()) {
                                $dev->setFsType($ty_buf[1]);
                                break;
                            }
                        }
                    } elseif (CommonFunctions::executeProgram('df', '-T', $dftypes, PSI_DEBUG)) {
                        $dftypes = preg_replace('/\n\s/m', ' ', $dftypes);
                        $mounttypes = preg_split("/\n/", $dftypes, -1, PREG_SPLIT_NO_EMPTY);
                        foreach ($mounttypes as $type) {
                            $ty_buf = preg_split("/\s+/", $type, 3);
                            if ($ty_buf[0] == $dev->getName()) {
                                $dev->setFsType($ty_buf[1]);
                                break;
                            }
                        }
                    }
                    $this->sys->setDiskDevices($dev);
                }
            }
        }
    }
749931
def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'):
    '''
    
    '''
    if util != 'mount':
        # This functionality used to live in img.mount_image
        if util == 'guestfs':
            return __salt__['guestfs.mount'](name, root=device)
        elif util == 'qemu_nbd':
            mnt = __salt__['qemu_nbd.init'](name, device)
            if not mnt:
                return False
            first = next(six.iterkeys(mnt))
            __context__['img.mnt_{0}'.format(first)] = mnt
            return first
        return False

    # Darwin doesn't expect defaults when mounting without other options
    if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']:
        opts = None

    if isinstance(opts, six.string_types):
        opts = opts.split(',')

    if not os.path.exists(name) and mkmnt:
        __salt__['file.mkdir'](name, user=user)

    args = ''
    if opts is not None:
        lopts = ','.join(opts)
        args = '-o {0}'.format(lopts)

    if fstype:
        # use of fstype on AIX differs from typical Linux use of -t
        # functionality AIX uses -v vfsname, -t fstype mounts all with
        # fstype in /etc/filesystems
        if 'AIX' in __grains__['os']:
            args += ' -v {0}'.format(fstype)
        elif 'solaris' in __grains__['os'].lower():
            args += ' -F {0}'.format(fstype)
        else:
            args += ' -t {0}'.format(fstype)

    cmd = 'mount {0} {1} {2} '.format(args, device, name)
    out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False)
    if out['retcode']:
        return out['stderr']
    return True
567343
def xoscmounts(host_mount):
    
    callback_lower_drive_letter = lambda pat: pat.group(1).lower()
    host_mount = re.sub(r"^([a-zA-Z])\:", callback_lower_drive_letter, host_mount)
    host_mount = re.sub(r"^([a-z])", "//\\1", host_mount)
    host_mount = re.sub(r"\\", "/", host_mount)
    return host_mount
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
96998
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"):
    """"""
    cmd_args = ['mount']
    if options is not None:
        cmd_args.extend(['-o', options])
    cmd_args.extend([device, mountpoint])
    try:
        subprocess.check_output(cmd_args)
    except subprocess.CalledProcessError as e:
        log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output))
        return False

    if persist:
        return fstab_add(device, mountpoint, filesystem, options=options)
    return True
938647
private function _filesystems()
    {
        $typearray = array('Unknown', 'No Root Directory', 'Removable Disk', 'Local Disk', 'Network Drive', 'Compact Disc', 'RAM Disk');
        $floppyarray = array('Unknown', '5 1/4 in.', '3 1/2 in.', '3 1/2 in.', '3 1/2 in.', '3 1/2 in.', '5 1/4 in.', '5 1/4 in.', '5 1/4 in.', '5 1/4 in.', '5 1/4 in.', 'Other', 'HD', '3 1/2 in.', '3 1/2 in.', '5 1/4 in.', '5 1/4 in.', '3 1/2 in.', '3 1/2 in.', '5 1/4 in.', '3 1/2 in.', '3 1/2 in.', '8 in.');
        $buffer = CommonFunctions::getWMI($this->_wmi, 'Win32_LogicalDisk', array('Name', 'Size', 'FreeSpace', 'FileSystem', 'DriveType', 'MediaType'));
        foreach ($buffer as $filesystem) {
            $dev = new DiskDevice();
            $dev->setMountPoint($filesystem['Name']);
            $dev->setFsType($filesystem['FileSystem']);
            if ($filesystem['Size'] > 0) {
                $dev->setTotal($filesystem['Size']);
                $dev->setFree($filesystem['FreeSpace']);
                $dev->setUsed($filesystem['Size'] - $filesystem['FreeSpace']);
            }
            if ($filesystem['MediaType'] != "" && $filesystem['DriveType'] == 2) {
                $dev->setName($typearray[$filesystem['DriveType']]." (".$floppyarray[$filesystem['MediaType']].")");
            } else {
                $dev->setName($typearray[$filesystem['DriveType']]);
            }
            $this->sys->setDiskDevices($dev);
        }
        if (!$buffer && ($this->sys->getDistribution()=="ReactOS")) {
            // test for command 'free' on current disk
            if (CommonFunctions::executeProgram('cmd', '/c free 2>nul', $out_value, true)) {
                for ($letter='A'; $letter!='AA'; $letter++) if (CommonFunctions::executeProgram('cmd', '/c free '.$letter.': 2>nul', $out_value, false)) {
                    $values = preg_replace('/[^\d\n]/', '', $out_value);
                    if (preg_match('/\n(\d+)\n(\d+)\n(\d+)$/', $values, $out_dig)) {
                        $size = $out_dig[1];
                        $used = $out_dig[2];
                        $free = $out_dig[3];
                        if ($used + $free == $size) {
                            $dev = new DiskDevice();
                            $dev->setMountPoint($letter.":");
                            $dev->setFsType('Unknown');
                            $dev->setName('Unknown');
                            $dev->setTotal($size);
                            $dev->setUsed($used);
                            $dev->setFree($free);
                            $this->sys->setDiskDevices($dev);
                        }
                    }
                }
            }
        }
    }
724967
def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None):
    '''
    
    '''
    force_mount = False
    if __grains__['os'] in ['MacOS', 'Darwin']:
        if opts == 'defaults':
            opts = 'noowners'
        if fstype == 'smbfs':
            force_mount = True

    if 'AIX' in __grains__['os']:
        if opts == 'defaults':
            opts = []

    if isinstance(opts, six.string_types):
        opts = opts.split(',')
    mnts = active()
    if name in mnts:
        # The mount point is mounted, attempt to remount it with the given data
        if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']:
            opts.append('remount')
        if force_mount:
            # We need to force the mount but first we should unmount
            umount(name, device, user=user)
        lopts = ','.join(opts)
        args = '-o {0}'.format(lopts)

        if fstype:
            # use of fstype on AIX differs from typical Linux use of
            # -t functionality AIX uses -v vfsname, -t fstype mounts
            # all with fstype in /etc/filesystems
            if 'AIX' in __grains__['os']:
                args += ' -v {0}'.format(fstype)
            elif 'solaris' in __grains__['os'].lower():
                args += ' -F {0}'.format(fstype)
            else:
                args += ' -t {0}'.format(fstype)

        if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount:
            cmd = 'mount {0} {1} {2} '.format(args, device, name)
        else:
            cmd = 'mount -u {0} {1} {2} '.format(args, device, name)
        out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False)
        if out['retcode']:
            return out['stderr']
        return True
    # Mount a filesystem that isn't already
    return mount(name, device, mkmnt, fstype, opts, user=user)
627279
def _active_mounts_aix(ret):
    '''
    
    '''
    for line in __salt__['cmd.run_stdout']('mount -p').split('\n'):
        comps = re.sub(r"\s+", " ", line).split()
        if comps:
            if comps[0] == 'node' or comps[0] == '--------':
                continue
            comps_len = len(comps)
            if line.startswith((' ', '\t')):
                curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else []
                if curr_opts:
                    ret[comps[1]] = {'device': comps[0],
                                    'fstype': comps[2],
                                    'opts': curr_opts}
                else:
                    ret[comps[1]] = {'device': comps[0],
                                    'fstype': comps[2]}
            else:
                curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else []
                if curr_opts:
                    ret[comps[2]] = {'node': comps[0],
                                    'device': comps[1],
                                    'fstype': comps[3],
                                    'opts': curr_opts}
                else:
                    ret[comps[2]] = {'node': comps[0],
                                    'device': comps[1],
                                    'fstype': comps[3]}
    return ret
348101
def file_hash(load, fnd):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if not all(x in load for x in ('path', 'saltenv')):
        return ''
    saltenv = load['saltenv']
    if saltenv == 'base':
        saltenv = 'trunk'
    ret = {}
    relpath = fnd['rel']
    path = fnd['path']

    # If the file doesn't exist, we can't get a hash
    if not path or not os.path.isfile(path):
        return ret

    # Set the hash_type as it is determined by config
    ret['hash_type'] = __opts__['hash_type']

    # Check if the hash is cached
    # Cache file's contents should be "hash:mtime"
    cache_path = os.path.join(__opts__['cachedir'],
                              'svnfs',
                              'hash',
                              saltenv,
                              '{0}.hash.{1}'.format(relpath,
                                                    __opts__['hash_type']))
    # If we have a cache, serve that if the mtime hasn't changed
    if os.path.exists(cache_path):
        with salt.utils.files.fopen(cache_path, 'rb') as fp_:
            hsum, mtime = fp_.read().split(':')
            if os.path.getmtime(path) == mtime:
                # check if mtime changed
                ret['hsum'] = hsum
                return ret

    # if we don't have a cache entry-- lets make one
    ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
    cache_dir = os.path.dirname(cache_path)
    # make cache directory if it doesn't exist
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)
    # save the cache object "hash:mtime"
    with salt.utils.files.fopen(cache_path, 'w') as fp_:
        fp_.write('{0}:{1}'.format(ret['hsum'], os.path.getmtime(path)))

    return ret
424387
def create_block_storage(kwargs=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The create_block_storage function must be called with '
            '-f or --function'
        )

    conn = get_conn()

    # Assemble the composite block storage object.
    block_storage = _get_block_storage(kwargs)

    data = conn.create_block_storage(block_storage=block_storage)

    return {'BlockStorage': data}
400121
def ls(self, src, extra_args=[]):
        ''''''
        src = [self._full_hdfs_path(x) for x in src]
        output = self._getStdOutCmd([self._hadoop_cmd, 'fs', '-ls'] + extra_args + src, True)
        return self._transform_ls_output(output, self.hdfs_url)