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