Create a map of disks in the machine.

        http://www.kernel.org/doc/Documentation/iostats.txt

        Returns:
          (major, minor) -> DiskStatistics(device, ...)
164001
def get_disk_statistics(self):
        
        result = {}

        if os.access('/proc/diskstats', os.R_OK):
            self.proc_diskstats = True
            fp = open('/proc/diskstats')

            try:
                for line in fp:
                    try:
                        columns = line.split()
                        # On early linux v2.6 versions, partitions have only 4
                        # output fields not 11. From linux 2.6.25 partitions
                        # have the full stats set.
                        if len(columns) < 14:
                            continue
                        major = int(columns[0])
                        minor = int(columns[1])
                        device = columns[2]

                        if ((device.startswith('ram') or
                             device.startswith('loop'))):
                            continue

                        result[(major, minor)] = {
                            'device': device,
                            'reads': float(columns[3]),
                            'reads_merged': float(columns[4]),
                            'reads_sectors': float(columns[5]),
                            'reads_milliseconds': float(columns[6]),
                            'writes': float(columns[7]),
                            'writes_merged': float(columns[8]),
                            'writes_sectors': float(columns[9]),
                            'writes_milliseconds': float(columns[10]),
                            'io_in_progress': float(columns[11]),
                            'io_milliseconds': float(columns[12]),
                            'io_milliseconds_weighted': float(columns[13])
                        }
                    except ValueError:
                        continue
            finally:
                fp.close()
        else:
            self.proc_diskstats = False
            if not psutil:
                self.log.error('Unable to import psutil')
                return None

            disks = psutil.disk_io_counters(True)
            sector_size = int(self.config['sector_size'])
            for disk in disks:
                result[(0, len(result))] = {
                    'device': disk,
                    'reads': disks[disk].read_count,
                    'reads_sectors': disks[disk].read_bytes / sector_size,
                    'reads_milliseconds': disks[disk].read_time,
                    'writes': disks[disk].write_count,
                    'writes_sectors': disks[disk].write_bytes / sector_size,
                    'writes_milliseconds': disks[disk].write_time,
                    'io_milliseconds':
                        disks[disk].read_time + disks[disk].write_time,
                    'io_milliseconds_weighted':
                        disks[disk].read_time + disks[disk].write_time
                }

        return result
