Physical memory information and Swap Space information

@return void
14696
private function _memory()
    {
        if (CommonFunctions::executeProgram('pidin', 'info', $buf)
           && preg_match('/^.* FreeMem:(\S+)Mb\/(\S+)Mb/', $buf, $memm)) {
            $this->sys->setMemTotal(1024*1024*$memm[2]);
            $this->sys->setMemFree(1024*1024*$memm[1]);
            $this->sys->setMemUsed(1024*1024*($memm[2]-$memm[1]));
        }
    }
1169840
protected function cpuinfo()
    {
        $dev = new CpuDevice();
        $dev->setModel($this->grabkey('hw.model'));
        $dev->setCpuSpeed($this->grabkey('hw.cpuspeed'));
        $was = false;
        foreach ($this->readdmesg() as $line) {
            if (preg_match("/^cpu[0-9]+: (.*)/", $line, $ar_buf)) {
                $was = true;
                if (preg_match("/^cpu[0-9]+: (\d+)([KM])B (.*) L2 cache/", $line, $ar_buf2)) {
                    if ($ar_buf2[2]=="M") {
                        $dev->setCache($ar_buf2[1]*1024*1024);
                    } elseif ($ar_buf2[2]=="K") {
                        $dev->setCache($ar_buf2[1]*1024);
                    }
                } else {
                    $feats = preg_split("/,/", strtolower(trim($ar_buf[1])), -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($feats as $feat) {
                        if (($feat=="vmx") || ($feat=="svm")) {
                            $dev->setVirt($feat);
                        }
                    }
                }
            } elseif ($was) {
                break;
            }
        }
        $ncpu = $this->grabkey('hw.ncpu');
        if (is_null($ncpu) || (trim($ncpu) == "") || (!($ncpu >= 1)))
            $ncpu = 1;
        for ($ncpu ; $ncpu > 0 ; $ncpu--) {
            $this->sys->setCpus($dev);
        }
    }
1131253
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats using the standard system lib
            # Grab SWAP using the psutil swap_memory method
            sm_stats = psutil.swap_memory()

            # Get all the swap stats (copy/paste of the psutil documentation)
            # total: total swap memory in bytes
            # used: used swap memory in bytes
            # free: free swap memory in bytes
            # percent: the percentage usage
            # sin: the number of bytes the system has swapped in from disk (cumulative)
            # sout: the number of bytes the system has swapped out from disk
            # (cumulative)
            for swap in ['total', 'used', 'free', 'percent',
                         'sin', 'sout']:
                if hasattr(sm_stats, swap):
                    stats[swap] = getattr(sm_stats, swap)
        elif self.input_method == 'snmp':
            # Update stats using SNMP
            if self.short_system_name == 'windows':
                # Mem stats for Windows OS are stored in the FS table
                try:
                    fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
                                                  bulk=True)
                except KeyError:
                    self.reset()
                else:
                    for fs in fs_stat:
                        # The virtual memory concept is used by the operating
                        # system to extend (virtually) the physical memory and
                        # thus to run more programs by swapping unused memory
                        # zone (page) to a disk file.
                        if fs == 'Virtual Memory':
                            stats['total'] = int(
                                fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
                            stats['used'] = int(
                                fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
                            stats['percent'] = float(
                                stats['used'] * 100 / stats['total'])
                            stats['free'] = stats['total'] - stats['used']
                            break
            else:
                stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])

                if stats['total'] == '':
                    self.reset()
                    return stats

                for key in iterkeys(stats):
                    if stats[key] != '':
                        stats[key] = float(stats[key]) * 1024

                # used=total-free
                stats['used'] = stats['total'] - stats['free']

                # percent: the percentage usage calculated as (total -
                # available) / total * 100.
                stats['percent'] = float(
                    (stats['total'] - stats['free']) / stats['total'] * 100)

        # Update the stats
        self.stats = stats

        return self.stats
343011
protected function configurePhp() {
        $memoryWarnLimit = php_byte_value(self::$defaultConfig->get('log.warn.memory_limit', 0));
        if ($memoryWarnLimit > 0) {
            register_shutdown_function(function() use ($memoryWarnLimit) {
                $usedBytes = memory_get_peak_usage($real=true);
                if ($usedBytes > $memoryWarnLimit) {
                    Logger::log('Memory consumption exceeded '.prettyBytes($memoryWarnLimit).' (peak usage: '.prettyBytes($usedBytes).')', L_WARN, ['class' => __CLASS__]);
                }
            });
        }
        /*
        ini_set('arg_separator.output'    , '&amp;'                );
        ini_set('auto_detect_line_endings',  1                     );
        ini_set('default_mimetype'        , 'text/html'            );
        ini_set('default_charset'         , 'UTF-8'                );
        ini_set('ignore_repeated_errors'  ,  0                     );
        ini_set('ignore_repeated_source'  ,  0                     );
        ini_set('ignore_user_abort'       ,  1                     );
        ini_set('display_errors'          , (int)(CLI || LOCALHOST));
        ini_set('display_startup_errors'  , (int)(CLI || LOCALHOST));
        ini_set('log_errors'              ,  1                     );
        ini_set('log_errors_max_len'      ,  0                     );
        ini_set('track_errors'            ,  1                     );
        ini_set('html_errors'             ,  0                     );
        ini_set('session.use_cookies'     ,  1                     );
        ini_set('session.use_trans_sid'   ,  0                     );
        ini_set('session.cookie_httponly' ,  1                     );
        ini_set('session.referer_check'   , ''                     );
        ini_set('zend.detect_unicode'     ,  1                     );     // BOM header recognition
        */
    }
