From 22c20f37bbcbdcd0d252da64d7f702d85a209599 Mon Sep 17 00:00:00 2001
From: Andrey Arapov <andrey.arapov@nixaid.com>
Date: Sat, 10 Sep 2022 03:18:06 +0200
Subject: [PATCH] initdb: do not exit when PGDATA, PGDATA/pg_wal is a
 mountpoint

With the rise of containerized environments postgresql is running at,
more people are using to mount the persistent storage devices over the PGDATA
path (e.g. `/var/lib/postgresql/data`).

With that, the `lost+found` directory gets created in that path.

According to already existing warn_on_mount_point() for errno 2 & 3 - it is
expected only to warn the user when it assumes the directory being is
a mount point.

This patch eliminates initdb to exit when it finds the PGDATA is a mountpoint,
which is now often the case.
---
 src/bin/initdb/initdb.c | 26 ++++++++++++++------------
 1 file changed, 14 insertions(+), 12 deletions(-)

diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index e00837ecac..43cbb0e91f 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -2508,19 +2508,20 @@ create_data_directory(void)
 			found_existing_pgdata = true;
 			break;
 
-		case 2:
-		case 3:
-		case 4:
-			/* Present and not empty */
-			pg_log_error("directory \"%s\" exists but is not empty", pg_data);
+		case 2: /* warn if exists and contains _only_ dot files */
+		case 3: /* warn if exists and contains a mount point */
+		case 4: /* exit if exists and not empty */
 			if (ret != 4)
 				warn_on_mount_point(ret);
 			else
+			{
+				pg_log_error("directory \"%s\" exists but is not empty", pg_data);
 				pg_log_error_hint("If you want to create a new database system, either remove or empty "
 								  "the directory \"%s\" or run %s "
 								  "with an argument other than \"%s\".",
 								  pg_data, progname, pg_data);
-			exit(1);			/* no further message needed */
+				exit(1);			/* no further message needed */
+			}
 
 		default:
 			/* Trouble accessing directory */
@@ -2580,17 +2581,18 @@ create_xlog_or_symlink(void)
 				found_existing_xlogdir = true;
 				break;
 
-			case 2:
-			case 3:
-			case 4:
-				/* Present and not empty */
-				pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
+			case 2: /* warn if exists and contains _only_ dot files */
+			case 3: /* warn if exists and contains a mount point */
+			case 4: /* exit if exists and not empty */
 				if (ret != 4)
 					warn_on_mount_point(ret);
 				else
+				{
+					pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
 					pg_log_error_hint("If you want to store the WAL there, either remove or empty the directory \"%s\".",
 									  xlog_dir);
-				exit(1);
+					exit(1);
+				}
 
 			default:
 				/* Trouble accessing directory */
-- 
2.34.1

