at commit cbd35cad

1 /*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style
5 * license that can be found in the LICENSE file or at
6 * https://developers.google.com/open-source/licenses/bsd
7 */
8
9 #include "stack.h"
10
11 #include "system.h"
12 #include "constants.h"
13 #include "merged.h"
14 #include "reftable-error.h"
15 #include "reftable-record.h"
16 #include "reftable-merged.h"
17 #include "table.h"
18 #include "writer.h"
19
20 static int stack_filename(struct reftable_buf *dest, struct reftable_stack *st,
21 const char *name)
22 {
23 int err;
24 reftable_buf_reset(dest);
25 if ((err = reftable_buf_addstr(dest, st->reftable_dir)) < 0 ||
26 (err = reftable_buf_addstr(dest, "/")) < 0 ||
27 (err = reftable_buf_addstr(dest, name)) < 0)
28 return err;
29 return 0;
30 }
31
32 static ssize_t reftable_write_data(int fd, const void *data, size_t size)
33 {
34 size_t total_written = 0;
35 const char *p = data;
36
37 while (total_written < size) {
38 ssize_t bytes_written = write(fd, p, size - total_written);
39 if (bytes_written < 0 && (errno == EAGAIN || errno == EINTR))
40 continue;
41 if (bytes_written < 0)
42 return REFTABLE_IO_ERROR;
43
44 total_written += bytes_written;
45 p += bytes_written;
46 }
47
48 return total_written;
49 }
50
51 struct fd_writer {
52 const struct reftable_write_options *opts;
53 int fd;
54 };
55
56 static ssize_t fd_writer_write(void *arg, const void *data, size_t sz)
57 {
58 struct fd_writer *writer = arg;
59 return reftable_write_data(writer->fd, data, sz);
60 }
61
62 static int fd_writer_flush(void *arg)
63 {
64 struct fd_writer *writer = arg;
65 return fsync(writer->fd);
66 }
67
68 static int fd_read_lines(int fd, char ***namesp)
69 {
70 char *buf = NULL;
71 int err = 0;
72 off_t size;
73
74 size = lseek(fd, 0, SEEK_END);
75 if (size < 0) {
76 err = REFTABLE_IO_ERROR;
77 goto done;
78 }
79
80 err = lseek(fd, 0, SEEK_SET);
81 if (err < 0) {
82 err = REFTABLE_IO_ERROR;
83 goto done;
84 }
85
86 REFTABLE_ALLOC_ARRAY(buf, size + 1);
87 if (!buf) {
88 err = REFTABLE_OUT_OF_MEMORY_ERROR;
89 goto done;
90 }
91
92 for (off_t total_read = 0; total_read < size; ) {
93 ssize_t bytes_read = read(fd, buf + total_read, size - total_read);
94 if (bytes_read < 0 && (errno == EAGAIN || errno == EINTR))
95 continue;
96 if (bytes_read < 0 || !bytes_read) {
97 err = REFTABLE_IO_ERROR;
98 goto done;
99 }
100
101 total_read += bytes_read;
102 }
103 buf[size] = 0;
104
105 err = parse_names(buf, size, namesp);
106 done:
107 reftable_free(buf);
108 return err;
109 }
110
111 int read_lines(const char *filename, char ***namesp)
112 {
113 int fd = open(filename, O_RDONLY);
114 int err = 0;
115 if (fd < 0) {
116 if (errno == ENOENT) {
117 REFTABLE_CALLOC_ARRAY(*namesp, 1);
118 if (!*namesp)
119 return REFTABLE_OUT_OF_MEMORY_ERROR;
120 return 0;
121 }
122
123 return REFTABLE_IO_ERROR;
124 }
125 err = fd_read_lines(fd, namesp);
126 close(fd);
127 return err;
128 }
129
130 int reftable_stack_init_ref_iterator(struct reftable_stack *st,
131 struct reftable_iterator *it)
132 {
133 return merged_table_init_iter(reftable_stack_merged_table(st),
134 it, REFTABLE_BLOCK_TYPE_REF);
135 }
136
137 int reftable_stack_init_log_iterator(struct reftable_stack *st,
138 struct reftable_iterator *it)
139 {
140 return merged_table_init_iter(reftable_stack_merged_table(st),
141 it, REFTABLE_BLOCK_TYPE_LOG);
142 }
143
144 struct reftable_merged_table *
145 reftable_stack_merged_table(struct reftable_stack *st)
146 {
147 return st->merged;
148 }
149
150 static int has_name(char **names, const char *name)
151 {
152 while (*names) {
153 if (!strcmp(*names, name))
154 return 1;
155 names++;
156 }
157 return 0;
158 }
159
160 /* Close and free the stack */
161 void reftable_stack_destroy(struct reftable_stack *st)
162 {
163 char **names = NULL;
164 int err = 0;
165
166 if (!st)
167 return;
168
169 if (st->merged) {
170 reftable_merged_table_free(st->merged);
171 st->merged = NULL;
172 }
173
174 if (st->list_file)
175 err = read_lines(st->list_file, &names);
176 if (err < 0) {
177 REFTABLE_FREE_AND_NULL(names);
178 }
179
180 if (st->tables) {
181 struct reftable_buf filename = REFTABLE_BUF_INIT;
182
183 for (size_t i = 0; i < st->tables_len; i++) {
184 const char *name = reftable_table_name(st->tables[i]);
185 int try_unlinking = 1;
186
187 reftable_buf_reset(&filename);
188 if (names && !has_name(names, name)) {
189 if (stack_filename(&filename, st, name) < 0)
190 try_unlinking = 0;
191 }
192 reftable_table_decref(st->tables[i]);
193
194 if (try_unlinking && filename.len) {
195 /* On Windows, can only unlink after closing. */
196 unlink(filename.buf);
197 }
198 }
199
200 reftable_buf_release(&filename);
201 st->tables_len = 0;
202 REFTABLE_FREE_AND_NULL(st->tables);
203 }
204
205 if (st->list_fd >= 0) {
206 close(st->list_fd);
207 st->list_fd = -1;
208 }
209
210 REFTABLE_FREE_AND_NULL(st->list_file);
211 REFTABLE_FREE_AND_NULL(st->reftable_dir);
212 reftable_free(st);
213 free_names(names);
214 }
215
216 static struct reftable_table **stack_copy_tables(struct reftable_stack *st,
217 size_t cur_len)
218 {
219 struct reftable_table **cur = reftable_calloc(cur_len, sizeof(*cur));
220 if (!cur)
221 return NULL;
222 for (size_t i = 0; i < cur_len; i++)
223 cur[i] = st->tables[i];
224 return cur;
225 }
226
227 static int reftable_stack_reload_once(struct reftable_stack *st,
228 const char **names,
229 int reuse_open)
230 {
231 size_t cur_len = !st->merged ? 0 : st->merged->tables_len;
232 struct reftable_table **cur = NULL;
233 struct reftable_table **reused = NULL;
234 struct reftable_table **new_tables = NULL;
235 size_t reused_len = 0, reused_alloc = 0, names_len;
236 size_t new_tables_len = 0;
237 struct reftable_merged_table *new_merged = NULL;
238 struct reftable_buf table_path = REFTABLE_BUF_INIT;
239 int err = 0;
240 size_t i;
241
242 if (cur_len) {
243 cur = stack_copy_tables(st, cur_len);
244 if (!cur) {
245 err = REFTABLE_OUT_OF_MEMORY_ERROR;
246 goto done;
247 }
248 }
249
250 names_len = names_length(names);
251
252 if (names_len) {
253 new_tables = reftable_calloc(names_len, sizeof(*new_tables));
254 if (!new_tables) {
255 err = REFTABLE_OUT_OF_MEMORY_ERROR;
256 goto done;
257 }
258 }
259
260 while (*names) {
261 struct reftable_table *table = NULL;
262 const char *name = *names++;
263
264 /* this is linear; we assume compaction keeps the number of
265 tables under control so this is not quadratic. */
266 for (i = 0; reuse_open && i < cur_len; i++) {
267 if (cur[i] && 0 == strcmp(cur[i]->name, name)) {
268 table = cur[i];
269 cur[i] = NULL;
270
271 /*
272 * When reloading the stack fails, we end up
273 * releasing all new tables. This also
274 * includes the reused tables, even though
275 * they are still in used by the old stack. We
276 * thus need to keep them alive here, which we
277 * do by bumping their refcount.
278 */
279 REFTABLE_ALLOC_GROW_OR_NULL(reused,
280 reused_len + 1,
281 reused_alloc);
282 if (!reused) {
283 err = REFTABLE_OUT_OF_MEMORY_ERROR;
284 goto done;
285 }
286 reused[reused_len++] = table;
287 reftable_table_incref(table);
288 break;
289 }
290 }
291
292 if (!table) {
293 struct reftable_block_source src = { NULL };
294
295 err = stack_filename(&table_path, st, name);
296 if (err < 0)
297 goto done;
298
299 err = reftable_block_source_from_file(&src,
300 table_path.buf);
301 if (err < 0)
302 goto done;
303
304 err = reftable_table_new(&table, &src, name);
305 if (err < 0)
306 goto done;
307 }
308
309 new_tables[new_tables_len] = table;
310 new_tables_len++;
311 }
312
313 /* success! */
314 err = reftable_merged_table_new(&new_merged, new_tables,
315 new_tables_len, st->opts.hash_id);
316 if (err < 0)
317 goto done;
318
319 /*
320 * Close the old, non-reused tables and proactively try to unlink
321 * them. This is done for systems like Windows, where the underlying
322 * file of such an open table wouldn't have been possible to be
323 * unlinked by the compacting process.
324 */
325 for (i = 0; i < cur_len; i++) {
326 if (cur[i]) {
327 const char *name = reftable_table_name(cur[i]);
328
329 err = stack_filename(&table_path, st, name);
330 if (err < 0)
331 goto done;
332
333 reftable_table_decref(cur[i]);
334 unlink(table_path.buf);
335 }
336 }
337
338 /* Update the stack to point to the new tables. */
339 if (st->merged)
340 reftable_merged_table_free(st->merged);
341 new_merged->suppress_deletions = st->opts.suppress_deletions;
342 st->merged = new_merged;
343
344 if (st->tables)
345 reftable_free(st->tables);
346 st->tables = new_tables;
347 st->tables_len = new_tables_len;
348 new_tables = NULL;
349 new_tables_len = 0;
350
351 /*
352 * Decrement the refcount of reused tables again. This only needs to
353 * happen on the successful case, because on the unsuccessful one we
354 * decrement their refcount via `new_tables`.
355 */
356 for (i = 0; i < reused_len; i++)
357 reftable_table_decref(reused[i]);
358
359 done:
360 for (i = 0; i < new_tables_len; i++)
361 reftable_table_decref(new_tables[i]);
362 reftable_free(new_tables);
363 reftable_free(reused);
364 reftable_free(cur);
365 reftable_buf_release(&table_path);
366 return err;
367 }
368
369 static int reftable_stack_reload_maybe_reuse(struct reftable_stack *st,
370 int reuse_open)
371 {
372 char **names = NULL, **names_after = NULL;
373 uint64_t deadline;
374 int64_t delay = 0;
375 int tries = 0, err;
376 int fd = -1;
377
378 deadline = reftable_time_ms() + 3000;
379
380 while (1) {
381 uint64_t now = reftable_time_ms();
382
383 /*
384 * Only look at deadlines after the first few times. This
385 * simplifies debugging in GDB.
386 */
387 tries++;
388 if (tries > 3 && now >= deadline)
389 goto out;
390
391 fd = open(st->list_file, O_RDONLY);
392 if (fd < 0) {
393 if (errno != ENOENT) {
394 err = REFTABLE_IO_ERROR;
395 goto out;
396 }
397
398 REFTABLE_CALLOC_ARRAY(names, 1);
399 if (!names) {
400 err = REFTABLE_OUT_OF_MEMORY_ERROR;
401 goto out;
402 }
403 } else {
404 err = fd_read_lines(fd, &names);
405 if (err < 0)
406 goto out;
407 }
408
409 err = reftable_stack_reload_once(st, (const char **) names, reuse_open);
410 if (!err)
411 break;
412 if (err != REFTABLE_NOT_EXIST_ERROR)
413 goto out;
414
415 /*
416 * REFTABLE_NOT_EXIST_ERROR can be caused by a concurrent
417 * writer. Check if there was one by checking if the name list
418 * changed.
419 */
420 err = read_lines(st->list_file, &names_after);
421 if (err < 0)
422 goto out;
423 if (names_equal((const char **) names_after,
424 (const char **) names)) {
425 err = REFTABLE_NOT_EXIST_ERROR;
426 goto out;
427 }
428
429 free_names(names);
430 names = NULL;
431 free_names(names_after);
432 names_after = NULL;
433 close(fd);
434 fd = -1;
435
436 delay = delay + (delay * reftable_rand()) / UINT32_MAX + 1;
437 poll(NULL, 0, delay);
438 }
439
440 out:
441 /*
442 * Invalidate the stat cache. It is sufficient to only close the file
443 * descriptor and keep the cached stat info because we never use the
444 * latter when the former is negative.
445 */
446 if (st->list_fd >= 0) {
447 close(st->list_fd);
448 st->list_fd = -1;
449 }
450
451 /*
452 * Cache stat information in case it provides a useful signal to us.
453 * According to POSIX, "The st_ino and st_dev fields taken together
454 * uniquely identify the file within the system." That being said,
455 * Windows is not POSIX compliant and we do not have these fields
456 * available. So the information we have there is insufficient to
457 * determine whether two file descriptors point to the same file.
458 *
459 * While we could fall back to using other signals like the file's
460 * mtime, those are not sufficient to avoid races. We thus refrain from
461 * using the stat cache on such systems and fall back to the secondary
462 * caching mechanism, which is to check whether contents of the file
463 * have changed.
464 *
465 * On other systems which are POSIX compliant we must keep the file
466 * descriptor open. This is to avoid a race condition where two
467 * processes access the reftable stack at the same point in time:
468 *
469 * 1. A reads the reftable stack and caches its stat info.
470 *
471 * 2. B updates the stack, appending a new table to "tables.list".
472 * This will both use a new inode and result in a different file
473 * size, thus invalidating A's cache in theory.
474 *
475 * 3. B decides to auto-compact the stack and merges two tables. The
476 * file size now matches what A has cached again. Furthermore, the
477 * filesystem may decide to recycle the inode number of the file
478 * we have replaced in (2) because it is not in use anymore.
479 *
480 * 4. A reloads the reftable stack. Neither the inode number nor the
481 * file size changed. If the timestamps did not change either then
482 * we think the cached copy of our stack is up-to-date.
483 *
484 * By keeping the file descriptor open the inode number cannot be
485 * recycled, mitigating the race.
486 */
487 if (!err && fd >= 0 && !fstat(fd, &st->list_st) &&
488 st->list_st.st_dev && st->list_st.st_ino) {
489 st->list_fd = fd;
490 fd = -1;
491 }
492
493 if (fd >= 0)
494 close(fd);
495 free_names(names);
496 free_names(names_after);
497
498 if (st->opts.on_reload)
499 st->opts.on_reload(st->opts.on_reload_payload);
500
501 return err;
502 }
503
504 int reftable_new_stack(struct reftable_stack **dest, const char *dir,
505 const struct reftable_stack_options *_opts)
506 {
507 struct reftable_buf list_file_name = REFTABLE_BUF_INIT;
508 struct reftable_stack_options opts = { 0 };
509 struct reftable_stack *p;
510 int err;
511
512 p = reftable_calloc(1, sizeof(*p));
513 if (!p) {
514 err = REFTABLE_OUT_OF_MEMORY_ERROR;
515 goto out;
516 }
517
518 if (_opts)
519 opts = *_opts;
520 if (opts.hash_id == 0)
521 opts.hash_id = REFTABLE_HASH_SHA1;
522
523 *dest = NULL;
524
525 reftable_buf_reset(&list_file_name);
526 if ((err = reftable_buf_addstr(&list_file_name, dir)) < 0 ||
527 (err = reftable_buf_addstr(&list_file_name, "/tables.list")) < 0)
528 goto out;
529
530 p->list_file = reftable_buf_detach(&list_file_name);
531 p->list_fd = -1;
532 p->opts = opts;
533 p->reftable_dir = reftable_strdup(dir);
534 if (!p->reftable_dir) {
535 err = REFTABLE_OUT_OF_MEMORY_ERROR;
536 goto out;
537 }
538
539 err = reftable_stack_reload_maybe_reuse(p, 1);
540 if (err < 0)
541 goto out;
542
543 *dest = p;
544 err = 0;
545
546 out:
547 if (err < 0)
548 reftable_stack_destroy(p);
549 return err;
550 }
551
552 /*
553 * Check whether the given stack is up-to-date with what we have in memory.
554 * Returns 0 if so, 1 if the stack is out-of-date or a negative error code
555 * otherwise.
556 */
557 static int stack_uptodate(struct reftable_stack *st)
558 {
559 char **names = NULL;
560 int err;
561
562 /*
563 * When we have cached stat information available then we use it to
564 * verify whether the file has been rewritten.
565 *
566 * Note that we explicitly do not want to use `stat_validity_check()`
567 * and friends here because they may end up not comparing the `st_dev`
568 * and `st_ino` fields. These functions thus cannot guarantee that we
569 * indeed still have the same file.
570 */
571 if (st->list_fd >= 0) {
572 struct stat list_st;
573
574 if (stat(st->list_file, &list_st) < 0) {
575 /*
576 * It's fine for "tables.list" to not exist. In that
577 * case, we have to refresh when the loaded stack has
578 * any tables.
579 */
580 if (errno == ENOENT)
581 return !!st->tables_len;
582 return REFTABLE_IO_ERROR;
583 }
584
585 /*
586 * When "tables.list" refers to the same file we can assume
587 * that it didn't change. This is because we always use
588 * rename(3P) to update the file and never write to it
589 * directly.
590 */
591 if (st->list_st.st_dev == list_st.st_dev &&
592 st->list_st.st_ino == list_st.st_ino)
593 return 0;
594 }
595
596 err = read_lines(st->list_file, &names);
597 if (err < 0)
598 return err;
599
600 for (size_t i = 0; i < st->tables_len; i++) {
601 if (!names[i]) {
602 err = 1;
603 goto done;
604 }
605
606 if (strcmp(st->tables[i]->name, names[i])) {
607 err = 1;
608 goto done;
609 }
610 }
611
612 if (names[st->merged->tables_len]) {
613 err = 1;
614 goto done;
615 }
616
617 done:
618 free_names(names);
619 return err;
620 }
621
622 int reftable_stack_reload(struct reftable_stack *st)
623 {
624 int err = stack_uptodate(st);
625 if (err > 0)
626 return reftable_stack_reload_maybe_reuse(st, 1);
627 return err;
628 }
629
630 struct reftable_addition {
631 struct reftable_flock tables_list_lock;
632 struct reftable_stack *stack;
633 struct reftable_write_options opts;
634
635 char **new_tables;
636 size_t new_tables_len, new_tables_cap;
637 uint64_t next_update_index;
638 };
639
640 static void reftable_addition_close(struct reftable_addition *add)
641 {
642 struct reftable_buf nm = REFTABLE_BUF_INIT;
643 size_t i;
644
645 for (i = 0; i < add->new_tables_len; i++) {
646 if (!stack_filename(&nm, add->stack, add->new_tables[i]))
647 unlink(nm.buf);
648 reftable_free(add->new_tables[i]);
649 add->new_tables[i] = NULL;
650 }
651 reftable_free(add->new_tables);
652 add->new_tables = NULL;
653 add->new_tables_len = 0;
654 add->new_tables_cap = 0;
655
656 flock_release(&add->tables_list_lock);
657 reftable_buf_release(&nm);
658 }
659
660 static int reftable_stack_init_addition(struct reftable_addition *add,
661 struct reftable_stack *st,
662 const struct reftable_write_options *opts)
663 {
664 struct reftable_buf lock_file_name = REFTABLE_BUF_INIT;
665 int err;
666
667 memset(add, 0, sizeof(*add));
668 add->stack = st;
669 if (opts)
670 add->opts = *opts;
671
672 err = flock_acquire(&add->tables_list_lock, st->list_file,
673 add->opts.lock_timeout_ms);
674 if (err < 0)
675 goto done;
676
677 if (add->opts.default_permissions) {
678 if (chmod(add->tables_list_lock.path,
679 add->opts.default_permissions) < 0) {
680 err = REFTABLE_IO_ERROR;
681 goto done;
682 }
683 }
684
685 err = stack_uptodate(st);
686 if (err < 0)
687 goto done;
688 if (err > 0) {
689 err = reftable_stack_reload_maybe_reuse(add->stack, 1);
690 if (err)
691 goto done;
692 }
693
694 add->next_update_index = reftable_stack_next_update_index(st);
695 done:
696 if (err)
697 reftable_addition_close(add);
698 reftable_buf_release(&lock_file_name);
699 return err;
700 }
701
702 static int stack_try_add(struct reftable_stack *st,
703 int (*write_table)(struct reftable_writer *wr,
704 void *arg),
705 void *arg,
706 const struct reftable_write_options *opts)
707 {
708 struct reftable_addition add;
709 int err;
710
711 err = reftable_stack_init_addition(&add, st, opts);
712 if (err < 0)
713 goto done;
714
715 err = reftable_addition_add(&add, write_table, arg);
716 if (err < 0)
717 goto done;
718
719 err = reftable_addition_commit(&add);
720 done:
721 reftable_addition_close(&add);
722 return err;
723 }
724
725 int reftable_stack_add(struct reftable_stack *st,
726 int (*write)(struct reftable_writer *wr, void *arg),
727 void *arg,
728 const struct reftable_write_options *opts)
729 {
730 int err = stack_try_add(st, write, arg, opts);
731 if (err < 0) {
732 return err;
733 }
734
735 return 0;
736 }
737
738 static int format_name(struct reftable_buf *dest, uint64_t min, uint64_t max)
739 {
740 char buf[100];
741 uint32_t rnd = reftable_rand();
742 snprintf(buf, sizeof(buf), "0x%012" PRIx64 "-0x%012" PRIx64 "-%08x",
743 min, max, rnd);
744 reftable_buf_reset(dest);
745 return reftable_buf_addstr(dest, buf);
746 }
747
748 void reftable_addition_destroy(struct reftable_addition *add)
749 {
750 if (!add) {
751 return;
752 }
753 reftable_addition_close(add);
754 reftable_free(add);
755 }
756
757 int reftable_addition_commit(struct reftable_addition *add)
758 {
759 struct reftable_buf table_list = REFTABLE_BUF_INIT;
760 int err = 0;
761 size_t i;
762
763 if (add->new_tables_len == 0)
764 goto done;
765
766 for (i = 0; i < add->stack->merged->tables_len; i++) {
767 if ((err = reftable_buf_addstr(&table_list, add->stack->tables[i]->name)) < 0 ||
768 (err = reftable_buf_addstr(&table_list, "\n")) < 0)
769 goto done;
770 }
771 for (i = 0; i < add->new_tables_len; i++) {
772 if ((err = reftable_buf_addstr(&table_list, add->new_tables[i])) < 0 ||
773 (err = reftable_buf_addstr(&table_list, "\n")) < 0)
774 goto done;
775 }
776
777 err = reftable_write_data(add->tables_list_lock.fd,
778 table_list.buf, table_list.len);
779 reftable_buf_release(&table_list);
780 if (err < 0) {
781 err = REFTABLE_IO_ERROR;
782 goto done;
783 }
784
785 err = fsync(add->tables_list_lock.fd);
786 if (err < 0) {
787 err = REFTABLE_IO_ERROR;
788 goto done;
789 }
790
791 err = flock_commit(&add->tables_list_lock);
792 if (err < 0) {
793 err = REFTABLE_IO_ERROR;
794 goto done;
795 }
796
797 /* success, no more state to clean up. */
798 for (i = 0; i < add->new_tables_len; i++)
799 reftable_free(add->new_tables[i]);
800 reftable_free(add->new_tables);
801 add->new_tables = NULL;
802 add->new_tables_len = 0;
803 add->new_tables_cap = 0;
804
805 err = reftable_stack_reload_maybe_reuse(add->stack, 1);
806 if (err)
807 goto done;
808
809 if (!add->opts.disable_auto_compact) {
810 /*
811 * Auto-compact the stack to keep the number of tables in
812 * control. It is possible that a concurrent writer is already
813 * trying to compact parts of the stack, which would lead to a
814 * `REFTABLE_LOCK_ERROR` because parts of the stack are locked
815 * already. Similarly, the stack may have been rewritten by a
816 * concurrent writer, which causes `REFTABLE_OUTDATED_ERROR`.
817 * Both of these errors are benign, so we simply ignore them.
818 */
819 err = reftable_stack_auto_compact(add->stack, &add->opts);
820 if (err < 0 && err != REFTABLE_LOCK_ERROR &&
821 err != REFTABLE_OUTDATED_ERROR)
822 goto done;
823 err = 0;
824 }
825
826 done:
827 reftable_addition_close(add);
828 return err;
829 }
830
831 int reftable_stack_addition_new(struct reftable_addition **dest,
832 struct reftable_stack *st,
833 const struct reftable_write_options *opts)
834 {
835 int err;
836
837 REFTABLE_CALLOC_ARRAY(*dest, 1);
838 if (!*dest)
839 return REFTABLE_OUT_OF_MEMORY_ERROR;
840
841 err = reftable_stack_init_addition(*dest, st, opts);
842 if (err) {
843 reftable_free(*dest);
844 *dest = NULL;
845 }
846
847 return err;
848 }
849
850 int reftable_addition_add(struct reftable_addition *add,
851 int (*write_table)(struct reftable_writer *wr,
852 void *arg),
853 void *arg)
854 {
855 struct reftable_buf temp_tab_file_name = REFTABLE_BUF_INIT;
856 struct reftable_buf tab_file_name = REFTABLE_BUF_INIT;
857 struct reftable_buf next_name = REFTABLE_BUF_INIT;
858 struct reftable_writer *wr = NULL;
859 struct reftable_tmpfile tab_file = REFTABLE_TMPFILE_INIT;
860 struct fd_writer writer = {
861 .opts = &add->opts,
862 };
863 int err = 0;
864
865 reftable_buf_reset(&next_name);
866
867 err = format_name(&next_name, add->next_update_index, add->next_update_index);
868 if (err < 0)
869 goto done;
870
871 err = stack_filename(&temp_tab_file_name, add->stack, next_name.buf);
872 if (err < 0)
873 goto done;
874
875 err = reftable_buf_addstr(&temp_tab_file_name, ".temp.XXXXXX");
876 if (err < 0)
877 goto done;
878
879 err = tmpfile_from_pattern(&tab_file, temp_tab_file_name.buf);
880 if (err < 0)
881 goto done;
882 if (add->opts.default_permissions) {
883 if (chmod(tab_file.path,
884 add->opts.default_permissions)) {
885 err = REFTABLE_IO_ERROR;
886 goto done;
887 }
888 }
889
890 writer.fd = tab_file.fd;
891 err = reftable_writer_new(&wr, fd_writer_write, fd_writer_flush,
892 &writer, add->stack->opts.hash_id, &add->opts);
893 if (err < 0)
894 goto done;
895
896 err = write_table(wr, arg);
897 if (err < 0)
898 goto done;
899
900 err = reftable_writer_close(wr);
901 if (err == REFTABLE_EMPTY_TABLE_ERROR) {
902 err = 0;
903 goto done;
904 }
905 if (err < 0)
906 goto done;
907
908 err = tmpfile_close(&tab_file);
909 if (err < 0)
910 goto done;
911
912 if (wr->min_update_index < add->next_update_index) {
913 err = REFTABLE_API_ERROR;
914 goto done;
915 }
916
917 err = format_name(&next_name, wr->min_update_index, wr->max_update_index);
918 if (err < 0)
919 goto done;
920
921 err = reftable_buf_addstr(&next_name, ".ref");
922 if (err < 0)
923 goto done;
924
925 err = stack_filename(&tab_file_name, add->stack, next_name.buf);
926 if (err < 0)
927 goto done;
928
929 /*
930 On windows, this relies on rand() picking a unique destination name.
931 Maybe we should do retry loop as well?
932 */
933 err = tmpfile_rename(&tab_file, tab_file_name.buf);
934 if (err < 0)
935 goto done;
936
937 REFTABLE_ALLOC_GROW_OR_NULL(add->new_tables, add->new_tables_len + 1,
938 add->new_tables_cap);
939 if (!add->new_tables) {
940 err = REFTABLE_OUT_OF_MEMORY_ERROR;
941 goto done;
942 }
943 add->new_tables[add->new_tables_len++] = reftable_buf_detach(&next_name);
944
945 done:
946 tmpfile_delete(&tab_file);
947 reftable_buf_release(&temp_tab_file_name);
948 reftable_buf_release(&tab_file_name);
949 reftable_buf_release(&next_name);
950 reftable_writer_free(wr);
951 return err;
952 }
953
954 uint64_t reftable_stack_next_update_index(struct reftable_stack *st)
955 {
956 int sz = st->merged->tables_len;
957 if (sz > 0)
958 return reftable_table_max_update_index(st->tables[sz - 1]) +
959 1;
960 return 1;
961 }
962
963 static int stack_write_compact(struct reftable_stack *st,
964 struct reftable_writer *wr,
965 size_t first, size_t last,
966 struct reftable_log_expiry_config *config)
967 {
968 struct reftable_merged_table *mt = NULL;
969 struct reftable_iterator it = { NULL };
970 struct reftable_ref_record ref = { NULL };
971 struct reftable_log_record log = { NULL };
972 size_t subtabs_len = last - first + 1;
973 uint64_t entries = 0;
974 int err = 0;
975
976 for (size_t i = first; i <= last; i++)
977 st->stats.bytes += st->tables[i]->size;
978 err = reftable_writer_set_limits(wr, st->tables[first]->min_update_index,
979 st->tables[last]->max_update_index);
980 if (err < 0)
981 goto done;
982
983 err = reftable_merged_table_new(&mt, st->tables + first, subtabs_len,
984 st->opts.hash_id);
985 if (err < 0)
986 goto done;
987
988 err = merged_table_init_iter(mt, &it, REFTABLE_BLOCK_TYPE_REF);
989 if (err < 0)
990 goto done;
991
992 err = reftable_iterator_seek_ref(&it, "");
993 if (err < 0)
994 goto done;
995
996 while (1) {
997 err = reftable_iterator_next_ref(&it, &ref);
998 if (err > 0) {
999 err = 0;
1000 break;
1001 }
1002 if (err < 0)
1003 goto done;
1004
1005 if (first == 0 && reftable_ref_record_is_deletion(&ref)) {
1006 continue;
1007 }
1008
1009 err = reftable_writer_add_ref(wr, &ref);
1010 if (err < 0)
1011 goto done;
1012 entries++;
1013 }
1014 reftable_iterator_destroy(&it);
1015
1016 err = merged_table_init_iter(mt, &it, REFTABLE_BLOCK_TYPE_LOG);
1017 if (err < 0)
1018 goto done;
1019
1020 err = reftable_iterator_seek_log(&it, "");
1021 if (err < 0)
1022 goto done;
1023
1024 while (1) {
1025 err = reftable_iterator_next_log(&it, &log);
1026 if (err > 0) {
1027 err = 0;
1028 break;
1029 }
1030 if (err < 0)
1031 goto done;
1032 if (first == 0 && reftable_log_record_is_deletion(&log)) {
1033 continue;
1034 }
1035
1036 if (config && config->min_update_index > 0 &&
1037 log.update_index < config->min_update_index) {
1038 continue;
1039 }
1040
1041 if (config && config->time > 0 &&
1042 log.value.update.time < config->time) {
1043 continue;
1044 }
1045
1046 err = reftable_writer_add_log(wr, &log);
1047 if (err < 0)
1048 goto done;
1049 entries++;
1050 }
1051
1052 done:
1053 reftable_iterator_destroy(&it);
1054 if (mt)
1055 reftable_merged_table_free(mt);
1056 reftable_ref_record_release(&ref);
1057 reftable_log_record_release(&log);
1058 st->stats.entries_written += entries;
1059 return err;
1060 }
1061
1062 static int stack_compact_locked(struct reftable_stack *st,
1063 size_t first, size_t last,
1064 struct reftable_log_expiry_config *config,
1065 const struct reftable_write_options *opts,
1066 struct reftable_tmpfile *tab_file_out)
1067 {
1068 struct reftable_buf next_name = REFTABLE_BUF_INIT;
1069 struct reftable_buf tab_file_path = REFTABLE_BUF_INIT;
1070 struct reftable_writer *wr = NULL;
1071 struct fd_writer writer= {
1072 .opts = opts,
1073 };
1074 struct reftable_tmpfile tab_file = REFTABLE_TMPFILE_INIT;
1075 int err = 0;
1076
1077 err = format_name(&next_name, reftable_table_min_update_index(st->tables[first]),
1078 reftable_table_max_update_index(st->tables[last]));
1079 if (err < 0)
1080 goto done;
1081
1082 err = stack_filename(&tab_file_path, st, next_name.buf);
1083 if (err < 0)
1084 goto done;
1085
1086 err = reftable_buf_addstr(&tab_file_path, ".temp.XXXXXX");
1087 if (err < 0)
1088 goto done;
1089
1090 err = tmpfile_from_pattern(&tab_file, tab_file_path.buf);
1091 if (err < 0)
1092 goto done;
1093
1094 if (opts->default_permissions &&
1095 chmod(tab_file.path, opts->default_permissions) < 0) {
1096 err = REFTABLE_IO_ERROR;
1097 goto done;
1098 }
1099
1100 writer.fd = tab_file.fd;
1101 err = reftable_writer_new(&wr, fd_writer_write, fd_writer_flush,
1102 &writer, st->opts.hash_id, opts);
1103 if (err < 0)
1104 goto done;
1105
1106 err = stack_write_compact(st, wr, first, last, config);
1107 if (err < 0)
1108 goto done;
1109
1110 err = reftable_writer_close(wr);
1111 if (err < 0)
1112 goto done;
1113
1114 err = tmpfile_close(&tab_file);
1115 if (err < 0)
1116 goto done;
1117
1118 *tab_file_out = tab_file;
1119 tab_file = REFTABLE_TMPFILE_INIT;
1120
1121 done:
1122 tmpfile_delete(&tab_file);
1123 reftable_writer_free(wr);
1124 reftable_buf_release(&next_name);
1125 reftable_buf_release(&tab_file_path);
1126 return err;
1127 }
1128
1129 enum stack_compact_range_flags {
1130 /*
1131 * Perform a best-effort compaction. That is, even if we cannot lock
1132 * all tables in the specified range, we will try to compact the
1133 * remaining slice.
1134 */
1135 STACK_COMPACT_RANGE_BEST_EFFORT = (1 << 0),
1136 };
1137
1138 /*
1139 * Compact all tables in the range `[first, last)` into a single new table.
1140 *
1141 * This function returns `0` on success or a code `< 0` on failure. When the
1142 * stack or any of the tables in the specified range are already locked then
1143 * this function returns `REFTABLE_LOCK_ERROR`. This is a benign error that
1144 * callers can either ignore, or they may choose to retry compaction after some
1145 * amount of time.
1146 */
1147 static int stack_compact_range(struct reftable_stack *st,
1148 size_t first, size_t last,
1149 struct reftable_log_expiry_config *expiry,
1150 const struct reftable_write_options *opts,
1151 unsigned int flags)
1152 {
1153 struct reftable_buf tables_list_buf = REFTABLE_BUF_INIT;
1154 struct reftable_buf new_table_name = REFTABLE_BUF_INIT;
1155 struct reftable_buf new_table_path = REFTABLE_BUF_INIT;
1156 struct reftable_buf table_name = REFTABLE_BUF_INIT;
1157 struct reftable_flock tables_list_lock = REFTABLE_FLOCK_INIT;
1158 struct reftable_flock *table_locks = NULL;
1159 struct reftable_tmpfile new_table = REFTABLE_TMPFILE_INIT;
1160 int is_empty_table = 0, err = 0;
1161 size_t first_to_replace, last_to_replace;
1162 size_t i, nlocks = 0;
1163 char **names = NULL;
1164
1165 if (first > last || (!expiry && first == last)) {
1166 err = 0;
1167 goto done;
1168 }
1169
1170 st->stats.attempts++;
1171
1172 /*
1173 * Hold the lock so that we can read "tables.list" and lock all tables
1174 * which are part of the user-specified range.
1175 */
1176 err = flock_acquire(&tables_list_lock, st->list_file, opts->lock_timeout_ms);
1177 if (err < 0)
1178 goto done;
1179
1180 /*
1181 * Check whether the stack is up-to-date. We unfortunately cannot
1182 * handle the situation gracefully in case it's _not_ up-to-date
1183 * because the range of tables that the user has requested us to
1184 * compact may have been changed. So instead we abort.
1185 *
1186 * We could in theory improve the situation by having the caller not
1187 * pass in a range, but instead the list of tables to compact. If so,
1188 * we could check that relevant tables still exist. But for now it's
1189 * good enough to just abort.
1190 */
1191 err = stack_uptodate(st);
1192 if (err < 0)
1193 goto done;
1194 if (err > 0) {
1195 err = REFTABLE_OUTDATED_ERROR;
1196 goto done;
1197 }
1198
1199 /*
1200 * Lock all tables in the user-provided range. This is the slice of our
1201 * stack which we'll compact.
1202 *
1203 * Note that we lock tables in reverse order from last to first. The
1204 * intent behind this is to allow a newer process to perform best
1205 * effort compaction of tables that it has added in the case where an
1206 * older process is still busy compacting tables which are preexisting
1207 * from the point of view of the newer process.
1208 */
1209 REFTABLE_ALLOC_ARRAY(table_locks, last - first + 1);
1210 if (!table_locks) {
1211 err = REFTABLE_OUT_OF_MEMORY_ERROR;
1212 goto done;
1213 }
1214 for (i = 0; i < last - first + 1; i++)
1215 table_locks[i] = REFTABLE_FLOCK_INIT;
1216
1217 for (i = last + 1; i > first; i--) {
1218 err = stack_filename(&table_name, st, reftable_table_name(st->tables[i - 1]));
1219 if (err < 0)
1220 goto done;
1221
1222 err = flock_acquire(&table_locks[nlocks], table_name.buf, 0);
1223 if (err < 0) {
1224 /*
1225 * When the table is locked already we may do a
1226 * best-effort compaction and compact only the tables
1227 * that we have managed to lock so far. This of course
1228 * requires that we have been able to lock at least two
1229 * tables, otherwise there would be nothing to compact.
1230 * In that case, we return a lock error to our caller.
1231 */
1232 if (err == REFTABLE_LOCK_ERROR && last - (i - 1) >= 2 &&
1233 flags & STACK_COMPACT_RANGE_BEST_EFFORT) {
1234 err = 0;
1235 /*
1236 * The subtraction is to offset the index, the
1237 * addition is to only compact up to the table
1238 * of the preceding iteration. They obviously
1239 * cancel each other out, but that may be
1240 * non-obvious when it was omitted.
1241 */
1242 first = (i - 1) + 1;
1243 break;
1244 }
1245
1246 goto done;
1247 }
1248
1249 /*
1250 * We need to close the lockfiles as we might otherwise easily
1251 * run into file descriptor exhaustion when we compress a lot
1252 * of tables.
1253 */
1254 err = flock_close(&table_locks[nlocks++]);
1255 if (err < 0)
1256 goto done;
1257 }
1258
1259 /*
1260 * We have locked all tables in our range and can thus release the
1261 * "tables.list" lock while compacting the locked tables. This allows
1262 * concurrent updates to the stack to proceed.
1263 */
1264 err = flock_release(&tables_list_lock);
1265 if (err < 0) {
1266 err = REFTABLE_IO_ERROR;
1267 goto done;
1268 }
1269
1270 /*
1271 * Compact the now-locked tables into a new table. Note that compacting
1272 * these tables may end up with an empty new table in case tombstones
1273 * end up cancelling out all refs in that range.
1274 */
1275 err = stack_compact_locked(st, first, last, expiry, opts, &new_table);
1276 if (err < 0) {
1277 if (err != REFTABLE_EMPTY_TABLE_ERROR)
1278 goto done;
1279 is_empty_table = 1;
1280 }
1281
1282 /*
1283 * Now that we have written the new, compacted table we need to re-lock
1284 * "tables.list". We'll then replace the compacted range of tables with
1285 * the new table.
1286 */
1287 err = flock_acquire(&tables_list_lock, st->list_file, opts->lock_timeout_ms);
1288 if (err < 0)
1289 goto done;
1290
1291 if (opts->default_permissions) {
1292 if (chmod(tables_list_lock.path,
1293 opts->default_permissions) < 0) {
1294 err = REFTABLE_IO_ERROR;
1295 goto done;
1296 }
1297 }
1298
1299 /*
1300 * As we have unlocked the stack while compacting our slice of tables
1301 * it may have happened that a concurrently running process has updated
1302 * the stack while we were compacting. In that case, we need to check
1303 * whether the tables that we have just compacted still exist in the
1304 * stack in the exact same order as we have compacted them.
1305 *
1306 * If they do exist, then it is fine to continue and replace those
1307 * tables with our compacted version. If they don't, then we need to
1308 * abort.
1309 */
1310 err = stack_uptodate(st);
1311 if (err < 0)
1312 goto done;
1313 if (err > 0) {
1314 ssize_t new_offset = -1;
1315 int fd;
1316
1317 fd = open(st->list_file, O_RDONLY);
1318 if (fd < 0) {
1319 err = REFTABLE_IO_ERROR;
1320 goto done;
1321 }
1322
1323 err = fd_read_lines(fd, &names);
1324 close(fd);
1325 if (err < 0)
1326 goto done;
1327
1328 /*
1329 * Search for the offset of the first table that we have
1330 * compacted in the updated "tables.list" file.
1331 */
1332 for (size_t i = 0; names[i]; i++) {
1333 if (strcmp(names[i], st->tables[first]->name))
1334 continue;
1335
1336 /*
1337 * We have found the first entry. Verify that all the
1338 * subsequent tables we have compacted still exist in
1339 * the modified stack in the exact same order as we
1340 * have compacted them.
1341 */
1342 for (size_t j = 1; j < last - first + 1; j++) {
1343 const char *old = first + j < st->merged->tables_len ?
1344 st->tables[first + j]->name : NULL;
1345 const char *new = names[i + j];
1346
1347 /*
1348 * If some entries are missing or in case the tables
1349 * have changed then we need to bail out. Again, this
1350 * shouldn't ever happen because we have locked the
1351 * tables we are compacting.
1352 */
1353 if (!old || !new || strcmp(old, new)) {
1354 err = REFTABLE_OUTDATED_ERROR;
1355 goto done;
1356 }
1357 }
1358
1359 new_offset = i;
1360 break;
1361 }
1362
1363 /*
1364 * In case we didn't find our compacted tables in the stack we
1365 * need to bail out. In theory, this should have never happened
1366 * because we locked the tables we are compacting.
1367 */
1368 if (new_offset < 0) {
1369 err = REFTABLE_OUTDATED_ERROR;
1370 goto done;
1371 }
1372
1373 /*
1374 * We have found the new range that we want to replace, so
1375 * let's update the range of tables that we want to replace.
1376 */
1377 first_to_replace = new_offset;
1378 last_to_replace = last + (new_offset - first);
1379 } else {
1380 /*
1381 * `fd_read_lines()` uses a `NULL` sentinel to indicate that
1382 * the array is at its end. As we use `free_names()` to free
1383 * the array, we need to include this sentinel value here and
1384 * thus have to allocate `tables_len + 1` many entries.
1385 */
1386 REFTABLE_CALLOC_ARRAY(names, st->merged->tables_len + 1);
1387 if (!names) {
1388 err = REFTABLE_OUT_OF_MEMORY_ERROR;
1389 goto done;
1390 }
1391
1392 for (size_t i = 0; i < st->merged->tables_len; i++) {
1393 names[i] = reftable_strdup(st->tables[i]->name);
1394 if (!names[i]) {
1395 err = REFTABLE_OUT_OF_MEMORY_ERROR;
1396 goto done;
1397 }
1398 }
1399 first_to_replace = first;
1400 last_to_replace = last;
1401 }
1402
1403 /*
1404 * If the resulting compacted table is not empty, then we need to move
1405 * it into place now.
1406 */
1407 if (!is_empty_table) {
1408 err = format_name(&new_table_name, st->tables[first]->min_update_index,
1409 st->tables[last]->max_update_index);
1410 if (err < 0)
1411 goto done;
1412
1413 err = reftable_buf_addstr(&new_table_name, ".ref");
1414 if (err < 0)
1415 goto done;
1416
1417 err = stack_filename(&new_table_path, st, new_table_name.buf);
1418 if (err < 0)
1419 goto done;
1420
1421 err = tmpfile_rename(&new_table, new_table_path.buf);
1422 if (err < 0)
1423 goto done;
1424 }
1425
1426 /*
1427 * Write the new "tables.list" contents with the compacted table we
1428 * have just written. In case the compacted table became empty we
1429 * simply skip writing it.
1430 */
1431 for (i = 0; i < first_to_replace; i++) {
1432 if ((err = reftable_buf_addstr(&tables_list_buf, names[i])) < 0 ||
1433 (err = reftable_buf_addstr(&tables_list_buf, "\n")) < 0)
1434 goto done;
1435 }
1436 if (!is_empty_table) {
1437 if ((err = reftable_buf_addstr(&tables_list_buf, new_table_name.buf)) < 0 ||
1438 (err = reftable_buf_addstr(&tables_list_buf, "\n")) < 0)
1439 goto done;
1440 }
1441 for (i = last_to_replace + 1; names[i]; i++) {
1442 if ((err = reftable_buf_addstr(&tables_list_buf, names[i])) < 0 ||
1443 (err = reftable_buf_addstr(&tables_list_buf, "\n")) < 0)
1444 goto done;
1445 }
1446
1447 err = reftable_write_data(tables_list_lock.fd,
1448 tables_list_buf.buf, tables_list_buf.len);
1449 if (err < 0) {
1450 err = REFTABLE_IO_ERROR;
1451 unlink(new_table_path.buf);
1452 goto done;
1453 }
1454
1455 err = fsync(tables_list_lock.fd);
1456 if (err < 0) {
1457 err = REFTABLE_IO_ERROR;
1458 unlink(new_table_path.buf);
1459 goto done;
1460 }
1461
1462 err = flock_commit(&tables_list_lock);
1463 if (err < 0) {
1464 err = REFTABLE_IO_ERROR;
1465 unlink(new_table_path.buf);
1466 goto done;
1467 }
1468
1469 /*
1470 * Reload the stack before deleting the compacted tables. We can only
1471 * delete the files after we closed them on Windows, so this needs to
1472 * happen first.
1473 */
1474 err = reftable_stack_reload_maybe_reuse(st, first < last);
1475 if (err < 0)
1476 goto done;
1477
1478 /*
1479 * Delete the old tables. They may still be in use by concurrent
1480 * readers, so it is expected that unlinking tables may fail.
1481 */
1482 for (i = 0; i < nlocks; i++) {
1483 struct reftable_flock *table_lock = &table_locks[i];
1484
1485 reftable_buf_reset(&table_name);
1486 err = reftable_buf_add(&table_name, table_lock->path,
1487 strlen(table_lock->path) - strlen(".lock"));
1488 if (err)
1489 continue;
1490
1491 unlink(table_name.buf);
1492 }
1493
1494 done:
1495 flock_release(&tables_list_lock);
1496 for (i = 0; table_locks && i < nlocks; i++)
1497 flock_release(&table_locks[i]);
1498 reftable_free(table_locks);
1499
1500 tmpfile_delete(&new_table);
1501 reftable_buf_release(&new_table_name);
1502 reftable_buf_release(&new_table_path);
1503 reftable_buf_release(&tables_list_buf);
1504 reftable_buf_release(&table_name);
1505 free_names(names);
1506
1507 if (err == REFTABLE_LOCK_ERROR)
1508 st->stats.failures++;
1509
1510 return err;
1511 }
1512
1513 int reftable_stack_compact_all(struct reftable_stack *st,
1514 const struct reftable_write_options *opts,
1515 struct reftable_log_expiry_config *config)
1516 {
1517 struct reftable_write_options opts_default = { 0 };
1518 size_t last = st->merged->tables_len ? st->merged->tables_len - 1 : 0;
1519
1520 if (!opts)
1521 opts = &opts_default;
1522
1523 return stack_compact_range(st, 0, last, config, opts, 0);
1524 }
1525
1526 static int segment_size(struct segment *s)
1527 {
1528 return s->end - s->start;
1529 }
1530
1531 struct segment suggest_compaction_segment(uint64_t *sizes, size_t n,
1532 uint8_t factor)
1533 {
1534 struct segment seg = { 0 };
1535 uint64_t bytes;
1536 size_t i;
1537
1538 if (!factor)
1539 factor = DEFAULT_GEOMETRIC_FACTOR;
1540
1541 /*
1542 * If there are no tables or only a single one then we don't have to
1543 * compact anything. The sequence is geometric by definition already.
1544 */
1545 if (n <= 1)
1546 return seg;
1547
1548 /*
1549 * Find the ending table of the compaction segment needed to restore the
1550 * geometric sequence. Note that the segment end is exclusive.
1551 *
1552 * To do so, we iterate backwards starting from the most recent table
1553 * until a valid segment end is found. If the preceding table is smaller
1554 * than the current table multiplied by the geometric factor (2), the
1555 * compaction segment end has been identified.
1556 *
1557 * Tables after the ending point are not added to the byte count because
1558 * they are already valid members of the geometric sequence. Due to the
1559 * properties of a geometric sequence, it is not possible for the sum of
1560 * these tables to exceed the value of the ending point table.
1561 *
1562 * Example table size sequence requiring no compaction:
1563 * 64, 32, 16, 8, 4, 2, 1
1564 *
1565 * Example table size sequence where compaction segment end is set to
1566 * the last table. Since the segment end is exclusive, the last table is
1567 * excluded during subsequent compaction and the table with size 3 is
1568 * the final table included:
1569 * 64, 32, 16, 8, 4, 3, 1
1570 */
1571 for (i = n - 1; i > 0; i--) {
1572 if (sizes[i - 1] < sizes[i] * factor) {
1573 seg.end = i + 1;
1574 bytes = sizes[i];
1575 break;
1576 }
1577 }
1578
1579 /*
1580 * Find the starting table of the compaction segment by iterating
1581 * through the remaining tables and keeping track of the accumulated
1582 * size of all tables seen from the segment end table. The previous
1583 * table is compared to the accumulated size because the tables from the
1584 * segment end are merged backwards recursively.
1585 *
1586 * Note that we keep iterating even after we have found the first
1587 * starting point. This is because there may be tables in the stack
1588 * preceding that first starting point which violate the geometric
1589 * sequence.
1590 *
1591 * Example compaction segment start set to table with size 32:
1592 * 128, 32, 16, 8, 4, 3, 1
1593 */
1594 for (; i > 0; i--) {
1595 uint64_t curr = bytes;
1596 bytes += sizes[i - 1];
1597
1598 if (sizes[i - 1] < curr * factor) {
1599 seg.start = i - 1;
1600 seg.bytes = bytes;
1601 }
1602 }
1603
1604 return seg;
1605 }
1606
1607 static int stack_segments_for_compaction(struct reftable_stack *st,
1608 const struct reftable_write_options *opts,
1609 struct segment *seg)
1610 {
1611 int version = (st->opts.hash_id == REFTABLE_HASH_SHA1) ? 1 : 2;
1612 int overhead = header_size(version) - 1;
1613 uint64_t *sizes;
1614
1615 REFTABLE_CALLOC_ARRAY(sizes, st->merged->tables_len);
1616 if (!sizes)
1617 return REFTABLE_OUT_OF_MEMORY_ERROR;
1618
1619 for (size_t i = 0; i < st->merged->tables_len; i++)
1620 sizes[i] = st->tables[i]->size - overhead;
1621
1622 *seg = suggest_compaction_segment(sizes, st->merged->tables_len,
1623 opts->auto_compaction_factor);
1624 reftable_free(sizes);
1625
1626 return 0;
1627 }
1628
1629 static int update_segment_if_compaction_required(struct reftable_stack *st,
1630 const struct reftable_write_options *opts,
1631 struct segment *seg,
1632 bool use_geometric,
1633 bool *required)
1634 {
1635 int err;
1636
1637 if (st->merged->tables_len < 2) {
1638 *required = false;
1639 return 0;
1640 }
1641
1642 if (!use_geometric) {
1643 *required = true;
1644 return 0;
1645 }
1646
1647 err = stack_segments_for_compaction(st, opts, seg);
1648 if (err)
1649 return err;
1650
1651 *required = segment_size(seg) > 0;
1652 return 0;
1653 }
1654
1655 int reftable_stack_compaction_required(struct reftable_stack *st,
1656 const struct reftable_write_options *opts,
1657 bool use_heuristics,
1658 bool *required)
1659 {
1660 struct reftable_write_options opts_default = { 0 };
1661 struct segment seg;
1662
1663 if (!opts)
1664 opts = &opts_default;
1665
1666 return update_segment_if_compaction_required(st, opts, &seg,
1667 use_heuristics, required);
1668 }
1669
1670 int reftable_stack_auto_compact(struct reftable_stack *st,
1671 const struct reftable_write_options *opts)
1672 {
1673 struct reftable_write_options opts_default = { 0 };
1674 struct segment seg;
1675 bool required;
1676 int err;
1677
1678 if (!opts)
1679 opts = &opts_default;
1680
1681 err = update_segment_if_compaction_required(st, opts, &seg, true,
1682 &required);
1683 if (err)
1684 return err;
1685
1686 if (required)
1687 return stack_compact_range(st, seg.start, seg.end - 1,
1688 NULL, opts,
1689 STACK_COMPACT_RANGE_BEST_EFFORT);
1690
1691 return 0;
1692 }
1693
1694 struct reftable_compaction_stats *
1695 reftable_stack_compaction_stats(struct reftable_stack *st)
1696 {
1697 return &st->stats;
1698 }
1699
1700 int reftable_stack_read_ref(struct reftable_stack *st, const char *refname,
1701 struct reftable_ref_record *ref)
1702 {
1703 struct reftable_iterator it = { 0 };
1704 int ret;
1705
1706 ret = reftable_merged_table_init_ref_iterator(st->merged, &it);
1707 if (ret)
1708 goto out;
1709
1710 ret = reftable_iterator_seek_ref(&it, refname);
1711 if (ret)
1712 goto out;
1713
1714 ret = reftable_iterator_next_ref(&it, ref);
1715 if (ret)
1716 goto out;
1717
1718 if (strcmp(ref->refname, refname) ||
1719 reftable_ref_record_is_deletion(ref)) {
1720 reftable_ref_record_release(ref);
1721 ret = 1;
1722 goto out;
1723 }
1724
1725 out:
1726 reftable_iterator_destroy(&it);
1727 return ret;
1728 }
1729
1730 int reftable_stack_read_log(struct reftable_stack *st, const char *refname,
1731 struct reftable_log_record *log)
1732 {
1733 struct reftable_iterator it = {0};
1734 int err;
1735
1736 err = reftable_stack_init_log_iterator(st, &it);
1737 if (err)
1738 goto done;
1739
1740 err = reftable_iterator_seek_log(&it, refname);
1741 if (err)
1742 goto done;
1743
1744 err = reftable_iterator_next_log(&it, log);
1745 if (err)
1746 goto done;
1747
1748 if (strcmp(log->refname, refname) ||
1749 reftable_log_record_is_deletion(log)) {
1750 err = 1;
1751 goto done;
1752 }
1753
1754 done:
1755 if (err) {
1756 reftable_log_record_release(log);
1757 }
1758 reftable_iterator_destroy(&it);
1759 return err;
1760 }
1761
1762 static int is_table_name(const char *s)
1763 {
1764 const char *dot = strrchr(s, '.');
1765 return dot && !strcmp(dot, ".ref");
1766 }
1767
1768 static void remove_maybe_stale_table(struct reftable_stack *st, uint64_t max,
1769 const char *name)
1770 {
1771 int err = 0;
1772 uint64_t update_idx = 0;
1773 struct reftable_block_source src = { NULL };
1774 struct reftable_table *table = NULL;
1775 struct reftable_buf table_path = REFTABLE_BUF_INIT;
1776
1777 err = stack_filename(&table_path, st, name);
1778 if (err < 0)
1779 goto done;
1780
1781 err = reftable_block_source_from_file(&src, table_path.buf);
1782 if (err < 0)
1783 goto done;
1784
1785 err = reftable_table_new(&table, &src, name);
1786 if (err < 0)
1787 goto done;
1788
1789 update_idx = reftable_table_max_update_index(table);
1790 reftable_table_decref(table);
1791
1792 if (update_idx <= max) {
1793 unlink(table_path.buf);
1794 }
1795 done:
1796 reftable_buf_release(&table_path);
1797 }
1798
1799 static int reftable_stack_clean_locked(struct reftable_stack *st)
1800 {
1801 uint64_t max = reftable_merged_table_max_update_index(
1802 reftable_stack_merged_table(st));
1803 DIR *dir = opendir(st->reftable_dir);
1804 struct dirent *d = NULL;
1805 if (!dir) {
1806 return REFTABLE_IO_ERROR;
1807 }
1808
1809 while ((d = readdir(dir))) {
1810 int found = 0;
1811 if (!is_table_name(d->d_name))
1812 continue;
1813
1814 for (size_t i = 0; !found && i < st->tables_len; i++)
1815 found = !strcmp(reftable_table_name(st->tables[i]), d->d_name);
1816 if (found)
1817 continue;
1818
1819 remove_maybe_stale_table(st, max, d->d_name);
1820 }
1821
1822 closedir(dir);
1823 return 0;
1824 }
1825
1826 int reftable_stack_clean(struct reftable_stack *st)
1827 {
1828 struct reftable_addition *add = NULL;
1829 int err = reftable_stack_addition_new(&add, st, NULL);
1830 if (err < 0) {
1831 goto done;
1832 }
1833
1834 err = reftable_stack_clean_locked(st);
1835
1836 done:
1837 reftable_addition_destroy(add);
1838 return err;
1839 }
1840
1841 enum reftable_hash reftable_stack_hash_id(struct reftable_stack *st)
1842 {
1843 return reftable_merged_table_hash_id(st->merged);
1844 }