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