System.cpp 13.3 KB
Newer Older
xiongziliang committed
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
/*
 * MIT License
 *
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
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

#include "System.h"
#include <stdlib.h>
#include <signal.h>
#include <arpa/inet.h>
#include <limits.h>
#include <sys/resource.h>
#include <unistd.h>
#include <sys/wait.h>
#include <execinfo.h>
#include <map>
#include <string>
#include <iostream>
#include "Util/mini.h"
#include "Util/util.h"
#include "Util/logger.h"
#include "Util/onceToken.h"
#include "Util/NoticeCenter.h"
#include "System.h"
#include "Util/uv_errno.h"
#include "Util/CMD.h"
#include "Util/MD5.h"
using namespace toolkit;

const int MAX_STACK_FRAMES = 128;
#define BroadcastOnCrashDumpArgs int &sig,const vector<vector<string> > &stack
const char kBroadcastOnCrashDump[] = "kBroadcastOnCrashDump";

//#if defined(__MACH__) || defined(__APPLE__)
//#define TEST_LINUX
//#endif

vector<string> splitWithEmptyLine(const string &s, const char *delim) {
    vector<string> ret;
    int last = 0;
    int index = s.find(delim, last);
    while (index != string::npos) {
        ret.push_back(s.substr(last, index - last));
        last = index + strlen(delim);
        index = s.find(delim, last);
    }
    if (s.size() - last > 0) {
        ret.push_back(s.substr(last));
    }
    return ret;
}

map<string, mINI> splitTopStr(const string &cmd_str) {
    map<string, mINI> ret;
    auto lines = splitWithEmptyLine(cmd_str, "\n");
    int i = 0;
    for (auto &line : lines) {
        if(i++ < 1 && line.empty()){
            continue;
        }
        if (line.empty()) {
            break;
        }
        auto line_vec = split(line, ":");

        if (line_vec.size() < 2) {
            continue;
        }
        trim(line_vec[0], " \r\n\t");
        auto args_vec = split(line_vec[1], ",");
        for (auto &arg : args_vec) {
            auto arg_vec = split(trim(arg, " \r\n\t."), " ");
            if (arg_vec.size() < 2) {
                continue;
            }
            ret[line_vec[0]].emplace(arg_vec[1], arg_vec[0]);
        }
    }
    return ret;
}

bool System::getSystemUsage(SystemUsage &usage) {
    try {
#if defined(__linux) || defined(__linux__) || defined(TEST_LINUX)
        string cmd_str;
#if !defined(TEST_LINUX)
        cmd_str = System::execute("top -b -n 1");
#else
        cmd_str = "top - 07:21:31 up  5:48,  2 users,  load average: 0.03, 0.62, 0.54\n"
                  "Tasks:  80 total,   1 running,  78 sleeping,   0 stopped,   1 zombie\n"
                  "%Cpu(s):  0.8 us,  0.4 sy,  0.0 ni, 98.8 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st\n"
                  "KiB Mem:   2058500 total,   249100 used,  1809400 free,    19816 buffers\n"
                  "KiB Swap:  1046524 total,        0 used,  1046524 free.   153012 cached Mem\n"
                  "\n";
#endif
        if (cmd_str.empty()) {
            WarnL << "System::execute(\"top -b -n 1\") return empty";
            return false;
        }
        auto topMap = splitTopStr(cmd_str);

        usage.task_total = topMap["Tasks"]["total"];
        usage.task_running = topMap["Tasks"]["running"];
        usage.task_sleeping = topMap["Tasks"]["sleeping"];
        usage.task_stopped = topMap["Tasks"]["stopped"];

        usage.cpu_user = topMap["%Cpu(s)"]["us"];
        usage.cpu_sys = topMap["%Cpu(s)"]["sy"];
        usage.cpu_idle = topMap["%Cpu(s)"]["id"];

        usage.mem_total = topMap["KiB Mem"]["total"];
        usage.mem_free = topMap["KiB Mem"]["free"];
        usage.mem_used = topMap["KiB Mem"]["used"];
        return true;

#elif defined(__MACH__) || defined(__APPLE__)
        /*
        "Processes: 275 total, 2 running, 1 stuck, 272 sleeping, 1258 threads \n"
        "2018/09/12 10:41:32\n"
        "Load Avg: 2.06, 2.88, 2.86 \n"
        "CPU usage: 14.54% user, 25.45% sys, 60.0% idle \n"
        "SharedLibs: 117M resident, 37M data, 15M linkedit.\n"
        "MemRegions: 46648 total, 3654M resident, 62M private, 714M shared.\n"
        "PhysMem: 7809M used (1906M wired), 381M unused.\n"
        "VM: 751G vsize, 614M framework vsize, 0(0) swapins, 0(0) swapouts.\n"
        "Networks: packets: 502366/248M in, 408957/87M out.\n"
        "Disks: 349435/6037M read, 78622/2577M written.";
         */

        string cmd_str = System::execute("top -l 1");
        if(cmd_str.empty()){
            WarnL << "System::execute(\"top -n 1\") return empty";
            return false;
        }
        auto topMap = splitTopStr(cmd_str);
        usage.task_total = topMap["Processes"]["total"];
        usage.task_running = topMap["Processes"]["running"];
        usage.task_sleeping = topMap["Processes"]["sleeping"];
        usage.task_stopped = topMap["Processes"]["stuck"];

        usage.cpu_user = topMap["CPU usage"]["user"];
        usage.cpu_sys = topMap["CPU usage"]["sys"];
        usage.cpu_idle = topMap["CPU usage"]["idle"];

        usage.mem_free = topMap["PhysMem"]["unused"].as<uint32_t>() * 1024 * 1024;
        usage.mem_used = topMap["PhysMem"]["used"].as<uint32_t>() * 1024 * 1024;
        usage.mem_total = usage.mem_free + usage.mem_used;
        return true;
