Merge branch 'ds/maintenance-part-2'
[git] / builtin / gc.c
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 "repository.h"
15 #include "config.h"
16 #include "tempfile.h"
17 #include "lockfile.h"
18 #include "parse-options.h"
19 #include "run-command.h"
20 #include "sigchain.h"
21 #include "strvec.h"
22 #include "commit.h"
23 #include "commit-graph.h"
24 #include "packfile.h"
25 #include "object-store.h"
26 #include "pack.h"
27 #include "pack-objects.h"
28 #include "blob.h"
29 #include "tree.h"
30 #include "promisor-remote.h"
31 #include "refs.h"
32 #include "remote.h"
33 #include "object-store.h"
34
35 #define FAILED_RUN "failed to run %s"
36
37 static const char * const builtin_gc_usage[] = {
38         N_("git gc [<options>]"),
39         NULL
40 };
41
42 static int pack_refs = 1;
43 static int prune_reflogs = 1;
44 static int aggressive_depth = 50;
45 static int aggressive_window = 250;
46 static int gc_auto_threshold = 6700;
47 static int gc_auto_pack_limit = 50;
48 static int detach_auto = 1;
49 static timestamp_t gc_log_expire_time;
50 static const char *gc_log_expire = "1.day.ago";
51 static const char *prune_expire = "2.weeks.ago";
52 static const char *prune_worktrees_expire = "3.months.ago";
53 static unsigned long big_pack_threshold;
54 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
55
56 static struct strvec pack_refs_cmd = STRVEC_INIT;
57 static struct strvec reflog = STRVEC_INIT;
58 static struct strvec repack = STRVEC_INIT;
59 static struct strvec prune = STRVEC_INIT;
60 static struct strvec prune_worktrees = STRVEC_INIT;
61 static struct strvec rerere = STRVEC_INIT;
62
63 static struct tempfile *pidfile;
64 static struct lock_file log_lock;
65
66 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
67
68 static void clean_pack_garbage(void)
69 {
70         int i;
71         for (i = 0; i < pack_garbage.nr; i++)
72                 unlink_or_warn(pack_garbage.items[i].string);
73         string_list_clear(&pack_garbage, 0);
74 }
75
76 static void report_pack_garbage(unsigned seen_bits, const char *path)
77 {
78         if (seen_bits == PACKDIR_FILE_IDX)
79                 string_list_append(&pack_garbage, path);
80 }
81
82 static void process_log_file(void)
83 {
84         struct stat st;
85         if (fstat(get_lock_file_fd(&log_lock), &st)) {
86                 /*
87                  * Perhaps there was an i/o error or another
88                  * unlikely situation.  Try to make a note of
89                  * this in gc.log along with any existing
90                  * messages.
91                  */
92                 int saved_errno = errno;
93                 fprintf(stderr, _("Failed to fstat %s: %s"),
94                         get_tempfile_path(log_lock.tempfile),
95                         strerror(saved_errno));
96                 fflush(stderr);
97                 commit_lock_file(&log_lock);
98                 errno = saved_errno;
99         } else if (st.st_size) {
100                 /* There was some error recorded in the lock file */
101                 commit_lock_file(&log_lock);
102         } else {
103                 /* No error, clean up any old gc.log */
104                 unlink(git_path("gc.log"));
105                 rollback_lock_file(&log_lock);
106         }
107 }
108
109 static void process_log_file_at_exit(void)
110 {
111         fflush(stderr);
112         process_log_file();
113 }
114
115 static void process_log_file_on_signal(int signo)
116 {
117         process_log_file();
118         sigchain_pop(signo);
119         raise(signo);
120 }
121
122 static int gc_config_is_timestamp_never(const char *var)
123 {
124         const char *value;
125         timestamp_t expire;
126
127         if (!git_config_get_value(var, &value) && value) {
128                 if (parse_expiry_date(value, &expire))
129                         die(_("failed to parse '%s' value '%s'"), var, value);
130                 return expire == 0;
131         }
132         return 0;
133 }
134
135 static void gc_config(void)
136 {
137         const char *value;
138
139         if (!git_config_get_value("gc.packrefs", &value)) {
140                 if (value && !strcmp(value, "notbare"))
141                         pack_refs = -1;
142                 else
143                         pack_refs = git_config_bool("gc.packrefs", value);
144         }
145
146         if (gc_config_is_timestamp_never("gc.reflogexpire") &&
147             gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
148                 prune_reflogs = 0;
149
150         git_config_get_int("gc.aggressivewindow", &aggressive_window);
151         git_config_get_int("gc.aggressivedepth", &aggressive_depth);
152         git_config_get_int("gc.auto", &gc_auto_threshold);
153         git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
154         git_config_get_bool("gc.autodetach", &detach_auto);
155         git_config_get_expiry("gc.pruneexpire", &prune_expire);
156         git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
157         git_config_get_expiry("gc.logexpiry", &gc_log_expire);
158
159         git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
160         git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
161
162         git_config(git_default_config, NULL);
163 }
164
165 static int too_many_loose_objects(void)
166 {
167         /*
168          * Quickly check if a "gc" is needed, by estimating how
169          * many loose objects there are.  Because SHA-1 is evenly
170          * distributed, we can check only one and get a reasonable
171          * estimate.
172          */
173         DIR *dir;
174         struct dirent *ent;
175         int auto_threshold;
176         int num_loose = 0;
177         int needed = 0;
178         const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
179
180         dir = opendir(git_path("objects/17"));
181         if (!dir)
182                 return 0;
183
184         auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
185         while ((ent = readdir(dir)) != NULL) {
186                 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
187                     ent->d_name[hexsz_loose] != '\0')
188                         continue;
189                 if (++num_loose > auto_threshold) {
190                         needed = 1;
191                         break;
192                 }
193         }
194         closedir(dir);
195         return needed;
196 }
197
198 static struct packed_git *find_base_packs(struct string_list *packs,
199                                           unsigned long limit)
200 {
201         struct packed_git *p, *base = NULL;
202
203         for (p = get_all_packs(the_repository); p; p = p->next) {
204                 if (!p->pack_local)
205                         continue;
206                 if (limit) {
207                         if (p->pack_size >= limit)
208                                 string_list_append(packs, p->pack_name);
209                 } else if (!base || base->pack_size < p->pack_size) {
210                         base = p;
211                 }
212         }
213
214         if (base)
215                 string_list_append(packs, base->pack_name);
216
217         return base;
218 }
219
220 static int too_many_packs(void)
221 {
222         struct packed_git *p;
223         int cnt;
224
225         if (gc_auto_pack_limit <= 0)
226                 return 0;
227
228         for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
229                 if (!p->pack_local)
230                         continue;
231                 if (p->pack_keep)
232                         continue;
233                 /*
234                  * Perhaps check the size of the pack and count only
235                  * very small ones here?
236                  */
237                 cnt++;
238         }
239         return gc_auto_pack_limit < cnt;
240 }
241
242 static uint64_t total_ram(void)
243 {
244 #if defined(HAVE_SYSINFO)
245         struct sysinfo si;
246
247         if (!sysinfo(&si))
248                 return si.totalram;
249 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
250         int64_t physical_memory;
251         int mib[2];
252         size_t length;
253
254         mib[0] = CTL_HW;
255 # if defined(HW_MEMSIZE)
256         mib[1] = HW_MEMSIZE;
257 # else
258         mib[1] = HW_PHYSMEM;
259 # endif
260         length = sizeof(int64_t);
261         if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
262                 return physical_memory;
263 #elif defined(GIT_WINDOWS_NATIVE)
264         MEMORYSTATUSEX memInfo;
265
266         memInfo.dwLength = sizeof(MEMORYSTATUSEX);
267         if (GlobalMemoryStatusEx(&memInfo))
268                 return memInfo.ullTotalPhys;
269 #endif
270         return 0;
271 }
272
273 static uint64_t estimate_repack_memory(struct packed_git *pack)
274 {
275         unsigned long nr_objects = approximate_object_count();
276         size_t os_cache, heap;
277
278         if (!pack || !nr_objects)
279                 return 0;
280
281         /*
282          * First we have to scan through at least one pack.
283          * Assume enough room in OS file cache to keep the entire pack
284          * or we may accidentally evict data of other processes from
285          * the cache.
286          */
287         os_cache = pack->pack_size + pack->index_size;
288         /* then pack-objects needs lots more for book keeping */
289         heap = sizeof(struct object_entry) * nr_objects;
290         /*
291          * internal rev-list --all --objects takes up some memory too,
292          * let's say half of it is for blobs
293          */
294         heap += sizeof(struct blob) * nr_objects / 2;
295         /*
296          * and the other half is for trees (commits and tags are
297          * usually insignificant)
298          */
299         heap += sizeof(struct tree) * nr_objects / 2;
300         /* and then obj_hash[], underestimated in fact */
301         heap += sizeof(struct object *) * nr_objects;
302         /* revindex is used also */
303         heap += sizeof(struct revindex_entry) * nr_objects;
304         /*
305          * read_sha1_file() (either at delta calculation phase, or
306          * writing phase) also fills up the delta base cache
307          */
308         heap += delta_base_cache_limit;
309         /* and of course pack-objects has its own delta cache */
310         heap += max_delta_cache_size;
311
312         return os_cache + heap;
313 }
314
315 static int keep_one_pack(struct string_list_item *item, void *data)
316 {
317         strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
318         return 0;
319 }
320
321 static void add_repack_all_option(struct string_list *keep_pack)
322 {
323         if (prune_expire && !strcmp(prune_expire, "now"))
324                 strvec_push(&repack, "-a");
325         else {
326                 strvec_push(&repack, "-A");
327                 if (prune_expire)
328                         strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
329         }
330
331         if (keep_pack)
332                 for_each_string_list(keep_pack, keep_one_pack, NULL);
333 }
334
335 static void add_repack_incremental_option(void)
336 {
337         strvec_push(&repack, "--no-write-bitmap-index");
338 }
339
340 static int need_to_gc(void)
341 {
342         /*
343          * Setting gc.auto to 0 or negative can disable the
344          * automatic gc.
345          */
346         if (gc_auto_threshold <= 0)
347                 return 0;
348
349         /*
350          * If there are too many loose objects, but not too many
351          * packs, we run "repack -d -l".  If there are too many packs,
352          * we run "repack -A -d -l".  Otherwise we tell the caller
353          * there is no need.
354          */
355         if (too_many_packs()) {
356                 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
357
358                 if (big_pack_threshold) {
359                         find_base_packs(&keep_pack, big_pack_threshold);
360                         if (keep_pack.nr >= gc_auto_pack_limit) {
361                                 big_pack_threshold = 0;
362                                 string_list_clear(&keep_pack, 0);
363                                 find_base_packs(&keep_pack, 0);
364                         }
365                 } else {
366                         struct packed_git *p = find_base_packs(&keep_pack, 0);
367                         uint64_t mem_have, mem_want;
368
369                         mem_have = total_ram();
370                         mem_want = estimate_repack_memory(p);
371
372                         /*
373                          * Only allow 1/2 of memory for pack-objects, leave
374                          * the rest for the OS and other processes in the
375                          * system.
376                          */
377                         if (!mem_have || mem_want < mem_have / 2)
378                                 string_list_clear(&keep_pack, 0);
379                 }
380
381                 add_repack_all_option(&keep_pack);
382                 string_list_clear(&keep_pack, 0);
383         } else if (too_many_loose_objects())
384                 add_repack_incremental_option();
385         else
386                 return 0;
387
388         if (run_hook_le(NULL, "pre-auto-gc", NULL))
389                 return 0;
390         return 1;
391 }
392
393 /* return NULL on success, else hostname running the gc */
394 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
395 {
396         struct lock_file lock = LOCK_INIT;
397         char my_host[HOST_NAME_MAX + 1];
398         struct strbuf sb = STRBUF_INIT;
399         struct stat st;
400         uintmax_t pid;
401         FILE *fp;
402         int fd;
403         char *pidfile_path;
404
405         if (is_tempfile_active(pidfile))
406                 /* already locked */
407                 return NULL;
408
409         if (xgethostname(my_host, sizeof(my_host)))
410                 xsnprintf(my_host, sizeof(my_host), "unknown");
411
412         pidfile_path = git_pathdup("gc.pid");
413         fd = hold_lock_file_for_update(&lock, pidfile_path,
414                                        LOCK_DIE_ON_ERROR);
415         if (!force) {
416                 static char locking_host[HOST_NAME_MAX + 1];
417                 static char *scan_fmt;
418                 int should_exit;
419
420                 if (!scan_fmt)
421                         scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
422                 fp = fopen(pidfile_path, "r");
423                 memset(locking_host, 0, sizeof(locking_host));
424                 should_exit =
425                         fp != NULL &&
426                         !fstat(fileno(fp), &st) &&
427                         /*
428                          * 12 hour limit is very generous as gc should
429                          * never take that long. On the other hand we
430                          * don't really need a strict limit here,
431                          * running gc --auto one day late is not a big
432                          * problem. --force can be used in manual gc
433                          * after the user verifies that no gc is
434                          * running.
435                          */
436                         time(NULL) - st.st_mtime <= 12 * 3600 &&
437                         fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
438                         /* be gentle to concurrent "gc" on remote hosts */
439                         (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
440                 if (fp != NULL)
441                         fclose(fp);
442                 if (should_exit) {
443                         if (fd >= 0)
444                                 rollback_lock_file(&lock);
445                         *ret_pid = pid;
446                         free(pidfile_path);
447                         return locking_host;
448                 }
449         }
450
451         strbuf_addf(&sb, "%"PRIuMAX" %s",
452                     (uintmax_t) getpid(), my_host);
453         write_in_full(fd, sb.buf, sb.len);
454         strbuf_release(&sb);
455         commit_lock_file(&lock);
456         pidfile = register_tempfile(pidfile_path);
457         free(pidfile_path);
458         return NULL;
459 }
460
461 /*
462  * Returns 0 if there was no previous error and gc can proceed, 1 if
463  * gc should not proceed due to an error in the last run. Prints a
464  * message and returns -1 if an error occurred while reading gc.log
465  */
466 static int report_last_gc_error(void)
467 {
468         struct strbuf sb = STRBUF_INIT;
469         int ret = 0;
470         ssize_t len;
471         struct stat st;
472         char *gc_log_path = git_pathdup("gc.log");
473
474         if (stat(gc_log_path, &st)) {
475                 if (errno == ENOENT)
476                         goto done;
477
478                 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
479                 goto done;
480         }
481
482         if (st.st_mtime < gc_log_expire_time)
483                 goto done;
484
485         len = strbuf_read_file(&sb, gc_log_path, 0);
486         if (len < 0)
487                 ret = error_errno(_("cannot read '%s'"), gc_log_path);
488         else if (len > 0) {
489                 /*
490                  * A previous gc failed.  Report the error, and don't
491                  * bother with an automatic gc run since it is likely
492                  * to fail in the same way.
493                  */
494                 warning(_("The last gc run reported the following. "
495                                "Please correct the root cause\n"
496                                "and remove %s.\n"
497                                "Automatic cleanup will not be performed "
498                                "until the file is removed.\n\n"
499                                "%s"),
500                             gc_log_path, sb.buf);
501                 ret = 1;
502         }
503         strbuf_release(&sb);
504 done:
505         free(gc_log_path);
506         return ret;
507 }
508
509 static void gc_before_repack(void)
510 {
511         /*
512          * We may be called twice, as both the pre- and
513          * post-daemonized phases will call us, but running these
514          * commands more than once is pointless and wasteful.
515          */
516         static int done = 0;
517         if (done++)
518                 return;
519
520         if (pack_refs && run_command_v_opt(pack_refs_cmd.v, RUN_GIT_CMD))
521                 die(FAILED_RUN, pack_refs_cmd.v[0]);
522
523         if (prune_reflogs && run_command_v_opt(reflog.v, RUN_GIT_CMD))
524                 die(FAILED_RUN, reflog.v[0]);
525 }
526
527 int cmd_gc(int argc, const char **argv, const char *prefix)
528 {
529         int aggressive = 0;
530         int auto_gc = 0;
531         int quiet = 0;
532         int force = 0;
533         const char *name;
534         pid_t pid;
535         int daemonized = 0;
536         int keep_base_pack = -1;
537         timestamp_t dummy;
538
539         struct option builtin_gc_options[] = {
540                 OPT__QUIET(&quiet, N_("suppress progress reporting")),
541                 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
542                         N_("prune unreferenced objects"),
543                         PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
544                 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
545                 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
546                            PARSE_OPT_NOCOMPLETE),
547                 OPT_BOOL_F(0, "force", &force,
548                            N_("force running gc even if there may be another gc running"),
549                            PARSE_OPT_NOCOMPLETE),
550                 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
551                          N_("repack all other packs except the largest pack")),
552                 OPT_END()
553         };
554
555         if (argc == 2 && !strcmp(argv[1], "-h"))
556                 usage_with_options(builtin_gc_usage, builtin_gc_options);
557
558         strvec_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
559         strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
560         strvec_pushl(&repack, "repack", "-d", "-l", NULL);
561         strvec_pushl(&prune, "prune", "--expire", NULL);
562         strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
563         strvec_pushl(&rerere, "rerere", "gc", NULL);
564
565         /* default expiry time, overwritten in gc_config */
566         gc_config();
567         if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
568                 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
569
570         if (pack_refs < 0)
571                 pack_refs = !is_bare_repository();
572
573         argc = parse_options(argc, argv, prefix, builtin_gc_options,
574                              builtin_gc_usage, 0);
575         if (argc > 0)
576                 usage_with_options(builtin_gc_usage, builtin_gc_options);
577
578         if (prune_expire && parse_expiry_date(prune_expire, &dummy))
579                 die(_("failed to parse prune expiry value %s"), prune_expire);
580
581         if (aggressive) {
582                 strvec_push(&repack, "-f");
583                 if (aggressive_depth > 0)
584                         strvec_pushf(&repack, "--depth=%d", aggressive_depth);
585                 if (aggressive_window > 0)
586                         strvec_pushf(&repack, "--window=%d", aggressive_window);
587         }
588         if (quiet)
589                 strvec_push(&repack, "-q");
590
591         if (auto_gc) {
592                 /*
593                  * Auto-gc should be least intrusive as possible.
594                  */
595                 if (!need_to_gc())
596                         return 0;
597                 if (!quiet) {
598                         if (detach_auto)
599                                 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
600                         else
601                                 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
602                         fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
603                 }
604                 if (detach_auto) {
605                         int ret = report_last_gc_error();
606                         if (ret < 0)
607                                 /* an I/O error occurred, already reported */
608                                 exit(128);
609                         if (ret == 1)
610                                 /* Last gc --auto failed. Skip this one. */
611                                 return 0;
612
613                         if (lock_repo_for_gc(force, &pid))
614                                 return 0;
615                         gc_before_repack(); /* dies on failure */
616                         delete_tempfile(&pidfile);
617
618                         /*
619                          * failure to daemonize is ok, we'll continue
620                          * in foreground
621                          */
622                         daemonized = !daemonize();
623                 }
624         } else {
625                 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
626
627                 if (keep_base_pack != -1) {
628                         if (keep_base_pack)
629                                 find_base_packs(&keep_pack, 0);
630                 } else if (big_pack_threshold) {
631                         find_base_packs(&keep_pack, big_pack_threshold);
632                 }
633
634                 add_repack_all_option(&keep_pack);
635                 string_list_clear(&keep_pack, 0);
636         }
637
638         name = lock_repo_for_gc(force, &pid);
639         if (name) {
640                 if (auto_gc)
641                         return 0; /* be quiet on --auto */
642                 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
643                     name, (uintmax_t)pid);
644         }
645
646         if (daemonized) {
647                 hold_lock_file_for_update(&log_lock,
648                                           git_path("gc.log"),
649                                           LOCK_DIE_ON_ERROR);
650                 dup2(get_lock_file_fd(&log_lock), 2);
651                 sigchain_push_common(process_log_file_on_signal);
652                 atexit(process_log_file_at_exit);
653         }
654
655         gc_before_repack();
656
657         if (!repository_format_precious_objects) {
658                 close_object_store(the_repository->objects);
659                 if (run_command_v_opt(repack.v, RUN_GIT_CMD))
660                         die(FAILED_RUN, repack.v[0]);
661
662                 if (prune_expire) {
663                         strvec_push(&prune, prune_expire);
664                         if (quiet)
665                                 strvec_push(&prune, "--no-progress");
666                         if (has_promisor_remote())
667                                 strvec_push(&prune,
668                                             "--exclude-promisor-objects");
669                         if (run_command_v_opt(prune.v, RUN_GIT_CMD))
670                                 die(FAILED_RUN, prune.v[0]);
671                 }
672         }
673
674         if (prune_worktrees_expire) {
675                 strvec_push(&prune_worktrees, prune_worktrees_expire);
676                 if (run_command_v_opt(prune_worktrees.v, RUN_GIT_CMD))
677                         die(FAILED_RUN, prune_worktrees.v[0]);
678         }
679
680         if (run_command_v_opt(rerere.v, RUN_GIT_CMD))
681                 die(FAILED_RUN, rerere.v[0]);
682
683         report_garbage = report_pack_garbage;
684         reprepare_packed_git(the_repository);
685         if (pack_garbage.nr > 0) {
686                 close_object_store(the_repository->objects);
687                 clean_pack_garbage();
688         }
689
690         prepare_repo_settings(the_repository);
691         if (the_repository->settings.gc_write_commit_graph == 1)
692                 write_commit_graph_reachable(the_repository->objects->odb,
693                                              !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
694                                              NULL);
695
696         if (auto_gc && too_many_loose_objects())
697                 warning(_("There are too many unreachable loose objects; "
698                         "run 'git prune' to remove them."));
699
700         if (!daemonized)
701                 unlink(git_path("gc.log"));
702
703         return 0;
704 }
705
706 static const char * const builtin_maintenance_run_usage[] = {
707         N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>]"),
708         NULL
709 };
710
711 struct maintenance_run_opts {
712         int auto_flag;
713         int quiet;
714 };
715
716 /* Remember to update object flag allocation in object.h */
717 #define SEEN            (1u<<0)
718
719 struct cg_auto_data {
720         int num_not_in_graph;
721         int limit;
722 };
723
724 static int dfs_on_ref(const char *refname,
725                       const struct object_id *oid, int flags,
726                       void *cb_data)
727 {
728         struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
729         int result = 0;
730         struct object_id peeled;
731         struct commit_list *stack = NULL;
732         struct commit *commit;
733
734         if (!peel_ref(refname, &peeled))
735                 oid = &peeled;
736         if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
737                 return 0;
738
739         commit = lookup_commit(the_repository, oid);
740         if (!commit)
741                 return 0;
742         if (parse_commit(commit))
743                 return 0;
744
745         commit_list_append(commit, &stack);
746
747         while (!result && stack) {
748                 struct commit_list *parent;
749
750                 commit = pop_commit(&stack);
751
752                 for (parent = commit->parents; parent; parent = parent->next) {
753                         if (parse_commit(parent->item) ||
754                             commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
755                             parent->item->object.flags & SEEN)
756                                 continue;
757
758                         parent->item->object.flags |= SEEN;
759                         data->num_not_in_graph++;
760
761                         if (data->num_not_in_graph >= data->limit) {
762                                 result = 1;
763                                 break;
764                         }
765
766                         commit_list_append(parent->item, &stack);
767                 }
768         }
769
770         free_commit_list(stack);
771         return result;
772 }
773
774 static int should_write_commit_graph(void)
775 {
776         int result;
777         struct cg_auto_data data;
778
779         data.num_not_in_graph = 0;
780         data.limit = 100;
781         git_config_get_int("maintenance.commit-graph.auto",
782                            &data.limit);
783
784         if (!data.limit)
785                 return 0;
786         if (data.limit < 0)
787                 return 1;
788
789         result = for_each_ref(dfs_on_ref, &data);
790
791         clear_commit_marks_all(SEEN);
792
793         return result;
794 }
795
796 static int run_write_commit_graph(struct maintenance_run_opts *opts)
797 {
798         struct child_process child = CHILD_PROCESS_INIT;
799
800         child.git_cmd = 1;
801         strvec_pushl(&child.args, "commit-graph", "write",
802                      "--split", "--reachable", NULL);
803
804         if (opts->quiet)
805                 strvec_push(&child.args, "--no-progress");
806
807         return !!run_command(&child);
808 }
809
810 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
811 {
812         close_object_store(the_repository->objects);
813         if (run_write_commit_graph(opts)) {
814                 error(_("failed to write commit-graph"));
815                 return 1;
816         }
817
818         return 0;
819 }
820
821 static int fetch_remote(const char *remote, struct maintenance_run_opts *opts)
822 {
823         struct child_process child = CHILD_PROCESS_INIT;
824
825         child.git_cmd = 1;
826         strvec_pushl(&child.args, "fetch", remote, "--prune", "--no-tags",
827                      "--no-write-fetch-head", "--recurse-submodules=no",
828                      "--refmap=", NULL);
829
830         if (opts->quiet)
831                 strvec_push(&child.args, "--quiet");
832
833         strvec_pushf(&child.args, "+refs/heads/*:refs/prefetch/%s/*", remote);
834
835         return !!run_command(&child);
836 }
837
838 static int append_remote(struct remote *remote, void *cbdata)
839 {
840         struct string_list *remotes = (struct string_list *)cbdata;
841
842         string_list_append(remotes, remote->name);
843         return 0;
844 }
845
846 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
847 {
848         int result = 0;
849         struct string_list_item *item;
850         struct string_list remotes = STRING_LIST_INIT_DUP;
851
852         if (for_each_remote(append_remote, &remotes)) {
853                 error(_("failed to fill remotes"));
854                 result = 1;
855                 goto cleanup;
856         }
857
858         for_each_string_list_item(item, &remotes)
859                 result |= fetch_remote(item->string, opts);
860
861 cleanup:
862         string_list_clear(&remotes, 0);
863         return result;
864 }
865
866 static int maintenance_task_gc(struct maintenance_run_opts *opts)
867 {
868         struct child_process child = CHILD_PROCESS_INIT;
869
870         child.git_cmd = 1;
871         strvec_push(&child.args, "gc");
872
873         if (opts->auto_flag)
874                 strvec_push(&child.args, "--auto");
875         if (opts->quiet)
876                 strvec_push(&child.args, "--quiet");
877         else
878                 strvec_push(&child.args, "--no-quiet");
879
880         close_object_store(the_repository->objects);
881         return run_command(&child);
882 }
883
884 static int prune_packed(struct maintenance_run_opts *opts)
885 {
886         struct child_process child = CHILD_PROCESS_INIT;
887
888         child.git_cmd = 1;
889         strvec_push(&child.args, "prune-packed");
890
891         if (opts->quiet)
892                 strvec_push(&child.args, "--quiet");
893
894         return !!run_command(&child);
895 }
896
897 struct write_loose_object_data {
898         FILE *in;
899         int count;
900         int batch_size;
901 };
902
903 static int loose_object_auto_limit = 100;
904
905 static int loose_object_count(const struct object_id *oid,
906                                const char *path,
907                                void *data)
908 {
909         int *count = (int*)data;
910         if (++(*count) >= loose_object_auto_limit)
911                 return 1;
912         return 0;
913 }
914
915 static int loose_object_auto_condition(void)
916 {
917         int count = 0;
918
919         git_config_get_int("maintenance.loose-objects.auto",
920                            &loose_object_auto_limit);
921
922         if (!loose_object_auto_limit)
923                 return 0;
924         if (loose_object_auto_limit < 0)
925                 return 1;
926
927         return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
928                                              loose_object_count,
929                                              NULL, NULL, &count);
930 }
931
932 static int bail_on_loose(const struct object_id *oid,
933                          const char *path,
934                          void *data)
935 {
936         return 1;
937 }
938
939 static int write_loose_object_to_stdin(const struct object_id *oid,
940                                        const char *path,
941                                        void *data)
942 {
943         struct write_loose_object_data *d = (struct write_loose_object_data *)data;
944
945         fprintf(d->in, "%s\n", oid_to_hex(oid));
946
947         return ++(d->count) > d->batch_size;
948 }
949
950 static int pack_loose(struct maintenance_run_opts *opts)
951 {
952         struct repository *r = the_repository;
953         int result = 0;
954         struct write_loose_object_data data;
955         struct child_process pack_proc = CHILD_PROCESS_INIT;
956
957         /*
958          * Do not start pack-objects process
959          * if there are no loose objects.
960          */
961         if (!for_each_loose_file_in_objdir(r->objects->odb->path,
962                                            bail_on_loose,
963                                            NULL, NULL, NULL))
964                 return 0;
965
966         pack_proc.git_cmd = 1;
967
968         strvec_push(&pack_proc.args, "pack-objects");
969         if (opts->quiet)
970                 strvec_push(&pack_proc.args, "--quiet");
971         strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
972
973         pack_proc.in = -1;
974
975         if (start_command(&pack_proc)) {
976                 error(_("failed to start 'git pack-objects' process"));
977                 return 1;
978         }
979
980         data.in = xfdopen(pack_proc.in, "w");
981         data.count = 0;
982         data.batch_size = 50000;
983
984         for_each_loose_file_in_objdir(r->objects->odb->path,
985                                       write_loose_object_to_stdin,
986                                       NULL,
987                                       NULL,
988                                       &data);
989
990         fclose(data.in);
991
992         if (finish_command(&pack_proc)) {
993                 error(_("failed to finish 'git pack-objects' process"));
994                 result = 1;
995         }
996
997         return result;
998 }
999
1000 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1001 {
1002         return prune_packed(opts) || pack_loose(opts);
1003 }
1004
1005 static int incremental_repack_auto_condition(void)
1006 {
1007         struct packed_git *p;
1008         int enabled;
1009         int incremental_repack_auto_limit = 10;
1010         int count = 0;
1011
1012         if (git_config_get_bool("core.multiPackIndex", &enabled) ||
1013             !enabled)
1014                 return 0;
1015
1016         git_config_get_int("maintenance.incremental-repack.auto",
1017                            &incremental_repack_auto_limit);
1018
1019         if (!incremental_repack_auto_limit)
1020                 return 0;
1021         if (incremental_repack_auto_limit < 0)
1022                 return 1;
1023
1024         for (p = get_packed_git(the_repository);
1025              count < incremental_repack_auto_limit && p;
1026              p = p->next) {
1027                 if (!p->multi_pack_index)
1028                         count++;
1029         }
1030
1031         return count >= incremental_repack_auto_limit;
1032 }
1033
1034 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1035 {
1036         struct child_process child = CHILD_PROCESS_INIT;
1037
1038         child.git_cmd = 1;
1039         strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1040
1041         if (opts->quiet)
1042                 strvec_push(&child.args, "--no-progress");
1043
1044         if (run_command(&child))
1045                 return error(_("failed to write multi-pack-index"));
1046
1047         return 0;
1048 }
1049
1050 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1051 {
1052         struct child_process child = CHILD_PROCESS_INIT;
1053
1054         child.git_cmd = 1;
1055         strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1056
1057         if (opts->quiet)
1058                 strvec_push(&child.args, "--no-progress");
1059
1060         close_object_store(the_repository->objects);
1061
1062         if (run_command(&child))
1063                 return error(_("'git multi-pack-index expire' failed"));
1064
1065         return 0;
1066 }
1067
1068 #define TWO_GIGABYTES (INT32_MAX)
1069
1070 static off_t get_auto_pack_size(void)
1071 {
1072         /*
1073          * The "auto" value is special: we optimize for
1074          * one large pack-file (i.e. from a clone) and
1075          * expect the rest to be small and they can be
1076          * repacked quickly.
1077          *
1078          * The strategy we select here is to select a
1079          * size that is one more than the second largest
1080          * pack-file. This ensures that we will repack
1081          * at least two packs if there are three or more
1082          * packs.
1083          */
1084         off_t max_size = 0;
1085         off_t second_largest_size = 0;
1086         off_t result_size;
1087         struct packed_git *p;
1088         struct repository *r = the_repository;
1089
1090         reprepare_packed_git(r);
1091         for (p = get_all_packs(r); p; p = p->next) {
1092                 if (p->pack_size > max_size) {
1093                         second_largest_size = max_size;
1094                         max_size = p->pack_size;
1095                 } else if (p->pack_size > second_largest_size)
1096                         second_largest_size = p->pack_size;
1097         }
1098
1099         result_size = second_largest_size + 1;
1100
1101         /* But limit ourselves to a batch size of 2g */
1102         if (result_size > TWO_GIGABYTES)
1103                 result_size = TWO_GIGABYTES;
1104
1105         return result_size;
1106 }
1107
1108 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1109 {
1110         struct child_process child = CHILD_PROCESS_INIT;
1111
1112         child.git_cmd = 1;
1113         strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1114
1115         if (opts->quiet)
1116                 strvec_push(&child.args, "--no-progress");
1117
1118         strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1119                                   (uintmax_t)get_auto_pack_size());
1120
1121         close_object_store(the_repository->objects);
1122
1123         if (run_command(&child))
1124                 return error(_("'git multi-pack-index repack' failed"));
1125
1126         return 0;
1127 }
1128
1129 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1130 {
1131         prepare_repo_settings(the_repository);
1132         if (!the_repository->settings.core_multi_pack_index) {
1133                 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1134                 return 0;
1135         }
1136
1137         if (multi_pack_index_write(opts))
1138                 return 1;
1139         if (multi_pack_index_expire(opts))
1140                 return 1;
1141         if (multi_pack_index_repack(opts))
1142                 return 1;
1143         return 0;
1144 }
1145
1146 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1147
1148 /*
1149  * An auto condition function returns 1 if the task should run
1150  * and 0 if the task should NOT run. See needs_to_gc() for an
1151  * example.
1152  */
1153 typedef int maintenance_auto_fn(void);
1154
1155 struct maintenance_task {
1156         const char *name;
1157         maintenance_task_fn *fn;
1158         maintenance_auto_fn *auto_condition;
1159         unsigned enabled:1;
1160
1161         /* -1 if not selected. */
1162         int selected_order;
1163 };
1164
1165 enum maintenance_task_label {
1166         TASK_PREFETCH,
1167         TASK_LOOSE_OBJECTS,
1168         TASK_INCREMENTAL_REPACK,
1169         TASK_GC,
1170         TASK_COMMIT_GRAPH,
1171
1172         /* Leave as final value */
1173         TASK__COUNT
1174 };
1175
1176 static struct maintenance_task tasks[] = {
1177         [TASK_PREFETCH] = {
1178                 "prefetch",
1179                 maintenance_task_prefetch,
1180         },
1181         [TASK_LOOSE_OBJECTS] = {
1182                 "loose-objects",
1183                 maintenance_task_loose_objects,
1184                 loose_object_auto_condition,
1185         },
1186         [TASK_INCREMENTAL_REPACK] = {
1187                 "incremental-repack",
1188                 maintenance_task_incremental_repack,
1189                 incremental_repack_auto_condition,
1190         },
1191         [TASK_GC] = {
1192                 "gc",
1193                 maintenance_task_gc,
1194                 need_to_gc,
1195                 1,
1196         },
1197         [TASK_COMMIT_GRAPH] = {
1198                 "commit-graph",
1199                 maintenance_task_commit_graph,
1200                 should_write_commit_graph,
1201         },
1202 };
1203
1204 static int compare_tasks_by_selection(const void *a_, const void *b_)
1205 {
1206         const struct maintenance_task *a, *b;
1207
1208         a = (const struct maintenance_task *)&a_;
1209         b = (const struct maintenance_task *)&b_;
1210
1211         return b->selected_order - a->selected_order;
1212 }
1213
1214 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1215 {
1216         int i, found_selected = 0;
1217         int result = 0;
1218         struct lock_file lk;
1219         struct repository *r = the_repository;
1220         char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1221
1222         if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1223                 /*
1224                  * Another maintenance command is running.
1225                  *
1226                  * If --auto was provided, then it is likely due to a
1227                  * recursive process stack. Do not report an error in
1228                  * that case.
1229                  */
1230                 if (!opts->auto_flag && !opts->quiet)
1231                         warning(_("lock file '%s' exists, skipping maintenance"),
1232                                 lock_path);
1233                 free(lock_path);
1234                 return 0;
1235         }
1236         free(lock_path);
1237
1238         for (i = 0; !found_selected && i < TASK__COUNT; i++)
1239                 found_selected = tasks[i].selected_order >= 0;
1240
1241         if (found_selected)
1242                 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1243
1244         for (i = 0; i < TASK__COUNT; i++) {
1245                 if (found_selected && tasks[i].selected_order < 0)
1246                         continue;
1247
1248                 if (!found_selected && !tasks[i].enabled)
1249                         continue;
1250
1251                 if (opts->auto_flag &&
1252                     (!tasks[i].auto_condition ||
1253                      !tasks[i].auto_condition()))
1254                         continue;
1255
1256                 trace2_region_enter("maintenance", tasks[i].name, r);
1257                 if (tasks[i].fn(opts)) {
1258                         error(_("task '%s' failed"), tasks[i].name);
1259                         result = 1;
1260                 }
1261                 trace2_region_leave("maintenance", tasks[i].name, r);
1262         }
1263
1264         rollback_lock_file(&lk);
1265         return result;
1266 }
1267
1268 static void initialize_task_config(void)
1269 {
1270         int i;
1271         struct strbuf config_name = STRBUF_INIT;
1272         gc_config();
1273
1274         for (i = 0; i < TASK__COUNT; i++) {
1275                 int config_value;
1276
1277                 strbuf_setlen(&config_name, 0);
1278                 strbuf_addf(&config_name, "maintenance.%s.enabled",
1279                             tasks[i].name);
1280
1281                 if (!git_config_get_bool(config_name.buf, &config_value))
1282                         tasks[i].enabled = config_value;
1283         }
1284
1285         strbuf_release(&config_name);
1286 }
1287
1288 static int task_option_parse(const struct option *opt,
1289                              const char *arg, int unset)
1290 {
1291         int i, num_selected = 0;
1292         struct maintenance_task *task = NULL;
1293
1294         BUG_ON_OPT_NEG(unset);
1295
1296         for (i = 0; i < TASK__COUNT; i++) {
1297                 if (tasks[i].selected_order >= 0)
1298                         num_selected++;
1299                 if (!strcasecmp(tasks[i].name, arg)) {
1300                         task = &tasks[i];
1301                 }
1302         }
1303
1304         if (!task) {
1305                 error(_("'%s' is not a valid task"), arg);
1306                 return 1;
1307         }
1308
1309         if (task->selected_order >= 0) {
1310                 error(_("task '%s' cannot be selected multiple times"), arg);
1311                 return 1;
1312         }
1313
1314         task->selected_order = num_selected + 1;
1315
1316         return 0;
1317 }
1318
1319 static int maintenance_run(int argc, const char **argv, const char *prefix)
1320 {
1321         int i;
1322         struct maintenance_run_opts opts;
1323         struct option builtin_maintenance_run_options[] = {
1324                 OPT_BOOL(0, "auto", &opts.auto_flag,
1325                          N_("run tasks based on the state of the repository")),
1326                 OPT_BOOL(0, "quiet", &opts.quiet,
1327                          N_("do not report progress or other information over stderr")),
1328                 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1329                         N_("run a specific task"),
1330                         PARSE_OPT_NONEG, task_option_parse),
1331                 OPT_END()
1332         };
1333         memset(&opts, 0, sizeof(opts));
1334
1335         opts.quiet = !isatty(2);
1336         initialize_task_config();
1337
1338         for (i = 0; i < TASK__COUNT; i++)
1339                 tasks[i].selected_order = -1;
1340
1341         argc = parse_options(argc, argv, prefix,
1342                              builtin_maintenance_run_options,
1343                              builtin_maintenance_run_usage,
1344                              PARSE_OPT_STOP_AT_NON_OPTION);
1345
1346         if (argc != 0)
1347                 usage_with_options(builtin_maintenance_run_usage,
1348                                    builtin_maintenance_run_options);
1349         return maintenance_run_tasks(&opts);
1350 }
1351
1352 static const char builtin_maintenance_usage[] = N_("git maintenance run [<options>]");
1353
1354 int cmd_maintenance(int argc, const char **argv, const char *prefix)
1355 {
1356         if (argc < 2 ||
1357             (argc == 2 && !strcmp(argv[1], "-h")))
1358                 usage(builtin_maintenance_usage);
1359
1360         if (!strcmp(argv[1], "run"))
1361                 return maintenance_run(argc - 1, argv + 1, prefix);
1362
1363         die(_("invalid subcommand: %s"), argv[1]);
1364 }