Postgresql - 源码 - logger process

代码位置:

src/backend/postmaster/syslogger.c

system logger是从PG 8开始的。通过重定向到管道来捕获来自Postmaster, backends, 和其他的子进程的所有stderr,并写入日志文件。可以再postgresql.conf 中配置日志文件的 size 和 age限制。如果达到了限制,关闭当前日志文件,并创建新的日志文件。日志文件存储在子目录子目录中,可以配置命名方案。

/* syslogger process 主入口 */

NON_EXEC_STATIC void

SysLoggerMain(int argc, char *argv[])

{

#ifndef WIN32

    char        logbuffer[READ_BUF_SIZE];

    int         bytes_in_logbuffer = 0;

#endif

    char     *currentLogDir;

    char     *currentLogFilename;

    int         currentLogRotationAge;

    pg_time_t   now;

    now = MyStartTime;

#ifdef EXEC_BACKEND

    syslogger_parseArgs(argc, argv);

#endif                          /* EXEC_BACKEND */

    am_syslogger = true;

    init_ps_display("logger", "", "", "");

    /* 如果重新启动,我们的STDRR已经被重定向到我们自己的输入管道中。这当然是无用的,更不用说它干扰检测管EOF。把stderr只想到 /dev/null 。假设 syslogger 中生成的所有的消息将通过 elog.c 发送到 write_syslogger_file 。 */

    if (redirection_done)

    {

        int         fd = open(DEVNULL, O_WRONLY, 0);

        /* 关闭可能看起来是多余,但实际上并不是:我们要确保管道即使打开失败也会关闭。我们可以在 stderr 指向任何地方运行,但我们不能负担额外的管道输入描述符。由于我们只是试图将这些重置为DEVNULL,所以在这里从close/dup2 调用中检查失败没有多大意义,如果它们失败,那么可能文件描述符被关闭,并且任何写入都将进入 bitbucket 。 */

        close(fileno(stdout));

        close(fileno(stderr));

        if (fd != -1)

        {

            (void) dup2(fd, fileno(stdout));

            (void) dup2(fd, fileno(stderr));

            close(fd);

        }

    }

    /* Syslogger 自己的stderr 不可能是syslogPipe,所以如果我们不关闭它,就将其设置为文本模式。SubPostmasterMain中设置为二进制 */

#ifdef WIN32

    else

        _setmode(_fileno(stderr), _O_TEXT);

#endif

    /* 也关闭我们的管道的书写端。这就需要我们能够正确地检测管道EOF。(但注意,在重新启动的情况下,postmaster 已经这样做了。) */

#ifndef WIN32

    if (syslogPipe[1] >= 0)

        close(syslogPipe[1]);

    syslogPipe[1] = -1;

#else

    if (syslogPipe[1])

        CloseHandle(syslogPipe[1]);

    syslogPipe[1] = 0;

#endif

    /* 正确接受或忽略 postmaster 可能发送给我们的信号 */

    pqsignal(SIGHUP, sigHupHandler);    /* set flag to read config file */

    pqsignal(SIGINT, SIG_IGN);

    pqsignal(SIGTERM, SIG_IGN);

    pqsignal(SIGQUIT, SIG_IGN);

    pqsignal(SIGALRM, SIG_IGN);

    pqsignal(SIGPIPE, SIG_IGN);

    pqsignal(SIGUSR1, sigUsr1Handler);  /* request log rotation */

    pqsignal(SIGUSR2, SIG_IGN);

    /* 重置一些由 postmaster 接受但不在这里接受的信号 */

    pqsignal(SIGCHLD, SIG_DFL);

    pqsignal(SIGTTIN, SIG_DFL);

    pqsignal(SIGTTOU, SIG_DFL);

    pqsignal(SIGCONT, SIG_DFL);

    pqsignal(SIGWINCH, SIG_DFL);

    PG_SETMASK(&UnBlockSig);

#ifdef WIN32

    /* 启动单独的数据传输线程 */

    InitializeCriticalSection(&sysloggerSection);

    EnterCriticalSection(&sysloggerSection);

    threadHandle = (HANDLE) _beginthreadex(NULL, 0, pipeThread, NULL, 0, NULL);

    if (threadHandle == 0)

        elog(FATAL, "could not create syslogger data transfer thread: %m");

#endif                          /* WIN32 */

    /* 记住active logfile的名称。我们从饮用时间重新计算,因为值传递了pg_time_t 比在EXEC_BACKEND情况下传递整个文件路径要便宜的多。 */

    last_file_name = logfile_getname(first_syslogger_file_time, NULL);

    /* 记住活动日志文件参数 */

    currentLogDir = pstrdup(Log_directory);

    currentLogFilename = pstrdup(Log_filename);

    currentLogRotationAge = Log_RotationAge;

    /* 设置下一个计划的旋转时间 */

    set_next_rotation_time();

    update_metainfo_datafile();

    /* 主worker循环 */

    for (;;)

    {

        bool        time_based_rotation = false;

        int         size_rotation_for = 0;

        long        cur_timeout;

        int         cur_flags;

#ifndef WIN32

        int         rc;

#endif

        /* 清除任何已挂起的唤醒 */

        ResetLatch(MyLatch);

        /* 处理最近收到的任何请求或信号。 */

        if (got_SIGHUP)

        {

            got_SIGHUP = false;

            ProcessConfigFile(PGC_SIGHUP);

            /* 检查postgresql.conf中的日志目录或文件名模式是否更改。如果是,强制旋转以确保将日志文件写入正确的位置。 */

            if (strcmp(Log_directory, currentLogDir) != 0)

            {

                pfree(currentLogDir);

                currentLogDir = pstrdup(Log_directory);

                rotation_requested = true;

                /* 此外,如果不存在,则创建新目录;忽略错误 */

                (void) MakePGDirectory(Log_directory);

            }

            if (strcmp(Log_filename, currentLogFilename) != 0)

            {

                pfree(currentLogFilename);

                currentLogFilename = pstrdup(Log_filename);

                rotation_requested = true;

            }

            /* 如果循环时间参数改变,则重置下一个循环时间,但不要立即强制旋转。 */

            if (currentLogRotationAge != Log_RotationAge)

            {

                currentLogRotationAge = Log_RotationAge;

                set_next_rotation_time();

            }

            /* 如果我们循环禁用失败,在SIGHUP 之后 重新启用循环尝试。 */

            if (rotation_disabled)

            {

                rotation_disabled = false;

                rotation_requested = true;

            }

            /* 重新加载配置时,重写最后一个日志文件名。即使 rotation_requested 是 false 的,log_destination 可能已经改变,我们不希望等待下一个文件转换。 */

            update_metainfo_datafile();

        }

        if (Log_RotationAge > 0 && !rotation_disabled)

        {

            /* 如果到时间,执行日志文件转换 */

            now = (pg_time_t) time(NULL);

            if (now >= next_rotation_time)

                rotation_requested = time_based_rotation = true;

        }

        if (!rotation_requested && Log_RotationSize > 0 && !rotation_disabled)

        {

            /* 如果日志文件太大,转换文件 */

            if (ftell(syslogFile) >= Log_RotationSize * 1024L)

            {

                rotation_requested = true;

                size_rotation_for |= LOG_DESTINATION_STDERR;

            }

            if (csvlogFile != NULL &&

                ftell(csvlogFile) >= Log_RotationSize * 1024L)

            {

                rotation_requested = true;

                size_rotation_for |= LOG_DESTINATION_CSVLOG;

            }

        }

        if (rotation_requested)

        {

            /* 当值都是0的时候强制转换文件。意味着请求是由pg_rotate_logfile 发送的。 */

            if (!time_based_rotation && size_rotation_for == 0)

                size_rotation_for = LOG_DESTINATION_STDERR | LOG_DESTINATION_CSVLOG;

            logfile_rotate(time_based_rotation, size_rotation_for);

        }

        /* 计算下一次转换的时间,这样我们就不会sleep的更久。我们假设上面得到的“now”值仍然足够接近。注意,在调用 logfile_rotate() 之后,我们不能进行这个计算,因为它将推进next_rotation_time. 还要注意,在计算超时时时需要注意溢出:对于Log_RotationAge 的设置,next_rotation_time 将来可能超过INT_MAX 毫秒。在这种情况下,我们将不再等待INT_MAX 毫秒,然后再试一次。 */

        if (Log_RotationAge > 0 && !rotation_disabled)

        {

            pg_time_t   delay;

            delay = next_rotation_time - now;

            if (delay > 0)

            {

                if (delay > INT_MAX / 1000)

                    delay = INT_MAX / 1000;

                cur_timeout = delay * 1000L;    /* msec */

            }

            else

                cur_timeout = 0;

            cur_flags = WL_TIMEOUT;

        }

        else

        {

            cur_timeout = -1L;

            cur_flags = 0;

        }

        /* sleep直到有一些事需要去做 */

#ifndef WIN32

        rc = WaitLatchOrSocket(MyLatch,

                             WL_LATCH_SET | WL_SOCKET_READABLE | cur_flags,

                             syslogPipe[0],

                             cur_timeout,

                             WAIT_EVENT_SYSLOGGER_MAIN);

        if (rc & WL_SOCKET_READABLE)

        {

            int         bytesRead;

            bytesRead = read(syslogPipe[0],

                             logbuffer + bytes_in_logbuffer,

                             sizeof(logbuffer) - bytes_in_logbuffer);

            if (bytesRead < 0)

            {

                if (errno != EINTR)

                    ereport(LOG,

                            (errcode_for_socket_access(),

                             errmsg("could not read from logger pipe: %m")));

            }

            else if (bytesRead > 0)

            {

                bytes_in_logbuffer += bytesRead;

                process_pipe_input(logbuffer, &bytes_in_logbuffer);

                continue;

            }

            else

            {

                /* 当select()表示read-ready意味着管道上的EOF时,读取的字节为零:也就是说,不再存在管道写端打开的进程。因此,postmaster 和所有的后端进程都关闭了,结束了。 */

                pipe_eof_seen = true;

                /* 如果有任何数据剩下,现在就强迫它输出 */

                flush_pipe_input(logbuffer, &bytes_in_logbuffer);

            }

        }

#else                           /* WIN32 */

        /* 在Windows上,我们把它留给一个单独的线程来传输数据和检测管道EOF。主线程刚刚醒来,以处理SIGHUP 和转换条件。服务器代码通常不是线程安全的,所以我们确保每次只有一个线程是活动的,只要我们不sleep,就进入关键部分。 */

        LeaveCriticalSection(&sysloggerSection);

        (void) WaitLatch(MyLatch,

                         WL_LATCH_SET | cur_flags,

                         cur_timeout,

                         WAIT_EVENT_SYSLOGGER_MAIN);

        EnterCriticalSection(&sysloggerSection);

#endif                          /* WIN32 */

        if (pipe_eof_seen)

        {

            ereport(DEBUG1,

                    (errmsg("logger shutting down")));

            /* 从系统日志中正常退出。注意,我们故意不在退出之前关闭 syslogFile ;这是为了允许在 proc_exit 中生成elog消息。规则exit() 将负责 flushing 和关闭STDIO通道。 */

            proc_exit(0);

        }

    }

}

猜你喜欢

转载自blog.csdn.net/chuckchen1222/article/details/83111136