Return usage information for volumes mounted on this minion

    CLI Example:

    .. code-block:: bash

        salt '*' disk.usage
182585
def usage():
    '''
    
    '''
    drives = []
    ret = {}
    drive_bitmask = ctypes.windll.kernel32.GetLogicalDrives()
    for letter in UPPERCASE:
        if drive_bitmask & 1:
            drives.append(letter)
        drive_bitmask >>= 1
    for drive in drives:
        try:
            (available_bytes,
             total_bytes,
             total_free_bytes) = win32api.GetDiskFreeSpaceEx(
                 '{0}:\\'.format(drive)
            )
            used = total_bytes - total_free_bytes
            capacity = used / float(total_bytes) * 100
            ret['{0}:\\'.format(drive)] = {
                'filesystem': '{0}:\\'.format(drive),
                '1K-blocks': total_bytes / 1024,
                'used': used / 1024,
                'available': total_free_bytes / 1024,
                'capacity': '{0:.0f}%'.format(capacity),
            }
        except Exception:
            ret['{0}:\\'.format(drive)] = {
                'filesystem': '{0}:\\'.format(drive),
                '1K-blocks': None,
                'used': None,
                'available': None,
                'capacity': None,
            }
    return ret
1237743
def _get_disk_size(self, device):
        '''
        
        '''
        out = __salt__['cmd.run_all']("df {0}".format(device))
        if out['retcode']:
            msg = "Disk size info error: {0}".format(out['stderr'])
            log.error(msg)
            raise SIException(msg)

        devpath, blocks, used, available, used_p, mountpoint = [elm for elm in
                                                                out['stdout'].split(os.linesep)[-1].split(" ") if elm]
        return {
            'device': devpath, 'blocks': blocks, 'used': used,
            'available': available, 'used (%)': used_p, 'mounted': mountpoint,
        }
