Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*-------------------------------------------------------------------------
 *
 * cfs_swap.c
 *    The compaction swap protocol: the .cfsswap commit marker, the
 *    candidate (.new) activation renames, the stale trailing-segment
 *    cleanup and the crash recovery that finishes (or aborts) an
 *    interrupted swap before anyone opens the pair.  One home shared by
 *    the compaction driver (cfs_compact.c) and the open path
 *    (cfs_storage.c / cfs_recovery.c), so the protocol cannot fork.
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 2026, Diasoft
 *
 * src/backend/storage/cfs/cfs_swap.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
#include <sys/stat.h>
#include <unistd.h>
 
#include "storage/cfs/cfs_cfp.h"
#include "storage/cfs/cfs_format.h"
#include "storage/cfs/cfs_journal.h"
#include "storage/cfs/cfs_map_file.h"
#include "storage/cfs/cfs_path.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/cfs/cfs_swap.h"
#include "storage/fd.h"
 
static void cfs_map_file_summary(const char *cfp_path, const char *jrn_path,
                                 uint64 *cfp_size, uint32 *max_generation);
 
int
cfs_rename_if_exists(const char *src, const char *dst)
{
    struct stat st;
 
    if (stat(src, &st) != 0)
    {
        if (errno == ENOENT)
            return 0;
        return -1;
    }
    return durable_rename(src, dst, WARNING);
}
 
void
cfs_unlink_if_exists(const char *path)
{
    struct stat st;
 
    if (stat(path, &st) == 0)
    {
        if (unlink(path) != 0 && errno != ENOENT)
            ereport(WARNING,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not unlink \"%s\": %m", path)));
    }
}
 
void
cfs_unlink_trailing_segments(const char *cfp_path, uint32 last_seg)
{
    uint32      segno;
 
    for (segno = last_seg + 1;; segno++)
    {
        char       *seg_path = cfs_segment_path(cfp_path, segno);
        struct stat st;
 
        if (stat(seg_path, &st) != 0)
        {
            pfree(seg_path);
            break;              /* end of the chain */
        }
        ereport(DEBUG1,
                (errmsg("CFS: removing stale trailing segment \"%s\"",
                        seg_path)));
        if (unlink(seg_path) != 0 && errno != ENOENT)
            ereport(WARNING,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not unlink stale segment \"%s\": %m",
                            seg_path)));
        pfree(seg_path);
    }
}
 
