builtin/gc: move `struct maintenance_run_opts`
[alt-git.git] / builtin / gc.c
blobe0029c88f9fe71dd87368dea08f2cab198e8227a
1 /*
2 * git gc builtin command
4 * Cleanup unreachable files and optimize the repository.
6 * Copyright (c) 2007 James Bowes
8 * Based on git-gc.sh, which is
10 * Copyright (c) 2006 Shawn O. Pearce
13 #include "builtin.h"
14 #include "abspath.h"
15 #include "date.h"
16 #include "environment.h"
17 #include "hex.h"
18 #include "repository.h"
19 #include "config.h"
20 #include "tempfile.h"
21 #include "lockfile.h"
22 #include "parse-options.h"
23 #include "run-command.h"
24 #include "sigchain.h"
25 #include "strvec.h"
26 #include "commit.h"
27 #include "commit-graph.h"
28 #include "packfile.h"
29 #include "object-file.h"
30 #include "object-store-ll.h"
31 #include "pack.h"
32 #include "pack-objects.h"
33 #include "path.h"
34 #include "blob.h"
35 #include "tree.h"
36 #include "promisor-remote.h"
37 #include "refs.h"
38 #include "remote.h"
39 #include "exec-cmd.h"
40 #include "gettext.h"
41 #include "hook.h"
42 #include "setup.h"
43 #include "trace2.h"
45 #define FAILED_RUN "failed to run %s"
47 static const char * const builtin_gc_usage[] = {
48 N_("git gc [<options>]"),
49 NULL
52 static int pack_refs = 1;
53 static int prune_reflogs = 1;
54 static int cruft_packs = 1;
55 static unsigned long max_cruft_size;
56 static int aggressive_depth = 50;
57 static int aggressive_window = 250;
58 static int gc_auto_threshold = 6700;
59 static int gc_auto_pack_limit = 50;
60 static int detach_auto = 1;
61 static timestamp_t gc_log_expire_time;
62 static const char *gc_log_expire = "1.day.ago";
63 static const char *prune_expire = "2.weeks.ago";
64 static const char *prune_worktrees_expire = "3.months.ago";
65 static char *repack_filter;
66 static char *repack_filter_to;
67 static unsigned long big_pack_threshold;
68 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
70 static struct strvec reflog = STRVEC_INIT;
71 static struct strvec repack = STRVEC_INIT;
72 static struct strvec prune = STRVEC_INIT;
73 static struct strvec prune_worktrees = STRVEC_INIT;
74 static struct strvec rerere = STRVEC_INIT;
76 static struct tempfile *pidfile;
77 static struct lock_file log_lock;
79 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
81 static void clean_pack_garbage(void)
83 int i;
84 for (i = 0; i < pack_garbage.nr; i++)
85 unlink_or_warn(pack_garbage.items[i].string);
86 string_list_clear(&pack_garbage, 0);
89 static void report_pack_garbage(unsigned seen_bits, const char *path)
91 if (seen_bits == PACKDIR_FILE_IDX)
92 string_list_append(&pack_garbage, path);
95 static void process_log_file(void)
97 struct stat st;
98 if (fstat(get_lock_file_fd(&log_lock), &st)) {
100 * Perhaps there was an i/o error or another
101 * unlikely situation. Try to make a note of
102 * this in gc.log along with any existing
103 * messages.
105 int saved_errno = errno;
106 fprintf(stderr, _("Failed to fstat %s: %s"),
107 get_lock_file_path(&log_lock),
108 strerror(saved_errno));
109 fflush(stderr);
110 commit_lock_file(&log_lock);
111 errno = saved_errno;
112 } else if (st.st_size) {
113 /* There was some error recorded in the lock file */
114 commit_lock_file(&log_lock);
115 } else {
116 /* No error, clean up any old gc.log */
117 unlink(git_path("gc.log"));
118 rollback_lock_file(&log_lock);
122 static void process_log_file_at_exit(void)
124 fflush(stderr);
125 process_log_file();
128 static void process_log_file_on_signal(int signo)
130 process_log_file();
131 sigchain_pop(signo);
132 raise(signo);
135 static int gc_config_is_timestamp_never(const char *var)
137 const char *value;
138 timestamp_t expire;
140 if (!git_config_get_value(var, &value) && value) {
141 if (parse_expiry_date(value, &expire))
142 die(_("failed to parse '%s' value '%s'"), var, value);
143 return expire == 0;
145 return 0;
148 static void gc_config(void)
150 const char *value;
152 if (!git_config_get_value("gc.packrefs", &value)) {
153 if (value && !strcmp(value, "notbare"))
154 pack_refs = -1;
155 else
156 pack_refs = git_config_bool("gc.packrefs", value);
159 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
160 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
161 prune_reflogs = 0;
163 git_config_get_int("gc.aggressivewindow", &aggressive_window);
164 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
165 git_config_get_int("gc.auto", &gc_auto_threshold);
166 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
167 git_config_get_bool("gc.autodetach", &detach_auto);
168 git_config_get_bool("gc.cruftpacks", &cruft_packs);
169 git_config_get_ulong("gc.maxcruftsize", &max_cruft_size);
170 git_config_get_expiry("gc.pruneexpire", &prune_expire);
171 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
172 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
174 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
175 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
177 git_config_get_string("gc.repackfilter", &repack_filter);
178 git_config_get_string("gc.repackfilterto", &repack_filter_to);
180 git_config(git_default_config, NULL);
183 enum schedule_priority {
184 SCHEDULE_NONE = 0,
185 SCHEDULE_WEEKLY = 1,
186 SCHEDULE_DAILY = 2,
187 SCHEDULE_HOURLY = 3,
190 static enum schedule_priority parse_schedule(const char *value)
192 if (!value)
193 return SCHEDULE_NONE;
194 if (!strcasecmp(value, "hourly"))
195 return SCHEDULE_HOURLY;
196 if (!strcasecmp(value, "daily"))
197 return SCHEDULE_DAILY;
198 if (!strcasecmp(value, "weekly"))
199 return SCHEDULE_WEEKLY;
200 return SCHEDULE_NONE;
203 struct maintenance_run_opts {
204 int auto_flag;
205 int quiet;
206 enum schedule_priority schedule;
209 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
211 struct child_process cmd = CHILD_PROCESS_INIT;
213 cmd.git_cmd = 1;
214 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
215 return run_command(&cmd);
218 static int too_many_loose_objects(void)
221 * Quickly check if a "gc" is needed, by estimating how
222 * many loose objects there are. Because SHA-1 is evenly
223 * distributed, we can check only one and get a reasonable
224 * estimate.
226 DIR *dir;
227 struct dirent *ent;
228 int auto_threshold;
229 int num_loose = 0;
230 int needed = 0;
231 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
233 dir = opendir(git_path("objects/17"));
234 if (!dir)
235 return 0;
237 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
238 while ((ent = readdir(dir)) != NULL) {
239 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
240 ent->d_name[hexsz_loose] != '\0')
241 continue;
242 if (++num_loose > auto_threshold) {
243 needed = 1;
244 break;
247 closedir(dir);
248 return needed;
251 static struct packed_git *find_base_packs(struct string_list *packs,
252 unsigned long limit)
254 struct packed_git *p, *base = NULL;
256 for (p = get_all_packs(the_repository); p; p = p->next) {
257 if (!p->pack_local || p->is_cruft)
258 continue;
259 if (limit) {
260 if (p->pack_size >= limit)
261 string_list_append(packs, p->pack_name);
262 } else if (!base || base->pack_size < p->pack_size) {
263 base = p;
267 if (base)
268 string_list_append(packs, base->pack_name);
270 return base;
273 static int too_many_packs(void)
275 struct packed_git *p;
276 int cnt;
278 if (gc_auto_pack_limit <= 0)
279 return 0;
281 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
282 if (!p->pack_local)
283 continue;
284 if (p->pack_keep)
285 continue;
287 * Perhaps check the size of the pack and count only
288 * very small ones here?
290 cnt++;
292 return gc_auto_pack_limit < cnt;
295 static uint64_t total_ram(void)
297 #if defined(HAVE_SYSINFO)
298 struct sysinfo si;
300 if (!sysinfo(&si))
301 return si.totalram;
302 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
303 int64_t physical_memory;
304 int mib[2];
305 size_t length;
307 mib[0] = CTL_HW;
308 # if defined(HW_MEMSIZE)
309 mib[1] = HW_MEMSIZE;
310 # else
311 mib[1] = HW_PHYSMEM;
312 # endif
313 length = sizeof(int64_t);
314 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
315 return physical_memory;
316 #elif defined(GIT_WINDOWS_NATIVE)
317 MEMORYSTATUSEX memInfo;
319 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
320 if (GlobalMemoryStatusEx(&memInfo))
321 return memInfo.ullTotalPhys;
322 #endif
323 return 0;
326 static uint64_t estimate_repack_memory(struct packed_git *pack)
328 unsigned long nr_objects = repo_approximate_object_count(the_repository);
329 size_t os_cache, heap;
331 if (!pack || !nr_objects)
332 return 0;
335 * First we have to scan through at least one pack.
336 * Assume enough room in OS file cache to keep the entire pack
337 * or we may accidentally evict data of other processes from
338 * the cache.
340 os_cache = pack->pack_size + pack->index_size;
341 /* then pack-objects needs lots more for book keeping */
342 heap = sizeof(struct object_entry) * nr_objects;
344 * internal rev-list --all --objects takes up some memory too,
345 * let's say half of it is for blobs
347 heap += sizeof(struct blob) * nr_objects / 2;
349 * and the other half is for trees (commits and tags are
350 * usually insignificant)
352 heap += sizeof(struct tree) * nr_objects / 2;
353 /* and then obj_hash[], underestimated in fact */
354 heap += sizeof(struct object *) * nr_objects;
355 /* revindex is used also */
356 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
358 * read_sha1_file() (either at delta calculation phase, or
359 * writing phase) also fills up the delta base cache
361 heap += delta_base_cache_limit;
362 /* and of course pack-objects has its own delta cache */
363 heap += max_delta_cache_size;
365 return os_cache + heap;
368 static int keep_one_pack(struct string_list_item *item, void *data UNUSED)
370 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
371 return 0;
374 static void add_repack_all_option(struct string_list *keep_pack)
376 if (prune_expire && !strcmp(prune_expire, "now"))
377 strvec_push(&repack, "-a");
378 else if (cruft_packs) {
379 strvec_push(&repack, "--cruft");
380 if (prune_expire)
381 strvec_pushf(&repack, "--cruft-expiration=%s", prune_expire);
382 if (max_cruft_size)
383 strvec_pushf(&repack, "--max-cruft-size=%lu",
384 max_cruft_size);
385 } else {
386 strvec_push(&repack, "-A");
387 if (prune_expire)
388 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
391 if (keep_pack)
392 for_each_string_list(keep_pack, keep_one_pack, NULL);
394 if (repack_filter && *repack_filter)
395 strvec_pushf(&repack, "--filter=%s", repack_filter);
396 if (repack_filter_to && *repack_filter_to)
397 strvec_pushf(&repack, "--filter-to=%s", repack_filter_to);
400 static void add_repack_incremental_option(void)
402 strvec_push(&repack, "--no-write-bitmap-index");
405 static int need_to_gc(void)
408 * Setting gc.auto to 0 or negative can disable the
409 * automatic gc.
411 if (gc_auto_threshold <= 0)
412 return 0;
415 * If there are too many loose objects, but not too many
416 * packs, we run "repack -d -l". If there are too many packs,
417 * we run "repack -A -d -l". Otherwise we tell the caller
418 * there is no need.
420 if (too_many_packs()) {
421 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
423 if (big_pack_threshold) {
424 find_base_packs(&keep_pack, big_pack_threshold);
425 if (keep_pack.nr >= gc_auto_pack_limit) {
426 big_pack_threshold = 0;
427 string_list_clear(&keep_pack, 0);
428 find_base_packs(&keep_pack, 0);
430 } else {
431 struct packed_git *p = find_base_packs(&keep_pack, 0);
432 uint64_t mem_have, mem_want;
434 mem_have = total_ram();
435 mem_want = estimate_repack_memory(p);
438 * Only allow 1/2 of memory for pack-objects, leave
439 * the rest for the OS and other processes in the
440 * system.
442 if (!mem_have || mem_want < mem_have / 2)
443 string_list_clear(&keep_pack, 0);
446 add_repack_all_option(&keep_pack);
447 string_list_clear(&keep_pack, 0);
448 } else if (too_many_loose_objects())
449 add_repack_incremental_option();
450 else
451 return 0;
453 if (run_hooks("pre-auto-gc"))
454 return 0;
455 return 1;
458 /* return NULL on success, else hostname running the gc */
459 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
461 struct lock_file lock = LOCK_INIT;
462 char my_host[HOST_NAME_MAX + 1];
463 struct strbuf sb = STRBUF_INIT;
464 struct stat st;
465 uintmax_t pid;
466 FILE *fp;
467 int fd;
468 char *pidfile_path;
470 if (is_tempfile_active(pidfile))
471 /* already locked */
472 return NULL;
474 if (xgethostname(my_host, sizeof(my_host)))
475 xsnprintf(my_host, sizeof(my_host), "unknown");
477 pidfile_path = git_pathdup("gc.pid");
478 fd = hold_lock_file_for_update(&lock, pidfile_path,
479 LOCK_DIE_ON_ERROR);
480 if (!force) {
481 static char locking_host[HOST_NAME_MAX + 1];
482 static char *scan_fmt;
483 int should_exit;
485 if (!scan_fmt)
486 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
487 fp = fopen(pidfile_path, "r");
488 memset(locking_host, 0, sizeof(locking_host));
489 should_exit =
490 fp != NULL &&
491 !fstat(fileno(fp), &st) &&
493 * 12 hour limit is very generous as gc should
494 * never take that long. On the other hand we
495 * don't really need a strict limit here,
496 * running gc --auto one day late is not a big
497 * problem. --force can be used in manual gc
498 * after the user verifies that no gc is
499 * running.
501 time(NULL) - st.st_mtime <= 12 * 3600 &&
502 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
503 /* be gentle to concurrent "gc" on remote hosts */
504 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
505 if (fp)
506 fclose(fp);
507 if (should_exit) {
508 if (fd >= 0)
509 rollback_lock_file(&lock);
510 *ret_pid = pid;
511 free(pidfile_path);
512 return locking_host;
516 strbuf_addf(&sb, "%"PRIuMAX" %s",
517 (uintmax_t) getpid(), my_host);
518 write_in_full(fd, sb.buf, sb.len);
519 strbuf_release(&sb);
520 commit_lock_file(&lock);
521 pidfile = register_tempfile(pidfile_path);
522 free(pidfile_path);
523 return NULL;
527 * Returns 0 if there was no previous error and gc can proceed, 1 if
528 * gc should not proceed due to an error in the last run. Prints a
529 * message and returns with a non-[01] status code if an error occurred
530 * while reading gc.log
532 static int report_last_gc_error(void)
534 struct strbuf sb = STRBUF_INIT;
535 int ret = 0;
536 ssize_t len;
537 struct stat st;
538 char *gc_log_path = git_pathdup("gc.log");
540 if (stat(gc_log_path, &st)) {
541 if (errno == ENOENT)
542 goto done;
544 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
545 goto done;
548 if (st.st_mtime < gc_log_expire_time)
549 goto done;
551 len = strbuf_read_file(&sb, gc_log_path, 0);
552 if (len < 0)
553 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
554 else if (len > 0) {
556 * A previous gc failed. Report the error, and don't
557 * bother with an automatic gc run since it is likely
558 * to fail in the same way.
560 warning(_("The last gc run reported the following. "
561 "Please correct the root cause\n"
562 "and remove %s\n"
563 "Automatic cleanup will not be performed "
564 "until the file is removed.\n\n"
565 "%s"),
566 gc_log_path, sb.buf);
567 ret = 1;
569 strbuf_release(&sb);
570 done:
571 free(gc_log_path);
572 return ret;
575 static void gc_before_repack(void)
578 * We may be called twice, as both the pre- and
579 * post-daemonized phases will call us, but running these
580 * commands more than once is pointless and wasteful.
582 static int done = 0;
583 if (done++)
584 return;
586 if (pack_refs && maintenance_task_pack_refs(NULL))
587 die(FAILED_RUN, "pack-refs");
589 if (prune_reflogs) {
590 struct child_process cmd = CHILD_PROCESS_INIT;
592 cmd.git_cmd = 1;
593 strvec_pushv(&cmd.args, reflog.v);
594 if (run_command(&cmd))
595 die(FAILED_RUN, reflog.v[0]);
599 int cmd_gc(int argc, const char **argv, const char *prefix)
601 int aggressive = 0;
602 int auto_gc = 0;
603 int quiet = 0;
604 int force = 0;
605 const char *name;
606 pid_t pid;
607 int daemonized = 0;
608 int keep_largest_pack = -1;
609 timestamp_t dummy;
610 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
612 struct option builtin_gc_options[] = {
613 OPT__QUIET(&quiet, N_("suppress progress reporting")),
614 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
615 N_("prune unreferenced objects"),
616 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
617 OPT_BOOL(0, "cruft", &cruft_packs, N_("pack unreferenced objects separately")),
618 OPT_MAGNITUDE(0, "max-cruft-size", &max_cruft_size,
619 N_("with --cruft, limit the size of new cruft packs")),
620 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
621 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
622 PARSE_OPT_NOCOMPLETE),
623 OPT_BOOL_F(0, "force", &force,
624 N_("force running gc even if there may be another gc running"),
625 PARSE_OPT_NOCOMPLETE),
626 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
627 N_("repack all other packs except the largest pack")),
628 OPT_END()
631 if (argc == 2 && !strcmp(argv[1], "-h"))
632 usage_with_options(builtin_gc_usage, builtin_gc_options);
634 strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
635 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
636 strvec_pushl(&prune, "prune", "--expire", NULL);
637 strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
638 strvec_pushl(&rerere, "rerere", "gc", NULL);
640 /* default expiry time, overwritten in gc_config */
641 gc_config();
642 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
643 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire);
645 if (pack_refs < 0)
646 pack_refs = !is_bare_repository();
648 argc = parse_options(argc, argv, prefix, builtin_gc_options,
649 builtin_gc_usage, 0);
650 if (argc > 0)
651 usage_with_options(builtin_gc_usage, builtin_gc_options);
653 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
654 die(_("failed to parse prune expiry value %s"), prune_expire);
656 if (aggressive) {
657 strvec_push(&repack, "-f");
658 if (aggressive_depth > 0)
659 strvec_pushf(&repack, "--depth=%d", aggressive_depth);
660 if (aggressive_window > 0)
661 strvec_pushf(&repack, "--window=%d", aggressive_window);
663 if (quiet)
664 strvec_push(&repack, "-q");
666 if (auto_gc) {
668 * Auto-gc should be least intrusive as possible.
670 if (!need_to_gc())
671 return 0;
672 if (!quiet) {
673 if (detach_auto)
674 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
675 else
676 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
677 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
679 if (detach_auto) {
680 int ret = report_last_gc_error();
682 if (ret == 1)
683 /* Last gc --auto failed. Skip this one. */
684 return 0;
685 else if (ret)
686 /* an I/O error occurred, already reported */
687 return ret;
689 if (lock_repo_for_gc(force, &pid))
690 return 0;
691 gc_before_repack(); /* dies on failure */
692 delete_tempfile(&pidfile);
695 * failure to daemonize is ok, we'll continue
696 * in foreground
698 daemonized = !daemonize();
700 } else {
701 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
703 if (keep_largest_pack != -1) {
704 if (keep_largest_pack)
705 find_base_packs(&keep_pack, 0);
706 } else if (big_pack_threshold) {
707 find_base_packs(&keep_pack, big_pack_threshold);
710 add_repack_all_option(&keep_pack);
711 string_list_clear(&keep_pack, 0);
714 name = lock_repo_for_gc(force, &pid);
715 if (name) {
716 if (auto_gc)
717 return 0; /* be quiet on --auto */
718 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
719 name, (uintmax_t)pid);
722 if (daemonized) {
723 hold_lock_file_for_update(&log_lock,
724 git_path("gc.log"),
725 LOCK_DIE_ON_ERROR);
726 dup2(get_lock_file_fd(&log_lock), 2);
727 sigchain_push_common(process_log_file_on_signal);
728 atexit(process_log_file_at_exit);
731 gc_before_repack();
733 if (!repository_format_precious_objects) {
734 struct child_process repack_cmd = CHILD_PROCESS_INIT;
736 repack_cmd.git_cmd = 1;
737 repack_cmd.close_object_store = 1;
738 strvec_pushv(&repack_cmd.args, repack.v);
739 if (run_command(&repack_cmd))
740 die(FAILED_RUN, repack.v[0]);
742 if (prune_expire) {
743 struct child_process prune_cmd = CHILD_PROCESS_INIT;
745 /* run `git prune` even if using cruft packs */
746 strvec_push(&prune, prune_expire);
747 if (quiet)
748 strvec_push(&prune, "--no-progress");
749 if (repo_has_promisor_remote(the_repository))
750 strvec_push(&prune,
751 "--exclude-promisor-objects");
752 prune_cmd.git_cmd = 1;
753 strvec_pushv(&prune_cmd.args, prune.v);
754 if (run_command(&prune_cmd))
755 die(FAILED_RUN, prune.v[0]);
759 if (prune_worktrees_expire) {
760 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
762 strvec_push(&prune_worktrees, prune_worktrees_expire);
763 prune_worktrees_cmd.git_cmd = 1;
764 strvec_pushv(&prune_worktrees_cmd.args, prune_worktrees.v);
765 if (run_command(&prune_worktrees_cmd))
766 die(FAILED_RUN, prune_worktrees.v[0]);
769 rerere_cmd.git_cmd = 1;
770 strvec_pushv(&rerere_cmd.args, rerere.v);
771 if (run_command(&rerere_cmd))
772 die(FAILED_RUN, rerere.v[0]);
774 report_garbage = report_pack_garbage;
775 reprepare_packed_git(the_repository);
776 if (pack_garbage.nr > 0) {
777 close_object_store(the_repository->objects);
778 clean_pack_garbage();
781 if (the_repository->settings.gc_write_commit_graph == 1)
782 write_commit_graph_reachable(the_repository->objects->odb,
783 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
784 NULL);
786 if (auto_gc && too_many_loose_objects())
787 warning(_("There are too many unreachable loose objects; "
788 "run 'git prune' to remove them."));
790 if (!daemonized)
791 unlink(git_path("gc.log"));
793 return 0;
796 static const char *const builtin_maintenance_run_usage[] = {
797 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
798 NULL
801 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
802 int unset)
804 enum schedule_priority *priority = opt->value;
806 if (unset)
807 die(_("--no-schedule is not allowed"));
809 *priority = parse_schedule(arg);
811 if (!*priority)
812 die(_("unrecognized --schedule argument '%s'"), arg);
814 return 0;
817 /* Remember to update object flag allocation in object.h */
818 #define SEEN (1u<<0)
820 struct cg_auto_data {
821 int num_not_in_graph;
822 int limit;
825 static int dfs_on_ref(const char *refname UNUSED,
826 const struct object_id *oid,
827 int flags UNUSED,
828 void *cb_data)
830 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
831 int result = 0;
832 struct object_id peeled;
833 struct commit_list *stack = NULL;
834 struct commit *commit;
836 if (!peel_iterated_oid(oid, &peeled))
837 oid = &peeled;
838 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
839 return 0;
841 commit = lookup_commit(the_repository, oid);
842 if (!commit)
843 return 0;
844 if (repo_parse_commit(the_repository, commit) ||
845 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
846 return 0;
848 data->num_not_in_graph++;
850 if (data->num_not_in_graph >= data->limit)
851 return 1;
853 commit_list_append(commit, &stack);
855 while (!result && stack) {
856 struct commit_list *parent;
858 commit = pop_commit(&stack);
860 for (parent = commit->parents; parent; parent = parent->next) {
861 if (repo_parse_commit(the_repository, parent->item) ||
862 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
863 parent->item->object.flags & SEEN)
864 continue;
866 parent->item->object.flags |= SEEN;
867 data->num_not_in_graph++;
869 if (data->num_not_in_graph >= data->limit) {
870 result = 1;
871 break;
874 commit_list_append(parent->item, &stack);
878 free_commit_list(stack);
879 return result;
882 static int should_write_commit_graph(void)
884 int result;
885 struct cg_auto_data data;
887 data.num_not_in_graph = 0;
888 data.limit = 100;
889 git_config_get_int("maintenance.commit-graph.auto",
890 &data.limit);
892 if (!data.limit)
893 return 0;
894 if (data.limit < 0)
895 return 1;
897 result = for_each_ref(dfs_on_ref, &data);
899 repo_clear_commit_marks(the_repository, SEEN);
901 return result;
904 static int run_write_commit_graph(struct maintenance_run_opts *opts)
906 struct child_process child = CHILD_PROCESS_INIT;
908 child.git_cmd = child.close_object_store = 1;
909 strvec_pushl(&child.args, "commit-graph", "write",
910 "--split", "--reachable", NULL);
912 if (opts->quiet)
913 strvec_push(&child.args, "--no-progress");
915 return !!run_command(&child);
918 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
920 prepare_repo_settings(the_repository);
921 if (!the_repository->settings.core_commit_graph)
922 return 0;
924 if (run_write_commit_graph(opts)) {
925 error(_("failed to write commit-graph"));
926 return 1;
929 return 0;
932 static int fetch_remote(struct remote *remote, void *cbdata)
934 struct maintenance_run_opts *opts = cbdata;
935 struct child_process child = CHILD_PROCESS_INIT;
937 if (remote->skip_default_update)
938 return 0;
940 child.git_cmd = 1;
941 strvec_pushl(&child.args, "fetch", remote->name,
942 "--prefetch", "--prune", "--no-tags",
943 "--no-write-fetch-head", "--recurse-submodules=no",
944 NULL);
946 if (opts->quiet)
947 strvec_push(&child.args, "--quiet");
949 return !!run_command(&child);
952 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
954 if (for_each_remote(fetch_remote, opts)) {
955 error(_("failed to prefetch remotes"));
956 return 1;
959 return 0;
962 static int maintenance_task_gc(struct maintenance_run_opts *opts)
964 struct child_process child = CHILD_PROCESS_INIT;
966 child.git_cmd = child.close_object_store = 1;
967 strvec_push(&child.args, "gc");
969 if (opts->auto_flag)
970 strvec_push(&child.args, "--auto");
971 if (opts->quiet)
972 strvec_push(&child.args, "--quiet");
973 else
974 strvec_push(&child.args, "--no-quiet");
976 return run_command(&child);
979 static int prune_packed(struct maintenance_run_opts *opts)
981 struct child_process child = CHILD_PROCESS_INIT;
983 child.git_cmd = 1;
984 strvec_push(&child.args, "prune-packed");
986 if (opts->quiet)
987 strvec_push(&child.args, "--quiet");
989 return !!run_command(&child);
992 struct write_loose_object_data {
993 FILE *in;
994 int count;
995 int batch_size;
998 static int loose_object_auto_limit = 100;
1000 static int loose_object_count(const struct object_id *oid UNUSED,
1001 const char *path UNUSED,
1002 void *data)
1004 int *count = (int*)data;
1005 if (++(*count) >= loose_object_auto_limit)
1006 return 1;
1007 return 0;
1010 static int loose_object_auto_condition(void)
1012 int count = 0;
1014 git_config_get_int("maintenance.loose-objects.auto",
1015 &loose_object_auto_limit);
1017 if (!loose_object_auto_limit)
1018 return 0;
1019 if (loose_object_auto_limit < 0)
1020 return 1;
1022 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
1023 loose_object_count,
1024 NULL, NULL, &count);
1027 static int bail_on_loose(const struct object_id *oid UNUSED,
1028 const char *path UNUSED,
1029 void *data UNUSED)
1031 return 1;
1034 static int write_loose_object_to_stdin(const struct object_id *oid,
1035 const char *path UNUSED,
1036 void *data)
1038 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1040 fprintf(d->in, "%s\n", oid_to_hex(oid));
1042 return ++(d->count) > d->batch_size;
1045 static int pack_loose(struct maintenance_run_opts *opts)
1047 struct repository *r = the_repository;
1048 int result = 0;
1049 struct write_loose_object_data data;
1050 struct child_process pack_proc = CHILD_PROCESS_INIT;
1053 * Do not start pack-objects process
1054 * if there are no loose objects.
1056 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1057 bail_on_loose,
1058 NULL, NULL, NULL))
1059 return 0;
1061 pack_proc.git_cmd = 1;
1063 strvec_push(&pack_proc.args, "pack-objects");
1064 if (opts->quiet)
1065 strvec_push(&pack_proc.args, "--quiet");
1066 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1068 pack_proc.in = -1;
1070 if (start_command(&pack_proc)) {
1071 error(_("failed to start 'git pack-objects' process"));
1072 return 1;
1075 data.in = xfdopen(pack_proc.in, "w");
1076 data.count = 0;
1077 data.batch_size = 50000;
1079 for_each_loose_file_in_objdir(r->objects->odb->path,
1080 write_loose_object_to_stdin,
1081 NULL,
1082 NULL,
1083 &data);
1085 fclose(data.in);
1087 if (finish_command(&pack_proc)) {
1088 error(_("failed to finish 'git pack-objects' process"));
1089 result = 1;
1092 return result;
1095 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1097 return prune_packed(opts) || pack_loose(opts);
1100 static int incremental_repack_auto_condition(void)
1102 struct packed_git *p;
1103 int incremental_repack_auto_limit = 10;
1104 int count = 0;
1106 prepare_repo_settings(the_repository);
1107 if (!the_repository->settings.core_multi_pack_index)
1108 return 0;
1110 git_config_get_int("maintenance.incremental-repack.auto",
1111 &incremental_repack_auto_limit);
1113 if (!incremental_repack_auto_limit)
1114 return 0;
1115 if (incremental_repack_auto_limit < 0)
1116 return 1;
1118 for (p = get_packed_git(the_repository);
1119 count < incremental_repack_auto_limit && p;
1120 p = p->next) {
1121 if (!p->multi_pack_index)
1122 count++;
1125 return count >= incremental_repack_auto_limit;
1128 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1130 struct child_process child = CHILD_PROCESS_INIT;
1132 child.git_cmd = 1;
1133 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1135 if (opts->quiet)
1136 strvec_push(&child.args, "--no-progress");
1138 if (run_command(&child))
1139 return error(_("failed to write multi-pack-index"));
1141 return 0;
1144 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1146 struct child_process child = CHILD_PROCESS_INIT;
1148 child.git_cmd = child.close_object_store = 1;
1149 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1151 if (opts->quiet)
1152 strvec_push(&child.args, "--no-progress");
1154 if (run_command(&child))
1155 return error(_("'git multi-pack-index expire' failed"));
1157 return 0;
1160 #define TWO_GIGABYTES (INT32_MAX)
1162 static off_t get_auto_pack_size(void)
1165 * The "auto" value is special: we optimize for
1166 * one large pack-file (i.e. from a clone) and
1167 * expect the rest to be small and they can be
1168 * repacked quickly.
1170 * The strategy we select here is to select a
1171 * size that is one more than the second largest
1172 * pack-file. This ensures that we will repack
1173 * at least two packs if there are three or more
1174 * packs.
1176 off_t max_size = 0;
1177 off_t second_largest_size = 0;
1178 off_t result_size;
1179 struct packed_git *p;
1180 struct repository *r = the_repository;
1182 reprepare_packed_git(r);
1183 for (p = get_all_packs(r); p; p = p->next) {
1184 if (p->pack_size > max_size) {
1185 second_largest_size = max_size;
1186 max_size = p->pack_size;
1187 } else if (p->pack_size > second_largest_size)
1188 second_largest_size = p->pack_size;
1191 result_size = second_largest_size + 1;
1193 /* But limit ourselves to a batch size of 2g */
1194 if (result_size > TWO_GIGABYTES)
1195 result_size = TWO_GIGABYTES;
1197 return result_size;
1200 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1202 struct child_process child = CHILD_PROCESS_INIT;
1204 child.git_cmd = child.close_object_store = 1;
1205 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1207 if (opts->quiet)
1208 strvec_push(&child.args, "--no-progress");
1210 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1211 (uintmax_t)get_auto_pack_size());
1213 if (run_command(&child))
1214 return error(_("'git multi-pack-index repack' failed"));
1216 return 0;
1219 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1221 prepare_repo_settings(the_repository);
1222 if (!the_repository->settings.core_multi_pack_index) {
1223 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1224 return 0;
1227 if (multi_pack_index_write(opts))
1228 return 1;
1229 if (multi_pack_index_expire(opts))
1230 return 1;
1231 if (multi_pack_index_repack(opts))
1232 return 1;
1233 return 0;
1236 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1239 * An auto condition function returns 1 if the task should run
1240 * and 0 if the task should NOT run. See needs_to_gc() for an
1241 * example.
1243 typedef int maintenance_auto_fn(void);
1245 struct maintenance_task {
1246 const char *name;
1247 maintenance_task_fn *fn;
1248 maintenance_auto_fn *auto_condition;
1249 unsigned enabled:1;
1251 enum schedule_priority schedule;
1253 /* -1 if not selected. */
1254 int selected_order;
1257 enum maintenance_task_label {
1258 TASK_PREFETCH,
1259 TASK_LOOSE_OBJECTS,
1260 TASK_INCREMENTAL_REPACK,
1261 TASK_GC,
1262 TASK_COMMIT_GRAPH,
1263 TASK_PACK_REFS,
1265 /* Leave as final value */
1266 TASK__COUNT
1269 static struct maintenance_task tasks[] = {
1270 [TASK_PREFETCH] = {
1271 "prefetch",
1272 maintenance_task_prefetch,
1274 [TASK_LOOSE_OBJECTS] = {
1275 "loose-objects",
1276 maintenance_task_loose_objects,
1277 loose_object_auto_condition,
1279 [TASK_INCREMENTAL_REPACK] = {
1280 "incremental-repack",
1281 maintenance_task_incremental_repack,
1282 incremental_repack_auto_condition,
1284 [TASK_GC] = {
1285 "gc",
1286 maintenance_task_gc,
1287 need_to_gc,
1290 [TASK_COMMIT_GRAPH] = {
1291 "commit-graph",
1292 maintenance_task_commit_graph,
1293 should_write_commit_graph,
1295 [TASK_PACK_REFS] = {
1296 "pack-refs",
1297 maintenance_task_pack_refs,
1298 NULL,
1302 static int compare_tasks_by_selection(const void *a_, const void *b_)
1304 const struct maintenance_task *a = a_;
1305 const struct maintenance_task *b = b_;
1307 return b->selected_order - a->selected_order;
1310 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1312 int i, found_selected = 0;
1313 int result = 0;
1314 struct lock_file lk;
1315 struct repository *r = the_repository;
1316 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1318 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1320 * Another maintenance command is running.
1322 * If --auto was provided, then it is likely due to a
1323 * recursive process stack. Do not report an error in
1324 * that case.
1326 if (!opts->auto_flag && !opts->quiet)
1327 warning(_("lock file '%s' exists, skipping maintenance"),
1328 lock_path);
1329 free(lock_path);
1330 return 0;
1332 free(lock_path);
1334 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1335 found_selected = tasks[i].selected_order >= 0;
1337 if (found_selected)
1338 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1340 for (i = 0; i < TASK__COUNT; i++) {
1341 if (found_selected && tasks[i].selected_order < 0)
1342 continue;
1344 if (!found_selected && !tasks[i].enabled)
1345 continue;
1347 if (opts->auto_flag &&
1348 (!tasks[i].auto_condition ||
1349 !tasks[i].auto_condition()))
1350 continue;
1352 if (opts->schedule && tasks[i].schedule < opts->schedule)
1353 continue;
1355 trace2_region_enter("maintenance", tasks[i].name, r);
1356 if (tasks[i].fn(opts)) {
1357 error(_("task '%s' failed"), tasks[i].name);
1358 result = 1;
1360 trace2_region_leave("maintenance", tasks[i].name, r);
1363 rollback_lock_file(&lk);
1364 return result;
1367 static void initialize_maintenance_strategy(void)
1369 char *config_str;
1371 if (git_config_get_string("maintenance.strategy", &config_str))
1372 return;
1374 if (!strcasecmp(config_str, "incremental")) {
1375 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1376 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1377 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1378 tasks[TASK_PREFETCH].enabled = 1;
1379 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1380 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1381 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1382 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1383 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1384 tasks[TASK_PACK_REFS].enabled = 1;
1385 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1389 static void initialize_task_config(int schedule)
1391 int i;
1392 struct strbuf config_name = STRBUF_INIT;
1393 gc_config();
1395 if (schedule)
1396 initialize_maintenance_strategy();
1398 for (i = 0; i < TASK__COUNT; i++) {
1399 int config_value;
1400 char *config_str;
1402 strbuf_reset(&config_name);
1403 strbuf_addf(&config_name, "maintenance.%s.enabled",
1404 tasks[i].name);
1406 if (!git_config_get_bool(config_name.buf, &config_value))
1407 tasks[i].enabled = config_value;
1409 strbuf_reset(&config_name);
1410 strbuf_addf(&config_name, "maintenance.%s.schedule",
1411 tasks[i].name);
1413 if (!git_config_get_string(config_name.buf, &config_str)) {
1414 tasks[i].schedule = parse_schedule(config_str);
1415 free(config_str);
1419 strbuf_release(&config_name);
1422 static int task_option_parse(const struct option *opt UNUSED,
1423 const char *arg, int unset)
1425 int i, num_selected = 0;
1426 struct maintenance_task *task = NULL;
1428 BUG_ON_OPT_NEG(unset);
1430 for (i = 0; i < TASK__COUNT; i++) {
1431 if (tasks[i].selected_order >= 0)
1432 num_selected++;
1433 if (!strcasecmp(tasks[i].name, arg)) {
1434 task = &tasks[i];
1438 if (!task) {
1439 error(_("'%s' is not a valid task"), arg);
1440 return 1;
1443 if (task->selected_order >= 0) {
1444 error(_("task '%s' cannot be selected multiple times"), arg);
1445 return 1;
1448 task->selected_order = num_selected + 1;
1450 return 0;
1453 static int maintenance_run(int argc, const char **argv, const char *prefix)
1455 int i;
1456 struct maintenance_run_opts opts;
1457 struct option builtin_maintenance_run_options[] = {
1458 OPT_BOOL(0, "auto", &opts.auto_flag,
1459 N_("run tasks based on the state of the repository")),
1460 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1461 N_("run tasks based on frequency"),
1462 maintenance_opt_schedule),
1463 OPT_BOOL(0, "quiet", &opts.quiet,
1464 N_("do not report progress or other information over stderr")),
1465 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1466 N_("run a specific task"),
1467 PARSE_OPT_NONEG, task_option_parse),
1468 OPT_END()
1470 memset(&opts, 0, sizeof(opts));
1472 opts.quiet = !isatty(2);
1474 for (i = 0; i < TASK__COUNT; i++)
1475 tasks[i].selected_order = -1;
1477 argc = parse_options(argc, argv, prefix,
1478 builtin_maintenance_run_options,
1479 builtin_maintenance_run_usage,
1480 PARSE_OPT_STOP_AT_NON_OPTION);
1482 if (opts.auto_flag && opts.schedule)
1483 die(_("use at most one of --auto and --schedule=<frequency>"));
1485 initialize_task_config(opts.schedule);
1487 if (argc != 0)
1488 usage_with_options(builtin_maintenance_run_usage,
1489 builtin_maintenance_run_options);
1490 return maintenance_run_tasks(&opts);
1493 static char *get_maintpath(void)
1495 struct strbuf sb = STRBUF_INIT;
1496 const char *p = the_repository->worktree ?
1497 the_repository->worktree : the_repository->gitdir;
1499 strbuf_realpath(&sb, p, 1);
1500 return strbuf_detach(&sb, NULL);
1503 static char const * const builtin_maintenance_register_usage[] = {
1504 "git maintenance register [--config-file <path>]",
1505 NULL
1508 static int maintenance_register(int argc, const char **argv, const char *prefix)
1510 char *config_file = NULL;
1511 struct option options[] = {
1512 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1513 OPT_END(),
1515 int found = 0;
1516 const char *key = "maintenance.repo";
1517 char *maintpath = get_maintpath();
1518 struct string_list_item *item;
1519 const struct string_list *list;
1521 argc = parse_options(argc, argv, prefix, options,
1522 builtin_maintenance_register_usage, 0);
1523 if (argc)
1524 usage_with_options(builtin_maintenance_register_usage,
1525 options);
1527 /* Disable foreground maintenance */
1528 git_config_set("maintenance.auto", "false");
1530 /* Set maintenance strategy, if unset */
1531 if (git_config_get("maintenance.strategy"))
1532 git_config_set("maintenance.strategy", "incremental");
1534 if (!git_config_get_string_multi(key, &list)) {
1535 for_each_string_list_item(item, list) {
1536 if (!strcmp(maintpath, item->string)) {
1537 found = 1;
1538 break;
1543 if (!found) {
1544 int rc;
1545 char *global_config_file = NULL;
1547 if (!config_file) {
1548 global_config_file = git_global_config();
1549 config_file = global_config_file;
1551 if (!config_file)
1552 die(_("$HOME not set"));
1553 rc = git_config_set_multivar_in_file_gently(
1554 config_file, "maintenance.repo", maintpath,
1555 CONFIG_REGEX_NONE, 0);
1556 free(global_config_file);
1558 if (rc)
1559 die(_("unable to add '%s' value of '%s'"),
1560 key, maintpath);
1563 free(maintpath);
1564 return 0;
1567 static char const * const builtin_maintenance_unregister_usage[] = {
1568 "git maintenance unregister [--config-file <path>] [--force]",
1569 NULL
1572 static int maintenance_unregister(int argc, const char **argv, const char *prefix)
1574 int force = 0;
1575 char *config_file = NULL;
1576 struct option options[] = {
1577 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1578 OPT__FORCE(&force,
1579 N_("return success even if repository was not registered"),
1580 PARSE_OPT_NOCOMPLETE),
1581 OPT_END(),
1583 const char *key = "maintenance.repo";
1584 char *maintpath = get_maintpath();
1585 int found = 0;
1586 struct string_list_item *item;
1587 const struct string_list *list;
1588 struct config_set cs = { { 0 } };
1590 argc = parse_options(argc, argv, prefix, options,
1591 builtin_maintenance_unregister_usage, 0);
1592 if (argc)
1593 usage_with_options(builtin_maintenance_unregister_usage,
1594 options);
1596 if (config_file) {
1597 git_configset_init(&cs);
1598 git_configset_add_file(&cs, config_file);
1600 if (!(config_file
1601 ? git_configset_get_string_multi(&cs, key, &list)
1602 : git_config_get_string_multi(key, &list))) {
1603 for_each_string_list_item(item, list) {
1604 if (!strcmp(maintpath, item->string)) {
1605 found = 1;
1606 break;
1611 if (found) {
1612 int rc;
1613 char *global_config_file = NULL;
1615 if (!config_file) {
1616 global_config_file = git_global_config();
1617 config_file = global_config_file;
1619 if (!config_file)
1620 die(_("$HOME not set"));
1621 rc = git_config_set_multivar_in_file_gently(
1622 config_file, key, NULL, maintpath,
1623 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
1624 free(global_config_file);
1626 if (rc &&
1627 (!force || rc == CONFIG_NOTHING_SET))
1628 die(_("unable to unset '%s' value of '%s'"),
1629 key, maintpath);
1630 } else if (!force) {
1631 die(_("repository '%s' is not registered"), maintpath);
1634 git_configset_clear(&cs);
1635 free(maintpath);
1636 return 0;
1639 static const char *get_frequency(enum schedule_priority schedule)
1641 switch (schedule) {
1642 case SCHEDULE_HOURLY:
1643 return "hourly";
1644 case SCHEDULE_DAILY:
1645 return "daily";
1646 case SCHEDULE_WEEKLY:
1647 return "weekly";
1648 default:
1649 BUG("invalid schedule %d", schedule);
1654 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1655 * to mock the schedulers that `git maintenance start` rely on.
1657 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1658 * list of colon-separated key/value pairs where each pair contains a scheduler
1659 * and its corresponding mock.
1661 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1662 * arguments unmodified.
1664 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1665 * In this case, the *cmd value is read as input.
1667 * * if the input value *cmd is the key of one of the comma-separated list
1668 * item, then *is_available is set to true and *cmd is modified and becomes
1669 * the mock command.
1671 * * if the input value *cmd isn’t the key of any of the comma-separated list
1672 * item, then *is_available is set to false.
1674 * Ex.:
1675 * GIT_TEST_MAINT_SCHEDULER not set
1676 * +-------+-------------------------------------------------+
1677 * | Input | Output |
1678 * | *cmd | return code | *cmd | *is_available |
1679 * +-------+-------------+-------------------+---------------+
1680 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1681 * +-------+-------------+-------------------+---------------+
1683 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1684 * +-------+-------------------------------------------------+
1685 * | Input | Output |
1686 * | *cmd | return code | *cmd | *is_available |
1687 * +-------+-------------+-------------------+---------------+
1688 * | "foo" | true | "./mock.foo.sh" | true |
1689 * | "qux" | true | "qux" (unchanged) | false |
1690 * +-------+-------------+-------------------+---------------+
1692 static int get_schedule_cmd(const char **cmd, int *is_available)
1694 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1695 struct string_list_item *item;
1696 struct string_list list = STRING_LIST_INIT_NODUP;
1698 if (!testing)
1699 return 0;
1701 if (is_available)
1702 *is_available = 0;
1704 string_list_split_in_place(&list, testing, ",", -1);
1705 for_each_string_list_item(item, &list) {
1706 struct string_list pair = STRING_LIST_INIT_NODUP;
1708 if (string_list_split_in_place(&pair, item->string, ":", 2) != 2)
1709 continue;
1711 if (!strcmp(*cmd, pair.items[0].string)) {
1712 *cmd = pair.items[1].string;
1713 if (is_available)
1714 *is_available = 1;
1715 string_list_clear(&list, 0);
1716 UNLEAK(testing);
1717 return 1;
1721 string_list_clear(&list, 0);
1722 free(testing);
1723 return 1;
1726 static int get_random_minute(void)
1728 /* Use a static value when under tests. */
1729 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
1730 return 13;
1732 return git_rand() % 60;
1735 static int is_launchctl_available(void)
1737 const char *cmd = "launchctl";
1738 int is_available;
1739 if (get_schedule_cmd(&cmd, &is_available))
1740 return is_available;
1742 #ifdef __APPLE__
1743 return 1;
1744 #else
1745 return 0;
1746 #endif
1749 static char *launchctl_service_name(const char *frequency)
1751 struct strbuf label = STRBUF_INIT;
1752 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1753 return strbuf_detach(&label, NULL);
1756 static char *launchctl_service_filename(const char *name)
1758 char *expanded;
1759 struct strbuf filename = STRBUF_INIT;
1760 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1762 expanded = interpolate_path(filename.buf, 1);
1763 if (!expanded)
1764 die(_("failed to expand path '%s'"), filename.buf);
1766 strbuf_release(&filename);
1767 return expanded;
1770 static char *launchctl_get_uid(void)
1772 return xstrfmt("gui/%d", getuid());
1775 static int launchctl_boot_plist(int enable, const char *filename)
1777 const char *cmd = "launchctl";
1778 int result;
1779 struct child_process child = CHILD_PROCESS_INIT;
1780 char *uid = launchctl_get_uid();
1782 get_schedule_cmd(&cmd, NULL);
1783 strvec_split(&child.args, cmd);
1784 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1785 filename, NULL);
1787 child.no_stderr = 1;
1788 child.no_stdout = 1;
1790 if (start_command(&child))
1791 die(_("failed to start launchctl"));
1793 result = finish_command(&child);
1795 free(uid);
1796 return result;
1799 static int launchctl_remove_plist(enum schedule_priority schedule)
1801 const char *frequency = get_frequency(schedule);
1802 char *name = launchctl_service_name(frequency);
1803 char *filename = launchctl_service_filename(name);
1804 int result = launchctl_boot_plist(0, filename);
1805 unlink(filename);
1806 free(filename);
1807 free(name);
1808 return result;
1811 static int launchctl_remove_plists(void)
1813 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1814 launchctl_remove_plist(SCHEDULE_DAILY) ||
1815 launchctl_remove_plist(SCHEDULE_WEEKLY);
1818 static int launchctl_list_contains_plist(const char *name, const char *cmd)
1820 struct child_process child = CHILD_PROCESS_INIT;
1822 strvec_split(&child.args, cmd);
1823 strvec_pushl(&child.args, "list", name, NULL);
1825 child.no_stderr = 1;
1826 child.no_stdout = 1;
1828 if (start_command(&child))
1829 die(_("failed to start launchctl"));
1831 /* Returns failure if 'name' doesn't exist. */
1832 return !finish_command(&child);
1835 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1837 int i, fd;
1838 const char *preamble, *repeat;
1839 const char *frequency = get_frequency(schedule);
1840 char *name = launchctl_service_name(frequency);
1841 char *filename = launchctl_service_filename(name);
1842 struct lock_file lk = LOCK_INIT;
1843 static unsigned long lock_file_timeout_ms = ULONG_MAX;
1844 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
1845 struct stat st;
1846 const char *cmd = "launchctl";
1847 int minute = get_random_minute();
1849 get_schedule_cmd(&cmd, NULL);
1850 preamble = "<?xml version=\"1.0\"?>\n"
1851 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1852 "<plist version=\"1.0\">"
1853 "<dict>\n"
1854 "<key>Label</key><string>%s</string>\n"
1855 "<key>ProgramArguments</key>\n"
1856 "<array>\n"
1857 "<string>%s/git</string>\n"
1858 "<string>--exec-path=%s</string>\n"
1859 "<string>for-each-repo</string>\n"
1860 "<string>--config=maintenance.repo</string>\n"
1861 "<string>maintenance</string>\n"
1862 "<string>run</string>\n"
1863 "<string>--schedule=%s</string>\n"
1864 "</array>\n"
1865 "<key>StartCalendarInterval</key>\n"
1866 "<array>\n";
1867 strbuf_addf(&plist, preamble, name, exec_path, exec_path, frequency);
1869 switch (schedule) {
1870 case SCHEDULE_HOURLY:
1871 repeat = "<dict>\n"
1872 "<key>Hour</key><integer>%d</integer>\n"
1873 "<key>Minute</key><integer>%d</integer>\n"
1874 "</dict>\n";
1875 for (i = 1; i <= 23; i++)
1876 strbuf_addf(&plist, repeat, i, minute);
1877 break;
1879 case SCHEDULE_DAILY:
1880 repeat = "<dict>\n"
1881 "<key>Day</key><integer>%d</integer>\n"
1882 "<key>Hour</key><integer>0</integer>\n"
1883 "<key>Minute</key><integer>%d</integer>\n"
1884 "</dict>\n";
1885 for (i = 1; i <= 6; i++)
1886 strbuf_addf(&plist, repeat, i, minute);
1887 break;
1889 case SCHEDULE_WEEKLY:
1890 strbuf_addf(&plist,
1891 "<dict>\n"
1892 "<key>Day</key><integer>0</integer>\n"
1893 "<key>Hour</key><integer>0</integer>\n"
1894 "<key>Minute</key><integer>%d</integer>\n"
1895 "</dict>\n",
1896 minute);
1897 break;
1899 default:
1900 /* unreachable */
1901 break;
1903 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
1905 if (safe_create_leading_directories(filename))
1906 die(_("failed to create directories for '%s'"), filename);
1908 if ((long)lock_file_timeout_ms < 0 &&
1909 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1910 &lock_file_timeout_ms))
1911 lock_file_timeout_ms = 150;
1913 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
1914 lock_file_timeout_ms);
1917 * Does this file already exist? With the intended contents? Is it
1918 * registered already? Then it does not need to be re-registered.
1920 if (!stat(filename, &st) && st.st_size == plist.len &&
1921 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
1922 !strbuf_cmp(&plist, &plist2) &&
1923 launchctl_list_contains_plist(name, cmd))
1924 rollback_lock_file(&lk);
1925 else {
1926 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
1927 commit_lock_file(&lk))
1928 die_errno(_("could not write '%s'"), filename);
1930 /* bootout might fail if not already running, so ignore */
1931 launchctl_boot_plist(0, filename);
1932 if (launchctl_boot_plist(1, filename))
1933 die(_("failed to bootstrap service %s"), filename);
1936 free(filename);
1937 free(name);
1938 strbuf_release(&plist);
1939 strbuf_release(&plist2);
1940 return 0;
1943 static int launchctl_add_plists(void)
1945 const char *exec_path = git_exec_path();
1947 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1948 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1949 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1952 static int launchctl_update_schedule(int run_maintenance, int fd UNUSED)
1954 if (run_maintenance)
1955 return launchctl_add_plists();
1956 else
1957 return launchctl_remove_plists();
1960 static int is_schtasks_available(void)
1962 const char *cmd = "schtasks";
1963 int is_available;
1964 if (get_schedule_cmd(&cmd, &is_available))
1965 return is_available;
1967 #ifdef GIT_WINDOWS_NATIVE
1968 return 1;
1969 #else
1970 return 0;
1971 #endif
1974 static char *schtasks_task_name(const char *frequency)
1976 struct strbuf label = STRBUF_INIT;
1977 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1978 return strbuf_detach(&label, NULL);
1981 static int schtasks_remove_task(enum schedule_priority schedule)
1983 const char *cmd = "schtasks";
1984 struct child_process child = CHILD_PROCESS_INIT;
1985 const char *frequency = get_frequency(schedule);
1986 char *name = schtasks_task_name(frequency);
1988 get_schedule_cmd(&cmd, NULL);
1989 strvec_split(&child.args, cmd);
1990 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
1991 free(name);
1993 return run_command(&child);
1996 static int schtasks_remove_tasks(void)
1998 return schtasks_remove_task(SCHEDULE_HOURLY) ||
1999 schtasks_remove_task(SCHEDULE_DAILY) ||
2000 schtasks_remove_task(SCHEDULE_WEEKLY);
2003 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
2005 const char *cmd = "schtasks";
2006 int result;
2007 struct child_process child = CHILD_PROCESS_INIT;
2008 const char *xml;
2009 struct tempfile *tfile;
2010 const char *frequency = get_frequency(schedule);
2011 char *name = schtasks_task_name(frequency);
2012 struct strbuf tfilename = STRBUF_INIT;
2013 int minute = get_random_minute();
2015 get_schedule_cmd(&cmd, NULL);
2017 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
2018 get_git_common_dir(), frequency);
2019 tfile = xmks_tempfile(tfilename.buf);
2020 strbuf_release(&tfilename);
2022 if (!fdopen_tempfile(tfile, "w"))
2023 die(_("failed to create temp xml file"));
2025 xml = "<?xml version=\"1.0\" ?>\n"
2026 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2027 "<Triggers>\n"
2028 "<CalendarTrigger>\n";
2029 fputs(xml, tfile->fp);
2031 switch (schedule) {
2032 case SCHEDULE_HOURLY:
2033 fprintf(tfile->fp,
2034 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2035 "<Enabled>true</Enabled>\n"
2036 "<ScheduleByDay>\n"
2037 "<DaysInterval>1</DaysInterval>\n"
2038 "</ScheduleByDay>\n"
2039 "<Repetition>\n"
2040 "<Interval>PT1H</Interval>\n"
2041 "<Duration>PT23H</Duration>\n"
2042 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2043 "</Repetition>\n",
2044 minute);
2045 break;
2047 case SCHEDULE_DAILY:
2048 fprintf(tfile->fp,
2049 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2050 "<Enabled>true</Enabled>\n"
2051 "<ScheduleByWeek>\n"
2052 "<DaysOfWeek>\n"
2053 "<Monday />\n"
2054 "<Tuesday />\n"
2055 "<Wednesday />\n"
2056 "<Thursday />\n"
2057 "<Friday />\n"
2058 "<Saturday />\n"
2059 "</DaysOfWeek>\n"
2060 "<WeeksInterval>1</WeeksInterval>\n"
2061 "</ScheduleByWeek>\n",
2062 minute);
2063 break;
2065 case SCHEDULE_WEEKLY:
2066 fprintf(tfile->fp,
2067 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2068 "<Enabled>true</Enabled>\n"
2069 "<ScheduleByWeek>\n"
2070 "<DaysOfWeek>\n"
2071 "<Sunday />\n"
2072 "</DaysOfWeek>\n"
2073 "<WeeksInterval>1</WeeksInterval>\n"
2074 "</ScheduleByWeek>\n",
2075 minute);
2076 break;
2078 default:
2079 break;
2082 xml = "</CalendarTrigger>\n"
2083 "</Triggers>\n"
2084 "<Principals>\n"
2085 "<Principal id=\"Author\">\n"
2086 "<LogonType>InteractiveToken</LogonType>\n"
2087 "<RunLevel>LeastPrivilege</RunLevel>\n"
2088 "</Principal>\n"
2089 "</Principals>\n"
2090 "<Settings>\n"
2091 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2092 "<Enabled>true</Enabled>\n"
2093 "<Hidden>true</Hidden>\n"
2094 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2095 "<WakeToRun>false</WakeToRun>\n"
2096 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2097 "<Priority>7</Priority>\n"
2098 "</Settings>\n"
2099 "<Actions Context=\"Author\">\n"
2100 "<Exec>\n"
2101 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2102 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2103 "</Exec>\n"
2104 "</Actions>\n"
2105 "</Task>\n";
2106 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
2107 strvec_split(&child.args, cmd);
2108 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2109 get_tempfile_path(tfile), NULL);
2110 close_tempfile_gently(tfile);
2112 child.no_stdout = 1;
2113 child.no_stderr = 1;
2115 if (start_command(&child))
2116 die(_("failed to start schtasks"));
2117 result = finish_command(&child);
2119 delete_tempfile(&tfile);
2120 free(name);
2121 return result;
2124 static int schtasks_schedule_tasks(void)
2126 const char *exec_path = git_exec_path();
2128 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2129 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2130 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
2133 static int schtasks_update_schedule(int run_maintenance, int fd UNUSED)
2135 if (run_maintenance)
2136 return schtasks_schedule_tasks();
2137 else
2138 return schtasks_remove_tasks();
2141 MAYBE_UNUSED
2142 static int check_crontab_process(const char *cmd)
2144 struct child_process child = CHILD_PROCESS_INIT;
2146 strvec_split(&child.args, cmd);
2147 strvec_push(&child.args, "-l");
2148 child.no_stdin = 1;
2149 child.no_stdout = 1;
2150 child.no_stderr = 1;
2151 child.silent_exec_failure = 1;
2153 if (start_command(&child))
2154 return 0;
2155 /* Ignore exit code, as an empty crontab will return error. */
2156 finish_command(&child);
2157 return 1;
2160 static int is_crontab_available(void)
2162 const char *cmd = "crontab";
2163 int is_available;
2165 if (get_schedule_cmd(&cmd, &is_available))
2166 return is_available;
2168 #ifdef __APPLE__
2170 * macOS has cron, but it requires special permissions and will
2171 * create a UI alert when attempting to run this command.
2173 return 0;
2174 #else
2175 return check_crontab_process(cmd);
2176 #endif
2179 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2180 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2182 static int crontab_update_schedule(int run_maintenance, int fd)
2184 const char *cmd = "crontab";
2185 int result = 0;
2186 int in_old_region = 0;
2187 struct child_process crontab_list = CHILD_PROCESS_INIT;
2188 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2189 FILE *cron_list, *cron_in;
2190 struct strbuf line = STRBUF_INIT;
2191 struct tempfile *tmpedit = NULL;
2192 int minute = get_random_minute();
2194 get_schedule_cmd(&cmd, NULL);
2195 strvec_split(&crontab_list.args, cmd);
2196 strvec_push(&crontab_list.args, "-l");
2197 crontab_list.in = -1;
2198 crontab_list.out = dup(fd);
2199 crontab_list.git_cmd = 0;
2201 if (start_command(&crontab_list))
2202 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2204 /* Ignore exit code, as an empty crontab will return error. */
2205 finish_command(&crontab_list);
2207 tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2208 if (!tmpedit) {
2209 result = error(_("failed to create crontab temporary file"));
2210 goto out;
2212 cron_in = fdopen_tempfile(tmpedit, "w");
2213 if (!cron_in) {
2214 result = error(_("failed to open temporary file"));
2215 goto out;
2219 * Read from the .lock file, filtering out the old
2220 * schedule while appending the new schedule.
2222 cron_list = fdopen(fd, "r");
2223 rewind(cron_list);
2225 while (!strbuf_getline_lf(&line, cron_list)) {
2226 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2227 in_old_region = 1;
2228 else if (in_old_region && !strcmp(line.buf, END_LINE))
2229 in_old_region = 0;
2230 else if (!in_old_region)
2231 fprintf(cron_in, "%s\n", line.buf);
2233 strbuf_release(&line);
2235 if (run_maintenance) {
2236 struct strbuf line_format = STRBUF_INIT;
2237 const char *exec_path = git_exec_path();
2239 fprintf(cron_in, "%s\n", BEGIN_LINE);
2240 fprintf(cron_in,
2241 "# The following schedule was created by Git\n");
2242 fprintf(cron_in, "# Any edits made in this region might be\n");
2243 fprintf(cron_in,
2244 "# replaced in the future by a Git command.\n\n");
2246 strbuf_addf(&line_format,
2247 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2248 exec_path, exec_path);
2249 fprintf(cron_in, line_format.buf, minute, "1-23", "*", "hourly");
2250 fprintf(cron_in, line_format.buf, minute, "0", "1-6", "daily");
2251 fprintf(cron_in, line_format.buf, minute, "0", "0", "weekly");
2252 strbuf_release(&line_format);
2254 fprintf(cron_in, "\n%s\n", END_LINE);
2257 fflush(cron_in);
2259 strvec_split(&crontab_edit.args, cmd);
2260 strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2261 crontab_edit.git_cmd = 0;
2263 if (start_command(&crontab_edit)) {
2264 result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2265 goto out;
2268 if (finish_command(&crontab_edit))
2269 result = error(_("'crontab' died"));
2270 else
2271 fclose(cron_list);
2272 out:
2273 delete_tempfile(&tmpedit);
2274 return result;
2277 static int real_is_systemd_timer_available(void)
2279 struct child_process child = CHILD_PROCESS_INIT;
2281 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2282 child.no_stdin = 1;
2283 child.no_stdout = 1;
2284 child.no_stderr = 1;
2285 child.silent_exec_failure = 1;
2287 if (start_command(&child))
2288 return 0;
2289 if (finish_command(&child))
2290 return 0;
2291 return 1;
2294 static int is_systemd_timer_available(void)
2296 const char *cmd = "systemctl";
2297 int is_available;
2299 if (get_schedule_cmd(&cmd, &is_available))
2300 return is_available;
2302 return real_is_systemd_timer_available();
2305 static char *xdg_config_home_systemd(const char *filename)
2307 return xdg_config_home_for("systemd/user", filename);
2310 #define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2312 static int systemd_timer_delete_timer_file(enum schedule_priority priority)
2314 int ret = 0;
2315 const char *frequency = get_frequency(priority);
2316 char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2317 char *filename = xdg_config_home_systemd(local_timer_name);
2319 if (unlink(filename) && !is_missing_file_error(errno))
2320 ret = error_errno(_("failed to delete '%s'"), filename);
2322 free(filename);
2323 free(local_timer_name);
2324 return ret;
2327 static int systemd_timer_delete_service_template(void)
2329 int ret = 0;
2330 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2331 char *filename = xdg_config_home_systemd(local_service_name);
2332 if (unlink(filename) && !is_missing_file_error(errno))
2333 ret = error_errno(_("failed to delete '%s'"), filename);
2335 free(filename);
2336 free(local_service_name);
2337 return ret;
2341 * Write the schedule information into a git-maintenance@<schedule>.timer
2342 * file using a custom minute. This timer file cannot use the templating
2343 * system, so we generate a specific file for each.
2345 static int systemd_timer_write_timer_file(enum schedule_priority schedule,
2346 int minute)
2348 int res = -1;
2349 char *filename;
2350 FILE *file;
2351 const char *unit;
2352 char *schedule_pattern = NULL;
2353 const char *frequency = get_frequency(schedule);
2354 char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2356 filename = xdg_config_home_systemd(local_timer_name);
2358 if (safe_create_leading_directories(filename)) {
2359 error(_("failed to create directories for '%s'"), filename);
2360 goto error;
2362 file = fopen_or_warn(filename, "w");
2363 if (!file)
2364 goto error;
2366 switch (schedule) {
2367 case SCHEDULE_HOURLY:
2368 schedule_pattern = xstrfmt("*-*-* 1..23:%02d:00", minute);
2369 break;
2371 case SCHEDULE_DAILY:
2372 schedule_pattern = xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute);
2373 break;
2375 case SCHEDULE_WEEKLY:
2376 schedule_pattern = xstrfmt("Mon 0:%02d:00", minute);
2377 break;
2379 default:
2380 BUG("Unhandled schedule_priority");
2383 unit = "# This file was created and is maintained by Git.\n"
2384 "# Any edits made in this file might be replaced in the future\n"
2385 "# by a Git command.\n"
2386 "\n"
2387 "[Unit]\n"
2388 "Description=Optimize Git repositories data\n"
2389 "\n"
2390 "[Timer]\n"
2391 "OnCalendar=%s\n"
2392 "Persistent=true\n"
2393 "\n"
2394 "[Install]\n"
2395 "WantedBy=timers.target\n";
2396 if (fprintf(file, unit, schedule_pattern) < 0) {
2397 error(_("failed to write to '%s'"), filename);
2398 fclose(file);
2399 goto error;
2401 if (fclose(file) == EOF) {
2402 error_errno(_("failed to flush '%s'"), filename);
2403 goto error;
2406 res = 0;
2408 error:
2409 free(schedule_pattern);
2410 free(local_timer_name);
2411 free(filename);
2412 return res;
2416 * No matter the schedule, we use the same service and can make use of the
2417 * templating system. When installing git-maintenance@<schedule>.timer,
2418 * systemd will notice that git-maintenance@.service exists as a template
2419 * and will use this file and insert the <schedule> into the template at
2420 * the position of "%i".
2422 static int systemd_timer_write_service_template(const char *exec_path)
2424 int res = -1;
2425 char *filename;
2426 FILE *file;
2427 const char *unit;
2428 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2430 filename = xdg_config_home_systemd(local_service_name);
2431 if (safe_create_leading_directories(filename)) {
2432 error(_("failed to create directories for '%s'"), filename);
2433 goto error;
2435 file = fopen_or_warn(filename, "w");
2436 if (!file)
2437 goto error;
2439 unit = "# This file was created and is maintained by Git.\n"
2440 "# Any edits made in this file might be replaced in the future\n"
2441 "# by a Git command.\n"
2442 "\n"
2443 "[Unit]\n"
2444 "Description=Optimize Git repositories data\n"
2445 "\n"
2446 "[Service]\n"
2447 "Type=oneshot\n"
2448 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2449 "LockPersonality=yes\n"
2450 "MemoryDenyWriteExecute=yes\n"
2451 "NoNewPrivileges=yes\n"
2452 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
2453 "RestrictNamespaces=yes\n"
2454 "RestrictRealtime=yes\n"
2455 "RestrictSUIDSGID=yes\n"
2456 "SystemCallArchitectures=native\n"
2457 "SystemCallFilter=@system-service\n";
2458 if (fprintf(file, unit, exec_path, exec_path) < 0) {
2459 error(_("failed to write to '%s'"), filename);
2460 fclose(file);
2461 goto error;
2463 if (fclose(file) == EOF) {
2464 error_errno(_("failed to flush '%s'"), filename);
2465 goto error;
2468 res = 0;
2470 error:
2471 free(local_service_name);
2472 free(filename);
2473 return res;
2476 static int systemd_timer_enable_unit(int enable,
2477 enum schedule_priority schedule,
2478 int minute)
2480 const char *cmd = "systemctl";
2481 struct child_process child = CHILD_PROCESS_INIT;
2482 const char *frequency = get_frequency(schedule);
2485 * Disabling the systemd unit while it is already disabled makes
2486 * systemctl print an error.
2487 * Let's ignore it since it means we already are in the expected state:
2488 * the unit is disabled.
2490 * On the other hand, enabling a systemd unit which is already enabled
2491 * produces no error.
2493 if (!enable)
2494 child.no_stderr = 1;
2495 else if (systemd_timer_write_timer_file(schedule, minute))
2496 return -1;
2498 get_schedule_cmd(&cmd, NULL);
2499 strvec_split(&child.args, cmd);
2500 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2501 "--now", NULL);
2502 strvec_pushf(&child.args, SYSTEMD_UNIT_FORMAT, frequency, "timer");
2504 if (start_command(&child))
2505 return error(_("failed to start systemctl"));
2506 if (finish_command(&child))
2508 * Disabling an already disabled systemd unit makes
2509 * systemctl fail.
2510 * Let's ignore this failure.
2512 * Enabling an enabled systemd unit doesn't fail.
2514 if (enable)
2515 return error(_("failed to run systemctl"));
2516 return 0;
2520 * A previous version of Git wrote the timer units as template files.
2521 * Clean these up, if they exist.
2523 static void systemd_timer_delete_stale_timer_templates(void)
2525 char *timer_template_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "timer");
2526 char *filename = xdg_config_home_systemd(timer_template_name);
2528 if (unlink(filename) && !is_missing_file_error(errno))
2529 warning(_("failed to delete '%s'"), filename);
2531 free(filename);
2532 free(timer_template_name);
2535 static int systemd_timer_delete_unit_files(void)
2537 systemd_timer_delete_stale_timer_templates();
2539 /* Purposefully not short-circuited to make sure all are called. */
2540 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY) |
2541 systemd_timer_delete_timer_file(SCHEDULE_DAILY) |
2542 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY) |
2543 systemd_timer_delete_service_template();
2546 static int systemd_timer_delete_units(void)
2548 int minute = get_random_minute();
2549 /* Purposefully not short-circuited to make sure all are called. */
2550 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY, minute) |
2551 systemd_timer_enable_unit(0, SCHEDULE_DAILY, minute) |
2552 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY, minute) |
2553 systemd_timer_delete_unit_files();
2556 static int systemd_timer_setup_units(void)
2558 int minute = get_random_minute();
2559 const char *exec_path = git_exec_path();
2561 int ret = systemd_timer_write_service_template(exec_path) ||
2562 systemd_timer_enable_unit(1, SCHEDULE_HOURLY, minute) ||
2563 systemd_timer_enable_unit(1, SCHEDULE_DAILY, minute) ||
2564 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY, minute);
2566 if (ret)
2567 systemd_timer_delete_units();
2568 else
2569 systemd_timer_delete_stale_timer_templates();
2571 return ret;
2574 static int systemd_timer_update_schedule(int run_maintenance, int fd UNUSED)
2576 if (run_maintenance)
2577 return systemd_timer_setup_units();
2578 else
2579 return systemd_timer_delete_units();
2582 enum scheduler {
2583 SCHEDULER_INVALID = -1,
2584 SCHEDULER_AUTO,
2585 SCHEDULER_CRON,
2586 SCHEDULER_SYSTEMD,
2587 SCHEDULER_LAUNCHCTL,
2588 SCHEDULER_SCHTASKS,
2591 static const struct {
2592 const char *name;
2593 int (*is_available)(void);
2594 int (*update_schedule)(int run_maintenance, int fd);
2595 } scheduler_fn[] = {
2596 [SCHEDULER_CRON] = {
2597 .name = "crontab",
2598 .is_available = is_crontab_available,
2599 .update_schedule = crontab_update_schedule,
2601 [SCHEDULER_SYSTEMD] = {
2602 .name = "systemctl",
2603 .is_available = is_systemd_timer_available,
2604 .update_schedule = systemd_timer_update_schedule,
2606 [SCHEDULER_LAUNCHCTL] = {
2607 .name = "launchctl",
2608 .is_available = is_launchctl_available,
2609 .update_schedule = launchctl_update_schedule,
2611 [SCHEDULER_SCHTASKS] = {
2612 .name = "schtasks",
2613 .is_available = is_schtasks_available,
2614 .update_schedule = schtasks_update_schedule,
2618 static enum scheduler parse_scheduler(const char *value)
2620 if (!value)
2621 return SCHEDULER_INVALID;
2622 else if (!strcasecmp(value, "auto"))
2623 return SCHEDULER_AUTO;
2624 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2625 return SCHEDULER_CRON;
2626 else if (!strcasecmp(value, "systemd") ||
2627 !strcasecmp(value, "systemd-timer"))
2628 return SCHEDULER_SYSTEMD;
2629 else if (!strcasecmp(value, "launchctl"))
2630 return SCHEDULER_LAUNCHCTL;
2631 else if (!strcasecmp(value, "schtasks"))
2632 return SCHEDULER_SCHTASKS;
2633 else
2634 return SCHEDULER_INVALID;
2637 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2638 int unset)
2640 enum scheduler *scheduler = opt->value;
2642 BUG_ON_OPT_NEG(unset);
2644 *scheduler = parse_scheduler(arg);
2645 if (*scheduler == SCHEDULER_INVALID)
2646 return error(_("unrecognized --scheduler argument '%s'"), arg);
2647 return 0;
2650 struct maintenance_start_opts {
2651 enum scheduler scheduler;
2654 static enum scheduler resolve_scheduler(enum scheduler scheduler)
2656 if (scheduler != SCHEDULER_AUTO)
2657 return scheduler;
2659 #if defined(__APPLE__)
2660 return SCHEDULER_LAUNCHCTL;
2662 #elif defined(GIT_WINDOWS_NATIVE)
2663 return SCHEDULER_SCHTASKS;
2665 #elif defined(__linux__)
2666 if (is_systemd_timer_available())
2667 return SCHEDULER_SYSTEMD;
2668 else if (is_crontab_available())
2669 return SCHEDULER_CRON;
2670 else
2671 die(_("neither systemd timers nor crontab are available"));
2673 #else
2674 return SCHEDULER_CRON;
2675 #endif
2678 static void validate_scheduler(enum scheduler scheduler)
2680 if (scheduler == SCHEDULER_INVALID)
2681 BUG("invalid scheduler");
2682 if (scheduler == SCHEDULER_AUTO)
2683 BUG("resolve_scheduler should have been called before");
2685 if (!scheduler_fn[scheduler].is_available())
2686 die(_("%s scheduler is not available"),
2687 scheduler_fn[scheduler].name);
2690 static int update_background_schedule(const struct maintenance_start_opts *opts,
2691 int enable)
2693 unsigned int i;
2694 int result = 0;
2695 struct lock_file lk;
2696 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2698 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2699 free(lock_path);
2700 return error(_("another process is scheduling background maintenance"));
2703 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2704 if (enable && opts->scheduler == i)
2705 continue;
2706 if (!scheduler_fn[i].is_available())
2707 continue;
2708 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2711 if (enable)
2712 result = scheduler_fn[opts->scheduler].update_schedule(
2713 1, get_lock_file_fd(&lk));
2715 rollback_lock_file(&lk);
2717 free(lock_path);
2718 return result;
2721 static const char *const builtin_maintenance_start_usage[] = {
2722 N_("git maintenance start [--scheduler=<scheduler>]"),
2723 NULL
2726 static int maintenance_start(int argc, const char **argv, const char *prefix)
2728 struct maintenance_start_opts opts = { 0 };
2729 struct option options[] = {
2730 OPT_CALLBACK_F(
2731 0, "scheduler", &opts.scheduler, N_("scheduler"),
2732 N_("scheduler to trigger git maintenance run"),
2733 PARSE_OPT_NONEG, maintenance_opt_scheduler),
2734 OPT_END()
2736 const char *register_args[] = { "register", NULL };
2738 argc = parse_options(argc, argv, prefix, options,
2739 builtin_maintenance_start_usage, 0);
2740 if (argc)
2741 usage_with_options(builtin_maintenance_start_usage, options);
2743 opts.scheduler = resolve_scheduler(opts.scheduler);
2744 validate_scheduler(opts.scheduler);
2746 if (update_background_schedule(&opts, 1))
2747 die(_("failed to set up maintenance schedule"));
2749 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL))
2750 warning(_("failed to add repo to global config"));
2751 return 0;
2754 static const char *const builtin_maintenance_stop_usage[] = {
2755 "git maintenance stop",
2756 NULL
2759 static int maintenance_stop(int argc, const char **argv, const char *prefix)
2761 struct option options[] = {
2762 OPT_END()
2764 argc = parse_options(argc, argv, prefix, options,
2765 builtin_maintenance_stop_usage, 0);
2766 if (argc)
2767 usage_with_options(builtin_maintenance_stop_usage, options);
2768 return update_background_schedule(NULL, 0);
2771 static const char * const builtin_maintenance_usage[] = {
2772 N_("git maintenance <subcommand> [<options>]"),
2773 NULL,
2776 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2778 parse_opt_subcommand_fn *fn = NULL;
2779 struct option builtin_maintenance_options[] = {
2780 OPT_SUBCOMMAND("run", &fn, maintenance_run),
2781 OPT_SUBCOMMAND("start", &fn, maintenance_start),
2782 OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
2783 OPT_SUBCOMMAND("register", &fn, maintenance_register),
2784 OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
2785 OPT_END(),
2788 argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
2789 builtin_maintenance_usage, 0);
2790 return fn(argc, argv, prefix);