Provide grains for SmartOS
771532
def smartos():
    '''
    
    '''
    grains = {}

    if salt.utils.platform.is_smartos_zone():
        grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)
        grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)
        grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)
    elif salt.utils.platform.is_smartos_globalzone():
        grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)

    return grains
1243003
def _memdata(osdata):
    '''
    
    '''
    # Provides:
    #   mem_total
    #   swap_total, for supported systems.
    grains = {'mem_total': 0}
    if osdata['kernel'] == 'Linux':
        grains.update(_linux_memdata())
    elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
        grains.update(_bsd_memdata(osdata))
    elif osdata['kernel'] == 'Darwin':
        grains.update(_osx_memdata())
    elif osdata['kernel'] == 'SunOS':
        grains.update(_sunos_memdata())
    elif osdata['kernel'] == 'AIX':
        grains.update(_aix_memdata())
    elif osdata['kernel'] == 'Windows' and HAS_WMI:
        grains.update(_windows_memdata())
    return grains
293359
def items(sanitize=False):
    '''
    
    '''
    if salt.utils.data.is_true(sanitize):
        out = dict(__grains__)
        for key, func in six.iteritems(_SANITIZERS):
            if key in out:
                out[key] = func(out[key])
        return out
    else:
        return __grains__
271017
def _grains():
    '''
    
    '''
    try:
        host = __pillar__['proxy']['host']
        if host:
            username, password = _find_credentials(host)
            protocol = __pillar__['proxy'].get('protocol')
            port = __pillar__['proxy'].get('port')
            ret = salt.modules.vsphere.system_info(host=host,
                                                   username=username,
                                                   password=password,
                                                   protocol=protocol,
                                                   port=port)
            GRAINS_CACHE.update(ret)
    except KeyError:
        pass

    return GRAINS_CACHE
