interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / builtin / gc.c

3147 lines · 84639 bytes Raw Blame History
1/*
2 * git gc builtin command
3 *
4 * Cleanup unreachable files and optimize the repository.
5 *
6 * Copyright (c) 2007 James Bowes
7 *
8 * Based on git-gc.sh, which is
9 *
10 * Copyright (c) 2006 Shawn O. Pearce
11 */
12
13#define USE_THE_REPOSITORY_VARIABLE
14#define DISABLE_SIGN_COMPARE_WARNINGS
15
16#include "builtin.h"
17#include "abspath.h"
18#include "date.h"
19#include "dir.h"
20#include "environment.h"
21#include "hex.h"
22#include "config.h"
23#include "tempfile.h"
24#include "lockfile.h"
25#include "parse-options.h"
26#include "run-command.h"
27#include "sigchain.h"
28#include "strvec.h"
29#include "commit.h"
30#include "commit-graph.h"
31#include "packfile.h"
32#include "object-file.h"
33#include "odb.h"
34#include "path.h"
35#include "reflog.h"
36#include "rerere.h"
37#include "revision.h"
38#include "refs.h"
39#include "remote.h"
40#include "exec-cmd.h"
41#include "gettext.h"
42#include "hook.h"
43#include "setup.h"
44#include "trace2.h"
45#include "worktree.h"
46
47#define FAILED_RUN "failed to run %s"
48
49static const char * const builtin_gc_usage[] = {
50 N_("git gc [<options>]"),
51 NULL
52};
53
54static timestamp_t gc_log_expire_time;
55static struct tempfile *pidfile;
56static struct lock_file log_lock;
57static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
58
59static void clean_pack_garbage(void)
60{
61 int i;
62 for (i = 0; i < pack_garbage.nr; i++)
63 unlink_or_warn(pack_garbage.items[i].string);
64 string_list_clear(&pack_garbage, 0);
65}
66
67static void report_pack_garbage(unsigned seen_bits, const char *path)
68{
69 if (seen_bits == PACKDIR_FILE_IDX)
70 string_list_append(&pack_garbage, path);
71}
72
73static void process_log_file(void)
74{
75 struct stat st;
76 if (fstat(get_lock_file_fd(&log_lock), &st)) {
77 /*
78 * Perhaps there was an i/o error or another
79 * unlikely situation. Try to make a note of
80 * this in gc.log along with any existing
81 * messages.
82 */
83 int saved_errno = errno;
84 fprintf(stderr, _("Failed to fstat %s: %s"),
85 get_lock_file_path(&log_lock),
86 strerror(saved_errno));
87 fflush(stderr);
88 commit_lock_file(&log_lock);
89 errno = saved_errno;
90 } else if (st.st_size) {
91 /* There was some error recorded in the lock file */
92 commit_lock_file(&log_lock);
93 } else {
94 char *path = repo_git_path(the_repository, "gc.log");
95 /* No error, clean up any old gc.log */
96 unlink(path);
97 rollback_lock_file(&log_lock);
98 free(path);
99 }
100}
101
102static void process_log_file_at_exit(void)
103{
104 fflush(stderr);
105 process_log_file();
106}
107
108static int gc_config_is_timestamp_never(const char *var)
109{
110 const char *value;
111 timestamp_t expire;
112
113 if (!repo_config_get_value(the_repository, var, &value) && value) {
114 if (parse_expiry_date(value, &expire))
115 die(_("failed to parse '%s' value '%s'"), var, value);
116 return expire == 0;
117 }
118 return 0;
119}
120
121struct gc_config {
122 int pack_refs;
123 int prune_reflogs;
124 int cruft_packs;
125 unsigned long max_cruft_size;
126 int aggressive_depth;
127 int aggressive_window;
128 int detach_auto;
129 char *gc_log_expire;
130 char *prune_expire;
131 char *prune_worktrees_expire;
132 char *repack_expire_to;
133};
134
135#define GC_CONFIG_INIT { \
136 .pack_refs = 1, \
137 .prune_reflogs = 1, \
138 .cruft_packs = 1, \
139 .aggressive_depth = 50, \
140 .aggressive_window = 250, \
141 .detach_auto = 1, \
142 .gc_log_expire = xstrdup("1.day.ago"), \
143 .prune_expire = xstrdup("2.weeks.ago"), \
144 .prune_worktrees_expire = xstrdup("3.months.ago"), \
145}
146
147static void gc_config_release(struct gc_config *cfg)
148{
149 free(cfg->gc_log_expire);
150 free(cfg->prune_expire);
151 free(cfg->prune_worktrees_expire);
152}
153
154static void gc_config(struct gc_config *cfg)
155{
156 const char *value;
157 char *owned = NULL;
158
159 if (!repo_config_get_value(the_repository, "gc.packrefs", &value)) {
160 if (value && !strcmp(value, "notbare"))
161 cfg->pack_refs = -1;
162 else
163 cfg->pack_refs = git_config_bool("gc.packrefs", value);
164 }
165
166 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
167 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
168 cfg->prune_reflogs = 0;
169
170 repo_config_get_int(the_repository, "gc.aggressivewindow", &cfg->aggressive_window);
171 repo_config_get_int(the_repository, "gc.aggressivedepth", &cfg->aggressive_depth);
172 repo_config_get_bool(the_repository, "gc.autodetach", &cfg->detach_auto);
173 repo_config_get_bool(the_repository, "gc.cruftpacks", &cfg->cruft_packs);
174 repo_config_get_ulong(the_repository, "gc.maxcruftsize", &cfg->max_cruft_size);
175
176 if (!repo_config_get_expiry(the_repository, "gc.pruneexpire", &owned)) {
177 free(cfg->prune_expire);
178 cfg->prune_expire = owned;
179 }
180
181 if (!repo_config_get_expiry(the_repository, "gc.worktreepruneexpire", &owned)) {
182 free(cfg->prune_worktrees_expire);
183 cfg->prune_worktrees_expire = owned;
184 }
185
186 if (!repo_config_get_expiry(the_repository, "gc.logexpiry", &owned)) {
187 free(cfg->gc_log_expire);
188 cfg->gc_log_expire = owned;
189 }
190
191 repo_config(the_repository, git_default_config, NULL);
192}
193
194enum schedule_priority {
195 SCHEDULE_NONE = 0,
196 SCHEDULE_WEEKLY = 1,
197 SCHEDULE_DAILY = 2,
198 SCHEDULE_HOURLY = 3,
199};
200
201static enum schedule_priority parse_schedule(const char *value)
202{
203 if (!value)
204 return SCHEDULE_NONE;
205 if (!strcasecmp(value, "hourly"))
206 return SCHEDULE_HOURLY;
207 if (!strcasecmp(value, "daily"))
208 return SCHEDULE_DAILY;
209 if (!strcasecmp(value, "weekly"))
210 return SCHEDULE_WEEKLY;
211 return SCHEDULE_NONE;
212}
213
214enum maintenance_task_label {
215 TASK_PREFETCH,
216 TASK_LOOSE_OBJECTS,
217 TASK_INCREMENTAL_REPACK,
218 TASK_GEOMETRIC_REPACK,
219 TASK_GC,
220 TASK_COMMIT_GRAPH,
221 TASK_PACK_REFS,
222 TASK_REFLOG_EXPIRE,
223 TASK_WORKTREE_PRUNE,
224 TASK_RERERE_GC,
225
226 /* Leave as final value */
227 TASK__COUNT
228};
229
230struct maintenance_run_opts {
231 enum maintenance_task_label *tasks;
232 size_t tasks_nr, tasks_alloc;
233 int auto_flag;
234 int detach;
235 int quiet;
236 enum schedule_priority schedule;
237};
238#define MAINTENANCE_RUN_OPTS_INIT { \
239 .detach = -1, \
240}
241
242static void maintenance_run_opts_release(struct maintenance_run_opts *opts)
243{
244 free(opts->tasks);
245}
246
247static int pack_refs_condition(UNUSED struct gc_config *cfg)
248{
249 struct string_list included_refs = STRING_LIST_INIT_NODUP;
250 struct ref_exclusions excludes = REF_EXCLUSIONS_INIT;
251 struct refs_optimize_opts optimize_opts = {
252 .exclusions = &excludes,
253 .includes = &included_refs,
254 .flags = REFS_OPTIMIZE_PRUNE | REFS_OPTIMIZE_AUTO,
255 };
256 bool required;
257
258 /* Check for all refs, similar to 'git refs optimize --all'. */
259 string_list_append(optimize_opts.includes, "*");
260
261 if (refs_optimize_required(get_main_ref_store(the_repository),
262 &optimize_opts, &required))
263 return 0;
264
265 clear_ref_exclusions(&excludes);
266 string_list_clear(&included_refs, 0);
267
268 return required;
269}
270
271static int maintenance_task_pack_refs(struct maintenance_run_opts *opts,
272 UNUSED struct gc_config *cfg)
273{
274 struct child_process cmd = CHILD_PROCESS_INIT;
275
276 cmd.git_cmd = 1;
277 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
278 if (opts->auto_flag)
279 strvec_push(&cmd.args, "--auto");
280
281 return run_command(&cmd);
282}
283
284struct count_reflog_entries_data {
285 struct expire_reflog_policy_cb policy;
286 size_t count;
287 size_t limit;
288};
289
290static int count_reflog_entries(const char *refname UNUSED,
291 struct object_id *old_oid, struct object_id *new_oid,
292 const char *committer, timestamp_t timestamp,
293 int tz, const char *msg, void *cb_data)
294{
295 struct count_reflog_entries_data *data = cb_data;
296 if (should_expire_reflog_ent(old_oid, new_oid, committer, timestamp, tz, msg, &data->policy))
297 data->count++;
298 return data->count >= data->limit;
299}
300
301static int reflog_expire_condition(struct gc_config *cfg UNUSED)
302{
303 timestamp_t now = time(NULL);
304 struct count_reflog_entries_data data = {
305 .policy = {
306 .opts = REFLOG_EXPIRE_OPTIONS_INIT(now),
307 },
308 };
309 int limit = 100;
310
311 repo_config_get_int(the_repository, "maintenance.reflog-expire.auto", &limit);
312 if (!limit)
313 return 0;
314 if (limit < 0)
315 return 1;
316 data.limit = limit;
317
318 repo_config(the_repository, reflog_expire_config, &data.policy.opts);
319
320 reflog_expire_options_set_refname(&data.policy.opts, "HEAD");
321 refs_for_each_reflog_ent(get_main_ref_store(the_repository), "HEAD",
322 count_reflog_entries, &data);
323
324 reflog_expiry_cleanup(&data.policy);
325 reflog_clear_expire_config(&data.policy.opts);
326 return data.count >= data.limit;
327}
328
329static int maintenance_task_reflog_expire(struct maintenance_run_opts *opts UNUSED,
330 struct gc_config *cfg UNUSED)
331{
332 struct child_process cmd = CHILD_PROCESS_INIT;
333 cmd.git_cmd = 1;
334 strvec_pushl(&cmd.args, "reflog", "expire", "--all", NULL);
335 return run_command(&cmd);
336}
337
338static int maintenance_task_worktree_prune(struct maintenance_run_opts *opts UNUSED,
339 struct gc_config *cfg)
340{
341 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
342
343 prune_worktrees_cmd.git_cmd = 1;
344 strvec_pushl(&prune_worktrees_cmd.args, "worktree", "prune", "--expire", NULL);
345 strvec_push(&prune_worktrees_cmd.args, cfg->prune_worktrees_expire);
346
347 return run_command(&prune_worktrees_cmd);
348}
349
350static int worktree_prune_condition(struct gc_config *cfg)
351{
352 struct strbuf buf = STRBUF_INIT;
353 int should_prune = 0, limit = 1;
354 timestamp_t expiry_date;
355 struct dirent *d;
356 DIR *dir = NULL;
357
358 repo_config_get_int(the_repository, "maintenance.worktree-prune.auto", &limit);
359 if (limit <= 0) {
360 should_prune = limit < 0;
361 goto out;
362 }
363
364 if (parse_expiry_date(cfg->prune_worktrees_expire, &expiry_date))
365 goto out;
366
367 dir = opendir(repo_git_path_replace(the_repository, &buf, "worktrees"));
368 if (!dir)
369 goto out;
370
371 while (limit && (d = readdir_skip_dot_and_dotdot(dir))) {
372 char *wtpath;
373 strbuf_reset(&buf);
374 if (should_prune_worktree(the_repository, d->d_name, &buf, &wtpath, expiry_date))
375 limit--;
376 free(wtpath);
377 }
378
379 should_prune = !limit;
380
381out:
382 if (dir)
383 closedir(dir);
384 strbuf_release(&buf);
385 return should_prune;
386}
387
388static int maintenance_task_rerere_gc(struct maintenance_run_opts *opts,
389 struct gc_config *cfg UNUSED)
390{
391 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
392 rerere_cmd.git_cmd = 1;
393 strvec_pushl(&rerere_cmd.args, "rerere", "gc", NULL);
394 if (opts->auto_flag)
395 strvec_push(&rerere_cmd.args, "--skip-locked");
396 return run_command(&rerere_cmd);
397}
398
399static int rerere_gc_condition(struct gc_config *cfg UNUSED)
400{
401 int limit = 512;
402
403 repo_config_get_int(the_repository, "maintenance.rerere-gc.auto", &limit);
404 if (!limit)
405 return 0; /* never prune */
406 if (limit < 0)
407 return 1; /* always prune */
408
409 return rerere_gc_needed(the_repository, (size_t)limit);
410}
411
412#define OPTIMIZE_FIELDS_FROM_GC_CONFIG(cfg, aggressive) \
413 .prune_expire = (cfg)->prune_expire, \
414 .expire_to = (cfg)->repack_expire_to, \
415 .cruft_packs = (cfg)->cruft_packs, \
416 .max_cruft_size = (cfg)->max_cruft_size, \
417 .window = (aggressive) ? (cfg)->aggressive_window : 0, \
418 .depth = (aggressive) ? (cfg)->aggressive_depth : 0
419
420/* return NULL on success, else hostname running the gc */
421static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
422{
423 struct lock_file lock = LOCK_INIT;
424 char my_host[HOST_NAME_MAX + 1];
425 struct strbuf sb = STRBUF_INIT;
426 struct stat st;
427 uintmax_t pid;
428 FILE *fp;
429 int fd;
430 char *pidfile_path;
431
432 if (is_tempfile_active(pidfile))
433 /* already locked */
434 return NULL;
435
436 if (xgethostname(my_host, sizeof(my_host)))
437 xsnprintf(my_host, sizeof(my_host), "unknown");
438
439 pidfile_path = repo_git_path(the_repository, "gc.pid");
440 fd = hold_lock_file_for_update(&lock, pidfile_path,
441 LOCK_DIE_ON_ERROR);
442 if (!force) {
443 static char locking_host[HOST_NAME_MAX + 1];
444 static char *scan_fmt;
445 int should_exit;
446
447 if (!scan_fmt)
448 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
449 fp = fopen(pidfile_path, "r");
450 memset(locking_host, 0, sizeof(locking_host));
451 should_exit =
452 fp != NULL &&
453 !fstat(fileno(fp), &st) &&
454 /*
455 * 12 hour limit is very generous as gc should
456 * never take that long. On the other hand we
457 * don't really need a strict limit here,
458 * running gc --auto one day late is not a big
459 * problem. --force can be used in manual gc
460 * after the user verifies that no gc is
461 * running.
462 */
463 time(NULL) - st.st_mtime <= 12 * 3600 &&
464 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
465 /* be gentle to concurrent "gc" on remote hosts */
466 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
467 if (fp)
468 fclose(fp);
469 if (should_exit) {
470 if (fd >= 0)
471 rollback_lock_file(&lock);
472 *ret_pid = pid;
473 free(pidfile_path);
474 return locking_host;
475 }
476 }
477
478 strbuf_addf(&sb, "%"PRIuMAX" %s",
479 (uintmax_t) getpid(), my_host);
480 write_in_full(fd, sb.buf, sb.len);
481 strbuf_release(&sb);
482 commit_lock_file(&lock);
483 pidfile = register_tempfile(pidfile_path);
484 free(pidfile_path);
485 return NULL;
486}
487
488/*
489 * Returns 0 if there was no previous error and gc can proceed, 1 if
490 * gc should not proceed due to an error in the last run. Prints a
491 * message and returns with a non-[01] status code if an error occurred
492 * while reading gc.log
493 */
494static int report_last_gc_error(void)
495{
496 struct strbuf sb = STRBUF_INIT;
497 int ret = 0;
498 ssize_t len;
499 struct stat st;
500 char *gc_log_path = repo_git_path(the_repository, "gc.log");
501
502 if (stat(gc_log_path, &st)) {
503 if (errno == ENOENT)
504 goto done;
505
506 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
507 goto done;
508 }
509
510 if (st.st_mtime < gc_log_expire_time)
511 goto done;
512
513 len = strbuf_read_file(&sb, gc_log_path, 0);
514 if (len < 0)
515 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
516 else if (len > 0) {
517 /*
518 * A previous gc failed. Report the error, and don't
519 * bother with an automatic gc run since it is likely
520 * to fail in the same way.
521 */
522 warning(_("The last gc run reported the following. "
523 "Please correct the root cause\n"
524 "and remove %s\n"
525 "Automatic cleanup will not be performed "
526 "until the file is removed.\n\n"
527 "%s"),
528 gc_log_path, sb.buf);
529 ret = 1;
530 }
531 strbuf_release(&sb);
532done:
533 free(gc_log_path);
534 return ret;
535}
536
537static int gc_foreground_tasks(struct maintenance_run_opts *opts,
538 struct gc_config *cfg)
539{
540 if (cfg->pack_refs && maintenance_task_pack_refs(opts, cfg))
541 return error(FAILED_RUN, "pack-refs");
542 if (cfg->prune_reflogs && maintenance_task_reflog_expire(opts, cfg))
543 return error(FAILED_RUN, "reflog");
544 return 0;
545}
546
547static int maintenance_task_odb(struct maintenance_run_opts *opts,
548 struct gc_config *cfg,
549 int keep_largest_pack,
550 int aggressive)
551{
552 struct odb_optimize_options odb_opts = {
553 .strategy = ODB_OPTIMIZE_INCREMENTAL,
554 .keep_largest_pack = keep_largest_pack,
555 OPTIMIZE_FIELDS_FROM_GC_CONFIG(cfg, aggressive),
556 };
557
558 if (opts->auto_flag)
559 odb_opts.flags |= ODB_OPTIMIZE_AUTO;
560 if (!opts->quiet)
561 odb_opts.flags |= ODB_OPTIMIZE_VERBOSE;
562 if (aggressive)
563 odb_opts.flags |= ODB_OPTIMIZE_NO_REUSE_DELTAS;
564
565 return odb_optimize(the_repository->objects, &odb_opts);
566}
567
568int cmd_gc(int argc,
569 const char **argv,
570 const char *prefix,
571 struct repository *repo UNUSED)
572{
573 int aggressive = 0;
574 int force = 0;
575 const char *name;
576 pid_t pid;
577 int daemonized = 0;
578 int keep_largest_pack = -1;
579 int skip_foreground_tasks = 0;
580 timestamp_t dummy;
581 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
582 struct gc_config cfg = GC_CONFIG_INIT;
583 const char *prune_expire_sentinel = "sentinel";
584 const char *prune_expire_arg = prune_expire_sentinel;
585 int ret;
586 struct option builtin_gc_options[] = {
587 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
588 {
589 .type = OPTION_STRING,
590 .long_name = "prune",
591 .value = &prune_expire_arg,
592 .argh = N_("date"),
593 .help = N_("prune unreferenced objects"),
594 .flags = PARSE_OPT_OPTARG,
595 .defval = (intptr_t)prune_expire_arg,
596 },
597 OPT_BOOL(0, "cruft", &cfg.cruft_packs, N_("pack unreferenced objects separately")),
598 OPT_UNSIGNED(0, "max-cruft-size", &cfg.max_cruft_size,
599 N_("with --cruft, limit the size of new cruft packs")),
600 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
601 OPT_BOOL_F(0, "auto", &opts.auto_flag, N_("enable auto-gc mode"),
602 PARSE_OPT_NOCOMPLETE),
603 OPT_BOOL(0, "detach", &opts.detach,
604 N_("perform garbage collection in the background")),
605 OPT_BOOL_F(0, "force", &force,
606 N_("force running gc even if there may be another gc running"),
607 PARSE_OPT_NOCOMPLETE),
608 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
609 N_("repack all other packs except the largest pack")),
610 OPT_STRING(0, "expire-to", &cfg.repack_expire_to, N_("dir"),
611 N_("pack prefix to store a pack containing pruned objects")),
612 OPT_HIDDEN_BOOL(0, "skip-foreground-tasks", &skip_foreground_tasks,
613 N_("skip maintenance tasks typically done in the foreground")),
614 OPT_END()
615 };
616
617 show_usage_with_options_if_asked(argc, argv,
618 builtin_gc_usage, builtin_gc_options);
619
620 gc_config(&cfg);
621
622 if (parse_expiry_date(cfg.gc_log_expire, &gc_log_expire_time))
623 die(_("failed to parse gc.logExpiry value %s"), cfg.gc_log_expire);
624
625 if (cfg.pack_refs < 0)
626 cfg.pack_refs = !is_bare_repository(the_repository);
627
628 argc = parse_options(argc, argv, prefix, builtin_gc_options,
629 builtin_gc_usage, 0);
630 if (argc > 0)
631 usage_with_options(builtin_gc_usage, builtin_gc_options);
632
633 if (prune_expire_arg != prune_expire_sentinel) {
634 free(cfg.prune_expire);
635 cfg.prune_expire = xstrdup_or_null(prune_expire_arg);
636 }
637 if (cfg.prune_expire && parse_expiry_date(cfg.prune_expire, &dummy))
638 die(_("failed to parse prune expiry value %s"), cfg.prune_expire);
639
640 if (opts.auto_flag) {
641 struct odb_optimize_options optimize_opts = {
642 .strategy = ODB_OPTIMIZE_INCREMENTAL,
643 OPTIMIZE_FIELDS_FROM_GC_CONFIG(&cfg, 0),
644 };
645
646 if (cfg.detach_auto && opts.detach < 0)
647 opts.detach = 1;
648
649 /*
650 * Auto-gc should be least intrusive as possible.
651 */
652 if (!odb_optimize_required(the_repository->objects, &optimize_opts) ||
653 run_hooks(the_repository, "pre-auto-gc")) {
654 ret = 0;
655 goto out;
656 }
657
658 if (!opts.quiet) {
659 if (opts.detach > 0)
660 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
661 else
662 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
663 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
664 }
665 }
666
667 if (opts.detach > 0) {
668 ret = report_last_gc_error();
669 if (ret == 1) {
670 /* Last gc --auto failed. Skip this one. */
671 ret = 0;
672 goto out;
673
674 } else if (ret) {
675 /* an I/O error occurred, already reported */
676 goto out;
677 }
678
679 if (!skip_foreground_tasks) {
680 if (lock_repo_for_gc(force, &pid)) {
681 ret = 0;
682 goto out;
683 }
684
685 if (gc_foreground_tasks(&opts, &cfg) < 0)
686 die(NULL);
687 delete_tempfile(&pidfile);
688 }
689
690 /*
691 * failure to daemonize is ok, we'll continue
692 * in foreground
693 */
694 daemonized = !daemonize();
695 }
696
697 name = lock_repo_for_gc(force, &pid);
698 if (name) {
699 if (opts.auto_flag) {
700 ret = 0;
701 goto out; /* be quiet on --auto */
702 }
703
704 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
705 name, (uintmax_t)pid);
706 }
707
708 if (daemonized) {
709 char *path = repo_git_path(the_repository, "gc.log");
710 hold_lock_file_for_update(&log_lock, path,
711 LOCK_DIE_ON_ERROR);
712 dup2(get_lock_file_fd(&log_lock), 2);
713 atexit(process_log_file_at_exit);
714 free(path);
715 }
716
717 if (opts.detach <= 0 && !skip_foreground_tasks)
718 gc_foreground_tasks(&opts, &cfg);
719
720 if (cfg.prune_worktrees_expire &&
721 maintenance_task_worktree_prune(&opts, &cfg))
722 die(FAILED_RUN, "worktree");
723
724 if (maintenance_task_rerere_gc(&opts, &cfg))
725 die(FAILED_RUN, "rerere");
726
727 if (maintenance_task_odb(&opts, &cfg, keep_largest_pack, aggressive))
728 die(NULL);
729
730 report_garbage = report_pack_garbage;
731 odb_reprepare(the_repository->objects);
732 if (pack_garbage.nr > 0) {
733 odb_close(the_repository->objects);
734 clean_pack_garbage();
735 }
736
737 if (the_repository->settings.gc_write_commit_graph == 1)
738 write_commit_graph_reachable(the_repository,
739 the_repository->objects->source->path,
740 !opts.quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
741 NULL);
742
743 if (!daemonized) {
744 char *path = repo_git_path(the_repository, "gc.log");
745 unlink(path);
746 free(path);
747 }
748
749out:
750 maintenance_run_opts_release(&opts);
751 gc_config_release(&cfg);
752 return 0;
753}
754
755static const char *const builtin_maintenance_run_usage[] = {
756 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
757 NULL
758};
759
760static int maintenance_opt_schedule(const struct option *opt, const char *arg,
761 int unset)
762{
763 enum schedule_priority *priority = opt->value;
764
765 if (unset)
766 die(_("--no-schedule is not allowed"));
767
768 *priority = parse_schedule(arg);
769
770 if (!*priority)
771 die(_("unrecognized --schedule argument '%s'"), arg);
772
773 return 0;
774}
775
776struct cg_auto_data {
777 int num_not_in_graph;
778 int limit;
779};
780
781static int dfs_on_ref(const struct reference *ref, void *cb_data)
782{
783 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
784 int result = 0;
785 const struct object_id *maybe_peeled = ref->oid;
786 struct object_id peeled;
787 struct commit_list *stack = NULL;
788 struct commit *commit;
789
790 if (!reference_get_peeled_oid(the_repository, ref, &peeled))
791 maybe_peeled = &peeled;
792 if (odb_read_object_info(the_repository->objects, maybe_peeled, NULL) != OBJ_COMMIT)
793 return 0;
794
795 commit = lookup_commit(the_repository, maybe_peeled);
796 if (!commit || commit->object.flags & SEEN)
797 return 0;
798 commit->object.flags |= SEEN;
799
800 if (repo_parse_commit(the_repository, commit) ||
801 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
802 return 0;
803
804 data->num_not_in_graph++;
805
806 if (data->num_not_in_graph >= data->limit)
807 return 1;
808
809 commit_list_insert(commit, &stack);
810
811 while (!result && stack) {
812 struct commit_list *parent;
813
814 commit = pop_commit(&stack);
815
816 for (parent = commit->parents; parent; parent = parent->next) {
817 if (repo_parse_commit(the_repository, parent->item) ||
818 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
819 parent->item->object.flags & SEEN)
820 continue;
821
822 parent->item->object.flags |= SEEN;
823 data->num_not_in_graph++;
824
825 if (data->num_not_in_graph >= data->limit) {
826 result = 1;
827 break;
828 }
829
830 commit_list_insert(parent->item, &stack);
831 }
832 }
833
834 commit_list_free(stack);
835 return result;
836}
837
838static int should_write_commit_graph(struct gc_config *cfg UNUSED)
839{
840 int result;
841 struct cg_auto_data data;
842
843 data.num_not_in_graph = 0;
844 data.limit = 100;
845 repo_config_get_int(the_repository, "maintenance.commit-graph.auto",
846 &data.limit);
847
848 if (!data.limit)
849 return 0;
850 if (data.limit < 0)
851 return 1;
852
853 result = refs_for_each_ref(get_main_ref_store(the_repository),
854 dfs_on_ref, &data);
855
856 repo_clear_commit_marks(the_repository, SEEN);
857
858 return result;
859}
860
861static int run_write_commit_graph(struct maintenance_run_opts *opts)
862{
863 struct child_process child = CHILD_PROCESS_INIT;
864
865 child.git_cmd = 1;
866 child.odb_to_close = the_repository->objects;
867 strvec_pushl(&child.args, "commit-graph", "write",
868 "--split", "--reachable", NULL);
869
870 if (opts->quiet)
871 strvec_push(&child.args, "--no-progress");
872 else
873 strvec_push(&child.args, "--progress");
874
875 return !!run_command(&child);
876}
877
878static int maintenance_task_commit_graph(struct maintenance_run_opts *opts,
879 struct gc_config *cfg UNUSED)
880{
881 prepare_repo_settings(the_repository);
882 if (!the_repository->settings.core_commit_graph)
883 return 0;
884
885 if (run_write_commit_graph(opts)) {
886 error(_("failed to write commit-graph"));
887 return 1;
888 }
889
890 return 0;
891}
892
893static int fetch_remote(struct remote *remote, void *cbdata)
894{
895 struct maintenance_run_opts *opts = cbdata;
896 struct child_process child = CHILD_PROCESS_INIT;
897
898 if (remote->skip_default_update)
899 return 0;
900
901 child.git_cmd = 1;
902 strvec_pushl(&child.args, "fetch", remote->name,
903 "--prefetch", "--prune", "--no-tags",
904 "--no-write-fetch-head", "--recurse-submodules=no",
905 NULL);
906
907 if (opts->quiet)
908 strvec_push(&child.args, "--quiet");
909
910 return !!run_command(&child);
911}
912
913static int maintenance_task_prefetch(struct maintenance_run_opts *opts,
914 struct gc_config *cfg UNUSED)
915{
916 if (for_each_remote(fetch_remote, opts)) {
917 error(_("failed to prefetch remotes"));
918 return 1;
919 }
920
921 return 0;
922}
923
924static int maintenance_task_gc_foreground(struct maintenance_run_opts *opts,
925 struct gc_config *cfg)
926{
927 return gc_foreground_tasks(opts, cfg);
928}
929
930static int maintenance_task_gc_background(struct maintenance_run_opts *opts,
931 struct gc_config *cfg UNUSED)
932{
933 struct child_process child = CHILD_PROCESS_INIT;
934
935 child.git_cmd = 1;
936 child.odb_to_close = the_repository->objects;
937 strvec_push(&child.args, "gc");
938
939 if (opts->auto_flag)
940 strvec_push(&child.args, "--auto");
941 if (opts->quiet)
942 strvec_push(&child.args, "--quiet");
943 else
944 strvec_push(&child.args, "--no-quiet");
945 strvec_push(&child.args, "--no-detach");
946 strvec_push(&child.args, "--skip-foreground-tasks");
947
948 return run_command(&child);
949}
950
951static int gc_condition(struct gc_config *cfg)
952{
953 struct odb_optimize_options opts = {
954 .strategy = ODB_OPTIMIZE_INCREMENTAL,
955 OPTIMIZE_FIELDS_FROM_GC_CONFIG(cfg, 0),
956 };
957 return odb_optimize_required(the_repository->objects, &opts);
958}
959
960static int prune_packed(struct maintenance_run_opts *opts)
961{
962 struct child_process child = CHILD_PROCESS_INIT;
963
964 child.git_cmd = 1;
965 strvec_push(&child.args, "prune-packed");
966
967 if (opts->quiet)
968 strvec_push(&child.args, "--quiet");
969
970 return !!run_command(&child);
971}
972
973struct write_loose_object_data {
974 FILE *in;
975 int count;
976 int batch_size;
977};
978
979static int loose_object_auto_limit = 100;
980
981static int loose_object_count(const struct object_id *oid UNUSED,
982 const char *path UNUSED,
983 void *data)
984{
985 int *count = (int*)data;
986 if (++(*count) >= loose_object_auto_limit)
987 return 1;
988 return 0;
989}
990
991static int loose_object_auto_condition(struct gc_config *cfg UNUSED)
992{
993 int count = 0;
994
995 repo_config_get_int(the_repository, "maintenance.loose-objects.auto",
996 &loose_object_auto_limit);
997
998 if (!loose_object_auto_limit)
999 return 0;
1000 if (loose_object_auto_limit < 0)
1001 return 1;
1002
1003 return for_each_loose_file_in_source(the_repository->objects->source,
1004 loose_object_count,
1005 NULL, NULL, &count);
1006}
1007
1008static int bail_on_loose(const struct object_id *oid UNUSED,
1009 const char *path UNUSED,
1010 void *data UNUSED)
1011{
1012 return 1;
1013}
1014
1015static int write_loose_object_to_stdin(const struct object_id *oid,
1016 const char *path UNUSED,
1017 void *data)
1018{
1019 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1020
1021 fprintf(d->in, "%s\n", oid_to_hex(oid));
1022
1023 /* If batch_size is INT_MAX, then this will return 0 always. */
1024 return ++(d->count) > d->batch_size;
1025}
1026
1027static int pack_loose(struct maintenance_run_opts *opts)
1028{
1029 struct repository *r = the_repository;
1030 int result = 0;
1031 struct write_loose_object_data data;
1032 struct child_process pack_proc = CHILD_PROCESS_INIT;
1033
1034 /*
1035 * Do not start pack-objects process
1036 * if there are no loose objects.
1037 */
1038 if (!for_each_loose_file_in_source(r->objects->source,
1039 bail_on_loose,
1040 NULL, NULL, NULL))
1041 return 0;
1042
1043 pack_proc.git_cmd = 1;
1044
1045 strvec_push(&pack_proc.args, "pack-objects");
1046 if (opts->quiet)
1047 strvec_push(&pack_proc.args, "--quiet");
1048 else
1049 strvec_push(&pack_proc.args, "--no-quiet");
1050 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->source->path);
1051
1052 pack_proc.in = -1;
1053
1054 /*
1055 * git-pack-objects(1) ends up writing the pack hash to stdout, which
1056 * we do not care for.
1057 */
1058 pack_proc.out = -1;
1059
1060 if (start_command(&pack_proc)) {
1061 error(_("failed to start 'git pack-objects' process"));
1062 return 1;
1063 }
1064
1065 data.in = xfdopen(pack_proc.in, "w");
1066 data.count = 0;
1067 data.batch_size = 50000;
1068
1069 repo_config_get_int(r, "maintenance.loose-objects.batchSize",
1070 &data.batch_size);
1071
1072 /* If configured as 0, then remove limit. */
1073 if (!data.batch_size)
1074 data.batch_size = INT_MAX;
1075 else if (data.batch_size > 0)
1076 data.batch_size--; /* Decrease for equality on limit. */
1077
1078 for_each_loose_file_in_source(r->objects->source,
1079 write_loose_object_to_stdin,
1080 NULL, NULL, &data);
1081
1082 fclose(data.in);
1083
1084 if (finish_command(&pack_proc)) {
1085 error(_("failed to finish 'git pack-objects' process"));
1086 result = 1;
1087 }
1088
1089 return result;
1090}
1091
1092static int maintenance_task_loose_objects(struct maintenance_run_opts *opts,
1093 struct gc_config *cfg UNUSED)
1094{
1095 return prune_packed(opts) || pack_loose(opts);
1096}
1097
1098static int incremental_repack_auto_condition(struct gc_config *cfg UNUSED)
1099{
1100 struct packed_git *p;
1101 int incremental_repack_auto_limit = 10;
1102 int count = 0;
1103
1104 prepare_repo_settings(the_repository);
1105 if (!the_repository->settings.core_multi_pack_index)
1106 return 0;
1107
1108 repo_config_get_int(the_repository, "maintenance.incremental-repack.auto",
1109 &incremental_repack_auto_limit);
1110
1111 if (!incremental_repack_auto_limit)
1112 return 0;
1113 if (incremental_repack_auto_limit < 0)
1114 return 1;
1115
1116 repo_for_each_pack(the_repository, p) {
1117 if (count >= incremental_repack_auto_limit)
1118 break;
1119 if (!p->multi_pack_index)
1120 count++;
1121 }
1122
1123 return count >= incremental_repack_auto_limit;
1124}
1125
1126static int multi_pack_index_write(struct maintenance_run_opts *opts)
1127{
1128 struct child_process child = CHILD_PROCESS_INIT;
1129
1130 child.git_cmd = 1;
1131 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1132
1133 if (opts->quiet)
1134 strvec_push(&child.args, "--no-progress");
1135 else
1136 strvec_push(&child.args, "--progress");
1137
1138 if (run_command(&child))
1139 return error(_("failed to write multi-pack-index"));
1140
1141 return 0;
1142}
1143
1144static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1145{
1146 struct child_process child = CHILD_PROCESS_INIT;
1147
1148 child.git_cmd = 1;
1149 child.odb_to_close = the_repository->objects;
1150 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1151
1152 if (opts->quiet)
1153 strvec_push(&child.args, "--no-progress");
1154 else
1155 strvec_push(&child.args, "--progress");
1156
1157 if (run_command(&child))
1158 return error(_("'git multi-pack-index expire' failed"));
1159
1160 return 0;
1161}
1162
1163#define TWO_GIGABYTES (INT32_MAX)
1164
1165static off_t get_auto_pack_size(void)
1166{
1167 /*
1168 * The "auto" value is special: we optimize for
1169 * one large pack-file (i.e. from a clone) and
1170 * expect the rest to be small and they can be
1171 * repacked quickly.
1172 *
1173 * The strategy we select here is to select a
1174 * size that is one more than the second largest
1175 * pack-file. This ensures that we will repack
1176 * at least two packs if there are three or more
1177 * packs.
1178 */
1179 off_t max_size = 0;
1180 off_t second_largest_size = 0;
1181 off_t result_size;
1182 struct packed_git *p;
1183 struct repository *r = the_repository;
1184
1185 odb_reprepare(r->objects);
1186 repo_for_each_pack(r, p) {
1187 if (p->pack_size > max_size) {
1188 second_largest_size = max_size;
1189 max_size = p->pack_size;
1190 } else if (p->pack_size > second_largest_size)
1191 second_largest_size = p->pack_size;
1192 }
1193
1194 result_size = second_largest_size + 1;
1195
1196 /* But limit ourselves to a batch size of 2g */
1197 if (result_size > TWO_GIGABYTES)
1198 result_size = TWO_GIGABYTES;
1199
1200 return result_size;
1201}
1202
1203static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1204{
1205 struct child_process child = CHILD_PROCESS_INIT;
1206
1207 child.git_cmd = 1;
1208 child.odb_to_close = the_repository->objects;
1209 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1210
1211 if (opts->quiet)
1212 strvec_push(&child.args, "--no-progress");
1213 else
1214 strvec_push(&child.args, "--progress");
1215
1216 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1217 (uintmax_t)get_auto_pack_size());
1218
1219 if (run_command(&child))
1220 return error(_("'git multi-pack-index repack' failed"));
1221
1222 return 0;
1223}
1224
1225static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts,
1226 struct gc_config *cfg UNUSED)
1227{
1228 prepare_repo_settings(the_repository);
1229 if (!the_repository->settings.core_multi_pack_index) {
1230 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1231 return 0;
1232 }
1233
1234 if (multi_pack_index_write(opts))
1235 return 1;
1236 if (multi_pack_index_expire(opts))
1237 return 1;
1238 if (multi_pack_index_repack(opts))
1239 return 1;
1240 return 0;
1241}
1242
1243static int maintenance_task_geometric_repack(struct maintenance_run_opts *opts,
1244 struct gc_config *cfg)
1245{
1246 struct odb_optimize_options odb_opts = {
1247 .strategy = ODB_OPTIMIZE_GEOMETRIC,
1248 OPTIMIZE_FIELDS_FROM_GC_CONFIG(cfg, 0),
1249 };
1250
1251 if (!opts->quiet)
1252 odb_opts.flags |= ODB_OPTIMIZE_VERBOSE;
1253
1254 return odb_optimize(the_repository->objects, &odb_opts);
1255}
1256
1257static int geometric_repack_auto_condition(struct gc_config *cfg)
1258{
1259 struct odb_optimize_options opts = {
1260 .strategy = ODB_OPTIMIZE_GEOMETRIC,
1261 OPTIMIZE_FIELDS_FROM_GC_CONFIG(cfg, 0),
1262 };
1263 return odb_optimize_required(the_repository->objects, &opts);
1264}
1265
1266typedef int (*maintenance_task_fn)(struct maintenance_run_opts *opts,
1267 struct gc_config *cfg);
1268typedef int (*maintenance_auto_fn)(struct gc_config *cfg);
1269
1270struct maintenance_task {
1271 const char *name;
1272
1273 /*
1274 * Work that will be executed before detaching. This should not include
1275 * tasks that may run for an extended amount of time as it does cause
1276 * auto-maintenance to block until foreground tasks have been run.
1277 */
1278 maintenance_task_fn foreground;
1279
1280 /*
1281 * Work that will be executed after detaching. When not detaching the
1282 * work will be run in the foreground, as well.
1283 */
1284 maintenance_task_fn background;
1285
1286 /*
1287 * An auto condition function returns 1 if the task should run and 0 if
1288 * the task should NOT run. See needs_to_gc() for an example.
1289 */
1290 maintenance_auto_fn auto_condition;
1291};
1292
1293static const struct maintenance_task tasks[] = {
1294 [TASK_PREFETCH] = {
1295 .name = "prefetch",
1296 .background = maintenance_task_prefetch,
1297 },
1298 [TASK_LOOSE_OBJECTS] = {
1299 .name = "loose-objects",
1300 .background = maintenance_task_loose_objects,
1301 .auto_condition = loose_object_auto_condition,
1302 },
1303 [TASK_INCREMENTAL_REPACK] = {
1304 .name = "incremental-repack",
1305 .background = maintenance_task_incremental_repack,
1306 .auto_condition = incremental_repack_auto_condition,
1307 },
1308 [TASK_GEOMETRIC_REPACK] = {
1309 .name = "geometric-repack",
1310 .background = maintenance_task_geometric_repack,
1311 .auto_condition = geometric_repack_auto_condition,
1312 },
1313 [TASK_GC] = {
1314 .name = "gc",
1315 .foreground = maintenance_task_gc_foreground,
1316 .background = maintenance_task_gc_background,
1317 .auto_condition = gc_condition,
1318 },
1319 [TASK_COMMIT_GRAPH] = {
1320 .name = "commit-graph",
1321 .background = maintenance_task_commit_graph,
1322 .auto_condition = should_write_commit_graph,
1323 },
1324 [TASK_PACK_REFS] = {
1325 .name = "pack-refs",
1326 .foreground = maintenance_task_pack_refs,
1327 .auto_condition = pack_refs_condition,
1328 },
1329 [TASK_REFLOG_EXPIRE] = {
1330 .name = "reflog-expire",
1331 .foreground = maintenance_task_reflog_expire,
1332 .auto_condition = reflog_expire_condition,
1333 },
1334 [TASK_WORKTREE_PRUNE] = {
1335 .name = "worktree-prune",
1336 .background = maintenance_task_worktree_prune,
1337 .auto_condition = worktree_prune_condition,
1338 },
1339 [TASK_RERERE_GC] = {
1340 .name = "rerere-gc",
1341 .background = maintenance_task_rerere_gc,
1342 .auto_condition = rerere_gc_condition,
1343 },
1344};
1345
1346enum task_phase {
1347 TASK_PHASE_FOREGROUND,
1348 TASK_PHASE_BACKGROUND,
1349};
1350
1351enum auto_gc_hook_result {
1352 AUTO_GC_HOOK_UNDECIDED = 0,
1353 AUTO_GC_HOOK_RUN = 1,
1354 AUTO_GC_HOOK_SKIP = 2,
1355};
1356
1357static int maybe_run_task(const struct maintenance_task *task,
1358 struct repository *repo,
1359 struct maintenance_run_opts *opts,
1360 struct gc_config *cfg,
1361 enum task_phase phase,
1362 enum auto_gc_hook_result *auto_gc_hook_result)
1363{
1364 int foreground = (phase == TASK_PHASE_FOREGROUND);
1365 maintenance_task_fn fn = foreground ? task->foreground : task->background;
1366 const char *region = foreground ? "maintenance foreground" : "maintenance";
1367 int ret = 0;
1368
1369 if (!fn)
1370 return 0;
1371 if (opts->auto_flag) {
1372 if (*auto_gc_hook_result == AUTO_GC_HOOK_SKIP)
1373 return 0;
1374
1375 if (!task->auto_condition || !task->auto_condition(cfg))
1376 return 0;
1377
1378 if (*auto_gc_hook_result == AUTO_GC_HOOK_UNDECIDED)
1379 *auto_gc_hook_result = run_hooks(repo, "pre-auto-gc") ?
1380 AUTO_GC_HOOK_SKIP : AUTO_GC_HOOK_RUN;
1381 if (*auto_gc_hook_result == AUTO_GC_HOOK_SKIP)
1382 return 0;
1383 }
1384
1385 trace2_region_enter(region, task->name, repo);
1386 if (fn(opts, cfg)) {
1387 error(_("task '%s' failed"), task->name);
1388 ret = 1;
1389 }
1390 trace2_region_leave(region, task->name, repo);
1391
1392 return ret;
1393}
1394
1395static int maintenance_run_tasks(struct maintenance_run_opts *opts,
1396 struct gc_config *cfg)
1397{
1398 int result = 0;
1399 struct lock_file lk;
1400 struct repository *r = the_repository;
1401 char *lock_path = xstrfmt("%s/maintenance", r->objects->source->path);
1402 enum auto_gc_hook_result auto_gc_hook_result = AUTO_GC_HOOK_UNDECIDED;
1403
1404 if (repo_hold_lock_file_for_update(r, &lk, lock_path, LOCK_NO_DEREF) < 0) {
1405 /*
1406 * Another maintenance command is running.
1407 *
1408 * If --auto was provided, then it is likely due to a
1409 * recursive process stack. Do not report an error in
1410 * that case.
1411 */
1412 if (!opts->auto_flag && !opts->quiet)
1413 warning(_("lock file '%s' exists, skipping maintenance"),
1414 lock_path);
1415 free(lock_path);
1416 return 0;
1417 }
1418 free(lock_path);
1419
1420 for (size_t i = 0; i < opts->tasks_nr; i++)
1421 if (maybe_run_task(&tasks[opts->tasks[i]], r, opts, cfg,
1422 TASK_PHASE_FOREGROUND, &auto_gc_hook_result))
1423 result = 1;
1424
1425 /* Failure to daemonize is ok, we'll continue in foreground. */
1426 if (opts->detach > 0) {
1427 trace2_region_enter("maintenance", "detach", the_repository);
1428 daemonize();
1429 trace2_region_leave("maintenance", "detach", the_repository);
1430 }
1431
1432 for (size_t i = 0; i < opts->tasks_nr; i++)
1433 if (maybe_run_task(&tasks[opts->tasks[i]], r, opts, cfg,
1434 TASK_PHASE_BACKGROUND, &auto_gc_hook_result))
1435 result = 1;
1436
1437 rollback_lock_file(&lk);
1438 return result;
1439}
1440
1441enum maintenance_type {
1442 /* As invoked via `git maintenance run --schedule=`. */
1443 MAINTENANCE_TYPE_SCHEDULED = (1 << 0),
1444 /* As invoked via `git maintenance run` and with `--auto`. */
1445 MAINTENANCE_TYPE_MANUAL = (1 << 1),
1446};
1447
1448struct maintenance_strategy {
1449 struct {
1450 unsigned type;
1451 enum schedule_priority schedule;
1452 } tasks[TASK__COUNT];
1453};
1454
1455static const struct maintenance_strategy none_strategy = { 0 };
1456
1457static const struct maintenance_strategy gc_strategy = {
1458 .tasks = {
1459 [TASK_GC] = {
1460 .type = MAINTENANCE_TYPE_MANUAL | MAINTENANCE_TYPE_SCHEDULED,
1461 .schedule = SCHEDULE_DAILY,
1462 },
1463 },
1464};
1465
1466static const struct maintenance_strategy incremental_strategy = {
1467 .tasks = {
1468 [TASK_COMMIT_GRAPH] = {
1469 .type = MAINTENANCE_TYPE_SCHEDULED,
1470 .schedule = SCHEDULE_HOURLY,
1471 },
1472 [TASK_PREFETCH] = {
1473 .type = MAINTENANCE_TYPE_SCHEDULED,
1474 .schedule = SCHEDULE_HOURLY,
1475 },
1476 [TASK_INCREMENTAL_REPACK] = {
1477 .type = MAINTENANCE_TYPE_SCHEDULED,
1478 .schedule = SCHEDULE_DAILY,
1479 },
1480 [TASK_LOOSE_OBJECTS] = {
1481 .type = MAINTENANCE_TYPE_SCHEDULED,
1482 .schedule = SCHEDULE_DAILY,
1483 },
1484 [TASK_PACK_REFS] = {
1485 .type = MAINTENANCE_TYPE_SCHEDULED,
1486 .schedule = SCHEDULE_WEEKLY,
1487 },
1488 /*
1489 * Historically, the "incremental" strategy was only available
1490 * in the context of scheduled maintenance when set up via
1491 * "maintenance.strategy". We have later expanded that config
1492 * to also cover manual maintenance.
1493 *
1494 * To retain backwards compatibility with the previous status
1495 * quo we thus run git-gc(1) in case manual maintenance was
1496 * requested. This is the same as the default strategy, which
1497 * would have been in use beforehand.
1498 */
1499 [TASK_GC] = {
1500 .type = MAINTENANCE_TYPE_MANUAL,
1501 },
1502 },
1503};
1504
1505static const struct maintenance_strategy geometric_strategy = {
1506 .tasks = {
1507 [TASK_COMMIT_GRAPH] = {
1508 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1509 .schedule = SCHEDULE_HOURLY,
1510 },
1511 [TASK_GEOMETRIC_REPACK] = {
1512 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1513 .schedule = SCHEDULE_DAILY,
1514 },
1515 [TASK_PACK_REFS] = {
1516 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1517 .schedule = SCHEDULE_DAILY,
1518 },
1519 [TASK_RERERE_GC] = {
1520 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1521 .schedule = SCHEDULE_WEEKLY,
1522 },
1523 [TASK_REFLOG_EXPIRE] = {
1524 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1525 .schedule = SCHEDULE_WEEKLY,
1526 },
1527 [TASK_WORKTREE_PRUNE] = {
1528 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1529 .schedule = SCHEDULE_WEEKLY,
1530 },
1531 },
1532};
1533
1534static struct maintenance_strategy parse_maintenance_strategy(const char *name)
1535{
1536 if (!strcasecmp(name, "incremental"))
1537 return incremental_strategy;
1538 if (!strcasecmp(name, "gc"))
1539 return gc_strategy;
1540 if (!strcasecmp(name, "geometric"))
1541 return geometric_strategy;
1542 die(_("unknown maintenance strategy: '%s'"), name);
1543}
1544
1545static void initialize_task_config(struct maintenance_run_opts *opts,
1546 const struct string_list *selected_tasks)
1547{
1548 struct strbuf config_name = STRBUF_INIT;
1549 struct maintenance_strategy strategy;
1550 enum maintenance_type type;
1551 const char *config_str;
1552
1553 /*
1554 * In case the user has asked us to run tasks explicitly we only use
1555 * those specified tasks. Specifically, we do _not_ want to consult the
1556 * config or maintenance strategy.
1557 */
1558 if (selected_tasks->nr) {
1559 for (size_t i = 0; i < selected_tasks->nr; i++) {
1560 enum maintenance_task_label label = (intptr_t)selected_tasks->items[i].util;;
1561 ALLOC_GROW(opts->tasks, opts->tasks_nr + 1, opts->tasks_alloc);
1562 opts->tasks[opts->tasks_nr++] = label;
1563 }
1564
1565 return;
1566 }
1567
1568 /*
1569 * Otherwise, the strategy depends on whether we run as part of a
1570 * scheduled job or not:
1571 *
1572 * - Scheduled maintenance does not perform any housekeeping by
1573 * default, but requires the user to pick a maintenance strategy.
1574 *
1575 * - Unscheduled maintenance uses our default strategy.
1576 *
1577 * Both of these are affected by the gitconfig though, which may
1578 * override specific aspects of our strategy. Furthermore, both
1579 * strategies can be overridden by setting "maintenance.strategy".
1580 */
1581 if (opts->schedule) {
1582 strategy = none_strategy;
1583 type = MAINTENANCE_TYPE_SCHEDULED;
1584 } else {
1585 strategy = geometric_strategy;
1586 type = MAINTENANCE_TYPE_MANUAL;
1587 }
1588
1589 if (!repo_config_get_string_tmp(the_repository, "maintenance.strategy", &config_str))
1590 strategy = parse_maintenance_strategy(config_str);
1591
1592 for (size_t i = 0; i < TASK__COUNT; i++) {
1593 int config_value;
1594
1595 strbuf_reset(&config_name);
1596 strbuf_addf(&config_name, "maintenance.%s.enabled",
1597 tasks[i].name);
1598 if (!repo_config_get_bool(the_repository, config_name.buf, &config_value))
1599 strategy.tasks[i].type = config_value ? type : 0;
1600 if (!(strategy.tasks[i].type & type))
1601 continue;
1602
1603 if (opts->schedule) {
1604 strbuf_reset(&config_name);
1605 strbuf_addf(&config_name, "maintenance.%s.schedule",
1606 tasks[i].name);
1607 if (!repo_config_get_string_tmp(the_repository, config_name.buf, &config_str))
1608 strategy.tasks[i].schedule = parse_schedule(config_str);
1609 if (strategy.tasks[i].schedule < opts->schedule)
1610 continue;
1611 }
1612
1613 ALLOC_GROW(opts->tasks, opts->tasks_nr + 1, opts->tasks_alloc);
1614 opts->tasks[opts->tasks_nr++] = i;
1615 }
1616
1617 strbuf_release(&config_name);
1618}
1619
1620static int task_option_parse(const struct option *opt,
1621 const char *arg, int unset)
1622{
1623 struct string_list *selected_tasks = opt->value;
1624 size_t i;
1625
1626 BUG_ON_OPT_NEG(unset);
1627
1628 for (i = 0; i < TASK__COUNT; i++)
1629 if (!strcasecmp(tasks[i].name, arg))
1630 break;
1631 if (i >= TASK__COUNT) {
1632 error(_("'%s' is not a valid task"), arg);
1633 return 1;
1634 }
1635
1636 if (unsorted_string_list_has_string(selected_tasks, arg)) {
1637 error(_("task '%s' cannot be selected multiple times"), arg);
1638 return 1;
1639 }
1640
1641 string_list_append(selected_tasks, arg)->util = (void *)(intptr_t)i;
1642
1643 return 0;
1644}
1645
1646static int maintenance_run(int argc, const char **argv, const char *prefix,
1647 struct repository *repo UNUSED)
1648{
1649 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
1650 struct string_list selected_tasks = STRING_LIST_INIT_DUP;
1651 struct gc_config cfg = GC_CONFIG_INIT;
1652 struct option builtin_maintenance_run_options[] = {
1653 OPT_BOOL(0, "auto", &opts.auto_flag,
1654 N_("run tasks based on the state of the repository")),
1655 OPT_BOOL(0, "detach", &opts.detach,
1656 N_("perform maintenance in the background")),
1657 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1658 N_("run tasks based on frequency"),
1659 maintenance_opt_schedule),
1660 OPT_BOOL(0, "quiet", &opts.quiet,
1661 N_("do not report progress or other information over stderr")),
1662 OPT_CALLBACK_F(0, "task", &selected_tasks, N_("task"),
1663 N_("run a specific task"),
1664 PARSE_OPT_NONEG, task_option_parse),
1665 OPT_END()
1666 };
1667 int ret;
1668
1669 opts.quiet = !isatty(2);
1670
1671 argc = parse_options(argc, argv, prefix,
1672 builtin_maintenance_run_options,
1673 builtin_maintenance_run_usage,
1674 PARSE_OPT_STOP_AT_NON_OPTION);
1675
1676 die_for_incompatible_opt2(opts.auto_flag, "--auto",
1677 opts.schedule, "--schedule=");
1678 die_for_incompatible_opt2(selected_tasks.nr, "--task=",
1679 opts.schedule, "--schedule=");
1680
1681 gc_config(&cfg);
1682 initialize_task_config(&opts, &selected_tasks);
1683
1684 if (argc != 0)
1685 usage_with_options(builtin_maintenance_run_usage,
1686 builtin_maintenance_run_options);
1687
1688 ret = maintenance_run_tasks(&opts, &cfg);
1689
1690 string_list_clear(&selected_tasks, 0);
1691 maintenance_run_opts_release(&opts);
1692 gc_config_release(&cfg);
1693 return ret;
1694}
1695
1696static char *get_maintpath(void)
1697{
1698 struct strbuf sb = STRBUF_INIT;
1699 const char *p = the_repository->worktree ?
1700 the_repository->worktree : the_repository->gitdir;
1701
1702 strbuf_realpath(&sb, p, 1);
1703 return strbuf_detach(&sb, NULL);
1704}
1705
1706static char const * const builtin_maintenance_register_usage[] = {
1707 "git maintenance register [--config-file <path>]",
1708 NULL
1709};
1710
1711static int maintenance_register(int argc, const char **argv, const char *prefix,
1712 struct repository *repo UNUSED)
1713{
1714 char *config_file = NULL;
1715 struct option options[] = {
1716 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1717 OPT_END(),
1718 };
1719 int found = 0;
1720 const char *key = "maintenance.repo";
1721 char *maintpath = get_maintpath();
1722 struct string_list_item *item;
1723 const struct string_list *list;
1724
1725 argc = parse_options(argc, argv, prefix, options,
1726 builtin_maintenance_register_usage, 0);
1727 if (argc)
1728 usage_with_options(builtin_maintenance_register_usage,
1729 options);
1730
1731 /* Disable foreground maintenance */
1732 repo_config_set(the_repository, "maintenance.auto", "false");
1733
1734 /* Set maintenance strategy, if unset */
1735 if (repo_config_get(the_repository, "maintenance.strategy"))
1736 repo_config_set(the_repository, "maintenance.strategy", "incremental");
1737
1738 if (!repo_config_get_string_multi(the_repository, key, &list)) {
1739 for_each_string_list_item(item, list) {
1740 if (!strcmp(maintpath, item->string)) {
1741 found = 1;
1742 break;
1743 }
1744 }
1745 }
1746
1747 if (!found) {
1748 int rc;
1749 char *global_config_file = NULL;
1750
1751 if (!config_file) {
1752 global_config_file = git_global_config();
1753 config_file = global_config_file;
1754 }
1755 if (!config_file)
1756 die(_("$HOME not set"));
1757 rc = repo_config_set_multivar_in_file_gently(the_repository,
1758 config_file, "maintenance.repo", maintpath,
1759 CONFIG_REGEX_NONE, NULL, 0);
1760 free(global_config_file);
1761
1762 if (rc)
1763 die(_("unable to add '%s' value of '%s'"),
1764 key, maintpath);
1765 }
1766
1767 free(maintpath);
1768 return 0;
1769}
1770
1771static char const * const builtin_maintenance_unregister_usage[] = {
1772 "git maintenance unregister [--config-file <path>] [--force]",
1773 NULL
1774};
1775
1776static int maintenance_unregister(int argc, const char **argv, const char *prefix,
1777 struct repository *repo UNUSED)
1778{
1779 int force = 0;
1780 char *config_file = NULL;
1781 struct option options[] = {
1782 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1783 OPT__FORCE(&force,
1784 N_("return success even if repository was not registered"),
1785 PARSE_OPT_NOCOMPLETE),
1786 OPT_END(),
1787 };
1788 const char *key = "maintenance.repo";
1789 char *maintpath = get_maintpath();
1790 int found = 0;
1791 struct string_list_item *item;
1792 const struct string_list *list;
1793 struct config_set cs = { { 0 } };
1794
1795 argc = parse_options(argc, argv, prefix, options,
1796 builtin_maintenance_unregister_usage, 0);
1797 if (argc)
1798 usage_with_options(builtin_maintenance_unregister_usage,
1799 options);
1800
1801 if (config_file) {
1802 git_configset_init(&cs);
1803 git_configset_add_file(&cs, config_file);
1804 }
1805 if (!(config_file
1806 ? git_configset_get_string_multi(&cs, key, &list)
1807 : repo_config_get_string_multi(the_repository, key, &list))) {
1808 for_each_string_list_item(item, list) {
1809 if (!strcmp(maintpath, item->string)) {
1810 found = 1;
1811 break;
1812 }
1813 }
1814 }
1815
1816 if (found) {
1817 int rc;
1818 char *global_config_file = NULL;
1819
1820 if (!config_file) {
1821 global_config_file = git_global_config();
1822 config_file = global_config_file;
1823 }
1824 if (!config_file)
1825 die(_("$HOME not set"));
1826 rc = repo_config_set_multivar_in_file_gently(the_repository,
1827 config_file, key, NULL, maintpath, NULL,
1828 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
1829 free(global_config_file);
1830
1831 if (rc &&
1832 (!force || rc == CONFIG_NOTHING_SET))
1833 die(_("unable to unset '%s' value of '%s'"),
1834 key, maintpath);
1835 } else if (!force) {
1836 die(_("repository '%s' is not registered"), maintpath);
1837 }
1838
1839 git_configset_clear(&cs);
1840 free(maintpath);
1841 return 0;
1842}
1843
1844static const char *get_frequency(enum schedule_priority schedule)
1845{
1846 switch (schedule) {
1847 case SCHEDULE_HOURLY:
1848 return "hourly";
1849 case SCHEDULE_DAILY:
1850 return "daily";
1851 case SCHEDULE_WEEKLY:
1852 return "weekly";
1853 default:
1854 BUG("invalid schedule %d", schedule);
1855 }
1856}
1857
1858static const char *extraconfig[] = {
1859 "credential.interactive=false",
1860 "core.askPass=true", /* 'true' returns success, but no output. */
1861 NULL
1862};
1863
1864static const char *get_extra_config_parameters(void) {
1865 static const char *result = NULL;
1866 struct strbuf builder = STRBUF_INIT;
1867
1868 if (result)
1869 return result;
1870
1871 for (const char **s = extraconfig; s && *s; s++)
1872 strbuf_addf(&builder, "-c %s ", *s);
1873
1874 result = strbuf_detach(&builder, NULL);
1875 return result;
1876}
1877
1878static const char *get_extra_launchctl_strings(void) {
1879 static const char *result = NULL;
1880 struct strbuf builder = STRBUF_INIT;
1881
1882 if (result)
1883 return result;
1884
1885 for (const char **s = extraconfig; s && *s; s++) {
1886 strbuf_addstr(&builder, "<string>-c</string>\n");
1887 strbuf_addf(&builder, "<string>%s</string>\n", *s);
1888 }
1889
1890 result = strbuf_detach(&builder, NULL);
1891 return result;
1892}
1893
1894/*
1895 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1896 * to mock the schedulers that `git maintenance start` rely on.
1897 *
1898 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1899 * list of colon-separated key/value pairs where each pair contains a scheduler
1900 * and its corresponding mock.
1901 *
1902 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1903 * arguments unmodified.
1904 *
1905 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1906 * In this case, the *cmd value is read as input.
1907 *
1908 * * if the input value cmd is the key of one of the comma-separated list
1909 * item, then *is_available is set to true and *out is set to
1910 * the mock command.
1911 *
1912 * * if the input value *cmd isn’t the key of any of the comma-separated list
1913 * item, then *is_available is set to false and *out is set to the original
1914 * command.
1915 *
1916 * Ex.:
1917 * GIT_TEST_MAINT_SCHEDULER not set
1918 * +-------+-------------------------------------------------+
1919 * | Input | Output |
1920 * | *cmd | return code | *out | *is_available |
1921 * +-------+-------------+-------------------+---------------+
1922 * | "foo" | false | "foo" (allocated) | (unchanged) |
1923 * +-------+-------------+-------------------+---------------+
1924 *
1925 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1926 * +-------+-------------------------------------------------+
1927 * | Input | Output |
1928 * | *cmd | return code | *out | *is_available |
1929 * +-------+-------------+-------------------+---------------+
1930 * | "foo" | true | "./mock.foo.sh" | true |
1931 * | "qux" | true | "qux" (allocated) | false |
1932 * +-------+-------------+-------------------+---------------+
1933 */
1934static int get_schedule_cmd(const char *cmd, int *is_available, char **out)
1935{
1936 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1937 struct string_list_item *item;
1938 struct string_list list = STRING_LIST_INIT_NODUP;
1939
1940 if (!testing) {
1941 if (out)
1942 *out = xstrdup(cmd);
1943 return 0;
1944 }
1945
1946 if (is_available)
1947 *is_available = 0;
1948
1949 string_list_split_in_place(&list, testing, ",", -1);
1950 for_each_string_list_item(item, &list) {
1951 struct string_list pair = STRING_LIST_INIT_NODUP;
1952
1953 if (string_list_split_in_place(&pair, item->string, ":", 2) != 2)
1954 continue;
1955
1956 if (!strcmp(cmd, pair.items[0].string)) {
1957 if (out)
1958 *out = xstrdup(pair.items[1].string);
1959 if (is_available)
1960 *is_available = 1;
1961 string_list_clear(&pair, 0);
1962 goto out;
1963 }
1964
1965 string_list_clear(&pair, 0);
1966 }
1967
1968 if (out)
1969 *out = xstrdup(cmd);
1970
1971out:
1972 string_list_clear(&list, 0);
1973 free(testing);
1974 return 1;
1975}
1976
1977static int get_random_minute(void)
1978{
1979 /* Use a static value when under tests. */
1980 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
1981 return 13;
1982
1983 return git_rand(0) % 60;
1984}
1985
1986static int is_launchctl_available(void)
1987{
1988 int is_available;
1989 if (get_schedule_cmd("launchctl", &is_available, NULL))
1990 return is_available;
1991
1992#ifdef __APPLE__
1993 return 1;
1994#else
1995 return 0;
1996#endif
1997}
1998
1999static char *launchctl_service_name(const char *frequency)
2000{
2001 struct strbuf label = STRBUF_INIT;
2002 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
2003 return strbuf_detach(&label, NULL);
2004}
2005
2006static char *launchctl_service_filename(const char *name)
2007{
2008 char *expanded;
2009 struct strbuf filename = STRBUF_INIT;
2010 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
2011
2012 expanded = interpolate_path(filename.buf, 1);
2013 if (!expanded)
2014 die(_("failed to expand path '%s'"), filename.buf);
2015
2016 strbuf_release(&filename);
2017 return expanded;
2018}
2019
2020static char *launchctl_get_uid(void)
2021{
2022 return xstrfmt("gui/%d", getuid());
2023}
2024
2025static int launchctl_boot_plist(int enable, const char *filename)
2026{
2027 char *cmd;
2028 int result;
2029 struct child_process child = CHILD_PROCESS_INIT;
2030 char *uid = launchctl_get_uid();
2031
2032 get_schedule_cmd("launchctl", NULL, &cmd);
2033 strvec_split(&child.args, cmd);
2034 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
2035 filename, NULL);
2036
2037 child.no_stderr = 1;
2038 child.no_stdout = 1;
2039
2040 if (start_command(&child))
2041 die(_("failed to start launchctl"));
2042
2043 result = finish_command(&child);
2044
2045 free(cmd);
2046 free(uid);
2047 return result;
2048}
2049
2050static int launchctl_remove_plist(enum schedule_priority schedule)
2051{
2052 const char *frequency = get_frequency(schedule);
2053 char *name = launchctl_service_name(frequency);
2054 char *filename = launchctl_service_filename(name);
2055 int result = launchctl_boot_plist(0, filename);
2056 unlink(filename);
2057 free(filename);
2058 free(name);
2059 return result;
2060}
2061
2062static int launchctl_remove_plists(void)
2063{
2064 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
2065 launchctl_remove_plist(SCHEDULE_DAILY) ||
2066 launchctl_remove_plist(SCHEDULE_WEEKLY);
2067}
2068
2069static int launchctl_list_contains_plist(const char *name, const char *cmd)
2070{
2071 struct child_process child = CHILD_PROCESS_INIT;
2072
2073 strvec_split(&child.args, cmd);
2074 strvec_pushl(&child.args, "list", name, NULL);
2075
2076 child.no_stderr = 1;
2077 child.no_stdout = 1;
2078
2079 if (start_command(&child))
2080 die(_("failed to start launchctl"));
2081
2082 /* Returns failure if 'name' doesn't exist. */
2083 return !finish_command(&child);
2084}
2085
2086static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
2087{
2088 int i, fd;
2089 const char *preamble, *repeat;
2090 const char *frequency = get_frequency(schedule);
2091 char *name = launchctl_service_name(frequency);
2092 char *filename = launchctl_service_filename(name);
2093 struct lock_file lk = LOCK_INIT;
2094 static unsigned long lock_file_timeout_ms = ULONG_MAX;
2095 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
2096 struct stat st;
2097 char *cmd;
2098 int minute = get_random_minute();
2099
2100 get_schedule_cmd("launchctl", NULL, &cmd);
2101 preamble = "<?xml version=\"1.0\"?>\n"
2102 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
2103 "<plist version=\"1.0\">"
2104 "<dict>\n"
2105 "<key>Label</key><string>%s</string>\n"
2106 "<key>ProgramArguments</key>\n"
2107 "<array>\n"
2108 "<string>%s/git</string>\n"
2109 "<string>--exec-path=%s</string>\n"
2110 "%s" /* For extra config parameters. */
2111 "<string>for-each-repo</string>\n"
2112 "<string>--keep-going</string>\n"
2113 "<string>--config=maintenance.repo</string>\n"
2114 "<string>maintenance</string>\n"
2115 "<string>run</string>\n"
2116 "<string>--schedule=%s</string>\n"
2117 "</array>\n"
2118 "<key>StartCalendarInterval</key>\n"
2119 "<array>\n";
2120 strbuf_addf(&plist, preamble, name, exec_path, exec_path,
2121 get_extra_launchctl_strings(), frequency);
2122
2123 switch (schedule) {
2124 case SCHEDULE_HOURLY:
2125 repeat = "<dict>\n"
2126 "<key>Hour</key><integer>%d</integer>\n"
2127 "<key>Minute</key><integer>%d</integer>\n"
2128 "</dict>\n";
2129 for (i = 1; i <= 23; i++)
2130 strbuf_addf(&plist, repeat, i, minute);
2131 break;
2132
2133 case SCHEDULE_DAILY:
2134 repeat = "<dict>\n"
2135 "<key>Weekday</key><integer>%d</integer>\n"
2136 "<key>Hour</key><integer>0</integer>\n"
2137 "<key>Minute</key><integer>%d</integer>\n"
2138 "</dict>\n";
2139 for (i = 1; i <= 6; i++)
2140 strbuf_addf(&plist, repeat, i, minute);
2141 break;
2142
2143 case SCHEDULE_WEEKLY:
2144 strbuf_addf(&plist,
2145 "<dict>\n"
2146 "<key>Weekday</key><integer>0</integer>\n"
2147 "<key>Hour</key><integer>0</integer>\n"
2148 "<key>Minute</key><integer>%d</integer>\n"
2149 "</dict>\n",
2150 minute);
2151 break;
2152
2153 default:
2154 /* unreachable */
2155 break;
2156 }
2157 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
2158
2159 if (safe_create_leading_directories(the_repository, filename))
2160 die(_("failed to create directories for '%s'"), filename);
2161
2162 if ((long)lock_file_timeout_ms < 0 &&
2163 repo_config_get_ulong(the_repository, "gc.launchctlplistlocktimeoutms",
2164 &lock_file_timeout_ms))
2165 lock_file_timeout_ms = 150;
2166
2167 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
2168 lock_file_timeout_ms);
2169
2170 /*
2171 * Does this file already exist? With the intended contents? Is it
2172 * registered already? Then it does not need to be re-registered.
2173 */
2174 if (!stat(filename, &st) && st.st_size == plist.len &&
2175 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
2176 !strbuf_cmp(&plist, &plist2) &&
2177 launchctl_list_contains_plist(name, cmd))
2178 rollback_lock_file(&lk);
2179 else {
2180 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
2181 commit_lock_file(&lk))
2182 die_errno(_("could not write '%s'"), filename);
2183
2184 /* bootout might fail if not already running, so ignore */
2185 launchctl_boot_plist(0, filename);
2186 if (launchctl_boot_plist(1, filename))
2187 die(_("failed to bootstrap service %s"), filename);
2188 }
2189
2190 free(filename);
2191 free(name);
2192 free(cmd);
2193 strbuf_release(&plist);
2194 strbuf_release(&plist2);
2195 return 0;
2196}
2197
2198static int launchctl_add_plists(void)
2199{
2200 const char *exec_path = git_exec_path();
2201
2202 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
2203 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
2204 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
2205}
2206
2207static int launchctl_update_schedule(int run_maintenance, int fd UNUSED)
2208{
2209 if (run_maintenance)
2210 return launchctl_add_plists();
2211 else
2212 return launchctl_remove_plists();
2213}
2214
2215static int is_schtasks_available(void)
2216{
2217 int is_available;
2218 if (get_schedule_cmd("schtasks", &is_available, NULL))
2219 return is_available;
2220
2221#ifdef GIT_WINDOWS_NATIVE
2222 return 1;
2223#else
2224 return 0;
2225#endif
2226}
2227
2228static char *schtasks_task_name(const char *frequency)
2229{
2230 struct strbuf label = STRBUF_INIT;
2231 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
2232 return strbuf_detach(&label, NULL);
2233}
2234
2235static int schtasks_remove_task(enum schedule_priority schedule)
2236{
2237 char *cmd;
2238 struct child_process child = CHILD_PROCESS_INIT;
2239 const char *frequency = get_frequency(schedule);
2240 char *name = schtasks_task_name(frequency);
2241
2242 get_schedule_cmd("schtasks", NULL, &cmd);
2243 strvec_split(&child.args, cmd);
2244 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
2245 free(name);
2246 free(cmd);
2247
2248 return run_command(&child);
2249}
2250
2251static int schtasks_remove_tasks(void)
2252{
2253 return schtasks_remove_task(SCHEDULE_HOURLY) ||
2254 schtasks_remove_task(SCHEDULE_DAILY) ||
2255 schtasks_remove_task(SCHEDULE_WEEKLY);
2256}
2257
2258static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
2259{
2260 char *cmd;
2261 int result;
2262 struct child_process child = CHILD_PROCESS_INIT;
2263 const char *xml;
2264 struct tempfile *tfile;
2265 const char *frequency = get_frequency(schedule);
2266 char *name = schtasks_task_name(frequency);
2267 struct strbuf tfilename = STRBUF_INIT;
2268 int minute = get_random_minute();
2269
2270 get_schedule_cmd("schtasks", NULL, &cmd);
2271
2272 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
2273 repo_get_common_dir(the_repository), frequency);
2274 tfile = xmks_tempfile(tfilename.buf);
2275 strbuf_release(&tfilename);
2276
2277 if (!fdopen_tempfile(tfile, "w"))
2278 die(_("failed to create temp xml file"));
2279
2280 xml = "<?xml version=\"1.0\" ?>\n"
2281 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2282 "<Triggers>\n"
2283 "<CalendarTrigger>\n";
2284 fputs(xml, tfile->fp);
2285
2286 switch (schedule) {
2287 case SCHEDULE_HOURLY:
2288 fprintf(tfile->fp,
2289 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2290 "<Enabled>true</Enabled>\n"
2291 "<ScheduleByDay>\n"
2292 "<DaysInterval>1</DaysInterval>\n"
2293 "</ScheduleByDay>\n"
2294 "<Repetition>\n"
2295 "<Interval>PT1H</Interval>\n"
2296 "<Duration>PT23H</Duration>\n"
2297 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2298 "</Repetition>\n",
2299 minute);
2300 break;
2301
2302 case SCHEDULE_DAILY:
2303 fprintf(tfile->fp,
2304 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2305 "<Enabled>true</Enabled>\n"
2306 "<ScheduleByWeek>\n"
2307 "<DaysOfWeek>\n"
2308 "<Monday />\n"
2309 "<Tuesday />\n"
2310 "<Wednesday />\n"
2311 "<Thursday />\n"
2312 "<Friday />\n"
2313 "<Saturday />\n"
2314 "</DaysOfWeek>\n"
2315 "<WeeksInterval>1</WeeksInterval>\n"
2316 "</ScheduleByWeek>\n",
2317 minute);
2318 break;
2319
2320 case SCHEDULE_WEEKLY:
2321 fprintf(tfile->fp,
2322 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2323 "<Enabled>true</Enabled>\n"
2324 "<ScheduleByWeek>\n"
2325 "<DaysOfWeek>\n"
2326 "<Sunday />\n"
2327 "</DaysOfWeek>\n"
2328 "<WeeksInterval>1</WeeksInterval>\n"
2329 "</ScheduleByWeek>\n",
2330 minute);
2331 break;
2332
2333 default:
2334 break;
2335 }
2336
2337 xml = "</CalendarTrigger>\n"
2338 "</Triggers>\n"
2339 "<Principals>\n"
2340 "<Principal id=\"Author\">\n"
2341 "<LogonType>InteractiveToken</LogonType>\n"
2342 "<RunLevel>LeastPrivilege</RunLevel>\n"
2343 "</Principal>\n"
2344 "</Principals>\n"
2345 "<Settings>\n"
2346 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2347 "<Enabled>true</Enabled>\n"
2348 "<Hidden>true</Hidden>\n"
2349 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2350 "<WakeToRun>false</WakeToRun>\n"
2351 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2352 "<Priority>7</Priority>\n"
2353 "</Settings>\n"
2354 "<Actions Context=\"Author\">\n"
2355 "<Exec>\n"
2356 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2357 "<Arguments>--exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2358 "</Exec>\n"
2359 "</Actions>\n"
2360 "</Task>\n";
2361 fprintf(tfile->fp, xml, exec_path, exec_path,
2362 get_extra_config_parameters(), frequency);
2363 strvec_split(&child.args, cmd);
2364 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2365 get_tempfile_path(tfile), NULL);
2366 close_tempfile_gently(tfile);
2367
2368 child.no_stdout = 1;
2369 child.no_stderr = 1;
2370
2371 if (start_command(&child))
2372 die(_("failed to start schtasks"));
2373 result = finish_command(&child);
2374
2375 delete_tempfile(&tfile);
2376 free(name);
2377 free(cmd);
2378 return result;
2379}
2380
2381static int schtasks_schedule_tasks(void)
2382{
2383 const char *exec_path = git_exec_path();
2384
2385 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2386 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2387 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
2388}
2389
2390static int schtasks_update_schedule(int run_maintenance, int fd UNUSED)
2391{
2392 if (run_maintenance)
2393 return schtasks_schedule_tasks();
2394 else
2395 return schtasks_remove_tasks();
2396}
2397
2398MAYBE_UNUSED
2399static int check_crontab_process(const char *cmd)
2400{
2401 struct child_process child = CHILD_PROCESS_INIT;
2402
2403 strvec_split(&child.args, cmd);
2404 strvec_push(&child.args, "-l");
2405 child.no_stdin = 1;
2406 child.no_stdout = 1;
2407 child.no_stderr = 1;
2408 child.silent_exec_failure = 1;
2409
2410 if (start_command(&child))
2411 return 0;
2412 /* Ignore exit code, as an empty crontab will return error. */
2413 finish_command(&child);
2414 return 1;
2415}
2416
2417static int is_crontab_available(void)
2418{
2419 char *cmd;
2420 int is_available;
2421 int ret;
2422
2423 if (get_schedule_cmd("crontab", &is_available, &cmd)) {
2424 ret = is_available;
2425 goto out;
2426 }
2427
2428#ifdef __APPLE__
2429 /*
2430 * macOS has cron, but it requires special permissions and will
2431 * create a UI alert when attempting to run this command.
2432 */
2433 ret = 0;
2434#else
2435 ret = check_crontab_process(cmd);
2436#endif
2437
2438out:
2439 free(cmd);
2440 return ret;
2441}
2442
2443#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2444#define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2445
2446static int crontab_update_schedule(int run_maintenance, int fd)
2447{
2448 char *cmd;
2449 int result = 0;
2450 int in_old_region = 0;
2451 struct child_process crontab_list = CHILD_PROCESS_INIT;
2452 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2453 FILE *cron_list, *cron_in;
2454 struct strbuf line = STRBUF_INIT;
2455 struct tempfile *tmpedit = NULL;
2456 int minute = get_random_minute();
2457
2458 get_schedule_cmd("crontab", NULL, &cmd);
2459 strvec_split(&crontab_list.args, cmd);
2460 strvec_push(&crontab_list.args, "-l");
2461 crontab_list.in = -1;
2462 crontab_list.out = dup(fd);
2463 crontab_list.git_cmd = 0;
2464
2465 if (start_command(&crontab_list)) {
2466 result = error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2467 goto out;
2468 }
2469
2470 /* Ignore exit code, as an empty crontab will return error. */
2471 finish_command(&crontab_list);
2472
2473 tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2474 if (!tmpedit) {
2475 result = error(_("failed to create crontab temporary file"));
2476 goto out;
2477 }
2478 cron_in = fdopen_tempfile(tmpedit, "w");
2479 if (!cron_in) {
2480 result = error(_("failed to open temporary file"));
2481 goto out;
2482 }
2483
2484 /*
2485 * Read from the .lock file, filtering out the old
2486 * schedule while appending the new schedule.
2487 */
2488 cron_list = fdopen(fd, "r");
2489 rewind(cron_list);
2490
2491 while (!strbuf_getline_lf(&line, cron_list)) {
2492 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2493 in_old_region = 1;
2494 else if (in_old_region && !strcmp(line.buf, END_LINE))
2495 in_old_region = 0;
2496 else if (!in_old_region)
2497 fprintf(cron_in, "%s\n", line.buf);
2498 }
2499 strbuf_release(&line);
2500
2501 if (run_maintenance) {
2502 struct strbuf line_format = STRBUF_INIT;
2503 const char *exec_path = git_exec_path();
2504
2505 fprintf(cron_in, "%s\n", BEGIN_LINE);
2506 fprintf(cron_in,
2507 "# The following schedule was created by Git\n");
2508 fprintf(cron_in, "# Any edits made in this region might be\n");
2509 fprintf(cron_in,
2510 "# replaced in the future by a Git command.\n\n");
2511
2512 strbuf_addf(&line_format,
2513 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%s\n",
2514 exec_path, exec_path, get_extra_config_parameters());
2515 fprintf(cron_in, line_format.buf, minute, "1-23", "*", "hourly");
2516 fprintf(cron_in, line_format.buf, minute, "0", "1-6", "daily");
2517 fprintf(cron_in, line_format.buf, minute, "0", "0", "weekly");
2518 strbuf_release(&line_format);
2519
2520 fprintf(cron_in, "\n%s\n", END_LINE);
2521 }
2522
2523 fflush(cron_in);
2524
2525 strvec_split(&crontab_edit.args, cmd);
2526 strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2527 crontab_edit.git_cmd = 0;
2528
2529 if (start_command(&crontab_edit)) {
2530 result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2531 goto out;
2532 }
2533
2534 if (finish_command(&crontab_edit))
2535 result = error(_("'crontab' died"));
2536 else
2537 fclose(cron_list);
2538
2539out:
2540 delete_tempfile(&tmpedit);
2541 free(cmd);
2542 return result;
2543}
2544
2545static int real_is_systemd_timer_available(void)
2546{
2547 struct child_process child = CHILD_PROCESS_INIT;
2548
2549 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2550 child.no_stdin = 1;
2551 child.no_stdout = 1;
2552 child.no_stderr = 1;
2553 child.silent_exec_failure = 1;
2554
2555 if (start_command(&child))
2556 return 0;
2557 if (finish_command(&child))
2558 return 0;
2559 return 1;
2560}
2561
2562static int is_systemd_timer_available(void)
2563{
2564 int is_available;
2565
2566 if (get_schedule_cmd("systemctl", &is_available, NULL))
2567 return is_available;
2568
2569 return real_is_systemd_timer_available();
2570}
2571
2572static char *xdg_config_home_systemd(const char *filename)
2573{
2574 return xdg_config_home_for("systemd/user", filename);
2575}
2576
2577#define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2578
2579static int systemd_timer_delete_timer_file(enum schedule_priority priority)
2580{
2581 int ret = 0;
2582 const char *frequency = get_frequency(priority);
2583 char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2584 char *filename = xdg_config_home_systemd(local_timer_name);
2585
2586 if (unlink(filename) && !is_missing_file_error(errno))
2587 ret = error_errno(_("failed to delete '%s'"), filename);
2588
2589 free(filename);
2590 free(local_timer_name);
2591 return ret;
2592}
2593
2594static int systemd_timer_delete_service_template(void)
2595{
2596 int ret = 0;
2597 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2598 char *filename = xdg_config_home_systemd(local_service_name);
2599 if (unlink(filename) && !is_missing_file_error(errno))
2600 ret = error_errno(_("failed to delete '%s'"), filename);
2601
2602 free(filename);
2603 free(local_service_name);
2604 return ret;
2605}
2606
2607/*
2608 * Write the schedule information into a git-maintenance@<schedule>.timer
2609 * file using a custom minute. This timer file cannot use the templating
2610 * system, so we generate a specific file for each.
2611 */
2612static int systemd_timer_write_timer_file(enum schedule_priority schedule,
2613 int minute)
2614{
2615 int res = -1;
2616 char *filename;
2617 FILE *file;
2618 const char *unit;
2619 char *schedule_pattern = NULL;
2620 const char *frequency = get_frequency(schedule);
2621 char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2622
2623 filename = xdg_config_home_systemd(local_timer_name);
2624
2625 if (safe_create_leading_directories(the_repository, filename)) {
2626 error(_("failed to create directories for '%s'"), filename);
2627 goto error;
2628 }
2629 file = fopen_or_warn(filename, "w");
2630 if (!file)
2631 goto error;
2632
2633 switch (schedule) {
2634 case SCHEDULE_HOURLY:
2635 schedule_pattern = xstrfmt("*-*-* 1..23:%02d:00", minute);
2636 break;
2637
2638 case SCHEDULE_DAILY:
2639 schedule_pattern = xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute);
2640 break;
2641
2642 case SCHEDULE_WEEKLY:
2643 schedule_pattern = xstrfmt("Mon 0:%02d:00", minute);
2644 break;
2645
2646 default:
2647 BUG("Unhandled schedule_priority");
2648 }
2649
2650 unit = "# This file was created and is maintained by Git.\n"
2651 "# Any edits made in this file might be replaced in the future\n"
2652 "# by a Git command.\n"
2653 "\n"
2654 "[Unit]\n"
2655 "Description=Optimize Git repositories data\n"
2656 "\n"
2657 "[Timer]\n"
2658 "OnCalendar=%s\n"
2659 "Persistent=true\n"
2660 "\n"
2661 "[Install]\n"
2662 "WantedBy=timers.target\n";
2663 if (fprintf(file, unit, schedule_pattern) < 0) {
2664 error(_("failed to write to '%s'"), filename);
2665 fclose(file);
2666 goto error;
2667 }
2668 if (fclose(file) == EOF) {
2669 error_errno(_("failed to flush '%s'"), filename);
2670 goto error;
2671 }
2672
2673 res = 0;
2674
2675error:
2676 free(schedule_pattern);
2677 free(local_timer_name);
2678 free(filename);
2679 return res;
2680}
2681
2682/*
2683 * No matter the schedule, we use the same service and can make use of the
2684 * templating system. When installing git-maintenance@<schedule>.timer,
2685 * systemd will notice that git-maintenance@.service exists as a template
2686 * and will use this file and insert the <schedule> into the template at
2687 * the position of "%i".
2688 */
2689static int systemd_timer_write_service_template(const char *exec_path)
2690{
2691 int res = -1;
2692 char *filename;
2693 FILE *file;
2694 const char *unit;
2695 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2696
2697 filename = xdg_config_home_systemd(local_service_name);
2698 if (safe_create_leading_directories(the_repository, filename)) {
2699 error(_("failed to create directories for '%s'"), filename);
2700 goto error;
2701 }
2702 file = fopen_or_warn(filename, "w");
2703 if (!file)
2704 goto error;
2705
2706 unit = "# This file was created and is maintained by Git.\n"
2707 "# Any edits made in this file might be replaced in the future\n"
2708 "# by a Git command.\n"
2709 "\n"
2710 "[Unit]\n"
2711 "Description=Optimize Git repositories data\n"
2712 "\n"
2713 "[Service]\n"
2714 "Type=oneshot\n"
2715 "ExecStart=\"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
2716 "LockPersonality=yes\n"
2717 "MemoryDenyWriteExecute=yes\n"
2718 "NoNewPrivileges=yes\n"
2719 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
2720 "RestrictNamespaces=yes\n"
2721 "RestrictRealtime=yes\n"
2722 "RestrictSUIDSGID=yes\n"
2723 "SystemCallArchitectures=native\n"
2724 "SystemCallFilter=@system-service\n";
2725 if (fprintf(file, unit, exec_path, exec_path, get_extra_config_parameters()) < 0) {
2726 error(_("failed to write to '%s'"), filename);
2727 fclose(file);
2728 goto error;
2729 }
2730 if (fclose(file) == EOF) {
2731 error_errno(_("failed to flush '%s'"), filename);
2732 goto error;
2733 }
2734
2735 res = 0;
2736
2737error:
2738 free(local_service_name);
2739 free(filename);
2740 return res;
2741}
2742
2743static int systemd_timer_enable_unit(int enable,
2744 enum schedule_priority schedule,
2745 int minute)
2746{
2747 char *cmd = NULL;
2748 struct child_process child = CHILD_PROCESS_INIT;
2749 const char *frequency = get_frequency(schedule);
2750 int ret;
2751
2752 /*
2753 * Disabling the systemd unit while it is already disabled makes
2754 * systemctl print an error.
2755 * Let's ignore it since it means we already are in the expected state:
2756 * the unit is disabled.
2757 *
2758 * On the other hand, enabling a systemd unit which is already enabled
2759 * produces no error.
2760 */
2761 if (!enable) {
2762 child.no_stderr = 1;
2763 } else if (systemd_timer_write_timer_file(schedule, minute)) {
2764 ret = -1;
2765 goto out;
2766 }
2767
2768 get_schedule_cmd("systemctl", NULL, &cmd);
2769 strvec_split(&child.args, cmd);
2770 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2771 "--now", NULL);
2772 strvec_pushf(&child.args, SYSTEMD_UNIT_FORMAT, frequency, "timer");
2773
2774 if (start_command(&child)) {
2775 ret = error(_("failed to start systemctl"));
2776 goto out;
2777 }
2778
2779 if (finish_command(&child)) {
2780 /*
2781 * Disabling an already disabled systemd unit makes
2782 * systemctl fail.
2783 * Let's ignore this failure.
2784 *
2785 * Enabling an enabled systemd unit doesn't fail.
2786 */
2787 if (enable) {
2788 ret = error(_("failed to run systemctl"));
2789 goto out;
2790 }
2791 }
2792
2793 ret = 0;
2794
2795out:
2796 free(cmd);
2797 return ret;
2798}
2799
2800/*
2801 * A previous version of Git wrote the timer units as template files.
2802 * Clean these up, if they exist.
2803 */
2804static void systemd_timer_delete_stale_timer_templates(void)
2805{
2806 char *timer_template_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "timer");
2807 char *filename = xdg_config_home_systemd(timer_template_name);
2808
2809 if (unlink(filename) && !is_missing_file_error(errno))
2810 warning(_("failed to delete '%s'"), filename);
2811
2812 free(filename);
2813 free(timer_template_name);
2814}
2815
2816static int systemd_timer_delete_unit_files(void)
2817{
2818 systemd_timer_delete_stale_timer_templates();
2819
2820 /* Purposefully not short-circuited to make sure all are called. */
2821 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY) |
2822 systemd_timer_delete_timer_file(SCHEDULE_DAILY) |
2823 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY) |
2824 systemd_timer_delete_service_template();
2825}
2826
2827static int systemd_timer_delete_units(void)
2828{
2829 int minute = get_random_minute();
2830 /* Purposefully not short-circuited to make sure all are called. */
2831 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY, minute) |
2832 systemd_timer_enable_unit(0, SCHEDULE_DAILY, minute) |
2833 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY, minute) |
2834 systemd_timer_delete_unit_files();
2835}
2836
2837static int systemd_timer_setup_units(void)
2838{
2839 int minute = get_random_minute();
2840 const char *exec_path = git_exec_path();
2841
2842 int ret = systemd_timer_write_service_template(exec_path) ||
2843 systemd_timer_enable_unit(1, SCHEDULE_HOURLY, minute) ||
2844 systemd_timer_enable_unit(1, SCHEDULE_DAILY, minute) ||
2845 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY, minute);
2846
2847 if (ret)
2848 systemd_timer_delete_units();
2849 else
2850 systemd_timer_delete_stale_timer_templates();
2851
2852 return ret;
2853}
2854
2855static int systemd_timer_update_schedule(int run_maintenance, int fd UNUSED)
2856{
2857 if (run_maintenance)
2858 return systemd_timer_setup_units();
2859 else
2860 return systemd_timer_delete_units();
2861}
2862
2863enum scheduler {
2864 SCHEDULER_INVALID = -1,
2865 SCHEDULER_AUTO,
2866 SCHEDULER_CRON,
2867 SCHEDULER_SYSTEMD,
2868 SCHEDULER_LAUNCHCTL,
2869 SCHEDULER_SCHTASKS,
2870};
2871
2872static const struct {
2873 const char *name;
2874 int (*is_available)(void);
2875 int (*update_schedule)(int run_maintenance, int fd);
2876} scheduler_fn[] = {
2877 [SCHEDULER_CRON] = {
2878 .name = "crontab",
2879 .is_available = is_crontab_available,
2880 .update_schedule = crontab_update_schedule,
2881 },
2882 [SCHEDULER_SYSTEMD] = {
2883 .name = "systemctl",
2884 .is_available = is_systemd_timer_available,
2885 .update_schedule = systemd_timer_update_schedule,
2886 },
2887 [SCHEDULER_LAUNCHCTL] = {
2888 .name = "launchctl",
2889 .is_available = is_launchctl_available,
2890 .update_schedule = launchctl_update_schedule,
2891 },
2892 [SCHEDULER_SCHTASKS] = {
2893 .name = "schtasks",
2894 .is_available = is_schtasks_available,
2895 .update_schedule = schtasks_update_schedule,
2896 },
2897};
2898
2899static enum scheduler parse_scheduler(const char *value)
2900{
2901 if (!value)
2902 return SCHEDULER_INVALID;
2903 else if (!strcasecmp(value, "auto"))
2904 return SCHEDULER_AUTO;
2905 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2906 return SCHEDULER_CRON;
2907 else if (!strcasecmp(value, "systemd") ||
2908 !strcasecmp(value, "systemd-timer"))
2909 return SCHEDULER_SYSTEMD;
2910 else if (!strcasecmp(value, "launchctl"))
2911 return SCHEDULER_LAUNCHCTL;
2912 else if (!strcasecmp(value, "schtasks"))
2913 return SCHEDULER_SCHTASKS;
2914 else
2915 return SCHEDULER_INVALID;
2916}
2917
2918static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2919 int unset)
2920{
2921 enum scheduler *scheduler = opt->value;
2922
2923 BUG_ON_OPT_NEG(unset);
2924
2925 *scheduler = parse_scheduler(arg);
2926 if (*scheduler == SCHEDULER_INVALID)
2927 return error(_("unrecognized --scheduler argument '%s'"), arg);
2928 return 0;
2929}
2930
2931struct maintenance_start_opts {
2932 enum scheduler scheduler;
2933};
2934
2935static enum scheduler resolve_scheduler(enum scheduler scheduler)
2936{
2937 if (scheduler != SCHEDULER_AUTO)
2938 return scheduler;
2939
2940#if defined(__APPLE__)
2941 return SCHEDULER_LAUNCHCTL;
2942
2943#elif defined(GIT_WINDOWS_NATIVE)
2944 return SCHEDULER_SCHTASKS;
2945
2946#elif defined(__linux__)
2947 if (is_systemd_timer_available())
2948 return SCHEDULER_SYSTEMD;
2949 else if (is_crontab_available())
2950 return SCHEDULER_CRON;
2951 else
2952 die(_("neither systemd timers nor crontab are available"));
2953
2954#else
2955 return SCHEDULER_CRON;
2956#endif
2957}
2958
2959static void validate_scheduler(enum scheduler scheduler)
2960{
2961 if (scheduler == SCHEDULER_INVALID)
2962 BUG("invalid scheduler");
2963 if (scheduler == SCHEDULER_AUTO)
2964 BUG("resolve_scheduler should have been called before");
2965
2966 if (!scheduler_fn[scheduler].is_available())
2967 die(_("%s scheduler is not available"),
2968 scheduler_fn[scheduler].name);
2969}
2970
2971static int update_background_schedule(const struct maintenance_start_opts *opts,
2972 int enable)
2973{
2974 unsigned int i;
2975 int result = 0;
2976 struct lock_file lk;
2977 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->source->path);
2978
2979 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2980 if (errno == EEXIST)
2981 error(_("unable to create '%s.lock': %s.\n\n"
2982 "Another scheduled git-maintenance(1) process seems to be running in this\n"
2983 "repository. Please make sure no other maintenance processes are running and\n"
2984 "then try again. If it still fails, a git-maintenance(1) process may have\n"
2985 "crashed in this repository earlier: remove the file manually to continue."),
2986 absolute_path(lock_path), strerror(errno));
2987 else
2988 error_errno(_("cannot acquire lock for scheduled background maintenance"));
2989 free(lock_path);
2990 return -1;
2991 }
2992
2993 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2994 if (enable && opts->scheduler == i)
2995 continue;
2996 if (!scheduler_fn[i].is_available())
2997 continue;
2998 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2999 }
3000
3001 if (enable)
3002 result = scheduler_fn[opts->scheduler].update_schedule(
3003 1, get_lock_file_fd(&lk));
3004
3005 rollback_lock_file(&lk);
3006
3007 free(lock_path);
3008 return result;
3009}
3010
3011static const char *const builtin_maintenance_start_usage[] = {
3012 N_("git maintenance start [--scheduler=<scheduler>]"),
3013 NULL
3014};
3015
3016static int maintenance_start(int argc, const char **argv, const char *prefix,
3017 struct repository *repo)
3018{
3019 struct maintenance_start_opts opts = { 0 };
3020 struct option options[] = {
3021 OPT_CALLBACK_F(
3022 0, "scheduler", &opts.scheduler, N_("scheduler"),
3023 N_("scheduler to trigger git maintenance run"),
3024 PARSE_OPT_NONEG, maintenance_opt_scheduler),
3025 OPT_END()
3026 };
3027 const char *register_args[] = { "register", NULL };
3028
3029 argc = parse_options(argc, argv, prefix, options,
3030 builtin_maintenance_start_usage, 0);
3031 if (argc)
3032 usage_with_options(builtin_maintenance_start_usage, options);
3033
3034 opts.scheduler = resolve_scheduler(opts.scheduler);
3035 validate_scheduler(opts.scheduler);
3036
3037 if (update_background_schedule(&opts, 1))
3038 die(_("failed to set up maintenance schedule"));
3039
3040 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL, repo))
3041 warning(_("failed to add repo to global config"));
3042 return 0;
3043}
3044
3045static const char *const builtin_maintenance_stop_usage[] = {
3046 "git maintenance stop",
3047 NULL
3048};
3049
3050static int maintenance_stop(int argc, const char **argv, const char *prefix,
3051 struct repository *repo UNUSED)
3052{
3053 struct option options[] = {
3054 OPT_END()
3055 };
3056 argc = parse_options(argc, argv, prefix, options,
3057 builtin_maintenance_stop_usage, 0);
3058 if (argc)
3059 usage_with_options(builtin_maintenance_stop_usage, options);
3060 return update_background_schedule(NULL, 0);
3061}
3062
3063static const char *const builtin_maintenance_is_needed_usage[] = {
3064 "git maintenance is-needed [--task=<task>] [--schedule]",
3065 NULL
3066};
3067
3068static int maintenance_is_needed(int argc, const char **argv, const char *prefix,
3069 struct repository *repo UNUSED)
3070{
3071 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
3072 struct string_list selected_tasks = STRING_LIST_INIT_DUP;
3073 struct gc_config cfg = GC_CONFIG_INIT;
3074 struct option options[] = {
3075 OPT_BOOL(0, "auto", &opts.auto_flag,
3076 N_("run tasks based on the state of the repository")),
3077 OPT_CALLBACK_F(0, "task", &selected_tasks, N_("task"),
3078 N_("check a specific task"),
3079 PARSE_OPT_NONEG, task_option_parse),
3080 OPT_END()
3081 };
3082 bool is_needed = false;
3083
3084 argc = parse_options(argc, argv, prefix, options,
3085 builtin_maintenance_is_needed_usage,
3086 PARSE_OPT_STOP_AT_NON_OPTION);
3087 if (argc)
3088 usage_with_options(builtin_maintenance_is_needed_usage, options);
3089
3090 gc_config(&cfg);
3091 initialize_task_config(&opts, &selected_tasks);
3092
3093 if (opts.auto_flag) {
3094 for (size_t i = 0; i < opts.tasks_nr; i++) {
3095 if (tasks[opts.tasks[i]].auto_condition &&
3096 tasks[opts.tasks[i]].auto_condition(&cfg)) {
3097 is_needed = true;
3098 break;
3099 }
3100 }
3101 } else {
3102 /*
3103 * When not using --auto we always require maintenance right now.
3104 *
3105 * TODO: this certainly is too eager, as some maintenance tasks may
3106 * decide to not do anything because the data structures are already
3107 * fully optimized. We may eventually want to extend the auto
3108 * condition to also cover non-auto runs so that we can detect such
3109 * cases.
3110 */
3111 is_needed = true;
3112 }
3113
3114 string_list_clear(&selected_tasks, 0);
3115 maintenance_run_opts_release(&opts);
3116 gc_config_release(&cfg);
3117
3118 if (is_needed)
3119 return 0;
3120 return 1;
3121}
3122
3123static const char *const builtin_maintenance_usage[] = {
3124 N_("git maintenance <subcommand> [<options>]"),
3125 NULL,
3126};
3127
3128int cmd_maintenance(int argc,
3129 const char **argv,
3130 const char *prefix,
3131 struct repository *repo)
3132{
3133 parse_opt_subcommand_fn *fn = NULL;
3134 struct option builtin_maintenance_options[] = {
3135 OPT_SUBCOMMAND("run", &fn, maintenance_run),
3136 OPT_SUBCOMMAND("start", &fn, maintenance_start),
3137 OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
3138 OPT_SUBCOMMAND("register", &fn, maintenance_register),
3139 OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
3140 OPT_SUBCOMMAND("is-needed", &fn, maintenance_is_needed),
3141 OPT_END(),
3142 };
3143
3144 argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
3145 builtin_maintenance_usage, 0);
3146 return fn(argc, argv, prefix, repo);
3147}