]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/gc.c
gc: handle a corner case in gc.bigPackThreshold
[thirdparty/git.git] / builtin / gc.c
CommitLineData
6757ada4
JB
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
baffc0e7 13#include "builtin.h"
a80d72db 14#include "repository.h"
b2141fc1 15#include "config.h"
ebebeaea 16#include "tempfile.h"
697cc8ef 17#include "lockfile.h"
44c637c8 18#include "parse-options.h"
6757ada4 19#include "run-command.h"
4c5baf02 20#include "sigchain.h"
234587fc 21#include "argv-array.h"
eab3296c 22#include "commit.h"
0abe14f6 23#include "packfile.h"
a80d72db 24#include "object-store.h"
6757ada4
JB
25
26#define FAILED_RUN "failed to run %s"
27
44c637c8 28static const char * const builtin_gc_usage[] = {
9c9b4f2f 29 N_("git gc [<options>]"),
44c637c8
JB
30 NULL
31};
6757ada4 32
56752391 33static int pack_refs = 1;
62aad184 34static int prune_reflogs = 1;
07e7dbf0 35static int aggressive_depth = 50;
1c192f34 36static int aggressive_window = 250;
2c3c4399 37static int gc_auto_threshold = 6700;
97063974 38static int gc_auto_pack_limit = 50;
9f673f94 39static int detach_auto = 1;
dddbad72 40static timestamp_t gc_log_expire_time;
a831c06a 41static const char *gc_log_expire = "1.day.ago";
d3154b44 42static const char *prune_expire = "2.weeks.ago";
e3df33bb 43static const char *prune_worktrees_expire = "3.months.ago";
55dfe13d 44static unsigned long big_pack_threshold;
6757ada4 45
234587fc
JK
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;
e3df33bb 50static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
234587fc 51static struct argv_array rerere = ARGV_ARRAY_INIT;
6757ada4 52
076aa2cb 53static struct tempfile *pidfile;
329e6e87 54static struct lock_file log_lock;
4c5baf02 55
478f34d2
DK
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
329e6e87
NTND
72static void process_log_file(void)
73{
74 struct stat st;
a831c06a
DT
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"),
076aa2cb 84 get_tempfile_path(log_lock.tempfile),
a831c06a
DT
85 strerror(saved_errno));
86 fflush(stderr);
329e6e87 87 commit_lock_file(&log_lock);
a831c06a
DT
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"));
329e6e87 95 rollback_lock_file(&log_lock);
a831c06a 96 }
329e6e87
NTND
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
5801d3b4 112static void gc_config(void)
6757ada4 113{
5801d3b4
TA
114 const char *value;
115
116 if (!git_config_get_value("gc.packrefs", &value)) {
c5e5a2c0 117 if (value && !strcmp(value, "notbare"))
6757ada4
JB
118 pack_refs = -1;
119 else
5801d3b4 120 pack_refs = git_config_bool("gc.packrefs", value);
17815501 121 }
5801d3b4
TA
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);
77d67977
CC
128 git_config_get_expiry("gc.pruneexpire", &prune_expire);
129 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
94c9b5af 130 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
a831c06a 131
55dfe13d
NTND
132 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
133
5801d3b4 134 git_config(git_default_config, NULL);
6757ada4
JB
135}
136
a087cc98 137static int too_many_loose_objects(void)
2c3c4399
JH
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 */
2c3c4399
JH
145 DIR *dir;
146 struct dirent *ent;
147 int auto_threshold;
148 int num_loose = 0;
149 int needed = 0;
150
17815501
JH
151 if (gc_auto_threshold <= 0)
152 return 0;
153
07af8891 154 dir = opendir(git_path("objects/17"));
2c3c4399
JH
155 if (!dir)
156 return 0;
157
42c78a21 158 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
2c3c4399
JH
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
55dfe13d 172static void find_base_packs(struct string_list *packs, unsigned long limit)
ae4e89e5
NTND
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;
55dfe13d
NTND
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) {
ae4e89e5
NTND
183 base = p;
184 }
185 }
186
187 if (base)
188 string_list_append(packs, base->pack_name);
189}
190
17815501
JH
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
a80d72db 199 for (cnt = 0, p = get_packed_git(the_repository); p; p = p->next) {
17815501
JH
200 if (!p->pack_local)
201 continue;
01af249f 202 if (p->pack_keep)
17815501
JH
203 continue;
204 /*
205 * Perhaps check the size of the pack and count only
206 * very small ones here?
207 */
208 cnt++;
209 }
5f4e3bf5 210 return gc_auto_pack_limit < cnt;
17815501
JH
211}
212
ae4e89e5
NTND
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)
7e52f566
JK
220{
221 if (prune_expire && !strcmp(prune_expire, "now"))
234587fc 222 argv_array_push(&repack, "-a");
7e52f566 223 else {
234587fc
JK
224 argv_array_push(&repack, "-A");
225 if (prune_expire)
226 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
7e52f566 227 }
ae4e89e5
NTND
228
229 if (keep_pack)
230 for_each_string_list(keep_pack, keep_one_pack, NULL);
7e52f566
JK
231}
232
bdf56de8
DT
233static void add_repack_incremental_option(void)
234{
235 argv_array_push(&repack, "--no-write-bitmap-index");
236}
237
a087cc98
JH
238static int need_to_gc(void)
239{
240 /*
b14d255b
BC
241 * Setting gc.auto to 0 or negative can disable the
242 * automatic gc.
a087cc98 243 */
b14d255b 244 if (gc_auto_threshold <= 0)
95143f9e
JH
245 return 0;
246
17815501
JH
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 */
55dfe13d
NTND
253 if (too_many_packs()) {
254 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
255
8fc67762 256 if (big_pack_threshold) {
55dfe13d 257 find_base_packs(&keep_pack, big_pack_threshold);
8fc67762
NTND
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 }
55dfe13d
NTND
264
265 add_repack_all_option(&keep_pack);
266 string_list_clear(&keep_pack, 0);
267 } else if (too_many_loose_objects())
bdf56de8
DT
268 add_repack_incremental_option();
269 else
17815501 270 return 0;
bde30540 271
15048f8a 272 if (run_hook_le(NULL, "pre-auto-gc", NULL))
bde30540 273 return 0;
95143f9e 274 return 1;
a087cc98
JH
275}
276
64a99eb4
NTND
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;
da25bdb7 281 char my_host[HOST_NAME_MAX + 1];
64a99eb4
NTND
282 struct strbuf sb = STRBUF_INIT;
283 struct stat st;
284 uintmax_t pid;
285 FILE *fp;
4f1c0b21 286 int fd;
00539cef 287 char *pidfile_path;
64a99eb4 288
076aa2cb 289 if (is_tempfile_active(pidfile))
4c5baf02
JN
290 /* already locked */
291 return NULL;
292
5781a9a2 293 if (xgethostname(my_host, sizeof(my_host)))
5096d490 294 xsnprintf(my_host, sizeof(my_host), "unknown");
64a99eb4 295
00539cef
MH
296 pidfile_path = git_pathdup("gc.pid");
297 fd = hold_lock_file_for_update(&lock, pidfile_path,
64a99eb4
NTND
298 LOCK_DIE_ON_ERROR);
299 if (!force) {
da25bdb7
RS
300 static char locking_host[HOST_NAME_MAX + 1];
301 static char *scan_fmt;
4f1c0b21 302 int should_exit;
da25bdb7
RS
303
304 if (!scan_fmt)
afe2fab7 305 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
00539cef 306 fp = fopen(pidfile_path, "r");
64a99eb4
NTND
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 &&
da25bdb7 321 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
64a99eb4 322 /* be gentle to concurrent "gc" on remote hosts */
ed7eda8b 323 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
64a99eb4
NTND
324 if (fp != NULL)
325 fclose(fp);
326 if (should_exit) {
327 if (fd >= 0)
328 rollback_lock_file(&lock);
329 *ret_pid = pid;
00539cef 330 free(pidfile_path);
64a99eb4
NTND
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);
076aa2cb 340 pidfile = register_tempfile(pidfile_path);
ebebeaea 341 free(pidfile_path);
64a99eb4
NTND
342 return NULL;
343}
344
329e6e87
NTND
345static int report_last_gc_error(void)
346{
347 struct strbuf sb = STRBUF_INIT;
a831c06a
DT
348 int ret = 0;
349 struct stat st;
350 char *gc_log_path = git_pathdup("gc.log");
329e6e87 351
a831c06a
DT
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);
329e6e87 364 if (ret > 0)
a831c06a 365 ret = error(_("The last gc run reported the following. "
329e6e87
NTND
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"),
a831c06a 371 gc_log_path, sb.buf);
329e6e87 372 strbuf_release(&sb);
a831c06a
DT
373done:
374 free(gc_log_path);
375 return ret;
329e6e87
NTND
376}
377
62aad184
NTND
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
6757ada4
JB
391int cmd_gc(int argc, const char **argv, const char *prefix)
392{
44c637c8 393 int aggressive = 0;
2c3c4399 394 int auto_gc = 0;
a0c14cbb 395 int quiet = 0;
64a99eb4
NTND
396 int force = 0;
397 const char *name;
398 pid_t pid;
329e6e87 399 int daemonized = 0;
ae4e89e5 400 int keep_base_pack = -1;
6757ada4 401
44c637c8 402 struct option builtin_gc_options[] = {
6705c162
NTND
403 OPT__QUIET(&quiet, N_("suppress progress reporting")),
404 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
405 N_("prune unreferenced objects"),
58e9d9d4 406 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
d5d09d47 407 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
7e1eeaa4
NTND
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),
ae4e89e5
NTND
413 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
414 N_("repack all other packs except the largest pack")),
44c637c8
JB
415 OPT_END()
416 };
417
0c8151b6
NTND
418 if (argc == 2 && !strcmp(argv[1], "-h"))
419 usage_with_options(builtin_gc_usage, builtin_gc_options);
420
234587fc
JK
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);
2cfe2a78 424 argv_array_pushl(&prune, "prune", "--expire", NULL);
df0b6cfb 425 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
234587fc
JK
426 argv_array_pushl(&rerere, "rerere", "gc", NULL);
427
a831c06a 428 /* default expiry time, overwritten in gc_config */
5801d3b4 429 gc_config();
a831c06a
DT
430 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
431 die(_("Failed to parse gc.logexpiry value %s"), gc_log_expire);
6757ada4
JB
432
433 if (pack_refs < 0)
434 pack_refs = !is_bare_repository();
435
37782920
SB
436 argc = parse_options(argc, argv, prefix, builtin_gc_options,
437 builtin_gc_usage, 0);
44c637c8
JB
438 if (argc > 0)
439 usage_with_options(builtin_gc_usage, builtin_gc_options);
440
441 if (aggressive) {
234587fc 442 argv_array_push(&repack, "-f");
125f8146
NTND
443 if (aggressive_depth > 0)
444 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
234587fc
JK
445 if (aggressive_window > 0)
446 argv_array_pushf(&repack, "--window=%d", aggressive_window);
6757ada4 447 }
a0c14cbb 448 if (quiet)
234587fc 449 argv_array_push(&repack, "-q");
6757ada4 450
2c3c4399
JH
451 if (auto_gc) {
452 /*
453 * Auto-gc should be least intrusive as possible.
454 */
2c3c4399
JH
455 if (!need_to_gc())
456 return 0;
9f673f94
NTND
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 }
62aad184 464 if (detach_auto) {
329e6e87
NTND
465 if (report_last_gc_error())
466 return -1;
467
c45af94d
JK
468 if (lock_repo_for_gc(force, &pid))
469 return 0;
62aad184
NTND
470 if (gc_before_repack())
471 return -1;
c45af94d
JK
472 delete_tempfile(&pidfile);
473
9f673f94
NTND
474 /*
475 * failure to daemonize is ok, we'll continue
476 * in foreground
477 */
329e6e87 478 daemonized = !daemonize();
62aad184 479 }
ae4e89e5
NTND
480 } else {
481 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
482
483 if (keep_base_pack != -1) {
484 if (keep_base_pack)
55dfe13d
NTND
485 find_base_packs(&keep_pack, 0);
486 } else if (big_pack_threshold) {
487 find_base_packs(&keep_pack, big_pack_threshold);
ae4e89e5
NTND
488 }
489
490 add_repack_all_option(&keep_pack);
491 string_list_clear(&keep_pack, 0);
492 }
2c3c4399 493
64a99eb4
NTND
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
329e6e87
NTND
502 if (daemonized) {
503 hold_lock_file_for_update(&log_lock,
504 git_path("gc.log"),
505 LOCK_DIE_ON_ERROR);
076c8278 506 dup2(get_lock_file_fd(&log_lock), 2);
329e6e87
NTND
507 sigchain_push_common(process_log_file_on_signal);
508 atexit(process_log_file_at_exit);
509 }
510
62aad184
NTND
511 if (gc_before_repack())
512 return -1;
6757ada4 513
067fbd41
JK
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");
0c16cd49
JT
522 if (repository_format_partial_clone)
523 argv_array_push(&prune,
524 "--exclude-promisor-objects");
067fbd41
JK
525 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
526 return error(FAILED_RUN, prune.argv[0]);
527 }
58e9d9d4 528 }
6757ada4 529
e3df33bb
NTND
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
234587fc
JK
536 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
537 return error(FAILED_RUN, rerere.argv[0]);
6757ada4 538
478f34d2 539 report_garbage = report_pack_garbage;
a49d2834 540 reprepare_packed_git(the_repository);
478f34d2
DK
541 if (pack_garbage.nr > 0)
542 clean_pack_garbage();
543
a087cc98 544 if (auto_gc && too_many_loose_objects())
fea6128b
ÆAB
545 warning(_("There are too many unreachable loose objects; "
546 "run 'git prune' to remove them."));
a087cc98 547
a831c06a
DT
548 if (!daemonized)
549 unlink(git_path("gc.log"));
550
6757ada4
JB
551 return 0;
552}