]> granicus.if.org Git - postgresql/commitdiff
PANIC on fsync() failure.
authorThomas Munro <tmunro@postgresql.org>
Mon, 19 Nov 2018 00:40:57 +0000 (13:40 +1300)
committerThomas Munro <tmunro@postgresql.org>
Mon, 19 Nov 2018 00:54:00 +0000 (13:54 +1300)
On some operating systems, it doesn't make sense to retry fsync(),
because dirty data cached by the kernel may have been dropped on
write-back failure.  In that case the only remaining copy of the
data is in the WAL.  A subsequent fsync() could appear to succeed,
but not have flushed the data.  That means that a future checkpoint
could apparently complete successfully but have lost data.

Therefore, violently prevent any future checkpoint attempts by
panicking on the first fsync() failure.  Note that we already
did the same for WAL data; this change extends that behavior to
non-temporary data files.

Provide a GUC data_sync_retry to control this new behavior, for
users of operating systems that don't eject dirty data, and possibly
forensic/testing uses.  If it is set to on and the write-back error
was transient, a later checkpoint might genuinely succeed (on a
system that does not throw away buffers on failure); if the error is
permanent, later checkpoints will continue to fail.  The GUC defaults
to off, meaning that we panic.

Back-patch to all supported releases.

There is still a narrow window for error-loss on some operating
systems: if the file is closed and later reopened and a write-back
error occurs in the intervening time, but the inode has the bad
luck to be evicted due to memory pressure before we reopen, we could
miss the error.  A later patch will address that with a scheme
for keeping files with dirty data open at all times, but we judge
that to be too complicated to back-patch.

Author: Craig Ringer, with some adjustments by Thomas Munro
Reported-by: Craig Ringer
Reviewed-by: Robert Haas, Thomas Munro, Andres Freund
Discussion: https://postgr.es/m/20180427222842.in2e4mibx45zdth5%40alap3.anarazel.de

12 files changed:
doc/src/sgml/config.sgml
src/backend/access/heap/rewriteheap.c
src/backend/access/transam/slru.c
src/backend/access/transam/timeline.c
src/backend/access/transam/xlog.c
src/backend/replication/logical/snapbuild.c
src/backend/storage/file/fd.c
src/backend/storage/smgr/md.c
src/backend/utils/cache/relmapper.c
src/backend/utils/misc/guc.c
src/backend/utils/misc/postgresql.conf.sample
src/include/storage/fd.h

index 54dfa14963bc918eea70c84dc060e51d07f5e775..d4ef8869f152a0427c9db9f9cf15a0fc3e8811f0 100644 (file)
@@ -7512,6 +7512,38 @@ dynamic_library_path = 'C:\tools\postgresql;H:\my_project\lib;$libdir'
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-data-sync-retry" xreflabel="data_sync_retry">
+      <term><varname>data_sync_retry</varname> (<type>boolean</type>)
+      <indexterm>
+       <primary><varname>data_sync_retry</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        When set to false, which is the default, <productname>PostgreSQL</productname>
+        will raise a PANIC-level error on failure to flush modified data files
+        to the filesystem.  This causes the database server to crash.
+       </para>
+       <para>
+        On some operating systems, the status of data in the kernel's page
+        cache is unknown after a write-back failure.  In some cases it might
+        have been entirely forgotten, making it unsafe to retry; the second
+        attempt may be reported as successful, when in fact the data has been
+        lost.  In these circumstances, the only way to avoid data loss is to
+        recover from the WAL after any failure is reported, preferably
+        after investigating the root cause of the failure and replacing any
+        faulty hardware.
+       </para>
+       <para>
+        If set to true, <productname>PostgreSQL</productname> will instead
+        report an error but continue to run so that the data flushing
+        operation can be retried in a later checkpoint.  Only set it to true
+        after investigating the operating system's treatment of buffered data
+        in case of write-back failure.
+       </para>
+      </listitem>
+     </varlistentry>
+
     </variablelist>
 
    </sect1>