416940
def stat(self, path=None, client_kwargs=None, header=None):
        
        # Should contain at least the strict minimum of os.stat_result
        stat = OrderedDict((
            ("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
            ("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
            ("st_mtime", 0), ("st_ctime", 0)))

        # Populate standard os.stat_result values with object header content
        header = self.head(path, client_kwargs, header)
        for key, method in (
                ('st_size', self._getsize_from_header),
                ('st_ctime', self._getctime_from_header),
                ('st_mtime', self._getmtime_from_header),):
            try:
                stat[key] = int(method(header))
            except UnsupportedOperation:
                continue

        # File mode
        if self.islink(path=path, header=header):
            # Symlink
            stat['st_mode'] = S_IFLNK
        elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
                stat['st_size']):
            # Directory
            stat['st_mode'] = S_IFDIR
        else:
            # File
            stat['st_mode'] = S_IFREG

        # Add storage specific keys
        sub = self._CHAR_FILTER.sub
        for key, value in tuple(header.items()):
            stat['st_' + sub('', key.lower())] = value

        # Convert to "os.stat_result" like object
        stat_result = namedtuple('stat_result', tuple(stat))
        stat_result.__name__ = 'os.stat_result'
        stat_result.__module__ = 'pycosio'
        return stat_result(**stat)
816213
def output_disk(gandi, disk, datacenters, vms, profiles, output_keys,
                justify=10):
    
    output_generic(gandi, disk, output_keys, justify)

    if 'kernel' in output_keys and disk.get('kernel_version'):
        output_line(gandi, 'kernel', disk['kernel_version'], justify)

    if 'cmdline' in output_keys and disk.get('kernel_cmdline'):
        output_cmdline(gandi, disk.get('kernel_cmdline'), justify)

    if 'dc' in output_keys:
        dc_name = None
        for dc in datacenters:
            if dc['id'] == disk['datacenter_id']:
                dc_name = dc.get('dc_code', dc.get('iso', ''))
                break

        if dc_name:
            output_line(gandi, 'datacenter', dc_name, justify)

    if 'vm' in output_keys:
        for vm_id in disk['vms_id']:
            vm_name = vms.get(vm_id, {}).get('hostname')
            if vm_name:
                output_line(gandi, 'vm', vm_name, justify)

    if 'profile' in output_keys and disk.get('snapshot_profile'):
        output_line(gandi, 'profile', disk['snapshot_profile']['name'],
                    justify)
    elif 'profile' in output_keys and disk.get('snapshot_profile_id'):
        for profile in profiles:
            if profile['id'] == disk['snapshot_profile_id']:
                output_line(gandi, 'profile', profile['name'], justify)
                break
998009
def os_data():
    '''
    
    '''
    grains = {
        'num_gpus': 0,
        'gpus': [],
        }

    # Windows Server 2008 64-bit
    # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
    #  'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
    # Ubuntu 10.04
    # ('Linux', 'MINIONNAME', '2.6.32-38-server',
    # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')

    # pylint: disable=unpacking-non-sequence
    (grains['kernel'], grains['nodename'],
     grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname()
    # pylint: enable=unpacking-non-sequence

    if salt.utils.platform.is_proxy():
        grains['kernel'] = 'proxy'
        grains['kernelrelease'] = 'proxy'
        grains['kernelversion'] = 'proxy'
        grains['osrelease'] = 'proxy'
        grains['os'] = 'proxy'
        grains['os_family'] = 'proxy'
        grains['osfullname'] = 'proxy'
    elif salt.utils.platform.is_windows():
        grains['os'] = 'Windows'
        grains['os_family'] = 'Windows'
        grains.update(_memdata(grains))
        grains.update(_windows_platform_data())
        grains.update(_windows_cpudata())
        grains.update(_windows_virtual(grains))
        grains.update(_ps(grains))

        if 'Server' in grains['osrelease']:
            osrelease_info = grains['osrelease'].split('Server', 1)
            osrelease_info[1] = osrelease_info[1].lstrip('R')
        else:
            osrelease_info = grains['osrelease'].split('.')

        for idx, value in enumerate(osrelease_info):
            if not value.isdigit():
                continue
            osrelease_info[idx] = int(value)
        grains['osrelease_info'] = tuple(osrelease_info)

        grains['osfinger'] = '{os}-{ver}'.format(
            os=grains['os'],
            ver=grains['osrelease'])

        grains['init'] = 'Windows'

        return grains
    elif salt.utils.platform.is_linux():
        # Add SELinux grain, if you have it
        if _linux_bin_exists('selinuxenabled'):
            log.trace('Adding selinux grains')
            grains['selinux'] = {}
            grains['selinux']['enabled'] = __salt__['cmd.retcode'](
                'selinuxenabled'
            ) == 0
            if _linux_bin_exists('getenforce'):
                grains['selinux']['enforced'] = __salt__['cmd.run'](
                    'getenforce'
                ).strip()

        # Add systemd grain, if you have it
        if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'):
            log.trace('Adding systemd grains')
            grains['systemd'] = {}
            systemd_info = __salt__['cmd.run'](
                'systemctl --version'
            ).splitlines()
            grains['systemd']['version'] = systemd_info[0].split()[1]
            grains['systemd']['features'] = systemd_info[1]

        # Add init grain
        grains['init'] = 'unknown'
        log.trace('Adding init grain')
        try:
            os.stat('/run/systemd/system')
            grains['init'] = 'systemd'
        except (OSError, IOError):
            try:
                with salt.utils.files.fopen('/proc/1/cmdline') as fhr:
                    init_cmdline = fhr.read().replace('\x00', ' ').split()
            except (IOError, OSError):
                pass
            else:
                try:
                    init_bin = salt.utils.path.which(init_cmdline[0])
                except IndexError:
                    # Emtpy init_cmdline
                    init_bin = None
                    log.warning('Unable to fetch data from /proc/1/cmdline')
                if init_bin is not None and init_bin.endswith('bin/init'):
                    supported_inits = (b'upstart', b'sysvinit', b'systemd')
                    edge_len = max(len(x) for x in supported_inits) - 1
                    try:
                        buf_size = __opts__['file_buffer_size']
                    except KeyError:
                        # Default to the value of file_buffer_size for the minion
                        buf_size = 262144
                    try:
                        with salt.utils.files.fopen(init_bin, 'rb') as fp_:
                            edge = b''
                            buf = fp_.read(buf_size).lower()
                            while buf:
                                buf = edge + buf
                                for item in supported_inits:
                                    if item in buf:
                                        if six.PY3:
                                            item = item.decode('utf-8')
                                        grains['init'] = item
                                        buf = b''
                                        break
                                edge = buf[-edge_len:]
                                buf = fp_.read(buf_size).lower()
                    except (IOError, OSError) as exc:
                        log.error(
                            'Unable to read from init_bin (%s): %s',
                            init_bin, exc
                        )
                elif salt.utils.path.which('supervisord') in init_cmdline:
                    grains['init'] = 'supervisord'
                elif salt.utils.path.which('dumb-init') in init_cmdline:
                    # https://github.com/Yelp/dumb-init
                    grains['init'] = 'dumb-init'
                elif salt.utils.path.which('tini') in init_cmdline:
                    # https://github.com/krallin/tini
                    grains['init'] = 'tini'
                elif init_cmdline == ['runit']:
                    grains['init'] = 'runit'
                elif '/sbin/my_init' in init_cmdline:
                    # Phusion Base docker container use runit for srv mgmt, but
                    # my_init as pid1
                    grains['init'] = 'runit'
                else:
                    log.debug(
                        'Could not determine init system from command line: (%s)',
                        ' '.join(init_cmdline)
                    )

        # Add lsb grains on any distro with lsb-release. Note that this import
        # can fail on systems with lsb-release installed if the system package
        # does not install the python package for the python interpreter used by
        # Salt (i.e. python2 or python3)
        try:
            log.trace('Getting lsb_release distro information')
            import lsb_release  # pylint: disable=import-error
            release = lsb_release.get_distro_information()
            for key, value in six.iteritems(release):
                key = key.lower()
                lsb_param = 'lsb_{0}{1}'.format(
                    '' if key.startswith('distrib_') else 'distrib_',
                    key
                )
                grains[lsb_param] = value
        # Catch a NameError to workaround possible breakage in lsb_release
        # See https://github.com/saltstack/salt/issues/37867
        except (ImportError, NameError):
            # if the python library isn't available, try to parse
            # /etc/lsb-release using regex
            log.trace('lsb_release python bindings not available')
            grains.update(_parse_lsb_release())

            if grains.get('lsb_distrib_description', '').lower().startswith('antergos'):
                # Antergos incorrectly configures their /etc/lsb-release,
                # setting the DISTRIB_ID to "Arch". This causes the "os" grain
                # to be incorrectly set to "Arch".
                grains['osfullname'] = 'Antergos Linux'
            elif 'lsb_distrib_id' not in grains:
                log.trace(
                    'Failed to get lsb_distrib_id, trying to parse os-release'
                )
                os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release')
                if os_release:
                    if 'NAME' in os_release:
                        grains['lsb_distrib_id'] = os_release['NAME'].strip()
                    if 'VERSION_ID' in os_release:
                        grains['lsb_distrib_release'] = os_release['VERSION_ID']
                    if 'VERSION_CODENAME' in os_release:
                        grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME']
                    elif 'PRETTY_NAME' in os_release:
                        codename = os_release['PRETTY_NAME']
                        # https://github.com/saltstack/salt/issues/44108
                        if os_release['ID'] == 'debian':
                            codename_match = re.search(r'\((\w+)\)$', codename)
                            if codename_match:
                                codename = codename_match.group(1)
                        grains['lsb_distrib_codename'] = codename
                    if 'CPE_NAME' in os_release:
                        cpe = _parse_cpe_name(os_release['CPE_NAME'])
                        if not cpe:
                            log.error('Broken CPE_NAME format in /etc/os-release!')
                        elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']:
                            grains['os'] = "SUSE"
                            # openSUSE `osfullname` grain normalization
                            if os_release.get("NAME") == "openSUSE Leap":
                                grains['osfullname'] = "Leap"
                            elif os_release.get("VERSION") == "Tumbleweed":
                                grains['osfullname'] = os_release["VERSION"]
                            # Override VERSION_ID, if CPE_NAME around
                            if cpe.get('version') and cpe.get('vendor') == 'opensuse':  # Keep VERSION_ID for SLES
                                grains['lsb_distrib_release'] = cpe['version']

                elif os.path.isfile('/etc/SuSE-release'):
                    log.trace('Parsing distrib info from /etc/SuSE-release')
                    grains['lsb_distrib_id'] = 'SUSE'
                    version = ''
                    patch = ''
                    with salt.utils.files.fopen('/etc/SuSE-release') as fhr:
                        for line in fhr:
                            if 'enterprise' in line.lower():
                                grains['lsb_distrib_id'] = 'SLES'
                                grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip()
                            elif 'version' in line.lower():
                                version = re.sub(r'[^0-9]', '', line)
                            elif 'patchlevel' in line.lower():
                                patch = re.sub(r'[^0-9]', '', line)
                    grains['lsb_distrib_release'] = version
                    if patch:
                        grains['lsb_distrib_release'] += '.' + patch
                        patchstr = 'SP' + patch
                        if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']:
                            grains['lsb_distrib_codename'] += ' ' + patchstr
                    if not grains.get('lsb_distrib_codename'):
                        grains['lsb_distrib_codename'] = 'n.a'
                elif os.path.isfile('/etc/altlinux-release'):
                    log.trace('Parsing distrib info from /etc/altlinux-release')
                    # ALT Linux
                    grains['lsb_distrib_id'] = 'altlinux'
                    with salt.utils.files.fopen('/etc/altlinux-release') as ifile:
                        # This file is symlinked to from:
                        #     /etc/fedora-release
                        #     /etc/redhat-release
                        #     /etc/system-release
                        for line in ifile:
                            # ALT Linux Sisyphus (unstable)
                            comps = line.split()
                            if comps[0] == 'ALT':
                                grains['lsb_distrib_release'] = comps[2]
                                grains['lsb_distrib_codename'] = \
                                    comps[3].replace('(', '').replace(')', '')
                elif os.path.isfile('/etc/centos-release'):
                    log.trace('Parsing distrib info from /etc/centos-release')
                    # Maybe CentOS Linux; could also be SUSE Expanded Support.
                    # SUSE ES has both, centos-release and redhat-release.
                    if os.path.isfile('/etc/redhat-release'):
                        with salt.utils.files.fopen('/etc/redhat-release') as ifile:
                            for line in ifile:
                                if "red hat enterprise linux server" in line.lower():
                                    # This is a SUSE Expanded Support Rhel installation
                                    grains['lsb_distrib_id'] = 'RedHat'
                                    break
                    grains.setdefault('lsb_distrib_id', 'CentOS')
                    with salt.utils.files.fopen('/etc/centos-release') as ifile:
                        for line in ifile:
                            # Need to pull out the version and codename
                            # in the case of custom content in /etc/centos-release
                            find_release = re.compile(r'\d+\.\d+')
                            find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
                            release = find_release.search(line)
                            codename = find_codename.search(line)
                            if release is not None:
                                grains['lsb_distrib_release'] = release.group()
                            if codename is not None:
                                grains['lsb_distrib_codename'] = codename.group()
                elif os.path.isfile('/etc.defaults/VERSION') \
                        and os.path.isfile('/etc.defaults/synoinfo.conf'):
                    grains['osfullname'] = 'Synology'
                    log.trace(
                        'Parsing Synology distrib info from /etc/.defaults/VERSION'
                    )
                    with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_:
                        synoinfo = {}
                        for line in fp_:
                            try:
                                key, val = line.rstrip('\n').split('=')
                            except ValueError:
                                continue
                            if key in ('majorversion', 'minorversion',
                                       'buildnumber'):
                                synoinfo[key] = val.strip('"')
                        if len(synoinfo) != 3:
                            log.warning(
                                'Unable to determine Synology version info. '
                                'Please report this, as it is likely a bug.'
                            )
                        else:
                            grains['osrelease'] = (
                                '{majorversion}.{minorversion}-{buildnumber}'
                                .format(**synoinfo)
                            )

        # Use the already intelligent platform module to get distro info
        # (though apparently it's not intelligent enough to strip quotes)
        log.trace(
            'Getting OS name, release, and codename from '
            'distro.linux_distribution()'
        )
        (osname, osrelease, oscodename) = \
            [x.strip('"').strip("'") for x in
             linux_distribution(supported_dists=_supported_dists)]
        # Try to assign these three names based on the lsb info, they tend to
        # be more accurate than what python gets from /etc/DISTRO-release.
        # It's worth noting that Ubuntu has patched their Python distribution
        # so that linux_distribution() does the /etc/lsb-release parsing, but
        # we do it anyway here for the sake for full portability.
        if 'osfullname' not in grains:
            # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
            if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'):
                grains['osfullname'] = 'nilrt'
            else:
                grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
        if 'osrelease' not in grains:
            # NOTE: This is a workaround for CentOS 7 os-release bug
            # https://bugs.centos.org/view.php?id=8359
            # /etc/os-release contains no minor distro release number so we fall back to parse
            # /etc/centos-release file instead.
            # Commit introducing this comment should be reverted after the upstream bug is released.
            if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''):
                grains.pop('lsb_distrib_release', None)
            grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip()
        grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename
        if 'Red Hat' in grains['oscodename']:
            grains['oscodename'] = oscodename
        distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
        # return the first ten characters with no spaces, lowercased
        shortname = distroname.replace(' ', '').lower()[:10]
        # this maps the long names from the /etc/DISTRO-release files to the
        # traditional short names that Salt has used.
        if 'os' not in grains:
            grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
        grains.update(_linux_cpudata())
        grains.update(_linux_gpu_data())
    elif grains['kernel'] == 'SunOS':
        if salt.utils.platform.is_smartos():
            # See https://github.com/joyent/smartos-live/issues/224
            if HAS_UNAME:
                uname_v = os.uname()[3]  # format: joyent_20161101T004406Z
            else:
                uname_v = os.name
            uname_v = uname_v[uname_v.index('_')+1:]
            grains['os'] = grains['osfullname'] = 'SmartOS'
            # store a parsed version of YYYY.MM.DD as osrelease
            grains['osrelease'] = ".".join([
                uname_v.split('T')[0][0:4],
                uname_v.split('T')[0][4:6],
                uname_v.split('T')[0][6:8],
            ])
            # store a untouched copy of the timestamp in osrelease_stamp
            grains['osrelease_stamp'] = uname_v
        elif os.path.isfile('/etc/release'):
            with salt.utils.files.fopen('/etc/release', 'r') as fp_:
                rel_data = fp_.read()
                try:
                    release_re = re.compile(
                        r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?'
                        r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?'
                    )
                    osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups()
                except AttributeError:
                    # Set a blank osrelease grain and fallback to 'Solaris'
                    # as the 'os' grain.
                    grains['os'] = grains['osfullname'] = 'Solaris'
                    grains['osrelease'] = ''
                else:
                    if development is not None:
                        osname = ' '.join((osname, development))
                    if HAS_UNAME:
                        uname_v = os.uname()[3]
                    else:
                        uname_v = os.name
                    grains['os'] = grains['osfullname'] = osname
                    if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease):
                        # Oracla Solars 11 and up have minor version in uname
                        grains['osrelease'] = uname_v
                    elif osname in ['OmniOS']:
                        # OmniOS
                        osrelease = []
                        osrelease.append(osmajorrelease[1:])
                        osrelease.append(osminorrelease[1:])
                        grains['osrelease'] = ".".join(osrelease)
                        grains['osrelease_stamp'] = uname_v
                    else:
                        # Sun Solaris 10 and earlier/comparable
                        osrelease = []
                        osrelease.append(osmajorrelease)
                        if osminorrelease:
                            osrelease.append(osminorrelease)
                        grains['osrelease'] = ".".join(osrelease)
                        grains['osrelease_stamp'] = uname_v

        grains.update(_sunos_cpudata())
    elif grains['kernel'] == 'VMkernel':
        grains['os'] = 'ESXi'
    elif grains['kernel'] == 'Darwin':
        osrelease = __salt__['cmd.run']('sw_vers -productVersion')
        osname = __salt__['cmd.run']('sw_vers -productName')
        osbuild = __salt__['cmd.run']('sw_vers -buildVersion')
        grains['os'] = 'MacOS'
        grains['os_family'] = 'MacOS'
        grains['osfullname'] = "{0} {1}".format(osname, osrelease)
        grains['osrelease'] = osrelease
        grains['osbuild'] = osbuild
        grains['init'] = 'launchd'
        grains.update(_bsd_cpudata(grains))
        grains.update(_osx_gpudata())
        grains.update(_osx_platform_data())
    elif grains['kernel'] == 'AIX':
        osrelease = __salt__['cmd.run']('oslevel')
        osrelease_techlevel = __salt__['cmd.run']('oslevel -r')
        osname = __salt__['cmd.run']('uname')
        grains['os'] = 'AIX'
        grains['osfullname'] = osname
        grains['osrelease'] = osrelease
        grains['osrelease_techlevel'] = osrelease_techlevel
        grains.update(_aix_cpudata())
    else:
        grains['os'] = grains['kernel']
    if grains['kernel'] == 'FreeBSD':
        try:
            grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0]
        except salt.exceptions.CommandExecutionError:
            # freebsd-version was introduced in 10.0.
            # derive osrelease from kernelversion prior to that
            grains['osrelease'] = grains['kernelrelease'].split('-')[0]
        grains.update(_bsd_cpudata(grains))
    if grains['kernel'] in ('OpenBSD', 'NetBSD'):
        grains.update(_bsd_cpudata(grains))
        grains['osrelease'] = grains['kernelrelease'].split('-')[0]
        if grains['kernel'] == 'NetBSD':
            grains.update(_netbsd_gpu_data())
    if not grains['os']:
        grains['os'] = 'Unknown {0}'.format(grains['kernel'])
        grains['os_family'] = 'Unknown'
    else:
        # this assigns family names based on the os name
        # family defaults to the os name if not found
        grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
                                                 grains['os'])

    # Build the osarch grain. This grain will be used for platform-specific
    # considerations such as package management. Fall back to the CPU
    # architecture.
    if grains.get('os_family') == 'Debian':
        osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
    elif grains.get('os_family') in ['RedHat', 'Suse']:
        osarch = salt.utils.pkg.rpm.get_osarch()
    elif grains.get('os_family') in ('NILinuxRT', 'Poky'):
        archinfo = {}
        for line in __salt__['cmd.run']('opkg print-architecture').splitlines():
            if line.startswith('arch'):
                _, arch, priority = line.split()
                archinfo[arch.strip()] = int(priority.strip())

        # Return osarch in priority order (higher to lower)
        osarch = sorted(archinfo, key=archinfo.get, reverse=True)
    else:
        osarch = grains['cpuarch']
    grains['osarch'] = osarch

    grains.update(_memdata(grains))

    # Get the hardware and bios data
    grains.update(_hw_data(grains))

    # Load the virtual machine info
    grains.update(_virtual(grains))
    grains.update(_virtual_hv(grains))
    grains.update(_ps(grains))

    if grains.get('osrelease', ''):
        osrelease_info = grains['osrelease'].split('.')
        for idx, value in enumerate(osrelease_info):
            if not value.isdigit():
                continue
            osrelease_info[idx] = int(value)
        grains['osrelease_info'] = tuple(osrelease_info)
        try:
            grains['osmajorrelease'] = int(grains['osrelease_info'][0])
        except (IndexError, TypeError, ValueError):
            log.debug(
                'Unable to derive osmajorrelease from osrelease_info \'%s\'. '
                'The osmajorrelease grain will not be set.',
                grains['osrelease_info']
            )
        os_name = grains['os' if grains.get('os') in (
            'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname']
        grains['osfinger'] = '{0}-{1}'.format(
            os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0])

    return grains
