Merge branch 'ab/progress-cleanup' into seen
[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 #include "exec-cmd.h"
35
36 #define FAILED_RUN "failed to run %s"
37
38 static const char * const builtin_gc_usage[] = {
39         N_("git gc [<options>]"),
40         NULL
41 };
42
43 static int pack_refs = 1;
44 static int prune_reflogs = 1;
45 static int aggressive_depth = 50;
46 static int aggressive_window = 250;
47 static int gc_auto_threshold = 6700;
48 static int gc_auto_pack_limit = 50;
49 static int detach_auto = 1;
50 static timestamp_t gc_log_expire_time;
51 static const char *gc_log_expire = "1.day.ago";
52 static const char *prune_expire = "2.weeks.ago";
53 static const char *prune_worktrees_expire = "3.months.ago";
54 static unsigned long big_pack_threshold;
55 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
56
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_lock_file_path(&log_lock),
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 struct maintenance_run_opts;
166 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
167 {
168         struct strvec pack_refs_cmd = STRVEC_INIT;
169         strvec_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
170
171         return run_command_v_opt(pack_refs_cmd.v, RUN_GIT_CMD);
172 }
173
174 static int too_many_loose_objects(void)
175 {
176         /*
177          * Quickly check if a "gc" is needed, by estimating how
178          * many loose objects there are.  Because SHA-1 is evenly
179          * distributed, we can check only one and get a reasonable
180          * estimate.
181          */
182         DIR *dir;
183         struct dirent *ent;
184         int auto_threshold;
185         int num_loose = 0;
186         int needed = 0;
187         const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
188
189         dir = opendir(git_path("objects/17"));
190         if (!dir)
191                 return 0;
192
193         auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
194         while ((ent = readdir(dir)) != NULL) {
195                 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
196                     ent->d_name[hexsz_loose] != '\0')
197                         continue;
198                 if (++num_loose > auto_threshold) {
199                         needed = 1;
200                         break;
201                 }
202         }
203         closedir(dir);
204         return needed;
205 }
206
207 static struct packed_git *find_base_packs(struct string_list *packs,
208                                           unsigned long limit)
209 {
210         struct packed_git *p, *base = NULL;
211
212         for (p = get_all_packs(the_repository); p; p = p->next) {
213                 if (!p->pack_local)
214                         continue;
215                 if (limit) {
216                         if (p->pack_size >= limit)
217                                 string_list_append(packs, p->pack_name);
218                 } else if (!base || base->pack_size < p->pack_size) {
219                         base = p;
220                 }
221         }
222
223         if (base)
224                 string_list_append(packs, base->pack_name);
225
226         return base;
227 }
228
229 static int too_many_packs(void)
230 {
231         struct packed_git *p;
232         int cnt;
233
234         if (gc_auto_pack_limit <= 0)
235                 return 0;
236
237         for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
238                 if (!p->pack_local)
239                         continue;
240                 if (p->pack_keep)
241                         continue;
242                 /*
243                  * Perhaps check the size of the pack and count only
244                  * very small ones here?
245                  */
246                 cnt++;
247         }
248         return gc_auto_pack_limit < cnt;
249 }
250
251 static uint64_t total_ram(void)
252 {
253 #if defined(HAVE_SYSINFO)
254         struct sysinfo si;
255
256         if (!sysinfo(&si))
257                 return si.totalram;
258 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
259         int64_t physical_memory;
260         int mib[2];
261         size_t length;
262
263         mib[0] = CTL_HW;
264 # if defined(HW_MEMSIZE)
265         mib[1] = HW_MEMSIZE;
266 # else
267         mib[1] = HW_PHYSMEM;
268 # endif
269         length = sizeof(int64_t);
270         if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
271                 return physical_memory;
272 #elif defined(GIT_WINDOWS_NATIVE)
273         MEMORYSTATUSEX memInfo;
274
275         memInfo.dwLength = sizeof(MEMORYSTATUSEX);
276         if (GlobalMemoryStatusEx(&memInfo))
277                 return memInfo.ullTotalPhys;
278 #endif
279         return 0;
280 }
281
282 static uint64_t estimate_repack_memory(struct packed_git *pack)
283 {
284         unsigned long nr_objects = approximate_object_count();
285         size_t os_cache, heap;
286
287         if (!pack || !nr_objects)
288                 return 0;
289
290         /*
291          * First we have to scan through at least one pack.
292          * Assume enough room in OS file cache to keep the entire pack
293          * or we may accidentally evict data of other processes from
294          * the cache.
295          */
296         os_cache = pack->pack_size + pack->index_size;
297         /* then pack-objects needs lots more for book keeping */
298         heap = sizeof(struct object_entry) * nr_objects;
299         /*
300          * internal rev-list --all --objects takes up some memory too,
301          * let's say half of it is for blobs
302          */
303         heap += sizeof(struct blob) * nr_objects / 2;
304         /*
305          * and the other half is for trees (commits and tags are
306          * usually insignificant)
307          */
308         heap += sizeof(struct tree) * nr_objects / 2;
309         /* and then obj_hash[], underestimated in fact */
310         heap += sizeof(struct object *) * nr_objects;
311         /* revindex is used also */
312         heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
313         /*
314          * read_sha1_file() (either at delta calculation phase, or
315          * writing phase) also fills up the delta base cache
316          */
317         heap += delta_base_cache_limit;
318         /* and of course pack-objects has its own delta cache */
319         heap += max_delta_cache_size;
320
321         return os_cache + heap;
322 }
323
324 static int keep_one_pack(struct string_list_item *item, void *data)
325 {
326         strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
327         return 0;
328 }
329
330 static void add_repack_all_option(struct string_list *keep_pack)
331 {
332         if (prune_expire && !strcmp(prune_expire, "now"))
333                 strvec_push(&repack, "-a");
334         else {
335                 strvec_push(&repack, "-A");
336                 if (prune_expire)
337                         strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
338         }
339
340         if (keep_pack)
341                 for_each_string_list(keep_pack, keep_one_pack, NULL);
342 }
343
344 static void add_repack_incremental_option(void)
345 {
346         strvec_push(&repack, "--no-write-bitmap-index");
347 }
348
349 static int need_to_gc(void)
350 {
351         /*
352          * Setting gc.auto to 0 or negative can disable the
353          * automatic gc.
354          */
355         if (gc_auto_threshold <= 0)
356                 return 0;
357
358         /*
359          * If there are too many loose objects, but not too many
360          * packs, we run "repack -d -l".  If there are too many packs,
361          * we run "repack -A -d -l".  Otherwise we tell the caller
362          * there is no need.
363          */
364         if (too_many_packs()) {
365                 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
366
367                 if (big_pack_threshold) {
368                         find_base_packs(&keep_pack, big_pack_threshold);
369                         if (keep_pack.nr >= gc_auto_pack_limit) {
370                                 big_pack_threshold = 0;
371                                 string_list_clear(&keep_pack, 0);
372                                 find_base_packs(&keep_pack, 0);
373                         }
374                 } else {
375                         struct packed_git *p = find_base_packs(&keep_pack, 0);
376                         uint64_t mem_have, mem_want;
377
378                         mem_have = total_ram();
379                         mem_want = estimate_repack_memory(p);
380
381                         /*
382                          * Only allow 1/2 of memory for pack-objects, leave
383                          * the rest for the OS and other processes in the
384                          * system.
385                          */
386                         if (!mem_have || mem_want < mem_have / 2)
387                                 string_list_clear(&keep_pack, 0);
388                 }
389
390                 add_repack_all_option(&keep_pack);
391                 string_list_clear(&keep_pack, 0);
392         } else if (too_many_loose_objects())
393                 add_repack_incremental_option();
394         else
395                 return 0;
396
397         if (run_hook_le(NULL, "pre-auto-gc", NULL))
398                 return 0;
399         return 1;
400 }
401
402 /* return NULL on success, else hostname running the gc */
403 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
404 {
405         struct lock_file lock = LOCK_INIT;
406         char my_host[HOST_NAME_MAX + 1];
407         struct strbuf sb = STRBUF_INIT;
408         struct stat st;
409         uintmax_t pid;
410         FILE *fp;
411         int fd;
412         char *pidfile_path;
413
414         if (is_tempfile_active(pidfile))
415                 /* already locked */
416                 return NULL;
417
418         if (xgethostname(my_host, sizeof(my_host)))
419                 xsnprintf(my_host, sizeof(my_host), "unknown");
420
421         pidfile_path = git_pathdup("gc.pid");
422         fd = hold_lock_file_for_update(&lock, pidfile_path,
423                                        LOCK_DIE_ON_ERROR);
424         if (!force) {
425                 static char locking_host[HOST_NAME_MAX + 1];
426                 static char *scan_fmt;
427                 int should_exit;
428
429                 if (!scan_fmt)
430                         scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
431                 fp = fopen(pidfile_path, "r");
432                 memset(locking_host, 0, sizeof(locking_host));
433                 should_exit =
434                         fp != NULL &&
435                         !fstat(fileno(fp), &st) &&
436                         /*
437                          * 12 hour limit is very generous as gc should
438                          * never take that long. On the other hand we
439                          * don't really need a strict limit here,
440                          * running gc --auto one day late is not a big
441                          * problem. --force can be used in manual gc
442                          * after the user verifies that no gc is
443                          * running.
444                          */
445                         time(NULL) - st.st_mtime <= 12 * 3600 &&
446                         fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
447                         /* be gentle to concurrent "gc" on remote hosts */
448                         (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
449                 if (fp != NULL)
450                         fclose(fp);
451                 if (should_exit) {
452                         if (fd >= 0)
453                                 rollback_lock_file(&lock);
454                         *ret_pid = pid;
455                         free(pidfile_path);
456                         return locking_host;
457                 }
458         }
459
460         strbuf_addf(&sb, "%"PRIuMAX" %s",
461                     (uintmax_t) getpid(), my_host);
462         write_in_full(fd, sb.buf, sb.len);
463         strbuf_release(&sb);
464         commit_lock_file(&lock);
465         pidfile = register_tempfile(pidfile_path);
466         free(pidfile_path);
467         return NULL;
468 }
469
470 /*
471  * Returns 0 if there was no previous error and gc can proceed, 1 if
472  * gc should not proceed due to an error in the last run. Prints a
473  * message and returns -1 if an error occurred while reading gc.log
474  */
475 static int report_last_gc_error(void)
476 {
477         struct strbuf sb = STRBUF_INIT;
478         int ret = 0;
479         ssize_t len;
480         struct stat st;
481         char *gc_log_path = git_pathdup("gc.log");
482
483         if (stat(gc_log_path, &st)) {
484                 if (errno == ENOENT)
485                         goto done;
486
487                 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
488                 goto done;
489         }
490
491         if (st.st_mtime < gc_log_expire_time)
492                 goto done;
493
494         len = strbuf_read_file(&sb, gc_log_path, 0);
495         if (len < 0)
496                 ret = error_errno(_("cannot read '%s'"), gc_log_path);
497         else if (len > 0) {
498                 /*
499                  * A previous gc failed.  Report the error, and don't
500                  * bother with an automatic gc run since it is likely
501                  * to fail in the same way.
502                  */
503                 warning(_("The last gc run reported the following. "
504                                "Please correct the root cause\n"
505                                "and remove %s.\n"
506                                "Automatic cleanup will not be performed "
507                                "until the file is removed.\n\n"
508                                "%s"),
509                             gc_log_path, sb.buf);
510                 ret = 1;
511         }
512         strbuf_release(&sb);
513 done:
514         free(gc_log_path);
515         return ret;
516 }
517
518 static void gc_before_repack(void)
519 {
520         /*
521          * We may be called twice, as both the pre- and
522          * post-daemonized phases will call us, but running these
523          * commands more than once is pointless and wasteful.
524          */
525         static int done = 0;
526         if (done++)
527                 return;
528
529         if (pack_refs && maintenance_task_pack_refs(NULL))
530                 die(FAILED_RUN, "pack-refs");
531
532         if (prune_reflogs && run_command_v_opt(reflog.v, RUN_GIT_CMD))
533                 die(FAILED_RUN, reflog.v[0]);
534 }
535
536 int cmd_gc(int argc, const char **argv, const char *prefix)
537 {
538         int aggressive = 0;
539         int auto_gc = 0;
540         int quiet = 0;
541         int force = 0;
542         const char *name;
543         pid_t pid;
544         int daemonized = 0;
545         int keep_largest_pack = -1;
546         timestamp_t dummy;
547
548         struct option builtin_gc_options[] = {
549                 OPT__QUIET(&quiet, N_("suppress progress reporting")),
550                 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
551                         N_("prune unreferenced objects"),
552                         PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
553                 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
554                 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
555                            PARSE_OPT_NOCOMPLETE),
556                 OPT_BOOL_F(0, "force", &force,
557                            N_("force running gc even if there may be another gc running"),
558                            PARSE_OPT_NOCOMPLETE),
559                 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
560                          N_("repack all other packs except the largest pack")),
561                 OPT_END()
562         };
563
564         if (argc == 2 && !strcmp(argv[1], "-h"))
565                 usage_with_options(builtin_gc_usage, builtin_gc_options);
566
567         strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
568         strvec_pushl(&repack, "repack", "-d", "-l", NULL);
569         strvec_pushl(&prune, "prune", "--expire", NULL);
570         strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
571         strvec_pushl(&rerere, "rerere", "gc", NULL);
572
573         /* default expiry time, overwritten in gc_config */
574         gc_config();
575         if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
576                 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
577
578         if (pack_refs < 0)
579                 pack_refs = !is_bare_repository();
580
581         argc = parse_options(argc, argv, prefix, builtin_gc_options,
582                              builtin_gc_usage, 0);
583         if (argc > 0)
584                 usage_with_options(builtin_gc_usage, builtin_gc_options);
585
586         if (prune_expire && parse_expiry_date(prune_expire, &dummy))
587                 die(_("failed to parse prune expiry value %s"), prune_expire);
588
589         if (aggressive) {
590                 strvec_push(&repack, "-f");
591                 if (aggressive_depth > 0)
592                         strvec_pushf(&repack, "--depth=%d", aggressive_depth);
593                 if (aggressive_window > 0)
594                         strvec_pushf(&repack, "--window=%d", aggressive_window);
595         }
596         if (quiet)
597                 strvec_push(&repack, "-q");
598
599         if (auto_gc) {
600                 /*
601                  * Auto-gc should be least intrusive as possible.
602                  */
603                 if (!need_to_gc())
604                         return 0;
605                 if (!quiet) {
606                         if (detach_auto)
607                                 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
608                         else
609                                 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
610                         fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
611                 }
612                 if (detach_auto) {
613                         int ret = report_last_gc_error();
614                         if (ret < 0)
615                                 /* an I/O error occurred, already reported */
616                                 exit(128);
617                         if (ret == 1)
618                                 /* Last gc --auto failed. Skip this one. */
619                                 return 0;
620
621                         if (lock_repo_for_gc(force, &pid))
622                                 return 0;
623                         gc_before_repack(); /* dies on failure */
624                         delete_tempfile(&pidfile);
625
626                         /*
627                          * failure to daemonize is ok, we'll continue
628                          * in foreground
629                          */
630                         daemonized = !daemonize();
631                 }
632         } else {
633                 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
634
635                 if (keep_largest_pack != -1) {
636                         if (keep_largest_pack)
637                                 find_base_packs(&keep_pack, 0);
638                 } else if (big_pack_threshold) {
639                         find_base_packs(&keep_pack, big_pack_threshold);
640                 }
641
642                 add_repack_all_option(&keep_pack);
643                 string_list_clear(&keep_pack, 0);
644         }
645
646         name = lock_repo_for_gc(force, &pid);
647         if (name) {
648                 if (auto_gc)
649                         return 0; /* be quiet on --auto */
650                 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
651                     name, (uintmax_t)pid);
652         }
653
654         if (daemonized) {
655                 hold_lock_file_for_update(&log_lock,
656                                           git_path("gc.log"),
657                                           LOCK_DIE_ON_ERROR);
658                 dup2(get_lock_file_fd(&log_lock), 2);
659                 sigchain_push_common(process_log_file_on_signal);
660                 atexit(process_log_file_at_exit);
661         }
662
663         gc_before_repack();
664
665         if (!repository_format_precious_objects) {
666                 close_object_store(the_repository->objects);
667                 if (run_command_v_opt(repack.v, RUN_GIT_CMD))
668                         die(FAILED_RUN, repack.v[0]);
669
670                 if (prune_expire) {
671                         strvec_push(&prune, prune_expire);
672                         if (quiet)
673                                 strvec_push(&prune, "--no-progress");
674                         if (has_promisor_remote())
675                                 strvec_push(&prune,
676                                             "--exclude-promisor-objects");
677                         if (run_command_v_opt(prune.v, RUN_GIT_CMD))
678                                 die(FAILED_RUN, prune.v[0]);
679                 }
680         }
681
682         if (prune_worktrees_expire) {
683                 strvec_push(&prune_worktrees, prune_worktrees_expire);
684                 if (run_command_v_opt(prune_worktrees.v, RUN_GIT_CMD))
685                         die(FAILED_RUN, prune_worktrees.v[0]);
686         }
687
688         if (run_command_v_opt(rerere.v, RUN_GIT_CMD))
689                 die(FAILED_RUN, rerere.v[0]);
690
691         report_garbage = report_pack_garbage;
692         reprepare_packed_git(the_repository);
693         if (pack_garbage.nr > 0) {
694                 close_object_store(the_repository->objects);
695                 clean_pack_garbage();
696         }
697
698         prepare_repo_settings(the_repository);
699         if (the_repository->settings.gc_write_commit_graph == 1)
700                 write_commit_graph_reachable(the_repository->objects->odb,
701                                              !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
702                                              NULL);
703
704         if (auto_gc && too_many_loose_objects())
705                 warning(_("There are too many unreachable loose objects; "
706                         "run 'git prune' to remove them."));
707
708         if (!daemonized)
709                 unlink(git_path("gc.log"));
710
711         return 0;
712 }
713
714 static const char *const builtin_maintenance_run_usage[] = {
715         N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
716         NULL
717 };
718
719 enum schedule_priority {
720         SCHEDULE_NONE = 0,
721         SCHEDULE_WEEKLY = 1,
722         SCHEDULE_DAILY = 2,
723         SCHEDULE_HOURLY = 3,
724 };
725
726 static enum schedule_priority parse_schedule(const char *value)
727 {
728         if (!value)
729                 return SCHEDULE_NONE;
730         if (!strcasecmp(value, "hourly"))
731                 return SCHEDULE_HOURLY;
732         if (!strcasecmp(value, "daily"))
733                 return SCHEDULE_DAILY;
734         if (!strcasecmp(value, "weekly"))
735                 return SCHEDULE_WEEKLY;
736         return SCHEDULE_NONE;
737 }
738
739 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
740                                     int unset)
741 {
742         enum schedule_priority *priority = opt->value;
743
744         if (unset)
745                 die(_("--no-schedule is not allowed"));
746
747         *priority = parse_schedule(arg);
748
749         if (!*priority)
750                 die(_("unrecognized --schedule argument '%s'"), arg);
751
752         return 0;
753 }
754
755 struct maintenance_run_opts {
756         int auto_flag;
757         int quiet;
758         enum schedule_priority schedule;
759 };
760
761 /* Remember to update object flag allocation in object.h */
762 #define SEEN            (1u<<0)
763
764 struct cg_auto_data {
765         int num_not_in_graph;
766         int limit;
767 };
768
769 static int dfs_on_ref(const char *refname,
770                       const struct object_id *oid, int flags,
771                       void *cb_data)
772 {
773         struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
774         int result = 0;
775         struct object_id peeled;
776         struct commit_list *stack = NULL;
777         struct commit *commit;
778
779         if (!peel_iterated_oid(oid, &peeled))
780                 oid = &peeled;
781         if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
782                 return 0;
783
784         commit = lookup_commit(the_repository, oid);
785         if (!commit)
786                 return 0;
787         if (parse_commit(commit) ||
788             commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
789                 return 0;
790
791         data->num_not_in_graph++;
792
793         if (data->num_not_in_graph >= data->limit)
794                 return 1;
795
796         commit_list_append(commit, &stack);
797
798         while (!result && stack) {
799                 struct commit_list *parent;
800
801                 commit = pop_commit(&stack);
802
803                 for (parent = commit->parents; parent; parent = parent->next) {
804                         if (parse_commit(parent->item) ||
805                             commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
806                             parent->item->object.flags & SEEN)
807                                 continue;
808
809                         parent->item->object.flags |= SEEN;
810                         data->num_not_in_graph++;
811
812                         if (data->num_not_in_graph >= data->limit) {
813                                 result = 1;
814                                 break;
815                         }
816
817                         commit_list_append(parent->item, &stack);
818                 }
819         }
820
821         free_commit_list(stack);
822         return result;
823 }
824
825 static int should_write_commit_graph(void)
826 {
827         int result;
828         struct cg_auto_data data;
829
830         data.num_not_in_graph = 0;
831         data.limit = 100;
832         git_config_get_int("maintenance.commit-graph.auto",
833                            &data.limit);
834
835         if (!data.limit)
836                 return 0;
837         if (data.limit < 0)
838                 return 1;
839
840         result = for_each_ref(dfs_on_ref, &data);
841
842         repo_clear_commit_marks(the_repository, SEEN);
843
844         return result;
845 }
846
847 static int run_write_commit_graph(struct maintenance_run_opts *opts)
848 {
849         struct child_process child = CHILD_PROCESS_INIT;
850
851         child.git_cmd = 1;
852         strvec_pushl(&child.args, "commit-graph", "write",
853                      "--split", "--reachable", NULL);
854
855         if (opts->quiet)
856                 strvec_push(&child.args, "--no-progress");
857
858         return !!run_command(&child);
859 }
860
861 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
862 {
863         prepare_repo_settings(the_repository);
864         if (!the_repository->settings.core_commit_graph)
865                 return 0;
866
867         close_object_store(the_repository->objects);
868         if (run_write_commit_graph(opts)) {
869                 error(_("failed to write commit-graph"));
870                 return 1;
871         }
872
873         return 0;
874 }
875
876 static int fetch_remote(struct remote *remote, void *cbdata)
877 {
878         struct maintenance_run_opts *opts = cbdata;
879         struct child_process child = CHILD_PROCESS_INIT;
880
881         if (remote->skip_default_update)
882                 return 0;
883
884         child.git_cmd = 1;
885         strvec_pushl(&child.args, "fetch", remote->name,
886                      "--prefetch", "--prune", "--no-tags",
887                      "--no-write-fetch-head", "--recurse-submodules=no",
888                      NULL);
889
890         if (opts->quiet)
891                 strvec_push(&child.args, "--quiet");
892
893         return !!run_command(&child);
894 }
895
896 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
897 {
898         git_config_set_multivar_gently("log.excludedecoration",
899                                         "refs/prefetch/",
900                                         "refs/prefetch/",
901                                         CONFIG_FLAGS_FIXED_VALUE |
902                                         CONFIG_FLAGS_MULTI_REPLACE);
903
904         if (for_each_remote(fetch_remote, opts)) {
905                 error(_("failed to prefetch remotes"));
906                 return 1;
907         }
908
909         return 0;
910 }
911
912 static int maintenance_task_gc(struct maintenance_run_opts *opts)
913 {
914         struct child_process child = CHILD_PROCESS_INIT;
915
916         child.git_cmd = 1;
917         strvec_push(&child.args, "gc");
918
919         if (opts->auto_flag)
920                 strvec_push(&child.args, "--auto");
921         if (opts->quiet)
922                 strvec_push(&child.args, "--quiet");
923         else
924                 strvec_push(&child.args, "--no-quiet");
925
926         close_object_store(the_repository->objects);
927         return run_command(&child);
928 }
929
930 static int prune_packed(struct maintenance_run_opts *opts)
931 {
932         struct child_process child = CHILD_PROCESS_INIT;
933
934         child.git_cmd = 1;
935         strvec_push(&child.args, "prune-packed");
936
937         if (opts->quiet)
938                 strvec_push(&child.args, "--quiet");
939
940         return !!run_command(&child);
941 }
942
943 struct write_loose_object_data {
944         FILE *in;
945         int count;
946         int batch_size;
947 };
948
949 static int loose_object_auto_limit = 100;
950
951 static int loose_object_count(const struct object_id *oid,
952                                const char *path,
953                                void *data)
954 {
955         int *count = (int*)data;
956         if (++(*count) >= loose_object_auto_limit)
957                 return 1;
958         return 0;
959 }
960
961 static int loose_object_auto_condition(void)
962 {
963         int count = 0;
964
965         git_config_get_int("maintenance.loose-objects.auto",
966                            &loose_object_auto_limit);
967
968         if (!loose_object_auto_limit)
969                 return 0;
970         if (loose_object_auto_limit < 0)
971                 return 1;
972
973         return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
974                                              loose_object_count,
975                                              NULL, NULL, &count);
976 }
977
978 static int bail_on_loose(const struct object_id *oid,
979                          const char *path,
980                          void *data)
981 {
982         return 1;
983 }
984
985 static int write_loose_object_to_stdin(const struct object_id *oid,
986                                        const char *path,
987                                        void *data)
988 {
989         struct write_loose_object_data *d = (struct write_loose_object_data *)data;
990
991         fprintf(d->in, "%s\n", oid_to_hex(oid));
992
993         return ++(d->count) > d->batch_size;
994 }
995
996 static int pack_loose(struct maintenance_run_opts *opts)
997 {
998         struct repository *r = the_repository;
999         int result = 0;
1000         struct write_loose_object_data data;
1001         struct child_process pack_proc = CHILD_PROCESS_INIT;
1002
1003         /*
1004          * Do not start pack-objects process
1005          * if there are no loose objects.
1006          */
1007         if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1008                                            bail_on_loose,
1009                                            NULL, NULL, NULL))
1010                 return 0;
1011
1012         pack_proc.git_cmd = 1;
1013
1014         strvec_push(&pack_proc.args, "pack-objects");
1015         if (opts->quiet)
1016                 strvec_push(&pack_proc.args, "--quiet");
1017         strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1018
1019         pack_proc.in = -1;
1020
1021         if (start_command(&pack_proc)) {
1022                 error(_("failed to start 'git pack-objects' process"));
1023                 return 1;
1024         }
1025
1026         data.in = xfdopen(pack_proc.in, "w");
1027         data.count = 0;
1028         data.batch_size = 50000;
1029
1030         for_each_loose_file_in_objdir(r->objects->odb->path,
1031                                       write_loose_object_to_stdin,
1032                                       NULL,
1033                                       NULL,
1034                                       &data);
1035
1036         fclose(data.in);
1037
1038         if (finish_command(&pack_proc)) {
1039                 error(_("failed to finish 'git pack-objects' process"));
1040                 result = 1;
1041         }
1042
1043         return result;
1044 }
1045
1046 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1047 {
1048         return prune_packed(opts) || pack_loose(opts);
1049 }
1050
1051 static int incremental_repack_auto_condition(void)
1052 {
1053         struct packed_git *p;
1054         int enabled;
1055         int incremental_repack_auto_limit = 10;
1056         int count = 0;
1057
1058         if (git_config_get_bool("core.multiPackIndex", &enabled) ||
1059             !enabled)
1060                 return 0;
1061
1062         git_config_get_int("maintenance.incremental-repack.auto",
1063                            &incremental_repack_auto_limit);
1064
1065         if (!incremental_repack_auto_limit)
1066                 return 0;
1067         if (incremental_repack_auto_limit < 0)
1068                 return 1;
1069
1070         for (p = get_packed_git(the_repository);
1071              count < incremental_repack_auto_limit && p;
1072              p = p->next) {
1073                 if (!p->multi_pack_index)
1074                         count++;
1075         }
1076
1077         return count >= incremental_repack_auto_limit;
1078 }
1079
1080 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1081 {
1082         struct child_process child = CHILD_PROCESS_INIT;
1083
1084         child.git_cmd = 1;
1085         strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1086
1087         if (opts->quiet)
1088                 strvec_push(&child.args, "--no-progress");
1089
1090         if (run_command(&child))
1091                 return error(_("failed to write multi-pack-index"));
1092
1093         return 0;
1094 }
1095
1096 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1097 {
1098         struct child_process child = CHILD_PROCESS_INIT;
1099
1100         child.git_cmd = 1;
1101         strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1102
1103         if (opts->quiet)
1104                 strvec_push(&child.args, "--no-progress");
1105
1106         close_object_store(the_repository->objects);
1107
1108         if (run_command(&child))
1109                 return error(_("'git multi-pack-index expire' failed"));
1110
1111         return 0;
1112 }
1113
1114 #define TWO_GIGABYTES (INT32_MAX)
1115
1116 static off_t get_auto_pack_size(void)
1117 {
1118         /*
1119          * The "auto" value is special: we optimize for
1120          * one large pack-file (i.e. from a clone) and
1121          * expect the rest to be small and they can be
1122          * repacked quickly.
1123          *
1124          * The strategy we select here is to select a
1125          * size that is one more than the second largest
1126          * pack-file. This ensures that we will repack
1127          * at least two packs if there are three or more
1128          * packs.
1129          */
1130         off_t max_size = 0;
1131         off_t second_largest_size = 0;
1132         off_t result_size;
1133         struct packed_git *p;
1134         struct repository *r = the_repository;
1135
1136         reprepare_packed_git(r);
1137         for (p = get_all_packs(r); p; p = p->next) {
1138                 if (p->pack_size > max_size) {
1139                         second_largest_size = max_size;
1140                         max_size = p->pack_size;
1141                 } else if (p->pack_size > second_largest_size)
1142                         second_largest_size = p->pack_size;
1143         }
1144
1145         result_size = second_largest_size + 1;
1146
1147         /* But limit ourselves to a batch size of 2g */
1148         if (result_size > TWO_GIGABYTES)
1149                 result_size = TWO_GIGABYTES;
1150
1151         return result_size;
1152 }
1153
1154 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1155 {
1156         struct child_process child = CHILD_PROCESS_INIT;
1157
1158         child.git_cmd = 1;
1159         strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1160
1161         if (opts->quiet)
1162                 strvec_push(&child.args, "--no-progress");
1163
1164         strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1165                                   (uintmax_t)get_auto_pack_size());
1166
1167         close_object_store(the_repository->objects);
1168
1169         if (run_command(&child))
1170                 return error(_("'git multi-pack-index repack' failed"));
1171
1172         return 0;
1173 }
1174
1175 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1176 {
1177         prepare_repo_settings(the_repository);
1178         if (!the_repository->settings.core_multi_pack_index) {
1179                 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1180                 return 0;
1181         }
1182
1183         if (multi_pack_index_write(opts))
1184                 return 1;
1185         if (multi_pack_index_expire(opts))
1186                 return 1;
1187         if (multi_pack_index_repack(opts))
1188                 return 1;
1189         return 0;
1190 }
1191
1192 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1193
1194 /*
1195  * An auto condition function returns 1 if the task should run
1196  * and 0 if the task should NOT run. See needs_to_gc() for an
1197  * example.
1198  */
1199 typedef int maintenance_auto_fn(void);
1200
1201 struct maintenance_task {
1202         const char *name;
1203         maintenance_task_fn *fn;
1204         maintenance_auto_fn *auto_condition;
1205         unsigned enabled:1;
1206
1207         enum schedule_priority schedule;
1208
1209         /* -1 if not selected. */
1210         int selected_order;
1211 };
1212
1213 enum maintenance_task_label {
1214         TASK_PREFETCH,
1215         TASK_LOOSE_OBJECTS,
1216         TASK_INCREMENTAL_REPACK,
1217         TASK_GC,
1218         TASK_COMMIT_GRAPH,
1219         TASK_PACK_REFS,
1220
1221         /* Leave as final value */
1222         TASK__COUNT
1223 };
1224
1225 static struct maintenance_task tasks[] = {
1226         [TASK_PREFETCH] = {
1227                 "prefetch",
1228                 maintenance_task_prefetch,
1229         },
1230         [TASK_LOOSE_OBJECTS] = {
1231                 "loose-objects",
1232                 maintenance_task_loose_objects,
1233                 loose_object_auto_condition,
1234         },
1235         [TASK_INCREMENTAL_REPACK] = {
1236                 "incremental-repack",
1237                 maintenance_task_incremental_repack,
1238                 incremental_repack_auto_condition,
1239         },
1240         [TASK_GC] = {
1241                 "gc",
1242                 maintenance_task_gc,
1243                 need_to_gc,
1244                 1,
1245         },
1246         [TASK_COMMIT_GRAPH] = {
1247                 "commit-graph",
1248                 maintenance_task_commit_graph,
1249                 should_write_commit_graph,
1250         },
1251         [TASK_PACK_REFS] = {
1252                 "pack-refs",
1253                 maintenance_task_pack_refs,
1254                 NULL,
1255         },
1256 };
1257
1258 static int compare_tasks_by_selection(const void *a_, const void *b_)
1259 {
1260         const struct maintenance_task *a = a_;
1261         const struct maintenance_task *b = b_;
1262
1263         return b->selected_order - a->selected_order;
1264 }
1265
1266 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1267 {
1268         int i, found_selected = 0;
1269         int result = 0;
1270         struct lock_file lk;
1271         struct repository *r = the_repository;
1272         char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1273
1274         if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1275                 /*
1276                  * Another maintenance command is running.
1277                  *
1278                  * If --auto was provided, then it is likely due to a
1279                  * recursive process stack. Do not report an error in
1280                  * that case.
1281                  */
1282                 if (!opts->auto_flag && !opts->quiet)
1283                         warning(_("lock file '%s' exists, skipping maintenance"),
1284                                 lock_path);
1285                 free(lock_path);
1286                 return 0;
1287         }
1288         free(lock_path);
1289
1290         for (i = 0; !found_selected && i < TASK__COUNT; i++)
1291                 found_selected = tasks[i].selected_order >= 0;
1292
1293         if (found_selected)
1294                 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1295
1296         for (i = 0; i < TASK__COUNT; i++) {
1297                 if (found_selected && tasks[i].selected_order < 0)
1298                         continue;
1299
1300                 if (!found_selected && !tasks[i].enabled)
1301                         continue;
1302
1303                 if (opts->auto_flag &&
1304                     (!tasks[i].auto_condition ||
1305                      !tasks[i].auto_condition()))
1306                         continue;
1307
1308                 if (opts->schedule && tasks[i].schedule < opts->schedule)
1309                         continue;
1310
1311                 trace2_region_enter("maintenance", tasks[i].name, r);
1312                 if (tasks[i].fn(opts)) {
1313                         error(_("task '%s' failed"), tasks[i].name);
1314                         result = 1;
1315                 }
1316                 trace2_region_leave("maintenance", tasks[i].name, r);
1317         }
1318
1319         rollback_lock_file(&lk);
1320         return result;
1321 }
1322
1323 static void initialize_maintenance_strategy(void)
1324 {
1325         char *config_str;
1326
1327         if (git_config_get_string("maintenance.strategy", &config_str))
1328                 return;
1329
1330         if (!strcasecmp(config_str, "incremental")) {
1331                 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1332                 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1333                 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1334                 tasks[TASK_PREFETCH].enabled = 1;
1335                 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1336                 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1337                 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1338                 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1339                 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1340                 tasks[TASK_PACK_REFS].enabled = 1;
1341                 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1342         }
1343 }
1344
1345 static void initialize_task_config(int schedule)
1346 {
1347         int i;
1348         struct strbuf config_name = STRBUF_INIT;
1349         gc_config();
1350
1351         if (schedule)
1352                 initialize_maintenance_strategy();
1353
1354         for (i = 0; i < TASK__COUNT; i++) {
1355                 int config_value;
1356                 char *config_str;
1357
1358                 strbuf_reset(&config_name);
1359                 strbuf_addf(&config_name, "maintenance.%s.enabled",
1360                             tasks[i].name);
1361
1362                 if (!git_config_get_bool(config_name.buf, &config_value))
1363                         tasks[i].enabled = config_value;
1364
1365                 strbuf_reset(&config_name);
1366                 strbuf_addf(&config_name, "maintenance.%s.schedule",
1367                             tasks[i].name);
1368
1369                 if (!git_config_get_string(config_name.buf, &config_str)) {
1370                         tasks[i].schedule = parse_schedule(config_str);
1371                         free(config_str);
1372                 }
1373         }
1374
1375         strbuf_release(&config_name);
1376 }
1377
1378 static int task_option_parse(const struct option *opt,
1379                              const char *arg, int unset)
1380 {
1381         int i, num_selected = 0;
1382         struct maintenance_task *task = NULL;
1383
1384         BUG_ON_OPT_NEG(unset);
1385
1386         for (i = 0; i < TASK__COUNT; i++) {
1387                 if (tasks[i].selected_order >= 0)
1388                         num_selected++;
1389                 if (!strcasecmp(tasks[i].name, arg)) {
1390                         task = &tasks[i];
1391                 }
1392         }
1393
1394         if (!task) {
1395                 error(_("'%s' is not a valid task"), arg);
1396                 return 1;
1397         }
1398
1399         if (task->selected_order >= 0) {
1400                 error(_("task '%s' cannot be selected multiple times"), arg);
1401                 return 1;
1402         }
1403
1404         task->selected_order = num_selected + 1;
1405
1406         return 0;
1407 }
1408
1409 static int maintenance_run(int argc, const char **argv, const char *prefix)
1410 {
1411         int i;
1412         struct maintenance_run_opts opts;
1413         struct option builtin_maintenance_run_options[] = {
1414                 OPT_BOOL(0, "auto", &opts.auto_flag,
1415                          N_("run tasks based on the state of the repository")),
1416                 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1417                              N_("run tasks based on frequency"),
1418                              maintenance_opt_schedule),
1419                 OPT_BOOL(0, "quiet", &opts.quiet,
1420                          N_("do not report progress or other information over stderr")),
1421                 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1422                         N_("run a specific task"),
1423                         PARSE_OPT_NONEG, task_option_parse),
1424                 OPT_END()
1425         };
1426         memset(&opts, 0, sizeof(opts));
1427
1428         opts.quiet = !isatty(2);
1429
1430         for (i = 0; i < TASK__COUNT; i++)
1431                 tasks[i].selected_order = -1;
1432
1433         argc = parse_options(argc, argv, prefix,
1434                              builtin_maintenance_run_options,
1435                              builtin_maintenance_run_usage,
1436                              PARSE_OPT_STOP_AT_NON_OPTION);
1437
1438         if (opts.auto_flag && opts.schedule)
1439                 die(_("use at most one of --auto and --schedule=<frequency>"));
1440
1441         initialize_task_config(opts.schedule);
1442
1443         if (argc != 0)
1444                 usage_with_options(builtin_maintenance_run_usage,
1445                                    builtin_maintenance_run_options);
1446         return maintenance_run_tasks(&opts);
1447 }
1448
1449 static char *get_maintpath(void)
1450 {
1451         struct strbuf sb = STRBUF_INIT;
1452         const char *p = the_repository->worktree ?
1453                 the_repository->worktree : the_repository->gitdir;
1454
1455         strbuf_realpath(&sb, p, 1);
1456         return strbuf_detach(&sb, NULL);
1457 }
1458
1459 static int maintenance_register(void)
1460 {
1461         int rc;
1462         char *config_value;
1463         struct child_process config_set = CHILD_PROCESS_INIT;
1464         struct child_process config_get = CHILD_PROCESS_INIT;
1465         char *maintpath = get_maintpath();
1466
1467         /* Disable foreground maintenance */
1468         git_config_set("maintenance.auto", "false");
1469
1470         /* Set maintenance strategy, if unset */
1471         if (!git_config_get_string("maintenance.strategy", &config_value))
1472                 free(config_value);
1473         else
1474                 git_config_set("maintenance.strategy", "incremental");
1475
1476         config_get.git_cmd = 1;
1477         strvec_pushl(&config_get.args, "config", "--global", "--get",
1478                      "--fixed-value", "maintenance.repo", maintpath, NULL);
1479         config_get.out = -1;
1480
1481         if (start_command(&config_get)) {
1482                 rc = error(_("failed to run 'git config'"));
1483                 goto done;
1484         }
1485
1486         /* We already have this value in our config! */
1487         if (!finish_command(&config_get)) {
1488                 rc = 0;
1489                 goto done;
1490         }
1491
1492         config_set.git_cmd = 1;
1493         strvec_pushl(&config_set.args, "config", "--add", "--global", "maintenance.repo",
1494                      maintpath, NULL);
1495
1496         rc = run_command(&config_set);
1497
1498 done:
1499         free(maintpath);
1500         return rc;
1501 }
1502
1503 static int maintenance_unregister(void)
1504 {
1505         int rc;
1506         struct child_process config_unset = CHILD_PROCESS_INIT;
1507         char *maintpath = get_maintpath();
1508
1509         config_unset.git_cmd = 1;
1510         strvec_pushl(&config_unset.args, "config", "--global", "--unset",
1511                      "--fixed-value", "maintenance.repo", maintpath, NULL);
1512
1513         rc = run_command(&config_unset);
1514         free(maintpath);
1515         return rc;
1516 }
1517
1518 static const char *get_frequency(enum schedule_priority schedule)
1519 {
1520         switch (schedule) {
1521         case SCHEDULE_HOURLY:
1522                 return "hourly";
1523         case SCHEDULE_DAILY:
1524                 return "daily";
1525         case SCHEDULE_WEEKLY:
1526                 return "weekly";
1527         default:
1528                 BUG("invalid schedule %d", schedule);
1529         }
1530 }
1531
1532 static int get_schedule_cmd(const char **cmd, int *is_available)
1533 {
1534         char *item;
1535         char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1536
1537         if (!testing)
1538                 return 0;
1539
1540         if (is_available)
1541                 *is_available = 0;
1542
1543         for (item = testing;;) {
1544                 char *sep;
1545                 char *end_item = strchr(item, ',');
1546                 if (end_item)
1547                         *end_item = '\0';
1548
1549                 sep = strchr(item, ':');
1550                 if (!sep)
1551                         die("GIT_TEST_MAINT_SCHEDULER unparseable: %s", testing);
1552                 *sep = '\0';
1553
1554                 if (!strcmp(*cmd, item)) {
1555                         *cmd = sep + 1;
1556                         if (is_available)
1557                                 *is_available = 1;
1558                         UNLEAK(testing);
1559                         return 1;
1560                 }
1561
1562                 if (!end_item)
1563                         break;
1564                 item = end_item + 1;
1565         }
1566
1567         free(testing);
1568         return 1;
1569 }
1570
1571 static int is_launchctl_available(void)
1572 {
1573         const char *cmd = "launchctl";
1574         int is_available;
1575         if (get_schedule_cmd(&cmd, &is_available))
1576                 return is_available;
1577
1578 #ifdef __APPLE__
1579         return 1;
1580 #else
1581         return 0;
1582 #endif
1583 }
1584
1585 static char *launchctl_service_name(const char *frequency)
1586 {
1587         struct strbuf label = STRBUF_INIT;
1588         strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1589         return strbuf_detach(&label, NULL);
1590 }
1591
1592 static char *launchctl_service_filename(const char *name)
1593 {
1594         char *expanded;
1595         struct strbuf filename = STRBUF_INIT;
1596         strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1597
1598         expanded = expand_user_path(filename.buf, 1);
1599         if (!expanded)
1600                 die(_("failed to expand path '%s'"), filename.buf);
1601
1602         strbuf_release(&filename);
1603         return expanded;
1604 }
1605
1606 static char *launchctl_get_uid(void)
1607 {
1608         return xstrfmt("gui/%d", getuid());
1609 }
1610
1611 static int launchctl_boot_plist(int enable, const char *filename)
1612 {
1613         const char *cmd = "launchctl";
1614         int result;
1615         struct child_process child = CHILD_PROCESS_INIT;
1616         char *uid = launchctl_get_uid();
1617
1618         get_schedule_cmd(&cmd, NULL);
1619         strvec_split(&child.args, cmd);
1620         strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1621                      filename, NULL);
1622
1623         child.no_stderr = 1;
1624         child.no_stdout = 1;
1625
1626         if (start_command(&child))
1627                 die(_("failed to start launchctl"));
1628
1629         result = finish_command(&child);
1630
1631         free(uid);
1632         return result;
1633 }
1634
1635 static int launchctl_remove_plist(enum schedule_priority schedule)
1636 {
1637         const char *frequency = get_frequency(schedule);
1638         char *name = launchctl_service_name(frequency);
1639         char *filename = launchctl_service_filename(name);
1640         int result = launchctl_boot_plist(0, filename);
1641         unlink(filename);
1642         free(filename);
1643         free(name);
1644         return result;
1645 }
1646
1647 static int launchctl_remove_plists(void)
1648 {
1649         return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1650                launchctl_remove_plist(SCHEDULE_DAILY) ||
1651                launchctl_remove_plist(SCHEDULE_WEEKLY);
1652 }
1653
1654 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1655 {
1656         FILE *plist;
1657         int i;
1658         const char *preamble, *repeat;
1659         const char *frequency = get_frequency(schedule);
1660         char *name = launchctl_service_name(frequency);
1661         char *filename = launchctl_service_filename(name);
1662
1663         if (safe_create_leading_directories(filename))
1664                 die(_("failed to create directories for '%s'"), filename);
1665         plist = xfopen(filename, "w");
1666
1667         preamble = "<?xml version=\"1.0\"?>\n"
1668                    "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1669                    "<plist version=\"1.0\">"
1670                    "<dict>\n"
1671                    "<key>Label</key><string>%s</string>\n"
1672                    "<key>ProgramArguments</key>\n"
1673                    "<array>\n"
1674                    "<string>%s/git</string>\n"
1675                    "<string>--exec-path=%s</string>\n"
1676                    "<string>for-each-repo</string>\n"
1677                    "<string>--config=maintenance.repo</string>\n"
1678                    "<string>maintenance</string>\n"
1679                    "<string>run</string>\n"
1680                    "<string>--schedule=%s</string>\n"
1681                    "</array>\n"
1682                    "<key>StartCalendarInterval</key>\n"
1683                    "<array>\n";
1684         fprintf(plist, preamble, name, exec_path, exec_path, frequency);
1685
1686         switch (schedule) {
1687         case SCHEDULE_HOURLY:
1688                 repeat = "<dict>\n"
1689                          "<key>Hour</key><integer>%d</integer>\n"
1690                          "<key>Minute</key><integer>0</integer>\n"
1691                          "</dict>\n";
1692                 for (i = 1; i <= 23; i++)
1693                         fprintf(plist, repeat, i);
1694                 break;
1695
1696         case SCHEDULE_DAILY:
1697                 repeat = "<dict>\n"
1698                          "<key>Day</key><integer>%d</integer>\n"
1699                          "<key>Hour</key><integer>0</integer>\n"
1700                          "<key>Minute</key><integer>0</integer>\n"
1701                          "</dict>\n";
1702                 for (i = 1; i <= 6; i++)
1703                         fprintf(plist, repeat, i);
1704                 break;
1705
1706         case SCHEDULE_WEEKLY:
1707                 fprintf(plist,
1708                         "<dict>\n"
1709                         "<key>Day</key><integer>0</integer>\n"
1710                         "<key>Hour</key><integer>0</integer>\n"
1711                         "<key>Minute</key><integer>0</integer>\n"
1712                         "</dict>\n");
1713                 break;
1714
1715         default:
1716                 /* unreachable */
1717                 break;
1718         }
1719         fprintf(plist, "</array>\n</dict>\n</plist>\n");
1720         fclose(plist);
1721
1722         /* bootout might fail if not already running, so ignore */
1723         launchctl_boot_plist(0, filename);
1724         if (launchctl_boot_plist(1, filename))
1725                 die(_("failed to bootstrap service %s"), filename);
1726
1727         free(filename);
1728         free(name);
1729         return 0;
1730 }
1731
1732 static int launchctl_add_plists(void)
1733 {
1734         const char *exec_path = git_exec_path();
1735
1736         return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1737                launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1738                launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1739 }
1740
1741 static int launchctl_update_schedule(int run_maintenance, int fd)
1742 {
1743         if (run_maintenance)
1744                 return launchctl_add_plists();
1745         else
1746                 return launchctl_remove_plists();
1747 }
1748
1749 static int is_schtasks_available(void)
1750 {
1751         const char *cmd = "schtasks";
1752         int is_available;
1753         if (get_schedule_cmd(&cmd, &is_available))
1754                 return is_available;
1755
1756 #ifdef GIT_WINDOWS_NATIVE
1757         return 1;
1758 #else
1759         return 0;
1760 #endif
1761 }
1762
1763 static char *schtasks_task_name(const char *frequency)
1764 {
1765         struct strbuf label = STRBUF_INIT;
1766         strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1767         return strbuf_detach(&label, NULL);
1768 }
1769
1770 static int schtasks_remove_task(enum schedule_priority schedule)
1771 {
1772         const char *cmd = "schtasks";
1773         int result;
1774         struct strvec args = STRVEC_INIT;
1775         const char *frequency = get_frequency(schedule);
1776         char *name = schtasks_task_name(frequency);
1777
1778         get_schedule_cmd(&cmd, NULL);
1779         strvec_split(&args, cmd);
1780         strvec_pushl(&args, "/delete", "/tn", name, "/f", NULL);
1781
1782         result = run_command_v_opt(args.v, 0);
1783
1784         strvec_clear(&args);
1785         free(name);
1786         return result;
1787 }
1788
1789 static int schtasks_remove_tasks(void)
1790 {
1791         return schtasks_remove_task(SCHEDULE_HOURLY) ||
1792                schtasks_remove_task(SCHEDULE_DAILY) ||
1793                schtasks_remove_task(SCHEDULE_WEEKLY);
1794 }
1795
1796 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
1797 {
1798         const char *cmd = "schtasks";
1799         int result;
1800         struct child_process child = CHILD_PROCESS_INIT;
1801         const char *xml;
1802         struct tempfile *tfile;
1803         const char *frequency = get_frequency(schedule);
1804         char *name = schtasks_task_name(frequency);
1805         struct strbuf tfilename = STRBUF_INIT;
1806
1807         get_schedule_cmd(&cmd, NULL);
1808
1809         strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1810                     get_git_common_dir(), frequency);
1811         tfile = xmks_tempfile(tfilename.buf);
1812         strbuf_release(&tfilename);
1813
1814         if (!fdopen_tempfile(tfile, "w"))
1815                 die(_("failed to create temp xml file"));
1816
1817         xml = "<?xml version=\"1.0\" ?>\n"
1818               "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1819               "<Triggers>\n"
1820               "<CalendarTrigger>\n";
1821         fputs(xml, tfile->fp);
1822
1823         switch (schedule) {
1824         case SCHEDULE_HOURLY:
1825                 fprintf(tfile->fp,
1826                         "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1827                         "<Enabled>true</Enabled>\n"
1828                         "<ScheduleByDay>\n"
1829                         "<DaysInterval>1</DaysInterval>\n"
1830                         "</ScheduleByDay>\n"
1831                         "<Repetition>\n"
1832                         "<Interval>PT1H</Interval>\n"
1833                         "<Duration>PT23H</Duration>\n"
1834                         "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1835                         "</Repetition>\n");
1836                 break;
1837
1838         case SCHEDULE_DAILY:
1839                 fprintf(tfile->fp,
1840                         "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1841                         "<Enabled>true</Enabled>\n"
1842                         "<ScheduleByWeek>\n"
1843                         "<DaysOfWeek>\n"
1844                         "<Monday />\n"
1845                         "<Tuesday />\n"
1846                         "<Wednesday />\n"
1847                         "<Thursday />\n"
1848                         "<Friday />\n"
1849                         "<Saturday />\n"
1850                         "</DaysOfWeek>\n"
1851                         "<WeeksInterval>1</WeeksInterval>\n"
1852                         "</ScheduleByWeek>\n");
1853                 break;
1854
1855         case SCHEDULE_WEEKLY:
1856                 fprintf(tfile->fp,
1857                         "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1858                         "<Enabled>true</Enabled>\n"
1859                         "<ScheduleByWeek>\n"
1860                         "<DaysOfWeek>\n"
1861                         "<Sunday />\n"
1862                         "</DaysOfWeek>\n"
1863                         "<WeeksInterval>1</WeeksInterval>\n"
1864                         "</ScheduleByWeek>\n");
1865                 break;
1866
1867         default:
1868                 break;
1869         }
1870
1871         xml = "</CalendarTrigger>\n"
1872               "</Triggers>\n"
1873               "<Principals>\n"
1874               "<Principal id=\"Author\">\n"
1875               "<LogonType>InteractiveToken</LogonType>\n"
1876               "<RunLevel>LeastPrivilege</RunLevel>\n"
1877               "</Principal>\n"
1878               "</Principals>\n"
1879               "<Settings>\n"
1880               "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1881               "<Enabled>true</Enabled>\n"
1882               "<Hidden>true</Hidden>\n"
1883               "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1884               "<WakeToRun>false</WakeToRun>\n"
1885               "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1886               "<Priority>7</Priority>\n"
1887               "</Settings>\n"
1888               "<Actions Context=\"Author\">\n"
1889               "<Exec>\n"
1890               "<Command>\"%s\\git.exe\"</Command>\n"
1891               "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1892               "</Exec>\n"
1893               "</Actions>\n"
1894               "</Task>\n";
1895         fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
1896         strvec_split(&child.args, cmd);
1897         strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
1898                                   get_tempfile_path(tfile), NULL);
1899         close_tempfile_gently(tfile);
1900
1901         child.no_stdout = 1;
1902         child.no_stderr = 1;
1903
1904         if (start_command(&child))
1905                 die(_("failed to start schtasks"));
1906         result = finish_command(&child);
1907
1908         delete_tempfile(&tfile);
1909         free(name);
1910         return result;
1911 }
1912
1913 static int schtasks_schedule_tasks(void)
1914 {
1915         const char *exec_path = git_exec_path();
1916
1917         return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
1918                schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
1919                schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
1920 }
1921
1922 static int schtasks_update_schedule(int run_maintenance, int fd)
1923 {
1924         if (run_maintenance)
1925                 return schtasks_schedule_tasks();
1926         else
1927                 return schtasks_remove_tasks();
1928 }
1929
1930 static int is_crontab_available(void)
1931 {
1932         const char *cmd = "crontab";
1933         int is_available;
1934         struct child_process child = CHILD_PROCESS_INIT;
1935
1936         if (get_schedule_cmd(&cmd, &is_available) && !is_available)
1937                 return 0;
1938
1939         strvec_split(&child.args, cmd);
1940         strvec_push(&child.args, "-l");
1941         child.no_stdin = 1;
1942         child.no_stdout = 1;
1943         child.no_stderr = 1;
1944         child.silent_exec_failure = 1;
1945
1946         if (start_command(&child))
1947                 return 0;
1948         /* Ignore exit code, as an empty crontab will return error. */
1949         finish_command(&child);
1950         return 1;
1951 }
1952
1953 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
1954 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
1955
1956 static int crontab_update_schedule(int run_maintenance, int fd)
1957 {
1958         const char *cmd = "crontab";
1959         int result = 0;
1960         int in_old_region = 0;
1961         struct child_process crontab_list = CHILD_PROCESS_INIT;
1962         struct child_process crontab_edit = CHILD_PROCESS_INIT;
1963         FILE *cron_list, *cron_in;
1964         struct strbuf line = STRBUF_INIT;
1965
1966         get_schedule_cmd(&cmd, NULL);
1967         strvec_split(&crontab_list.args, cmd);
1968         strvec_push(&crontab_list.args, "-l");
1969         crontab_list.in = -1;
1970         crontab_list.out = dup(fd);
1971         crontab_list.git_cmd = 0;
1972
1973         if (start_command(&crontab_list))
1974                 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
1975
1976         /* Ignore exit code, as an empty crontab will return error. */
1977         finish_command(&crontab_list);
1978
1979         /*
1980          * Read from the .lock file, filtering out the old
1981          * schedule while appending the new schedule.
1982          */
1983         cron_list = fdopen(fd, "r");
1984         rewind(cron_list);
1985
1986         strvec_split(&crontab_edit.args, cmd);
1987         crontab_edit.in = -1;
1988         crontab_edit.git_cmd = 0;
1989
1990         if (start_command(&crontab_edit))
1991                 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
1992
1993         cron_in = fdopen(crontab_edit.in, "w");
1994         if (!cron_in) {
1995                 result = error(_("failed to open stdin of 'crontab'"));
1996                 goto done_editing;
1997         }
1998
1999         while (!strbuf_getline_lf(&line, cron_list)) {
2000                 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2001                         in_old_region = 1;
2002                 else if (in_old_region && !strcmp(line.buf, END_LINE))
2003                         in_old_region = 0;
2004                 else if (!in_old_region)
2005                         fprintf(cron_in, "%s\n", line.buf);
2006         }
2007         strbuf_release(&line);
2008
2009         if (run_maintenance) {
2010                 struct strbuf line_format = STRBUF_INIT;
2011                 const char *exec_path = git_exec_path();
2012
2013                 fprintf(cron_in, "%s\n", BEGIN_LINE);
2014                 fprintf(cron_in,
2015                         "# The following schedule was created by Git\n");
2016                 fprintf(cron_in, "# Any edits made in this region might be\n");
2017                 fprintf(cron_in,
2018                         "# replaced in the future by a Git command.\n\n");
2019
2020                 strbuf_addf(&line_format,
2021                             "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2022                             exec_path, exec_path);
2023                 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2024                 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2025                 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2026                 strbuf_release(&line_format);
2027
2028                 fprintf(cron_in, "\n%s\n", END_LINE);
2029         }
2030
2031         fflush(cron_in);
2032         fclose(cron_in);
2033         close(crontab_edit.in);
2034
2035 done_editing:
2036         if (finish_command(&crontab_edit))
2037                 result = error(_("'crontab' died"));
2038         else
2039                 fclose(cron_list);
2040         return result;
2041 }
2042
2043 #ifdef __linux__
2044
2045 static int real_is_systemd_timer_available(void)
2046 {
2047         struct child_process child = CHILD_PROCESS_INIT;
2048
2049         strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2050         child.no_stdin = 1;
2051         child.no_stdout = 1;
2052         child.no_stderr = 1;
2053         child.silent_exec_failure = 1;
2054
2055         if (start_command(&child))
2056                 return 0;
2057         if (finish_command(&child))
2058                 return 0;
2059         return 1;
2060 }
2061
2062 #else
2063
2064 static int real_is_systemd_timer_available(void)
2065 {
2066         return 0;
2067 }
2068
2069 #endif
2070
2071 static int is_systemd_timer_available(void)
2072 {
2073         const char *cmd = "systemctl";
2074         int is_available;
2075
2076         if (get_schedule_cmd(&cmd, &is_available))
2077                 return is_available;
2078
2079         return real_is_systemd_timer_available();
2080 }
2081
2082 static char *xdg_config_home_systemd(const char *filename)
2083 {
2084         return xdg_config_home_for("systemd/user", filename);
2085 }
2086
2087 static int systemd_timer_enable_unit(int enable,
2088                                      enum schedule_priority schedule)
2089 {
2090         const char *cmd = "systemctl";
2091         struct child_process child = CHILD_PROCESS_INIT;
2092         const char *frequency = get_frequency(schedule);
2093
2094         /*
2095          * Disabling the systemd unit while it is already disabled makes
2096          * systemctl print an error.
2097          * Let's ignore it since it means we already are in the expected state:
2098          * the unit is disabled.
2099          *
2100          * On the other hand, enabling a systemd unit which is already enabled
2101          * produces no error.
2102          */
2103         if (!enable)
2104                 child.no_stderr = 1;
2105
2106         get_schedule_cmd(&cmd, NULL);
2107         strvec_split(&child.args, cmd);
2108         strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2109                      "--now", NULL);
2110         strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2111
2112         if (start_command(&child))
2113                 return error(_("failed to start systemctl"));
2114         if (finish_command(&child))
2115                 /*
2116                  * Disabling an already disabled systemd unit makes
2117                  * systemctl fail.
2118                  * Let's ignore this failure.
2119                  *
2120                  * Enabling an enabled systemd unit doesn't fail.
2121                  */
2122                 if (enable)
2123                         return error(_("failed to run systemctl"));
2124         return 0;
2125 }
2126
2127 static int systemd_timer_delete_unit_templates(void)
2128 {
2129         int ret = 0;
2130         char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2131         if (unlink(filename) && !is_missing_file_error(errno))
2132                 ret = error_errno(_("failed to delete '%s'"), filename);
2133         FREE_AND_NULL(filename);
2134
2135         filename = xdg_config_home_systemd("git-maintenance@.service");
2136         if (unlink(filename) && !is_missing_file_error(errno))
2137                 ret = error_errno(_("failed to delete '%s'"), filename);
2138
2139         free(filename);
2140         return ret;
2141 }
2142
2143 static int systemd_timer_delete_units(void)
2144 {
2145         return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2146                systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2147                systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2148                systemd_timer_delete_unit_templates();
2149 }
2150
2151 static int systemd_timer_write_unit_templates(const char *exec_path)
2152 {
2153         char *filename;
2154         FILE *file;
2155         const char *unit;
2156
2157         filename = xdg_config_home_systemd("git-maintenance@.timer");
2158         if (safe_create_leading_directories(filename)) {
2159                 error(_("failed to create directories for '%s'"), filename);
2160                 goto error;
2161         }
2162         file = fopen_or_warn(filename, "w");
2163         if (file == NULL)
2164                 goto error;
2165
2166         unit = "# This file was created and is maintained by Git.\n"
2167                "# Any edits made in this file might be replaced in the future\n"
2168                "# by a Git command.\n"
2169                "\n"
2170                "[Unit]\n"
2171                "Description=Optimize Git repositories data\n"
2172                "\n"
2173                "[Timer]\n"
2174                "OnCalendar=%i\n"
2175                "Persistent=true\n"
2176                "\n"
2177                "[Install]\n"
2178                "WantedBy=timers.target\n";
2179         if (fputs(unit, file) == EOF) {
2180                 error(_("failed to write to '%s'"), filename);
2181                 fclose(file);
2182                 goto error;
2183         }
2184         if (fclose(file) == EOF) {
2185                 error_errno(_("failed to flush '%s'"), filename);
2186                 goto error;
2187         }
2188         free(filename);
2189
2190         filename = xdg_config_home_systemd("git-maintenance@.service");
2191         file = fopen_or_warn(filename, "w");
2192         if (file == NULL)
2193                 goto error;
2194
2195         unit = "# This file was created and is maintained by Git.\n"
2196                "# Any edits made in this file might be replaced in the future\n"
2197                "# by a Git command.\n"
2198                "\n"
2199                "[Unit]\n"
2200                "Description=Optimize Git repositories data\n"
2201                "\n"
2202                "[Service]\n"
2203                "Type=oneshot\n"
2204                "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2205                "LockPersonality=yes\n"
2206                "MemoryDenyWriteExecute=yes\n"
2207                "NoNewPrivileges=yes\n"
2208                "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2209                "RestrictNamespaces=yes\n"
2210                "RestrictRealtime=yes\n"
2211                "RestrictSUIDSGID=yes\n"
2212                "SystemCallArchitectures=native\n"
2213                "SystemCallFilter=@system-service\n";
2214         if (fprintf(file, unit, exec_path, exec_path) < 0) {
2215                 error(_("failed to write to '%s'"), filename);
2216                 fclose(file);
2217                 goto error;
2218         }
2219         if (fclose(file) == EOF) {
2220                 error_errno(_("failed to flush '%s'"), filename);
2221                 goto error;
2222         }
2223         free(filename);
2224         return 0;
2225
2226 error:
2227         free(filename);
2228         systemd_timer_delete_unit_templates();
2229         return -1;
2230 }
2231
2232 static int systemd_timer_setup_units(void)
2233 {
2234         const char *exec_path = git_exec_path();
2235
2236         int ret = systemd_timer_write_unit_templates(exec_path) ||
2237                   systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2238                   systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2239                   systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2240         if (ret)
2241                 systemd_timer_delete_units();
2242         return ret;
2243 }
2244
2245 static int systemd_timer_update_schedule(int run_maintenance, int fd)
2246 {
2247         if (run_maintenance)
2248                 return systemd_timer_setup_units();
2249         else
2250                 return systemd_timer_delete_units();
2251 }
2252
2253 enum scheduler {
2254         SCHEDULER_INVALID = -1,
2255         SCHEDULER_AUTO,
2256         SCHEDULER_CRON,
2257         SCHEDULER_SYSTEMD,
2258         SCHEDULER_LAUNCHCTL,
2259         SCHEDULER_SCHTASKS,
2260 };
2261
2262 static const struct {
2263         const char *name;
2264         int (*is_available)(void);
2265         int (*update_schedule)(int run_maintenance, int fd);
2266 } scheduler_fn[] = {
2267         [SCHEDULER_CRON] = {
2268                 .name = "crontab",
2269                 .is_available = is_crontab_available,
2270                 .update_schedule = crontab_update_schedule,
2271         },
2272         [SCHEDULER_SYSTEMD] = {
2273                 .name = "systemctl",
2274                 .is_available = is_systemd_timer_available,
2275                 .update_schedule = systemd_timer_update_schedule,
2276         },
2277         [SCHEDULER_LAUNCHCTL] = {
2278                 .name = "launchctl",
2279                 .is_available = is_launchctl_available,
2280                 .update_schedule = launchctl_update_schedule,
2281         },
2282         [SCHEDULER_SCHTASKS] = {
2283                 .name = "schtasks",
2284                 .is_available = is_schtasks_available,
2285                 .update_schedule = schtasks_update_schedule,
2286         },
2287 };
2288
2289 static enum scheduler parse_scheduler(const char *value)
2290 {
2291         if (!value)
2292                 return SCHEDULER_INVALID;
2293         else if (!strcasecmp(value, "auto"))
2294                 return SCHEDULER_AUTO;
2295         else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2296                 return SCHEDULER_CRON;
2297         else if (!strcasecmp(value, "systemd") ||
2298                  !strcasecmp(value, "systemd-timer"))
2299                 return SCHEDULER_SYSTEMD;
2300         else if (!strcasecmp(value, "launchctl"))
2301                 return SCHEDULER_LAUNCHCTL;
2302         else if (!strcasecmp(value, "schtasks"))
2303                 return SCHEDULER_SCHTASKS;
2304         else
2305                 return SCHEDULER_INVALID;
2306 }
2307
2308 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2309                                      int unset)
2310 {
2311         enum scheduler *scheduler = opt->value;
2312
2313         BUG_ON_OPT_NEG(unset);
2314
2315         *scheduler = parse_scheduler(arg);
2316         if (*scheduler == SCHEDULER_INVALID)
2317                 return error(_("unrecognized --scheduler argument '%s'"), arg);
2318         return 0;
2319 }
2320
2321 struct maintenance_start_opts {
2322         enum scheduler scheduler;
2323 };
2324
2325 static void resolve_auto_scheduler(enum scheduler *scheduler)
2326 {
2327         if (*scheduler != SCHEDULER_AUTO)
2328                 return;
2329
2330 #if defined(__APPLE__)
2331         *scheduler = SCHEDULER_LAUNCHCTL;
2332         return;
2333
2334 #elif defined(GIT_WINDOWS_NATIVE)
2335         *scheduler = SCHEDULER_SCHTASKS;
2336         return;
2337
2338 #elif defined(__linux__)
2339         if (is_systemd_timer_available())
2340                 *scheduler = SCHEDULER_SYSTEMD;
2341         else if (is_crontab_available())
2342                 *scheduler = SCHEDULER_CRON;
2343         else
2344                 die(_("neither systemd timers nor crontab are available"));
2345         return;
2346
2347 #else
2348         *scheduler = SCHEDULER_CRON;
2349         return;
2350 #endif
2351 }
2352
2353 static void validate_scheduler(enum scheduler scheduler)
2354 {
2355         if (scheduler == SCHEDULER_INVALID)
2356                 BUG("invalid scheduler");
2357         if (scheduler == SCHEDULER_AUTO)
2358                 BUG("resolve_auto_scheduler should have been called before");
2359
2360         if (!scheduler_fn[scheduler].is_available())
2361                 die(_("%s scheduler is not available"),
2362                     scheduler_fn[scheduler].name);
2363 }
2364
2365 static int update_background_schedule(const struct maintenance_start_opts *opts,
2366                                       int enable)
2367 {
2368         unsigned int i;
2369         int result = 0;
2370         struct lock_file lk;
2371         char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2372
2373         if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2374                 free(lock_path);
2375                 return error(_("another process is scheduling background maintenance"));
2376         }
2377
2378         for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2379                 if (enable && opts->scheduler == i)
2380                         continue;
2381                 if (!scheduler_fn[i].is_available())
2382                         continue;
2383                 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2384         }
2385
2386         if (enable)
2387                 result = scheduler_fn[opts->scheduler].update_schedule(
2388                         1, get_lock_file_fd(&lk));
2389
2390         rollback_lock_file(&lk);
2391
2392         free(lock_path);
2393         return result;
2394 }
2395
2396 static const char *const builtin_maintenance_start_usage[] = {
2397         N_("git maintenance start [--scheduler=<scheduler>]"),
2398         NULL
2399 };
2400
2401 static int maintenance_start(int argc, const char **argv, const char *prefix)
2402 {
2403         struct maintenance_start_opts opts = { 0 };
2404         struct option options[] = {
2405                 OPT_CALLBACK_F(
2406                         0, "scheduler", &opts.scheduler, N_("scheduler"),
2407                         N_("scheduler to use to trigger git maintenance run"),
2408                         PARSE_OPT_NONEG, maintenance_opt_scheduler),
2409                 OPT_END()
2410         };
2411
2412         argc = parse_options(argc, argv, prefix, options,
2413                              builtin_maintenance_start_usage, 0);
2414         if (argc)
2415                 usage_with_options(builtin_maintenance_start_usage, options);
2416
2417         resolve_auto_scheduler(&opts.scheduler);
2418         validate_scheduler(opts.scheduler);
2419
2420         if (maintenance_register())
2421                 warning(_("failed to add repo to global config"));
2422         return update_background_schedule(&opts, 1);
2423 }
2424
2425 static int maintenance_stop(void)
2426 {
2427         return update_background_schedule(NULL, 0);
2428 }
2429
2430 static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
2431
2432 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2433 {
2434         if (argc < 2 ||
2435             (argc == 2 && !strcmp(argv[1], "-h")))
2436                 usage(builtin_maintenance_usage);
2437
2438         if (!strcmp(argv[1], "run"))
2439                 return maintenance_run(argc - 1, argv + 1, prefix);
2440         if (!strcmp(argv[1], "start"))
2441                 return maintenance_start(argc - 1, argv + 1, prefix);
2442         if (!strcmp(argv[1], "stop"))
2443                 return maintenance_stop();
2444         if (!strcmp(argv[1], "register"))
2445                 return maintenance_register();
2446         if (!strcmp(argv[1], "unregister"))
2447                 return maintenance_unregister();
2448
2449         die(_("invalid subcommand: %s"), argv[1]);
2450 }