611047
public static Double getDiskUsage() {
        if (!OSInfo.isLinux() && !OSInfo.isMac()) {
            return 0.0;
        }
        try {
            String output = SystemOperation.exec("df -h " + duHome);
            if (output != null) {
                String[] lines = output.split("[\\r\\n]+");
                if (lines.length >= 2) {
                    String[] parts = lines[1].split("\\s+");
                    if (parts.length >= 5) {
                        String pct = parts[4];
                        if (pct.endsWith("%")) {
                            return Integer.valueOf(pct.substring(0, pct.length() - 1)) / 100.0;
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.warn("failed to get disk usage.");
        }
        return 0.0;
    }
666073
def usage(self, callback=None, errback=None, **kwargs):
        
        stats = Stats(self.config)
        return stats.usage(zone=self.zone, callback=callback, errback=errback,
                           **kwargs)
1224208
def inodeusage(args=None):
    '''
    
    '''
    flags = _clean_flags(args, 'disk.inodeusage')
    if __grains__['kernel'] == 'AIX':
        cmd = 'df -i'
    else:
        cmd = 'df -iP'
    if flags:
        cmd += ' -{0}'.format(flags)
    ret = {}
    out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    for line in out:
        if line.startswith('Filesystem'):
            continue
        comps = line.split()
        # Don't choke on empty lines
        if not comps:
            continue

        try:
            if __grains__['kernel'] == 'OpenBSD':
                ret[comps[8]] = {
                    'inodes': int(comps[5]) + int(comps[6]),
                    'used': comps[5],
                    'free': comps[6],
                    'use': comps[7],
                    'filesystem': comps[0],
                }
            elif __grains__['kernel'] == 'AIX':
                ret[comps[6]] = {
                    'inodes': comps[4],
                    'used': comps[5],
                    'free': comps[2],
                    'use': comps[5],
                    'filesystem': comps[0],
                }
            else:
                ret[comps[5]] = {
                    'inodes': comps[1],
                    'used': comps[2],
                    'free': comps[3],
                    'use': comps[4],
                    'filesystem': comps[0],
                }
        except (IndexError, ValueError):
            log.error('Problem parsing inode usage information')
            ret = {}
    return ret
267911
def _volume_get(self, volume_id):
        '''
        
        '''
        if self.volume_conn is None:
            raise SaltCloudSystemExit('No cinder endpoint available')
        nt_ks = self.volume_conn
        volume = nt_ks.volumes.get(volume_id)
        response = {'name': volume.display_name,
                    'size': volume.size,
                    'id': volume.id,
                    'description': volume.display_description,
                    'attachments': volume.attachments,
                    'status': volume.status
                    }
        return response
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)()
677473
def get_memory_usage():
    
    process = psutil.Process(os.getpid())
    mem = process.memory_info().rss
    return mem / (1024 * 1024)
103241
def usage(self):
        
        arg_list = ' '.join(self.cmd_args).upper()
        name = self.interface.name()
        return '%s [options] %s %s' % (name, self.__name__, arg_list)
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)
889349
def active(display_progress=False):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
    except SaltClientError as client_error:
        print(client_error)
        return ret

    if display_progress:
        __jid_event__.fire_event({
            'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
            }, 'progress')
    for minion, data in six.iteritems(active_):
        if display_progress:
            __jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
        if not isinstance(data, list):
            continue
        for job in data:
            if not job['jid'] in ret:
                ret[job['jid']] = _format_jid_instance(job['jid'], job)
                ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
            else:
                ret[job['jid']]['Running'].append({minion: job['pid']})

    mminion = salt.minion.MasterMinion(__opts__)
    for jid in ret:
        returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
        data = mminion.returners['{0}.get_jid'.format(returner)](jid)
        if data:
            for minion in data:
                if minion not in ret[jid]['Returned']:
                    ret[jid]['Returned'].append(minion)

    return ret
1005458
def get_volumes(self):
        
        vols = [self.find_volume(name) for name in self.virsp.listVolumes()]
        return vols
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
707772
def _find_usage_vpcs(self):
        """"""
        # overall number of VPCs
        vpcs = self.conn.describe_vpcs()
        self.limits['VPCs']._add_current_usage(
            len(vpcs['Vpcs']),
            aws_type='AWS::EC2::VPC'
        )
758992
def devices_data():
    
    response = {}
    for part in psutil.disk_partitions():
        device = part.device
        response[device] = {
            'device': device,
            'mountpoint': part.mountpoint,
            'fstype': part.fstype,
            'opts': part.opts,
        }
        if part.mountpoint:
            usage = psutil.disk_usage(part.mountpoint)
            response[device]['usage'] = {
                'size': mark(usage.total, 'bytes'),
                'used': mark(usage.used, 'bytes'),
                'free': mark(usage.free, 'bytes'),
                'percent': mark(usage.percent, 'percentage')
            }
    return response
330147
private static void usage() {
        display("Usage: CSVLoader <params>");
        display("where <params> are:");
        display("   -app <name>         Doradus application name. Default is: {}", CSVConfig.DEFAULT_APPNAME);
        display("   -batchsize <#>      Batch size. Default is: {}", CSVConfig.DEFAULT_BATCH_SIZE);
        display("   -compress [T|F]     Compress messages. Default is: {}", CSVConfig.DEFAULT_COMPRESS);
        display("   -host <host>        Doradus server host name. Default is: {}", CSVConfig.DEFAULT_HOST);
        display("   -id <name>          Column name of ID field. Default is: {}", CSVConfig.DEFAULT_ID_FIELD);
        display("   -increment_ts [T|F] True to increment timestamp fields 1 day per batch. Default is: {}", CSVConfig.DEFAULT_INCREMENT_TS);
        display("   -merge_all [T|F]    (OLAP only): true to merge after every batch. Default is: {}", CSVConfig.DEFAULT_MERGE_ALL);
        display("   -password <pw>      Password for tenant. Default is: {}", CSVConfig.DEFAULT_PASSWORD);
        display("   -port <port>        Doradus server port. Default is: {}", CSVConfig.DEFAULT_PORT);
        display("   -root <folder>      Root folder of CSV files. Default is: {}", CSVConfig.DEFAULT_ROOT);
        display("   -schema <file>      Name of application schema file. Default is: <app name>.xml");
        display("   -skip_undef [T|F]   True to skip fields not declared in the schema. Default is: {}", CSVConfig.DEFAULT_SKIP_UNDEF);
        display("   -shard <name>       (OLAP only): Name of shard to load. Default is: {}", CSVConfig.DEFAULT_SHARD);
        display("   -tenant <name>      Name of tenant to use. Default is: {}", CSVConfig.DEFAULT_TENANT);
        display("   -user <ID>          User ID for tenant. Default is: {}", CSVConfig.DEFAULT_USER);
        display("   -workers <#>        # of worker threads. Default is: {}", CSVConfig.DEFAULT_WORKERS);
        display("To use TLS:");
        display("   -tls [T|F]               True to enable TLS/SSL. Default is: {}", CSVConfig.DEFAULT_TLS);
        display("   -keystore <file>         File name of keystore. Default is: {}", CSVConfig.DEFAULT_KEYSTORE);
        display("   -keystorepassword <pw>   Password of keystore file. Default is: {}", CSVConfig.DEFAULT_KEYSTORE_PW);
        display("   -truststore <file>       File name of truststore. Default is: {}", CSVConfig.DEFAULT_TRUSTSTORE);
        display("   -truststorepassword <pw> Password of truststore file. Default is: {}", CSVConfig.DEFAULT_TRUSTSTORE_PW);
        display("Deletes and recreates OLAP or Spider application defined by 'schema' file, then loads all CSV");
        display("files found in 'root' folder.");
        System.exit(0);
    }
987405
def _check_available_disk_space(self, project):
        

        try:
            used_disk_space = psutil.disk_usage(project.path).percent
        except FileNotFoundError:
            log.warning('Could not find "{}" when checking for used disk space'.format(project.path))
            return
        # send a warning if used disk space is >= 90%
        if used_disk_space >= 90:
            message = 'Only {}% or less of disk space detected in "{}" on "{}"'.format(used_disk_space,
                                                                                       project.path,
                                                                                       platform.node())
            log.warning(message)
            project.emit("log.warning", {"message": message})