128500
def check_drives(drivename, drivestatus):
        
        return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format(
            drivename, DISK_STATES[int(drivestatus)]["result"])
1207015
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats using the standard system lib
            # Grab the stat using the psutil disk_io_counters method
            # read_count: number of reads
            # write_count: number of writes
            # read_bytes: number of bytes read
            # write_bytes: number of bytes written
            # read_time: time spent reading from disk (in milliseconds)
            # write_time: time spent writing to disk (in milliseconds)
            try:
                diskiocounters = psutil.disk_io_counters(perdisk=True)
            except Exception:
                return stats

            # Previous disk IO stats are stored in the diskio_old variable
            if not hasattr(self, 'diskio_old'):
                # First call, we init the diskio_old var
                try:
                    self.diskio_old = diskiocounters
                except (IOError, UnboundLocalError):
                    pass
            else:
                # By storing time data we enable Rx/s and Tx/s calculations in the
                # XML/RPC API, which would otherwise be overly difficult work
                # for users of the API
                time_since_update = getTimeSinceLastUpdate('disk')

                diskio_new = diskiocounters
                for disk in diskio_new:
                    # By default, RamFS is not displayed (issue #714)
                    if self.args is not None and not self.args.diskio_show_ramfs and disk.startswith('ram'):
                        continue

                    # Do not take hide disk into account
                    if self.is_hide(disk):
                        continue

                    # Compute count and bit rate
                    try:
                        read_count = (diskio_new[disk].read_count -
                                      self.diskio_old[disk].read_count)
                        write_count = (diskio_new[disk].write_count -
                                       self.diskio_old[disk].write_count)
                        read_bytes = (diskio_new[disk].read_bytes -
                                      self.diskio_old[disk].read_bytes)
                        write_bytes = (diskio_new[disk].write_bytes -
                                       self.diskio_old[disk].write_bytes)
                        diskstat = {
                            'time_since_update': time_since_update,
                            'disk_name': n(disk),
                            'read_count': read_count,
                            'write_count': write_count,
                            'read_bytes': read_bytes,
                            'write_bytes': write_bytes}
                        # Add alias if exist (define in the configuration file)
                        if self.has_alias(disk) is not None:
                            diskstat['alias'] = self.has_alias(disk)
                    except KeyError:
                        continue
                    else:
                        diskstat['key'] = self.get_key()
                        stats.append(diskstat)

                # Save stats to compute next bitrate
                self.diskio_old = diskio_new
        elif self.input_method == 'snmp':
            # Update stats using SNMP
            # No standard way for the moment...
            pass

        # Update the stats
        self.stats = stats

        return self.stats