void
cfs_recover_compaction(const char *cfp_path, const char *map_path,
                       const char *jrn_path)
{
    char       *map_new = psprintf("%s%s", map_path, CFS_CANDIDATE_SUFFIX);
    char       *map_tmp = psprintf("%s%s", map_path,
                                 CFS_MAP_CANDIDATE_TMP_SUFFIX);
 
    /*
     * The swap marker lives next to the .cfp file and is named after it so a
     * single relation cannot be confused with another.
     */
    char       *swap_marker = psprintf("%s%s", cfp_path, CFS_SWAP_MARKER_SUFFIX);
    struct stat st;
    bool        marker_present = (stat(swap_marker, &st) == 0);
    uint32      jrn_max_generation = 0;
 
    if (marker_present)
    {
        uint32      segno;
 
        /*
         * Commit point was reached: the candidate pair is fully durable.
         * Complete the activation renames for every .cfp segment (no-op for
         * whichever already happened), then drop the marker.
         */
        ereport(DEBUG1,
                (errmsg("CFS: completing interrupted compaction swap for \"%s\"",
                        cfp_path)));
 
        /*
         * The activation renames are durability operations: a persistent
         * failure (EACCES / EISDIR / EROFS from a broken filesystem object)
         * must be a hard ERROR, leaving the commit marker in place.
         * Continuation with a WARNING would run the follow-up steps (map
         * rename, trailing cleanup, journal reset, marker unlink) over a
         * half-activated pair and destroy the very state the promised
         * idempotent retry needs — like vanilla durability operations, work
         * is never marked done when the work failed. cfs_rename_if_exists
         * only reports real errors (a missing source is silently skipped), so
         * every failure here is persistent.
         */
        for (segno = 0;; segno++)
        {
            char       *seg_path = cfs_segment_path(cfp_path, segno);
            char       *seg_new = psprintf("%s%s", seg_path,
                                           CFS_CANDIDATE_SUFFIX);
 
            if (cfs_rename_if_exists(seg_new, seg_path) != 0)
            {
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("CFS: recovery could not activate \"%s\"",
                                seg_new)));
            }
            else if (segno > 0)
            {
                struct stat seg_st;
 
                /*
                 * The candidate chain is contiguous: stop at the first
                 * segment that has neither a candidate nor an activated file.
                 */
                if (stat(seg_new, &seg_st) != 0 && stat(seg_path, &seg_st) != 0)
                {
                    pfree(seg_path);
                    pfree(seg_new);
                    break;
                }
            }
            pfree(seg_path);
            pfree(seg_new);
        }
 
        if (cfs_rename_if_exists(map_new, map_path) != 0)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("CFS: recovery could not activate \"%s\"",
                            map_new)));
 
        /*
         * Remove stale trailing segments of the old (pre-swap) chain: the
         * compaction may have shrunk the data file across a segment boundary.
         * The number of segments the new chain needs is derived from the
         * freshly activated map's cfp_size.  Idempotent.  The same helper
         * also supplies the watermark for the journal reset below; on
         * unreadable state it falls back to zero - the next checkpoint
         * recomputes.  The helper also validates the journal header through
         * cfs_journal_read_header (one pread).
         */
        {
            uint64      cfp_size;
            uint32      max_generation = 0;
            uint32      last_seg;
 
            cfs_map_file_summary(cfp_path, jrn_path,
                                 &cfp_size, &max_generation);
            last_seg = (cfp_size <= CFS_CFP_BASE_OFFSET) ? 0 :
                CFS_CFP_SEGNO(cfp_size - 1);
 
            cfs_unlink_trailing_segments(cfp_path, last_seg);
            jrn_max_generation = max_generation;
        }
 
        cfs_fsync_parent_dir(cfp_path, WARNING);
 
        /*
         * Repeat the journal reset (step 7 of the swap protocol): the crash
         * may have undone it, and replaying the stale journal on top of the
         * new map would corrupt it.  Idempotent.
         */
        cfs_journal_reset_file(jrn_path, jrn_max_generation);
 
        cfs_unlink_if_exists(swap_marker);
        cfs_fsync_parent_dir(cfp_path, WARNING);
    }
    else
    {
        uint32      segno;
 
        /*
         * No commit marker: compaction was interrupted before the candidate
         * became authoritative.  Discard every leftover candidate / temp file
         * of every segment so the old pair is used as-is.
         *
         * Invariant: this cleanup runs without the append lock, which is
         * safe because every caller first consults the state judge's
         * compaction provider (QDB-1514): candidates of a live online
         * compaction are never touched, and only a dead owner's leftovers
         * are discarded here; the startup recovery scan is single-threaded
         * and observes no live owners.  A caller that cannot ask the judge
         * (no provider installed) must not run this cleanup concurrently
         * with a compaction.
         */
        cfs_unlink_if_exists(map_new);
        cfs_unlink_if_exists(map_tmp);
        for (segno = 0;; segno++)
        {
            char       *seg_path = cfs_segment_path(cfp_path, segno);
            char       *seg_new = psprintf("%s%s", seg_path,
                                           CFS_CANDIDATE_SUFFIX);
            char       *seg_tmp = psprintf("%s.tmp", seg_path);
            struct stat st_new;
            struct stat st_tmp;
            bool        has_new = (stat(seg_new, &st_new) == 0);
            bool        has_tmp = (stat(seg_tmp, &st_tmp) == 0);
 
            if (segno > 0 && !has_new && !has_tmp)
            {
                pfree(seg_path);
                pfree(seg_new);
                pfree(seg_tmp);
                break;          /* candidate chains are contiguous */
            }
            /* has_new/has_tmp already probed the files: unlink directly. */
            if (has_new && unlink(seg_new) != 0 && errno != ENOENT)
                ereport(WARNING,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not unlink \"%s\": %m", seg_new)));
            if (has_tmp && unlink(seg_tmp) != 0 && errno != ENOENT)
                ereport(WARNING,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not unlink \"%s\": %m", seg_tmp)));
            pfree(seg_path);
            pfree(seg_new);
            pfree(seg_tmp);
        }
    }
 
    pfree(map_new);
    pfree(map_tmp);
    pfree(swap_marker);
}
 
/*
 * Collect the summary the journal reset must stamp after a swap recovery:
 * the .cfp chain size and the generation watermark.  The watermark comes
 * from the journal the reset is about to replace: its header stamp raised
 * by every UPDATE record the journal still holds, because those records
 * may postdate the last reset and their generations live on in the
 * swapped-in map rows (zero when nothing is readable - the next checkpoint
 * recomputes it).
 */
static void
cfs_map_file_summary(const char *cfp_path, const char *jrn_path,
                     uint64 *cfp_size, uint32 *max_generation)
{
    CfsJournalFileHeader jhdr;
    int         fd;
 
    if (!cfs_cfp_chain_stat(cfp_path, cfp_size, NULL))
        *cfp_size = CFS_CFP_BASE_OFFSET;
 
    *max_generation = 0;
    fd = BasicOpenFile(jrn_path, O_RDONLY | PG_BINARY);
    if (fd >= 0)
    {
        if (cfs_journal_read_header(fd, &jhdr))
            *max_generation = jhdr.max_generation;
 
        /*
         * The header watermark dates from the journal's last reset; UPDATE
         * records appended after it may carry higher generations, and the
         * rows they describe live on in the swapped-in map.  Raise the
         * watermark with every record the journal still holds, exactly like
         * the generation seeding (cfs_map_cache_next_generation): stamping a
         * value below what the map already contains would let the allocator
         * re-issue a live generation and defeat the (block, generation)
         * replay idempotency.  On an I/O error keep whatever was raised so
         * far - the next checkpoint recomputes the stamp.
         */
        (void) cfs_journal_fd_scan_max_generation(fd, jrn_path,
                                                  max_generation);
        close(fd);
    }
}
 
bool
cfs_swap_path_exists(const char *path)
{
    struct stat st;
 
    return stat(path, &st) == 0;
}
 
void
cfs_swap_unlink_marker(const char *marker)
{
    if (unlink(marker) != 0 && errno != ENOENT)
        ereport(WARNING,
                (errcode_for_file_access(),
                 errmsg("CFS: compaction: could not unlink commit marker \"%s\": %m",
                        marker)));
}