index e700824d12d66ddd56bafada001c03f743260112..93ab5249b644641be212d6f96eb88293b6f15dd0 100644 (file)
@@ -974,7 +974,7 @@ logical_end_heap_rewrite(RewriteState state)
        while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
        {
                if (FileSync(src->vfd) != 0)
-                       ereport(ERROR,
+                       ereport(data_sync_elevel(ERROR),
                                        (errcode_for_file_access(),
                                         errmsg("could not fsync file \"%s\": %m", src->path)));
                FileClose(src->vfd);
@@ -1192,7 +1192,7 @@ heap_xlog_logical_rewrite(XLogReaderState *r)
         * doesn't seem worth the trouble.
         */
        if (pg_fsync(fd) != 0)
-               ereport(ERROR,
+               ereport(data_sync_elevel(ERROR),
                                (errcode_for_file_access(),
                                 errmsg("could not fsync file \"%s\": %m", path)));
 
@@ -1289,7 +1289,7 @@ CheckPointLogicalRewriteHeap(void)
                         * but it's currently not deemed worth the effort.
                         */
                        else if (pg_fsync(fd) != 0)
-                               ereport(ERROR,
+                               ereport(data_sync_elevel(ERROR),
                                                (errcode_for_file_access(),
                                                 errmsg("could not fsync file \"%s\": %m", path)));
                        CloseTransientFile(fd);
index 9789d470780080e297f8c1b7e6d926a385d1002b..e708967e2f3a46d1f8703167937c56f773f9d7b0 100644 (file)
@@ -921,7 +921,7 @@ SlruReportIOError(SlruCtl ctl, int pageno, TransactionId xid)
                                                  path, offset)));
                        break;
                case SLRU_FSYNC_FAILED:
-                       ereport(ERROR,
+                       ereport(data_sync_elevel(ERROR),
                                        (errcode_for_file_access(),
                                         errmsg("could not access status of transaction %u", xid),
                                         errdetail("Could not fsync file \"%s\": %m.",
index bd91573708b224e84e36b2aff85f200a95986d92..5d73cc942cdb0827e805e69cb628bf62631184ad 100644 (file)
@@ -402,7 +402,7 @@ writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
        }
 
        if (pg_fsync(fd) != 0)
-               ereport(ERROR,
+               ereport(data_sync_elevel(ERROR),
                                (errcode_for_file_access(),
                                 errmsg("could not fsync file \"%s\": %m", tmppath)));
 
@@ -478,7 +478,7 @@ writeTimeLineHistoryFile(TimeLineID tli, char *content, int size)
        }
 
        if (pg_fsync(fd) != 0)
-               ereport(ERROR,
+               ereport(data_sync_elevel(ERROR),
                                (errcode_for_file_access(),
                                 errmsg("could not fsync file \"%s\": %m", tmppath)));
 
index d7505aa454bb7d1c1c587157b2254b1ded5687d2..004700febebf27ebd1fd3e8f2a6b48e09b6b84f9 100644 (file)
@@ -3283,7 +3283,7 @@ XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno,
        }
 
        if (pg_fsync(fd) != 0)
-               ereport(ERROR,
+               ereport(data_sync_elevel(ERROR),
                                (errcode_for_file_access(),
                                 errmsg("could not fsync file \"%s\": %m", tmppath)));
 
index d8d8f03cdf9ca6cec2912541b2ee6c102f586f5e..69ab728ed674bee4594b8112fb681c696cea119d 100644 (file)
@@ -1606,6 +1606,9 @@ SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn)
         * fsync the file before renaming so that even if we crash after this we
         * have either a fully valid file or nothing.
         *
+        * It's safe to just ERROR on fsync() here because we'll retry the whole
+        * operation including the writes.
+        *
         * TODO: Do the fsync() via checkpoints/restartpoints, doing it here has
         * some noticeable overhead since it's performed synchronously during
         * decoding?
index 9354652d914b729070869e5d9e1ef8a4ef0f997e..96c884a06343ddb5c9da630b4fc6eba46dfddbe1 100644 (file)
@@ -138,6 +138,8 @@ int                 max_files_per_process = 1000;
  */
 int                    max_safe_fds = 32;      /* default if not changed */
 
+/* Whether it is safe to continue running after fsync() fails. */
+bool           data_sync_retry = false;
 
 /* Debugging.... */
 
@@ -433,11 +435,9 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
                 */
                rc = sync_file_range(fd, offset, nbytes,
                                                         SYNC_FILE_RANGE_WRITE);
-
-               /* don't error out, this is just a performance optimization */
                if (rc != 0)
                {
-                       ereport(WARNING,
+                       ereport(data_sync_elevel(WARNING),
                                        (errcode_for_file_access(),
                                         errmsg("could not flush dirty data: %m")));
                }
@@ -509,7 +509,7 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
                        rc = msync(p, (size_t) nbytes, MS_ASYNC);
                        if (rc != 0)
                        {
-                               ereport(WARNING,
+                               ereport(data_sync_elevel(WARNING),
                                                (errcode_for_file_access(),
                                                 errmsg("could not flush dirty data: %m")));
                                /* NB: need to fall through to munmap()! */
@@ -565,7 +565,7 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
 void
 fsync_fname(const char *fname, bool isdir)
 {
-       fsync_fname_ext(fname, isdir, false, ERROR);
+       fsync_fname_ext(fname, isdir, false, data_sync_elevel(ERROR));
 }
 
 /*
@@ -994,7 +994,8 @@ LruDelete(File file)
         * to leak the FD than to mess up our internal state.
         */
        if (close(vfdP->fd))
-               elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
+               elog(vfdP->fdstate & FD_TEMPORARY ? LOG : data_sync_elevel(LOG),
+                        "could not close file \"%s\": %m", vfdP->fileName);
        vfdP->fd = VFD_CLOSED;
        --nfile;
 
@@ -1473,7 +1474,14 @@ FileClose(File file)
        {
                /* close the file */
                if (close(vfdP->fd))
-                       elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
+               {
+                       /*
+                        * We may need to panic on failure to close non-temporary files;
+                        * see LruDelete.
+                        */
+                       elog(vfdP->fdstate & FD_TEMPORARY ? LOG : data_sync_elevel(LOG),
+                               "could not close file \"%s\": %m", vfdP->fileName);
+               }
 
                --nfile;
                vfdP->fd = VFD_CLOSED;
@@ -2898,6 +2906,9 @@ looks_like_temp_rel_name(const char *name)
  * harmless cases such as read-only files in the data directory, and that's
  * not good either.
  *
+ * Note that if we previously crashed due to a PANIC on fsync(), we'll be
+ * rewriting all changes again during recovery.
+ *
  * Note we assume we're chdir'd into PGDATA to begin with.
  */
 void
@@ -3184,3 +3195,26 @@ fsync_parent_path(const char *fname, int elevel)
 
        return 0;
 }
+
+/*
+ * Return the passed-in error level, or PANIC if data_sync_retry is off.
+ *
+ * Failure to fsync any data file is cause for immediate panic, unless
+ * data_sync_retry is enabled.  Data may have been written to the operating
+ * system and removed from our buffer pool already, and if we are running on
+ * an operating system that forgets dirty data on write-back failure, there
+ * may be only one copy of the data remaining: in the WAL.  A later attempt to
+ * fsync again might falsely report success.  Therefore we must not allow any
+ * further checkpoints to be attempted.  data_sync_retry can in theory be
+ * enabled on systems known not to drop dirty buffered data on write-back
+ * failure (with the likely outcome that checkpoints will continue to fail
+ * until the underlying problem is fixed).
+ *
+ * Any code that reports a failure from fsync() or related functions should
+ * filter the error level with this function.
+ */
+int
+data_sync_elevel(int elevel)
+{
+       return data_sync_retry ? elevel : PANIC;
+}
index 91a290c357f1934689d8a93fff329de766218df0..b34a2e552a0a68d0cb571e8f2087e3f0f2032cdf 100644 (file)
@@ -1037,7 +1037,7 @@ mdimmedsync(SMgrRelation reln, ForkNumber forknum)
        while (v != NULL)
        {
                if (FileSync(v->mdfd_vfd) < 0)
-                       ereport(ERROR,
+                       ereport(data_sync_elevel(ERROR),
                                        (errcode_for_file_access(),
                                         errmsg("could not fsync file \"%s\": %m",
                                                        FilePathName(v->mdfd_vfd))));
@@ -1282,7 +1282,7 @@ mdsync(void)
                                                        bms_join(new_requests, requests);
 
                                                errno = save_errno;
-                                               ereport(ERROR,
+                                               ereport(data_sync_elevel(ERROR),
                                                                (errcode_for_file_access(),
                                                                 errmsg("could not fsync file \"%s\": %m",
                                                                                path)));
@@ -1456,7 +1456,7 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
                                (errmsg("could not forward fsync request because request queue is full")));
 
                if (FileSync(seg->mdfd_vfd) < 0)
-                       ereport(ERROR,
+                       ereport(data_sync_elevel(ERROR),
                                        (errcode_for_file_access(),
                                         errmsg("could not fsync file \"%s\": %m",
                                                        FilePathName(seg->mdfd_vfd))));
index 6a63b5e1d740e9a148dec0696b0bdcad0af1eba6..6010594f6e6396bef83380157f12e40bd8c8c32d 100644 (file)
@@ -792,7 +792,7 @@ write_relmap_file(bool shared, RelMapFile *newmap,
         * CheckPointRelationMap.
         */
        if (pg_fsync(fd) != 0)
-               ereport(ERROR,
+               ereport(data_sync_elevel(ERROR),
                                (errcode_for_file_access(),
                                 errmsg("could not fsync relation mapping file \"%s\": %m",
                                                mapfilename)));
index 5c27397ccc8057943c010d258c45ee58bffc9b05..ec83d1dd456299f680825141e663986eccdb5338 100644 (file)
@@ -1658,6 +1658,15 @@ static struct config_bool ConfigureNamesBool[] =
                NULL, NULL, NULL
        },
 
+       {
+               {"data_sync_retry", PGC_POSTMASTER, ERROR_HANDLING_OPTIONS,
+                       gettext_noop("Whether to continue running after a failure to sync data files."),
+               },
+               &data_sync_retry,
+               false,
+               NULL, NULL, NULL
+       },
+
        /* End-of-list marker */
        {
                {NULL, 0, 0, NULL, NULL}, NULL, false, NULL, NULL, NULL
index b6b683ec28050c021edc543ccdce101dd0145d65..756dfb396a7a806fa31966de12195a38060fb074 100644 (file)
 
 #exit_on_error = off                   # terminate session on any error?
 #restart_after_crash = on              # reinitialize after backend crash?
+#data_sync_retry = off                 # retry or panic on failure to fsync data?
 
 
 #------------------------------------------------------------------------------
index b6b5c7ab4b2bcf3cf7c493d0696ee9e8eef5a187..ee063f7cc481495cd37194955a772b175628f52f 100644 (file)
@@ -53,6 +53,7 @@ typedef int File;
 
 /* GUC parameter */
 extern PGDLLIMPORT int max_files_per_process;
+extern PGDLLIMPORT bool data_sync_retry;
 
 /*
  * This is private to fd.c, but exported for save/restore_backend_variables()
@@ -123,6 +124,7 @@ extern void fsync_fname(const char *fname, bool isdir);
 extern int     durable_rename(const char *oldfile, const char *newfile, int loglevel);
 extern int     durable_link_or_rename(const char *oldfile, const char *newfile, int loglevel);
 extern void SyncDataDirectory(void);
+extern int data_sync_elevel(int elevel);
 
 /* Filename components for OpenTemporaryFile */
 #define PG_TEMP_FILES_DIR "pgsql_tmp"