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