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