804545
public static function raiseMemoryLimitIfNecessary()
    {
        $memoryLimit = self::getMemoryLimitValue();
        if ($memoryLimit === false) {
            return false;
        }
        $minimumMemoryLimit = Config::getInstance()->General['minimum_memory_limit'];

        if (self::isArchivePhpTriggered()) {
            // core:archive command: no time limit, high memory limit
            self::setMaxExecutionTime(0);
            $minimumMemoryLimitWhenArchiving = Config::getInstance()->General['minimum_memory_limit_when_archiving'];
            if ($memoryLimit < $minimumMemoryLimitWhenArchiving) {
                return self::setMemoryLimit($minimumMemoryLimitWhenArchiving);
            }
            return false;
        }
        if ($memoryLimit < $minimumMemoryLimit) {
            return self::setMemoryLimit($minimumMemoryLimit);
        }
        return false;
    }
675855
protected function memory()
    {
        $s = $this->grabkey('hw.memsize');
        if (CommonFunctions::executeProgram('vm_stat', '', $pstat, PSI_DEBUG)) {
            // calculate free memory from page sizes (each page = 4096)
            if (preg_match('/^Pages free:\s+(\S+)/m', $pstat, $free_buf)) {
                if (preg_match('/^Anonymous pages:\s+(\S+)/m', $pstat, $anon_buf)
                   && preg_match('/^Pages wired down:\s+(\S+)/m', $pstat, $wire_buf)
                   && preg_match('/^File-backed pages:\s+(\S+)/m', $pstat, $fileb_buf)) {
                        // OS X 10.9 or never
                        $this->sys->setMemFree($free_buf[1] * 4 * 1024);
                        $this->sys->setMemApplication(($anon_buf[1]+$wire_buf[1]) * 4 * 1024);
                        $this->sys->setMemCache($fileb_buf[1] * 4 * 1024);
                        if (preg_match('/^Pages occupied by compressor:\s+(\S+)/m', $pstat, $compr_buf)) {
                            $this->sys->setMemBuffer($compr_buf[1] * 4 * 1024);
                        }
                } else {
                    if (preg_match('/^Pages speculative:\s+(\S+)/m', $pstat, $spec_buf)) {
                        $this->sys->setMemFree(($free_buf[1]+$spec_buf[1]) * 4 * 1024);
                    } else {
                        $this->sys->setMemFree($free_buf[1] * 4 * 1024);
                    }
                    $appMemory = 0;
                    if (preg_match('/^Pages wired down:\s+(\S+)/m', $pstat, $wire_buf)) {
                        $appMemory += $wire_buf[1] * 4 * 1024;
                    }
                    if (preg_match('/^Pages active:\s+(\S+)/m', $pstat, $active_buf)) {
                        $appMemory += $active_buf[1] * 4 * 1024;
                    }
                    $this->sys->setMemApplication($appMemory);

                    if (preg_match('/^Pages inactive:\s+(\S+)/m', $pstat, $inactive_buf)) {
                        $this->sys->setMemCache($inactive_buf[1] * 4 * 1024);
                    }
                }
            } else {
                $lines = preg_split("/\n/", $pstat, -1, PREG_SPLIT_NO_EMPTY);
                $ar_buf = preg_split("/\s+/", $lines[1], 19);
                $this->sys->setMemFree($ar_buf[2] * 4 * 1024);
            }

            $this->sys->setMemTotal($s);
            $this->sys->setMemUsed($this->sys->getMemTotal() - $this->sys->getMemFree());

            if (CommonFunctions::executeProgram('sysctl', 'vm.swapusage | colrm 1 22', $swapBuff, PSI_DEBUG)) {
                $swap1 = preg_split('/M/', $swapBuff);
                $swap2 = preg_split('/=/', $swap1[1]);
                $swap3 = preg_split('/=/', $swap1[2]);
                $dev = new DiskDevice();
                $dev->setName('SWAP');
                $dev->setMountPoint('SWAP');
                $dev->setFsType('swap');
                $dev->setTotal($swap1[0] * 1024 * 1024);
                $dev->setUsed($swap2[1] * 1024 * 1024);
                $dev->setFree($swap3[1] * 1024 * 1024);
                $this->sys->setSwapDevices($dev);
            }
        }
    }
587800
public function getMemory()
    {
        $memory = 0;
        foreach ($this->periods as $period) {
            if ($period->getMemory() > $memory) {
                $memory = $period->getMemory();
            }
        }

        return $memory;
    }
