2 * git gc builtin command
4 * Cleanup unreachable files and optimize the repository.
6 * Copyright (c) 2007 James Bowes
8 * Based on git-gc.sh, which is
10 * Copyright (c) 2006 Shawn O. Pearce
14 #include "repository.h"
18 #include "parse-options.h"
19 #include "run-command.h"
21 #include "argv-array.h"
23 #include "commit-graph.h"
25 #include "object-store.h"
27 #include "pack-objects.h"
30 #include "promisor-remote.h"
32 #define FAILED_RUN "failed to run %s"
34 static const char * const builtin_gc_usage[] = {
35 N_("git gc [<options>]"),
39 static int pack_refs = 1;
40 static int prune_reflogs = 1;
41 static int aggressive_depth = 50;
42 static int aggressive_window = 250;
43 static int gc_auto_threshold = 6700;
44 static int gc_auto_pack_limit = 50;
45 static int detach_auto = 1;
46 static timestamp_t gc_log_expire_time;
47 static const char *gc_log_expire = "1.day.ago";
48 static const char *prune_expire = "2.weeks.ago";
49 static const char *prune_worktrees_expire = "3.months.ago";
50 static unsigned long big_pack_threshold;
51 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
53 static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
54 static struct argv_array reflog = ARGV_ARRAY_INIT;
55 static struct argv_array repack = ARGV_ARRAY_INIT;
56 static struct argv_array prune = ARGV_ARRAY_INIT;
57 static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
58 static struct argv_array rerere = ARGV_ARRAY_INIT;
60 static struct tempfile *pidfile;
61 static struct lock_file log_lock;
63 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
65 static void clean_pack_garbage(void)
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);
73 static void report_pack_garbage(unsigned seen_bits, const char *path)
75 if (seen_bits == PACKDIR_FILE_IDX)
76 string_list_append(&pack_garbage, path);
79 static void process_log_file(void)
82 if (fstat(get_lock_file_fd(&log_lock), &st)) {
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
89 int saved_errno = errno;
90 fprintf(stderr, _("Failed to fstat %s: %s"),
91 get_tempfile_path(log_lock.tempfile),
92 strerror(saved_errno));
94 commit_lock_file(&log_lock);
96 } else if (st.st_size) {
97 /* There was some error recorded in the lock file */
98 commit_lock_file(&log_lock);
100 /* No error, clean up any old gc.log */
101 unlink(git_path("gc.log"));
102 rollback_lock_file(&log_lock);
106 static void process_log_file_at_exit(void)
112 static void process_log_file_on_signal(int signo)
119 static int gc_config_is_timestamp_never(const char *var)
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);
132 static void gc_config(void)
136 if (!git_config_get_value("gc.packrefs", &value)) {
137 if (value && !strcmp(value, "notbare"))
140 pack_refs = git_config_bool("gc.packrefs", value);
143 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
144 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
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.autodetach", &detach_auto);
152 git_config_get_expiry("gc.pruneexpire", &prune_expire);
153 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
154 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
156 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
157 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
159 git_config(git_default_config, NULL);
162 static int too_many_loose_objects(void)
165 * Quickly check if a "gc" is needed, by estimating how
166 * many loose objects there are. Because SHA-1 is evenly
167 * distributed, we can check only one and get a reasonable
175 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
177 dir = opendir(git_path("objects/17"));
181 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
182 while ((ent = readdir(dir)) != NULL) {
183 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
184 ent->d_name[hexsz_loose] != '\0')
186 if (++num_loose > auto_threshold) {
195 static struct packed_git *find_base_packs(struct string_list *packs,
198 struct packed_git *p, *base = NULL;
200 for (p = get_all_packs(the_repository); p; p = p->next) {
204 if (p->pack_size >= limit)
205 string_list_append(packs, p->pack_name);
206 } else if (!base || base->pack_size < p->pack_size) {
212 string_list_append(packs, base->pack_name);
217 static int too_many_packs(void)
219 struct packed_git *p;
222 if (gc_auto_pack_limit <= 0)
225 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
231 * Perhaps check the size of the pack and count only
232 * very small ones here?
236 return gc_auto_pack_limit < cnt;
239 static uint64_t total_ram(void)
241 #if defined(HAVE_SYSINFO)
246 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
247 int64_t physical_memory;
252 # if defined(HW_MEMSIZE)
257 length = sizeof(int64_t);
258 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
259 return physical_memory;
260 #elif defined(GIT_WINDOWS_NATIVE)
261 MEMORYSTATUSEX memInfo;
263 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
264 if (GlobalMemoryStatusEx(&memInfo))
265 return memInfo.ullTotalPhys;
270 static uint64_t estimate_repack_memory(struct packed_git *pack)
272 unsigned long nr_objects = approximate_object_count();
273 size_t os_cache, heap;
275 if (!pack || !nr_objects)
279 * First we have to scan through at least one pack.
280 * Assume enough room in OS file cache to keep the entire pack
281 * or we may accidentally evict data of other processes from
284 os_cache = pack->pack_size + pack->index_size;
285 /* then pack-objects needs lots more for book keeping */
286 heap = sizeof(struct object_entry) * nr_objects;
288 * internal rev-list --all --objects takes up some memory too,
289 * let's say half of it is for blobs
291 heap += sizeof(struct blob) * nr_objects / 2;
293 * and the other half is for trees (commits and tags are
294 * usually insignificant)
296 heap += sizeof(struct tree) * nr_objects / 2;
297 /* and then obj_hash[], underestimated in fact */
298 heap += sizeof(struct object *) * nr_objects;
299 /* revindex is used also */
300 heap += sizeof(struct revindex_entry) * nr_objects;
302 * read_sha1_file() (either at delta calculation phase, or
303 * writing phase) also fills up the delta base cache
305 heap += delta_base_cache_limit;
306 /* and of course pack-objects has its own delta cache */
307 heap += max_delta_cache_size;
309 return os_cache + heap;
312 static int keep_one_pack(struct string_list_item *item, void *data)
314 argv_array_pushf(&repack, "--keep-pack=%s", basename(item->string));
318 static void add_repack_all_option(struct string_list *keep_pack)
320 if (prune_expire && !strcmp(prune_expire, "now"))
321 argv_array_push(&repack, "-a");
323 argv_array_push(&repack, "-A");
325 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
329 for_each_string_list(keep_pack, keep_one_pack, NULL);
332 static void add_repack_incremental_option(void)
334 argv_array_push(&repack, "--no-write-bitmap-index");
337 static int need_to_gc(void)
340 * Setting gc.auto to 0 or negative can disable the
343 if (gc_auto_threshold <= 0)
347 * If there are too many loose objects, but not too many
348 * packs, we run "repack -d -l". If there are too many packs,
349 * we run "repack -A -d -l". Otherwise we tell the caller
352 if (too_many_packs()) {
353 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
355 if (big_pack_threshold) {
356 find_base_packs(&keep_pack, big_pack_threshold);
357 if (keep_pack.nr >= gc_auto_pack_limit) {
358 big_pack_threshold = 0;
359 string_list_clear(&keep_pack, 0);
360 find_base_packs(&keep_pack, 0);
363 struct packed_git *p = find_base_packs(&keep_pack, 0);
364 uint64_t mem_have, mem_want;
366 mem_have = total_ram();
367 mem_want = estimate_repack_memory(p);
370 * Only allow 1/2 of memory for pack-objects, leave
371 * the rest for the OS and other processes in the
374 if (!mem_have || mem_want < mem_have / 2)
375 string_list_clear(&keep_pack, 0);
378 add_repack_all_option(&keep_pack);
379 string_list_clear(&keep_pack, 0);
380 } else if (too_many_loose_objects())
381 add_repack_incremental_option();
385 if (run_hook_le(NULL, "pre-auto-gc", NULL))
390 /* return NULL on success, else hostname running the gc */
391 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
393 struct lock_file lock = LOCK_INIT;
394 char my_host[HOST_NAME_MAX + 1];
395 struct strbuf sb = STRBUF_INIT;
402 if (is_tempfile_active(pidfile))
406 if (xgethostname(my_host, sizeof(my_host)))
407 xsnprintf(my_host, sizeof(my_host), "unknown");
409 pidfile_path = git_pathdup("gc.pid");
410 fd = hold_lock_file_for_update(&lock, pidfile_path,
413 static char locking_host[HOST_NAME_MAX + 1];
414 static char *scan_fmt;
418 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
419 fp = fopen(pidfile_path, "r");
420 memset(locking_host, 0, sizeof(locking_host));
423 !fstat(fileno(fp), &st) &&
425 * 12 hour limit is very generous as gc should
426 * never take that long. On the other hand we
427 * don't really need a strict limit here,
428 * running gc --auto one day late is not a big
429 * problem. --force can be used in manual gc
430 * after the user verifies that no gc is
433 time(NULL) - st.st_mtime <= 12 * 3600 &&
434 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
435 /* be gentle to concurrent "gc" on remote hosts */
436 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
441 rollback_lock_file(&lock);
448 strbuf_addf(&sb, "%"PRIuMAX" %s",
449 (uintmax_t) getpid(), my_host);
450 write_in_full(fd, sb.buf, sb.len);
452 commit_lock_file(&lock);
453 pidfile = register_tempfile(pidfile_path);
459 * Returns 0 if there was no previous error and gc can proceed, 1 if
460 * gc should not proceed due to an error in the last run. Prints a
461 * message and returns -1 if an error occurred while reading gc.log
463 static int report_last_gc_error(void)
465 struct strbuf sb = STRBUF_INIT;
469 char *gc_log_path = git_pathdup("gc.log");
471 if (stat(gc_log_path, &st)) {
475 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
479 if (st.st_mtime < gc_log_expire_time)
482 len = strbuf_read_file(&sb, gc_log_path, 0);
484 ret = error_errno(_("cannot read '%s'"), gc_log_path);
487 * A previous gc failed. Report the error, and don't
488 * bother with an automatic gc run since it is likely
489 * to fail in the same way.
491 warning(_("The last gc run reported the following. "
492 "Please correct the root cause\n"
494 "Automatic cleanup will not be performed "
495 "until the file is removed.\n\n"
497 gc_log_path, sb.buf);
506 static void gc_before_repack(void)
509 * We may be called twice, as both the pre- and
510 * post-daemonized phases will call us, but running these
511 * commands more than once is pointless and wasteful.
517 if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
518 die(FAILED_RUN, pack_refs_cmd.argv[0]);
520 if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
521 die(FAILED_RUN, reflog.argv[0]);
524 int cmd_gc(int argc, const char **argv, const char *prefix)
533 int keep_base_pack = -1;
536 struct option builtin_gc_options[] = {
537 OPT__QUIET(&quiet, N_("suppress progress reporting")),
538 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
539 N_("prune unreferenced objects"),
540 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
541 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
542 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
543 PARSE_OPT_NOCOMPLETE),
544 OPT_BOOL_F(0, "force", &force,
545 N_("force running gc even if there may be another gc running"),
546 PARSE_OPT_NOCOMPLETE),
547 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
548 N_("repack all other packs except the largest pack")),
552 if (argc == 2 && !strcmp(argv[1], "-h"))
553 usage_with_options(builtin_gc_usage, builtin_gc_options);
555 argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
556 argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
557 argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
558 argv_array_pushl(&prune, "prune", "--expire", NULL);
559 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
560 argv_array_pushl(&rerere, "rerere", "gc", NULL);
562 /* default expiry time, overwritten in gc_config */
564 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
565 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
568 pack_refs = !is_bare_repository();
570 argc = parse_options(argc, argv, prefix, builtin_gc_options,
571 builtin_gc_usage, 0);
573 usage_with_options(builtin_gc_usage, builtin_gc_options);
575 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
576 die(_("failed to parse prune expiry value %s"), prune_expire);
579 argv_array_push(&repack, "-f");
580 if (aggressive_depth > 0)
581 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
582 if (aggressive_window > 0)
583 argv_array_pushf(&repack, "--window=%d", aggressive_window);
586 argv_array_push(&repack, "-q");
590 * Auto-gc should be least intrusive as possible.
596 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
598 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
599 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
602 int ret = report_last_gc_error();
604 /* an I/O error occurred, already reported */
607 /* Last gc --auto failed. Skip this one. */
610 if (lock_repo_for_gc(force, &pid))
612 gc_before_repack(); /* dies on failure */
613 delete_tempfile(&pidfile);
616 * failure to daemonize is ok, we'll continue
619 daemonized = !daemonize();
622 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
624 if (keep_base_pack != -1) {
626 find_base_packs(&keep_pack, 0);
627 } else if (big_pack_threshold) {
628 find_base_packs(&keep_pack, big_pack_threshold);
631 add_repack_all_option(&keep_pack);
632 string_list_clear(&keep_pack, 0);
635 name = lock_repo_for_gc(force, &pid);
638 return 0; /* be quiet on --auto */
639 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
640 name, (uintmax_t)pid);
644 hold_lock_file_for_update(&log_lock,
647 dup2(get_lock_file_fd(&log_lock), 2);
648 sigchain_push_common(process_log_file_on_signal);
649 atexit(process_log_file_at_exit);
654 if (!repository_format_precious_objects) {
655 close_object_store(the_repository->objects);
656 if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
657 die(FAILED_RUN, repack.argv[0]);
660 argv_array_push(&prune, prune_expire);
662 argv_array_push(&prune, "--no-progress");
663 if (has_promisor_remote())
664 argv_array_push(&prune,
665 "--exclude-promisor-objects");
666 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
667 die(FAILED_RUN, prune.argv[0]);
671 if (prune_worktrees_expire) {
672 argv_array_push(&prune_worktrees, prune_worktrees_expire);
673 if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
674 die(FAILED_RUN, prune_worktrees.argv[0]);
677 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
678 die(FAILED_RUN, rerere.argv[0]);
680 report_garbage = report_pack_garbage;
681 reprepare_packed_git(the_repository);
682 if (pack_garbage.nr > 0) {
683 close_object_store(the_repository->objects);
684 clean_pack_garbage();
687 prepare_repo_settings(the_repository);
688 if (the_repository->settings.gc_write_commit_graph == 1)
689 write_commit_graph_reachable(the_repository->objects->odb,
690 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
693 if (auto_gc && too_many_loose_objects())
694 warning(_("There are too many unreachable loose objects; "
695 "run 'git prune' to remove them."));
698 unlink(git_path("gc.log"));