378549
def list_disks(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_disks function must be called with -f or --function.'
        )

    if not conn:
        conn = get_conn()

    data = conn.list_disks()
    ret = {}
    for item in data.disks:
        ret[item.name] = object_to_dict(item)
    return ret
815677
function stat(path, callback) {
        appshell.fs.stat(path, function (err, stats) {
            if (err) {
                callback(_mapError(err));
            } else {
                var options = {
                    isFile: stats.isFile(),
                    mtime: stats.mtime,
                    size: stats.size,
                    realPath: stats.realPath,
                    hash: stats.mtime.getTime()
                };

                var fsStats = new FileSystemStats(options);

                callback(null, fsStats);
            }
        });
    }
7127
def _report_disk_stats(self):
        """"""
        stats = {
            'docker.data.used': None,
            'docker.data.total': None,
            'docker.data.free': None,
            'docker.metadata.used': None,
            'docker.metadata.total': None,
            'docker.metadata.free': None
            # these two are calculated by _calc_percent_disk_stats
            # 'docker.data.percent': None,
            # 'docker.metadata.percent': None
        }
        info = self.docker_util.client.info()
        driver_status = info.get('DriverStatus', [])
        if not driver_status:
            self.log.warning('Disk metrics collection is enabled but docker info did not'
                             ' report any. Your storage driver might not support them, skipping.')
            return
        for metric in driver_status:
            # only consider metrics about disk space
            if len(metric) == 2 and 'Space' in metric[0]:
                # identify Data and Metadata metrics
                mtype = 'data'
                if 'Metadata' in metric[0]:
                    mtype = 'metadata'

                if 'Used' in metric[0]:
                    stats['docker.{0}.used'.format(mtype)] = metric[1]
                elif 'Space Total' in metric[0]:
                    stats['docker.{0}.total'.format(mtype)] = metric[1]
                elif 'Space Available' in metric[0]:
                    stats['docker.{0}.free'.format(mtype)] = metric[1]
        stats = self._format_disk_metrics(stats)
        stats.update(self._calc_percent_disk_stats(stats))
        tags = self._get_tags()
        for name, val in stats.iteritems():
            if val is not None:
                self.gauge(name, val, tags)
