.. versionadded:: 2014.7.0

    Return a dict that describes swap memory statistics.

    .. note::

        This function is only available in psutil version 0.6.0 and above.

    CLI Example:

    .. code-block:: bash

        salt '*' ps.swap_memory
189984
def swap_memory():
    '''
    
    '''
    if psutil.version_info < (0, 6, 0):
        msg = 'swap_memory is only available in psutil 0.6.0 or greater'
        raise CommandExecutionError(msg)
    return dict(psutil.swap_memory()._asdict())
1242324
private function _memory()
    {
        if (CommonFunctions::rfts('/proc/meminfo', $bufr)) {
            $bufe = preg_split("/\n/", $bufr, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($bufe as $buf) {
                if (preg_match('/Mem:\s+(.*)$/', $buf, $ar_buf)) {
                    $ar_buf = preg_split('/\s+/', $ar_buf[1], 6);
                    $this->sys->setMemTotal($ar_buf[0]);
                    $this->sys->setMemUsed($ar_buf[1]);
                    $this->sys->setMemFree($ar_buf[2]);
                    $this->sys->setMemApplication($ar_buf[3]);
                    $this->sys->setMemBuffer($ar_buf[4]);
                    $this->sys->setMemCache($ar_buf[5]);
                }
                // Get info on individual swap files
                if (CommonFunctions::rfts('/proc/swaps', $swaps)) {
                    $swapdevs = preg_split("/\n/", $swaps, -1, PREG_SPLIT_NO_EMPTY);
                    for ($i = 1, $max = (sizeof($swapdevs) - 1); $i < $max; $i++) {
                        $ar_buf = preg_split('/\s+/', $swapdevs[$i], 6);
                        $dev = new DiskDevice();
                        $dev->setMountPoint($ar_buf[0]);
                        $dev->setName("SWAP");
                        $dev->setFsType('swap');
                        $dev->setTotal($ar_buf[2] * 1024);
                        $dev->setUsed($ar_buf[3] * 1024);
                        $dev->setFree($dev->getTotal() - $dev->getUsed());
                        $this->sys->setSwapDevices($dev);
                    }
                }
            }
        }
    }
1350089
def memory_usage():
    
    try:
        import psutil
        import os
    except ImportError:
        return _memory_usage_ps()

    process = psutil.Process(os.getpid())
    mem = process.memory_info()[0] / float(2 ** 20)
    return mem
316975
def sort_stats(stats,
               sortedby='cpu_percent',
               sortedby_secondary='memory_percent',
               reverse=True):
    
    if sortedby is None and sortedby_secondary is None:
        # No need to sort...
        return stats

    # Check if a specific sort should be done
    sort_lambda = _sort_lambda(sortedby=sortedby,
                               sortedby_secondary=sortedby_secondary)

    if sort_lambda is not None:
        # Specific sort
        try:
            stats.sort(key=sort_lambda, reverse=reverse)
        except Exception:
            # If an error is detected, fallback to cpu_percent
            stats.sort(key=lambda process: (weighted(process['cpu_percent']),
                                            weighted(process[sortedby_secondary])),
                       reverse=reverse)
    else:
        # Standard sort
        try:
            stats.sort(key=lambda process: (weighted(process[sortedby]),
                                            weighted(process[sortedby_secondary])),
                       reverse=reverse)
        except (KeyError, TypeError):
            # Fallback to name
            stats.sort(key=lambda process: process['name'] if process['name'] is not None else '~',
                       reverse=False)

    return stats
748801
def _sunos_cpudata():
    '''
    
    '''
    # Provides:
    #   cpuarch
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    grains = {}
    grains['cpu_flags'] = []

    grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
    psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
    grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
    kstat_info = 'kstat -p cpu_info:*:*:brand'
    for line in __salt__['cmd.run'](kstat_info).splitlines():
        match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
        if match:
            grains['cpu_model'] = match.group(2)
    isainfo = 'isainfo -n -v'
    for line in __salt__['cmd.run'](isainfo).splitlines():
        match = re.match(r'^\s+(.+)', line)
        if match:
            cpu_flags = match.group(1).split()
            grains['cpu_flags'].extend(cpu_flags)

    return grains
292978
def get_docker_memory(self, container_id, all_stats):
        
        ret = {}
        # Read the stats
        try:
            # Do not exist anymore with Docker 1.11 (issue #848)
            # ret['rss'] = all_stats['memory_stats']['stats']['rss']
            # ret['cache'] = all_stats['memory_stats']['stats']['cache']
            ret['usage'] = all_stats['memory_stats']['usage']
            ret['limit'] = all_stats['memory_stats']['limit']
            ret['max_usage'] = all_stats['memory_stats']['max_usage']
        except (KeyError, TypeError) as e:
            # all_stats do not have MEM information
            logger.debug("docker plugin - Cannot grab MEM usage for container {} ({})".format(container_id, e))
            logger.debug(all_stats)
        # Return the stats
        return ret
446123
def _memory_data(self, log_prefix):
        
        machine_data = psutil.virtual_memory()

        process = psutil.Process()
        process_data = {
            'memory_info': process.get_memory_info(),
            'ext_memory_info': process.get_ext_memory_info(),
            'memory_percent': process.get_memory_percent(),
            'cpu_percent': process.get_cpu_percent(),
        }

        log.info(u"%s Machine memory usage: %s; Process memory usage: %s", log_prefix, machine_data, process_data)
        return {
            'machine_data': machine_data,
            'process_data': process_data,
        }
517249
def ingest_memory(self, memory):
        
        def lshift(num, shift):
            return num << shift

        def k(num, thousands):
            return num * thousands

        # if isinstance(memory, int):
        #     # Memory was specified as an integer, meaning it is in bytes
        memory = str(memory)

        bit_shift = {
            'E': {'func': k, 'shift': 10e17},
            'P': {'func': k, 'shift': 10e14},
            'T': {'func': k, 'shift': 10e11},
            'G': {'func': k, 'shift': 10e8},
            'M': {'func': k, 'shift': 10e5},
            'K': {'func': k, 'shift': 10e2},
            'Ei': {'func': lshift, 'shift': 60},
            'Pi': {'func': lshift, 'shift': 50},
            'Ti': {'func': lshift, 'shift': 40},
            'Gi': {'func': lshift, 'shift': 30},
            'Mi': {'func': lshift, 'shift': 20},
            'Ki': {'func': lshift, 'shift': 10},
        }

        if len(memory) > 2 and memory[-2:] in bit_shift.keys():
            unit = memory[-2:]
            number = int(memory[:-2])
            memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
        elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
            unit = memory[-1]
            number = int(memory[:-1])
            memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
        # Cast to a float to properly consume scientific notation
        return int(float(memory))
196610
def load_stats(self, fdump):
        
        if isinstance(fdump, type('')):
            fdump = open(fdump, 'rb')
        self.index = pickle.load(fdump)
        self.snapshots = pickle.load(fdump)
        self.sorted = []
635250
def as_a_dict(self):
        
        index_dict = {
            'ddoc': self._ddoc_id,
            'name': self._name,
            'type': self._type,
            'def': self._def
        }

        if self._partitioned:
            index_dict['partitioned'] = True

        return index_dict
325814
def ingest_memory(self, memory):
        
        def lshift(num, shift):
            return num << shift

        def rshift(num, shift):
            return num >> shift

        if isinstance(memory, int):
            # Memory was specified as an integer, meaning it is in bytes
            memory = '{}b'.format(memory)

        bit_shift = {
            'g': {'func': lshift, 'shift': 30},
            'm': {'func': lshift, 'shift': 20},
            'k': {'func': lshift, 'shift': 10},
            'b': {'func': rshift, 'shift': 0}
        }
        unit = memory[-1]
        number = int(memory[:-1])
        return bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
350465
def memory_used(self):
        
        if self._end_memory:
            memory_used = self._end_memory - self._start_memory
            return memory_used
        else:
            return None
681290
def swapoff(name):
    '''
    
    '''
    on_ = swaps()
    if name in on_:
        if __grains__['kernel'] == 'SunOS':
            if __grains__['virtual'] != 'zone':
                __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False)
            else:
                return False
        elif __grains__['os'] != 'OpenBSD':
            __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False)
        else:
            __salt__['cmd.run']('swapctl -d {0}'.format(name),
                                python_shell=False)
        on_ = swaps()
        if name in on_:
            return False
        return True
    return None
