1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 
<?php
    declare(strict_types=1);
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    use Daphnie\Collector;
    use Daphnie\Metrics\Memory as MemoryMetric;
    use Opcenter\System\Memory;

    /**
     * Statistics/hardware information
     *
     * @package core
     */
    class Stats_Module extends Module_Skeleton
    {
        /**
         * {{{ void __construct(void)
         *
         * @ignore
         */
        public function __construct()
        {
            parent::__construct();
            $this->exportedFunctions = array(
                '*' => PRIVILEGE_ALL
            );
        }

        /**
         * array get_partition_information
         *
         * @return array
         */
        public function get_partition_information()
        {
            $fsoptions = array();

            $buffer = file('/proc/mounts', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);

            $results = [];
            $knownMounts = [];
            foreach ($buffer as $line) {
                if (0 !== strncmp($line, '/dev/', 5)) {
                    continue;
                }

                [$dev, $mpoint, $type, $options, $fsck, $_] = explode(' ', $line);

                if (isset($knownMounts[$dev])) {
                    continue;
                }

                $knownMounts[$dev] = 1;

                $total = disk_total_space($mpoint)/1024;
                if (!$total) {
                    // device mount, hugetlbfs/devpts
                    continue;
                }
                $free = disk_free_space($mpoint)/1024;

                $results[] = [
                    'disk' => $dev,
                    'size' => (int)$total,
                    'used' => (int)($total-$free),
                    'free' => (int)$free,
                    'percent' => round(($total - $free)/$total * 100) . '%',
                    'mount' => $mpoint,
                    'fstype' => $type,
                    'options' => $options
                ];
            }

            return $results;
        }

        public function get_spamassassin_stats()
        {
            $sastats = array();
            if (!file_exists('/tmp/sa-stats')) {
                return $sastats;
            }
            $fp = fopen('/tmp/sa-stats', 'r');
            while (false !== ($line = fgets($fp))) {
                $buffer = '  ';
                if (false !== strpos($line, 'Period Beginning')) {
                    $data = explode(':', $line);
                    $sastats['begin_date'] = trim(implode(':', array_slice($data, 1)));
                } else if (false !== strpos($line, 'Period Ending')) {
                    $data = explode(':', $line);
                    $sastats['end_date'] = trim(implode(':', array_slice($data, 1)));
                } else {
                    if (false !== strpos($line, 'Reporting Period')) {
                        /** Get the whole section of reporting period... */
                        $line = fgets($fp);
                        fgets($fp); // remove --------- line
                        while (false !== ($line = fgets($fp))) {
                            if ($buffer[strlen($buffer) - 2] == "\n" && $buffer[strlen($buffer) - 1] == "\n" && $line == "\n") {
                                break;
                            }
                            $buffer .= $line;
                        }
                        $sastats['reporting_information'] = trim($buffer);
                    } else {
                        if (false !== strpos($line, 'Statistics by Hour')) {
                            $line = fgets($fp); // remove --------- line
                            while (false !== ($line = fgets($fp))) {

                                if ($buffer[strlen($buffer) - 2] == "\n" && $buffer[strlen($buffer) - 1] == "\n" && $line == "\n") {
                                    break;
                                }
                                $buffer .= $line;
                            }
                            $sastats['stats_by_hour'] = trim($buffer);
                        } else {
                            if (false !== strpos($line, 'Done. Report generated')) {
                                while (false !== ($line = fgets($fp))) {
                                    /**
                                     * nasty hack, we shouldn't assume TOP [SPAM, HAM]
                                     * RULES FIRED is coming next
                                     */
                                    if (false !== strpos($line, 'TOP')) {
                                        $bufftmp = $buffer;
                                        $buffer = $line;
                                        while (false !== ($line = fgets($fp))) {
                                            $buffer .= $line;
                                        }
                                        $sastats['rule_information'] = trim($buffer);
                                        $buffer = $bufftmp;
                                        break;
                                    }
                                    $buffer .= $line;
                                }
                                $sastats['reporting_information'] .= "\n\n" . trim($buffer);
                            } else {
                                if (false !== strpos($line, 'TOP')) {

                                }
                            }
                        }
                    }
                }
            }
            fclose($fp);

            return $sastats;
        }

        /**
         * array get_memory_information()
         *
         * @return array
         */
        public function get_memory_information()
        {
            if (false === ($fd = fopen('/proc/meminfo', 'r'))) {
                return new FileError('/proc/meminfo does not exist');
            }

            $results['ram'] = array();
            $results['swap'] = array(
                'total'   => 0,
                'used'    => 0,
                'percent' => 0
            );
            $results['devswap'] = array();

            while ($buf = fgets($fd)) {
                if (preg_match('/^MemTotal:\s+(.*)\s*kB/i', $buf, $ar_buf)) {
                    $results['ram']['total'] = (int)$ar_buf[1];
                } else {
                    if (preg_match('/^MemFree:\s+(.*)\s*kB/i', $buf, $ar_buf)) {
                        $results['ram']['t_free'] = (int)$ar_buf[1];
                    } else {
                        if (preg_match('/^Cached:\s+(.*)\s*kB/i', $buf, $ar_buf)) {
                            $results['ram']['cached'] = (int)$ar_buf[1];
                        } else {
                            if (preg_match('/^Buffers:\s+(.*)\s*kB/i', $buf, $ar_buf)) {
                                $results['ram']['buffers'] = (int)$ar_buf[1];
                            } else {
                                if (preg_match('/^SwapTotal:\s+([1-9]\d*)\s*kB/i', $buf, $ar_buf)) {
                                    $results['swap']['total'] = (int)$ar_buf[1];
                                } else {
                                    if (preg_match('/^SwapFree:\s+(.*)\s*kB/i', $buf, $ar_buf)) {
                                        $results['swap']['free'] = (int)$ar_buf[1];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            fclose($fd);

            $results['ram']['t_used'] = $results['ram']['total'] - $results['ram']['t_free'];
            $results['ram']['percent'] = round(($results['ram']['t_used'] * 100) / $results['ram']['total']);
            $results['swap']['used'] = $results['swap']['total'] - $results['swap']['free'];
            if ($results['swap']['total'] > 0) {
                $results['swap']['percent'] = round(($results['swap']['used'] * 100) / $results['swap']['total']);
            }

            // values for splitting memory usage
            if (isset($results['ram']['cached']) && isset($results['ram']['buffers'])) {
                $results['ram']['app'] = $results['ram']['t_used'] - $results['ram']['cached'] - $results['ram']['buffers'];
                $results['ram']['app_percent'] = round(($results['ram']['app'] * 100) / $results['ram']['total']);
                $results['ram']['buffers_percent'] = round(($results['ram']['buffers'] * 100) / $results['ram']['total']);
                $results['ram']['cached_percent'] = round(($results['ram']['cached'] * 100) / $results['ram']['total']);
            }

            $swaps = file('/proc/swaps');
            for ($i = 1, $n = sizeof($swaps); $i < $n; $i++) {
                $ar_buf = preg_split('/\s+/', $swaps[$i], 6);
                $results['devswap'][$ar_buf[0]] = array();
                $results['devswap'][$ar_buf[0]]['total'] = $ar_buf[2];
                $results['devswap'][$ar_buf[0]]['used'] = $ar_buf[3];
                $results['devswap'][$ar_buf[0]]['free'] = ($results['devswap'][$ar_buf[0]]['total'] - $results['devswap'][$ar_buf[0]]['used']);
                $results['devswap'][$ar_buf[0]]['percent'] = round(($ar_buf[3] * 100) / $ar_buf[2]);
            }

            return $results;
        }

        /**
         * Report virtual memory statistics
         *
         * @return array
         */
        public function vmstat(): array {
            $stat = file('/proc/stat', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
            $ts = microtime(true);
            $fields = preg_split('/\s+/', $stat[0]);

            $labels = [
                'user',
                'nice',
                'system',
                'idle',
                'iowait',
                'irq',
                'softirq',
                'steal',
                'guest',
                'guest_nice'
            ];
            array_shift($fields);
            $values = array_combine($labels, array_map(static function ($v) {
                return (int)$v;
                }, $fields)
            );
            $values['ts'] = $ts;


            return $values;
        }
        /**
         * array get_network_device_information
         *
         * @return array key, device name, values:
         *              [tx,rx]_bytes, [tx,rx]_packets,
         *              [tx,rx]_errs, [tx,rx]_drop
         */
        public function get_network_device_information()
        {
            $results = array();

            if (false === ($fd = fopen('/proc/net/dev', 'r'))) {
                return new IOError('/proc/net/dev does not exist');
            }

            while ($buf = fgets($fd, 4096)) {
                if (preg_match('/:/', $buf)) {
                    list($dev_name, $stats_list) = explode(":", $buf, 2);
                    $stats = preg_split('/\s+/', trim($stats_list));
                    $results[$dev_name] = array();

                    $results[$dev_name]['rx_bytes'] = $stats[0];
                    $results[$dev_name]['rx_packets'] = $stats[1];
                    $results[$dev_name]['rx_errs'] = $stats[2];
                    $results[$dev_name]['rx_drop'] = $stats[3];

                    $results[$dev_name]['tx_bytes'] = $stats[8];
                    $results[$dev_name]['tx_packets'] = $stats[9];
                    $results[$dev_name]['tx_errs'] = $stats[10];
                    $results[$dev_name]['tx_drop'] = $stats[11];

                    $results[$dev_name]['errs'] = $stats[2] + $stats[10];
                    $results[$dev_name]['drop'] = $stats[3] + $stats[11];
                }
            }

            return $results;

        }

        public function _cron(Cronus $c)
        {
            if (!TELEMETRY_ENABLED) {
                return;
            }
            $collector = new Collector(PostgreSQL::pdo());
            $status = Memory::stats();
            foreach (MemoryMetric::getAttributeMap() as $attr => $metric) {
                $val = $status[$metric];

                if ($val instanceof Closure) {
                    $val = $val($status);
                }
                $collector->add("memory-${attr}", null, $val);
            }
        }
    }