739377
protected function storeActiveSortInSession()
    {
        if (null !== $this->activeSortDescending) {
            $direction = $this->activeSortDescending ? 'desc' : 'asc';
        } else {
            $direction = null;
        }

        $this->getListMemory()->setSortData($this->activeSort, $direction);
    }
530558
public function getInfo() {
		$info = $this->createInfoset();
		
		$memory = memory_get_peak_usage();
		$limit  = ini_get('memory_limit');
		
		if ($limit < 0) {
			$limit = 'unlimited';
		}
		
		$info->setIcon('chip')
		     ->setName('Memory usage')
		     ->setTitle($this->formatMemory($memory) . ' of ' . $limit);
		
		if ($limit / $memory < 0.25) {
			$info->setLevel(Infoset::LEVEL_WARNING);
		}
		
		return $info;
	}
1073675
protected function bootMemoryEvent()
    {
        $app = $this->app;
        /** looking for forms * */
        //$app->make('events')->listen('antares.forms', function ($name) use ($app) {
        $app->make('events')->listen(Form::class, function (Form $event) use ($app) {
            $app->make('antares.memory')->make('registry.forms')->put('forms', $event->formName);
        });
        /** when application is terminating we collect all data from application * */
        $app->terminating(function () use ($app) {
            if (!app('antares.installed')) {
                //$app->make('antares.memory')->finish();
            }
        });
        //$app->make('events')->listen('antares.after.load-service-providers', function() {
        $app->make('events')->listen(LoadServiceProviders::class, function() {
            $this->app->make('antares.defered.service')->run();
        });
    }
1205949
public function peek()
    {
        if($this->getType() == 'memory') {
            $position =  $this->_position;
        } else {
            $position = parent::peek();
        }

        return $position;
    }
1331838
private function getMemory()
    {
        $memory = shmop_open($this->key, "c", 0644, self::LIMIT);

        if (!$memory) {
            throw new Exception("Unable to open the shared memory block");
        }

        return $memory;
    }
792339
protected function serializeToStorage()
  {
    $this->debugLog('serializeToStorage()');
    $this->storage->updateLists($this->lists);
    $this->storage->setUpdaterState($this->next_request_timestamp, $this->error_count);
    
    $this->debugLog('current memory usage: '.memory_get_usage());
    $this->debugLog('peak memory usage   : '.memory_get_peak_usage());
  }
998067
private function _info()
    {
        if (empty($this->_output)) {
            return;
        }
        $model = array();
        $percCharge = array();
        $lines = explode(PHP_EOL, implode($this->_output));
        if (count($lines)>1) {
            $model = explode('FW:', $lines[1]);
            if (strpos($model[0], 'InternalBattery') === false) {
                $dev = new UPSDevice();
                $percCharge = explode(';', $lines[1]);
                $dev->setName('UPS');
                if ($model !== false) {
                    $dev->setModel(substr(trim($model[0]), 1));
                }
                if ($percCharge !== false) {
                    $dev->setBatterCharge(trim(substr($percCharge[0], -4, 3)));
                    $dev->setStatus(trim($percCharge[1]));
                    if (isset($percCharge[2])) {
                        $time = explode(':', $percCharge[2]);
                        $hours = $time[0];
                        $minutes = $hours*60+substr($time[1], 0, 2);
                        $dev->setTimeLeft($minutes);
                    }
                }
                $dev->setMode("pmset");
                $this->upsinfo->setUpsDevices($dev);
            }
        }
    }
857699
private function memoryLimit(): int
    {
        $memory_limit = ini_get('memory_limit');

        switch (substr($memory_limit, -1)) {
            case 'k':
            case 'K':
                $memory_limit = substr($memory_limit, 0, -1) / 1024;
                break;
            case 'm':
            case 'M':
                $memory_limit = substr($memory_limit, 0, -1);
                break;
            case 'g':
            case 'G':
                $memory_limit = substr($memory_limit, 0, -1) * 1024;
                break;
            case 't':
            case 'T':
                $memory_limit = substr($memory_limit, 0, -1) * 1024 * 1024;
                break;
            default:
                $memory_limit = $memory_limit / 1024 / 1024;
        }

        return (int) $memory_limit;
    }
1178524
public static function init()
    {
        if(static::$isInited)
        {
            throw new \RuntimeException('MemoryTableManager can not repeated init');
        }
        foreach(static::$tables as $name => $option)
        {
            $table = new \Swoole\Table($option['size'] ?? 1024, $option['conflictProportion'] ?? 0.2);
            foreach($option['columns'] as $column)
            {
                $table->column($column['name'], $column['type'] ?? swoole_table::TYPE_STRING, $column['size'] ?? 0);
            }
            if(!$table->create())
            {
                throw new \RuntimeException('MemoryTableManager create table failed');
            }
            static::$tables[$name] = $table;
        }
        static::$isInited = true;
    }
141441
public function calcResourceMemorySize(): int {
		$imageData = getimagesize($this->filePath);
		
		return round(($imageData[0] * $imageData[1] * $imageData['bits'] * $imageData['channels'] / 8));
	}