1/*
2 * git gc builtin command
3 *
4 * Cleanup unreachable files and optimize the repository.
5 *
6 * Copyright (c) 2007 James Bowes
7 *
8 * Based on git-gc.sh, which is
9 *
10 * Copyright (c) 2006 Shawn O. Pearce
11 */
12
13#include "builtin.h"
14#include "repository.h"
15#include "config.h"
16#include "tempfile.h"
17#include "lockfile.h"
18#include "parse-options.h"
19#include "run-command.h"
20#include "sigchain.h"
21#include "argv-array.h"
22#include "commit.h"
23#include "commit-graph.h"
24#include "packfile.h"
25#include "object-store.h"
26#include "pack.h"
27#include "pack-objects.h"
28#include "blob.h"
29#include "tree.h"
30
31#define FAILED_RUN "failed to run %s"
32
33static const char * const builtin_gc_usage[] = {
34 N_("git gc [<options>]"),
35 NULL
36};
37
38static int pack_refs = 1;
39static int prune_reflogs = 1;
40static int aggressive_depth = 50;
41static int aggressive_window = 250;
42static int gc_auto_threshold = 6700;
43static int gc_auto_pack_limit = 50;
44static int gc_write_commit_graph;
45static int detach_auto = 1;
46static timestamp_t gc_log_expire_time;
47static const char *gc_log_expire = "1.day.ago";
48static const char *prune_expire = "2.weeks.ago";
49static const char *prune_worktrees_expire = "3.months.ago";
50static unsigned long big_pack_threshold;
51static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
52
53static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
54static struct argv_array reflog = ARGV_ARRAY_INIT;
55static struct argv_array repack = ARGV_ARRAY_INIT;
56static struct argv_array prune = ARGV_ARRAY_INIT;
57static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
58static struct argv_array rerere = ARGV_ARRAY_INIT;
59
60static struct tempfile *pidfile;
61static struct lock_file log_lock;
62
63static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
64
65static void clean_pack_garbage(void)
66{
67 int i;
68 for (i = 0; i < pack_garbage.nr; i++)
69 unlink_or_warn(pack_garbage.items[i].string);
70 string_list_clear(&pack_garbage, 0);
71}
72
73static void report_pack_garbage(unsigned seen_bits, const char *path)
74{
75 if (seen_bits == PACKDIR_FILE_IDX)
76 string_list_append(&pack_garbage, path);
77}
78
79static void process_log_file(void)
80{
81 struct stat st;
82 if (fstat(get_lock_file_fd(&log_lock), &st)) {
83 /*
84 * Perhaps there was an i/o error or another
85 * unlikely situation. Try to make a note of
86 * this in gc.log along with any existing
87 * messages.
88 */
89 int saved_errno = errno;
90 fprintf(stderr, _("Failed to fstat %s: %s"),
91 get_tempfile_path(log_lock.tempfile),
92 strerror(saved_errno));
93 fflush(stderr);
94 commit_lock_file(&log_lock);
95 errno = saved_errno;
96 } else if (st.st_size) {
97 /* There was some error recorded in the lock file */
98 commit_lock_file(&log_lock);
99 } else {
100 /* No error, clean up any old gc.log */
101 unlink(git_path("gc.log"));
102 rollback_lock_file(&log_lock);
103 }
104}
105
106static void process_log_file_at_exit(void)
107{
108 fflush(stderr);
109 process_log_file();
110}
111
112static void process_log_file_on_signal(int signo)
113{
114 process_log_file();
115 sigchain_pop(signo);
116 raise(signo);
117}
118
119static int gc_config_is_timestamp_never(const char *var)
120{
121 const char *value;
122 timestamp_t expire;
123
124 if (!git_config_get_value(var, &value) && value) {
125 if (parse_expiry_date(value, &expire))
126 die(_("failed to parse '%s' value '%s'"), var, value);
127 return expire == 0;
128 }
129 return 0;
130}
131
132static void gc_config(void)
133{
134 const char *value;
135
136 if (!git_config_get_value("gc.packrefs", &value)) {
137 if (value && !strcmp(value, "notbare"))
138 pack_refs = -1;
139 else
140 pack_refs = git_config_bool("gc.packrefs", value);
141 }
142
143 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
144 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
145 prune_reflogs = 0;
146
147 git_config_get_int("gc.aggressivewindow", &aggressive_window);
148 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
149 git_config_get_int("gc.auto", &gc_auto_threshold);
150 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
151 git_config_get_bool("gc.writecommitgraph", &gc_write_commit_graph);
152 git_config_get_bool("gc.autodetach", &detach_auto);
153 git_config_get_expiry("gc.pruneexpire", &prune_expire);
154 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
155 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
156
157 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
158 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
159
160 git_config(git_default_config, NULL);
161}
162
163static int too_many_loose_objects(void)
164{
165 /*
166 * Quickly check if a "gc" is needed, by estimating how
167 * many loose objects there are. Because SHA-1 is evenly
168 * distributed, we can check only one and get a reasonable
169 * estimate.
170 */
171 DIR *dir;
172 struct dirent *ent;
173 int auto_threshold;
174 int num_loose = 0;
175 int needed = 0;
176 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
177
178 dir = opendir(git_path("objects/17"));
179 if (!dir)
180 return 0;
181
182 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
183 while ((ent = readdir(dir)) != NULL) {
184 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
185 ent->d_name[hexsz_loose] != '\0')
186 continue;
187 if (++num_loose > auto_threshold) {
188 needed = 1;
189 break;
190 }
191 }
192 closedir(dir);
193 return needed;
194}
195
196static struct packed_git *find_base_packs(struct string_list *packs,
197 unsigned long limit)
198{
199 struct packed_git *p, *base = NULL;
200
201 for (p = get_all_packs(the_repository); p; p = p->next) {
202 if (!p->pack_local)
203 continue;
204 if (limit) {
205 if (p->pack_size >= limit)
206 string_list_append(packs, p->pack_name);
207 } else if (!base || base->pack_size < p->pack_size) {
208 base = p;
209 }
210 }
211
212 if (base)
213 string_list_append(packs, base->pack_name);
214
215 return base;
216}
217
218static int too_many_packs(void)
219{
220 struct packed_git *p;
221 int cnt;
222
223 if (gc_auto_pack_limit <= 0)
224 return 0;
225
226 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
227 if (!p->pack_local)
228 continue;
229 if (p->pack_keep)
230 continue;
231 /*
232 * Perhaps check the size of the pack and count only
233 * very small ones here?
234 */
235 cnt++;
236 }
237 return gc_auto_pack_limit < cnt;
238}
239
240static uint64_t total_ram(void)
241{
242#if defined(HAVE_SYSINFO)
243 struct sysinfo si;
244
245 if (!sysinfo(&si))
246 return si.totalram;
247#elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
248 int64_t physical_memory;
249 int mib[2];
250 size_t length;
251
252 mib[0] = CTL_HW;
253# if defined(HW_MEMSIZE)
254 mib[1] = HW_MEMSIZE;
255# else
256 mib[1] = HW_PHYSMEM;
257# endif
258 length = sizeof(int64_t);
259 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
260 return physical_memory;
261#elif defined(GIT_WINDOWS_NATIVE)
262 MEMORYSTATUSEX memInfo;
263
264 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
265 if (GlobalMemoryStatusEx(&memInfo))
266 return memInfo.ullTotalPhys;
267#endif
268 return 0;
269}
270
271static uint64_t estimate_repack_memory(struct packed_git *pack)
272{
273 unsigned long nr_objects = approximate_object_count();
274 size_t os_cache, heap;
275
276 if (!pack || !nr_objects)
277 return 0;
278
279 /*
280 * First we have to scan through at least one pack.
281 * Assume enough room in OS file cache to keep the entire pack
282 * or we may accidentally evict data of other processes from
283 * the cache.
284 */
285 os_cache = pack->pack_size + pack->index_size;
286 /* then pack-objects needs lots more for book keeping */
287 heap = sizeof(struct object_entry) * nr_objects;
288 /*
289 * internal rev-list --all --objects takes up some memory too,
290 * let's say half of it is for blobs
291 */
292 heap += sizeof(struct blob) * nr_objects / 2;
293 /*
294 * and the other half is for trees (commits and tags are
295 * usually insignificant)
296 */
297 heap += sizeof(struct tree) * nr_objects / 2;
298 /* and then obj_hash[], underestimated in fact */
299 heap += sizeof(struct object *) * nr_objects;
300 /* revindex is used also */
301 heap += sizeof(struct revindex_entry) * nr_objects;
302 /*
303 * read_sha1_file() (either at delta calculation phase, or
304 * writing phase) also fills up the delta base cache
305 */
306 heap += delta_base_cache_limit;
307 /* and of course pack-objects has its own delta cache */
308 heap += max_delta_cache_size;
309
310 return os_cache + heap;
311}
312
313static int keep_one_pack(struct string_list_item *item, void *data)
314{
315 argv_array_pushf(&repack, "--keep-pack=%s", basename(item->string));
316 return 0;
317}
318
319static void add_repack_all_option(struct string_list *keep_pack)
320{
321 if (prune_expire && !strcmp(prune_expire, "now"))
322 argv_array_push(&repack, "-a");
323 else {
324 argv_array_push(&repack, "-A");
325 if (prune_expire)
326 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
327 }
328
329 if (keep_pack)
330 for_each_string_list(keep_pack, keep_one_pack, NULL);
331}
332
333static void add_repack_incremental_option(void)
334{
335 argv_array_push(&repack, "--no-write-bitmap-index");
336}
337
338static int need_to_gc(void)
339{
340 /*
341 * Setting gc.auto to 0 or negative can disable the
342 * automatic gc.
343 */
344 if (gc_auto_threshold <= 0)
345 return 0;
346
347 /*
348 * If there are too many loose objects, but not too many
349 * packs, we run "repack -d -l". If there are too many packs,
350 * we run "repack -A -d -l". Otherwise we tell the caller
351 * there is no need.
352 */
353 if (too_many_packs()) {
354 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
355
356 if (big_pack_threshold) {
357 find_base_packs(&keep_pack, big_pack_threshold);
358 if (keep_pack.nr >= gc_auto_pack_limit) {
359 big_pack_threshold = 0;
360 string_list_clear(&keep_pack, 0);
361 find_base_packs(&keep_pack, 0);
362 }
363 } else {
364 struct packed_git *p = find_base_packs(&keep_pack, 0);
365 uint64_t mem_have, mem_want;
366
367 mem_have = total_ram();
368 mem_want = estimate_repack_memory(p);
369
370 /*
371 * Only allow 1/2 of memory for pack-objects, leave
372 * the rest for the OS and other processes in the
373 * system.
374 */
375 if (!mem_have || mem_want < mem_have / 2)
376 string_list_clear(&keep_pack, 0);
377 }
378
379 add_repack_all_option(&keep_pack);
380 string_list_clear(&keep_pack, 0);
381 } else if (too_many_loose_objects())
382 add_repack_incremental_option();
383 else
384 return 0;
385
386 if (run_hook_le(NULL, "pre-auto-gc", NULL))
387 return 0;
388 return 1;
389}
390
391/* return NULL on success, else hostname running the gc */
392static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
393{
394 struct lock_file lock = LOCK_INIT;
395 char my_host[HOST_NAME_MAX + 1];
396 struct strbuf sb = STRBUF_INIT;
397 struct stat st;
398 uintmax_t pid;
399 FILE *fp;
400 int fd;
401 char *pidfile_path;
402
403 if (is_tempfile_active(pidfile))
404 /* already locked */
405 return NULL;
406
407 if (xgethostname(my_host, sizeof(my_host)))
408 xsnprintf(my_host, sizeof(my_host), "unknown");
409
410 pidfile_path = git_pathdup("gc.pid");
411 fd = hold_lock_file_for_update(&lock, pidfile_path,
412 LOCK_DIE_ON_ERROR);
413 if (!force) {
414 static char locking_host[HOST_NAME_MAX + 1];
415 static char *scan_fmt;
416 int should_exit;
417
418 if (!scan_fmt)
419 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
420 fp = fopen(pidfile_path, "r");
421 memset(locking_host, 0, sizeof(locking_host));
422 should_exit =
423 fp != NULL &&
424 !fstat(fileno(fp), &st) &&
425 /*
426 * 12 hour limit is very generous as gc should
427 * never take that long. On the other hand we
428 * don't really need a strict limit here,
429 * running gc --auto one day late is not a big
430 * problem. --force can be used in manual gc
431 * after the user verifies that no gc is
432 * running.
433 */
434 time(NULL) - st.st_mtime <= 12 * 3600 &&
435 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
436 /* be gentle to concurrent "gc" on remote hosts */
437 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
438 if (fp != NULL)
439 fclose(fp);
440 if (should_exit) {
441 if (fd >= 0)
442 rollback_lock_file(&lock);
443 *ret_pid = pid;
444 free(pidfile_path);
445 return locking_host;
446 }
447 }
448
449 strbuf_addf(&sb, "%"PRIuMAX" %s",
450 (uintmax_t) getpid(), my_host);
451 write_in_full(fd, sb.buf, sb.len);
452 strbuf_release(&sb);
453 commit_lock_file(&lock);
454 pidfile = register_tempfile(pidfile_path);
455 free(pidfile_path);
456 return NULL;
457}
458
459/*
460 * Returns 0 if there was no previous error and gc can proceed, 1 if
461 * gc should not proceed due to an error in the last run. Prints a
462 * message and returns -1 if an error occured while reading gc.log
463 */
464static int report_last_gc_error(void)
465{
466 struct strbuf sb = STRBUF_INIT;
467 int ret = 0;
468 ssize_t len;
469 struct stat st;
470 char *gc_log_path = git_pathdup("gc.log");
471
472 if (stat(gc_log_path, &st)) {
473 if (errno == ENOENT)
474 goto done;
475
476 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
477 goto done;
478 }
479
480 if (st.st_mtime < gc_log_expire_time)
481 goto done;
482
483 len = strbuf_read_file(&sb, gc_log_path, 0);
484 if (len < 0)
485 ret = error_errno(_("cannot read '%s'"), gc_log_path);
486 else if (len > 0) {
487 /*
488 * A previous gc failed. Report the error, and don't
489 * bother with an automatic gc run since it is likely
490 * to fail in the same way.
491 */
492 warning(_("The last gc run reported the following. "
493 "Please correct the root cause\n"
494 "and remove %s.\n"
495 "Automatic cleanup will not be performed "
496 "until the file is removed.\n\n"
497 "%s"),
498 gc_log_path, sb.buf);
499 ret = 1;
500 }
501 strbuf_release(&sb);
502done:
503 free(gc_log_path);
504 return ret;
505}
506
507static void gc_before_repack(void)
508{
509 /*
510 * We may be called twice, as both the pre- and
511 * post-daemonized phases will call us, but running these
512 * commands more than once is pointless and wasteful.
513 */
514 static int done = 0;
515 if (done++)
516 return;
517
518 if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
519 die(FAILED_RUN, pack_refs_cmd.argv[0]);
520
521 if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
522 die(FAILED_RUN, reflog.argv[0]);
523}
524
525int cmd_gc(int argc, const char **argv, const char *prefix)
526{
527 int aggressive = 0;
528 int auto_gc = 0;
529 int quiet = 0;
530 int force = 0;
531 const char *name;
532 pid_t pid;
533 int daemonized = 0;
534 int keep_base_pack = -1;
535 timestamp_t dummy;
536
537 struct option builtin_gc_options[] = {
538 OPT__QUIET(&quiet, N_("suppress progress reporting")),
539 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
540 N_("prune unreferenced objects"),
541 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
542 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
543 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
544 PARSE_OPT_NOCOMPLETE),
545 OPT_BOOL_F(0, "force", &force,
546 N_("force running gc even if there may be another gc running"),
547 PARSE_OPT_NOCOMPLETE),
548 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
549 N_("repack all other packs except the largest pack")),
550 OPT_END()
551 };
552
553 if (argc == 2 && !strcmp(argv[1], "-h"))
554 usage_with_options(builtin_gc_usage, builtin_gc_options);
555
556 argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
557 argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
558 argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
559 argv_array_pushl(&prune, "prune", "--expire", NULL);
560 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
561 argv_array_pushl(&rerere, "rerere", "gc", NULL);
562
563 /* default expiry time, overwritten in gc_config */
564 gc_config();
565 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
566 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
567
568 if (pack_refs < 0)
569 pack_refs = !is_bare_repository();
570
571 argc = parse_options(argc, argv, prefix, builtin_gc_options,
572 builtin_gc_usage, 0);
573 if (argc > 0)
574 usage_with_options(builtin_gc_usage, builtin_gc_options);
575
576 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
577 die(_("failed to parse prune expiry value %s"), prune_expire);
578
579 if (aggressive) {
580 argv_array_push(&repack, "-f");
581 if (aggressive_depth > 0)
582 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
583 if (aggressive_window > 0)
584 argv_array_pushf(&repack, "--window=%d", aggressive_window);
585 }
586 if (quiet)
587 argv_array_push(&repack, "-q");
588
589 if (auto_gc) {
590 /*
591 * Auto-gc should be least intrusive as possible.
592 */
593 if (!need_to_gc())
594 return 0;
595 if (!quiet) {
596 if (detach_auto)
597 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
598 else
599 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
600 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
601 }
602 if (detach_auto) {
603 int ret = report_last_gc_error();
604 if (ret < 0)
605 /* an I/O error occured, already reported */
606 exit(128);
607 if (ret == 1)
608 /* Last gc --auto failed. Skip this one. */
609 return 0;
610
611 if (lock_repo_for_gc(force, &pid))
612 return 0;
613 gc_before_repack(); /* dies on failure */
614 delete_tempfile(&pidfile);
615
616 /*
617 * failure to daemonize is ok, we'll continue
618 * in foreground
619 */
620 daemonized = !daemonize();
621 }
622 } else {
623 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
624
625 if (keep_base_pack != -1) {
626 if (keep_base_pack)
627 find_base_packs(&keep_pack, 0);
628 } else if (big_pack_threshold) {
629 find_base_packs(&keep_pack, big_pack_threshold);
630 }
631
632 add_repack_all_option(&keep_pack);
633 string_list_clear(&keep_pack, 0);
634 }
635
636 name = lock_repo_for_gc(force, &pid);
637 if (name) {
638 if (auto_gc)
639 return 0; /* be quiet on --auto */
640 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
641 name, (uintmax_t)pid);
642 }
643
644 if (daemonized) {
645 hold_lock_file_for_update(&log_lock,
646 git_path("gc.log"),
647 LOCK_DIE_ON_ERROR);
648 dup2(get_lock_file_fd(&log_lock), 2);
649 sigchain_push_common(process_log_file_on_signal);
650 atexit(process_log_file_at_exit);
651 }
652
653 gc_before_repack();
654
655 if (!repository_format_precious_objects) {
656 close_all_packs(the_repository->objects);
657 if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
658 die(FAILED_RUN, repack.argv[0]);
659
660 if (prune_expire) {
661 argv_array_push(&prune, prune_expire);
662 if (quiet)
663 argv_array_push(&prune, "--no-progress");
664 if (repository_format_partial_clone)
665 argv_array_push(&prune,
666 "--exclude-promisor-objects");
667 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
668 die(FAILED_RUN, prune.argv[0]);
669 }
670 }
671
672 if (prune_worktrees_expire) {
673 argv_array_push(&prune_worktrees, prune_worktrees_expire);
674 if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
675 die(FAILED_RUN, prune_worktrees.argv[0]);
676 }
677
678 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
679 die(FAILED_RUN, rerere.argv[0]);
680
681 report_garbage = report_pack_garbage;
682 reprepare_packed_git(the_repository);
683 if (pack_garbage.nr > 0) {
684 close_all_packs(the_repository->objects);
685 clean_pack_garbage();
686 }
687
688 if (gc_write_commit_graph)
689 write_commit_graph_reachable(get_object_directory(), 0,
690 !quiet && !daemonized);
691
692 if (auto_gc && too_many_loose_objects())
693 warning(_("There are too many unreachable loose objects; "
694 "run 'git prune' to remove them."));
695
696 if (!daemonized)
697 unlink(git_path("gc.log"));
698
699 return 0;
700}