32217
def list_(device, unit=None):
    '''
    
    '''
    _validate_device(device)

    if unit:
        if unit not in VALID_UNITS:
            raise CommandExecutionError(
                'Invalid unit passed to partition.part_list'
            )
        cmd = 'parted -m -s {0} unit {1} print'.format(device, unit)
    else:
        cmd = 'parted -m -s {0} print'.format(device)

    out = __salt__['cmd.run_stdout'](cmd).splitlines()
    ret = {'info': {}, 'partitions': {}}
    mode = 'info'
    for line in out:
        if line in ('BYT;', 'CHS;', 'CYL;'):
            continue
        cols = line.rstrip(';').split(':')
        if mode == 'info':
            if 7 <= len(cols) <= 8:
                ret['info'] = {
                    'disk': cols[0],
                    'size': cols[1],
                    'interface': cols[2],
                    'logical sector': cols[3],
                    'physical sector': cols[4],
                    'partition table': cols[5],
                    'model': cols[6]}
                if len(cols) == 8:
                    ret['info']['disk flags'] = cols[7]
                    # Older parted (2.x) doesn't show disk flags in the 'print'
                    # output, and will return a 7-column output for the info
                    # line. In these cases we just leave this field out of the
                    # return dict.
                mode = 'partitions'
            else:
                raise CommandExecutionError(
                    'Problem encountered while parsing output from parted')
        else:
            # Parted (v3.1) have a variable field list in machine
            # readable output:
            #
            # number:start:end:[size:]([file system:name:flags;]|[free;])
            #
            # * If units are in CHS 'size' is not printed.
            # * If is a logical partition with PED_PARTITION_FREESPACE
            #   set, the last three fields are replaced with the
            #   'free' text.
            #
            fields = ['number', 'start', 'end']
            if unit != 'chs':
                fields.append('size')
            if cols[-1] == 'free':
                # Drop the last element from the list
                cols.pop()
            else:
                fields.extend(['file system', 'name', 'flags'])
            if len(fields) == len(cols):
                ret['partitions'][cols[0]] = dict(six.moves.zip(fields, cols))
            else:
                raise CommandExecutionError(
                    'Problem encountered while parsing output from parted')
    return ret
