Return partition information for volumes mounted on this minion

    CLI Example:

    .. code-block:: bash

        salt '*' disk.percent /var
347671
def percent(args=None):
    '''
    
    '''
    if __grains__['kernel'] == 'Linux':
        cmd = 'df -P'
    elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
        cmd = 'df -kP'
    else:
        cmd = 'df'
    ret = {}
    out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    for line in out:
        if not line:
            continue
        if line.startswith('Filesystem'):
            continue
        comps = line.split()
        while len(comps) >= 2 and not comps[1].isdigit():
            comps[0] = '{0} {1}'.format(comps[0], comps[1])
            comps.pop(1)
        if len(comps) < 2:
            continue
        try:
            if __grains__['kernel'] == 'Darwin':
                ret[comps[8]] = comps[4]
            else:
                ret[comps[5]] = comps[4]
        except IndexError:
            log.error('Problem parsing disk usage information')
            ret = {}
    if args and args not in ret:
        log.error(
            'Problem parsing disk usage information: Partition \'%s\' '
            'does not exist!', args
        )
        ret = {}
    elif args:
        return ret[args]

    return ret
1108196
def get_volume(self):
        
        log.debug("getting volumne...")
        cmd, url = DEVICE_URLS["get_volume"]
        return self._exec(cmd, url)
411396
def getVolInfo(*paths):
    '''
    
    '''
    path = os.path.join(*paths)
    path = os.path.expanduser(path)

    st = os.statvfs(path)

    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize

    return {
        'free': free,
        'used': total - free,
        'total': total,
    }
353689
def get_recovery_range(working_dir):
    
    recovery_range_path = os.path.join(working_dir, '.recovery')
    if not os.path.exists(recovery_range_path):
        return (None, None)

    with open(recovery_range_path) as f:
        data = f.read()

    lines = filter(lambda l: len(l) > 0, map(lambda l2: l2.strip(), data.split()))
    assert len(lines) == 2, 'Invalid .recovery file'
    try:
        start_block = int(lines[0])
        end_block = int(lines[1])
    except:
        raise ValueError('Failed to parse {}'.format(recovery_range_path))

    return (start_block, end_block)
1286843
def stat(self):
        
        try:
            # Always use the last mount point because it's a very common
            # situation when mount points are moved, or sotorage is
            # double-mounted. Last mount point is always the newest.
            mp = self.mount_points[-1]
        except IndexError:
            return None
        stat = os.statvfs(mp)
        free = stat.f_frsize * stat.f_bavail
        total = stat.f_frsize * stat.f_blocks
        used = total - free
        used_pct = round(used / total * 100)
        free_pct = 100 - used_pct
        return Fstat(total, used, free, used_pct, free_pct)
567231
def get_percentage_volume_change(self):
        
        initial_vol = self.initial.lattice.volume
        final_vol = self.final.lattice.volume
        return final_vol / initial_vol - 1
1328822
def value(self):
        
        # This slightly convoluted calculation is equivalent to df's "Use%";
        # it calculates the percentage of FS usage as a proportion of the
        # space available to *non-root users*. Technically this means it can
        # exceed 100% (when FS is filled to the point that only root can write
        # to it), hence the clamp.
        vfs = os.statvfs(self.filesystem)
        used = vfs.f_blocks - vfs.f_bfree
        total = used + vfs.f_bavail
        return min(1.0, used / total)
