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 "packfile.h"
24#include "object-store.h"
25
26#define FAILED_RUN "failed to run %s"
27
28static const char * const builtin_gc_usage[] = {
29 N_("git gc [<options>]"),
30 NULL
31};
32
33static int pack_refs = 1;
34static int prune_reflogs = 1;
35static int aggressive_depth = 50;
36static int aggressive_window = 250;
37static int gc_auto_threshold = 6700;
38static int gc_auto_pack_limit = 50;
39static int detach_auto = 1;
40static timestamp_t gc_log_expire_time;
41static const char *gc_log_expire = "1.day.ago";
42static const char *prune_expire = "2.weeks.ago";
43static const char *prune_worktrees_expire = "3.months.ago";
44static unsigned long big_pack_threshold;
45
46static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
47static struct argv_array reflog = ARGV_ARRAY_INIT;
48static struct argv_array repack = ARGV_ARRAY_INIT;
49static struct argv_array prune = ARGV_ARRAY_INIT;
50static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
51static struct argv_array rerere = ARGV_ARRAY_INIT;
52
53static struct tempfile *pidfile;
54static struct lock_file log_lock;
55
56static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
57
58static void clean_pack_garbage(void)
59{
60 int i;
61 for (i = 0; i < pack_garbage.nr; i++)
62 unlink_or_warn(pack_garbage.items[i].string);
63 string_list_clear(&pack_garbage, 0);
64}
65
66static void report_pack_garbage(unsigned seen_bits, const char *path)
67{
68 if (seen_bits == PACKDIR_FILE_IDX)
69 string_list_append(&pack_garbage, path);
70}
71
72static void process_log_file(void)
73{
74 struct stat st;
75 if (fstat(get_lock_file_fd(&log_lock), &st)) {
76 /*
77 * Perhaps there was an i/o error or another
78 * unlikely situation. Try to make a note of
79 * this in gc.log along with any existing
80 * messages.
81 */
82 int saved_errno = errno;
83 fprintf(stderr, _("Failed to fstat %s: %s"),
84 get_tempfile_path(log_lock.tempfile),
85 strerror(saved_errno));
86 fflush(stderr);
87 commit_lock_file(&log_lock);
88 errno = saved_errno;
89 } else if (st.st_size) {
90 /* There was some error recorded in the lock file */
91 commit_lock_file(&log_lock);
92 } else {
93 /* No error, clean up any old gc.log */
94 unlink(git_path("gc.log"));
95 rollback_lock_file(&log_lock);
96 }
97}
98
99static void process_log_file_at_exit(void)
100{
101 fflush(stderr);
102 process_log_file();
103}
104
105static void process_log_file_on_signal(int signo)
106{
107 process_log_file();
108 sigchain_pop(signo);
109 raise(signo);
110}
111
112static void gc_config(void)
113{
114 const char *value;
115
116 if (!git_config_get_value("gc.packrefs", &value)) {
117 if (value && !strcmp(value, "notbare"))
118 pack_refs = -1;
119 else
120 pack_refs = git_config_bool("gc.packrefs", value);
121 }
122
123 git_config_get_int("gc.aggressivewindow", &aggressive_window);
124 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
125 git_config_get_int("gc.auto", &gc_auto_threshold);
126 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
127 git_config_get_bool("gc.autodetach", &detach_auto);
128 git_config_get_expiry("gc.pruneexpire", &prune_expire);
129 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
130 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
131
132 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
133
134 git_config(git_default_config, NULL);
135}
136
137static int too_many_loose_objects(void)
138{
139 /*
140 * Quickly check if a "gc" is needed, by estimating how
141 * many loose objects there are. Because SHA-1 is evenly
142 * distributed, we can check only one and get a reasonable
143 * estimate.
144 */
145 DIR *dir;
146 struct dirent *ent;
147 int auto_threshold;
148 int num_loose = 0;
149 int needed = 0;
150
151 if (gc_auto_threshold <= 0)
152 return 0;
153
154 dir = opendir(git_path("objects/17"));
155 if (!dir)
156 return 0;
157
158 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
159 while ((ent = readdir(dir)) != NULL) {
160 if (strspn(ent->d_name, "0123456789abcdef") != 38 ||
161 ent->d_name[38] != '\0')
162 continue;
163 if (++num_loose > auto_threshold) {
164 needed = 1;
165 break;
166 }
167 }
168 closedir(dir);
169 return needed;
170}
171
172static void find_base_packs(struct string_list *packs, unsigned long limit)
173{
174 struct packed_git *p, *base = NULL;
175
176 for (p = get_packed_git(the_repository); p; p = p->next) {
177 if (!p->pack_local)
178 continue;
179 if (limit) {
180 if (p->pack_size >= limit)
181 string_list_append(packs, p->pack_name);
182 } else if (!base || base->pack_size < p->pack_size) {
183 base = p;
184 }
185 }
186
187 if (base)
188 string_list_append(packs, base->pack_name);
189}
190
191static int too_many_packs(void)
192{
193 struct packed_git *p;
194 int cnt;
195
196 if (gc_auto_pack_limit <= 0)
197 return 0;
198
199 for (cnt = 0, p = get_packed_git(the_repository); p; p = p->next) {
200 if (!p->pack_local)
201 continue;
202 if (p->pack_keep)
203 continue;
204 /*
205 * Perhaps check the size of the pack and count only
206 * very small ones here?
207 */
208 cnt++;
209 }
210 return gc_auto_pack_limit < cnt;
211}
212
213static int keep_one_pack(struct string_list_item *item, void *data)
214{
215 argv_array_pushf(&repack, "--keep-pack=%s", basename(item->string));
216 return 0;
217}
218
219static void add_repack_all_option(struct string_list *keep_pack)
220{
221 if (prune_expire && !strcmp(prune_expire, "now"))
222 argv_array_push(&repack, "-a");
223 else {
224 argv_array_push(&repack, "-A");
225 if (prune_expire)
226 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
227 }
228
229 if (keep_pack)
230 for_each_string_list(keep_pack, keep_one_pack, NULL);
231}
232
233static void add_repack_incremental_option(void)
234{
235 argv_array_push(&repack, "--no-write-bitmap-index");
236}
237
238static int need_to_gc(void)
239{
240 /*
241 * Setting gc.auto to 0 or negative can disable the
242 * automatic gc.
243 */
244 if (gc_auto_threshold <= 0)
245 return 0;
246
247 /*
248 * If there are too many loose objects, but not too many
249 * packs, we run "repack -d -l". If there are too many packs,
250 * we run "repack -A -d -l". Otherwise we tell the caller
251 * there is no need.
252 */
253 if (too_many_packs()) {
254 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
255
256 if (big_pack_threshold) {
257 find_base_packs(&keep_pack, big_pack_threshold);
258 if (keep_pack.nr >= gc_auto_pack_limit) {
259 big_pack_threshold = 0;
260 string_list_clear(&keep_pack, 0);
261 find_base_packs(&keep_pack, 0);
262 }
263 }
264
265 add_repack_all_option(&keep_pack);
266 string_list_clear(&keep_pack, 0);
267 } else if (too_many_loose_objects())
268 add_repack_incremental_option();
269 else
270 return 0;
271
272 if (run_hook_le(NULL, "pre-auto-gc", NULL))
273 return 0;
274 return 1;
275}
276
277/* return NULL on success, else hostname running the gc */
278static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
279{
280 static struct lock_file lock;
281 char my_host[HOST_NAME_MAX + 1];
282 struct strbuf sb = STRBUF_INIT;
283 struct stat st;
284 uintmax_t pid;
285 FILE *fp;
286 int fd;
287 char *pidfile_path;
288
289 if (is_tempfile_active(pidfile))
290 /* already locked */
291 return NULL;
292
293 if (xgethostname(my_host, sizeof(my_host)))
294 xsnprintf(my_host, sizeof(my_host), "unknown");
295
296 pidfile_path = git_pathdup("gc.pid");
297 fd = hold_lock_file_for_update(&lock, pidfile_path,
298 LOCK_DIE_ON_ERROR);
299 if (!force) {
300 static char locking_host[HOST_NAME_MAX + 1];
301 static char *scan_fmt;
302 int should_exit;
303
304 if (!scan_fmt)
305 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
306 fp = fopen(pidfile_path, "r");
307 memset(locking_host, 0, sizeof(locking_host));
308 should_exit =
309 fp != NULL &&
310 !fstat(fileno(fp), &st) &&
311 /*
312 * 12 hour limit is very generous as gc should
313 * never take that long. On the other hand we
314 * don't really need a strict limit here,
315 * running gc --auto one day late is not a big
316 * problem. --force can be used in manual gc
317 * after the user verifies that no gc is
318 * running.
319 */
320 time(NULL) - st.st_mtime <= 12 * 3600 &&
321 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
322 /* be gentle to concurrent "gc" on remote hosts */
323 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
324 if (fp != NULL)
325 fclose(fp);
326 if (should_exit) {
327 if (fd >= 0)
328 rollback_lock_file(&lock);
329 *ret_pid = pid;
330 free(pidfile_path);
331 return locking_host;
332 }
333 }
334
335 strbuf_addf(&sb, "%"PRIuMAX" %s",
336 (uintmax_t) getpid(), my_host);
337 write_in_full(fd, sb.buf, sb.len);
338 strbuf_release(&sb);
339 commit_lock_file(&lock);
340 pidfile = register_tempfile(pidfile_path);
341 free(pidfile_path);
342 return NULL;
343}
344
345static int report_last_gc_error(void)
346{
347 struct strbuf sb = STRBUF_INIT;
348 int ret = 0;
349 struct stat st;
350 char *gc_log_path = git_pathdup("gc.log");
351
352 if (stat(gc_log_path, &st)) {
353 if (errno == ENOENT)
354 goto done;
355
356 ret = error_errno(_("Can't stat %s"), gc_log_path);
357 goto done;
358 }
359
360 if (st.st_mtime < gc_log_expire_time)
361 goto done;
362
363 ret = strbuf_read_file(&sb, gc_log_path, 0);
364 if (ret > 0)
365 ret = error(_("The last gc run reported the following. "
366 "Please correct the root cause\n"
367 "and remove %s.\n"
368 "Automatic cleanup will not be performed "
369 "until the file is removed.\n\n"
370 "%s"),
371 gc_log_path, sb.buf);
372 strbuf_release(&sb);
373done:
374 free(gc_log_path);
375 return ret;
376}
377
378static int gc_before_repack(void)
379{
380 if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
381 return error(FAILED_RUN, pack_refs_cmd.argv[0]);
382
383 if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
384 return error(FAILED_RUN, reflog.argv[0]);
385
386 pack_refs = 0;
387 prune_reflogs = 0;
388 return 0;
389}
390
391int cmd_gc(int argc, const char **argv, const char *prefix)
392{
393 int aggressive = 0;
394 int auto_gc = 0;
395 int quiet = 0;
396 int force = 0;
397 const char *name;
398 pid_t pid;
399 int daemonized = 0;
400 int keep_base_pack = -1;
401
402 struct option builtin_gc_options[] = {
403 OPT__QUIET(&quiet, N_("suppress progress reporting")),
404 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
405 N_("prune unreferenced objects"),
406 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
407 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
408 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
409 PARSE_OPT_NOCOMPLETE),
410 OPT_BOOL_F(0, "force", &force,
411 N_("force running gc even if there may be another gc running"),
412 PARSE_OPT_NOCOMPLETE),
413 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
414 N_("repack all other packs except the largest pack")),
415 OPT_END()
416 };
417
418 if (argc == 2 && !strcmp(argv[1], "-h"))
419 usage_with_options(builtin_gc_usage, builtin_gc_options);
420
421 argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
422 argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
423 argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
424 argv_array_pushl(&prune, "prune", "--expire", NULL);
425 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
426 argv_array_pushl(&rerere, "rerere", "gc", NULL);
427
428 /* default expiry time, overwritten in gc_config */
429 gc_config();
430 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
431 die(_("Failed to parse gc.logexpiry value %s"), gc_log_expire);
432
433 if (pack_refs < 0)
434 pack_refs = !is_bare_repository();
435
436 argc = parse_options(argc, argv, prefix, builtin_gc_options,
437 builtin_gc_usage, 0);
438 if (argc > 0)
439 usage_with_options(builtin_gc_usage, builtin_gc_options);
440
441 if (aggressive) {
442 argv_array_push(&repack, "-f");
443 if (aggressive_depth > 0)
444 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
445 if (aggressive_window > 0)
446 argv_array_pushf(&repack, "--window=%d", aggressive_window);
447 }
448 if (quiet)
449 argv_array_push(&repack, "-q");
450
451 if (auto_gc) {
452 /*
453 * Auto-gc should be least intrusive as possible.
454 */
455 if (!need_to_gc())
456 return 0;
457 if (!quiet) {
458 if (detach_auto)
459 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
460 else
461 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
462 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
463 }
464 if (detach_auto) {
465 if (report_last_gc_error())
466 return -1;
467
468 if (lock_repo_for_gc(force, &pid))
469 return 0;
470 if (gc_before_repack())
471 return -1;
472 delete_tempfile(&pidfile);
473
474 /*
475 * failure to daemonize is ok, we'll continue
476 * in foreground
477 */
478 daemonized = !daemonize();
479 }
480 } else {
481 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
482
483 if (keep_base_pack != -1) {
484 if (keep_base_pack)
485 find_base_packs(&keep_pack, 0);
486 } else if (big_pack_threshold) {
487 find_base_packs(&keep_pack, big_pack_threshold);
488 }
489
490 add_repack_all_option(&keep_pack);
491 string_list_clear(&keep_pack, 0);
492 }
493
494 name = lock_repo_for_gc(force, &pid);
495 if (name) {
496 if (auto_gc)
497 return 0; /* be quiet on --auto */
498 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
499 name, (uintmax_t)pid);
500 }
501
502 if (daemonized) {
503 hold_lock_file_for_update(&log_lock,
504 git_path("gc.log"),
505 LOCK_DIE_ON_ERROR);
506 dup2(get_lock_file_fd(&log_lock), 2);
507 sigchain_push_common(process_log_file_on_signal);
508 atexit(process_log_file_at_exit);
509 }
510
511 if (gc_before_repack())
512 return -1;
513
514 if (!repository_format_precious_objects) {
515 if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
516 return error(FAILED_RUN, repack.argv[0]);
517
518 if (prune_expire) {
519 argv_array_push(&prune, prune_expire);
520 if (quiet)
521 argv_array_push(&prune, "--no-progress");
522 if (repository_format_partial_clone)
523 argv_array_push(&prune,
524 "--exclude-promisor-objects");
525 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
526 return error(FAILED_RUN, prune.argv[0]);
527 }
528 }
529
530 if (prune_worktrees_expire) {
531 argv_array_push(&prune_worktrees, prune_worktrees_expire);
532 if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
533 return error(FAILED_RUN, prune_worktrees.argv[0]);
534 }
535
536 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
537 return error(FAILED_RUN, rerere.argv[0]);
538
539 report_garbage = report_pack_garbage;
540 reprepare_packed_git(the_repository);
541 if (pack_garbage.nr > 0)
542 clean_pack_garbage();
543
544 if (auto_gc && too_many_loose_objects())
545 warning(_("There are too many unreachable loose objects; "
546 "run 'git prune' to remove them."));
547
548 if (!daemonized)
549 unlink(git_path("gc.log"));
550
551 return 0;
552}