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