#else
        WarnL << "System not supported";
        return false;
#endif
    } catch (std::exception &ex) {
        WarnL << ex.what();
        return false;
    }
}

bool System::getNetworkUsage(vector<NetworkUsage> &usage) {
    try {
#if defined(__linux) || defined(__linux__) || defined(TEST_LINUX)
        string cmd_str;
#if !defined(TEST_LINUX)
        cmd_str = System::execute("cat /proc/net/dev");
#else
        cmd_str =
                "Inter-|   Receive                                                |  Transmit\n"
                " face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed\n"
                "    lo:  475978    7546    0    0    0     0          0         0   475978    7546    0    0    0     0       0          0\n"
                "enp3s0: 151747818  315136    0    0    0     0          0       145 1590783447 1124616    0    0    0     0       0          0";
#endif
        if (cmd_str.empty()) {
            return false;
        }
        auto lines = split(cmd_str, "\n");
        int i = 0;
        vector<string> column_name_vec;
        vector<string> category_prefix_vec;
        for (auto &line : lines) {
            switch (i++) {
                case 0: {
                    category_prefix_vec = split(line, "|");
                }
                    break;
                case 1: {
                    auto category_suffix_vec = split(line, "|");
                    int j = 0;
                    for (auto &category_suffix : category_suffix_vec) {
                        auto column_suffix_vec = split(category_suffix, " ");
                        for (auto &column_suffix : column_suffix_vec) {
                            column_name_vec.emplace_back(trim(category_prefix_vec[j]) + "-" + trim(column_suffix));
                        }
                        j++;
                    }
                }
                    break;
                default: {
                    mINI valMap;
                    auto vals = split(line, " ");
                    int j = 0;
                    for (auto &val : vals) {
                        valMap[column_name_vec[j++]] = trim(val, " \r\n\t:");
                    }
                    usage.emplace_back(NetworkUsage());
                    auto &ifrUsage = usage.back();
                    ifrUsage.interface = valMap["Inter--face"];
                    ifrUsage.recv_bytes = valMap["Receive-bytes"];
                    ifrUsage.recv_packets = valMap["Receive-packets"];
                    ifrUsage.snd_bytes = valMap["Transmit-bytes"];
                    ifrUsage.snd_packets = valMap["Transmit-packets"];
                }
                    break;
            }
        }
        return true;
#else
        WarnL << "System not supported";
        return false;
#endif
    } catch (std::exception &ex) {
        WarnL << ex.what();
        return false;
    }
}


bool System::getTcpUsage(System::TcpUsage &usage) {
    usage.established =  atoi(trim(System::execute("netstat -na|grep ESTABLISHED|wc -l")).data());
    usage.syn_recv =  atoi(trim(System::execute("netstat -na|grep SYN_RECV|wc -l")).data());
    usage.time_wait =  atoi(trim(System::execute("netstat -na|grep TIME_WAIT|wc -l")).data());
    usage.close_wait =  atoi(trim(System::execute("netstat -na|grep CLOSE_WAIT|wc -l")).data());
    return true;
}