1027632
def _cx_counters_psutil(self, tags=None):
        
        tags = [] if tags is None else tags
        for iface, counters in iteritems(psutil.net_io_counters(pernic=True)):
            metrics = {
                'bytes_rcvd': counters.bytes_recv,
                'bytes_sent': counters.bytes_sent,
                'packets_in.count': counters.packets_recv,
                'packets_in.error': counters.errin,
                'packets_out.count': counters.packets_sent,
                'packets_out.error': counters.errout,
            }
            self._submit_devicemetrics(iface, metrics, tags)
338861
def val_accuracy(show_swap):
    """"""
    kv = kernel_ver()
    pid = os.getpid()
    swap_accuracy = -1
    if kv[:2] == (2,4):
        if proc.open('meminfo').read().find("Inact_") == -1:
            return 1, swap_accuracy
        return 0, swap_accuracy
    elif kv[:2] == (2,6):
        if os.path.exists(proc.path(pid, 'smaps')):
            swap_accuracy = 1
            if proc.open(pid, 'smaps').read().find("Pss:")!=-1:
                return 2, swap_accuracy
            else:
                return 1, swap_accuracy
        if (2,6,1) <= kv <= (2,6,9):
            return -1, swap_accuracy
        return 0, swap_accuracy
    elif kv[0] > 2 and os.path.exists(proc.path(pid, 'smaps')):
        swap_accuracy = 1
        if show_swap and proc.open(pid, 'smaps').read().find("SwapPss:")!=-1:
            swap_accuracy = 2
        return 2, swap_accuracy
    else:
        return 1, swap_accuracy
1005952
def pretty_memory_info():
    '''
    
    '''
    process = psutil.Process(os.getpid())
    return '{}MB memory usage'.format(int(process.memory_info().rss / 2**20))
618468
def _gather_buffer_space():
    '''
    
    '''
    if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
        # Oh good, we have psutil. This will be quick.
        total_mem = psutil.virtual_memory().total
    else:
        # Avoid loading core grains unless absolutely required
        import platform
        import salt.grains.core
        # We need to load up ``mem_total`` grain. Let's mimic required OS data.
        os_data = {'kernel': platform.system()}
        grains = salt.grains.core._memdata(os_data)
        total_mem = grains['mem_total'] * 1024 * 1024
    # Return the higher number between 5% of the system memory and 10MiB
    return max([total_mem * 0.05, 10 << 20])