247193
async function logIOS() {
  const rawDevices = execFileSync(
    'xcrun',
    ['simctl', 'list', 'devices', '--json'],
    {encoding: 'utf8'},
  );

  const {devices} = JSON.parse(rawDevices);

  const device = findAvailableDevice(devices);
  if (device === undefined) {
    logger.error('No active iOS device found');
    return;
  }

  tailDeviceLogs(device.udid);
}
388354
def run_wfunc(self):
        '''
        
        '''
        # Ensure that opts/grains are up to date
        # Execute routine
        data_cache = False
        data = None
        cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
        if not os.path.isdir(cdir):
            os.makedirs(cdir)
        datap = os.path.join(cdir, 'ssh_data.p')
        refresh = False
        if not os.path.isfile(datap):
            refresh = True
        else:
            passed_time = (time.time() - os.stat(datap).st_mtime) / 60
            if passed_time > self.opts.get('cache_life', 60):
                refresh = True

        if self.opts.get('refresh_cache'):
            refresh = True
        conf_grains = {}
        # Save conf file grains before they get clobbered
        if 'ssh_grains' in self.opts:
            conf_grains = self.opts['ssh_grains']
        if not data_cache:
            refresh = True
        if refresh:
            # Make the datap
            # TODO: Auto expire the datap
            pre_wrapper = salt.client.ssh.wrapper.FunctionWrapper(
                self.opts,
                self.id,
                fsclient=self.fsclient,
                minion_opts=self.minion_opts,
                **self.target)
            opts_pkg = pre_wrapper['test.opts_pkg']()  # pylint: disable=E1102
            if '_error' in opts_pkg:
                #Refresh failed
                retcode = opts_pkg['retcode']
                ret = salt.utils.json.dumps({'local': opts_pkg})
                return ret, retcode

            opts_pkg['file_roots'] = self.opts['file_roots']
            opts_pkg['pillar_roots'] = self.opts['pillar_roots']
            opts_pkg['ext_pillar'] = self.opts['ext_pillar']
            opts_pkg['extension_modules'] = self.opts['extension_modules']
            opts_pkg['module_dirs'] = self.opts['module_dirs']
            opts_pkg['_ssh_version'] = self.opts['_ssh_version']
            opts_pkg['__master_opts__'] = self.context['master_opts']
            if 'known_hosts_file' in self.opts:
                opts_pkg['known_hosts_file'] = self.opts['known_hosts_file']
            if '_caller_cachedir' in self.opts:
                opts_pkg['_caller_cachedir'] = self.opts['_caller_cachedir']
            else:
                opts_pkg['_caller_cachedir'] = self.opts['cachedir']
            # Use the ID defined in the roster file
            opts_pkg['id'] = self.id

            retcode = 0

            # Restore master grains
            for grain in conf_grains:
                opts_pkg['grains'][grain] = conf_grains[grain]
            # Enable roster grains support
            if 'grains' in self.target:
                for grain in self.target['grains']:
                    opts_pkg['grains'][grain] = self.target['grains'][grain]

            popts = {}
            popts.update(opts_pkg)

            # Master centric operations such as mine.get must have master option loaded.
            # The pillar must then be compiled by passing master opts found in opts_pkg['__master_opts__']
            # which causes the pillar renderer to loose track of salt master options
            #
            # Depending on popts merge order, it will overwrite some options found in opts_pkg['__master_opts__']
            master_centric_funcs = [
              "pillar.items",
              "mine.get"
            ]

            # Pillar compilation is a master centric operation.
            # Master options take precedence during Pillar compilation
            popts.update(opts_pkg['__master_opts__'])

            pillar = salt.pillar.Pillar(
                    popts,
                    opts_pkg['grains'],
                    opts_pkg['id'],
                    opts_pkg.get('saltenv', 'base')
                    )
            pillar_data = pillar.compile_pillar()

            # Once pillar has been compiled, restore priority of minion opts
            if self.fun not in master_centric_funcs:
                log.debug('%s is a minion function', self.fun)
                popts.update(opts_pkg)
            else:
                log.debug('%s is a master function', self.fun)

            # TODO: cache minion opts in datap in master.py
            data = {'opts': opts_pkg,
                    'grains': opts_pkg['grains'],
                    'pillar': pillar_data}
            if data_cache:
                with salt.utils.files.fopen(datap, 'w+b') as fp_:
                    fp_.write(
                            self.serial.dumps(data)
                            )
        if not data and data_cache:
            with salt.utils.files.fopen(datap, 'rb') as fp_:
                data = self.serial.load(fp_)
        opts = data.get('opts', {})
        opts['grains'] = data.get('grains')

        # Restore master grains
        for grain in conf_grains:
            opts['grains'][grain] = conf_grains[grain]
        # Enable roster grains support
        if 'grains' in self.target:
            for grain in self.target['grains']:
                opts['grains'][grain] = self.target['grains'][grain]

        opts['pillar'] = data.get('pillar')
        wrapper = salt.client.ssh.wrapper.FunctionWrapper(
            opts,
            self.id,
            fsclient=self.fsclient,
            minion_opts=self.minion_opts,
            **self.target)
        self.wfuncs = salt.loader.ssh_wrapper(opts, wrapper, self.context)
        wrapper.wfuncs = self.wfuncs

        # We're running in the mine, need to fetch the arguments from the
        # roster, pillar, master config (in that order)
        if self.mine:
            mine_args = None
            mine_fun_data = None
            mine_fun = self.fun

            if self.mine_functions and self.fun in self.mine_functions:
                mine_fun_data = self.mine_functions[self.fun]
            elif opts['pillar'] and self.fun in opts['pillar'].get('mine_functions', {}):
                mine_fun_data = opts['pillar']['mine_functions'][self.fun]
            elif self.fun in self.context['master_opts'].get('mine_functions', {}):
                mine_fun_data = self.context['master_opts']['mine_functions'][self.fun]

            if isinstance(mine_fun_data, dict):
                mine_fun = mine_fun_data.pop('mine_function', mine_fun)
                mine_args = mine_fun_data
            elif isinstance(mine_fun_data, list):
                for item in mine_fun_data[:]:
                    if isinstance(item, dict) and 'mine_function' in item:
                        mine_fun = item['mine_function']
                        mine_fun_data.pop(mine_fun_data.index(item))
                mine_args = mine_fun_data
            else:
                mine_args = mine_fun_data

            # If we found mine_args, replace our command's args
            if isinstance(mine_args, dict):
                self.args = []
                self.kwargs = mine_args
            elif isinstance(mine_args, list):
                self.args = mine_args
                self.kwargs = {}

        try:
            if self.mine:
                result = wrapper[mine_fun](*self.args, **self.kwargs)
            else:
                result = self.wfuncs[self.fun](*self.args, **self.kwargs)
        except TypeError as exc:
            result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
            log.error(result, exc_info_on_loglevel=logging.DEBUG)
            retcode = 1
        except Exception as exc:
            result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
            log.error(result, exc_info_on_loglevel=logging.DEBUG)
            retcode = 1
        # Mimic the json data-structure that "salt-call --local" will
        # emit (as seen in ssh_py_shim.py)
        if isinstance(result, dict) and 'local' in result:
            ret = salt.utils.json.dumps({'local': result['local']})
        else:
            ret = salt.utils.json.dumps({'local': {'return': result}})
        return ret, retcode