779731
def generate_disk_vdev(self, start_vdev=None, offset=0):
        
        if not start_vdev:
            start_vdev = CONF.zvm.user_root_vdev
        vdev = self._generate_vdev(start_vdev, offset)
        if offset >= 0 and offset < 254:
            return vdev
        else:
            msg = ("Failed to generate disk vdev, invalid virtual device"
                   "number for disk:%s" % vdev)
            LOG.error(msg)
            raise exception.SDKGuestOperationError(rs=2, msg=msg)
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
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
530909
def create_disk(name, size):
    '''
    
    '''
    ret = False
    cmd = 'vmctl create {0} -s {1}'.format(name, size)

    result = __salt__['cmd.run_all'](cmd,
                                     output_loglevel='trace',
                                     python_shell=False)

    if result['retcode'] == 0:
        ret = True
    else:
        raise CommandExecutionError(
            'Problem encountered creating disk image',
            info={'errors': [result['stderr']], 'changes': ret}
        )

    return ret
68820
def getFilesystemStats(self, fs):
        
        if self._mapFSpathDev is None:
            self._initFilesystemInfo()
        return self._diskStats.get(self._mapFSpathDev.get(fs))
413165
def _get_device_template(disk, disk_info, template=None):
    '''
    

    '''
    def _require_disk_opts(*args):
        for arg in args:
            if arg not in disk_info:
                raise SaltCloudSystemExit(
                    'The disk {0} requires a {1}\
                    argument'.format(disk, arg)
                )

    _require_disk_opts('disk_type', 'size')

    size = disk_info['size']
    disk_type = disk_info['disk_type']

    if disk_type == 'clone':
        if 'image' in disk_info:
            clone_image = disk_info['image']
        else:
            clone_image = get_template_image(kwargs={'name':
                                                    template})

        clone_image_id = get_image_id(kwargs={'name': clone_image})
        temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\
                        SIZE={2}]'.format(clone_image, clone_image_id,
                                          size)
        return temp

    if disk_type == 'volatile':
        _require_disk_opts('type')
        v_type = disk_info['type']
        temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size)

        if v_type == 'fs':
            _require_disk_opts('format')
            format = disk_info['format']
            temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type,
                                                                  size, format)
        return temp
147552
def stat(self, filename, timeout=None):
    """"""
    transport = StatFilesyncTransport(self.stream)
    transport.write_data('STAT', filename, timeout)
    stat_msg = transport.read_message(timeout)
    stat_msg.assert_command_is('STAT')
    return DeviceFileStat(filename, stat_msg.mode, stat_msg.size, stat_msg.time)