LCOV - code coverage report
Current view: top level - src/backend/storage/file - reinit.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 103 112 92.0 %
Date: 2021-09-17 15:07:27 Functions: 4 4 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * reinit.c
       4             :  *    Reinitialization of unlogged relations
       5             :  *
       6             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  * IDENTIFICATION
      10             :  *    src/backend/storage/file/reinit.c
      11             :  *
      12             :  *-------------------------------------------------------------------------
      13             :  */
      14             : 
      15             : #include "postgres.h"
      16             : 
      17             : #include <unistd.h>
      18             : 
      19             : #include "common/relpath.h"
      20             : #include "storage/copydir.h"
      21             : #include "storage/fd.h"
      22             : #include "storage/reinit.h"
      23             : #include "utils/hsearch.h"
      24             : #include "utils/memutils.h"
      25             : 
      26             : static void ResetUnloggedRelationsInTablespaceDir(const char *tsdirname,
      27             :                                                   int op);
      28             : static void ResetUnloggedRelationsInDbspaceDir(const char *dbspacedirname,
      29             :                                                int op);
      30             : 
      31             : typedef struct
      32             : {
      33             :     Oid         reloid;         /* hash key */
      34             : } unlogged_relation_entry;
      35             : 
      36             : /*
      37             :  * Reset unlogged relations from before the last restart.
      38             :  *
      39             :  * If op includes UNLOGGED_RELATION_CLEANUP, we remove all forks of any
      40             :  * relation with an "init" fork, except for the "init" fork itself.
      41             :  *
      42             :  * If op includes UNLOGGED_RELATION_INIT, we copy the "init" fork to the main
      43             :  * fork.
      44             :  */
      45             : void
      46         466 : ResetUnloggedRelations(int op)
      47             : {
      48             :     char        temp_path[MAXPGPATH + 10 + sizeof(TABLESPACE_VERSION_DIRECTORY)];
      49             :     DIR        *spc_dir;
      50             :     struct dirent *spc_de;
      51             :     MemoryContext tmpctx,
      52             :                 oldctx;
      53             : 
      54             :     /* Log it. */
      55         466 :     elog(DEBUG1, "resetting unlogged relations: cleanup %d init %d",
      56             :          (op & UNLOGGED_RELATION_CLEANUP) != 0,
      57             :          (op & UNLOGGED_RELATION_INIT) != 0);
      58             : 
      59             :     /*
      60             :      * Just to be sure we don't leak any memory, let's create a temporary
      61             :      * memory context for this operation.
      62             :      */
      63         466 :     tmpctx = AllocSetContextCreate(CurrentMemoryContext,
      64             :                                    "ResetUnloggedRelations",
      65             :                                    ALLOCSET_DEFAULT_SIZES);
      66         466 :     oldctx = MemoryContextSwitchTo(tmpctx);
      67             : 
      68             :     /*
      69             :      * First process unlogged files in pg_default ($PGDATA/base)
      70             :      */
      71         466 :     ResetUnloggedRelationsInTablespaceDir("base", op);
      72             : 
      73             :     /*
      74             :      * Cycle through directories for all non-default tablespaces.
      75             :      */
      76         466 :     spc_dir = AllocateDir("pg_tblspc");
      77             : 
      78        1542 :     while ((spc_de = ReadDir(spc_dir, "pg_tblspc")) != NULL)
      79             :     {
      80        1076 :         if (strcmp(spc_de->d_name, ".") == 0 ||
      81         610 :             strcmp(spc_de->d_name, "..") == 0)
      82         932 :             continue;
      83             : 
      84         144 :         snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
      85         144 :                  spc_de->d_name, TABLESPACE_VERSION_DIRECTORY);
      86         144 :         ResetUnloggedRelationsInTablespaceDir(temp_path, op);
      87             :     }
      88             : 
      89         466 :     FreeDir(spc_dir);
      90             : 
      91             :     /*
      92             :      * Restore memory context.
      93             :      */
      94         466 :     MemoryContextSwitchTo(oldctx);
      95         466 :     MemoryContextDelete(tmpctx);
      96         466 : }
      97             : 
      98             : /*
      99             :  * Process one tablespace directory for ResetUnloggedRelations
     100             :  */
     101             : static void
     102         610 : ResetUnloggedRelationsInTablespaceDir(const char *tsdirname, int op)
     103             : {
     104             :     DIR        *ts_dir;
     105             :     struct dirent *de;
     106             :     char        dbspace_path[MAXPGPATH * 2];
     107             : 
     108         610 :     ts_dir = AllocateDir(tsdirname);
     109             : 
     110             :     /*
     111             :      * If we get ENOENT on a tablespace directory, log it and return.  This
     112             :      * can happen if a previous DROP TABLESPACE crashed between removing the
     113             :      * tablespace directory and removing the symlink in pg_tblspc.  We don't
     114             :      * really want to prevent database startup in that scenario, so let it
     115             :      * pass instead.  Any other type of error will be reported by ReadDir
     116             :      * (causing a startup failure).
     117             :      */
     118         610 :     if (ts_dir == NULL && errno == ENOENT)
     119             :     {
     120           0 :         ereport(LOG,
     121             :                 (errcode_for_file_access(),
     122             :                  errmsg("could not open directory \"%s\": %m",
     123             :                         tsdirname)));
     124           0 :         return;
     125             :     }
     126             : 
     127        3496 :     while ((de = ReadDir(ts_dir, tsdirname)) != NULL)
     128             :     {
     129             :         /*
     130             :          * We're only interested in the per-database directories, which have
     131             :          * numeric names.  Note that this code will also (properly) ignore "."
     132             :          * and "..".
     133             :          */
     134        2886 :         if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
     135        1306 :             continue;
     136             : 
     137        1580 :         snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
     138        1580 :                  tsdirname, de->d_name);
     139        1580 :         ResetUnloggedRelationsInDbspaceDir(dbspace_path, op);
     140             :     }
     141             : 
     142         610 :     FreeDir(ts_dir);
     143             : }
     144             : 
     145             : /*
     146             :  * Process one per-dbspace directory for ResetUnloggedRelations
     147             :  */
     148             : static void
     149        1580 : ResetUnloggedRelationsInDbspaceDir(const char *dbspacedirname, int op)
     150             : {
     151             :     DIR        *dbspace_dir;
     152             :     struct dirent *de;
     153             :     char        rm_path[MAXPGPATH * 2];
     154             : 
     155             :     /* Caller must specify at least one operation. */
     156             :     Assert((op & (UNLOGGED_RELATION_CLEANUP | UNLOGGED_RELATION_INIT)) != 0);
     157             : 
     158             :     /*
     159             :      * Cleanup is a two-pass operation.  First, we go through and identify all
     160             :      * the files with init forks.  Then, we go through again and nuke
     161             :      * everything with the same OID except the init fork.
     162             :      */
     163        1580 :     if ((op & UNLOGGED_RELATION_CLEANUP) != 0)
     164             :     {
     165             :         HTAB       *hash;
     166             :         HASHCTL     ctl;
     167             : 
     168             :         /*
     169             :          * It's possible that someone could create a ton of unlogged relations
     170             :          * in the same database & tablespace, so we'd better use a hash table
     171             :          * rather than an array or linked list to keep track of which files
     172             :          * need to be reset.  Otherwise, this cleanup operation would be
     173             :          * O(n^2).
     174             :          */
     175         864 :         ctl.keysize = sizeof(Oid);
     176         864 :         ctl.entrysize = sizeof(unlogged_relation_entry);
     177         864 :         ctl.hcxt = CurrentMemoryContext;
     178         864 :         hash = hash_create("unlogged relation OIDs", 32, &ctl,
     179             :                            HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     180             : 
     181             :         /* Scan the directory. */
     182         864 :         dbspace_dir = AllocateDir(dbspacedirname);
     183      236382 :         while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
     184             :         {
     185             :             ForkNumber  forkNum;
     186             :             int         oidchars;
     187             :             unlogged_relation_entry ent;
     188             : 
     189             :             /* Skip anything that doesn't look like a relation data file. */
     190      235518 :             if (!parse_filename_for_nontemp_relation(de->d_name, &oidchars,
     191             :                                                      &forkNum))
     192      235512 :                 continue;
     193             : 
     194             :             /* Also skip it unless this is the init fork. */
     195      232206 :             if (forkNum != INIT_FORKNUM)
     196      232200 :                 continue;
     197             : 
     198             :             /*
     199             :              * Put the OID portion of the name into the hash table, if it
     200             :              * isn't already.
     201             :              */
     202           6 :             ent.reloid = atooid(de->d_name);
     203           6 :             (void) hash_search(hash, &ent, HASH_ENTER, NULL);
     204             :         }
     205             : 
     206             :         /* Done with the first pass. */
     207         864 :         FreeDir(dbspace_dir);
     208             : 
     209             :         /*
     210             :          * If we didn't find any init forks, there's no point in continuing;
     211             :          * we can bail out now.
     212             :          */
     213         864 :         if (hash_get_num_entries(hash) == 0)
     214             :         {
     215         858 :             hash_destroy(hash);
     216         858 :             return;
     217             :         }
     218             : 
     219             :         /*
     220             :          * Now, make a second pass and remove anything that matches.
     221             :          */
     222           6 :         dbspace_dir = AllocateDir(dbspacedirname);
     223        1200 :         while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
     224             :         {
     225             :             ForkNumber  forkNum;
     226             :             int         oidchars;
     227             :             unlogged_relation_entry ent;
     228             : 
     229             :             /* Skip anything that doesn't look like a relation data file. */
     230        1194 :             if (!parse_filename_for_nontemp_relation(de->d_name, &oidchars,
     231             :                                                      &forkNum))
     232          26 :                 continue;
     233             : 
     234             :             /* We never remove the init fork. */
     235        1174 :             if (forkNum == INIT_FORKNUM)
     236           6 :                 continue;
     237             : 
     238             :             /*
     239             :              * See whether the OID portion of the name shows up in the hash
     240             :              * table.  If so, nuke it!
     241             :              */
     242        1168 :             ent.reloid = atooid(de->d_name);
     243        1168 :             if (hash_search(hash, &ent, HASH_FIND, NULL))
     244             :             {
     245           8 :                 snprintf(rm_path, sizeof(rm_path), "%s/%s",
     246           8 :                          dbspacedirname, de->d_name);
     247           8 :                 if (unlink(rm_path) < 0)
     248           0 :                     ereport(ERROR,
     249             :                             (errcode_for_file_access(),
     250             :                              errmsg("could not remove file \"%s\": %m",
     251             :                                     rm_path)));
     252             :                 else
     253           8 :                     elog(DEBUG2, "unlinked file \"%s\"", rm_path);
     254             :             }
     255             :         }
     256             : 
     257             :         /* Cleanup is complete. */
     258           6 :         FreeDir(dbspace_dir);
     259           6 :         hash_destroy(hash);
     260             :     }
     261             : 
     262             :     /*
     263             :      * Initialization happens after cleanup is complete: we copy each init
     264             :      * fork file to the corresponding main fork file.  Note that if we are
     265             :      * asked to do both cleanup and init, we may never get here: if the
     266             :      * cleanup code determines that there are no init forks in this dbspace,
     267             :      * it will return before we get to this point.
     268             :      */
     269         722 :     if ((op & UNLOGGED_RELATION_INIT) != 0)
     270             :     {
     271             :         /* Scan the directory. */
     272         716 :         dbspace_dir = AllocateDir(dbspacedirname);
     273      192718 :         while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
     274             :         {
     275             :             ForkNumber  forkNum;
     276             :             int         oidchars;
     277             :             char        oidbuf[OIDCHARS + 1];
     278             :             char        srcpath[MAXPGPATH * 2];
     279             :             char        dstpath[MAXPGPATH];
     280             : 
     281             :             /* Skip anything that doesn't look like a relation data file. */
     282      192002 :             if (!parse_filename_for_nontemp_relation(de->d_name, &oidchars,
     283             :                                                      &forkNum))
     284      191996 :                 continue;
     285             : 
     286             :             /* Also skip it unless this is the init fork. */
     287      189256 :             if (forkNum != INIT_FORKNUM)
     288      189250 :                 continue;
     289             : 
     290             :             /* Construct source pathname. */
     291           6 :             snprintf(srcpath, sizeof(srcpath), "%s/%s",
     292           6 :                      dbspacedirname, de->d_name);
     293             : 
     294             :             /* Construct destination pathname. */
     295           6 :             memcpy(oidbuf, de->d_name, oidchars);
     296           6 :             oidbuf[oidchars] = '\0';
     297           6 :             snprintf(dstpath, sizeof(dstpath), "%s/%s%s",
     298          12 :                      dbspacedirname, oidbuf, de->d_name + oidchars + 1 +
     299           6 :                      strlen(forkNames[INIT_FORKNUM]));
     300             : 
     301             :             /* OK, we're ready to perform the actual copy. */
     302           6 :             elog(DEBUG2, "copying %s to %s", srcpath, dstpath);
     303           6 :             copy_file(srcpath, dstpath);
     304             :         }
     305             : 
     306         716 :         FreeDir(dbspace_dir);
     307             : 
     308             :         /*
     309             :          * copy_file() above has already called pg_flush_data() on the files
     310             :          * it created. Now we need to fsync those files, because a checkpoint
     311             :          * won't do it for us while we're in recovery. We do this in a
     312             :          * separate pass to allow the kernel to perform all the flushes
     313             :          * (especially the metadata ones) at once.
     314             :          */
     315         716 :         dbspace_dir = AllocateDir(dbspacedirname);
     316      192724 :         while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
     317             :         {
     318             :             ForkNumber  forkNum;
     319             :             int         oidchars;
     320             :             char        oidbuf[OIDCHARS + 1];
     321             :             char        mainpath[MAXPGPATH];
     322             : 
     323             :             /* Skip anything that doesn't look like a relation data file. */
     324      192008 :             if (!parse_filename_for_nontemp_relation(de->d_name, &oidchars,
     325             :                                                      &forkNum))
     326      192002 :                 continue;
     327             : 
     328             :             /* Also skip it unless this is the init fork. */
     329      189262 :             if (forkNum != INIT_FORKNUM)
     330      189256 :                 continue;
     331             : 
     332             :             /* Construct main fork pathname. */
     333           6 :             memcpy(oidbuf, de->d_name, oidchars);
     334           6 :             oidbuf[oidchars] = '\0';
     335           6 :             snprintf(mainpath, sizeof(mainpath), "%s/%s%s",
     336          12 :                      dbspacedirname, oidbuf, de->d_name + oidchars + 1 +
     337           6 :                      strlen(forkNames[INIT_FORKNUM]));
     338             : 
     339           6 :             fsync_fname(mainpath, false);
     340             :         }
     341             : 
     342         716 :         FreeDir(dbspace_dir);
     343             : 
     344             :         /*
     345             :          * Lastly, fsync the database directory itself, ensuring the
     346             :          * filesystem remembers the file creations and deletions we've done.
     347             :          * We don't bother with this during a call that does only
     348             :          * UNLOGGED_RELATION_CLEANUP, because if recovery crashes before we
     349             :          * get to doing UNLOGGED_RELATION_INIT, we'll redo the cleanup step
     350             :          * too at the next startup attempt.
     351             :          */
     352         716 :         fsync_fname(dbspacedirname, true);
     353             :     }
     354             : }
     355             : 
     356             : /*
     357             :  * Basic parsing of putative relation filenames.
     358             :  *
     359             :  * This function returns true if the file appears to be in the correct format
     360             :  * for a non-temporary relation and false otherwise.
     361             :  *
     362             :  * NB: If this function returns true, the caller is entitled to assume that
     363             :  * *oidchars has been set to the a value no more than OIDCHARS, and thus
     364             :  * that a buffer of OIDCHARS+1 characters is sufficient to hold the OID
     365             :  * portion of the filename.  This is critical to protect against a possible
     366             :  * buffer overrun.
     367             :  */
     368             : bool
     369      909278 : parse_filename_for_nontemp_relation(const char *name, int *oidchars,
     370             :                                     ForkNumber *fork)
     371             : {
     372             :     int         pos;
     373             : 
     374             :     /* Look for a non-empty string of digits (that isn't too long). */
     375     4545618 :     for (pos = 0; isdigit((unsigned char) name[pos]); ++pos)
     376             :         ;
     377      909278 :     if (pos == 0 || pos > OIDCHARS)
     378       10868 :         return false;
     379      898410 :     *oidchars = pos;
     380             : 
     381             :     /* Check for a fork name. */
     382      898410 :     if (name[pos] != '_')
     383      670162 :         *fork = MAIN_FORKNUM;
     384             :     else
     385             :     {
     386             :         int         forkchar;
     387             : 
     388      228248 :         forkchar = forkname_chars(&name[pos + 1], fork);
     389      228248 :         if (forkchar <= 0)
     390           0 :             return false;
     391      228248 :         pos += forkchar + 1;
     392             :     }
     393             : 
     394             :     /* Check for a segment number. */
     395      898410 :     if (name[pos] == '.')
     396             :     {
     397             :         int         segchar;
     398             : 
     399           0 :         for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
     400             :             ;
     401           0 :         if (segchar <= 1)
     402           0 :             return false;
     403           0 :         pos += segchar;
     404             :     }
     405             : 
     406             :     /* Now we should be at the end. */
     407      898410 :     if (name[pos] != '\0')
     408           0 :         return false;
     409      898410 :     return true;
     410             : }

Generated by: LCOV version 1.13