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