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