665277
def get_hardware_grains(service_instance):
    '''
    
    '''
    hw_grain_data = {}
    if get_inventory(service_instance).about.apiType == 'HostAgent':
        view = service_instance.content.viewManager.CreateContainerView(service_instance.RetrieveContent().rootFolder,
                                                                        [vim.HostSystem], True)
        if view and view.view:
            hw_grain_data['manufacturer'] = view.view[0].hardware.systemInfo.vendor
            hw_grain_data['productname'] = view.view[0].hardware.systemInfo.model

            for _data in view.view[0].hardware.systemInfo.otherIdentifyingInfo:
                if _data.identifierType.key == 'ServiceTag':
                    hw_grain_data['serialnumber'] = _data.identifierValue

            hw_grain_data['osfullname'] = view.view[0].summary.config.product.fullName
            hw_grain_data['osmanufacturer'] = view.view[0].summary.config.product.vendor
            hw_grain_data['osrelease'] = view.view[0].summary.config.product.version
            hw_grain_data['osbuild'] = view.view[0].summary.config.product.build
            hw_grain_data['os_family'] = view.view[0].summary.config.product.name
            hw_grain_data['os'] = view.view[0].summary.config.product.name
            hw_grain_data['mem_total'] = view.view[0].hardware.memorySize /1024/1024
            hw_grain_data['biosversion'] = view.view[0].hardware.biosInfo.biosVersion
            hw_grain_data['biosreleasedate'] = view.view[0].hardware.biosInfo.releaseDate.date().strftime('%m/%d/%Y')
            hw_grain_data['cpu_model'] = view.view[0].hardware.cpuPkg[0].description
            hw_grain_data['kernel'] = view.view[0].summary.config.product.productLineId
            hw_grain_data['num_cpu_sockets'] = view.view[0].hardware.cpuInfo.numCpuPackages
            hw_grain_data['num_cpu_cores'] = view.view[0].hardware.cpuInfo.numCpuCores
            hw_grain_data['num_cpus'] = hw_grain_data['num_cpu_sockets'] * hw_grain_data['num_cpu_cores']
            hw_grain_data['ip_interfaces'] = {}
            hw_grain_data['ip4_interfaces'] = {}
            hw_grain_data['ip6_interfaces'] = {}
            hw_grain_data['hwaddr_interfaces'] = {}
            for _vnic in view.view[0].configManager.networkSystem.networkConfig.vnic:
                hw_grain_data['ip_interfaces'][_vnic.device] = []
                hw_grain_data['ip4_interfaces'][_vnic.device] = []
                hw_grain_data['ip6_interfaces'][_vnic.device] = []

                hw_grain_data['ip_interfaces'][_vnic.device].append(_vnic.spec.ip.ipAddress)
                hw_grain_data['ip4_interfaces'][_vnic.device].append(_vnic.spec.ip.ipAddress)
                if _vnic.spec.ip.ipV6Config:
                    hw_grain_data['ip6_interfaces'][_vnic.device].append(_vnic.spec.ip.ipV6Config.ipV6Address)
                hw_grain_data['hwaddr_interfaces'][_vnic.device] = _vnic.spec.mac
            hw_grain_data['host'] = view.view[0].configManager.networkSystem.dnsConfig.hostName
            hw_grain_data['domain'] = view.view[0].configManager.networkSystem.dnsConfig.domainName
            hw_grain_data['fqdn'] = '{0}{1}{2}'.format(
                view.view[0].configManager.networkSystem.dnsConfig.hostName,
                ('.' if view.view[0].configManager.networkSystem.dnsConfig.domainName else ''),
                view.view[0].configManager.networkSystem.dnsConfig.domainName)

            for _pnic in view.view[0].configManager.networkSystem.networkInfo.pnic:
                hw_grain_data['hwaddr_interfaces'][_pnic.device] = _pnic.mac

            hw_grain_data['timezone'] = view.view[0].configManager.dateTimeSystem.dateTimeInfo.timeZone.name
        view = None
    return hw_grain_data
