replace and remove run_command_v_opt()
[git/debian.git] / builtin / gc.c
blob962bab61f93758528872c9b2edbdda44f2d63956
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 "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 "exec-cmd.h"
34 #include "hook.h"
36 #define FAILED_RUN "failed to run %s"
38 static const char * const builtin_gc_usage[] = {
39 N_("git gc [<options>]"),
40 NULL
43 static int pack_refs = 1;
44 static int prune_reflogs = 1;
45 static int cruft_packs = 0;
46 static int aggressive_depth = 50;
47 static int aggressive_window = 250;
48 static int gc_auto_threshold = 6700;
49 static int gc_auto_pack_limit = 50;
50 static int detach_auto = 1;
51 static timestamp_t gc_log_expire_time;
52 static const char *gc_log_expire = "1.day.ago";
53 static const char *prune_expire = "2.weeks.ago";
54 static const char *prune_worktrees_expire = "3.months.ago";
55 static unsigned long big_pack_threshold;
56 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
58 static struct strvec reflog = STRVEC_INIT;
59 static struct strvec repack = STRVEC_INIT;
60 static struct strvec prune = STRVEC_INIT;
61 static struct strvec prune_worktrees = STRVEC_INIT;
62 static struct strvec rerere = STRVEC_INIT;
64 static struct tempfile *pidfile;
65 static struct lock_file log_lock;
67 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
69 static void clean_pack_garbage(void)
71 int i;
72 for (i = 0; i < pack_garbage.nr; i++)
73 unlink_or_warn(pack_garbage.items[i].string);
74 string_list_clear(&pack_garbage, 0);
77 static void report_pack_garbage(unsigned seen_bits, const char *path)
79 if (seen_bits == PACKDIR_FILE_IDX)
80 string_list_append(&pack_garbage, path);
83 static void process_log_file(void)
85 struct stat st;
86 if (fstat(get_lock_file_fd(&log_lock), &st)) {
88 * Perhaps there was an i/o error or another
89 * unlikely situation. Try to make a note of
90 * this in gc.log along with any existing
91 * messages.
93 int saved_errno = errno;
94 fprintf(stderr, _("Failed to fstat %s: %s"),
95 get_lock_file_path(&log_lock),
96 strerror(saved_errno));
97 fflush(stderr);
98 commit_lock_file(&log_lock);
99 errno = saved_errno;
100 } else if (st.st_size) {
101 /* There was some error recorded in the lock file */
102 commit_lock_file(&log_lock);
103 } else {
104 /* No error, clean up any old gc.log */
105 unlink(git_path("gc.log"));
106 rollback_lock_file(&log_lock);
110 static void process_log_file_at_exit(void)
112 fflush(stderr);
113 process_log_file();
116 static void process_log_file_on_signal(int signo)
118 process_log_file();
119 sigchain_pop(signo);
120 raise(signo);
123 static int gc_config_is_timestamp_never(const char *var)
125 const char *value;
126 timestamp_t expire;
128 if (!git_config_get_value(var, &value) && value) {
129 if (parse_expiry_date(value, &expire))
130 die(_("failed to parse '%s' value '%s'"), var, value);
131 return expire == 0;
133 return 0;
136 static void gc_config(void)
138 const char *value;
140 if (!git_config_get_value("gc.packrefs", &value)) {
141 if (value && !strcmp(value, "notbare"))
142 pack_refs = -1;
143 else
144 pack_refs = git_config_bool("gc.packrefs", value);
147 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
148 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
149 prune_reflogs = 0;
151 git_config_get_int("gc.aggressivewindow", &aggressive_window);
152 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
153 git_config_get_int("gc.auto", &gc_auto_threshold);
154 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
155 git_config_get_bool("gc.autodetach", &detach_auto);
156 git_config_get_bool("gc.cruftpacks", &cruft_packs);
157 git_config_get_expiry("gc.pruneexpire", &prune_expire);
158 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
159 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
161 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
162 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
164 git_config(git_default_config, NULL);
167 struct maintenance_run_opts;
168 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
170 struct child_process cmd = CHILD_PROCESS_INIT;
172 cmd.git_cmd = 1;
173 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
174 return run_command(&cmd);
177 static int too_many_loose_objects(void)
180 * Quickly check if a "gc" is needed, by estimating how
181 * many loose objects there are. Because SHA-1 is evenly
182 * distributed, we can check only one and get a reasonable
183 * estimate.
185 DIR *dir;
186 struct dirent *ent;
187 int auto_threshold;
188 int num_loose = 0;
189 int needed = 0;
190 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
192 dir = opendir(git_path("objects/17"));
193 if (!dir)
194 return 0;
196 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
197 while ((ent = readdir(dir)) != NULL) {
198 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
199 ent->d_name[hexsz_loose] != '\0')
200 continue;
201 if (++num_loose > auto_threshold) {
202 needed = 1;
203 break;
206 closedir(dir);
207 return needed;
210 static struct packed_git *find_base_packs(struct string_list *packs,
211 unsigned long limit)
213 struct packed_git *p, *base = NULL;
215 for (p = get_all_packs(the_repository); p; p = p->next) {
216 if (!p->pack_local)
217 continue;
218 if (limit) {
219 if (p->pack_size >= limit)
220 string_list_append(packs, p->pack_name);
221 } else if (!base || base->pack_size < p->pack_size) {
222 base = p;
226 if (base)
227 string_list_append(packs, base->pack_name);
229 return base;
232 static int too_many_packs(void)
234 struct packed_git *p;
235 int cnt;
237 if (gc_auto_pack_limit <= 0)
238 return 0;
240 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
241 if (!p->pack_local)
242 continue;
243 if (p->pack_keep)
244 continue;
246 * Perhaps check the size of the pack and count only
247 * very small ones here?
249 cnt++;
251 return gc_auto_pack_limit < cnt;
254 static uint64_t total_ram(void)
256 #if defined(HAVE_SYSINFO)
257 struct sysinfo si;
259 if (!sysinfo(&si))
260 return si.totalram;
261 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
262 int64_t physical_memory;
263 int mib[2];
264 size_t length;
266 mib[0] = CTL_HW;
267 # if defined(HW_MEMSIZE)
268 mib[1] = HW_MEMSIZE;
269 # else
270 mib[1] = HW_PHYSMEM;
271 # endif
272 length = sizeof(int64_t);
273 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
274 return physical_memory;
275 #elif defined(GIT_WINDOWS_NATIVE)
276 MEMORYSTATUSEX memInfo;
278 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
279 if (GlobalMemoryStatusEx(&memInfo))
280 return memInfo.ullTotalPhys;
281 #endif
282 return 0;
285 static uint64_t estimate_repack_memory(struct packed_git *pack)
287 unsigned long nr_objects = approximate_object_count();
288 size_t os_cache, heap;
290 if (!pack || !nr_objects)
291 return 0;
294 * First we have to scan through at least one pack.
295 * Assume enough room in OS file cache to keep the entire pack
296 * or we may accidentally evict data of other processes from
297 * the cache.
299 os_cache = pack->pack_size + pack->index_size;
300 /* then pack-objects needs lots more for book keeping */
301 heap = sizeof(struct object_entry) * nr_objects;
303 * internal rev-list --all --objects takes up some memory too,
304 * let's say half of it is for blobs
306 heap += sizeof(struct blob) * nr_objects / 2;
308 * and the other half is for trees (commits and tags are
309 * usually insignificant)
311 heap += sizeof(struct tree) * nr_objects / 2;
312 /* and then obj_hash[], underestimated in fact */
313 heap += sizeof(struct object *) * nr_objects;
314 /* revindex is used also */
315 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
317 * read_sha1_file() (either at delta calculation phase, or
318 * writing phase) also fills up the delta base cache
320 heap += delta_base_cache_limit;
321 /* and of course pack-objects has its own delta cache */
322 heap += max_delta_cache_size;
324 return os_cache + heap;
327 static int keep_one_pack(struct string_list_item *item, void *data)
329 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
330 return 0;
333 static void add_repack_all_option(struct string_list *keep_pack)
335 if (prune_expire && !strcmp(prune_expire, "now"))
336 strvec_push(&repack, "-a");
337 else if (cruft_packs) {
338 strvec_push(&repack, "--cruft");
339 if (prune_expire)
340 strvec_pushf(&repack, "--cruft-expiration=%s", prune_expire);
341 } else {
342 strvec_push(&repack, "-A");
343 if (prune_expire)
344 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
347 if (keep_pack)
348 for_each_string_list(keep_pack, keep_one_pack, NULL);
351 static void add_repack_incremental_option(void)
353 strvec_push(&repack, "--no-write-bitmap-index");
356 static int need_to_gc(void)
359 * Setting gc.auto to 0 or negative can disable the
360 * automatic gc.
362 if (gc_auto_threshold <= 0)
363 return 0;
366 * If there are too many loose objects, but not too many
367 * packs, we run "repack -d -l". If there are too many packs,
368 * we run "repack -A -d -l". Otherwise we tell the caller
369 * there is no need.
371 if (too_many_packs()) {
372 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
374 if (big_pack_threshold) {
375 find_base_packs(&keep_pack, big_pack_threshold);
376 if (keep_pack.nr >= gc_auto_pack_limit) {
377 big_pack_threshold = 0;
378 string_list_clear(&keep_pack, 0);
379 find_base_packs(&keep_pack, 0);
381 } else {
382 struct packed_git *p = find_base_packs(&keep_pack, 0);
383 uint64_t mem_have, mem_want;
385 mem_have = total_ram();
386 mem_want = estimate_repack_memory(p);
389 * Only allow 1/2 of memory for pack-objects, leave
390 * the rest for the OS and other processes in the
391 * system.
393 if (!mem_have || mem_want < mem_have / 2)
394 string_list_clear(&keep_pack, 0);
397 add_repack_all_option(&keep_pack);
398 string_list_clear(&keep_pack, 0);
399 } else if (too_many_loose_objects())
400 add_repack_incremental_option();
401 else
402 return 0;
404 if (run_hooks("pre-auto-gc"))
405 return 0;
406 return 1;
409 /* return NULL on success, else hostname running the gc */
410 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
412 struct lock_file lock = LOCK_INIT;
413 char my_host[HOST_NAME_MAX + 1];
414 struct strbuf sb = STRBUF_INIT;
415 struct stat st;
416 uintmax_t pid;
417 FILE *fp;
418 int fd;
419 char *pidfile_path;
421 if (is_tempfile_active(pidfile))
422 /* already locked */
423 return NULL;
425 if (xgethostname(my_host, sizeof(my_host)))
426 xsnprintf(my_host, sizeof(my_host), "unknown");
428 pidfile_path = git_pathdup("gc.pid");
429 fd = hold_lock_file_for_update(&lock, pidfile_path,
430 LOCK_DIE_ON_ERROR);
431 if (!force) {
432 static char locking_host[HOST_NAME_MAX + 1];
433 static char *scan_fmt;
434 int should_exit;
436 if (!scan_fmt)
437 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
438 fp = fopen(pidfile_path, "r");
439 memset(locking_host, 0, sizeof(locking_host));
440 should_exit =
441 fp != NULL &&
442 !fstat(fileno(fp), &st) &&
444 * 12 hour limit is very generous as gc should
445 * never take that long. On the other hand we
446 * don't really need a strict limit here,
447 * running gc --auto one day late is not a big
448 * problem. --force can be used in manual gc
449 * after the user verifies that no gc is
450 * running.
452 time(NULL) - st.st_mtime <= 12 * 3600 &&
453 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
454 /* be gentle to concurrent "gc" on remote hosts */
455 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
456 if (fp)
457 fclose(fp);
458 if (should_exit) {
459 if (fd >= 0)
460 rollback_lock_file(&lock);
461 *ret_pid = pid;
462 free(pidfile_path);
463 return locking_host;
467 strbuf_addf(&sb, "%"PRIuMAX" %s",
468 (uintmax_t) getpid(), my_host);
469 write_in_full(fd, sb.buf, sb.len);
470 strbuf_release(&sb);
471 commit_lock_file(&lock);
472 pidfile = register_tempfile(pidfile_path);
473 free(pidfile_path);
474 return NULL;
478 * Returns 0 if there was no previous error and gc can proceed, 1 if
479 * gc should not proceed due to an error in the last run. Prints a
480 * message and returns with a non-[01] status code if an error occurred
481 * while reading gc.log
483 static int report_last_gc_error(void)
485 struct strbuf sb = STRBUF_INIT;
486 int ret = 0;
487 ssize_t len;
488 struct stat st;
489 char *gc_log_path = git_pathdup("gc.log");
491 if (stat(gc_log_path, &st)) {
492 if (errno == ENOENT)
493 goto done;
495 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
496 goto done;
499 if (st.st_mtime < gc_log_expire_time)
500 goto done;
502 len = strbuf_read_file(&sb, gc_log_path, 0);
503 if (len < 0)
504 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
505 else if (len > 0) {
507 * A previous gc failed. Report the error, and don't
508 * bother with an automatic gc run since it is likely
509 * to fail in the same way.
511 warning(_("The last gc run reported the following. "
512 "Please correct the root cause\n"
513 "and remove %s\n"
514 "Automatic cleanup will not be performed "
515 "until the file is removed.\n\n"
516 "%s"),
517 gc_log_path, sb.buf);
518 ret = 1;
520 strbuf_release(&sb);
521 done:
522 free(gc_log_path);
523 return ret;
526 static void gc_before_repack(void)
529 * We may be called twice, as both the pre- and
530 * post-daemonized phases will call us, but running these
531 * commands more than once is pointless and wasteful.
533 static int done = 0;
534 if (done++)
535 return;
537 if (pack_refs && maintenance_task_pack_refs(NULL))
538 die(FAILED_RUN, "pack-refs");
540 if (prune_reflogs) {
541 struct child_process cmd = CHILD_PROCESS_INIT;
543 cmd.git_cmd = 1;
544 strvec_pushv(&cmd.args, reflog.v);
545 if (run_command(&cmd))
546 die(FAILED_RUN, reflog.v[0]);
550 int cmd_gc(int argc, const char **argv, const char *prefix)
552 int aggressive = 0;
553 int auto_gc = 0;
554 int quiet = 0;
555 int force = 0;
556 const char *name;
557 pid_t pid;
558 int daemonized = 0;
559 int keep_largest_pack = -1;
560 timestamp_t dummy;
561 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
563 struct option builtin_gc_options[] = {
564 OPT__QUIET(&quiet, N_("suppress progress reporting")),
565 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
566 N_("prune unreferenced objects"),
567 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
568 OPT_BOOL(0, "cruft", &cruft_packs, N_("pack unreferenced objects separately")),
569 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
570 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
571 PARSE_OPT_NOCOMPLETE),
572 OPT_BOOL_F(0, "force", &force,
573 N_("force running gc even if there may be another gc running"),
574 PARSE_OPT_NOCOMPLETE),
575 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
576 N_("repack all other packs except the largest pack")),
577 OPT_END()
580 if (argc == 2 && !strcmp(argv[1], "-h"))
581 usage_with_options(builtin_gc_usage, builtin_gc_options);
583 strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
584 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
585 strvec_pushl(&prune, "prune", "--expire", NULL);
586 strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
587 strvec_pushl(&rerere, "rerere", "gc", NULL);
589 /* default expiry time, overwritten in gc_config */
590 gc_config();
591 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
592 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire);
594 if (pack_refs < 0)
595 pack_refs = !is_bare_repository();
597 argc = parse_options(argc, argv, prefix, builtin_gc_options,
598 builtin_gc_usage, 0);
599 if (argc > 0)
600 usage_with_options(builtin_gc_usage, builtin_gc_options);
602 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
603 die(_("failed to parse prune expiry value %s"), prune_expire);
605 if (aggressive) {
606 strvec_push(&repack, "-f");
607 if (aggressive_depth > 0)
608 strvec_pushf(&repack, "--depth=%d", aggressive_depth);
609 if (aggressive_window > 0)
610 strvec_pushf(&repack, "--window=%d", aggressive_window);
612 if (quiet)
613 strvec_push(&repack, "-q");
615 if (auto_gc) {
617 * Auto-gc should be least intrusive as possible.
619 if (!need_to_gc())
620 return 0;
621 if (!quiet) {
622 if (detach_auto)
623 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
624 else
625 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
626 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
628 if (detach_auto) {
629 int ret = report_last_gc_error();
631 if (ret == 1)
632 /* Last gc --auto failed. Skip this one. */
633 return 0;
634 else if (ret)
635 /* an I/O error occurred, already reported */
636 return ret;
638 if (lock_repo_for_gc(force, &pid))
639 return 0;
640 gc_before_repack(); /* dies on failure */
641 delete_tempfile(&pidfile);
644 * failure to daemonize is ok, we'll continue
645 * in foreground
647 daemonized = !daemonize();
649 } else {
650 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
652 if (keep_largest_pack != -1) {
653 if (keep_largest_pack)
654 find_base_packs(&keep_pack, 0);
655 } else if (big_pack_threshold) {
656 find_base_packs(&keep_pack, big_pack_threshold);
659 add_repack_all_option(&keep_pack);
660 string_list_clear(&keep_pack, 0);
663 name = lock_repo_for_gc(force, &pid);
664 if (name) {
665 if (auto_gc)
666 return 0; /* be quiet on --auto */
667 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
668 name, (uintmax_t)pid);
671 if (daemonized) {
672 hold_lock_file_for_update(&log_lock,
673 git_path("gc.log"),
674 LOCK_DIE_ON_ERROR);
675 dup2(get_lock_file_fd(&log_lock), 2);
676 sigchain_push_common(process_log_file_on_signal);
677 atexit(process_log_file_at_exit);
680 gc_before_repack();
682 if (!repository_format_precious_objects) {
683 struct child_process repack_cmd = CHILD_PROCESS_INIT;
685 repack_cmd.git_cmd = 1;
686 repack_cmd.close_object_store = 1;
687 strvec_pushv(&repack_cmd.args, repack.v);
688 if (run_command(&repack_cmd))
689 die(FAILED_RUN, repack.v[0]);
691 if (prune_expire) {
692 struct child_process prune_cmd = CHILD_PROCESS_INIT;
694 /* run `git prune` even if using cruft packs */
695 strvec_push(&prune, prune_expire);
696 if (quiet)
697 strvec_push(&prune, "--no-progress");
698 if (has_promisor_remote())
699 strvec_push(&prune,
700 "--exclude-promisor-objects");
701 prune_cmd.git_cmd = 1;
702 strvec_pushv(&prune_cmd.args, prune.v);
703 if (run_command(&prune_cmd))
704 die(FAILED_RUN, prune.v[0]);
708 if (prune_worktrees_expire) {
709 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
711 strvec_push(&prune_worktrees, prune_worktrees_expire);
712 prune_worktrees_cmd.git_cmd = 1;
713 strvec_pushv(&prune_worktrees_cmd.args, prune_worktrees.v);
714 if (run_command(&prune_worktrees_cmd))
715 die(FAILED_RUN, prune_worktrees.v[0]);
718 rerere_cmd.git_cmd = 1;
719 strvec_pushv(&rerere_cmd.args, rerere.v);
720 if (run_command(&rerere_cmd))
721 die(FAILED_RUN, rerere.v[0]);
723 report_garbage = report_pack_garbage;
724 reprepare_packed_git(the_repository);
725 if (pack_garbage.nr > 0) {
726 close_object_store(the_repository->objects);
727 clean_pack_garbage();
730 prepare_repo_settings(the_repository);
731 if (the_repository->settings.gc_write_commit_graph == 1)
732 write_commit_graph_reachable(the_repository->objects->odb,
733 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
734 NULL);
736 if (auto_gc && too_many_loose_objects())
737 warning(_("There are too many unreachable loose objects; "
738 "run 'git prune' to remove them."));
740 if (!daemonized)
741 unlink(git_path("gc.log"));
743 return 0;
746 static const char *const builtin_maintenance_run_usage[] = {
747 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
748 NULL
751 enum schedule_priority {
752 SCHEDULE_NONE = 0,
753 SCHEDULE_WEEKLY = 1,
754 SCHEDULE_DAILY = 2,
755 SCHEDULE_HOURLY = 3,
758 static enum schedule_priority parse_schedule(const char *value)
760 if (!value)
761 return SCHEDULE_NONE;
762 if (!strcasecmp(value, "hourly"))
763 return SCHEDULE_HOURLY;
764 if (!strcasecmp(value, "daily"))
765 return SCHEDULE_DAILY;
766 if (!strcasecmp(value, "weekly"))
767 return SCHEDULE_WEEKLY;
768 return SCHEDULE_NONE;
771 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
772 int unset)
774 enum schedule_priority *priority = opt->value;
776 if (unset)
777 die(_("--no-schedule is not allowed"));
779 *priority = parse_schedule(arg);
781 if (!*priority)
782 die(_("unrecognized --schedule argument '%s'"), arg);
784 return 0;
787 struct maintenance_run_opts {
788 int auto_flag;
789 int quiet;
790 enum schedule_priority schedule;
793 /* Remember to update object flag allocation in object.h */
794 #define SEEN (1u<<0)
796 struct cg_auto_data {
797 int num_not_in_graph;
798 int limit;
801 static int dfs_on_ref(const char *refname UNUSED,
802 const struct object_id *oid,
803 int flags UNUSED,
804 void *cb_data)
806 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
807 int result = 0;
808 struct object_id peeled;
809 struct commit_list *stack = NULL;
810 struct commit *commit;
812 if (!peel_iterated_oid(oid, &peeled))
813 oid = &peeled;
814 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
815 return 0;
817 commit = lookup_commit(the_repository, oid);
818 if (!commit)
819 return 0;
820 if (parse_commit(commit) ||
821 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
822 return 0;
824 data->num_not_in_graph++;
826 if (data->num_not_in_graph >= data->limit)
827 return 1;
829 commit_list_append(commit, &stack);
831 while (!result && stack) {
832 struct commit_list *parent;
834 commit = pop_commit(&stack);
836 for (parent = commit->parents; parent; parent = parent->next) {
837 if (parse_commit(parent->item) ||
838 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
839 parent->item->object.flags & SEEN)
840 continue;
842 parent->item->object.flags |= SEEN;
843 data->num_not_in_graph++;
845 if (data->num_not_in_graph >= data->limit) {
846 result = 1;
847 break;
850 commit_list_append(parent->item, &stack);
854 free_commit_list(stack);
855 return result;
858 static int should_write_commit_graph(void)
860 int result;
861 struct cg_auto_data data;
863 data.num_not_in_graph = 0;
864 data.limit = 100;
865 git_config_get_int("maintenance.commit-graph.auto",
866 &data.limit);
868 if (!data.limit)
869 return 0;
870 if (data.limit < 0)
871 return 1;
873 result = for_each_ref(dfs_on_ref, &data);
875 repo_clear_commit_marks(the_repository, SEEN);
877 return result;
880 static int run_write_commit_graph(struct maintenance_run_opts *opts)
882 struct child_process child = CHILD_PROCESS_INIT;
884 child.git_cmd = child.close_object_store = 1;
885 strvec_pushl(&child.args, "commit-graph", "write",
886 "--split", "--reachable", NULL);
888 if (opts->quiet)
889 strvec_push(&child.args, "--no-progress");
891 return !!run_command(&child);
894 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
896 prepare_repo_settings(the_repository);
897 if (!the_repository->settings.core_commit_graph)
898 return 0;
900 if (run_write_commit_graph(opts)) {
901 error(_("failed to write commit-graph"));
902 return 1;
905 return 0;
908 static int fetch_remote(struct remote *remote, void *cbdata)
910 struct maintenance_run_opts *opts = cbdata;
911 struct child_process child = CHILD_PROCESS_INIT;
913 if (remote->skip_default_update)
914 return 0;
916 child.git_cmd = 1;
917 strvec_pushl(&child.args, "fetch", remote->name,
918 "--prefetch", "--prune", "--no-tags",
919 "--no-write-fetch-head", "--recurse-submodules=no",
920 NULL);
922 if (opts->quiet)
923 strvec_push(&child.args, "--quiet");
925 return !!run_command(&child);
928 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
930 if (for_each_remote(fetch_remote, opts)) {
931 error(_("failed to prefetch remotes"));
932 return 1;
935 return 0;
938 static int maintenance_task_gc(struct maintenance_run_opts *opts)
940 struct child_process child = CHILD_PROCESS_INIT;
942 child.git_cmd = child.close_object_store = 1;
943 strvec_push(&child.args, "gc");
945 if (opts->auto_flag)
946 strvec_push(&child.args, "--auto");
947 if (opts->quiet)
948 strvec_push(&child.args, "--quiet");
949 else
950 strvec_push(&child.args, "--no-quiet");
952 return run_command(&child);
955 static int prune_packed(struct maintenance_run_opts *opts)
957 struct child_process child = CHILD_PROCESS_INIT;
959 child.git_cmd = 1;
960 strvec_push(&child.args, "prune-packed");
962 if (opts->quiet)
963 strvec_push(&child.args, "--quiet");
965 return !!run_command(&child);
968 struct write_loose_object_data {
969 FILE *in;
970 int count;
971 int batch_size;
974 static int loose_object_auto_limit = 100;
976 static int loose_object_count(const struct object_id *oid,
977 const char *path,
978 void *data)
980 int *count = (int*)data;
981 if (++(*count) >= loose_object_auto_limit)
982 return 1;
983 return 0;
986 static int loose_object_auto_condition(void)
988 int count = 0;
990 git_config_get_int("maintenance.loose-objects.auto",
991 &loose_object_auto_limit);
993 if (!loose_object_auto_limit)
994 return 0;
995 if (loose_object_auto_limit < 0)
996 return 1;
998 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
999 loose_object_count,
1000 NULL, NULL, &count);
1003 static int bail_on_loose(const struct object_id *oid,
1004 const char *path,
1005 void *data)
1007 return 1;
1010 static int write_loose_object_to_stdin(const struct object_id *oid,
1011 const char *path,
1012 void *data)
1014 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1016 fprintf(d->in, "%s\n", oid_to_hex(oid));
1018 return ++(d->count) > d->batch_size;
1021 static int pack_loose(struct maintenance_run_opts *opts)
1023 struct repository *r = the_repository;
1024 int result = 0;
1025 struct write_loose_object_data data;
1026 struct child_process pack_proc = CHILD_PROCESS_INIT;
1029 * Do not start pack-objects process
1030 * if there are no loose objects.
1032 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1033 bail_on_loose,
1034 NULL, NULL, NULL))
1035 return 0;
1037 pack_proc.git_cmd = 1;
1039 strvec_push(&pack_proc.args, "pack-objects");
1040 if (opts->quiet)
1041 strvec_push(&pack_proc.args, "--quiet");
1042 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1044 pack_proc.in = -1;
1046 if (start_command(&pack_proc)) {
1047 error(_("failed to start 'git pack-objects' process"));
1048 return 1;
1051 data.in = xfdopen(pack_proc.in, "w");
1052 data.count = 0;
1053 data.batch_size = 50000;
1055 for_each_loose_file_in_objdir(r->objects->odb->path,
1056 write_loose_object_to_stdin,
1057 NULL,
1058 NULL,
1059 &data);
1061 fclose(data.in);
1063 if (finish_command(&pack_proc)) {
1064 error(_("failed to finish 'git pack-objects' process"));
1065 result = 1;
1068 return result;
1071 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1073 return prune_packed(opts) || pack_loose(opts);
1076 static int incremental_repack_auto_condition(void)
1078 struct packed_git *p;
1079 int incremental_repack_auto_limit = 10;
1080 int count = 0;
1082 prepare_repo_settings(the_repository);
1083 if (!the_repository->settings.core_multi_pack_index)
1084 return 0;
1086 git_config_get_int("maintenance.incremental-repack.auto",
1087 &incremental_repack_auto_limit);
1089 if (!incremental_repack_auto_limit)
1090 return 0;
1091 if (incremental_repack_auto_limit < 0)
1092 return 1;
1094 for (p = get_packed_git(the_repository);
1095 count < incremental_repack_auto_limit && p;
1096 p = p->next) {
1097 if (!p->multi_pack_index)
1098 count++;
1101 return count >= incremental_repack_auto_limit;
1104 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1106 struct child_process child = CHILD_PROCESS_INIT;
1108 child.git_cmd = 1;
1109 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1111 if (opts->quiet)
1112 strvec_push(&child.args, "--no-progress");
1114 if (run_command(&child))
1115 return error(_("failed to write multi-pack-index"));
1117 return 0;
1120 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1122 struct child_process child = CHILD_PROCESS_INIT;
1124 child.git_cmd = child.close_object_store = 1;
1125 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1127 if (opts->quiet)
1128 strvec_push(&child.args, "--no-progress");
1130 if (run_command(&child))
1131 return error(_("'git multi-pack-index expire' failed"));
1133 return 0;
1136 #define TWO_GIGABYTES (INT32_MAX)
1138 static off_t get_auto_pack_size(void)
1141 * The "auto" value is special: we optimize for
1142 * one large pack-file (i.e. from a clone) and
1143 * expect the rest to be small and they can be
1144 * repacked quickly.
1146 * The strategy we select here is to select a
1147 * size that is one more than the second largest
1148 * pack-file. This ensures that we will repack
1149 * at least two packs if there are three or more
1150 * packs.
1152 off_t max_size = 0;
1153 off_t second_largest_size = 0;
1154 off_t result_size;
1155 struct packed_git *p;
1156 struct repository *r = the_repository;
1158 reprepare_packed_git(r);
1159 for (p = get_all_packs(r); p; p = p->next) {
1160 if (p->pack_size > max_size) {
1161 second_largest_size = max_size;
1162 max_size = p->pack_size;
1163 } else if (p->pack_size > second_largest_size)
1164 second_largest_size = p->pack_size;
1167 result_size = second_largest_size + 1;
1169 /* But limit ourselves to a batch size of 2g */
1170 if (result_size > TWO_GIGABYTES)
1171 result_size = TWO_GIGABYTES;
1173 return result_size;
1176 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1178 struct child_process child = CHILD_PROCESS_INIT;
1180 child.git_cmd = child.close_object_store = 1;
1181 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1183 if (opts->quiet)
1184 strvec_push(&child.args, "--no-progress");
1186 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1187 (uintmax_t)get_auto_pack_size());
1189 if (run_command(&child))
1190 return error(_("'git multi-pack-index repack' failed"));
1192 return 0;
1195 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1197 prepare_repo_settings(the_repository);
1198 if (!the_repository->settings.core_multi_pack_index) {
1199 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1200 return 0;
1203 if (multi_pack_index_write(opts))
1204 return 1;
1205 if (multi_pack_index_expire(opts))
1206 return 1;
1207 if (multi_pack_index_repack(opts))
1208 return 1;
1209 return 0;
1212 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1215 * An auto condition function returns 1 if the task should run
1216 * and 0 if the task should NOT run. See needs_to_gc() for an
1217 * example.
1219 typedef int maintenance_auto_fn(void);
1221 struct maintenance_task {
1222 const char *name;
1223 maintenance_task_fn *fn;
1224 maintenance_auto_fn *auto_condition;
1225 unsigned enabled:1;
1227 enum schedule_priority schedule;
1229 /* -1 if not selected. */
1230 int selected_order;
1233 enum maintenance_task_label {
1234 TASK_PREFETCH,
1235 TASK_LOOSE_OBJECTS,
1236 TASK_INCREMENTAL_REPACK,
1237 TASK_GC,
1238 TASK_COMMIT_GRAPH,
1239 TASK_PACK_REFS,
1241 /* Leave as final value */
1242 TASK__COUNT
1245 static struct maintenance_task tasks[] = {
1246 [TASK_PREFETCH] = {
1247 "prefetch",
1248 maintenance_task_prefetch,
1250 [TASK_LOOSE_OBJECTS] = {
1251 "loose-objects",
1252 maintenance_task_loose_objects,
1253 loose_object_auto_condition,
1255 [TASK_INCREMENTAL_REPACK] = {
1256 "incremental-repack",
1257 maintenance_task_incremental_repack,
1258 incremental_repack_auto_condition,
1260 [TASK_GC] = {
1261 "gc",
1262 maintenance_task_gc,
1263 need_to_gc,
1266 [TASK_COMMIT_GRAPH] = {
1267 "commit-graph",
1268 maintenance_task_commit_graph,
1269 should_write_commit_graph,
1271 [TASK_PACK_REFS] = {
1272 "pack-refs",
1273 maintenance_task_pack_refs,
1274 NULL,
1278 static int compare_tasks_by_selection(const void *a_, const void *b_)
1280 const struct maintenance_task *a = a_;
1281 const struct maintenance_task *b = b_;
1283 return b->selected_order - a->selected_order;
1286 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1288 int i, found_selected = 0;
1289 int result = 0;
1290 struct lock_file lk;
1291 struct repository *r = the_repository;
1292 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1294 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1296 * Another maintenance command is running.
1298 * If --auto was provided, then it is likely due to a
1299 * recursive process stack. Do not report an error in
1300 * that case.
1302 if (!opts->auto_flag && !opts->quiet)
1303 warning(_("lock file '%s' exists, skipping maintenance"),
1304 lock_path);
1305 free(lock_path);
1306 return 0;
1308 free(lock_path);
1310 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1311 found_selected = tasks[i].selected_order >= 0;
1313 if (found_selected)
1314 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1316 for (i = 0; i < TASK__COUNT; i++) {
1317 if (found_selected && tasks[i].selected_order < 0)
1318 continue;
1320 if (!found_selected && !tasks[i].enabled)
1321 continue;
1323 if (opts->auto_flag &&
1324 (!tasks[i].auto_condition ||
1325 !tasks[i].auto_condition()))
1326 continue;
1328 if (opts->schedule && tasks[i].schedule < opts->schedule)
1329 continue;
1331 trace2_region_enter("maintenance", tasks[i].name, r);
1332 if (tasks[i].fn(opts)) {
1333 error(_("task '%s' failed"), tasks[i].name);
1334 result = 1;
1336 trace2_region_leave("maintenance", tasks[i].name, r);
1339 rollback_lock_file(&lk);
1340 return result;
1343 static void initialize_maintenance_strategy(void)
1345 char *config_str;
1347 if (git_config_get_string("maintenance.strategy", &config_str))
1348 return;
1350 if (!strcasecmp(config_str, "incremental")) {
1351 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1352 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1353 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1354 tasks[TASK_PREFETCH].enabled = 1;
1355 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1356 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1357 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1358 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1359 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1360 tasks[TASK_PACK_REFS].enabled = 1;
1361 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1365 static void initialize_task_config(int schedule)
1367 int i;
1368 struct strbuf config_name = STRBUF_INIT;
1369 gc_config();
1371 if (schedule)
1372 initialize_maintenance_strategy();
1374 for (i = 0; i < TASK__COUNT; i++) {
1375 int config_value;
1376 char *config_str;
1378 strbuf_reset(&config_name);
1379 strbuf_addf(&config_name, "maintenance.%s.enabled",
1380 tasks[i].name);
1382 if (!git_config_get_bool(config_name.buf, &config_value))
1383 tasks[i].enabled = config_value;
1385 strbuf_reset(&config_name);
1386 strbuf_addf(&config_name, "maintenance.%s.schedule",
1387 tasks[i].name);
1389 if (!git_config_get_string(config_name.buf, &config_str)) {
1390 tasks[i].schedule = parse_schedule(config_str);
1391 free(config_str);
1395 strbuf_release(&config_name);
1398 static int task_option_parse(const struct option *opt,
1399 const char *arg, int unset)
1401 int i, num_selected = 0;
1402 struct maintenance_task *task = NULL;
1404 BUG_ON_OPT_NEG(unset);
1406 for (i = 0; i < TASK__COUNT; i++) {
1407 if (tasks[i].selected_order >= 0)
1408 num_selected++;
1409 if (!strcasecmp(tasks[i].name, arg)) {
1410 task = &tasks[i];
1414 if (!task) {
1415 error(_("'%s' is not a valid task"), arg);
1416 return 1;
1419 if (task->selected_order >= 0) {
1420 error(_("task '%s' cannot be selected multiple times"), arg);
1421 return 1;
1424 task->selected_order = num_selected + 1;
1426 return 0;
1429 static int maintenance_run(int argc, const char **argv, const char *prefix)
1431 int i;
1432 struct maintenance_run_opts opts;
1433 struct option builtin_maintenance_run_options[] = {
1434 OPT_BOOL(0, "auto", &opts.auto_flag,
1435 N_("run tasks based on the state of the repository")),
1436 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1437 N_("run tasks based on frequency"),
1438 maintenance_opt_schedule),
1439 OPT_BOOL(0, "quiet", &opts.quiet,
1440 N_("do not report progress or other information over stderr")),
1441 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1442 N_("run a specific task"),
1443 PARSE_OPT_NONEG, task_option_parse),
1444 OPT_END()
1446 memset(&opts, 0, sizeof(opts));
1448 opts.quiet = !isatty(2);
1450 for (i = 0; i < TASK__COUNT; i++)
1451 tasks[i].selected_order = -1;
1453 argc = parse_options(argc, argv, prefix,
1454 builtin_maintenance_run_options,
1455 builtin_maintenance_run_usage,
1456 PARSE_OPT_STOP_AT_NON_OPTION);
1458 if (opts.auto_flag && opts.schedule)
1459 die(_("use at most one of --auto and --schedule=<frequency>"));
1461 initialize_task_config(opts.schedule);
1463 if (argc != 0)
1464 usage_with_options(builtin_maintenance_run_usage,
1465 builtin_maintenance_run_options);
1466 return maintenance_run_tasks(&opts);
1469 static char *get_maintpath(void)
1471 struct strbuf sb = STRBUF_INIT;
1472 const char *p = the_repository->worktree ?
1473 the_repository->worktree : the_repository->gitdir;
1475 strbuf_realpath(&sb, p, 1);
1476 return strbuf_detach(&sb, NULL);
1479 static char const * const builtin_maintenance_register_usage[] = {
1480 "git maintenance register",
1481 NULL
1484 static int maintenance_register(int argc, const char **argv, const char *prefix)
1486 struct option options[] = {
1487 OPT_END(),
1489 int found = 0;
1490 const char *key = "maintenance.repo";
1491 char *config_value;
1492 char *maintpath = get_maintpath();
1493 struct string_list_item *item;
1494 const struct string_list *list;
1496 argc = parse_options(argc, argv, prefix, options,
1497 builtin_maintenance_register_usage, 0);
1498 if (argc)
1499 usage_with_options(builtin_maintenance_register_usage,
1500 options);
1502 /* Disable foreground maintenance */
1503 git_config_set("maintenance.auto", "false");
1505 /* Set maintenance strategy, if unset */
1506 if (!git_config_get_string("maintenance.strategy", &config_value))
1507 free(config_value);
1508 else
1509 git_config_set("maintenance.strategy", "incremental");
1511 list = git_config_get_value_multi(key);
1512 if (list) {
1513 for_each_string_list_item(item, list) {
1514 if (!strcmp(maintpath, item->string)) {
1515 found = 1;
1516 break;
1521 if (!found) {
1522 int rc;
1523 char *user_config, *xdg_config;
1524 git_global_config(&user_config, &xdg_config);
1525 if (!user_config)
1526 die(_("$HOME not set"));
1527 rc = git_config_set_multivar_in_file_gently(
1528 user_config, "maintenance.repo", maintpath,
1529 CONFIG_REGEX_NONE, 0);
1530 free(user_config);
1531 free(xdg_config);
1533 if (rc)
1534 die(_("unable to add '%s' value of '%s'"),
1535 key, maintpath);
1538 free(maintpath);
1539 return 0;
1542 static char const * const builtin_maintenance_unregister_usage[] = {
1543 "git maintenance unregister [--force]",
1544 NULL
1547 static int maintenance_unregister(int argc, const char **argv, const char *prefix)
1549 int force = 0;
1550 struct option options[] = {
1551 OPT__FORCE(&force,
1552 N_("return success even if repository was not registered"),
1553 PARSE_OPT_NOCOMPLETE),
1554 OPT_END(),
1556 const char *key = "maintenance.repo";
1557 char *maintpath = get_maintpath();
1558 int found = 0;
1559 struct string_list_item *item;
1560 const struct string_list *list;
1562 argc = parse_options(argc, argv, prefix, options,
1563 builtin_maintenance_unregister_usage, 0);
1564 if (argc)
1565 usage_with_options(builtin_maintenance_unregister_usage,
1566 options);
1568 list = git_config_get_value_multi(key);
1569 if (list) {
1570 for_each_string_list_item(item, list) {
1571 if (!strcmp(maintpath, item->string)) {
1572 found = 1;
1573 break;
1578 if (found) {
1579 int rc;
1580 char *user_config, *xdg_config;
1581 git_global_config(&user_config, &xdg_config);
1582 if (!user_config)
1583 die(_("$HOME not set"));
1584 rc = git_config_set_multivar_in_file_gently(
1585 user_config, key, NULL, maintpath,
1586 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
1587 free(user_config);
1588 free(xdg_config);
1590 if (rc &&
1591 (!force || rc == CONFIG_NOTHING_SET))
1592 die(_("unable to unset '%s' value of '%s'"),
1593 key, maintpath);
1594 } else if (!force) {
1595 die(_("repository '%s' is not registered"), maintpath);
1598 free(maintpath);
1599 return 0;
1602 static const char *get_frequency(enum schedule_priority schedule)
1604 switch (schedule) {
1605 case SCHEDULE_HOURLY:
1606 return "hourly";
1607 case SCHEDULE_DAILY:
1608 return "daily";
1609 case SCHEDULE_WEEKLY:
1610 return "weekly";
1611 default:
1612 BUG("invalid schedule %d", schedule);
1617 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1618 * to mock the schedulers that `git maintenance start` rely on.
1620 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1621 * list of colon-separated key/value pairs where each pair contains a scheduler
1622 * and its corresponding mock.
1624 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1625 * arguments unmodified.
1627 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1628 * In this case, the *cmd value is read as input.
1630 * * if the input value *cmd is the key of one of the comma-separated list
1631 * item, then *is_available is set to true and *cmd is modified and becomes
1632 * the mock command.
1634 * * if the input value *cmd isn’t the key of any of the comma-separated list
1635 * item, then *is_available is set to false.
1637 * Ex.:
1638 * GIT_TEST_MAINT_SCHEDULER not set
1639 * +-------+-------------------------------------------------+
1640 * | Input | Output |
1641 * | *cmd | return code | *cmd | *is_available |
1642 * +-------+-------------+-------------------+---------------+
1643 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1644 * +-------+-------------+-------------------+---------------+
1646 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1647 * +-------+-------------------------------------------------+
1648 * | Input | Output |
1649 * | *cmd | return code | *cmd | *is_available |
1650 * +-------+-------------+-------------------+---------------+
1651 * | "foo" | true | "./mock.foo.sh" | true |
1652 * | "qux" | true | "qux" (unchanged) | false |
1653 * +-------+-------------+-------------------+---------------+
1655 static int get_schedule_cmd(const char **cmd, int *is_available)
1657 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1658 struct string_list_item *item;
1659 struct string_list list = STRING_LIST_INIT_NODUP;
1661 if (!testing)
1662 return 0;
1664 if (is_available)
1665 *is_available = 0;
1667 string_list_split_in_place(&list, testing, ',', -1);
1668 for_each_string_list_item(item, &list) {
1669 struct string_list pair = STRING_LIST_INIT_NODUP;
1671 if (string_list_split_in_place(&pair, item->string, ':', 2) != 2)
1672 continue;
1674 if (!strcmp(*cmd, pair.items[0].string)) {
1675 *cmd = pair.items[1].string;
1676 if (is_available)
1677 *is_available = 1;
1678 string_list_clear(&list, 0);
1679 UNLEAK(testing);
1680 return 1;
1684 string_list_clear(&list, 0);
1685 free(testing);
1686 return 1;
1689 static int is_launchctl_available(void)
1691 const char *cmd = "launchctl";
1692 int is_available;
1693 if (get_schedule_cmd(&cmd, &is_available))
1694 return is_available;
1696 #ifdef __APPLE__
1697 return 1;
1698 #else
1699 return 0;
1700 #endif
1703 static char *launchctl_service_name(const char *frequency)
1705 struct strbuf label = STRBUF_INIT;
1706 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1707 return strbuf_detach(&label, NULL);
1710 static char *launchctl_service_filename(const char *name)
1712 char *expanded;
1713 struct strbuf filename = STRBUF_INIT;
1714 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1716 expanded = interpolate_path(filename.buf, 1);
1717 if (!expanded)
1718 die(_("failed to expand path '%s'"), filename.buf);
1720 strbuf_release(&filename);
1721 return expanded;
1724 static char *launchctl_get_uid(void)
1726 return xstrfmt("gui/%d", getuid());
1729 static int launchctl_boot_plist(int enable, const char *filename)
1731 const char *cmd = "launchctl";
1732 int result;
1733 struct child_process child = CHILD_PROCESS_INIT;
1734 char *uid = launchctl_get_uid();
1736 get_schedule_cmd(&cmd, NULL);
1737 strvec_split(&child.args, cmd);
1738 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1739 filename, NULL);
1741 child.no_stderr = 1;
1742 child.no_stdout = 1;
1744 if (start_command(&child))
1745 die(_("failed to start launchctl"));
1747 result = finish_command(&child);
1749 free(uid);
1750 return result;
1753 static int launchctl_remove_plist(enum schedule_priority schedule)
1755 const char *frequency = get_frequency(schedule);
1756 char *name = launchctl_service_name(frequency);
1757 char *filename = launchctl_service_filename(name);
1758 int result = launchctl_boot_plist(0, filename);
1759 unlink(filename);
1760 free(filename);
1761 free(name);
1762 return result;
1765 static int launchctl_remove_plists(void)
1767 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1768 launchctl_remove_plist(SCHEDULE_DAILY) ||
1769 launchctl_remove_plist(SCHEDULE_WEEKLY);
1772 static int launchctl_list_contains_plist(const char *name, const char *cmd)
1774 struct child_process child = CHILD_PROCESS_INIT;
1776 strvec_split(&child.args, cmd);
1777 strvec_pushl(&child.args, "list", name, NULL);
1779 child.no_stderr = 1;
1780 child.no_stdout = 1;
1782 if (start_command(&child))
1783 die(_("failed to start launchctl"));
1785 /* Returns failure if 'name' doesn't exist. */
1786 return !finish_command(&child);
1789 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1791 int i, fd;
1792 const char *preamble, *repeat;
1793 const char *frequency = get_frequency(schedule);
1794 char *name = launchctl_service_name(frequency);
1795 char *filename = launchctl_service_filename(name);
1796 struct lock_file lk = LOCK_INIT;
1797 static unsigned long lock_file_timeout_ms = ULONG_MAX;
1798 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
1799 struct stat st;
1800 const char *cmd = "launchctl";
1802 get_schedule_cmd(&cmd, NULL);
1803 preamble = "<?xml version=\"1.0\"?>\n"
1804 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1805 "<plist version=\"1.0\">"
1806 "<dict>\n"
1807 "<key>Label</key><string>%s</string>\n"
1808 "<key>ProgramArguments</key>\n"
1809 "<array>\n"
1810 "<string>%s/git</string>\n"
1811 "<string>--exec-path=%s</string>\n"
1812 "<string>for-each-repo</string>\n"
1813 "<string>--config=maintenance.repo</string>\n"
1814 "<string>maintenance</string>\n"
1815 "<string>run</string>\n"
1816 "<string>--schedule=%s</string>\n"
1817 "</array>\n"
1818 "<key>StartCalendarInterval</key>\n"
1819 "<array>\n";
1820 strbuf_addf(&plist, preamble, name, exec_path, exec_path, frequency);
1822 switch (schedule) {
1823 case SCHEDULE_HOURLY:
1824 repeat = "<dict>\n"
1825 "<key>Hour</key><integer>%d</integer>\n"
1826 "<key>Minute</key><integer>0</integer>\n"
1827 "</dict>\n";
1828 for (i = 1; i <= 23; i++)
1829 strbuf_addf(&plist, repeat, i);
1830 break;
1832 case SCHEDULE_DAILY:
1833 repeat = "<dict>\n"
1834 "<key>Day</key><integer>%d</integer>\n"
1835 "<key>Hour</key><integer>0</integer>\n"
1836 "<key>Minute</key><integer>0</integer>\n"
1837 "</dict>\n";
1838 for (i = 1; i <= 6; i++)
1839 strbuf_addf(&plist, repeat, i);
1840 break;
1842 case SCHEDULE_WEEKLY:
1843 strbuf_addstr(&plist,
1844 "<dict>\n"
1845 "<key>Day</key><integer>0</integer>\n"
1846 "<key>Hour</key><integer>0</integer>\n"
1847 "<key>Minute</key><integer>0</integer>\n"
1848 "</dict>\n");
1849 break;
1851 default:
1852 /* unreachable */
1853 break;
1855 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
1857 if (safe_create_leading_directories(filename))
1858 die(_("failed to create directories for '%s'"), filename);
1860 if ((long)lock_file_timeout_ms < 0 &&
1861 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1862 &lock_file_timeout_ms))
1863 lock_file_timeout_ms = 150;
1865 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
1866 lock_file_timeout_ms);
1869 * Does this file already exist? With the intended contents? Is it
1870 * registered already? Then it does not need to be re-registered.
1872 if (!stat(filename, &st) && st.st_size == plist.len &&
1873 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
1874 !strbuf_cmp(&plist, &plist2) &&
1875 launchctl_list_contains_plist(name, cmd))
1876 rollback_lock_file(&lk);
1877 else {
1878 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
1879 commit_lock_file(&lk))
1880 die_errno(_("could not write '%s'"), filename);
1882 /* bootout might fail if not already running, so ignore */
1883 launchctl_boot_plist(0, filename);
1884 if (launchctl_boot_plist(1, filename))
1885 die(_("failed to bootstrap service %s"), filename);
1888 free(filename);
1889 free(name);
1890 strbuf_release(&plist);
1891 strbuf_release(&plist2);
1892 return 0;
1895 static int launchctl_add_plists(void)
1897 const char *exec_path = git_exec_path();
1899 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1900 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1901 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1904 static int launchctl_update_schedule(int run_maintenance, int fd)
1906 if (run_maintenance)
1907 return launchctl_add_plists();
1908 else
1909 return launchctl_remove_plists();
1912 static int is_schtasks_available(void)
1914 const char *cmd = "schtasks";
1915 int is_available;
1916 if (get_schedule_cmd(&cmd, &is_available))
1917 return is_available;
1919 #ifdef GIT_WINDOWS_NATIVE
1920 return 1;
1921 #else
1922 return 0;
1923 #endif
1926 static char *schtasks_task_name(const char *frequency)
1928 struct strbuf label = STRBUF_INIT;
1929 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1930 return strbuf_detach(&label, NULL);
1933 static int schtasks_remove_task(enum schedule_priority schedule)
1935 const char *cmd = "schtasks";
1936 struct child_process child = CHILD_PROCESS_INIT;
1937 const char *frequency = get_frequency(schedule);
1938 char *name = schtasks_task_name(frequency);
1940 get_schedule_cmd(&cmd, NULL);
1941 strvec_split(&child.args, cmd);
1942 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
1943 free(name);
1945 return run_command(&child);
1948 static int schtasks_remove_tasks(void)
1950 return schtasks_remove_task(SCHEDULE_HOURLY) ||
1951 schtasks_remove_task(SCHEDULE_DAILY) ||
1952 schtasks_remove_task(SCHEDULE_WEEKLY);
1955 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
1957 const char *cmd = "schtasks";
1958 int result;
1959 struct child_process child = CHILD_PROCESS_INIT;
1960 const char *xml;
1961 struct tempfile *tfile;
1962 const char *frequency = get_frequency(schedule);
1963 char *name = schtasks_task_name(frequency);
1964 struct strbuf tfilename = STRBUF_INIT;
1966 get_schedule_cmd(&cmd, NULL);
1968 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1969 get_git_common_dir(), frequency);
1970 tfile = xmks_tempfile(tfilename.buf);
1971 strbuf_release(&tfilename);
1973 if (!fdopen_tempfile(tfile, "w"))
1974 die(_("failed to create temp xml file"));
1976 xml = "<?xml version=\"1.0\" ?>\n"
1977 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1978 "<Triggers>\n"
1979 "<CalendarTrigger>\n";
1980 fputs(xml, tfile->fp);
1982 switch (schedule) {
1983 case SCHEDULE_HOURLY:
1984 fprintf(tfile->fp,
1985 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1986 "<Enabled>true</Enabled>\n"
1987 "<ScheduleByDay>\n"
1988 "<DaysInterval>1</DaysInterval>\n"
1989 "</ScheduleByDay>\n"
1990 "<Repetition>\n"
1991 "<Interval>PT1H</Interval>\n"
1992 "<Duration>PT23H</Duration>\n"
1993 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1994 "</Repetition>\n");
1995 break;
1997 case SCHEDULE_DAILY:
1998 fprintf(tfile->fp,
1999 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2000 "<Enabled>true</Enabled>\n"
2001 "<ScheduleByWeek>\n"
2002 "<DaysOfWeek>\n"
2003 "<Monday />\n"
2004 "<Tuesday />\n"
2005 "<Wednesday />\n"
2006 "<Thursday />\n"
2007 "<Friday />\n"
2008 "<Saturday />\n"
2009 "</DaysOfWeek>\n"
2010 "<WeeksInterval>1</WeeksInterval>\n"
2011 "</ScheduleByWeek>\n");
2012 break;
2014 case SCHEDULE_WEEKLY:
2015 fprintf(tfile->fp,
2016 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2017 "<Enabled>true</Enabled>\n"
2018 "<ScheduleByWeek>\n"
2019 "<DaysOfWeek>\n"
2020 "<Sunday />\n"
2021 "</DaysOfWeek>\n"
2022 "<WeeksInterval>1</WeeksInterval>\n"
2023 "</ScheduleByWeek>\n");
2024 break;
2026 default:
2027 break;
2030 xml = "</CalendarTrigger>\n"
2031 "</Triggers>\n"
2032 "<Principals>\n"
2033 "<Principal id=\"Author\">\n"
2034 "<LogonType>InteractiveToken</LogonType>\n"
2035 "<RunLevel>LeastPrivilege</RunLevel>\n"
2036 "</Principal>\n"
2037 "</Principals>\n"
2038 "<Settings>\n"
2039 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2040 "<Enabled>true</Enabled>\n"
2041 "<Hidden>true</Hidden>\n"
2042 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2043 "<WakeToRun>false</WakeToRun>\n"
2044 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2045 "<Priority>7</Priority>\n"
2046 "</Settings>\n"
2047 "<Actions Context=\"Author\">\n"
2048 "<Exec>\n"
2049 "<Command>\"%s\\git.exe\"</Command>\n"
2050 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2051 "</Exec>\n"
2052 "</Actions>\n"
2053 "</Task>\n";
2054 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
2055 strvec_split(&child.args, cmd);
2056 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2057 get_tempfile_path(tfile), NULL);
2058 close_tempfile_gently(tfile);
2060 child.no_stdout = 1;
2061 child.no_stderr = 1;
2063 if (start_command(&child))
2064 die(_("failed to start schtasks"));
2065 result = finish_command(&child);
2067 delete_tempfile(&tfile);
2068 free(name);
2069 return result;
2072 static int schtasks_schedule_tasks(void)
2074 const char *exec_path = git_exec_path();
2076 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2077 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2078 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
2081 static int schtasks_update_schedule(int run_maintenance, int fd)
2083 if (run_maintenance)
2084 return schtasks_schedule_tasks();
2085 else
2086 return schtasks_remove_tasks();
2089 MAYBE_UNUSED
2090 static int check_crontab_process(const char *cmd)
2092 struct child_process child = CHILD_PROCESS_INIT;
2094 strvec_split(&child.args, cmd);
2095 strvec_push(&child.args, "-l");
2096 child.no_stdin = 1;
2097 child.no_stdout = 1;
2098 child.no_stderr = 1;
2099 child.silent_exec_failure = 1;
2101 if (start_command(&child))
2102 return 0;
2103 /* Ignore exit code, as an empty crontab will return error. */
2104 finish_command(&child);
2105 return 1;
2108 static int is_crontab_available(void)
2110 const char *cmd = "crontab";
2111 int is_available;
2113 if (get_schedule_cmd(&cmd, &is_available))
2114 return is_available;
2116 #ifdef __APPLE__
2118 * macOS has cron, but it requires special permissions and will
2119 * create a UI alert when attempting to run this command.
2121 return 0;
2122 #else
2123 return check_crontab_process(cmd);
2124 #endif
2127 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2128 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2130 static int crontab_update_schedule(int run_maintenance, int fd)
2132 const char *cmd = "crontab";
2133 int result = 0;
2134 int in_old_region = 0;
2135 struct child_process crontab_list = CHILD_PROCESS_INIT;
2136 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2137 FILE *cron_list, *cron_in;
2138 struct strbuf line = STRBUF_INIT;
2139 struct tempfile *tmpedit = NULL;
2141 get_schedule_cmd(&cmd, NULL);
2142 strvec_split(&crontab_list.args, cmd);
2143 strvec_push(&crontab_list.args, "-l");
2144 crontab_list.in = -1;
2145 crontab_list.out = dup(fd);
2146 crontab_list.git_cmd = 0;
2148 if (start_command(&crontab_list))
2149 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2151 /* Ignore exit code, as an empty crontab will return error. */
2152 finish_command(&crontab_list);
2154 tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2155 if (!tmpedit) {
2156 result = error(_("failed to create crontab temporary file"));
2157 goto out;
2159 cron_in = fdopen_tempfile(tmpedit, "w");
2160 if (!cron_in) {
2161 result = error(_("failed to open temporary file"));
2162 goto out;
2166 * Read from the .lock file, filtering out the old
2167 * schedule while appending the new schedule.
2169 cron_list = fdopen(fd, "r");
2170 rewind(cron_list);
2172 while (!strbuf_getline_lf(&line, cron_list)) {
2173 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2174 in_old_region = 1;
2175 else if (in_old_region && !strcmp(line.buf, END_LINE))
2176 in_old_region = 0;
2177 else if (!in_old_region)
2178 fprintf(cron_in, "%s\n", line.buf);
2180 strbuf_release(&line);
2182 if (run_maintenance) {
2183 struct strbuf line_format = STRBUF_INIT;
2184 const char *exec_path = git_exec_path();
2186 fprintf(cron_in, "%s\n", BEGIN_LINE);
2187 fprintf(cron_in,
2188 "# The following schedule was created by Git\n");
2189 fprintf(cron_in, "# Any edits made in this region might be\n");
2190 fprintf(cron_in,
2191 "# replaced in the future by a Git command.\n\n");
2193 strbuf_addf(&line_format,
2194 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2195 exec_path, exec_path);
2196 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2197 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2198 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2199 strbuf_release(&line_format);
2201 fprintf(cron_in, "\n%s\n", END_LINE);
2204 fflush(cron_in);
2206 strvec_split(&crontab_edit.args, cmd);
2207 strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2208 crontab_edit.git_cmd = 0;
2210 if (start_command(&crontab_edit)) {
2211 result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2212 goto out;
2215 if (finish_command(&crontab_edit))
2216 result = error(_("'crontab' died"));
2217 else
2218 fclose(cron_list);
2219 out:
2220 delete_tempfile(&tmpedit);
2221 return result;
2224 static int real_is_systemd_timer_available(void)
2226 struct child_process child = CHILD_PROCESS_INIT;
2228 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2229 child.no_stdin = 1;
2230 child.no_stdout = 1;
2231 child.no_stderr = 1;
2232 child.silent_exec_failure = 1;
2234 if (start_command(&child))
2235 return 0;
2236 if (finish_command(&child))
2237 return 0;
2238 return 1;
2241 static int is_systemd_timer_available(void)
2243 const char *cmd = "systemctl";
2244 int is_available;
2246 if (get_schedule_cmd(&cmd, &is_available))
2247 return is_available;
2249 return real_is_systemd_timer_available();
2252 static char *xdg_config_home_systemd(const char *filename)
2254 return xdg_config_home_for("systemd/user", filename);
2257 static int systemd_timer_enable_unit(int enable,
2258 enum schedule_priority schedule)
2260 const char *cmd = "systemctl";
2261 struct child_process child = CHILD_PROCESS_INIT;
2262 const char *frequency = get_frequency(schedule);
2265 * Disabling the systemd unit while it is already disabled makes
2266 * systemctl print an error.
2267 * Let's ignore it since it means we already are in the expected state:
2268 * the unit is disabled.
2270 * On the other hand, enabling a systemd unit which is already enabled
2271 * produces no error.
2273 if (!enable)
2274 child.no_stderr = 1;
2276 get_schedule_cmd(&cmd, NULL);
2277 strvec_split(&child.args, cmd);
2278 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2279 "--now", NULL);
2280 strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2282 if (start_command(&child))
2283 return error(_("failed to start systemctl"));
2284 if (finish_command(&child))
2286 * Disabling an already disabled systemd unit makes
2287 * systemctl fail.
2288 * Let's ignore this failure.
2290 * Enabling an enabled systemd unit doesn't fail.
2292 if (enable)
2293 return error(_("failed to run systemctl"));
2294 return 0;
2297 static int systemd_timer_delete_unit_templates(void)
2299 int ret = 0;
2300 char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2301 if (unlink(filename) && !is_missing_file_error(errno))
2302 ret = error_errno(_("failed to delete '%s'"), filename);
2303 FREE_AND_NULL(filename);
2305 filename = xdg_config_home_systemd("git-maintenance@.service");
2306 if (unlink(filename) && !is_missing_file_error(errno))
2307 ret = error_errno(_("failed to delete '%s'"), filename);
2309 free(filename);
2310 return ret;
2313 static int systemd_timer_delete_units(void)
2315 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2316 systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2317 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2318 systemd_timer_delete_unit_templates();
2321 static int systemd_timer_write_unit_templates(const char *exec_path)
2323 char *filename;
2324 FILE *file;
2325 const char *unit;
2327 filename = xdg_config_home_systemd("git-maintenance@.timer");
2328 if (safe_create_leading_directories(filename)) {
2329 error(_("failed to create directories for '%s'"), filename);
2330 goto error;
2332 file = fopen_or_warn(filename, "w");
2333 if (!file)
2334 goto error;
2336 unit = "# This file was created and is maintained by Git.\n"
2337 "# Any edits made in this file might be replaced in the future\n"
2338 "# by a Git command.\n"
2339 "\n"
2340 "[Unit]\n"
2341 "Description=Optimize Git repositories data\n"
2342 "\n"
2343 "[Timer]\n"
2344 "OnCalendar=%i\n"
2345 "Persistent=true\n"
2346 "\n"
2347 "[Install]\n"
2348 "WantedBy=timers.target\n";
2349 if (fputs(unit, file) == EOF) {
2350 error(_("failed to write to '%s'"), filename);
2351 fclose(file);
2352 goto error;
2354 if (fclose(file) == EOF) {
2355 error_errno(_("failed to flush '%s'"), filename);
2356 goto error;
2358 free(filename);
2360 filename = xdg_config_home_systemd("git-maintenance@.service");
2361 file = fopen_or_warn(filename, "w");
2362 if (!file)
2363 goto error;
2365 unit = "# This file was created and is maintained by Git.\n"
2366 "# Any edits made in this file might be replaced in the future\n"
2367 "# by a Git command.\n"
2368 "\n"
2369 "[Unit]\n"
2370 "Description=Optimize Git repositories data\n"
2371 "\n"
2372 "[Service]\n"
2373 "Type=oneshot\n"
2374 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2375 "LockPersonality=yes\n"
2376 "MemoryDenyWriteExecute=yes\n"
2377 "NoNewPrivileges=yes\n"
2378 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2379 "RestrictNamespaces=yes\n"
2380 "RestrictRealtime=yes\n"
2381 "RestrictSUIDSGID=yes\n"
2382 "SystemCallArchitectures=native\n"
2383 "SystemCallFilter=@system-service\n";
2384 if (fprintf(file, unit, exec_path, exec_path) < 0) {
2385 error(_("failed to write to '%s'"), filename);
2386 fclose(file);
2387 goto error;
2389 if (fclose(file) == EOF) {
2390 error_errno(_("failed to flush '%s'"), filename);
2391 goto error;
2393 free(filename);
2394 return 0;
2396 error:
2397 free(filename);
2398 systemd_timer_delete_unit_templates();
2399 return -1;
2402 static int systemd_timer_setup_units(void)
2404 const char *exec_path = git_exec_path();
2406 int ret = systemd_timer_write_unit_templates(exec_path) ||
2407 systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2408 systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2409 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2410 if (ret)
2411 systemd_timer_delete_units();
2412 return ret;
2415 static int systemd_timer_update_schedule(int run_maintenance, int fd)
2417 if (run_maintenance)
2418 return systemd_timer_setup_units();
2419 else
2420 return systemd_timer_delete_units();
2423 enum scheduler {
2424 SCHEDULER_INVALID = -1,
2425 SCHEDULER_AUTO,
2426 SCHEDULER_CRON,
2427 SCHEDULER_SYSTEMD,
2428 SCHEDULER_LAUNCHCTL,
2429 SCHEDULER_SCHTASKS,
2432 static const struct {
2433 const char *name;
2434 int (*is_available)(void);
2435 int (*update_schedule)(int run_maintenance, int fd);
2436 } scheduler_fn[] = {
2437 [SCHEDULER_CRON] = {
2438 .name = "crontab",
2439 .is_available = is_crontab_available,
2440 .update_schedule = crontab_update_schedule,
2442 [SCHEDULER_SYSTEMD] = {
2443 .name = "systemctl",
2444 .is_available = is_systemd_timer_available,
2445 .update_schedule = systemd_timer_update_schedule,
2447 [SCHEDULER_LAUNCHCTL] = {
2448 .name = "launchctl",
2449 .is_available = is_launchctl_available,
2450 .update_schedule = launchctl_update_schedule,
2452 [SCHEDULER_SCHTASKS] = {
2453 .name = "schtasks",
2454 .is_available = is_schtasks_available,
2455 .update_schedule = schtasks_update_schedule,
2459 static enum scheduler parse_scheduler(const char *value)
2461 if (!value)
2462 return SCHEDULER_INVALID;
2463 else if (!strcasecmp(value, "auto"))
2464 return SCHEDULER_AUTO;
2465 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2466 return SCHEDULER_CRON;
2467 else if (!strcasecmp(value, "systemd") ||
2468 !strcasecmp(value, "systemd-timer"))
2469 return SCHEDULER_SYSTEMD;
2470 else if (!strcasecmp(value, "launchctl"))
2471 return SCHEDULER_LAUNCHCTL;
2472 else if (!strcasecmp(value, "schtasks"))
2473 return SCHEDULER_SCHTASKS;
2474 else
2475 return SCHEDULER_INVALID;
2478 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2479 int unset)
2481 enum scheduler *scheduler = opt->value;
2483 BUG_ON_OPT_NEG(unset);
2485 *scheduler = parse_scheduler(arg);
2486 if (*scheduler == SCHEDULER_INVALID)
2487 return error(_("unrecognized --scheduler argument '%s'"), arg);
2488 return 0;
2491 struct maintenance_start_opts {
2492 enum scheduler scheduler;
2495 static enum scheduler resolve_scheduler(enum scheduler scheduler)
2497 if (scheduler != SCHEDULER_AUTO)
2498 return scheduler;
2500 #if defined(__APPLE__)
2501 return SCHEDULER_LAUNCHCTL;
2503 #elif defined(GIT_WINDOWS_NATIVE)
2504 return SCHEDULER_SCHTASKS;
2506 #elif defined(__linux__)
2507 if (is_systemd_timer_available())
2508 return SCHEDULER_SYSTEMD;
2509 else if (is_crontab_available())
2510 return SCHEDULER_CRON;
2511 else
2512 die(_("neither systemd timers nor crontab are available"));
2514 #else
2515 return SCHEDULER_CRON;
2516 #endif
2519 static void validate_scheduler(enum scheduler scheduler)
2521 if (scheduler == SCHEDULER_INVALID)
2522 BUG("invalid scheduler");
2523 if (scheduler == SCHEDULER_AUTO)
2524 BUG("resolve_scheduler should have been called before");
2526 if (!scheduler_fn[scheduler].is_available())
2527 die(_("%s scheduler is not available"),
2528 scheduler_fn[scheduler].name);
2531 static int update_background_schedule(const struct maintenance_start_opts *opts,
2532 int enable)
2534 unsigned int i;
2535 int result = 0;
2536 struct lock_file lk;
2537 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2539 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2540 free(lock_path);
2541 return error(_("another process is scheduling background maintenance"));
2544 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2545 if (enable && opts->scheduler == i)
2546 continue;
2547 if (!scheduler_fn[i].is_available())
2548 continue;
2549 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2552 if (enable)
2553 result = scheduler_fn[opts->scheduler].update_schedule(
2554 1, get_lock_file_fd(&lk));
2556 rollback_lock_file(&lk);
2558 free(lock_path);
2559 return result;
2562 static const char *const builtin_maintenance_start_usage[] = {
2563 N_("git maintenance start [--scheduler=<scheduler>]"),
2564 NULL
2567 static int maintenance_start(int argc, const char **argv, const char *prefix)
2569 struct maintenance_start_opts opts = { 0 };
2570 struct option options[] = {
2571 OPT_CALLBACK_F(
2572 0, "scheduler", &opts.scheduler, N_("scheduler"),
2573 N_("scheduler to trigger git maintenance run"),
2574 PARSE_OPT_NONEG, maintenance_opt_scheduler),
2575 OPT_END()
2577 const char *register_args[] = { "register", NULL };
2579 argc = parse_options(argc, argv, prefix, options,
2580 builtin_maintenance_start_usage, 0);
2581 if (argc)
2582 usage_with_options(builtin_maintenance_start_usage, options);
2584 opts.scheduler = resolve_scheduler(opts.scheduler);
2585 validate_scheduler(opts.scheduler);
2587 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL))
2588 warning(_("failed to add repo to global config"));
2589 return update_background_schedule(&opts, 1);
2592 static const char *const builtin_maintenance_stop_usage[] = {
2593 "git maintenance stop",
2594 NULL
2597 static int maintenance_stop(int argc, const char **argv, const char *prefix)
2599 struct option options[] = {
2600 OPT_END()
2602 argc = parse_options(argc, argv, prefix, options,
2603 builtin_maintenance_stop_usage, 0);
2604 if (argc)
2605 usage_with_options(builtin_maintenance_stop_usage, options);
2606 return update_background_schedule(NULL, 0);
2609 static const char * const builtin_maintenance_usage[] = {
2610 N_("git maintenance <subcommand> [<options>]"),
2611 NULL,
2614 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2616 parse_opt_subcommand_fn *fn = NULL;
2617 struct option builtin_maintenance_options[] = {
2618 OPT_SUBCOMMAND("run", &fn, maintenance_run),
2619 OPT_SUBCOMMAND("start", &fn, maintenance_start),
2620 OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
2621 OPT_SUBCOMMAND("register", &fn, maintenance_register),
2622 OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
2623 OPT_END(),
2626 argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
2627 builtin_maintenance_usage, 0);
2628 return fn(argc, argv, prefix);