string System::execute(const string &cmd) {
//    DebugL << cmd;
    FILE *fPipe = popen(cmd.data(), "r");
    if(!fPipe){
        return "";
    }
    string ret;
    char buff[1024] = {0};
263
    while(fgets(buff, sizeof(buff) - 1, fPipe)){
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
        ret.append(buff);
    }
    pclose(fPipe);
    return ret;
}

static string addr2line(const string &address) {
    string cmd = StrPrinter << "addr2line -e " << exePath() << " " << address;
    return System::execute(cmd);
}

static void sig_crash(int sig) {
    signal(sig, SIG_DFL);
    void *array[MAX_STACK_FRAMES];
    int size = backtrace(array, MAX_STACK_FRAMES);
    char ** strings = backtrace_symbols(array, size);
    vector<vector<string> > stack(size);

    for (int i = 0; i < size; ++i) {
        auto &ref = stack[i];
        std::string symbol(strings[i]);
        ref.emplace_back(symbol);
#if defined(__linux) || defined(__linux__)
        size_t pos1 = symbol.find_first_of("[");
        size_t pos2 = symbol.find_last_of("]");
        std::string address = symbol.substr(pos1 + 1, pos2 - pos1 - 1);
        ref.emplace_back(addr2line(address));
#endif//__linux
    }
    free(strings);

    NoticeCenter::Instance().emitEvent(kBroadcastOnCrashDump,sig,stack);
}


void System::startDaemon() {
xiongziliang committed
300
    static pid_t pid;
301
    do{
xiongziliang committed
302
        pid = fork();
303 304 305 306 307 308
        if(pid == -1){
            WarnL << "fork失败:" << get_uv_errmsg();
            //休眠1秒再试
            sleep(1);
            continue;
        }
xiongziliang committed
309

310 311 312 313 314 315 316
        if(pid == 0){
            //子进程
            return;
        }

        //父进程,监视子进程是否退出
        DebugL << "启动子进程:"  << pid;
xiongziliang committed
317 318 319 320 321 322
        signal(SIGINT, [](int) {
            WarnL << "收到主动退出信号,关闭父进程与子进程";
            kill(pid,SIGINT);
            exit(0);
        });

323
        do{
xiongziliang committed
324 325 326 327 328 329
            int status = 0;
            if(waitpid(pid, &status, 0) >= 0) {
                WarnL << "子进程退出";
                //休眠1秒再启动子进程
                sleep(1);
                break;
330
            }
xiongziliang committed
331
            DebugL << "waitpid被中断:" << get_uv_errmsg();
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        }while (true);
    }while (true);
}



static string currentDateTime(){
    time_t ts = time(NULL);
    std::tm tm_snapshot;
    localtime_r(&ts, &tm_snapshot);

    char buffer[1024] = {0};
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm_snapshot);
    return buffer;
}

void System::systemSetup(){
    struct rlimit rlim,rlim_new;
    if (getrlimit(RLIMIT_CORE, &rlim)==0) {
        rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
        if (setrlimit(RLIMIT_CORE, &rlim_new)!=0) {
            rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
            setrlimit(RLIMIT_CORE, &rlim_new);
        }
        InfoL << "core文件大小设置为:" << rlim_new.rlim_cur;
    }

    if (getrlimit(RLIMIT_NOFILE, &rlim)==0) {
        rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
        if (setrlimit(RLIMIT_NOFILE, &rlim_new)!=0) {
            rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
            setrlimit(RLIMIT_NOFILE, &rlim_new);
        }
        InfoL << "文件最大描述符个数设置为:" << rlim_new.rlim_cur;
    }

    signal(SIGSEGV, sig_crash);
    signal(SIGABRT, sig_crash);
    NoticeCenter::Instance().addListener(nullptr,kBroadcastOnCrashDump,[](BroadcastOnCrashDumpArgs){
        stringstream ss;
        ss << "## crash date:" << currentDateTime() << endl;
        ss << "## exe:       " << exeName() << endl;
        ss << "## signal:    " << sig << endl;
        ss << "## stack:     " << endl;
        for (int i = 0; i < stack.size(); ++i) {
            ss << "[" << i << "]: ";
            for (auto &str : stack[i]){
                ss << str << endl;
            }
        }
        string stack_info = ss.str();
        ofstream out(StrPrinter << exeDir() << "/crash." << getpid(), ios::out | ios::binary | ios::trunc);
        out << stack_info;
        out.flush();

        cerr << stack_info << endl;
    });
}