at commit a0189536

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