at commit 654567cf

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 p->list_lock = REFTABLE_FLOCK_INIT;
540
541 err = reftable_stack_reload_maybe_reuse(p, 1);
542 if (err < 0)
543 goto out;
544
545 *dest = p;
546 err = 0;
547
548 out:
549 if (err < 0)
550 reftable_stack_destroy(p);
551 return err;
552 }
553
554 /*
555 * Check whether the given stack is up-to-date with what we have in memory.
556 * Returns 0 if so, 1 if the stack is out-of-date or a negative error code
557 * otherwise.
558 */
559 static int stack_uptodate(struct reftable_stack *st)
560 {
561 char **names = NULL;
562 int err;
563
564 /*
565 * When we have cached stat information available then we use it to
566 * verify whether the file has been rewritten.
567 *
568 * Note that we explicitly do not want to use `stat_validity_check()`
569 * and friends here because they may end up not comparing the `st_dev`
570 * and `st_ino` fields. These functions thus cannot guarantee that we
571 * indeed still have the same file.
572 */
573 if (st->list_fd >= 0) {
574 struct stat list_st;
575
576 if (stat(st->list_file, &list_st) < 0) {
577 /*
578 * It's fine for "tables.list" to not exist. In that
579 * case, we have to refresh when the loaded stack has
580 * any tables.
581 */
582 if (errno == ENOENT)
583 return !!st->tables_len;
584 return REFTABLE_IO_ERROR;
585 }
586
587 /*
588 * When "tables.list" refers to the same file we can assume
589 * that it didn't change. This is because we always use
590 * rename(3P) to update the file and never write to it
591 * directly.
592 */
593 if (st->list_st.st_dev == list_st.st_dev &&
594 st->list_st.st_ino == list_st.st_ino)
595 return 0;
596 }
597
598 err = read_lines(st->list_file, &names);
599 if (err < 0)
600 return err;
601
602 for (size_t i = 0; i < st->tables_len; i++) {
603 if (!names[i]) {
604 err = 1;
605 goto done;
606 }
607
608 if (strcmp(st->tables[i]->name, names[i])) {
609 err = 1;
610 goto done;
611 }
612 }
613
614 if (names[st->merged->tables_len]) {
615 err = 1;
616 goto done;
617 }
618
619 done:
620 free_names(names);
621 return err;
622 }
623
624 int reftable_stack_reload(struct reftable_stack *st)
625 {
626 int err = stack_uptodate(st);
627 if (err > 0)
628 return reftable_stack_reload_maybe_reuse(st, 1);
629 return err;
630 }
631
632 struct reftable_addition {
633 struct reftable_stack *stack;
634 struct reftable_write_options opts;
635
636 /*
637 * While the list lock is acquired on the stack, we need to distinguish
638 * which 'reftable_addition' is responsible for the lock. This avoids
639 * clearing the lock of another 'reftable_addition'.
640 */
641 unsigned int locked : 1;
642
643 char **new_tables;
644 size_t new_tables_len, new_tables_cap;
645 uint64_t next_update_index;
646 };
647
648 static void reftable_addition_close(struct reftable_addition *add)
649 {
650 struct reftable_buf nm = REFTABLE_BUF_INIT;
651 size_t i;
652
653 for (i = 0; i < add->new_tables_len; i++) {
654 if (!stack_filename(&nm, add->stack, add->new_tables[i]))
655 unlink(nm.buf);
656 reftable_free(add->new_tables[i]);
657 add->new_tables[i] = NULL;
658 }
659 reftable_free(add->new_tables);
660 add->new_tables = NULL;
661 add->new_tables_len = 0;
662 add->new_tables_cap = 0;
663
664 if (add->locked)
665 flock_release(&add->stack->list_lock);
666 add->locked = 0;
667 reftable_buf_release(&nm);
668 }
669
670 static int reftable_stack_init_addition(struct reftable_addition *add,
671 struct reftable_stack *st,
672 const struct reftable_write_options *opts)
673 {
674 struct reftable_buf lock_file_name = REFTABLE_BUF_INIT;
675 int err;
676
677 memset(add, 0, sizeof(*add));
678 add->stack = st;
679 if (opts)
680 add->opts = *opts;
681
682 err = flock_acquire(&add->stack->list_lock, st->list_file,
683 add->opts.lock_timeout_ms);
684 if (err < 0)
685 goto done;
686 add->locked = 1;
687
688 if (add->opts.default_permissions) {
689 if (chmod(add->stack->list_lock.path,
690 add->opts.default_permissions) < 0) {
691 err = REFTABLE_IO_ERROR;
692 goto done;
693 }
694 }
695
696 err = stack_uptodate(st);
697 if (err < 0)
698 goto done;
699 if (err > 0) {
700 err = reftable_stack_reload_maybe_reuse(add->stack, 1);
701 if (err)
702 goto done;
703 }
704
705 add->next_update_index = reftable_stack_next_update_index(st);
706 done:
707 if (err)
708 reftable_addition_close(add);
709 reftable_buf_release(&lock_file_name);
710 return err;
711 }
712
713 static int stack_try_add(struct reftable_stack *st,
714 int (*write_table)(struct reftable_writer *wr,
715 void *arg),
716 void *arg,
717 const struct reftable_write_options *opts)
718 {
719 struct reftable_addition add;
720 int err;
721
722 err = reftable_stack_init_addition(&add, st, opts);
723 if (err < 0)
724 goto done;
725
726 err = reftable_addition_add(&add, write_table, arg);
727 if (err < 0)
728 goto done;
729
730 err = reftable_addition_commit(&add);
731 done:
732 reftable_addition_close(&add);
733 return err;
734 }
735
736 int reftable_stack_add(struct reftable_stack *st,
737 int (*write)(struct reftable_writer *wr, void *arg),
738 void *arg,
739 const struct reftable_write_options *opts)
740 {
741 int err = stack_try_add(st, write, arg, opts);
742 if (err < 0) {
743 return err;
744 }
745
746 return 0;
747 }
748
749 static int format_name(struct reftable_buf *dest, uint64_t min, uint64_t max)
750 {
751 char buf[100];
752 uint32_t rnd = reftable_rand();
753 snprintf(buf, sizeof(buf), "0x%012" PRIx64 "-0x%012" PRIx64 "-%08x",
754 min, max, rnd);
755 reftable_buf_reset(dest);
756 return reftable_buf_addstr(dest, buf);
757 }
758
759 void reftable_addition_destroy(struct reftable_addition *add)
760 {
761 if (!add) {
762 return;
763 }
764 reftable_addition_close(add);
765 reftable_free(add);
766 }
767
768 int reftable_addition_commit(struct reftable_addition *add)
769 {
770 struct reftable_buf table_list = REFTABLE_BUF_INIT;
771 int err = 0;
772 size_t i;
773
774 if (add->new_tables_len == 0)
775 goto done;
776
777 for (i = 0; i < add->stack->merged->tables_len; i++) {
778 if ((err = reftable_buf_addstr(&table_list, add->stack->tables[i]->name)) < 0 ||
779 (err = reftable_buf_addstr(&table_list, "\n")) < 0)
780 goto done;
781 }
782 for (i = 0; i < add->new_tables_len; i++) {
783 if ((err = reftable_buf_addstr(&table_list, add->new_tables[i])) < 0 ||
784 (err = reftable_buf_addstr(&table_list, "\n")) < 0)
785 goto done;
786 }
787
788 err = reftable_write_data(add->stack->list_lock.fd,
789 table_list.buf, table_list.len);
790 reftable_buf_release(&table_list);
791 if (err < 0) {
792 err = REFTABLE_IO_ERROR;
793 goto done;
794 }
795
796 err = fsync(add->stack->list_lock.fd);
797 if (err < 0) {
798 err = REFTABLE_IO_ERROR;
799 goto done;
800 }
801
802 err = flock_commit(&add->stack->list_lock);
803 if (err < 0) {
804 err = REFTABLE_IO_ERROR;
805 goto done;
806 }
807 add->locked = 0;
808
809 /* success, no more state to clean up. */
810 for (i = 0; i < add->new_tables_len; i++)
811 reftable_free(add->new_tables[i]);
812 reftable_free(add->new_tables);
813 add->new_tables = NULL;
814 add->new_tables_len = 0;
815 add->new_tables_cap = 0;
816
817 err = reftable_stack_reload_maybe_reuse(add->stack, 1);
818 if (err)
819 goto done;
820
821 if (!add->opts.disable_auto_compact) {
822 /*
823 * Auto-compact the stack to keep the number of tables in
824 * control. It is possible that a concurrent writer is already
825 * trying to compact parts of the stack, which would lead to a
826 * `REFTABLE_LOCK_ERROR` because parts of the stack are locked
827 * already. Similarly, the stack may have been rewritten by a
828 * concurrent writer, which causes `REFTABLE_OUTDATED_ERROR`.
829 * Both of these errors are benign, so we simply ignore them.
830 */
831 err = reftable_stack_auto_compact(add->stack, &add->opts);
832 if (err < 0 && err != REFTABLE_LOCK_ERROR &&
833 err != REFTABLE_OUTDATED_ERROR)
834 goto done;
835 err = 0;
836 }
837
838 done:
839 reftable_addition_close(add);
840 return err;
841 }
842
843 int reftable_stack_addition_new(struct reftable_addition **dest,
844 struct reftable_stack *st,
845 const struct reftable_write_options *opts)
846 {
847 int err;
848
849 REFTABLE_CALLOC_ARRAY(*dest, 1);
850 if (!*dest)
851 return REFTABLE_OUT_OF_MEMORY_ERROR;
852
853 err = reftable_stack_init_addition(*dest, st, opts);
854 if (err) {
855 reftable_free(*dest);
856 *dest = NULL;
857 }
858
859 return err;
860 }
861
862 int reftable_addition_add(struct reftable_addition *add,
863 int (*write_table)(struct reftable_writer *wr,
864 void *arg),
865 void *arg)
866 {
867 struct reftable_buf temp_tab_file_name = REFTABLE_BUF_INIT;
868 struct reftable_buf tab_file_name = REFTABLE_BUF_INIT;
869 struct reftable_buf next_name = REFTABLE_BUF_INIT;
870 struct reftable_writer *wr = NULL;
871 struct reftable_tmpfile tab_file = REFTABLE_TMPFILE_INIT;
872 struct fd_writer writer = {
873 .opts = &add->opts,
874 };
875 int err = 0;
876
877 reftable_buf_reset(&next_name);
878
879 err = format_name(&next_name, add->next_update_index, add->next_update_index);
880 if (err < 0)
881 goto done;
882
883 err = stack_filename(&temp_tab_file_name, add->stack, next_name.buf);
884 if (err < 0)
885 goto done;
886
887 err = reftable_buf_addstr(&temp_tab_file_name, ".temp.XXXXXX");
888 if (err < 0)
889 goto done;
890
891 err = tmpfile_from_pattern(&tab_file, temp_tab_file_name.buf);
892 if (err < 0)
893 goto done;
894 if (add->opts.default_permissions) {
895 if (chmod(tab_file.path,
896 add->opts.default_permissions)) {
897 err = REFTABLE_IO_ERROR;
898 goto done;
899 }
900 }
901
902 writer.fd = tab_file.fd;
903 err = reftable_writer_new(&wr, fd_writer_write, fd_writer_flush,
904 &writer, add->stack->opts.hash_id, &add->opts);
905 if (err < 0)
906 goto done;
907
908 err = write_table(wr, arg);
909 if (err < 0)
910 goto done;
911
912 err = reftable_writer_close(wr);
913 if (err == REFTABLE_EMPTY_TABLE_ERROR) {
914 err = 0;
915 goto done;
916 }
917 if (err < 0)
918 goto done;
919
920 err = tmpfile_close(&tab_file);
921 if (err < 0)
922 goto done;
923
924 if (wr->min_update_index < add->next_update_index) {
925 err = REFTABLE_API_ERROR;
926 goto done;
927 }
928
929 err = format_name(&next_name, wr->min_update_index, wr->max_update_index);
930 if (err < 0)
931 goto done;
932
933 err = reftable_buf_addstr(&next_name, ".ref");
934 if (err < 0)
935 goto done;
936
937 err = stack_filename(&tab_file_name, add->stack, next_name.buf);
938 if (err < 0)
939 goto done;
940
941 /*
942 On windows, this relies on rand() picking a unique destination name.
943 Maybe we should do retry loop as well?
944 */
945 err = tmpfile_rename(&tab_file, tab_file_name.buf);
946 if (err < 0)
947 goto done;
948
949 REFTABLE_ALLOC_GROW_OR_NULL(add->new_tables, add->new_tables_len + 1,
950 add->new_tables_cap);
951 if (!add->new_tables) {
952 err = REFTABLE_OUT_OF_MEMORY_ERROR;
953 goto done;
954 }
955 add->new_tables[add->new_tables_len++] = reftable_buf_detach(&next_name);
956
957 done:
958 tmpfile_delete(&tab_file);
959 reftable_buf_release(&temp_tab_file_name);
960 reftable_buf_release(&tab_file_name);
961 reftable_buf_release(&next_name);
962 reftable_writer_free(wr);
963 return err;
964 }
965
966 uint64_t reftable_stack_next_update_index(struct reftable_stack *st)
967 {
968 int sz = st->merged->tables_len;
969 if (sz > 0)
970 return reftable_table_max_update_index(st->tables[sz - 1]) +
971 1;
972 return 1;
973 }
974
975 static int stack_write_compact(struct reftable_stack *st,
976 struct reftable_writer *wr,
977 size_t first, size_t last,
978 struct reftable_log_expiry_config *config)
979 {
980 struct reftable_merged_table *mt = NULL;
981 struct reftable_iterator it = { NULL };
982 struct reftable_ref_record ref = { NULL };
983 struct reftable_log_record log = { NULL };
984 size_t subtabs_len = last - first + 1;
985 uint64_t entries = 0;
986 int err = 0;
987
988 for (size_t i = first; i <= last; i++)
989 st->stats.bytes += st->tables[i]->size;
990 err = reftable_writer_set_limits(wr, st->tables[first]->min_update_index,
991 st->tables[last]->max_update_index);
992 if (err < 0)
993 goto done;
994
995 err = reftable_merged_table_new(&mt, st->tables + first, subtabs_len,
996 st->opts.hash_id);
997 if (err < 0)
998 goto done;
999
1000 err = merged_table_init_iter(mt, &it, REFTABLE_BLOCK_TYPE_REF);
1001 if (err < 0)
1002 goto done;
1003
1004 err = reftable_iterator_seek_ref(&it, "");
1005 if (err < 0)
1006 goto done;
1007
1008 while (1) {
1009 err = reftable_iterator_next_ref(&it, &ref);
1010 if (err > 0) {
1011 err = 0;
1012 break;
1013 }
1014 if (err < 0)
1015 goto done;
1016
1017 if (first == 0 && reftable_ref_record_is_deletion(&ref)) {
1018 continue;
1019 }
1020
1021 err = reftable_writer_add_ref(wr, &ref);
1022 if (err < 0)
1023 goto done;
1024 entries++;
1025 }
1026 reftable_iterator_destroy(&it);
1027
1028 err = merged_table_init_iter(mt, &it, REFTABLE_BLOCK_TYPE_LOG);
1029 if (err < 0)
1030 goto done;
1031
1032 err = reftable_iterator_seek_log(&it, "");
1033 if (err < 0)
1034 goto done;
1035
1036 while (1) {
1037 err = reftable_iterator_next_log(&it, &log);
1038 if (err > 0) {
1039 err = 0;
1040 break;
1041 }
1042 if (err < 0)
1043 goto done;
1044 if (first == 0 && reftable_log_record_is_deletion(&log)) {
1045 continue;
1046 }
1047
1048 if (config && config->min_update_index > 0 &&
1049 log.update_index < config->min_update_index) {
1050 continue;
1051 }
1052
1053 if (config && config->time > 0 &&
1054 log.value.update.time < config->time) {
1055 continue;
1056 }
1057
1058 err = reftable_writer_add_log(wr, &log);
1059 if (err < 0)
1060 goto done;
1061 entries++;
1062 }
1063
1064 done:
1065 reftable_iterator_destroy(&it);
1066 if (mt)
1067 reftable_merged_table_free(mt);
1068 reftable_ref_record_release(&ref);
1069 reftable_log_record_release(&log);
1070 st->stats.entries_written += entries;
1071 return err;
1072 }
1073
1074 static int stack_compact_locked(struct reftable_stack *st,
1075 size_t first, size_t last,
1076 struct reftable_log_expiry_config *config,
1077 const struct reftable_write_options *opts,
1078 struct reftable_tmpfile *tab_file_out)
1079 {
1080 struct reftable_buf next_name = REFTABLE_BUF_INIT;
1081 struct reftable_buf tab_file_path = REFTABLE_BUF_INIT;
1082 struct reftable_writer *wr = NULL;
1083 struct fd_writer writer= {
1084 .opts = opts,
1085 };
1086 struct reftable_tmpfile tab_file = REFTABLE_TMPFILE_INIT;
1087 int err = 0;
1088
1089 err = format_name(&next_name, reftable_table_min_update_index(st->tables[first]),
1090 reftable_table_max_update_index(st->tables[last]));
1091 if (err < 0)
1092 goto done;
1093
1094 err = stack_filename(&tab_file_path, st, next_name.buf);
1095 if (err < 0)
1096 goto done;
1097
1098 err = reftable_buf_addstr(&tab_file_path, ".temp.XXXXXX");
1099 if (err < 0)
1100 goto done;
1101
1102 err = tmpfile_from_pattern(&tab_file, tab_file_path.buf);
1103 if (err < 0)
1104 goto done;
1105
1106 if (opts->default_permissions &&
1107 chmod(tab_file.path, opts->default_permissions) < 0) {
1108 err = REFTABLE_IO_ERROR;
1109 goto done;
1110 }
1111
1112 writer.fd = tab_file.fd;
1113 err = reftable_writer_new(&wr, fd_writer_write, fd_writer_flush,
1114 &writer, st->opts.hash_id, opts);
1115 if (err < 0)
1116 goto done;
1117
1118 err = stack_write_compact(st, wr, first, last, config);
1119 if (err < 0)
1120 goto done;
1121
1122 err = reftable_writer_close(wr);
1123 if (err < 0)
1124 goto done;
1125
1126 err = tmpfile_close(&tab_file);
1127 if (err < 0)
1128 goto done;
1129
1130 *tab_file_out = tab_file;
1131 tab_file = REFTABLE_TMPFILE_INIT;
1132
1133 done:
1134 tmpfile_delete(&tab_file);
1135 reftable_writer_free(wr);
1136 reftable_buf_release(&next_name);
1137 reftable_buf_release(&tab_file_path);
1138 return err;
1139 }
1140
1141 enum stack_compact_range_flags {
1142 /*
1143 * Perform a best-effort compaction. That is, even if we cannot lock
1144 * all tables in the specified range, we will try to compact the
1145 * remaining slice.
1146 */
1147 STACK_COMPACT_RANGE_BEST_EFFORT = (1 << 0),
1148 };
1149
1150 /*
1151 * Compact all tables in the range `[first, last)` into a single new table.
1152 *
1153 * This function returns `0` on success or a code `< 0` on failure. When the
1154 * stack or any of the tables in the specified range are already locked then
1155 * this function returns `REFTABLE_LOCK_ERROR`. This is a benign error that
1156 * callers can either ignore, or they may choose to retry compaction after some
1157 * amount of time.
1158 */
1159 static int stack_compact_range(struct reftable_stack *st,
1160 size_t first, size_t last,
1161 struct reftable_log_expiry_config *expiry,
1162 const struct reftable_write_options *opts,
1163 unsigned int flags)
1164 {
1165 struct reftable_buf tables_list_buf = REFTABLE_BUF_INIT;
1166 struct reftable_buf new_table_name = REFTABLE_BUF_INIT;
1167 struct reftable_buf new_table_path = REFTABLE_BUF_INIT;
1168 struct reftable_buf table_name = REFTABLE_BUF_INIT;
1169 struct reftable_flock tables_list_lock = REFTABLE_FLOCK_INIT;
1170 struct reftable_flock *table_locks = NULL;
1171 struct reftable_tmpfile new_table = REFTABLE_TMPFILE_INIT;
1172 int is_empty_table = 0, err = 0;
1173 size_t first_to_replace, last_to_replace;
1174 size_t i, nlocks = 0;
1175 char **names = NULL;
1176
1177 if (first > last || (!expiry && first == last)) {
1178 err = 0;
1179 goto done;
1180 }
1181
1182 st->stats.attempts++;
1183
1184 /*
1185 * Hold the lock so that we can read "tables.list" and lock all tables
1186 * which are part of the user-specified range.
1187 */
1188 err = flock_acquire(&tables_list_lock, st->list_file, opts->lock_timeout_ms);
1189 if (err < 0)
1190 goto done;
1191
1192 /*
1193 * Check whether the stack is up-to-date. We unfortunately cannot
1194 * handle the situation gracefully in case it's _not_ up-to-date
1195 * because the range of tables that the user has requested us to
1196 * compact may have been changed. So instead we abort.
1197 *
1198 * We could in theory improve the situation by having the caller not
1199 * pass in a range, but instead the list of tables to compact. If so,
1200 * we could check that relevant tables still exist. But for now it's
1201 * good enough to just abort.
1202 */
1203 err = stack_uptodate(st);
1204 if (err < 0)
1205 goto done;
1206 if (err > 0) {
1207 err = REFTABLE_OUTDATED_ERROR;
1208 goto done;
1209 }
1210
1211 /*
1212 * Lock all tables in the user-provided range. This is the slice of our
1213 * stack which we'll compact.
1214 *
1215 * Note that we lock tables in reverse order from last to first. The
1216 * intent behind this is to allow a newer process to perform best
1217 * effort compaction of tables that it has added in the case where an
1218 * older process is still busy compacting tables which are preexisting
1219 * from the point of view of the newer process.
1220 */
1221 REFTABLE_ALLOC_ARRAY(table_locks, last - first + 1);
1222 if (!table_locks) {
1223 err = REFTABLE_OUT_OF_MEMORY_ERROR;
1224 goto done;
1225 }
1226 for (i = 0; i < last - first + 1; i++)
1227 table_locks[i] = REFTABLE_FLOCK_INIT;
1228
1229 for (i = last + 1; i > first; i--) {
1230 err = stack_filename(&table_name, st, reftable_table_name(st->tables[i - 1]));
1231 if (err < 0)
1232 goto done;
1233
1234 err = flock_acquire(&table_locks[nlocks], table_name.buf, 0);
1235 if (err < 0) {
1236 /*
1237 * When the table is locked already we may do a
1238 * best-effort compaction and compact only the tables
1239 * that we have managed to lock so far. This of course
1240 * requires that we have been able to lock at least two
1241 * tables, otherwise there would be nothing to compact.
1242 * In that case, we return a lock error to our caller.
1243 */
1244 if (err == REFTABLE_LOCK_ERROR && last - (i - 1) >= 2 &&
1245 flags & STACK_COMPACT_RANGE_BEST_EFFORT) {
1246 err = 0;
1247 /*
1248 * The subtraction is to offset the index, the
1249 * addition is to only compact up to the table
1250 * of the preceding iteration. They obviously
1251 * cancel each other out, but that may be
1252 * non-obvious when it was omitted.
1253 */
1254 first = (i - 1) + 1;
1255 break;
1256 }
1257
1258 goto done;
1259 }
1260
1261 /*
1262 * We need to close the lockfiles as we might otherwise easily
1263 * run into file descriptor exhaustion when we compress a lot
1264 * of tables.
1265 */
1266 err = flock_close(&table_locks[nlocks++]);
1267 if (err < 0)
1268 goto done;
1269 }
1270
1271 /*
1272 * We have locked all tables in our range and can thus release the
1273 * "tables.list" lock while compacting the locked tables. This allows
1274 * concurrent updates to the stack to proceed.
1275 */
1276 err = flock_release(&tables_list_lock);
1277 if (err < 0) {
1278 err = REFTABLE_IO_ERROR;
1279 goto done;
1280 }
1281
1282 /*
1283 * Compact the now-locked tables into a new table. Note that compacting
1284 * these tables may end up with an empty new table in case tombstones
1285 * end up cancelling out all refs in that range.
1286 */
1287 err = stack_compact_locked(st, first, last, expiry, opts, &new_table);
1288 if (err < 0) {
1289 if (err != REFTABLE_EMPTY_TABLE_ERROR)
1290 goto done;
1291 is_empty_table = 1;
1292 }
1293
1294 /*
1295 * Now that we have written the new, compacted table we need to re-lock
1296 * "tables.list". We'll then replace the compacted range of tables with
1297 * the new table.
1298 */
1299 err = flock_acquire(&tables_list_lock, st->list_file, opts->lock_timeout_ms);
1300 if (err < 0)
1301 goto done;
1302
1303 if (opts->default_permissions) {
1304 if (chmod(tables_list_lock.path,
1305 opts->default_permissions) < 0) {
1306 err = REFTABLE_IO_ERROR;
1307 goto done;
1308 }
1309 }
1310
1311 /*
1312 * As we have unlocked the stack while compacting our slice of tables
1313 * it may have happened that a concurrently running process has updated
1314 * the stack while we were compacting. In that case, we need to check
1315 * whether the tables that we have just compacted still exist in the
1316 * stack in the exact same order as we have compacted them.
1317 *
1318 * If they do exist, then it is fine to continue and replace those
1319 * tables with our compacted version. If they don't, then we need to
1320 * abort.
1321 */
1322 err = stack_uptodate(st);
1323 if (err < 0)
1324 goto done;
1325 if (err > 0) {
1326 ssize_t new_offset = -1;
1327 int fd;
1328
1329 fd = open(st->list_file, O_RDONLY);
1330 if (fd < 0) {
1331 err = REFTABLE_IO_ERROR;
1332 goto done;
1333 }
1334
1335 err = fd_read_lines(fd, &names);
1336 close(fd);
1337 if (err < 0)
1338 goto done;
1339
1340 /*
1341 * Search for the offset of the first table that we have
1342 * compacted in the updated "tables.list" file.
1343 */
1344 for (size_t i = 0; names[i]; i++) {
1345 if (strcmp(names[i], st->tables[first]->name))
1346 continue;
1347
1348 /*
1349 * We have found the first entry. Verify that all the
1350 * subsequent tables we have compacted still exist in
1351 * the modified stack in the exact same order as we
1352 * have compacted them.
1353 */
1354 for (size_t j = 1; j < last - first + 1; j++) {
1355 const char *old = first + j < st->merged->tables_len ?
1356 st->tables[first + j]->name : NULL;
1357 const char *new = names[i + j];
1358
1359 /*
1360 * If some entries are missing or in case the tables
1361 * have changed then we need to bail out. Again, this
1362 * shouldn't ever happen because we have locked the
1363 * tables we are compacting.
1364 */
1365 if (!old || !new || strcmp(old, new)) {
1366 err = REFTABLE_OUTDATED_ERROR;
1367 goto done;
1368 }
1369 }
1370
1371 new_offset = i;
1372 break;
1373 }
1374
1375 /*
1376 * In case we didn't find our compacted tables in the stack we
1377 * need to bail out. In theory, this should have never happened
1378 * because we locked the tables we are compacting.
1379 */
1380 if (new_offset < 0) {
1381 err = REFTABLE_OUTDATED_ERROR;
1382 goto done;
1383 }
1384
1385 /*
1386 * We have found the new range that we want to replace, so
1387 * let's update the range of tables that we want to replace.
1388 */
1389 first_to_replace = new_offset;
1390 last_to_replace = last + (new_offset - first);
1391 } else {
1392 /*
1393 * `fd_read_lines()` uses a `NULL` sentinel to indicate that
1394 * the array is at its end. As we use `free_names()` to free
1395 * the array, we need to include this sentinel value here and
1396 * thus have to allocate `tables_len + 1` many entries.
1397 */
1398 REFTABLE_CALLOC_ARRAY(names, st->merged->tables_len + 1);
1399 if (!names) {
1400 err = REFTABLE_OUT_OF_MEMORY_ERROR;
1401 goto done;
1402 }
1403
1404 for (size_t i = 0; i < st->merged->tables_len; i++) {
1405 names[i] = reftable_strdup(st->tables[i]->name);
1406 if (!names[i]) {
1407 err = REFTABLE_OUT_OF_MEMORY_ERROR;
1408 goto done;
1409 }
1410 }
1411 first_to_replace = first;
1412 last_to_replace = last;
1413 }
1414
1415 /*
1416 * If the resulting compacted table is not empty, then we need to move
1417 * it into place now.
1418 */
1419 if (!is_empty_table) {
1420 err = format_name(&new_table_name, st->tables[first]->min_update_index,
1421 st->tables[last]->max_update_index);
1422 if (err < 0)
1423 goto done;
1424
1425 err = reftable_buf_addstr(&new_table_name, ".ref");
1426 if (err < 0)
1427 goto done;
1428
1429 err = stack_filename(&new_table_path, st, new_table_name.buf);
1430 if (err < 0)
1431 goto done;
1432
1433 err = tmpfile_rename(&new_table, new_table_path.buf);
1434 if (err < 0)
1435 goto done;
1436 }
1437
1438 /*
1439 * Write the new "tables.list" contents with the compacted table we
1440 * have just written. In case the compacted table became empty we
1441 * simply skip writing it.
1442 */
1443 for (i = 0; i < first_to_replace; i++) {
1444 if ((err = reftable_buf_addstr(&tables_list_buf, names[i])) < 0 ||
1445 (err = reftable_buf_addstr(&tables_list_buf, "\n")) < 0)
1446 goto done;
1447 }
1448 if (!is_empty_table) {
1449 if ((err = reftable_buf_addstr(&tables_list_buf, new_table_name.buf)) < 0 ||
1450 (err = reftable_buf_addstr(&tables_list_buf, "\n")) < 0)
1451 goto done;
1452 }
1453 for (i = last_to_replace + 1; names[i]; i++) {
1454 if ((err = reftable_buf_addstr(&tables_list_buf, names[i])) < 0 ||
1455 (err = reftable_buf_addstr(&tables_list_buf, "\n")) < 0)
1456 goto done;
1457 }
1458
1459 err = reftable_write_data(tables_list_lock.fd,
1460 tables_list_buf.buf, tables_list_buf.len);
1461 if (err < 0) {
1462 err = REFTABLE_IO_ERROR;
1463 unlink(new_table_path.buf);
1464 goto done;
1465 }
1466
1467 err = fsync(tables_list_lock.fd);
1468 if (err < 0) {
1469 err = REFTABLE_IO_ERROR;
1470 unlink(new_table_path.buf);
1471 goto done;
1472 }
1473
1474 err = flock_commit(&tables_list_lock);
1475 if (err < 0) {
1476 err = REFTABLE_IO_ERROR;
1477 unlink(new_table_path.buf);
1478 goto done;
1479 }
1480
1481 /*
1482 * Reload the stack before deleting the compacted tables. We can only
1483 * delete the files after we closed them on Windows, so this needs to
1484 * happen first.
1485 */
1486 err = reftable_stack_reload_maybe_reuse(st, first < last);
1487 if (err < 0)
1488 goto done;
1489
1490 /*
1491 * Delete the old tables. They may still be in use by concurrent
1492 * readers, so it is expected that unlinking tables may fail.
1493 */
1494 for (i = 0; i < nlocks; i++) {
1495 struct reftable_flock *table_lock = &table_locks[i];
1496
1497 reftable_buf_reset(&table_name);
1498 err = reftable_buf_add(&table_name, table_lock->path,
1499 strlen(table_lock->path) - strlen(".lock"));
1500 if (err)
1501 continue;
1502
1503 unlink(table_name.buf);
1504 }
1505
1506 done:
1507 flock_release(&tables_list_lock);
1508 for (i = 0; table_locks && i < nlocks; i++)
1509 flock_release(&table_locks[i]);
1510 reftable_free(table_locks);
1511
1512 tmpfile_delete(&new_table);
1513 reftable_buf_release(&new_table_name);
1514 reftable_buf_release(&new_table_path);
1515 reftable_buf_release(&tables_list_buf);
1516 reftable_buf_release(&table_name);
1517 free_names(names);
1518
1519 if (err == REFTABLE_LOCK_ERROR)
1520 st->stats.failures++;
1521
1522 return err;
1523 }
1524
1525 int reftable_stack_compact_all(struct reftable_stack *st,
1526 const struct reftable_write_options *opts,
1527 struct reftable_log_expiry_config *config)
1528 {
1529 struct reftable_write_options opts_default = { 0 };
1530 size_t last = st->merged->tables_len ? st->merged->tables_len - 1 : 0;
1531
1532 if (!opts)
1533 opts = &opts_default;
1534
1535 return stack_compact_range(st, 0, last, config, opts, 0);
1536 }
1537
1538 static int segment_size(struct segment *s)
1539 {
1540 return s->end - s->start;
1541 }
1542
1543 struct segment suggest_compaction_segment(uint64_t *sizes, size_t n,
1544 uint8_t factor)
1545 {
1546 struct segment seg = { 0 };
1547 uint64_t bytes;
1548 size_t i;
1549
1550 if (!factor)
1551 factor = DEFAULT_GEOMETRIC_FACTOR;
1552
1553 /*
1554 * If there are no tables or only a single one then we don't have to
1555 * compact anything. The sequence is geometric by definition already.
1556 */
1557 if (n <= 1)
1558 return seg;
1559
1560 /*
1561 * Find the ending table of the compaction segment needed to restore the
1562 * geometric sequence. Note that the segment end is exclusive.
1563 *
1564 * To do so, we iterate backwards starting from the most recent table
1565 * until a valid segment end is found. If the preceding table is smaller
1566 * than the current table multiplied by the geometric factor (2), the
1567 * compaction segment end has been identified.
1568 *
1569 * Tables after the ending point are not added to the byte count because
1570 * they are already valid members of the geometric sequence. Due to the
1571 * properties of a geometric sequence, it is not possible for the sum of
1572 * these tables to exceed the value of the ending point table.
1573 *
1574 * Example table size sequence requiring no compaction:
1575 * 64, 32, 16, 8, 4, 2, 1
1576 *
1577 * Example table size sequence where compaction segment end is set to
1578 * the last table. Since the segment end is exclusive, the last table is
1579 * excluded during subsequent compaction and the table with size 3 is
1580 * the final table included:
1581 * 64, 32, 16, 8, 4, 3, 1
1582 */
1583 for (i = n - 1; i > 0; i--) {
1584 if (sizes[i - 1] < sizes[i] * factor) {
1585 seg.end = i + 1;
1586 bytes = sizes[i];
1587 break;
1588 }
1589 }
1590
1591 /*
1592 * Find the starting table of the compaction segment by iterating
1593 * through the remaining tables and keeping track of the accumulated
1594 * size of all tables seen from the segment end table. The previous
1595 * table is compared to the accumulated size because the tables from the
1596 * segment end are merged backwards recursively.
1597 *
1598 * Note that we keep iterating even after we have found the first
1599 * starting point. This is because there may be tables in the stack
1600 * preceding that first starting point which violate the geometric
1601 * sequence.
1602 *
1603 * Example compaction segment start set to table with size 32:
1604 * 128, 32, 16, 8, 4, 3, 1
1605 */
1606 for (; i > 0; i--) {
1607 uint64_t curr = bytes;
1608 bytes += sizes[i - 1];
1609
1610 if (sizes[i - 1] < curr * factor) {
1611 seg.start = i - 1;
1612 seg.bytes = bytes;
1613 }
1614 }
1615
1616 return seg;
1617 }
1618
1619 static int stack_segments_for_compaction(struct reftable_stack *st,
1620 const struct reftable_write_options *opts,
1621 struct segment *seg)
1622 {
1623 int version = (st->opts.hash_id == REFTABLE_HASH_SHA1) ? 1 : 2;
1624 int overhead = header_size(version) - 1;
1625 uint64_t *sizes;
1626
1627 REFTABLE_CALLOC_ARRAY(sizes, st->merged->tables_len);
1628 if (!sizes)
1629 return REFTABLE_OUT_OF_MEMORY_ERROR;
1630
1631 for (size_t i = 0; i < st->merged->tables_len; i++)
1632 sizes[i] = st->tables[i]->size - overhead;
1633
1634 *seg = suggest_compaction_segment(sizes, st->merged->tables_len,
1635 opts->auto_compaction_factor);
1636 reftable_free(sizes);
1637
1638 return 0;
1639 }
1640
1641 static int update_segment_if_compaction_required(struct reftable_stack *st,
1642 const struct reftable_write_options *opts,
1643 struct segment *seg,
1644 bool use_geometric,
1645 bool *required)
1646 {
1647 int err;
1648
1649 if (st->merged->tables_len < 2) {
1650 *required = false;
1651 return 0;
1652 }
1653
1654 if (!use_geometric) {
1655 *required = true;
1656 return 0;
1657 }
1658
1659 err = stack_segments_for_compaction(st, opts, seg);
1660 if (err)
1661 return err;
1662
1663 *required = segment_size(seg) > 0;
1664 return 0;
1665 }
1666
1667 int reftable_stack_compaction_required(struct reftable_stack *st,
1668 const struct reftable_write_options *opts,
1669 bool use_heuristics,
1670 bool *required)
1671 {
1672 struct reftable_write_options opts_default = { 0 };
1673 struct segment seg;
1674
1675 if (!opts)
1676 opts = &opts_default;
1677
1678 return update_segment_if_compaction_required(st, opts, &seg,
1679 use_heuristics, required);
1680 }
1681
1682 int reftable_stack_auto_compact(struct reftable_stack *st,
1683 const struct reftable_write_options *opts)
1684 {
1685 struct reftable_write_options opts_default = { 0 };
1686 struct segment seg;
1687 bool required;
1688 int err;
1689
1690 if (!opts)
1691 opts = &opts_default;
1692
1693 err = update_segment_if_compaction_required(st, opts, &seg, true,
1694 &required);
1695 if (err)
1696 return err;
1697
1698 if (required)
1699 return stack_compact_range(st, seg.start, seg.end - 1,
1700 NULL, opts,
1701 STACK_COMPACT_RANGE_BEST_EFFORT);
1702
1703 return 0;
1704 }
1705
1706 struct reftable_compaction_stats *
1707 reftable_stack_compaction_stats(struct reftable_stack *st)
1708 {
1709 return &st->stats;
1710 }
1711
1712 int reftable_stack_read_ref(struct reftable_stack *st, const char *refname,
1713 struct reftable_ref_record *ref)
1714 {
1715 struct reftable_iterator it = { 0 };
1716 int ret;
1717
1718 ret = reftable_merged_table_init_ref_iterator(st->merged, &it);
1719 if (ret)
1720 goto out;
1721
1722 ret = reftable_iterator_seek_ref(&it, refname);
1723 if (ret)
1724 goto out;
1725
1726 ret = reftable_iterator_next_ref(&it, ref);
1727 if (ret)
1728 goto out;
1729
1730 if (strcmp(ref->refname, refname) ||
1731 reftable_ref_record_is_deletion(ref)) {
1732 reftable_ref_record_release(ref);
1733 ret = 1;
1734 goto out;
1735 }
1736
1737 out:
1738 reftable_iterator_destroy(&it);
1739 return ret;
1740 }
1741
1742 int reftable_stack_read_log(struct reftable_stack *st, const char *refname,
1743 struct reftable_log_record *log)
1744 {
1745 struct reftable_iterator it = {0};
1746 int err;
1747
1748 err = reftable_stack_init_log_iterator(st, &it);
1749 if (err)
1750 goto done;
1751
1752 err = reftable_iterator_seek_log(&it, refname);
1753 if (err)
1754 goto done;
1755
1756 err = reftable_iterator_next_log(&it, log);
1757 if (err)
1758 goto done;
1759
1760 if (strcmp(log->refname, refname) ||
1761 reftable_log_record_is_deletion(log)) {
1762 err = 1;
1763 goto done;
1764 }
1765
1766 done:
1767 if (err) {
1768 reftable_log_record_release(log);
1769 }
1770 reftable_iterator_destroy(&it);
1771 return err;
1772 }
1773
1774 static int is_table_name(const char *s)
1775 {
1776 const char *dot = strrchr(s, '.');
1777 return dot && !strcmp(dot, ".ref");
1778 }
1779
1780 static void remove_maybe_stale_table(struct reftable_stack *st, uint64_t max,
1781 const char *name)
1782 {
1783 int err = 0;
1784 uint64_t update_idx = 0;
1785 struct reftable_block_source src = { NULL };
1786 struct reftable_table *table = NULL;
1787 struct reftable_buf table_path = REFTABLE_BUF_INIT;
1788
1789 err = stack_filename(&table_path, st, name);
1790 if (err < 0)
1791 goto done;
1792
1793 err = reftable_block_source_from_file(&src, table_path.buf);
1794 if (err < 0)
1795 goto done;
1796
1797 err = reftable_table_new(&table, &src, name);
1798 if (err < 0)
1799 goto done;
1800
1801 update_idx = reftable_table_max_update_index(table);
1802 reftable_table_decref(table);
1803
1804 if (update_idx <= max) {
1805 unlink(table_path.buf);
1806 }
1807 done:
1808 reftable_buf_release(&table_path);
1809 }
1810
1811 static int reftable_stack_clean_locked(struct reftable_stack *st)
1812 {
1813 uint64_t max = reftable_merged_table_max_update_index(
1814 reftable_stack_merged_table(st));
1815 DIR *dir = opendir(st->reftable_dir);
1816 struct dirent *d = NULL;
1817 if (!dir) {
1818 return REFTABLE_IO_ERROR;
1819 }
1820
1821 while ((d = readdir(dir))) {
1822 int found = 0;
1823 if (!is_table_name(d->d_name))
1824 continue;
1825
1826 for (size_t i = 0; !found && i < st->tables_len; i++)
1827 found = !strcmp(reftable_table_name(st->tables[i]), d->d_name);
1828 if (found)
1829 continue;
1830
1831 remove_maybe_stale_table(st, max, d->d_name);
1832 }
1833
1834 closedir(dir);
1835 return 0;
1836 }
1837
1838 int reftable_stack_clean(struct reftable_stack *st)
1839 {
1840 struct reftable_addition *add = NULL;
1841 int err = reftable_stack_addition_new(&add, st, NULL);
1842 if (err < 0) {
1843 goto done;
1844 }
1845
1846 err = reftable_stack_clean_locked(st);
1847
1848 done:
1849 reftable_addition_destroy(add);
1850 return err;
1851 }
1852
1853 enum reftable_hash reftable_stack_hash_id(struct reftable_stack *st)
1854 {
1855 return reftable_merged_table_hash_id(st->merged);
1856 }