<?php

namespace web\admin\autotask;

class base {
    public static function dayclean($systemrow) {
        global $db;
        $msg = '';
        $msg .= self::_base_deldb($db, (new \ciy\sql('zc_autotsk_run'))->where('addtimes<', time() - 86400 * 90));
        $msg .= self::_base_deldb($db, (new \ciy\sql('zc_autotsk_log'))->where('addtimes<', time() - 86400 * 90));
        $msg .= self::_base_deldb($db, (new \ciy\sql('zc_funcslow'))->where('addtimes<', time() - 86400 * 60));
        $msg .= self::_base_deldb($db, (new \ciy\sql('zc_stats'))->where('addtimes<', time() - 86400 * 60));
        $msg .= self::_base_deldb($db, (new \ciy\sql('zc_log'))->where('addtimes<', time() - 86400 * 100));
        $msg .= self::_base_deldb($db, (new \ciy\sql('zc_online'))->where('exptimes<', time() - 86400 * 7));

        $cnt = 0;
        $msg .= self::_base_delfile(PATH_WEB . 'ud/tmp', 86400 * 3, $cnt);
        $cnt = 0;
        $msg .= self::_base_delfile(PATH_WEB . 'ud/rep', 86400 * 1, $cnt);
        return $msg;
    }
    static function _base_deldb($db, $csql) {
        $execute = $db->delete($csql);
        if ($execute === false)
            return 'clean ' . $csql->table . ': ' . $db->error . '<br/>';
        else if ($execute > 0)
            return 'clean ' . $csql->table . ': ' . $execute . '<br/>';
        return '';
    }
    static function _base_delfile($pathfile, $timespan, &$cnt, $deep = 0) {
        if (!is_dir($pathfile)) {
            if (file_exists($pathfile)) {
                $mtime = filemtime($pathfile);
                if ($mtime !== false) {
                    if (tostamp() - $mtime > $timespan) {
                        $cnt++;
                        filedel($pathfile);
                    }
                }
            }
            return;
        }
        $files = scandir($pathfile);
        foreach ($files as $file) {
            if ($file == '.' || $file == '..')
                continue;
            self::_base_delfile($pathfile . '/' . $file, $timespan, $cnt, 1);
        }
        if ($deep == 0 && $cnt > 0)
            return 'clean file: ' . $cnt . '  ' . substr($pathfile, strlen(PATH_WEB)) . '<br/>';
        return '';
    }
    public static function srvstats($systemrow) {
        global $db;
        $func_succ = 0;
        $func_fail = 0;
        $func_commit = 0;
        $func_rollback = 0;
        $func_runms = 0;
        $csql = new \ciy\sql('zc_zmem_var');
        $memrows = $db->get($csql);
        foreach ($memrows as $memrow) {
            if ($memrow['types'] == 'func_succ')
                $func_succ = toint($memrow['params']);
            else if ($memrow['types'] == 'func_fail')
                $func_fail = toint($memrow['params']);
            else if ($memrow['types'] == 'func_commit')
                $func_commit = toint($memrow['params']);
            else if ($memrow['types'] == 'func_rollback')
                $func_rollback = toint($memrow['params']);
            else if ($memrow['types'] == 'func_runms') {
                $func_runms = toint($memrow['params']);
            } else
                continue;
            $updata = array();
            $updata['params'] = 0;
            $csql = new \ciy\sql('zc_zmem_var');
            $csql->where('id', $memrow['id']);
            $db->update($csql, $updata);
        }
        $func_runms = 0;
        if ($func_succ + $func_fail > 0)
            $func_runms = $func_runms / ($func_succ + $func_fail);

        $disk_sysfree = disk_free_space("/");
        $disk_datafree = disk_free_space("/data");
        // $disk_sysfree = disk_free_space("D:/");
        // $disk_datafree = disk_free_space("E:/");
        $starttime = timems();
        $fcontent = str_repeat("0", 1024 * 1024); //写入1MB
        $fpath = PATH_WEB . "/ud/_" . tostamp() . ".bin";
        file_put_contents($fpath, $fcontent);
        $rcontent = file_get_contents($fpath);
        unlink($fpath);
        $disk_ioms = timems() - $starttime;
        if ($rcontent !== $fcontent) {
            savelog($db, 0, 'STAT', '写入临时文件校验失败');
        }

        $output = array();
        exec("ps aux -A", $output);
        // $output = array();
        // $output[] = "USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND";
        // $output[] = "root         1  0.0  0.0 190928  3396 ?        Ss   Apr10   9:54 /usr/lib/systemd/systemd --switched-root --system --deserialize 22";
        // $output[] = "root         2  0.0  0.0      0     0 ?        S    Apr10   0:00 [kthreadd]";
        // $output[] = "root      1322  0.0  0.0 102900  2320 ?        Ss   Apr10   0:00 /sbin/dhclient -q -lf /var/lib/dhclient/dhclient--eth0.lease -pf /var/run/dhclient-eth0.pid -H VM_0_5_centos eth0";
        // $output[] = "mysql     2219  0.2  9.3 1654448 362344 ?      Sl   Apr10  76:53 /usr/libexec/mysqld --basedir=/usr --datadir=/data/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock";
        // $output[] = "root      2934  0.0  0.2 494920 10360 ?        S    Apr10   0:02 WorkerMan: worker process  proxy tcp://0.0.0.0:6981";
        $cmddb = ['mysql', 'mysqld'];
        $cmdweb = ['nginx', 'php', 'WorkerMan', 'mosquitto', 'gitea', '/zgo'];
        $cpu = array('db' => 0, 'web' => 0, 'oth' => 0);
        $mem = array('db' => 0, 'web' => 0, 'oth' => 0);

        foreach ($output as $line) {
            if (strpos($line, "COMMAND") !== false)
                continue;
            self::_base_nextspace($line);
            self::_base_nextspace($line);
            $cpup = (float)self::_base_nextspace($line);
            $memp = (float)self::_base_nextspace($line);
            self::_base_nextspace($line); //虚拟内存
            self::_base_nextspace($line); //物理内存 包括共享内存
            self::_base_nextspace($line);
            self::_base_nextspace($line);
            self::_base_nextspace($line);
            self::_base_nextspace($line);
            if (self::_base_arrin($line, $cmddb)) {
                $cpu['db'] += $cpup;
                $mem['db'] += $memp;
            } else if (self::_base_arrin($line, $cmdweb)) {
                $cpu['web'] += $cpup;
                $mem['web'] += $memp;
            } else {
                $cpu['oth'] += $cpup;
                $mem['oth'] += $memp;
            }
        }

        $output = array();
        exec("free -m", $output);
        // $output = array();
        // $output[] = "              total        used        free      shared  buff/cache   available";
        // $output[] = "Mem:           3789         860         201          18        2727        2629";

        preg_match('/Mem:\s+(\d+)/', $output[1], $totalmem);
        $mem_free = $totalmem[1] * (100 - $cpu['db'] - $cpu['web'] - $cpu['oth']) * 1024 * 1024 / 100;

        $output = array();
        exec("netstat -an | awk '/^tcp/ {++S[\$NF]} END {for(a in S) print a, S[a]}'", $output);

        // $output = array();
        // $output[] = "LISTEN 13";
        // $output[] = "SYN_RECV 3";
        // $output[] = "ESTABLISHED 15";
        // $output[] = "TIME_WAIT 36";
        $net_tcp = 0;
        foreach ($output as $line) {
            $ls = explode(" ", $line);
            if ($ls[0] == 'LISTEN')
                continue;
            $net_tcp += toint($ls[1]);
        }

        $starttime = timems();
        $http = new \ciy\http();
        $http->request('https://www.baidu.com');
        $http->get_data();
        $net_ioms = timems() - $starttime;

        $dbrows = $db->getraw('show global status');
        $dbstat = array();
        for ($i = 0; $i < count($dbrows); $i++) {
            $name = $dbrows[$i]['Variable_name'];
            $val = $dbrows[$i]['Value'];
            $dbstat[$name] = $val;
        }
        $db_keyhit = toint($dbstat['Handler_read_key']) / (toint($dbstat['Com_select']) + 1) * 100;
        $db_dbhit = 100 - toint($dbstat['Innodb_buffer_pool_reads']) / (toint($dbstat['Innodb_buffer_pool_read_requests']) + 1) * 100;
        $db_tmptable = toint($dbstat['Created_tmp_disk_tables']) / (toint($dbstat['Created_tmp_tables']) + 1) * 100;

        $updata = array();
        $updata['func_succ'] = $func_succ;
        $updata['func_fail'] = $func_fail;
        $updata['func_commit'] = $func_commit;
        $updata['func_rollback'] = $func_rollback;
        $updata['func_runms'] = $func_runms;
        $updata['disk_sysfree'] = $disk_sysfree;
        $updata['disk_datafree'] = $disk_datafree;
        $updata['disk_ioms'] = $disk_ioms;
        $updata['cpu_free'] = 100 - $cpu['db'] - $cpu['web'] - $cpu['oth'];
        $updata['cpu_db'] = $cpu['db'];
        $updata['cpu_web'] = $cpu['web'];
        $updata['cpu_oth'] = $cpu['oth'];
        $updata['mem_free'] = $mem_free;
        $updata['mem_db'] = $mem['db'];
        $updata['mem_web'] = $mem['web'];
        $updata['mem_oth'] = $mem['oth'];
        $updata['net_tcp'] = $net_tcp;
        $updata['net_ioms'] = $net_ioms;
        $updata['db_query'] = $dbstat['Questions'];
        $updata['db_commit'] = $dbstat['Com_commit'];
        $updata['db_rollback'] = $dbstat['Com_rollback'];
        $updata['db_keyhit'] = $db_keyhit;
        $updata['db_dbhit'] = $db_dbhit;
        $updata['db_tmptable'] = $db_tmptable;
        $updata['db_lock'] = $dbstat['Innodb_row_lock_current_waits'];
        $updata['addtimes'] = tostamp();
        $csql = new \ciy\sql('zc_stats');
        $db->insert($csql, $updata);
        if ($func_succ == 0 && $func_fail == 0 && $func_rollback == 0)
            return '';
        return 'succ: ' . $func_succ . ($func_rollback > 0 ? ', rollback: ' . $func_rollback : '');
    }
    static function _base_nextspace(&$line) {
        $ind = strpos($line, " ");
        if ($ind === false) {
            $line = '';
            return $line;
        }
        $va = substr($line, 0, $ind);
        $line = ltrim(substr($line, $ind));
        return $va;
    }
    static function _base_arrin($cmd, $arr) {
        foreach ($arr as $v) {
            if (strpos($cmd, $v) !== false)
                return true;
        }
        return false;
    }
}