1217949
def diskstats():
    '''
    
    '''
    def linux_diskstats():
        '''
        linux specific implementation of diskstats
        '''
        ret = {}
        try:
            with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
                stats = salt.utils.stringutils.to_unicode(fp_.read())
        except IOError:
            pass
        else:
            for line in stats.splitlines():
                if not line:
                    continue
                comps = line.split()
                ret[comps[2]] = {
                    'major': _number(comps[0]),
                    'minor': _number(comps[1]),
                    'device': _number(comps[2]),
                    'reads_issued': _number(comps[3]),
                    'reads_merged': _number(comps[4]),
                    'sectors_read': _number(comps[5]),
                    'ms_spent_reading': _number(comps[6]),
                    'writes_completed': _number(comps[7]),
                    'writes_merged': _number(comps[8]),
                    'sectors_written': _number(comps[9]),
                    'ms_spent_writing': _number(comps[10]),
                    'io_in_progress': _number(comps[11]),
                    'ms_spent_in_io': _number(comps[12]),
                    'weighted_ms_spent_in_io': _number(comps[13])
                }
        return ret

    def generic_diskstats():
        '''
        generic implementation of diskstats
        note: freebsd and sunos
        '''
        ret = {}
        iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
        header = iostat[1]
        for line in iostat[2:]:
            comps = line.split()
            ret[comps[0]] = {}
            for metric, value in zip(header.split()[1:], comps[1:]):
                ret[comps[0]][metric] = _number(value)
        return ret

    def aix_diskstats():
        '''
        AIX specific implementation of diskstats
        '''
        ret = {}
        procn = None
        fields = []
        disk_name = ''
        disk_mode = ''
        for line in __salt__['cmd.run']('iostat -dDV').splitlines():
            # Note: iostat -dDV is per-system
            #
            #System configuration: lcpu=8 drives=1 paths=2 vdisks=2
            #
            #hdisk0          xfer:  %tm_act      bps      tps      bread      bwrtn
            #                          0.0      0.8      0.0        0.0        0.8
            #                read:      rps  avgserv  minserv  maxserv   timeouts      fails
            #                          0.0      2.5      0.3     12.4           0          0
            #               write:      wps  avgserv  minserv  maxserv   timeouts      fails
            #                          0.0      0.3      0.2      0.7           0          0
            #               queue:  avgtime  mintime  maxtime  avgwqsz    avgsqsz     sqfull
            #                          0.3      0.0      5.3      0.0        0.0         0.0
            #--------------------------------------------------------------------------------
            if not line or line.startswith('System') or line.startswith('-----------'):
                continue

            if not re.match(r'\s', line):
                #have new disk
                dsk_comps = line.split(':')
                dsk_firsts = dsk_comps[0].split()
                disk_name = dsk_firsts[0]
                disk_mode = dsk_firsts[1]
                fields = dsk_comps[1].split()
                ret[disk_name] = []

                procn = len(ret[disk_name])
                ret[disk_name].append({})
                ret[disk_name][procn][disk_mode] = {}
                continue

            if ':' in line:
                comps = line.split(':')
                fields = comps[1].split()
                disk_mode = comps[0].lstrip()
                procn = len(ret[disk_name])
                ret[disk_name].append({})
                ret[disk_name][procn][disk_mode] = {}
            else:
                comps = line.split()
                for i in range(0, len(fields)):
                    if len(comps) > i:
                        ret[disk_name][procn][disk_mode][fields[i]] = comps[i]

        return ret

    # dict that return a function that does the right thing per platform
    get_version = {
        'Linux': linux_diskstats,
        'FreeBSD': generic_diskstats,
        'SunOS': generic_diskstats,
        'AIX': aix_diskstats,
    }

    errmsg = 'This method is unsupported on the current operating system!'
    return get_version.get(__grains__['kernel'], lambda: errmsg)()
664833
def _get_fs(self):
        '''
        
        '''

        data = dict()
        for dev, dev_data in salt.utils.fsutils._blkid().items():
            dev = self._get_disk_size(dev)
            device = dev.pop('device')
            dev['type'] = dev_data['type']
            data[device] = dev

        return data
504598
def __file_hash_and_stat(self, load):
        '''
        
        '''
        if 'env' in load:
            # "env" is not supported; Use "saltenv".
            load.pop('env')

        if 'path' not in load or 'saltenv' not in load:
            return '', None
        if not isinstance(load['saltenv'], six.string_types):
            load['saltenv'] = six.text_type(load['saltenv'])

        fnd = self.find_file(salt.utils.stringutils.to_unicode(load['path']),
                load['saltenv'])
        if not fnd.get('back'):
            return '', None
        stat_result = fnd.get('stat', None)
        fstr = '{0}.file_hash'.format(fnd['back'])
        if fstr in self.servers:
            return self.servers[fstr](load, fnd), stat_result
        return '', None
1292052
def make_vol_opt(hostdir, contdir, options=None):
    ''''''
    vol = '--volume={}:{}'.format(hostdir, contdir)
    if options != None:
        if isinstance(options, str):
            options = (options,)
        vol += ':' + ','.join(options)
    return vol
185102
def _GetStat(self):
    
    stat_object = super(BDEFileEntry, self)._GetStat()

    stat_object.size = self._bde_volume.get_size()

    return stat_object
1115702
def by_vol_id(blocks, slist=None):
    

    vol_blocks = {}

    # sort block by volume
    # not reliable with multiple partitions (fifo)

    for i in blocks:
        if slist and i not in slist:
            continue
        elif not blocks[i].is_valid:
            continue

        if blocks[i].vid_hdr.vol_id not in vol_blocks:
            vol_blocks[blocks[i].vid_hdr.vol_id] = []

        vol_blocks[blocks[i].vid_hdr.vol_id].append(blocks[i].peb_num)

    return vol_blocks
43559
def os_volumes(self):
        
        if not self.__os_volumes:
            self.__os_volumes = OsVolumes(self.__connection)
        return self.__os_volumes
757084
def mkdir_p(self, mode=0o777):
        
        try:
            self.mkdir(mode)
        except OSError:
            _, e, _ = sys.exc_info()
            if e.errno != errno.EEXIST:
                raise
        return self
70463
def statvfs(path):
    '''
    
    '''
    path = os.path.expanduser(path)

    if not os.path.isabs(path):
        raise SaltInvocationError('File path must be absolute.')

    try:
        stv = os.statvfs(path)
        return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree',
            'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag',
            'f_frsize', 'f_namemax'))
    except (OSError, IOError):
        raise CommandExecutionError('Could not statvfs \'{0}\''.format(path))
    return False
879768
def show_storage(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_storage function must be called with -f or --function.'
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('A name must be specified as "name"')

    data = conn.get_storage_account_properties(
        kwargs['name'],
    )
    return object_to_dict(data)