• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

postgresql源码学习36—— 事务日志11 - 日志归档

武飞扬头像
Hehuyi_In
帮助1

一、 日志归档参数

pg主要归档参数如下:

  • archive_mode:归档模式开关参数
  • archive_command:配置归档命令
  • archive_timeout:如果长时间没有归档,则在日志切换后强制归档

1. archive_mode参数

archive_mode参数有3种模式:

  • off:关闭归档
  • on:开启归档,但不允许在recovery模式下进行归档
  • always:开启归档,且允许在recovery模式下进行归档

以下代码在postmaster.c

  1.  
    /*
  2.  
    * Archiver is allowed to start up at the current postmaster state?
  3.  
    *
  4.  
    * If WAL archiving is enabled always, we are allowed to start archiver
  5.  
    * even during recovery.
  6.  
    */
  7.  
    #define PgArchStartupAllowed() \
  8.  
    (((XLogArchivingActive() && pmState == PM_RUN) || \
  9.  
    (XLogArchivingAlways() && \
  10.  
    (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) && \
  11.  
    PgArchCanRestart())

        除了开启归档外,还需要保证wal_level不能是MINIMAL状态(因为该状态下有些操作不会记录日志)。在db启动时,会同时检查archive_mode和wal_level。以下代码也在postmaster.c(PostmasterMain函数)。

  1.  
    if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL)
  2.  
    ereport(ERROR,
  3.  
    (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));

2. archive_command参数

      pg会启动一个辅助进程,作用是实时监控事务日志,发现能归档的日志则会通过用户设置的archive_command参数中的命令进行归档。归档命令可以很自由地被指定,一般是cp或者加上压缩命令,如果设置该参数,或者命令有错误,则无法真正归档。

  • %p:源文件路径
  • %f:源文件名

以下代码在pgarch.c(pgarch_ArchiverCopyLoop函数)

  1.  
    /* can't do anything if no command ... */
  2.  
    if (!XLogArchiveCommandSet())
  3.  
    {
  4.  
    ereport(WARNING,
  5.  
    (errmsg("archive_mode enabled, yet archive_command is not set")));
  6.  
    return;
  7.  
    }

3. archive_timeout参数

       如果只在日志切换时归档,假如在日志段未满时宕机,则归档日志会缺失一部分,可能造成数据丢失。另外,如果业务写请求较少,日志可能长期不归档。此时,可以通过archive_timeout参数设置超时强制归档,提高归档频率。

       注意,每次日志切换时,即使未写满日志大小依然是16M,因此该参数如果设置太小,可能导致归档过于频繁并且大量浪费空间。

  1.  
    -- 手动切WAL日志
  2.  
    SELECT pg_switch_wal();

       代码在checkpointer.c文件(CheckArchiveTimeout函数),有一丢丢长,我们放在下面看。

二、 日志归档主要步骤

每当WAL日志段切换时,就可以通知日志归档进程将该日志进行归档。

  • 产生日志切换的进程在pg_wal/archive_status下生成与待归档日志同名的.ready文件
  • 发送信号通知归档进程(旧版本是先发给Postmaster进程,再通知归档进程),归档进程只关心是否有.ready文件存在,不关心其内容
  • 归档进程按照archive_command进行日志归档
  • 归档完成后将.ready文件重命名为.done文件

三、 相关函数

1. XLogWrite

日志写入函数(一个老熟人),当一个日志段写满时,需要切换。

  1.  
    static void
  2.  
    XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
  3.  
    {
  4.  
  5.  
    /* 一个段已满 */
  6.  
    if (finishing_seg)
  7.  
    {
  8.  
    /* 将该段刷入磁盘,保证归档日志数据完整性 */
  9.  
    issue_xlog_fsync(openLogFile, openLogSegNo);
  10.  
     
  11.  
    /* 通知WalSender进程发送日志给从库 */
  12.  
    WalSndWakeupRequest();
  13.  
     
  14.  
    LogwrtResult.Flush = LogwrtResult.Write; /* end of page */
  15.  
     
  16.  
    /* 发送日志归档的通知信息 */
  17.  
    if (XLogArchivingActive())
  18.  
    XLogArchiveNotifySeg(openLogSegNo);
  19.  
  20.  
    }
  21.  
    }
学新通

2. XLogArchiveNotify函数

创建归档通知的.ready文件(相当于一种进程间的通信机制),告诉归档进程应该归档哪个日志。

  1.  
    /*
  2.  
    * Create an archive notification file
  3.  
    *
  4.  
    * The name of the notification file is the message that will be picked up
  5.  
    * by the archiver, e.g. we write 0000000100000001000000C6.ready
  6.  
    * and the archiver then knows to archive XLOGDIR/0000000100000001000000C6,
  7.  
    * then when complete, rename it to 0000000100000001000000C6.done
  8.  
    */
  9.  
    void
  10.  
    XLogArchiveNotify(const char *xlog)
  11.  
    {
  12.  
    char archiveStatusPath[MAXPGPATH];
  13.  
    FILE *fd;
  14.  
     
  15.  
    /* insert an otherwise empty file called <XLOG>.ready */
  16.  
    StatusFilePath(archiveStatusPath, xlog, ".ready");
  17.  
    fd = AllocateFile(archiveStatusPath, "w");
  18.  
    if (fd == NULL)
  19.  
    {
  20.  
    ereport(LOG,
  21.  
    (errcode_for_file_access(),
  22.  
    errmsg("could not create archive status file \"%s\": %m",
  23.  
    archiveStatusPath)));
  24.  
    return;
  25.  
    }
  26.  
    if (FreeFile(fd))
  27.  
    {
  28.  
    ereport(LOG,
  29.  
    (errcode_for_file_access(),
  30.  
    errmsg("could not write archive status file \"%s\": %m",
  31.  
    archiveStatusPath)));
  32.  
    return;
  33.  
    }
  34.  
     
  35.  
    /* Notify archiver that it's got something to do,发送信号给日志归档进程(旧版本是先发给Postmaster进程) */
  36.  
    if (IsUnderPostmaster)
  37.  
    PgArchWakeup();
  38.  
    }
学新通

3. PgArchWakeup函数

发送信号通知归档进程

  1.  
    /*
  2.  
    * Wake up the archiver
  3.  
    */
  4.  
    void
  5.  
    PgArchWakeup(void)
  6.  
    {
  7.  
    int arch_pgprocno = PgArch->pgprocno;
  8.  
     
  9.  
    /*
  10.  
    * We don't acquire ProcArrayLock here. It's actually fine because
  11.  
    * procLatch isn't ever freed, so we just can potentially set the wrong
  12.  
    * process' (or no process') latch. Even in that case the archiver will
  13.  
    * be relaunched shortly and will start archiving.
  14.  
    */
  15.  
    if (arch_pgprocno != INVALID_PGPROCNO)
  16.  
    SetLatch(&ProcGlobal->allProcs[arch_pgprocno].procLatch);
  17.  
    }
学新通

4. pgarch_ArchiverCopyLoop函数

       实际上日志归档的顺序也很重要,归档进程会优先选择段号较小的日志文件。因为日志清理时也是按段号顺序清理的,段号小的日志优先归档完就可以被清理了。

       归档完成后,归档进程会将.ready文件改为.done文件。

  1.  
    /*
  2.  
    * pgarch_ArchiverCopyLoop
  3.  
    *
  4.  
    * Archives all outstanding xlogs then returns
  5.  
    */
  6.  
    static void
  7.  
    pgarch_ArchiverCopyLoop(void)
  8.  
    {
  9.  
    char xlog[MAX_XFN_CHARS 1];
  10.  
     
  11.  
    /*
  12.  
    * 循环处理.ready文件
  13.  
    */
  14.  
    while (pgarch_readyXlog(xlog))
  15.  
    {
  16.  
    int failures = 0;
  17.  
    int failures_orphan = 0;
  18.  
     
  19.  
    for (;;)
  20.  
    {
  21.  
    struct stat stat_buf;
  22.  
    char pathname[MAXPGPATH];
  23.  
     
  24.  
    /*
  25.  
    * 如果收到停库请求或者postmaster异常挂掉,不再执行后续操作,直接返回
  26.  
    */
  27.  
    if (ShutdownRequestPending || !PostmasterIsAlive())
  28.  
    return;
  29.  
     
  30.  
    /*
  31.  
    * Check for barrier events and config update. This is so that
  32.  
    * we'll adopt a new setting for archive_command as soon as
  33.  
    * possible, even if there is a backlog of files to be archived.
  34.  
    */
  35.  
    HandlePgArchInterrupts();
  36.  
     
  37.  
    /* 如果没有设置archive_command或者设置有问题,报错返回 */
  38.  
    if (!XLogArchiveCommandSet())
  39.  
    {
  40.  
    ereport(WARNING,
  41.  
    (errmsg("archive_mode enabled, yet archive_command is not set")));
  42.  
    return;
  43.  
    }
  44.  
     
  45.  
    /* 一段异常宕机导致出现孤儿.ready文件时的处理,略 */
  46.  
  47.  
     
  48.  
    /* 进行日志归档 */
  49.  
    if (pgarch_archiveXlog(xlog))
  50.  
    {
  51.  
    /* successful,归档成功,将.ready改为.done文件 */
  52.  
    pgarch_archiveDone(xlog);
  53.  
     
  54.  
    /*
  55.  
    * Tell the collector about the WAL file that we successfully archived
  56.  
    */
  57.  
    pgstat_send_archiver(xlog, false);
  58.  
     
  59.  
    /* 开始处理下一个日志 */
  60.  
    break; /* out of inner retry loop */
  61.  
    }
  62.  
    /* 归档失败 */
  63.  
    else
  64.  
    {
  65.  
    /*
  66.  
    * Tell the collector about the WAL file that we failed to
  67.  
    * archive
  68.  
    */
  69.  
    pgstat_send_archiver(xlog, true);
  70.  
    /* 如果失败次数大于重试次数,报错返回 */
  71.  
    if ( failures >= NUM_ARCHIVE_RETRIES)
  72.  
    {
  73.  
    ereport(WARNING,
  74.  
    (errmsg("archiving write-ahead log file \"%s\" failed too many times, will try again later",
  75.  
    xlog)));
  76.  
    return; /* give up archiving for now */
  77.  
    }
  78.  
    pg_usleep(1000000L); /* wait a bit before retrying,休眠1秒,重试 */
  79.  
    }
  80.  
    }
  81.  
    }
  82.  
    }
学新通

四、 归档超时检查与切换

  1.  
    /*
  2.  
    * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
  3.  
    */
  4.  
    static void
  5.  
    CheckArchiveTimeout(void)
  6.  
    {
  7.  
    pg_time_t now;
  8.  
    pg_time_t last_time;
  9.  
    XLogRecPtr last_switch_lsn;
  10.  
     
  11.  
    /* 未设置超时参数或者在恢复阶段,直接返回 */
  12.  
    if (XLogArchiveTimeout <= 0 || RecoveryInProgress())
  13.  
    return;
  14.  
     
  15.  
    now = (pg_time_t) time(NULL);
  16.  
     
  17.  
    /* First we do a quick check using possibly-stale local state.
  18.  
    首先快速检查,看当前时间减去本地保存的last_xlog_switch_time是否超时,没有则返回
  19.  
    */
  20.  
    if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
  21.  
    return;
  22.  
     
  23.  
    /*
  24.  
    * Update local state ... note that last_xlog_switch_time is the last time a switch was performed *or requested*.
  25.  
    从共享内存中获得上次日志切换的时间,这是真正的日志切换时间。同时获取上次日志切换的LSN
  26.  
    */
  27.  
    last_time = GetLastSegSwitchData(&last_switch_lsn);
  28.  
     
  29.  
    /* 取两者较新的时间,更新本地保存值 */
  30.  
    last_xlog_switch_time = Max(last_xlog_switch_time, last_time);
  31.  
     
  32.  
    /* Now we can do the real checks,真正的检查,如果超时,执行后面的检查 */
  33.  
    if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
  34.  
    {
  35.  
    /*
  36.  
    * Switch segment only when "important" WAL has been logged since the
  37.  
    * last segment switch (last_switch_lsn points to end of segment
  38.  
    * switch occurred in).
  39.  
    如果日志的“重要”LSN >上次切换的LSN,则说明自上次切换以来有重要的WAL日志写入,执行强制切换日志段
  40.  
    */
  41.  
    if (GetLastImportantRecPtr() > last_switch_lsn)
  42.  
    {
  43.  
    XLogRecPtr switchpoint;
  44.  
     
  45.  
    /* mark switch as unimportant, avoids triggering checkpoints,切换日志段 */
  46.  
    switchpoint = RequestXLogSwitch(true);
  47.  
     
  48.  
    /*
  49.  
    * If the returned pointer points exactly to a segment boundary,
  50.  
    * assume nothing happened. 如果返回的指针正好在段边界,当做无事发生。否则记录一条DEBUG1级别的切换信息
  51.  
    */
  52.  
    if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
  53.  
    elog(DEBUG1, "write-ahead log switch forced (archive_timeout=%d)",
  54.  
    XLogArchiveTimeout);
  55.  
    }
  56.  
     
  57.  
    /*
  58.  
    * Update state in any case, so we don't retry constantly when the
  59.  
    * system is idle. 更新切换时间
  60.  
    */
  61.  
    last_xlog_switch_time = now;
  62.  
    }
  63.  
    }
学新通

参考

PostgreSQL技术内幕:事务处理深度探索》第4

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhbebh
系列文章
更多 icon
同类精品
更多 icon
继续加载