175607
def add_device(self, device, container):
        
        # There is a size tag which the JSS manages for us, so we can
        # ignore it.
        if self.findtext("is_smart") == "false":
            self.add_object_to_path(device, container)
        else:
            # Technically this isn't true. It will strangely accept
            # them, and they even show up as members of the group!
            raise ValueError("Devices may not be added to smart groups.")
54246
def _virtual(osdata):
    '''
    
    '''
    # This is going to be a monster, if you are running a vm you can test this
    # grain with please submit patches!
    # Provides:
    #   virtual
    #   virtual_subtype
    grains = {'virtual': 'physical'}

    # Skip the below loop on platforms which have none of the desired cmds
    # This is a temporary measure until we can write proper virtual hardware
    # detection.
    skip_cmds = ('AIX',)

    # list of commands to be executed to determine the 'virtual' grain
    _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
    # test first for virt-what, which covers most of the desired functionality
    # on most platforms
    if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
        if salt.utils.path.which('virt-what'):
            _cmds = ['virt-what']

    # Check if enable_lspci is True or False
    if __opts__.get('enable_lspci', True) is True:
        # /proc/bus/pci does not exists, lspci will fail
        if os.path.exists('/proc/bus/pci'):
            _cmds += ['lspci']

    # Add additional last resort commands
    if osdata['kernel'] in skip_cmds:
        _cmds = ()

    # Quick backout for BrandZ (Solaris LX Branded zones)
    # Don't waste time trying other commands to detect the virtual grain
    if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
        grains['virtual'] = 'zone'
        return grains

    failed_commands = set()
    for command in _cmds:
        args = []
        if osdata['kernel'] == 'Darwin':
            command = 'system_profiler'
            args = ['SPDisplaysDataType']
        elif osdata['kernel'] == 'SunOS':
            virtinfo = salt.utils.path.which('virtinfo')
            if virtinfo:
                try:
                    ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
                except salt.exceptions.CommandExecutionError:
                    if salt.log.is_logging_configured():
                        failed_commands.add(virtinfo)
                else:
                    if ret['stdout'].endswith('not supported'):
                        command = 'prtdiag'
                    else:
                        command = 'virtinfo'
            else:
                command = 'prtdiag'

        cmd = salt.utils.path.which(command)

        if not cmd:
            continue

        cmd = '{0} {1}'.format(cmd, ' '.join(args))

        try:
            ret = __salt__['cmd.run_all'](cmd)

            if ret['retcode'] > 0:
                if salt.log.is_logging_configured():
                    # systemd-detect-virt always returns > 0 on non-virtualized
                    # systems
                    # prtdiag only works in the global zone, skip if it fails
                    if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
                        continue
                    failed_commands.add(command)
                continue
        except salt.exceptions.CommandExecutionError:
            if salt.log.is_logging_configured():
                if salt.utils.platform.is_windows():
                    continue
                failed_commands.add(command)
            continue

        output = ret['stdout']
        if command == "system_profiler":
            macoutput = output.lower()
            if '0x1ab8' in macoutput:
                grains['virtual'] = 'Parallels'
            if 'parallels' in macoutput:
                grains['virtual'] = 'Parallels'
            if 'vmware' in macoutput:
                grains['virtual'] = 'VMware'
            if '0x15ad' in macoutput:
                grains['virtual'] = 'VMware'
            if 'virtualbox' in macoutput:
                grains['virtual'] = 'VirtualBox'
            # Break out of the loop so the next log message is not issued
            break
        elif command == 'systemd-detect-virt':
            if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
                grains['virtual'] = output
                break
            elif 'vmware' in output:
                grains['virtual'] = 'VMware'
                break
            elif 'microsoft' in output:
                grains['virtual'] = 'VirtualPC'
                break
            elif 'lxc' in output:
                grains['virtual'] = 'LXC'
                break
            elif 'systemd-nspawn' in output:
                grains['virtual'] = 'LXC'
                break
        elif command == 'virt-what':
            try:
                output = output.splitlines()[-1]
            except IndexError:
                pass
            if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
                grains['virtual'] = output
                break
            elif 'vmware' in output:
                grains['virtual'] = 'VMware'
                break
            elif 'parallels' in output:
                grains['virtual'] = 'Parallels'
                break
            elif 'hyperv' in output:
                grains['virtual'] = 'HyperV'
                break
        elif command == 'dmidecode':
            # Product Name: VirtualBox
            if 'Vendor: QEMU' in output:
                # FIXME: Make this detect between kvm or qemu
                grains['virtual'] = 'kvm'
            if 'Manufacturer: QEMU' in output:
                grains['virtual'] = 'kvm'
            if 'Vendor: Bochs' in output:
                grains['virtual'] = 'kvm'
            if 'Manufacturer: Bochs' in output:
                grains['virtual'] = 'kvm'
            if 'BHYVE' in output:
                grains['virtual'] = 'bhyve'
            # Product Name: (oVirt) www.ovirt.org
            # Red Hat Community virtualization Project based on kvm
            elif 'Manufacturer: oVirt' in output:
                grains['virtual'] = 'kvm'
                grains['virtual_subtype'] = 'ovirt'
            # Red Hat Enterprise Virtualization
            elif 'Product Name: RHEV Hypervisor' in output:
                grains['virtual'] = 'kvm'
                grains['virtual_subtype'] = 'rhev'
            elif 'VirtualBox' in output:
                grains['virtual'] = 'VirtualBox'
            # Product Name: VMware Virtual Platform
            elif 'VMware' in output:
                grains['virtual'] = 'VMware'
            # Manufacturer: Microsoft Corporation
            # Product Name: Virtual Machine
            elif ': Microsoft' in output and 'Virtual Machine' in output:
                grains['virtual'] = 'VirtualPC'
            # Manufacturer: Parallels Software International Inc.
            elif 'Parallels Software' in output:
                grains['virtual'] = 'Parallels'
            elif 'Manufacturer: Google' in output:
                grains['virtual'] = 'kvm'
            # Proxmox KVM
            elif 'Vendor: SeaBIOS' in output:
                grains['virtual'] = 'kvm'
            # Break out of the loop, lspci parsing is not necessary
            break
        elif command == 'lspci':
            # dmidecode not available or the user does not have the necessary
            # permissions
            model = output.lower()
            if 'vmware' in model:
                grains['virtual'] = 'VMware'
            # 00:04.0 System peripheral: InnoTek Systemberatung GmbH
            #         VirtualBox Guest Service
            elif 'virtualbox' in model:
                grains['virtual'] = 'VirtualBox'
            elif 'qemu' in model:
                grains['virtual'] = 'kvm'
            elif 'virtio' in model:
                grains['virtual'] = 'kvm'
            # Break out of the loop so the next log message is not issued
            break
        elif command == 'prtdiag':
            model = output.lower().split("\n")[0]
            if 'vmware' in model:
                grains['virtual'] = 'VMware'
            elif 'virtualbox' in model:
                grains['virtual'] = 'VirtualBox'
            elif 'qemu' in model:
                grains['virtual'] = 'kvm'
            elif 'joyent smartdc hvm' in model:
                grains['virtual'] = 'kvm'
            break
        elif command == 'virtinfo':
            grains['virtual'] = 'LDOM'
            break

    choices = ('Linux', 'HP-UX')
    isdir = os.path.isdir
    sysctl = salt.utils.path.which('sysctl')
    if osdata['kernel'] in choices:
        if os.path.isdir('/proc'):
            try:
                self_root = os.stat('/')
                init_root = os.stat('/proc/1/root/.')
                if self_root != init_root:
                    grains['virtual_subtype'] = 'chroot'
            except (IOError, OSError):
                pass
        if isdir('/proc/vz'):
            if os.path.isfile('/proc/vz/version'):
                grains['virtual'] = 'openvzhn'
            elif os.path.isfile('/proc/vz/veinfo'):
                grains['virtual'] = 'openvzve'
                # a posteriori, it's expected for these to have failed:
                failed_commands.discard('lspci')
                failed_commands.discard('dmidecode')
        # Provide additional detection for OpenVZ
        if os.path.isfile('/proc/self/status'):
            with salt.utils.files.fopen('/proc/self/status') as status_file:
                vz_re = re.compile(r'^envID:\s+(\d+)$')
                for line in status_file:
                    vz_match = vz_re.match(line.rstrip('\n'))
                    if vz_match and int(vz_match.groups()[0]) != 0:
                        grains['virtual'] = 'openvzve'
                    elif vz_match and int(vz_match.groups()[0]) == 0:
                        grains['virtual'] = 'openvzhn'
        if isdir('/proc/sys/xen') or \
                isdir('/sys/bus/xen') or isdir('/proc/xen'):
            if os.path.isfile('/proc/xen/xsd_kva'):
                # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
                # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
                grains['virtual_subtype'] = 'Xen Dom0'
            else:
                if osdata.get('productname', '') == 'HVM domU':
                    # Requires dmidecode!
                    grains['virtual_subtype'] = 'Xen HVM DomU'
                elif os.path.isfile('/proc/xen/capabilities') and \
                        os.access('/proc/xen/capabilities', os.R_OK):
                    with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
                        if 'control_d' not in fhr.read():
                            # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
                            grains['virtual_subtype'] = 'Xen PV DomU'
                        else:
                            # Shouldn't get to this, but just in case
                            grains['virtual_subtype'] = 'Xen Dom0'
                # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
                # Tested on Fedora 15 / 2.6.41.4-1 without running xen
                elif isdir('/sys/bus/xen'):
                    if 'xen:' in __salt__['cmd.run']('dmesg').lower():
                        grains['virtual_subtype'] = 'Xen PV DomU'
                    elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
                        # An actual DomU will have the xenconsole driver
                        grains['virtual_subtype'] = 'Xen PV DomU'
            # If a Dom0 or DomU was detected, obviously this is xen
            if 'dom' in grains.get('virtual_subtype', '').lower():
                grains['virtual'] = 'xen'
        # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
        if os.path.isfile('/proc/1/cgroup'):
            try:
                with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
                    fhr_contents = fhr.read()
                if ':/lxc/' in fhr_contents:
                    grains['virtual_subtype'] = 'LXC'
                elif ':/kubepods/' in fhr_contents:
                    grains['virtual_subtype'] = 'kubernetes'
                elif ':/libpod_parent/' in fhr_contents:
                    grains['virtual_subtype'] = 'libpod'
                else:
                    if any(x in fhr_contents
                           for x in (':/system.slice/docker', ':/docker/',
                                     ':/docker-ce/')):
                        grains['virtual_subtype'] = 'Docker'
            except IOError:
                pass
        if os.path.isfile('/proc/cpuinfo'):
            with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
                if 'QEMU Virtual CPU' in fhr.read():
                    grains['virtual'] = 'kvm'
        if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
            try:
                with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
                    output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
                    if 'VirtualBox' in output:
                        grains['virtual'] = 'VirtualBox'
                    elif 'RHEV Hypervisor' in output:
                        grains['virtual'] = 'kvm'
                        grains['virtual_subtype'] = 'rhev'
                    elif 'oVirt Node' in output:
                        grains['virtual'] = 'kvm'
                        grains['virtual_subtype'] = 'ovirt'
                    elif 'Google' in output:
                        grains['virtual'] = 'gce'
                    elif 'BHYVE' in output:
                        grains['virtual'] = 'bhyve'
            except IOError:
                pass
    elif osdata['kernel'] == 'FreeBSD':
        kenv = salt.utils.path.which('kenv')
        if kenv:
            product = __salt__['cmd.run'](
                '{0} smbios.system.product'.format(kenv)
            )
            maker = __salt__['cmd.run'](
                '{0} smbios.system.maker'.format(kenv)
            )
            if product.startswith('VMware'):
                grains['virtual'] = 'VMware'
            if product.startswith('VirtualBox'):
                grains['virtual'] = 'VirtualBox'
            if maker.startswith('Xen'):
                grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
                grains['virtual'] = 'xen'
            if maker.startswith('Microsoft') and product.startswith('Virtual'):
                grains['virtual'] = 'VirtualPC'
            if maker.startswith('OpenStack'):
                grains['virtual'] = 'OpenStack'
            if maker.startswith('Bochs'):
                grains['virtual'] = 'kvm'
        if sysctl:
            hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
            model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
            jail = __salt__['cmd.run'](
                '{0} -n security.jail.jailed'.format(sysctl)
            )
            if 'bhyve' in hv_vendor:
                grains['virtual'] = 'bhyve'
            if jail == '1':
                grains['virtual_subtype'] = 'jail'
            if 'QEMU Virtual CPU' in model:
                grains['virtual'] = 'kvm'
    elif osdata['kernel'] == 'OpenBSD':
        if 'manufacturer' in osdata:
            if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
                grains['virtual'] = 'kvm'
            if osdata['manufacturer'] == 'OpenBSD':
                grains['virtual'] = 'vmm'
    elif osdata['kernel'] == 'SunOS':
        if grains['virtual'] == 'LDOM':
            roles = []
            for role in ('control', 'io', 'root', 'service'):
                subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
                ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
                if ret['stdout'] == 'true':
                    roles.append(role)
            if roles:
                grains['virtual_subtype'] = roles
        else:
            # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
            zonename = salt.utils.path.which('zonename')
            if zonename:
                zone = __salt__['cmd.run']('{0}'.format(zonename))
                if zone != 'global':
                    grains['virtual'] = 'zone'
            # Check if it's a branded zone (i.e. Solaris 8/9 zone)
            if isdir('/.SUNWnative'):
                grains['virtual'] = 'zone'
    elif osdata['kernel'] == 'NetBSD':
        if sysctl:
            if 'QEMU Virtual CPU' in __salt__['cmd.run'](
                    '{0} -n machdep.cpu_brand'.format(sysctl)):
                grains['virtual'] = 'kvm'
            elif 'invalid' not in __salt__['cmd.run'](
                    '{0} -n machdep.xen.suspend'.format(sysctl)):
                grains['virtual'] = 'Xen PV DomU'
            elif 'VMware' in __salt__['cmd.run'](
                    '{0} -n machdep.dmi.system-vendor'.format(sysctl)):
                grains['virtual'] = 'VMware'
            # NetBSD has Xen dom0 support
            elif __salt__['cmd.run'](
                    '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
                if os.path.isfile('/var/run/xenconsoled.pid'):
                    grains['virtual_subtype'] = 'Xen Dom0'

    for command in failed_commands:
        log.info(
            "Although '%s' was found in path, the current user "
            'cannot execute it. Grains output might not be '
            'accurate.', command
        )
    return grains
499388
def _retrieve_grains_cache(proxy=None):
    '''
    
    '''
    global GRAINS_CACHE
    if not GRAINS_CACHE:
        if proxy and salt.utils.napalm.is_proxy(__opts__):
            # if proxy var passed and is NAPALM-type proxy minion
            GRAINS_CACHE = proxy['napalm.get_grains']()
        elif not proxy and salt.utils.napalm.is_minion(__opts__):
            # if proxy var not passed and is running in a straight minion
            GRAINS_CACHE = salt.utils.napalm.call(
                DEVICE_CACHE,
                'get_facts',
                **{}
            )
    return GRAINS_CACHE
379344
def _grains(host, protocol=None, port=None):
    '''
    
    '''
    username, password = find_credentials(DETAILS['host'])
    ret = __salt__['vsphere.system_info'](host=host,
                                          username=username,
                                          password=password,
                                          protocol=protocol,
                                          port=port)
    GRAINS_CACHE.update(ret)
    return GRAINS_CACHE
1175726
def process_minion_update(self, event_data):
        '''
        
        '''
        tag = event_data['tag']
        event_info = event_data['data']

        mid = tag.split('/')[-1]

        if not self.minions.get(mid, None):
            self.minions[mid] = {}

        minion = self.minions[mid]

        minion.update({'grains': event_info['return']})
        log.debug("In process minion grains update with minions=%s", self.minions)
        self.publish_minions()
1216292
def on(self, dev_id):
        
        path = 'device/on'
        payload = {'id': dev_id}
        return self.rachio.put(path, payload)
1038330
def _parse_oratab(sid):
    '''
    
    '''
    if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'):
        ORATAB = '/etc/oratab'
    elif __grains__.get('kernel') in 'SunOS':
        ORATAB = '/var/opt/oracle/oratab'
    else:
        # Windows has no oratab file
        raise CommandExecutionError(
            'No uri defined for {0} and oratab not available in this OS'.format(sid))
    with fopen(ORATAB, 'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
            if line.startswith('#'):
                continue
            if sid in line.split(':')[0]:
                return line.split(':')[1]
    return None
56071
def parse_grain(grain):
        
        if not grain:
            return InstantTime.day
        if grain.lower() == 'week':
            return InstantTime.week
        return InstantTime.day
919532
def _yum():
    '''
    
    '''
    contextkey = 'yum_bin'
    if contextkey not in __context__:
        if ('fedora' in __grains__['os'].lower()
           and int(__grains__['osrelease']) >= 22):
            __context__[contextkey] = 'dnf'
        elif 'photon' in __grains__['os'].lower():
            __context__[contextkey] = 'tdnf'
        else:
            __context__[contextkey] = 'yum'
    return __context__[contextkey]
102156
def _bsd_memdata(osdata):
    '''
    
    '''
    grains = {'mem_total': 0, 'swap_total': 0}

    sysctl = salt.utils.path.which('sysctl')
    if sysctl:
        mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl))
        if osdata['kernel'] == 'NetBSD' and mem.startswith('-'):
            mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl))
        grains['mem_total'] = int(mem) // 1024 // 1024

        if osdata['kernel'] in ['OpenBSD', 'NetBSD']:
            swapctl = salt.utils.path.which('swapctl')
            swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl))
            if swap_data == 'no swap devices configured':
                swap_total = 0
            else:
                swap_total = swap_data.split(' ')[1]
        else:
            swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl))
        grains['swap_total'] = int(swap_total) // 1024 // 1024
    return grains