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
14 #include "repository.h"
18 #include "parse-options.h"
19 #include "run-command.h"
23 #include "commit-graph.h"
25 #include "object-store.h"
27 #include "pack-objects.h"
30 #include "promisor-remote.h"
33 #include "object-store.h"
37 #define FAILED_RUN "failed to run %s"
39 static const char * const builtin_gc_usage[] = {
40 N_("git gc [<options>]"),
44 static int pack_refs = 1;
45 static int prune_reflogs = 1;
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)
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)
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
93 int saved_errno = errno;
94 fprintf(stderr, _("Failed to fstat %s: %s"),
95 get_lock_file_path(&log_lock),
96 strerror(saved_errno));
98 commit_lock_file(&log_lock);
100 } else if (st.st_size) {
101 /* There was some error recorded in the lock file */
102 commit_lock_file(&log_lock);
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)
116 static void process_log_file_on_signal(int signo)
123 static int gc_config_is_timestamp_never(const char *var)
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);
136 static void gc_config(void)
140 if (!git_config_get_value("gc.packrefs", &value)) {
141 if (value && !strcmp(value, "notbare"))
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"))
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_expiry("gc.pruneexpire", &prune_expire);
157 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
158 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
160 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
161 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
163 git_config(git_default_config, NULL);
166 struct maintenance_run_opts;
167 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
169 struct strvec pack_refs_cmd = STRVEC_INIT;
170 strvec_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
172 return run_command_v_opt(pack_refs_cmd.v, RUN_GIT_CMD);
175 static int too_many_loose_objects(void)
178 * Quickly check if a "gc" is needed, by estimating how
179 * many loose objects there are. Because SHA-1 is evenly
180 * distributed, we can check only one and get a reasonable
188 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
190 dir = opendir(git_path("objects/17"));
194 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
195 while ((ent = readdir(dir)) != NULL) {
196 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
197 ent->d_name[hexsz_loose] != '\0')
199 if (++num_loose > auto_threshold) {
208 static struct packed_git *find_base_packs(struct string_list *packs,
211 struct packed_git *p, *base = NULL;
213 for (p = get_all_packs(the_repository); p; p = p->next) {
217 if (p->pack_size >= limit)
218 string_list_append(packs, p->pack_name);
219 } else if (!base || base->pack_size < p->pack_size) {
225 string_list_append(packs, base->pack_name);
230 static int too_many_packs(void)
232 struct packed_git *p;
235 if (gc_auto_pack_limit <= 0)
238 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
244 * Perhaps check the size of the pack and count only
245 * very small ones here?
249 return gc_auto_pack_limit < cnt;
252 static uint64_t total_ram(void)
254 #if defined(HAVE_SYSINFO)
259 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
260 int64_t physical_memory;
265 # if defined(HW_MEMSIZE)
270 length = sizeof(int64_t);
271 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
272 return physical_memory;
273 #elif defined(GIT_WINDOWS_NATIVE)
274 MEMORYSTATUSEX memInfo;
276 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
277 if (GlobalMemoryStatusEx(&memInfo))
278 return memInfo.ullTotalPhys;
283 static uint64_t estimate_repack_memory(struct packed_git *pack)
285 unsigned long nr_objects = approximate_object_count();
286 size_t os_cache, heap;
288 if (!pack || !nr_objects)
292 * First we have to scan through at least one pack.
293 * Assume enough room in OS file cache to keep the entire pack
294 * or we may accidentally evict data of other processes from
297 os_cache = pack->pack_size + pack->index_size;
298 /* then pack-objects needs lots more for book keeping */
299 heap = sizeof(struct object_entry) * nr_objects;
301 * internal rev-list --all --objects takes up some memory too,
302 * let's say half of it is for blobs
304 heap += sizeof(struct blob) * nr_objects / 2;
306 * and the other half is for trees (commits and tags are
307 * usually insignificant)
309 heap += sizeof(struct tree) * nr_objects / 2;
310 /* and then obj_hash[], underestimated in fact */
311 heap += sizeof(struct object *) * nr_objects;
312 /* revindex is used also */
313 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
315 * read_sha1_file() (either at delta calculation phase, or
316 * writing phase) also fills up the delta base cache
318 heap += delta_base_cache_limit;
319 /* and of course pack-objects has its own delta cache */
320 heap += max_delta_cache_size;
322 return os_cache + heap;
325 static int keep_one_pack(struct string_list_item *item, void *data)
327 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
331 static void add_repack_all_option(struct string_list *keep_pack)
333 if (prune_expire && !strcmp(prune_expire, "now"))
334 strvec_push(&repack, "-a");
336 strvec_push(&repack, "-A");
338 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
342 for_each_string_list(keep_pack, keep_one_pack, NULL);
345 static void add_repack_incremental_option(void)
347 strvec_push(&repack, "--no-write-bitmap-index");
350 static int need_to_gc(void)
352 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
355 * Setting gc.auto to 0 or negative can disable the
358 if (gc_auto_threshold <= 0)
362 * If there are too many loose objects, but not too many
363 * packs, we run "repack -d -l". If there are too many packs,
364 * we run "repack -A -d -l". Otherwise we tell the caller
367 if (too_many_packs()) {
368 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
370 if (big_pack_threshold) {
371 find_base_packs(&keep_pack, big_pack_threshold);
372 if (keep_pack.nr >= gc_auto_pack_limit) {
373 big_pack_threshold = 0;
374 string_list_clear(&keep_pack, 0);
375 find_base_packs(&keep_pack, 0);
378 struct packed_git *p = find_base_packs(&keep_pack, 0);
379 uint64_t mem_have, mem_want;
381 mem_have = total_ram();
382 mem_want = estimate_repack_memory(p);
385 * Only allow 1/2 of memory for pack-objects, leave
386 * the rest for the OS and other processes in the
389 if (!mem_have || mem_want < mem_have / 2)
390 string_list_clear(&keep_pack, 0);
393 add_repack_all_option(&keep_pack);
394 string_list_clear(&keep_pack, 0);
395 } else if (too_many_loose_objects())
396 add_repack_incremental_option();
400 if (run_hooks("pre-auto-gc", &hook_opt)) {
401 run_hooks_opt_clear(&hook_opt);
404 run_hooks_opt_clear(&hook_opt);
408 /* return NULL on success, else hostname running the gc */
409 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
411 struct lock_file lock = LOCK_INIT;
412 char my_host[HOST_NAME_MAX + 1];
413 struct strbuf sb = STRBUF_INIT;
420 if (is_tempfile_active(pidfile))
424 if (xgethostname(my_host, sizeof(my_host)))
425 xsnprintf(my_host, sizeof(my_host), "unknown");
427 pidfile_path = git_pathdup("gc.pid");
428 fd = hold_lock_file_for_update(&lock, pidfile_path,
431 static char locking_host[HOST_NAME_MAX + 1];
432 static char *scan_fmt;
436 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
437 fp = fopen(pidfile_path, "r");
438 memset(locking_host, 0, sizeof(locking_host));
441 !fstat(fileno(fp), &st) &&
443 * 12 hour limit is very generous as gc should
444 * never take that long. On the other hand we
445 * don't really need a strict limit here,
446 * running gc --auto one day late is not a big
447 * problem. --force can be used in manual gc
448 * after the user verifies that no gc is
451 time(NULL) - st.st_mtime <= 12 * 3600 &&
452 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
453 /* be gentle to concurrent "gc" on remote hosts */
454 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
459 rollback_lock_file(&lock);
466 strbuf_addf(&sb, "%"PRIuMAX" %s",
467 (uintmax_t) getpid(), my_host);
468 write_in_full(fd, sb.buf, sb.len);
470 commit_lock_file(&lock);
471 pidfile = register_tempfile(pidfile_path);
477 * Returns 0 if there was no previous error and gc can proceed, 1 if
478 * gc should not proceed due to an error in the last run. Prints a
479 * message and returns -1 if an error occurred while reading gc.log
481 static int report_last_gc_error(void)
483 struct strbuf sb = STRBUF_INIT;
487 char *gc_log_path = git_pathdup("gc.log");
489 if (stat(gc_log_path, &st)) {
493 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
497 if (st.st_mtime < gc_log_expire_time)
500 len = strbuf_read_file(&sb, gc_log_path, 0);
502 ret = error_errno(_("cannot read '%s'"), gc_log_path);
505 * A previous gc failed. Report the error, and don't
506 * bother with an automatic gc run since it is likely
507 * to fail in the same way.
509 warning(_("The last gc run reported the following. "
510 "Please correct the root cause\n"
512 "Automatic cleanup will not be performed "
513 "until the file is removed.\n\n"
515 gc_log_path, sb.buf);
524 static void gc_before_repack(void)
527 * We may be called twice, as both the pre- and
528 * post-daemonized phases will call us, but running these
529 * commands more than once is pointless and wasteful.
535 if (pack_refs && maintenance_task_pack_refs(NULL))
536 die(FAILED_RUN, "pack-refs");
538 if (prune_reflogs && run_command_v_opt(reflog.v, RUN_GIT_CMD))
539 die(FAILED_RUN, reflog.v[0]);
542 int cmd_gc(int argc, const char **argv, const char *prefix)
551 int keep_largest_pack = -1;
554 struct option builtin_gc_options[] = {
555 OPT__QUIET(&quiet, N_("suppress progress reporting")),
556 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
557 N_("prune unreferenced objects"),
558 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
559 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
560 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
561 PARSE_OPT_NOCOMPLETE),
562 OPT_BOOL_F(0, "force", &force,
563 N_("force running gc even if there may be another gc running"),
564 PARSE_OPT_NOCOMPLETE),
565 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
566 N_("repack all other packs except the largest pack")),
570 if (argc == 2 && !strcmp(argv[1], "-h"))
571 usage_with_options(builtin_gc_usage, builtin_gc_options);
573 strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
574 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
575 strvec_pushl(&prune, "prune", "--expire", NULL);
576 strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
577 strvec_pushl(&rerere, "rerere", "gc", NULL);
579 /* default expiry time, overwritten in gc_config */
581 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
582 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
585 pack_refs = !is_bare_repository();
587 argc = parse_options(argc, argv, prefix, builtin_gc_options,
588 builtin_gc_usage, 0);
590 usage_with_options(builtin_gc_usage, builtin_gc_options);
592 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
593 die(_("failed to parse prune expiry value %s"), prune_expire);
596 strvec_push(&repack, "-f");
597 if (aggressive_depth > 0)
598 strvec_pushf(&repack, "--depth=%d", aggressive_depth);
599 if (aggressive_window > 0)
600 strvec_pushf(&repack, "--window=%d", aggressive_window);
603 strvec_push(&repack, "-q");
607 * Auto-gc should be least intrusive as possible.
613 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
615 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
616 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
619 int ret = report_last_gc_error();
621 /* an I/O error occurred, already reported */
624 /* Last gc --auto failed. Skip this one. */
627 if (lock_repo_for_gc(force, &pid))
629 gc_before_repack(); /* dies on failure */
630 delete_tempfile(&pidfile);
633 * failure to daemonize is ok, we'll continue
636 daemonized = !daemonize();
639 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
641 if (keep_largest_pack != -1) {
642 if (keep_largest_pack)
643 find_base_packs(&keep_pack, 0);
644 } else if (big_pack_threshold) {
645 find_base_packs(&keep_pack, big_pack_threshold);
648 add_repack_all_option(&keep_pack);
649 string_list_clear(&keep_pack, 0);
652 name = lock_repo_for_gc(force, &pid);
655 return 0; /* be quiet on --auto */
656 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
657 name, (uintmax_t)pid);
661 hold_lock_file_for_update(&log_lock,
664 dup2(get_lock_file_fd(&log_lock), 2);
665 sigchain_push_common(process_log_file_on_signal);
666 atexit(process_log_file_at_exit);
671 if (!repository_format_precious_objects) {
672 close_object_store(the_repository->objects);
673 if (run_command_v_opt(repack.v, RUN_GIT_CMD))
674 die(FAILED_RUN, repack.v[0]);
677 strvec_push(&prune, prune_expire);
679 strvec_push(&prune, "--no-progress");
680 if (has_promisor_remote())
682 "--exclude-promisor-objects");
683 if (run_command_v_opt(prune.v, RUN_GIT_CMD))
684 die(FAILED_RUN, prune.v[0]);
688 if (prune_worktrees_expire) {
689 strvec_push(&prune_worktrees, prune_worktrees_expire);
690 if (run_command_v_opt(prune_worktrees.v, RUN_GIT_CMD))
691 die(FAILED_RUN, prune_worktrees.v[0]);
694 if (run_command_v_opt(rerere.v, RUN_GIT_CMD))
695 die(FAILED_RUN, rerere.v[0]);
697 report_garbage = report_pack_garbage;
698 reprepare_packed_git(the_repository);
699 if (pack_garbage.nr > 0) {
700 close_object_store(the_repository->objects);
701 clean_pack_garbage();
704 prepare_repo_settings(the_repository);
705 if (the_repository->settings.gc_write_commit_graph == 1)
706 write_commit_graph_reachable(the_repository->objects->odb,
707 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
710 if (auto_gc && too_many_loose_objects())
711 warning(_("There are too many unreachable loose objects; "
712 "run 'git prune' to remove them."));
715 unlink(git_path("gc.log"));
720 static const char *const builtin_maintenance_run_usage[] = {
721 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
725 enum schedule_priority {
732 static enum schedule_priority parse_schedule(const char *value)
735 return SCHEDULE_NONE;
736 if (!strcasecmp(value, "hourly"))
737 return SCHEDULE_HOURLY;
738 if (!strcasecmp(value, "daily"))
739 return SCHEDULE_DAILY;
740 if (!strcasecmp(value, "weekly"))
741 return SCHEDULE_WEEKLY;
742 return SCHEDULE_NONE;
745 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
748 enum schedule_priority *priority = opt->value;
751 die(_("--no-schedule is not allowed"));
753 *priority = parse_schedule(arg);
756 die(_("unrecognized --schedule argument '%s'"), arg);
761 struct maintenance_run_opts {
764 enum schedule_priority schedule;
767 /* Remember to update object flag allocation in object.h */
770 struct cg_auto_data {
771 int num_not_in_graph;
775 static int dfs_on_ref(const char *refname,
776 const struct object_id *oid, int flags,
779 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
781 struct object_id peeled;
782 struct commit_list *stack = NULL;
783 struct commit *commit;
785 if (!peel_iterated_oid(oid, &peeled))
787 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
790 commit = lookup_commit(the_repository, oid);
793 if (parse_commit(commit) ||
794 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
797 data->num_not_in_graph++;
799 if (data->num_not_in_graph >= data->limit)
802 commit_list_append(commit, &stack);
804 while (!result && stack) {
805 struct commit_list *parent;
807 commit = pop_commit(&stack);
809 for (parent = commit->parents; parent; parent = parent->next) {
810 if (parse_commit(parent->item) ||
811 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
812 parent->item->object.flags & SEEN)
815 parent->item->object.flags |= SEEN;
816 data->num_not_in_graph++;
818 if (data->num_not_in_graph >= data->limit) {
823 commit_list_append(parent->item, &stack);
827 free_commit_list(stack);
831 static int should_write_commit_graph(void)
834 struct cg_auto_data data;
836 data.num_not_in_graph = 0;
838 git_config_get_int("maintenance.commit-graph.auto",
846 result = for_each_ref(dfs_on_ref, &data);
848 repo_clear_commit_marks(the_repository, SEEN);
853 static int run_write_commit_graph(struct maintenance_run_opts *opts)
855 struct child_process child = CHILD_PROCESS_INIT;
858 strvec_pushl(&child.args, "commit-graph", "write",
859 "--split", "--reachable", NULL);
862 strvec_push(&child.args, "--no-progress");
864 return !!run_command(&child);
867 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
869 prepare_repo_settings(the_repository);
870 if (!the_repository->settings.core_commit_graph)
873 close_object_store(the_repository->objects);
874 if (run_write_commit_graph(opts)) {
875 error(_("failed to write commit-graph"));
882 static int fetch_remote(struct remote *remote, void *cbdata)
884 struct maintenance_run_opts *opts = cbdata;
885 struct child_process child = CHILD_PROCESS_INIT;
887 if (remote->skip_default_update)
891 strvec_pushl(&child.args, "fetch", remote->name,
892 "--prefetch", "--prune", "--no-tags",
893 "--no-write-fetch-head", "--recurse-submodules=no",
897 strvec_push(&child.args, "--quiet");
899 return !!run_command(&child);
902 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
904 git_config_set_multivar_gently("log.excludedecoration",
907 CONFIG_FLAGS_FIXED_VALUE |
908 CONFIG_FLAGS_MULTI_REPLACE);
910 if (for_each_remote(fetch_remote, opts)) {
911 error(_("failed to prefetch remotes"));
918 static int maintenance_task_gc(struct maintenance_run_opts *opts)
920 struct child_process child = CHILD_PROCESS_INIT;
923 strvec_push(&child.args, "gc");
926 strvec_push(&child.args, "--auto");
928 strvec_push(&child.args, "--quiet");
930 strvec_push(&child.args, "--no-quiet");
932 close_object_store(the_repository->objects);
933 return run_command(&child);
936 static int prune_packed(struct maintenance_run_opts *opts)
938 struct child_process child = CHILD_PROCESS_INIT;
941 strvec_push(&child.args, "prune-packed");
944 strvec_push(&child.args, "--quiet");
946 return !!run_command(&child);
949 struct write_loose_object_data {
955 static int loose_object_auto_limit = 100;
957 static int loose_object_count(const struct object_id *oid,
961 int *count = (int*)data;
962 if (++(*count) >= loose_object_auto_limit)
967 static int loose_object_auto_condition(void)
971 git_config_get_int("maintenance.loose-objects.auto",
972 &loose_object_auto_limit);
974 if (!loose_object_auto_limit)
976 if (loose_object_auto_limit < 0)
979 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
984 static int bail_on_loose(const struct object_id *oid,
991 static int write_loose_object_to_stdin(const struct object_id *oid,
995 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
997 fprintf(d->in, "%s\n", oid_to_hex(oid));
999 return ++(d->count) > d->batch_size;
1002 static int pack_loose(struct maintenance_run_opts *opts)
1004 struct repository *r = the_repository;
1006 struct write_loose_object_data data;
1007 struct child_process pack_proc = CHILD_PROCESS_INIT;
1010 * Do not start pack-objects process
1011 * if there are no loose objects.
1013 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1018 pack_proc.git_cmd = 1;
1020 strvec_push(&pack_proc.args, "pack-objects");
1022 strvec_push(&pack_proc.args, "--quiet");
1023 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1027 if (start_command(&pack_proc)) {
1028 error(_("failed to start 'git pack-objects' process"));
1032 data.in = xfdopen(pack_proc.in, "w");
1034 data.batch_size = 50000;
1036 for_each_loose_file_in_objdir(r->objects->odb->path,
1037 write_loose_object_to_stdin,
1044 if (finish_command(&pack_proc)) {
1045 error(_("failed to finish 'git pack-objects' process"));
1052 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1054 return prune_packed(opts) || pack_loose(opts);
1057 static int incremental_repack_auto_condition(void)
1059 struct packed_git *p;
1061 int incremental_repack_auto_limit = 10;
1064 if (git_config_get_bool("core.multiPackIndex", &enabled) ||
1068 git_config_get_int("maintenance.incremental-repack.auto",
1069 &incremental_repack_auto_limit);
1071 if (!incremental_repack_auto_limit)
1073 if (incremental_repack_auto_limit < 0)
1076 for (p = get_packed_git(the_repository);
1077 count < incremental_repack_auto_limit && p;
1079 if (!p->multi_pack_index)
1083 return count >= incremental_repack_auto_limit;
1086 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1088 struct child_process child = CHILD_PROCESS_INIT;
1091 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1094 strvec_push(&child.args, "--no-progress");
1096 if (run_command(&child))
1097 return error(_("failed to write multi-pack-index"));
1102 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1104 struct child_process child = CHILD_PROCESS_INIT;
1107 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1110 strvec_push(&child.args, "--no-progress");
1112 close_object_store(the_repository->objects);
1114 if (run_command(&child))
1115 return error(_("'git multi-pack-index expire' failed"));
1120 #define TWO_GIGABYTES (INT32_MAX)
1122 static off_t get_auto_pack_size(void)
1125 * The "auto" value is special: we optimize for
1126 * one large pack-file (i.e. from a clone) and
1127 * expect the rest to be small and they can be
1130 * The strategy we select here is to select a
1131 * size that is one more than the second largest
1132 * pack-file. This ensures that we will repack
1133 * at least two packs if there are three or more
1137 off_t second_largest_size = 0;
1139 struct packed_git *p;
1140 struct repository *r = the_repository;
1142 reprepare_packed_git(r);
1143 for (p = get_all_packs(r); p; p = p->next) {
1144 if (p->pack_size > max_size) {
1145 second_largest_size = max_size;
1146 max_size = p->pack_size;
1147 } else if (p->pack_size > second_largest_size)
1148 second_largest_size = p->pack_size;
1151 result_size = second_largest_size + 1;
1153 /* But limit ourselves to a batch size of 2g */
1154 if (result_size > TWO_GIGABYTES)
1155 result_size = TWO_GIGABYTES;
1160 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1162 struct child_process child = CHILD_PROCESS_INIT;
1165 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1168 strvec_push(&child.args, "--no-progress");
1170 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1171 (uintmax_t)get_auto_pack_size());
1173 close_object_store(the_repository->objects);
1175 if (run_command(&child))
1176 return error(_("'git multi-pack-index repack' failed"));
1181 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1183 prepare_repo_settings(the_repository);
1184 if (!the_repository->settings.core_multi_pack_index) {
1185 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1189 if (multi_pack_index_write(opts))
1191 if (multi_pack_index_expire(opts))
1193 if (multi_pack_index_repack(opts))
1198 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1201 * An auto condition function returns 1 if the task should run
1202 * and 0 if the task should NOT run. See needs_to_gc() for an
1205 typedef int maintenance_auto_fn(void);
1207 struct maintenance_task {
1209 maintenance_task_fn *fn;
1210 maintenance_auto_fn *auto_condition;
1213 enum schedule_priority schedule;
1215 /* -1 if not selected. */
1219 enum maintenance_task_label {
1222 TASK_INCREMENTAL_REPACK,
1227 /* Leave as final value */
1231 static struct maintenance_task tasks[] = {
1234 maintenance_task_prefetch,
1236 [TASK_LOOSE_OBJECTS] = {
1238 maintenance_task_loose_objects,
1239 loose_object_auto_condition,
1241 [TASK_INCREMENTAL_REPACK] = {
1242 "incremental-repack",
1243 maintenance_task_incremental_repack,
1244 incremental_repack_auto_condition,
1248 maintenance_task_gc,
1252 [TASK_COMMIT_GRAPH] = {
1254 maintenance_task_commit_graph,
1255 should_write_commit_graph,
1257 [TASK_PACK_REFS] = {
1259 maintenance_task_pack_refs,
1264 static int compare_tasks_by_selection(const void *a_, const void *b_)
1266 const struct maintenance_task *a = a_;
1267 const struct maintenance_task *b = b_;
1269 return b->selected_order - a->selected_order;
1272 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1274 int i, found_selected = 0;
1276 struct lock_file lk;
1277 struct repository *r = the_repository;
1278 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1280 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1282 * Another maintenance command is running.
1284 * If --auto was provided, then it is likely due to a
1285 * recursive process stack. Do not report an error in
1288 if (!opts->auto_flag && !opts->quiet)
1289 warning(_("lock file '%s' exists, skipping maintenance"),
1296 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1297 found_selected = tasks[i].selected_order >= 0;
1300 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1302 for (i = 0; i < TASK__COUNT; i++) {
1303 if (found_selected && tasks[i].selected_order < 0)
1306 if (!found_selected && !tasks[i].enabled)
1309 if (opts->auto_flag &&
1310 (!tasks[i].auto_condition ||
1311 !tasks[i].auto_condition()))
1314 if (opts->schedule && tasks[i].schedule < opts->schedule)
1317 trace2_region_enter("maintenance", tasks[i].name, r);
1318 if (tasks[i].fn(opts)) {
1319 error(_("task '%s' failed"), tasks[i].name);
1322 trace2_region_leave("maintenance", tasks[i].name, r);
1325 rollback_lock_file(&lk);
1329 static void initialize_maintenance_strategy(void)
1333 if (git_config_get_string("maintenance.strategy", &config_str))
1336 if (!strcasecmp(config_str, "incremental")) {
1337 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1338 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1339 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1340 tasks[TASK_PREFETCH].enabled = 1;
1341 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1342 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1343 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1344 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1345 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1346 tasks[TASK_PACK_REFS].enabled = 1;
1347 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1351 static void initialize_task_config(int schedule)
1354 struct strbuf config_name = STRBUF_INIT;
1358 initialize_maintenance_strategy();
1360 for (i = 0; i < TASK__COUNT; i++) {
1364 strbuf_reset(&config_name);
1365 strbuf_addf(&config_name, "maintenance.%s.enabled",
1368 if (!git_config_get_bool(config_name.buf, &config_value))
1369 tasks[i].enabled = config_value;
1371 strbuf_reset(&config_name);
1372 strbuf_addf(&config_name, "maintenance.%s.schedule",
1375 if (!git_config_get_string(config_name.buf, &config_str)) {
1376 tasks[i].schedule = parse_schedule(config_str);
1381 strbuf_release(&config_name);
1384 static int task_option_parse(const struct option *opt,
1385 const char *arg, int unset)
1387 int i, num_selected = 0;
1388 struct maintenance_task *task = NULL;
1390 BUG_ON_OPT_NEG(unset);
1392 for (i = 0; i < TASK__COUNT; i++) {
1393 if (tasks[i].selected_order >= 0)
1395 if (!strcasecmp(tasks[i].name, arg)) {
1401 error(_("'%s' is not a valid task"), arg);
1405 if (task->selected_order >= 0) {
1406 error(_("task '%s' cannot be selected multiple times"), arg);
1410 task->selected_order = num_selected + 1;
1415 static int maintenance_run(int argc, const char **argv, const char *prefix)
1418 struct maintenance_run_opts opts;
1419 struct option builtin_maintenance_run_options[] = {
1420 OPT_BOOL(0, "auto", &opts.auto_flag,
1421 N_("run tasks based on the state of the repository")),
1422 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1423 N_("run tasks based on frequency"),
1424 maintenance_opt_schedule),
1425 OPT_BOOL(0, "quiet", &opts.quiet,
1426 N_("do not report progress or other information over stderr")),
1427 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1428 N_("run a specific task"),
1429 PARSE_OPT_NONEG, task_option_parse),
1432 memset(&opts, 0, sizeof(opts));
1434 opts.quiet = !isatty(2);
1436 for (i = 0; i < TASK__COUNT; i++)
1437 tasks[i].selected_order = -1;
1439 argc = parse_options(argc, argv, prefix,
1440 builtin_maintenance_run_options,
1441 builtin_maintenance_run_usage,
1442 PARSE_OPT_STOP_AT_NON_OPTION);
1444 if (opts.auto_flag && opts.schedule)
1445 die(_("use at most one of --auto and --schedule=<frequency>"));
1447 initialize_task_config(opts.schedule);
1450 usage_with_options(builtin_maintenance_run_usage,
1451 builtin_maintenance_run_options);
1452 return maintenance_run_tasks(&opts);
1455 static char *get_maintpath(void)
1457 struct strbuf sb = STRBUF_INIT;
1458 const char *p = the_repository->worktree ?
1459 the_repository->worktree : the_repository->gitdir;
1461 strbuf_realpath(&sb, p, 1);
1462 return strbuf_detach(&sb, NULL);
1465 static int maintenance_register(void)
1469 struct child_process config_set = CHILD_PROCESS_INIT;
1470 struct child_process config_get = CHILD_PROCESS_INIT;
1471 char *maintpath = get_maintpath();
1473 /* Disable foreground maintenance */
1474 git_config_set("maintenance.auto", "false");
1476 /* Set maintenance strategy, if unset */
1477 if (!git_config_get_string("maintenance.strategy", &config_value))
1480 git_config_set("maintenance.strategy", "incremental");
1482 config_get.git_cmd = 1;
1483 strvec_pushl(&config_get.args, "config", "--global", "--get",
1484 "--fixed-value", "maintenance.repo", maintpath, NULL);
1485 config_get.out = -1;
1487 if (start_command(&config_get)) {
1488 rc = error(_("failed to run 'git config'"));
1492 /* We already have this value in our config! */
1493 if (!finish_command(&config_get)) {
1498 config_set.git_cmd = 1;
1499 strvec_pushl(&config_set.args, "config", "--add", "--global", "maintenance.repo",
1502 rc = run_command(&config_set);
1509 static int maintenance_unregister(void)
1512 struct child_process config_unset = CHILD_PROCESS_INIT;
1513 char *maintpath = get_maintpath();
1515 config_unset.git_cmd = 1;
1516 strvec_pushl(&config_unset.args, "config", "--global", "--unset",
1517 "--fixed-value", "maintenance.repo", maintpath, NULL);
1519 rc = run_command(&config_unset);
1524 static const char *get_frequency(enum schedule_priority schedule)
1527 case SCHEDULE_HOURLY:
1529 case SCHEDULE_DAILY:
1531 case SCHEDULE_WEEKLY:
1534 BUG("invalid schedule %d", schedule);
1538 static int get_schedule_cmd(const char **cmd, int *is_available)
1541 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1549 for (item = testing;;) {
1551 char *end_item = strchr(item, ',');
1555 sep = strchr(item, ':');
1557 die("GIT_TEST_MAINT_SCHEDULER unparseable: %s", testing);
1560 if (!strcmp(*cmd, item)) {
1570 item = end_item + 1;
1577 static int is_launchctl_available(void)
1579 const char *cmd = "launchctl";
1581 if (get_schedule_cmd(&cmd, &is_available))
1582 return is_available;
1591 static char *launchctl_service_name(const char *frequency)
1593 struct strbuf label = STRBUF_INIT;
1594 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1595 return strbuf_detach(&label, NULL);
1598 static char *launchctl_service_filename(const char *name)
1601 struct strbuf filename = STRBUF_INIT;
1602 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1604 expanded = expand_user_path(filename.buf, 1);
1606 die(_("failed to expand path '%s'"), filename.buf);
1608 strbuf_release(&filename);
1612 static char *launchctl_get_uid(void)
1614 return xstrfmt("gui/%d", getuid());
1617 static int launchctl_boot_plist(int enable, const char *filename)
1619 const char *cmd = "launchctl";
1621 struct child_process child = CHILD_PROCESS_INIT;
1622 char *uid = launchctl_get_uid();
1624 get_schedule_cmd(&cmd, NULL);
1625 strvec_split(&child.args, cmd);
1626 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1629 child.no_stderr = 1;
1630 child.no_stdout = 1;
1632 if (start_command(&child))
1633 die(_("failed to start launchctl"));
1635 result = finish_command(&child);
1641 static int launchctl_remove_plist(enum schedule_priority schedule)
1643 const char *frequency = get_frequency(schedule);
1644 char *name = launchctl_service_name(frequency);
1645 char *filename = launchctl_service_filename(name);
1646 int result = launchctl_boot_plist(0, filename);
1653 static int launchctl_remove_plists(void)
1655 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1656 launchctl_remove_plist(SCHEDULE_DAILY) ||
1657 launchctl_remove_plist(SCHEDULE_WEEKLY);
1660 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1664 const char *preamble, *repeat;
1665 const char *frequency = get_frequency(schedule);
1666 char *name = launchctl_service_name(frequency);
1667 char *filename = launchctl_service_filename(name);
1669 if (safe_create_leading_directories(filename))
1670 die(_("failed to create directories for '%s'"), filename);
1671 plist = xfopen(filename, "w");
1673 preamble = "<?xml version=\"1.0\"?>\n"
1674 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1675 "<plist version=\"1.0\">"
1677 "<key>Label</key><string>%s</string>\n"
1678 "<key>ProgramArguments</key>\n"
1680 "<string>%s/git</string>\n"
1681 "<string>--exec-path=%s</string>\n"
1682 "<string>for-each-repo</string>\n"
1683 "<string>--config=maintenance.repo</string>\n"
1684 "<string>maintenance</string>\n"
1685 "<string>run</string>\n"
1686 "<string>--schedule=%s</string>\n"
1688 "<key>StartCalendarInterval</key>\n"
1690 fprintf(plist, preamble, name, exec_path, exec_path, frequency);
1693 case SCHEDULE_HOURLY:
1695 "<key>Hour</key><integer>%d</integer>\n"
1696 "<key>Minute</key><integer>0</integer>\n"
1698 for (i = 1; i <= 23; i++)
1699 fprintf(plist, repeat, i);
1702 case SCHEDULE_DAILY:
1704 "<key>Day</key><integer>%d</integer>\n"
1705 "<key>Hour</key><integer>0</integer>\n"
1706 "<key>Minute</key><integer>0</integer>\n"
1708 for (i = 1; i <= 6; i++)
1709 fprintf(plist, repeat, i);
1712 case SCHEDULE_WEEKLY:
1715 "<key>Day</key><integer>0</integer>\n"
1716 "<key>Hour</key><integer>0</integer>\n"
1717 "<key>Minute</key><integer>0</integer>\n"
1725 fprintf(plist, "</array>\n</dict>\n</plist>\n");
1728 /* bootout might fail if not already running, so ignore */
1729 launchctl_boot_plist(0, filename);
1730 if (launchctl_boot_plist(1, filename))
1731 die(_("failed to bootstrap service %s"), filename);
1738 static int launchctl_add_plists(void)
1740 const char *exec_path = git_exec_path();
1742 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1743 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1744 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1747 static int launchctl_update_schedule(int run_maintenance, int fd)
1749 if (run_maintenance)
1750 return launchctl_add_plists();
1752 return launchctl_remove_plists();
1755 static int is_schtasks_available(void)
1757 const char *cmd = "schtasks";
1759 if (get_schedule_cmd(&cmd, &is_available))
1760 return is_available;
1762 #ifdef GIT_WINDOWS_NATIVE
1769 static char *schtasks_task_name(const char *frequency)
1771 struct strbuf label = STRBUF_INIT;
1772 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1773 return strbuf_detach(&label, NULL);
1776 static int schtasks_remove_task(enum schedule_priority schedule)
1778 const char *cmd = "schtasks";
1780 struct strvec args = STRVEC_INIT;
1781 const char *frequency = get_frequency(schedule);
1782 char *name = schtasks_task_name(frequency);
1784 get_schedule_cmd(&cmd, NULL);
1785 strvec_split(&args, cmd);
1786 strvec_pushl(&args, "/delete", "/tn", name, "/f", NULL);
1788 result = run_command_v_opt(args.v, 0);
1790 strvec_clear(&args);
1795 static int schtasks_remove_tasks(void)
1797 return schtasks_remove_task(SCHEDULE_HOURLY) ||
1798 schtasks_remove_task(SCHEDULE_DAILY) ||
1799 schtasks_remove_task(SCHEDULE_WEEKLY);
1802 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
1804 const char *cmd = "schtasks";
1806 struct child_process child = CHILD_PROCESS_INIT;
1808 struct tempfile *tfile;
1809 const char *frequency = get_frequency(schedule);
1810 char *name = schtasks_task_name(frequency);
1811 struct strbuf tfilename = STRBUF_INIT;
1813 get_schedule_cmd(&cmd, NULL);
1815 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1816 get_git_common_dir(), frequency);
1817 tfile = xmks_tempfile(tfilename.buf);
1818 strbuf_release(&tfilename);
1820 if (!fdopen_tempfile(tfile, "w"))
1821 die(_("failed to create temp xml file"));
1823 xml = "<?xml version=\"1.0\" ?>\n"
1824 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1826 "<CalendarTrigger>\n";
1827 fputs(xml, tfile->fp);
1830 case SCHEDULE_HOURLY:
1832 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1833 "<Enabled>true</Enabled>\n"
1835 "<DaysInterval>1</DaysInterval>\n"
1836 "</ScheduleByDay>\n"
1838 "<Interval>PT1H</Interval>\n"
1839 "<Duration>PT23H</Duration>\n"
1840 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1844 case SCHEDULE_DAILY:
1846 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1847 "<Enabled>true</Enabled>\n"
1848 "<ScheduleByWeek>\n"
1857 "<WeeksInterval>1</WeeksInterval>\n"
1858 "</ScheduleByWeek>\n");
1861 case SCHEDULE_WEEKLY:
1863 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1864 "<Enabled>true</Enabled>\n"
1865 "<ScheduleByWeek>\n"
1869 "<WeeksInterval>1</WeeksInterval>\n"
1870 "</ScheduleByWeek>\n");
1877 xml = "</CalendarTrigger>\n"
1880 "<Principal id=\"Author\">\n"
1881 "<LogonType>InteractiveToken</LogonType>\n"
1882 "<RunLevel>LeastPrivilege</RunLevel>\n"
1886 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1887 "<Enabled>true</Enabled>\n"
1888 "<Hidden>true</Hidden>\n"
1889 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1890 "<WakeToRun>false</WakeToRun>\n"
1891 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1892 "<Priority>7</Priority>\n"
1894 "<Actions Context=\"Author\">\n"
1896 "<Command>\"%s\\git.exe\"</Command>\n"
1897 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1901 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
1902 strvec_split(&child.args, cmd);
1903 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
1904 get_tempfile_path(tfile), NULL);
1905 close_tempfile_gently(tfile);
1907 child.no_stdout = 1;
1908 child.no_stderr = 1;
1910 if (start_command(&child))
1911 die(_("failed to start schtasks"));
1912 result = finish_command(&child);
1914 delete_tempfile(&tfile);
1919 static int schtasks_schedule_tasks(void)
1921 const char *exec_path = git_exec_path();
1923 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
1924 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
1925 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
1928 static int schtasks_update_schedule(int run_maintenance, int fd)
1930 if (run_maintenance)
1931 return schtasks_schedule_tasks();
1933 return schtasks_remove_tasks();
1936 static int is_crontab_available(void)
1938 const char *cmd = "crontab";
1940 struct child_process child = CHILD_PROCESS_INIT;
1942 if (get_schedule_cmd(&cmd, &is_available) && !is_available)
1945 strvec_split(&child.args, cmd);
1946 strvec_push(&child.args, "-l");
1948 child.no_stdout = 1;
1949 child.no_stderr = 1;
1950 child.silent_exec_failure = 1;
1952 if (start_command(&child))
1954 /* Ignore exit code, as an empty crontab will return error. */
1955 finish_command(&child);
1959 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
1960 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
1962 static int crontab_update_schedule(int run_maintenance, int fd)
1964 const char *cmd = "crontab";
1966 int in_old_region = 0;
1967 struct child_process crontab_list = CHILD_PROCESS_INIT;
1968 struct child_process crontab_edit = CHILD_PROCESS_INIT;
1969 FILE *cron_list, *cron_in;
1970 struct strbuf line = STRBUF_INIT;
1972 get_schedule_cmd(&cmd, NULL);
1973 strvec_split(&crontab_list.args, cmd);
1974 strvec_push(&crontab_list.args, "-l");
1975 crontab_list.in = -1;
1976 crontab_list.out = dup(fd);
1977 crontab_list.git_cmd = 0;
1979 if (start_command(&crontab_list))
1980 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
1982 /* Ignore exit code, as an empty crontab will return error. */
1983 finish_command(&crontab_list);
1986 * Read from the .lock file, filtering out the old
1987 * schedule while appending the new schedule.
1989 cron_list = fdopen(fd, "r");
1992 strvec_split(&crontab_edit.args, cmd);
1993 crontab_edit.in = -1;
1994 crontab_edit.git_cmd = 0;
1996 if (start_command(&crontab_edit))
1997 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
1999 cron_in = fdopen(crontab_edit.in, "w");
2001 result = error(_("failed to open stdin of 'crontab'"));
2005 while (!strbuf_getline_lf(&line, cron_list)) {
2006 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2008 else if (in_old_region && !strcmp(line.buf, END_LINE))
2010 else if (!in_old_region)
2011 fprintf(cron_in, "%s\n", line.buf);
2013 strbuf_release(&line);
2015 if (run_maintenance) {
2016 struct strbuf line_format = STRBUF_INIT;
2017 const char *exec_path = git_exec_path();
2019 fprintf(cron_in, "%s\n", BEGIN_LINE);
2021 "# The following schedule was created by Git\n");
2022 fprintf(cron_in, "# Any edits made in this region might be\n");
2024 "# replaced in the future by a Git command.\n\n");
2026 strbuf_addf(&line_format,
2027 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2028 exec_path, exec_path);
2029 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2030 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2031 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2032 strbuf_release(&line_format);
2034 fprintf(cron_in, "\n%s\n", END_LINE);
2039 close(crontab_edit.in);
2042 if (finish_command(&crontab_edit))
2043 result = error(_("'crontab' died"));
2051 static int real_is_systemd_timer_available(void)
2053 struct child_process child = CHILD_PROCESS_INIT;
2055 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2057 child.no_stdout = 1;
2058 child.no_stderr = 1;
2059 child.silent_exec_failure = 1;
2061 if (start_command(&child))
2063 if (finish_command(&child))
2070 static int real_is_systemd_timer_available(void)
2077 static int is_systemd_timer_available(void)
2079 const char *cmd = "systemctl";
2082 if (get_schedule_cmd(&cmd, &is_available))
2083 return is_available;
2085 return real_is_systemd_timer_available();
2088 static char *xdg_config_home_systemd(const char *filename)
2090 return xdg_config_home_for("systemd/user", filename);
2093 static int systemd_timer_enable_unit(int enable,
2094 enum schedule_priority schedule)
2096 const char *cmd = "systemctl";
2097 struct child_process child = CHILD_PROCESS_INIT;
2098 const char *frequency = get_frequency(schedule);
2101 * Disabling the systemd unit while it is already disabled makes
2102 * systemctl print an error.
2103 * Let's ignore it since it means we already are in the expected state:
2104 * the unit is disabled.
2106 * On the other hand, enabling a systemd unit which is already enabled
2107 * produces no error.
2110 child.no_stderr = 1;
2112 get_schedule_cmd(&cmd, NULL);
2113 strvec_split(&child.args, cmd);
2114 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2116 strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2118 if (start_command(&child))
2119 return error(_("failed to start systemctl"));
2120 if (finish_command(&child))
2122 * Disabling an already disabled systemd unit makes
2124 * Let's ignore this failure.
2126 * Enabling an enabled systemd unit doesn't fail.
2129 return error(_("failed to run systemctl"));
2133 static int systemd_timer_delete_unit_templates(void)
2136 char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2137 if (unlink(filename) && !is_missing_file_error(errno))
2138 ret = error_errno(_("failed to delete '%s'"), filename);
2139 FREE_AND_NULL(filename);
2141 filename = xdg_config_home_systemd("git-maintenance@.service");
2142 if (unlink(filename) && !is_missing_file_error(errno))
2143 ret = error_errno(_("failed to delete '%s'"), filename);
2149 static int systemd_timer_delete_units(void)
2151 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2152 systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2153 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2154 systemd_timer_delete_unit_templates();
2157 static int systemd_timer_write_unit_templates(const char *exec_path)
2163 filename = xdg_config_home_systemd("git-maintenance@.timer");
2164 if (safe_create_leading_directories(filename)) {
2165 error(_("failed to create directories for '%s'"), filename);
2168 file = fopen_or_warn(filename, "w");
2172 unit = "# This file was created and is maintained by Git.\n"
2173 "# Any edits made in this file might be replaced in the future\n"
2174 "# by a Git command.\n"
2177 "Description=Optimize Git repositories data\n"
2184 "WantedBy=timers.target\n";
2185 if (fputs(unit, file) == EOF) {
2186 error(_("failed to write to '%s'"), filename);
2190 if (fclose(file) == EOF) {
2191 error_errno(_("failed to flush '%s'"), filename);
2196 filename = xdg_config_home_systemd("git-maintenance@.service");
2197 file = fopen_or_warn(filename, "w");
2201 unit = "# This file was created and is maintained by Git.\n"
2202 "# Any edits made in this file might be replaced in the future\n"
2203 "# by a Git command.\n"
2206 "Description=Optimize Git repositories data\n"
2210 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2211 "LockPersonality=yes\n"
2212 "MemoryDenyWriteExecute=yes\n"
2213 "NoNewPrivileges=yes\n"
2214 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2215 "RestrictNamespaces=yes\n"
2216 "RestrictRealtime=yes\n"
2217 "RestrictSUIDSGID=yes\n"
2218 "SystemCallArchitectures=native\n"
2219 "SystemCallFilter=@system-service\n";
2220 if (fprintf(file, unit, exec_path, exec_path) < 0) {
2221 error(_("failed to write to '%s'"), filename);
2225 if (fclose(file) == EOF) {
2226 error_errno(_("failed to flush '%s'"), filename);
2234 systemd_timer_delete_unit_templates();
2238 static int systemd_timer_setup_units(void)
2240 const char *exec_path = git_exec_path();
2242 int ret = systemd_timer_write_unit_templates(exec_path) ||
2243 systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2244 systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2245 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2247 systemd_timer_delete_units();
2251 static int systemd_timer_update_schedule(int run_maintenance, int fd)
2253 if (run_maintenance)
2254 return systemd_timer_setup_units();
2256 return systemd_timer_delete_units();
2260 SCHEDULER_INVALID = -1,
2264 SCHEDULER_LAUNCHCTL,
2268 static const struct {
2270 int (*is_available)(void);
2271 int (*update_schedule)(int run_maintenance, int fd);
2272 } scheduler_fn[] = {
2273 [SCHEDULER_CRON] = {
2275 .is_available = is_crontab_available,
2276 .update_schedule = crontab_update_schedule,
2278 [SCHEDULER_SYSTEMD] = {
2279 .name = "systemctl",
2280 .is_available = is_systemd_timer_available,
2281 .update_schedule = systemd_timer_update_schedule,
2283 [SCHEDULER_LAUNCHCTL] = {
2284 .name = "launchctl",
2285 .is_available = is_launchctl_available,
2286 .update_schedule = launchctl_update_schedule,
2288 [SCHEDULER_SCHTASKS] = {
2290 .is_available = is_schtasks_available,
2291 .update_schedule = schtasks_update_schedule,
2295 static enum scheduler parse_scheduler(const char *value)
2298 return SCHEDULER_INVALID;
2299 else if (!strcasecmp(value, "auto"))
2300 return SCHEDULER_AUTO;
2301 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2302 return SCHEDULER_CRON;
2303 else if (!strcasecmp(value, "systemd") ||
2304 !strcasecmp(value, "systemd-timer"))
2305 return SCHEDULER_SYSTEMD;
2306 else if (!strcasecmp(value, "launchctl"))
2307 return SCHEDULER_LAUNCHCTL;
2308 else if (!strcasecmp(value, "schtasks"))
2309 return SCHEDULER_SCHTASKS;
2311 return SCHEDULER_INVALID;
2314 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2317 enum scheduler *scheduler = opt->value;
2319 BUG_ON_OPT_NEG(unset);
2321 *scheduler = parse_scheduler(arg);
2322 if (*scheduler == SCHEDULER_INVALID)
2323 return error(_("unrecognized --scheduler argument '%s'"), arg);
2327 struct maintenance_start_opts {
2328 enum scheduler scheduler;
2331 static void resolve_auto_scheduler(enum scheduler *scheduler)
2333 if (*scheduler != SCHEDULER_AUTO)
2336 #if defined(__APPLE__)
2337 *scheduler = SCHEDULER_LAUNCHCTL;
2340 #elif defined(GIT_WINDOWS_NATIVE)
2341 *scheduler = SCHEDULER_SCHTASKS;
2344 #elif defined(__linux__)
2345 if (is_systemd_timer_available())
2346 *scheduler = SCHEDULER_SYSTEMD;
2347 else if (is_crontab_available())
2348 *scheduler = SCHEDULER_CRON;
2350 die(_("neither systemd timers nor crontab are available"));
2354 *scheduler = SCHEDULER_CRON;
2359 static void validate_scheduler(enum scheduler scheduler)
2361 if (scheduler == SCHEDULER_INVALID)
2362 BUG("invalid scheduler");
2363 if (scheduler == SCHEDULER_AUTO)
2364 BUG("resolve_auto_scheduler should have been called before");
2366 if (!scheduler_fn[scheduler].is_available())
2367 die(_("%s scheduler is not available"),
2368 scheduler_fn[scheduler].name);
2371 static int update_background_schedule(const struct maintenance_start_opts *opts,
2376 struct lock_file lk;
2377 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2379 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2381 return error(_("another process is scheduling background maintenance"));
2384 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2385 if (enable && opts->scheduler == i)
2387 if (!scheduler_fn[i].is_available())
2389 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2393 result = scheduler_fn[opts->scheduler].update_schedule(
2394 1, get_lock_file_fd(&lk));
2396 rollback_lock_file(&lk);
2402 static const char *const builtin_maintenance_start_usage[] = {
2403 N_("git maintenance start [--scheduler=<scheduler>]"),
2407 static int maintenance_start(int argc, const char **argv, const char *prefix)
2409 struct maintenance_start_opts opts = { 0 };
2410 struct option options[] = {
2412 0, "scheduler", &opts.scheduler, N_("scheduler"),
2413 N_("scheduler to use to trigger git maintenance run"),
2414 PARSE_OPT_NONEG, maintenance_opt_scheduler),
2418 argc = parse_options(argc, argv, prefix, options,
2419 builtin_maintenance_start_usage, 0);
2421 usage_with_options(builtin_maintenance_start_usage, options);
2423 resolve_auto_scheduler(&opts.scheduler);
2424 validate_scheduler(opts.scheduler);
2426 if (maintenance_register())
2427 warning(_("failed to add repo to global config"));
2428 return update_background_schedule(&opts, 1);
2431 static int maintenance_stop(void)
2433 return update_background_schedule(NULL, 0);
2436 static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
2438 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2441 (argc == 2 && !strcmp(argv[1], "-h")))
2442 usage(builtin_maintenance_usage);
2444 if (!strcmp(argv[1], "run"))
2445 return maintenance_run(argc - 1, argv + 1, prefix);
2446 if (!strcmp(argv[1], "start"))
2447 return maintenance_start(argc - 1, argv + 1, prefix);
2448 if (!strcmp(argv[1], "stop"))
2449 return maintenance_stop();
2450 if (!strcmp(argv[1], "register"))
2451 return maintenance_register();
2452 if (!strcmp(argv[1], "unregister"))
2453 return maintenance_unregister();
2455 die(_("invalid subcommand: %s"), argv[1]);