PostgreSQL 原始碼解讀(114)- 後臺程式#2(checkpointer程式#1)
本節簡單介紹了PostgreSQL的後臺程式:checkpointer,包括相關的資料結構和CheckpointerMain函式。
一、資料結構
CheckPoint
CheckPoint XLOG record結構體.
/* * Body of CheckPoint XLOG records. This is declared here because we keep * a copy of the latest one in pg_control for possible disaster recovery. * Changing this struct requires a PG_CONTROL_VERSION bump. * CheckPoint XLOG record結構體. * 在這裡宣告是因為我們在pg_control中儲存了最新的副本, * 以便進行可能的災難恢復。 * 改變這個結構體需要一個PG_CONTROL_VERSION bump。 */ typedef struct CheckPoint { //在開始建立CheckPoint時下一個可用的RecPtr(比如REDO的開始點) XLogRecPtr redo; /* next RecPtr available when we began to * create CheckPoint (i.e. REDO start point) */ //當前的時間線 TimeLineID ThisTimeLineID; /* current TLI */ //上一個時間線(如該記錄正在開啟一條新的時間線,否則等於當前時間線) TimeLineID PrevTimeLineID; /* previous TLI, if this record begins a new * timeline (equals ThisTimeLineID otherwise) */ //是否full-page-write bool fullPageWrites; /* current full_page_writes */ //nextXid的高階位 uint32 nextXidEpoch; /* higher-order bits of nextXid */ //下一個free的XID TransactionId nextXid; /* next free XID */ //下一個free的OID Oid nextOid; /* next free OID */ //下一個fredd的MultiXactId MultiXactId nextMulti; /* next free MultiXactId */ //下一個空閒的MultiXact偏移 MultiXactOffset nextMultiOffset; /* next free MultiXact offset */ //叢集範圍內的最小datfrozenxid TransactionId oldestXid; /* cluster-wide minimum datfrozenxid */ //最小datfrozenxid所在的database Oid oldestXidDB; /* database with minimum datfrozenxid */ //叢集範圍內的最小datminmxid MultiXactId oldestMulti; /* cluster-wide minimum datminmxid */ //最小datminmxid所在的database Oid oldestMultiDB; /* database with minimum datminmxid */ //checkpoint的時間戳 pg_time_t time; /* time stamp of checkpoint */ //帶有有效提交時間戳的最老Xid TransactionId oldestCommitTsXid; /* oldest Xid with valid commit * timestamp */ //帶有有效提交時間戳的最新Xid TransactionId newestCommitTsXid; /* newest Xid with valid commit * timestamp */ /* * Oldest XID still running. This is only needed to initialize hot standby * mode from an online checkpoint, so we only bother calculating this for * online checkpoints and only when wal_level is replica. Otherwise it's * set to InvalidTransactionId. * 最老的XID還在執行。 * 這隻需要從online checkpoint初始化熱備模式,因此我們只需要為線上檢查點計算此值, * 並且只在wal_level是replica時才計算此值。 * 否則它被設定為InvalidTransactionId。 */ TransactionId oldestActiveXid; } CheckPoint; /* XLOG info values for XLOG rmgr */ #define XLOG_CHECKPOINT_SHUTDOWN 0x00 #define XLOG_CHECKPOINT_ONLINE 0x10 #define XLOG_NOOP 0x20 #define XLOG_NEXTOID 0x30 #define XLOG_SWITCH 0x40 #define XLOG_BACKUP_END 0x50 #define XLOG_PARAMETER_CHANGE 0x60 #define XLOG_RESTORE_POINT 0x70 #define XLOG_FPW_CHANGE 0x80 #define XLOG_END_OF_RECOVERY 0x90 #define XLOG_FPI_FOR_HINT 0xA0 #define XLOG_FPI 0xB0
CheckpointerShmem
checkpointer程式和其他後臺程式之間通訊的共享記憶體結構.
/*---------- * Shared memory area for communication between checkpointer and backends * checkpointer程式和其他後臺程式之間通訊的共享記憶體結構. * * The ckpt counters allow backends to watch for completion of a checkpoint * request they send. Here's how it works: * * At start of a checkpoint, checkpointer reads (and clears) the request * flags and increments ckpt_started, while holding ckpt_lck. * * On completion of a checkpoint, checkpointer sets ckpt_done to * equal ckpt_started. * * On failure of a checkpoint, checkpointer increments ckpt_failed * and sets ckpt_done to equal ckpt_started. * ckpt計數器可以讓後臺程式監控它們發出來的checkpoint請求是否已完成.其工作原理如下: * * 在checkpoint啟動階段,checkpointer程式獲取並持有ckpt_lck鎖後, * 讀取(並清除)請求標誌並增加ckpt_started計數. * * checkpoint成功完成時,checkpointer設定ckpt_done值等於ckpt_started. * * checkpoint如執行失敗,checkpointer增加ckpt_failed計數,並設定ckpt_done值等於ckpt_started. * * The algorithm for backends is: * 1. Record current values of ckpt_failed and ckpt_started, and * set request flags, while holding ckpt_lck. * 2. Send signal to request checkpoint. * 3. Sleep until ckpt_started changes. Now you know a checkpoint has * begun since you started this algorithm (although *not* that it was * specifically initiated by your signal), and that it is using your flags. * 4. Record new value of ckpt_started. * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo * arithmetic here in case counters wrap around.) Now you know a * checkpoint has started and completed, but not whether it was * successful. * 6. If ckpt_failed is different from the originally saved value, * assume request failed; otherwise it was definitely successful. * 演算法如下: * 1.獲取並持有ckpt_lck鎖後,記錄ckpt_failed和ckpt_started的當前值,並設定請求標誌. * 2.傳送訊號,請求checkpoint. * 3.休眠直至ckpt_started發生變化. * 現在您知道自您啟動此演算法以來檢查點已經開始(儘管*不是*它是由您的訊號具體發起的),並且它正在使用您的標誌。 * 4.記錄ckpt_started的新值. * 5.休眠,直至ckpt_done >= 已儲存的ckpt_started值(取模).現在已知checkpoint已啟動&已完成,但checkpoint不一定成功. * 6.如果ckpt_failed與原來儲存的值不同,則可以認為請求失敗,否則它肯定是成功的. * * ckpt_flags holds the OR of the checkpoint request flags sent by all * requesting backends since the last checkpoint start. The flags are * chosen so that OR'ing is the correct way to combine multiple requests. * ckpt_flags儲存自上次檢查點啟動以來所有後臺程式傳送的檢查點請求標誌的OR或標記。 * 選擇標誌,以便OR'ing是組合多個請求的正確方法。 * * num_backend_writes is used to count the number of buffer writes performed * by user backend processes. This counter should be wide enough that it * can't overflow during a single processing cycle. num_backend_fsync * counts the subset of those writes that also had to do their own fsync, * because the checkpointer failed to absorb their request. * num_backend_writes用於計算使用者後臺程式寫入的緩衝區個數. * 在一個單獨的處理過程中,該計數器必須足夠大以防溢位. * num_backend_fsync計數那些必須執行fsync寫操作的子集, * 因為checkpointer程式未能接受它們的請求。 * * The requests array holds fsync requests sent by backends and not yet * absorbed by the checkpointer. * 請求陣列儲存後臺程式發出的未被checkpointer程式拒絕的fsync請求. * * Unlike the checkpoint fields, num_backend_writes, num_backend_fsync, and * the requests fields are protected by CheckpointerCommLock. * 不同於checkpoint域,num_backend_writes/num_backend_fsync透過CheckpointerCommLock保護. * *---------- */ typedef struct { RelFileNode rnode;//表空間/資料庫/Relation資訊 ForkNumber forknum;//fork編號 BlockNumber segno; /* see md.c for special values */ /* might add a real request-type field later; not needed yet */ } CheckpointerRequest; typedef struct { //checkpoint程式的pid(為0則程式未啟動) pid_t checkpointer_pid; /* PID (0 if not started) */ //用於保護所有的ckpt_*域 slock_t ckpt_lck; /* protects all the ckpt_* fields */ //在checkpoint啟動時計數 int ckpt_started; /* advances when checkpoint starts */ //在checkpoint完成時計數 int ckpt_done; /* advances when checkpoint done */ //在checkpoint失敗時計數 int ckpt_failed; /* advances when checkpoint fails */ //檢查點標記,在xlog.h中定義 int ckpt_flags; /* checkpoint flags, as defined in xlog.h */ //計數後臺程式快取寫的次數 uint32 num_backend_writes; /* counts user backend buffer writes */ //計數後臺程式fsync呼叫次數 uint32 num_backend_fsync; /* counts user backend fsync calls */ //當前的請求編號 int num_requests; /* current # of requests */ //最大的請求編號 int max_requests; /* allocated array size */ //請求陣列 CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]; } CheckpointerShmemStruct; //靜態變數(CheckpointerShmemStruct結構體指標) static CheckpointerShmemStruct *CheckpointerShmem;
二、原始碼解讀
CheckpointerMain函式是checkpointer程式的入口.
該函式首先為訊號設定控制器(如熟悉Java OO開發,對這樣的寫法應不陌生),然後建立程式的記憶體上下文,接著進入迴圈(forever),在"合適"的時候執行checkpoint.
/* * Main entry point for checkpointer process * checkpointer程式的入口. * * This is invoked from AuxiliaryProcessMain, which has already created the * basic execution environment, but not enabled signals yet. * 在AuxiliaryProcessMain中呼叫,已建立了基本的執行環境,但尚未啟用訊號. */ void CheckpointerMain(void) { sigjmp_buf local_sigjmp_buf; MemoryContext checkpointer_context; CheckpointerShmem->checkpointer_pid = MyProcPid; //為訊號設定控制器(如熟悉Java OO開發,對這樣的寫法應不陌生) /* * Properly accept or ignore signals the postmaster might send us * 接收或忽略postmaster程式可能發給我們的資訊. * * Note: we deliberately ignore SIGTERM, because during a standard Unix * system shutdown cycle, init will SIGTERM all processes at once. We * want to wait for the backends to exit, whereupon the postmaster will * tell us it's okay to shut down (via SIGUSR2). * 注意:我們有意忽略SIGTERM,因為在標準的Unix系統關閉週期中, * init將同時SIGTERM所有程式。 * 我們希望等待後臺程式退出,然後postmaster會通知checkpointer程式可以關閉(透過SIGUSR2)。 */ //設定標誌,讀取配置檔案 pqsignal(SIGHUP, ChkptSigHupHandler); /* set flag to read config file */ //請求checkpoint pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */ //忽略SIGTERM pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */ //當機 pqsignal(SIGQUIT, chkpt_quickdie); /* hard crash time */ //忽略SIGALRM & SIGPIPE pqsignal(SIGALRM, SIG_IGN); pqsignal(SIGPIPE, SIG_IGN); pqsignal(SIGUSR1, chkpt_sigusr1_handler); //請求關閉 pqsignal(SIGUSR2, ReqShutdownHandler); /* request shutdown */ /* * Reset some signals that are accepted by postmaster but not here * 重置某些postmaster接收而不是在這裡的訊號 */ pqsignal(SIGCHLD, SIG_DFL); /* We allow SIGQUIT (quickdie) at all times */ //執行SIGQUIT訊號 sigdelset(&BlockSig, SIGQUIT); /* * Initialize so that first time-driven event happens at the correct time. * 初始化以便時間驅動的事件在正確的時間發生. */ last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL); /* * Create a memory context that we will do all our work in. We do this so * that we can reset the context during error recovery and thereby avoid * possible memory leaks. Formerly this code just ran in * TopMemoryContext, but resetting that would be a really bad idea. * 建立程式的記憶體上下文. * 之所以這樣做是我們可以在出現異常執行恢復期間重置上下文以確保不會出現記憶體洩漏. * */ checkpointer_context = AllocSetContextCreate(TopMemoryContext, "Checkpointer", ALLOCSET_DEFAULT_SIZES); MemoryContextSwitchTo(checkpointer_context); /* * If an exception is encountered, processing resumes here. * 如出現異常,在這裡處理恢復. * * See notes in postgres.c about the design of this coding. * 這部分的設計可參照postgres.c中的註釋 */ if (sigsetjmp(local_sigjmp_buf, 1) != 0) { /* Since not using PG_TRY, must reset error stack by hand */ //沒有使用PG_TRY,必須重置錯誤棧 error_context_stack = NULL; /* Prevent interrupts while cleaning up */ //在清除期間必須避免中斷 HOLD_INTERRUPTS(); /* Report the error to the server log */ //在日誌中報告錯誤資訊 EmitErrorReport(); /* * These operations are really just a minimal subset of * AbortTransaction(). We don't have very many resources to worry * about in checkpointer, but we do have LWLocks, buffers, and temp * files. * 這些操作實際上只是AbortTransaction()的最小集合. * 我們不需要耗費太多的資源在checkpointer程式上,但需要持有LWLocks/快取和臨時檔案 */ LWLockReleaseAll(); ConditionVariableCancelSleep(); pgstat_report_wait_end(); AbortBufferIO(); UnlockBuffers(); ReleaseAuxProcessResources(false); AtEOXact_Buffers(false); AtEOXact_SMgr(); AtEOXact_Files(false); AtEOXact_HashTables(false); /* Warn any waiting backends that the checkpoint failed. */ //通知正在等待的後臺程式:checkpoint執行失敗 if (ckpt_active) { SpinLockAcquire(&CheckpointerShmem->ckpt_lck); CheckpointerShmem->ckpt_failed++; CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started; SpinLockRelease(&CheckpointerShmem->ckpt_lck); ckpt_active = false; } /* * Now return to normal top-level context and clear ErrorContext for * next time. * 回到常規的頂層上下文,為下一次checkpoint清空ErrorContext */ MemoryContextSwitchTo(checkpointer_context); FlushErrorState(); /* Flush any leaked data in the top-level context */ //在頂層上下文重新整理洩漏的資料 MemoryContextResetAndDeleteChildren(checkpointer_context); /* Now we can allow interrupts again */ //現在我們可以允許中斷了 RESUME_INTERRUPTS(); /* * Sleep at least 1 second after any error. A write error is likely * to be repeated, and we don't want to be filling the error logs as * fast as we can. * 出現錯誤後,至少休眠1s. * 寫入錯誤可能會重複出現,但我們不希望頻繁出現錯誤日誌,因此需要休眠1s. */ pg_usleep(1000000L); /* * Close all open files after any error. This is helpful on Windows, * where holding deleted files open causes various strange errors. * It's not clear we need it elsewhere, but shouldn't hurt. * 出現錯誤後,關閉所有開啟的檔案控制程式碼. * 尤其在Windows平臺,仍持有已刪除的檔案控制程式碼會導致莫名其妙的錯誤. * 目前還不清楚我們是否需要在其他地方使用它,但這不會導致其他額外的問題。 */ smgrcloseall(); } /* We can now handle ereport(ERROR) */ //現在可以處理ereport(ERROR)呼叫了. PG_exception_stack = &local_sigjmp_buf; /* * Unblock signals (they were blocked when the postmaster forked us) * 解鎖訊號(在postmaster fork程式的時候,會阻塞訊號) */ PG_SETMASK(&UnBlockSig); /* * Ensure all shared memory values are set correctly for the config. Doing * this here ensures no race conditions from other concurrent updaters. * 確保所有的共享記憶體變數已正確配置. * 在這裡執行這樣的檢查確保不存在來自其他併發更新程式的競爭條件. */ UpdateSharedMemoryConfig(); /* * Advertise our latch that backends can use to wake us up while we're * sleeping. * 廣播本程式的latch,在程式休眠時其他程式可以使用此latch喚醒. */ ProcGlobal->checkpointerLatch = &MyProc->procLatch; /* * Loop forever * 迴圈,迴圈,迴圈... */ for (;;) { bool do_checkpoint = false;//是否執行checkpoint int flags = 0;//標記 pg_time_t now;//時間 int elapsed_secs;//已消逝的時間 int cur_timeout;//timeout時間 /* Clear any already-pending wakeups */ ResetLatch(MyLatch); /* * Process any requests or signals received recently. * 處理最近接收到的請求或訊號 */ AbsorbFsyncRequests(); if (got_SIGHUP)// { got_SIGHUP = false; ProcessConfigFile(PGC_SIGHUP); /* * Checkpointer is the last process to shut down, so we ask it to * hold the keys for a range of other tasks required most of which * have nothing to do with checkpointing at all. * Checkpointer是最後一個關閉的程式,因此我們要求它儲存一些一系列其他任務需要的鍵值, * 雖然其中大部分任務與檢查點完全無關. * * For various reasons, some config values can change dynamically * so the primary copy of them is held in shared memory to make * sure all backends see the same value. We make Checkpointer * responsible for updating the shared memory copy if the * parameter setting changes because of SIGHUP. * 由於各種原因,某些配置項可以動態修改, * 因此這些配置項的複製在共享記憶體中儲存以確保所有的後臺程式看到的值是一樣的. * 如果引數設定是因為SIGHUP引起的,那麼我們讓Checkpointer程式負責更新共享記憶體中的配置項複製. */ UpdateSharedMemoryConfig(); } if (checkpoint_requested) { //接收到checkpoint請求 checkpoint_requested = false;//重置標誌 do_checkpoint = true;//需要執行checkpoint BgWriterStats.m_requested_checkpoints++;//計數 } if (shutdown_requested) { //接收到關閉請求 /* * From here on, elog(ERROR) should end with exit(1), not send * control back to the sigsetjmp block above * 從這裡開始,日誌(錯誤)應該以exit(1)結束,而不是將控制傳送回上面的sigsetjmp塊 */ ExitOnAnyError = true; /* Close down the database */ //關閉資料庫 ShutdownXLOG(0, 0); /* Normal exit from the checkpointer is here */ //checkpointer在這裡正常退出 proc_exit(0); /* done */ } /* * Force a checkpoint if too much time has elapsed since the last one. * Note that we count a timed checkpoint in stats only when this * occurs without an external request, but we set the CAUSE_TIME flag * bit even if there is also an external request. * 在上次checkpoint後,已超時,則執行checkpoint. * 注意,只有在沒有外部請求的情況下,我們才會在統計資料中計算定時檢查點, * 但計算出現;了外部請求,我們也會設定CAUSE_TIME標誌位. */ now = (pg_time_t) time(NULL);//當前時間 elapsed_secs = now - last_checkpoint_time;//已消逝的時間 if (elapsed_secs >= CheckPointTimeout) { //超時 if (!do_checkpoint) BgWriterStats.m_timed_checkpoints++;//沒有接收到checkpoint請求,進行統計 do_checkpoint = true;//設定標記 flags |= CHECKPOINT_CAUSE_TIME;//設定標記 } /* * Do a checkpoint if requested. * 執行checkpoint */ if (do_checkpoint) { bool ckpt_performed = false;//設定標記 bool do_restartpoint; /* * Check if we should perform a checkpoint or a restartpoint. As a * side-effect, RecoveryInProgress() initializes TimeLineID if * it's not set yet. * 檢查我們是否需要執行checkpoint或restartpoint. * 可能的其他影響是,如仍未設定TimeLineID,那麼RecoveryInProgress()會初始化TimeLineID */ do_restartpoint = RecoveryInProgress(); /* * Atomically fetch the request flags to figure out what kind of a * checkpoint we should perform, and increase the started-counter * to acknowledge that we've started a new checkpoint. * 自動提取請求標誌,以決定那種checkpoint需要執行,同時增加開始計數已確認我們已啟動了新的checkpoint. */ SpinLockAcquire(&CheckpointerShmem->ckpt_lck); flags |= CheckpointerShmem->ckpt_flags; CheckpointerShmem->ckpt_flags = 0; CheckpointerShmem->ckpt_started++; SpinLockRelease(&CheckpointerShmem->ckpt_lck); /* * The end-of-recovery checkpoint is a real checkpoint that's * performed while we're still in recovery. * end-of-recovery checkpoint是在資料庫恢復過程中執行的checkpoint. */ if (flags & CHECKPOINT_END_OF_RECOVERY) do_restartpoint = false; /* * We will warn if (a) too soon since last checkpoint (whatever * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag * since the last checkpoint start. Note in particular that this * implementation will not generate warnings caused by * CheckPointTimeout < CheckPointWarning. * 如果checkpoint發生的太頻繁(不管是什麼原因) * 或者在上次checkpoint啟動後某個程式設定了CHECKPOINT_CAUSE_XLOG標誌, * 我們都會發出警告. * 請特別注意,此實現不會生成由CheckPointTimeout < CheckPointWarning引起的警告。 */ if (!do_restartpoint && (flags & CHECKPOINT_CAUSE_XLOG) && elapsed_secs < CheckPointWarning) ereport(LOG, (errmsg_plural("checkpoints are occurring too frequently (%d second apart)", "checkpoints are occurring too frequently (%d seconds apart)", elapsed_secs, elapsed_secs), errhint("Consider increasing the configuration parameter \"max_wal_size\"."))); /* * Initialize checkpointer-private variables used during * checkpoint. * 初始化checkpointer程式在checkpoint過程中需使用的私有變數 */ ckpt_active = true; if (do_restartpoint) //執行restartpoint ckpt_start_recptr = GetXLogReplayRecPtr(NULL);//獲取Redo pint else //執行checkpoint ckpt_start_recptr = GetInsertRecPtr();//獲取checkpoint XLOG Record插入的位置 ckpt_start_time = now;//開始時間 ckpt_cached_elapsed = 0;//消逝時間 /* * Do the checkpoint. * 執行checkpoint. */ if (!do_restartpoint) { //執行checkpoint CreateCheckPoint(flags);//建立checkpoint ckpt_performed = true;//DONE! } else //恢復過程的restartpoint ckpt_performed = CreateRestartPoint(flags); /* * After any checkpoint, close all smgr files. This is so we * won't hang onto smgr references to deleted files indefinitely. * 執行checkpoint完成後,關閉所有的smgr檔案. * 這樣我們就不需要無限期的持有已刪除檔案的smgr引用. */ smgrcloseall(); /* * Indicate checkpoint completion to any waiting backends. * 通知等待的程式,checkpoint完成. */ SpinLockAcquire(&CheckpointerShmem->ckpt_lck); CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started; SpinLockRelease(&CheckpointerShmem->ckpt_lck); if (ckpt_performed) { //已完成checkpoint /* * Note we record the checkpoint start time not end time as * last_checkpoint_time. This is so that time-driven * checkpoints happen at a predictable spacing. * 注意我們記錄了checkpoint的開始時間而不是結束時間作為last_checkpoint_time. * 這樣,時間驅動的檢查點就會以可預測的間隔出現。 */ last_checkpoint_time = now; } else { // /* * We were not able to perform the restartpoint (checkpoints * throw an ERROR in case of error). Most likely because we * have not received any new checkpoint WAL records since the * last restartpoint. Try again in 15 s. * 沒有成功執行restartpoint(如果是checkpoint出現問題會直接報錯,不會進入到這裡). * 最有可能的原因是因為在上次restartpoint後沒有接收到新的checkpoint WAL記錄. * 15s後嘗試. */ last_checkpoint_time = now - CheckPointTimeout + 15; } ckpt_active = false; } /* Check for archive_timeout and switch xlog files if necessary. */ //在需要的時候,檢查archive_timeout並切換xlog檔案. CheckArchiveTimeout(); /* * Send off activity statistics to the stats collector. (The reason * why we re-use bgwriter-related code for this is that the bgwriter * and checkpointer used to be just one process. It's probably not * worth the trouble to split the stats support into two independent * stats message types.) * 傳送活動統計到統計收集器. */ pgstat_send_bgwriter(); /* * Sleep until we are signaled or it's time for another checkpoint or * xlog file switch. * 休眠,直至接收到訊號或者需要啟動新的checkpoint或xlog檔案切換. */ //重置相關變數 now = (pg_time_t) time(NULL); elapsed_secs = now - last_checkpoint_time; if (elapsed_secs >= CheckPointTimeout) continue; /* no sleep for us ... */ cur_timeout = CheckPointTimeout - elapsed_secs; if (XLogArchiveTimeout > 0 && !RecoveryInProgress()) { elapsed_secs = now - last_xlog_switch_time; if (elapsed_secs >= XLogArchiveTimeout) continue; /* no sleep for us ... */ cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);//獲得最小休眠時間 } (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, cur_timeout * 1000L /* convert to ms */ , WAIT_EVENT_CHECKPOINTER_MAIN);//休眠 } } /* * Unix-like signal handler installation * Unix風格的訊號處理器 * Only called on main thread, no sync required * 只需要在主執行緒執行,不需要sync同步. */ pqsigfunc pqsignal(int signum, pqsigfunc handler) { pqsigfunc prevfunc;//函式 if (signum >= PG_SIGNAL_COUNT || signum < 0) return SIG_ERR;//驗證不透過,返回錯誤 prevfunc = pg_signal_array[signum];//獲取先前的處理函式 pg_signal_array[signum] = handler;//註冊函式 return prevfunc;//返回先前註冊的函式 } /* * GetInsertRecPtr -- Returns the current insert position. * 返回當前插入位置 * * NOTE: The value *actually* returned is the position of the last full * xlog page. It lags behind the real insert position by at most 1 page. * For that, we don't need to scan through WAL insertion locks, and an * approximation is enough for the current usage of this function. * 注意:返回的值*實際上*是最後一個完整xlog頁面的位置. * 它比實際插入位置最多落後1頁。 * 為此,我們不需要遍歷WAL插入鎖,滿足該函式的當前使用目的,近似值已足夠。 */ XLogRecPtr GetInsertRecPtr(void) { XLogRecPtr recptr; SpinLockAcquire(&XLogCtl->info_lck); recptr = XLogCtl->LogwrtRqst.Write;//獲取插入位置 SpinLockRelease(&XLogCtl->info_lck); return recptr; }
三、跟蹤分析
建立資料表,插入資料,執行checkpoint
testdb=# drop table t_wal_ckpt; DROP TABLE testdb=# create table t_wal_ckpt(c1 int not null,c2 varchar(40),c3 varchar(40)); CREATE TABLE testdb=# insert into t_wal_ckpt(c1,c2,c3) values(1,'C2-1','C3-1'); INSERT 0 1 testdb=# testdb=# checkpoint; --> 第一次checkpoint
更新資料,執行checkpoint.
testdb=# update t_wal_ckpt set c2 = 'C2#'||substr(c2,4,40); UPDATE 1 testdb=# checkpoint;
啟動gdb,設定訊號控制
(gdb) handle SIGINT print nostop pass SIGINT is used by the debugger. Are you sure you want to change it? (y or n) y Signal Stop Print Pass to program Description SIGINT No Yes Yes Interrupt (gdb) (gdb) b checkpointer.c:441 Breakpoint 1 at 0x815197: file checkpointer.c, line 441. (gdb) c Continuing. Program received signal SIGINT, Interrupt. Breakpoint 1, CheckpointerMain () at checkpointer.c:441 441 flags |= CheckpointerShmem->ckpt_flags; (gdb)
檢視共享記憶體資訊CheckpointerShmem
(gdb) p *CheckpointerShmem $1 = {checkpointer_pid = 1650, ckpt_lck = 1 '\001', ckpt_started = 2, ckpt_done = 2, ckpt_failed = 0, ckpt_flags = 44, num_backend_writes = 0, num_backend_fsync = 0, num_requests = 0, max_requests = 65536, requests = 0x7f2cdda07b28} (gdb)
設定相關資訊CheckpointerShmem
441 flags |= CheckpointerShmem->ckpt_flags; (gdb) n 442 CheckpointerShmem->ckpt_flags = 0; (gdb) 443 CheckpointerShmem->ckpt_started++; (gdb) 444 SpinLockRelease(&CheckpointerShmem->ckpt_lck); (gdb) 450 if (flags & CHECKPOINT_END_OF_RECOVERY) (gdb) 460 if (!do_restartpoint && (gdb) 461 (flags & CHECKPOINT_CAUSE_XLOG) && (gdb) 460 if (!do_restartpoint &&
初始化checkpointer程式在checkpoint過程中需使用的私有變數.
其中ckpt_start_recptr為插入點,即Redo point,5521180544轉換為16進製為0x1 49168780
(gdb) 474 ckpt_active = true; (gdb) 475 if (do_restartpoint) (gdb) 478 ckpt_start_recptr = GetInsertRecPtr(); (gdb) p XLogCtl->LogwrtRqst $1 = {Write = 5521180544, Flush = 5521180544} (gdb) n 479 ckpt_start_time = now; (gdb) p ckpt_start_recptr $2 = 5521180544 (gdb) n 480 ckpt_cached_elapsed = 0; (gdb) 485 if (!do_restartpoint) (gdb)
執行checkpoint.OK!
(gdb) 487 CreateCheckPoint(flags); (gdb) 488 ckpt_performed = true; (gdb)
關閉資源,並設定共享記憶體中的資訊
497 smgrcloseall(); (gdb) 502 SpinLockAcquire(&CheckpointerShmem->ckpt_lck); (gdb) 503 CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started; (gdb) 504 SpinLockRelease(&CheckpointerShmem->ckpt_lck); (gdb) 506 if (ckpt_performed) (gdb) p CheckpointerShmem $3 = (CheckpointerShmemStruct *) 0x7fcecc063b00 (gdb) p *CheckpointerShmem $4 = {checkpointer_pid = 1697, ckpt_lck = 0 '\000', ckpt_started = 1, ckpt_done = 1, ckpt_failed = 0, ckpt_flags = 0, num_backend_writes = 0, num_backend_fsync = 0, num_requests = 0, max_requests = 65536, requests = 0x7fcecc063b28} (gdb)
checkpoint請求已清空
(gdb) p CheckpointerShmem->requests[0] $5 = {rnode = {spcNode = 0, dbNode = 0, relNode = 0}, forknum = MAIN_FORKNUM, segno = 0}
在需要的時候,檢查archive_timeout並切換xlog檔案.
休眠,直至接收到訊號或者需要啟動新的checkpoint或xlog檔案切換.
(gdb) n 513 last_checkpoint_time = now; (gdb) 526 ckpt_active = false; (gdb) 530 CheckArchiveTimeout(); (gdb) 539 pgstat_send_bgwriter(); (gdb) 545 now = (pg_time_t) time(NULL); (gdb) 546 elapsed_secs = now - last_checkpoint_time; (gdb) 547 if (elapsed_secs >= CheckPointTimeout) (gdb) p elapsed_secs $7 = 1044 (gdb) p CheckPointTimeout $8 = 900 (gdb) n 548 continue; /* no sleep for us ... */
已超時,執行新的checkpoint
(gdb) 569 } (gdb) 352 bool do_checkpoint = false; (gdb) 353 int flags = 0; (gdb) n 360 ResetLatch(MyLatch); (gdb) 365 AbsorbFsyncRequests(); (gdb) 367 if (got_SIGHUP) (gdb) 385 if (checkpoint_requested) (gdb) 391 if (shutdown_requested) (gdb) 410 now = (pg_time_t) time(NULL); (gdb) 411 elapsed_secs = now - last_checkpoint_time; (gdb) 412 if (elapsed_secs >= CheckPointTimeout) (gdb) p elapsed_secs $9 = 1131 (gdb) n 414 if (!do_checkpoint) (gdb) 415 BgWriterStats.m_timed_checkpoints++; (gdb) 416 do_checkpoint = true; (gdb) 417 flags |= CHECKPOINT_CAUSE_TIME; (gdb) 423 if (do_checkpoint) (gdb) 425 bool ckpt_performed = false; (gdb) 433 do_restartpoint = RecoveryInProgress(); (gdb) 440 SpinLockAcquire(&CheckpointerShmem->ckpt_lck); (gdb) Breakpoint 1, CheckpointerMain () at checkpointer.c:441 441 flags |= CheckpointerShmem->ckpt_flags; (gdb) 442 CheckpointerShmem->ckpt_flags = 0; (gdb) 443 CheckpointerShmem->ckpt_started++; (gdb) c Continuing.
DONE!
CreateCheckPoint函式下一節介紹
四、參考資料
checkpointer.c
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/6906/viewspace-2374762/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- PostgreSQL 原始碼解讀(115)- 後臺程式#3(checkpointer程式#2)SQL原始碼
- PostgreSQL 原始碼解讀(213)- 後臺程式#12(checkpointer-CheckpointWriteDelay)SQL原始碼
- PostgreSQL 原始碼解讀(214)- 後臺程式#13(checkpointer-IsCheckpointOnSchedule)SQL原始碼
- PostgreSQL 原始碼解讀(211)- 後臺程式#10(checkpointer-BufferSync)SQL原始碼
- PostgreSQL 原始碼解讀(212)- 後臺程式#11(checkpointer-SyncOneBuffer)SQL原始碼
- PostgreSQL 原始碼解讀(124)- 後臺程式#4(autovacuum程式#1)SQL原始碼
- PostgreSQL 原始碼解讀(236)- 後臺程式#14(autovacuum程式#2)SQL原始碼
- PostgreSQL 原始碼解讀(153)- 後臺程式#5(walsender#1)SQL原始碼
- PostgreSQL 原始碼解讀(154)- 後臺程式#6(walsender#2)SQL原始碼
- PostgreSQL 原始碼解讀(108)- 後臺程式#1(PGPROC資料結構)SQL原始碼資料結構
- PostgreSQL 原始碼解讀(156)- 後臺程式#8(walsender#4)SQL原始碼
- PostgreSQL 原始碼解讀(155)- 後臺程式#7(walsender#3)SQL原始碼
- PostgreSQL 原始碼解讀(237)- 後臺程式#15(rebuild_database_list)SQL原始碼RebuildDatabase
- PostgreSQL 原始碼解讀(157)- 後臺程式#9(同步複製主庫掛起分析)SQL原始碼
- PostgreSQL 原始碼解讀(1)- 插入資料#1SQL原始碼
- PostgreSQL 原始碼解讀(2)- 插入資料#2(RelationPutHeapTuple)SQL原始碼APT
- PostgreSQL 原始碼解讀(199)- 查詢#114(排序#7 - inittapes&dumptuples)SQL原始碼排序
- PostgreSQL 原始碼解讀(227)- Linux Kernel(程式虛擬記憶體#2)SQL原始碼Linux記憶體
- PostgreSQL 原始碼解讀(3)- 如何閱讀原始碼SQL原始碼
- PostgreSQL 原始碼解讀(117)- MVCC#2(獲取快照#2)SQL原始碼MVCC#
- PostgreSQL 原始碼解讀(116)- MVCC#1(獲取快照#1)SQL原始碼MVCC#
- PostgreSQL 原始碼解讀(92)- 分割槽表#1(資料插入路由#1)SQL原始碼路由
- PostgreSQL 原始碼解讀(145)- Storage Manager#1(RecordAndGetPageWithFreeSpace)SQL原始碼
- PostgreSQL 原始碼解讀(241)- plpgsql(CreateFunction)SQL原始碼Function
- PostgreSQL 原始碼解讀(94)- 分割槽表#2(資料插入路由#2)SQL原始碼路由
- PostgreSQL 原始碼解讀(247)- HTAB動態擴充套件圖解#1SQL原始碼套件圖解
- PostgreSQL 原始碼解讀(248)- HTAB動態擴充套件圖解#2SQL原始碼套件圖解
- PostgreSQL 原始碼解讀(136)- Buffer Manager#1(ReadBufferExtended函式)SQL原始碼函式
- PostgreSQL 原始碼解讀(240)- HTAB簡介SQL原始碼
- PostgreSQL 原始碼解讀(219)- Locks(Overview)SQL原始碼View
- PostgreSQL FSM(Free Space Map) 原始碼解讀SQL原始碼
- PostgreSQL 原始碼解讀(150)- PG Tools#2(BaseBackup函式)SQL原始碼函式
- PostgreSQL 原始碼解讀(229)- Linux Kernel(程式虛擬記憶體#3)SQL原始碼Linux記憶體
- preact原始碼解讀(1)React原始碼
- PostgreSQL 原始碼解讀(192)- 查詢#108(排序#1 - ExecInitSort)SQL原始碼排序
- PostgreSQL 原始碼解讀(90)- 查詢語句#75(ExecHashJoin函式#1)SQL原始碼函式
- PostgreSQL 原始碼解讀(50)- 查詢語句#35(Optimizer Review#1)SQL原始碼View
- PostgreSQL 原始碼解讀(239)- Locks(OOM & max_locks_per_transaction#2)SQL原始碼OOM