From 8ebc32b4372a8c3dbc3af6ceb0ad3082e02844a2 Mon Sep 17 00:00:00 2001
From: Ivan Trubach <mr.trubach@icloud.com>
Date: Mon, 26 Aug 2024 18:21:18 +0300
Subject: [PATCH] Support systemd readiness notifications on reload

Adds support for Type=notify-reload in systemd service that requires
sd_notify with MONOTONIC_USEC. See also
https://www.freedesktop.org/software/systemd/man/latest/sd_notify.html
---
 src/backend/postmaster/postmaster.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index a6fff93db3..2eaf7758e1 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -101,6 +101,7 @@
 #include "pg_getopt.h"
 #include "pgstat.h"
 #include "port/pg_bswap.h"
+#include "portability/instr_time.h"
 #include "postmaster/autovacuum.h"
 #include "postmaster/auxprocess.h"
 #include "postmaster/bgworker_internals.h"
@@ -1956,6 +1957,10 @@ handle_pm_reload_request_signal(SIGNAL_ARGS)
 static void
 process_pm_reload_request(void)
 {
+#ifdef USE_SYSTEMD
+	instr_time	cur_time;
+#endif
+
 	pending_pm_reload_request = false;
 
 	ereport(DEBUG2,
@@ -1963,6 +1968,13 @@ process_pm_reload_request(void)
 
 	if (Shutdown <= SmartShutdown)
 	{
+#ifdef USE_SYSTEMD
+		/* Set MONOTONIC_USEC for Type=notify-reload. */
+		INSTR_TIME_SET_CURRENT(cur_time);
+		sd_notifyf(0, "RELOADING=1\nMONOTONIC_USEC=" UINT64_FORMAT,
+				   INSTR_TIME_GET_MICROSEC(cur_time));
+#endif
+
 		ereport(LOG,
 				(errmsg("received SIGHUP, reloading configuration files")));
 		ProcessConfigFile(PGC_SIGHUP);
@@ -2019,6 +2031,10 @@ process_pm_reload_request(void)
 		/* Update the starting-point file for future children */
 		write_nondefault_variables(PGC_SIGHUP);
 #endif
+
+#ifdef USE_SYSTEMD
+		sd_notify(0, "READY=1");
+#endif
 	}
 }
 
-- 
2.44.1

