]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/gc.c
Merge branch 'jk/bundle-progress'
[thirdparty/git.git] / builtin / gc.c
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 #include "builtin.h"
14 #include "hex.h"
15 #include "repository.h"
16 #include "config.h"
17 #include "tempfile.h"
18 #include "lockfile.h"
19 #include "parse-options.h"
20 #include "run-command.h"
21 #include "sigchain.h"
22 #include "strvec.h"
23 #include "commit.h"
24 #include "commit-graph.h"
25 #include "packfile.h"
26 #include "object-store.h"
27 #include "pack.h"
28 #include "pack-objects.h"
29 #include "blob.h"
30 #include "tree.h"
31 #include "promisor-remote.h"
32 #include "refs.h"
33 #include "remote.h"
34 #include "exec-cmd.h"
35 #include "hook.h"
36
37 #define FAILED_RUN "failed to run %s"
38
39 static const char * const builtin_gc_usage[] = {
40 N_("git gc [<options>]"),
41 NULL
42 };
43
44 static int pack_refs = 1;
45 static int prune_reflogs = 1;
46 static int cruft_packs = -1;
47 static int aggressive_depth = 50;
48 static int aggressive_window = 250;
49 static int gc_auto_threshold = 6700;
50 static int gc_auto_pack_limit = 50;
51 static int detach_auto = 1;
52 static timestamp_t gc_log_expire_time;
53 static const char *gc_log_expire = "1.day.ago";
54 static const char *prune_expire = "2.weeks.ago";
55 static const char *prune_worktrees_expire = "3.months.ago";
56 static unsigned long big_pack_threshold;
57 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
58
59 static struct strvec reflog = STRVEC_INIT;
60 static struct strvec repack = STRVEC_INIT;
61 static struct strvec prune = STRVEC_INIT;
62 static struct strvec prune_worktrees = STRVEC_INIT;
63 static struct strvec rerere = STRVEC_INIT;
64
65 static struct tempfile *pidfile;
66 static struct lock_file log_lock;
67
68 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
69
70 static void clean_pack_garbage(void)
71 {
72 int i;
73 for (i = 0; i < pack_garbage.nr; i++)
74 unlink_or_warn(pack_garbage.items[i].string);
75 string_list_clear(&pack_garbage, 0);
76 }
77
78 static void report_pack_garbage(unsigned seen_bits, const char *path)
79 {
80 if (seen_bits == PACKDIR_FILE_IDX)
81 string_list_append(&pack_garbage, path);
82 }
83
84 static void process_log_file(void)
85 {
86 struct stat st;
87 if (fstat(get_lock_file_fd(&log_lock), &st)) {
88 /*
89 * Perhaps there was an i/o error or another
90 * unlikely situation. Try to make a note of
91 * this in gc.log along with any existing
92 * messages.
93 */
94 int saved_errno = errno;
95 fprintf(stderr, _("Failed to fstat %s: %s"),
96 get_lock_file_path(&log_lock),
97 strerror(saved_errno));
98 fflush(stderr);
99 commit_lock_file(&log_lock);
100 errno = saved_errno;
101 } else if (st.st_size) {
102 /* There was some error recorded in the lock file */
103 commit_lock_file(&log_lock);
104 } else {
105 /* No error, clean up any old gc.log */
106 unlink(git_path("gc.log"));
107 rollback_lock_file(&log_lock);
108 }
109 }
110
111 static void process_log_file_at_exit(void)
112 {
113 fflush(stderr);
114 process_log_file();
115 }
116
117 static void process_log_file_on_signal(int signo)
118 {
119 process_log_file();
120 sigchain_pop(signo);
121 raise(signo);
122 }
123
124 static int gc_config_is_timestamp_never(const char *var)
125 {
126 const char *value;
127 timestamp_t expire;
128
129 if (!git_config_get_value(var, &value) && value) {
130 if (parse_expiry_date(value, &expire))
131 die(_("failed to parse '%s' value '%s'"), var, value);
132 return expire == 0;
133 }
134 return 0;
135 }
136
137 static void gc_config(void)
138 {
139 const char *value;
140
141 if (!git_config_get_value("gc.packrefs", &value)) {
142 if (value && !strcmp(value, "notbare"))
143 pack_refs = -1;
144 else
145 pack_refs = git_config_bool("gc.packrefs", value);
146 }
147
148 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
149 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
150 prune_reflogs = 0;
151
152 git_config_get_int("gc.aggressivewindow", &aggressive_window);
153 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
154 git_config_get_int("gc.auto", &gc_auto_threshold);
155 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
156 git_config_get_bool("gc.autodetach", &detach_auto);
157 git_config_get_bool("gc.cruftpacks", &cruft_packs);
158 git_config_get_expiry("gc.pruneexpire", &prune_expire);
159 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
160 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
161
162 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
163 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
164
165 git_config(git_default_config, NULL);
166 }
167
168 struct maintenance_run_opts;
169 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
170 {
171 struct child_process cmd = CHILD_PROCESS_INIT;
172
173 cmd.git_cmd = 1;
174 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
175 return run_command(&cmd);
176 }
177
178 static int too_many_loose_objects(void)
179 {
180 /*
181 * Quickly check if a "gc" is needed, by estimating how
182 * many loose objects there are. Because SHA-1 is evenly
183 * distributed, we can check only one and get a reasonable
184 * estimate.
185 */
186 DIR *dir;
187 struct dirent *ent;
188 int auto_threshold;
189 int num_loose = 0;
190 int needed = 0;
191 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
192
193 dir = opendir(git_path("objects/17"));
194 if (!dir)
195 return 0;
196
197 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
198 while ((ent = readdir(dir)) != NULL) {
199 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
200 ent->d_name[hexsz_loose] != '\0')
201 continue;
202 if (++num_loose > auto_threshold) {
203 needed = 1;
204 break;
205 }
206 }
207 closedir(dir);
208 return needed;
209 }
210
211 static struct packed_git *find_base_packs(struct string_list *packs,
212 unsigned long limit)
213 {
214 struct packed_git *p, *base = NULL;
215
216 for (p = get_all_packs(the_repository); p; p = p->next) {
217 if (!p->pack_local)
218 continue;
219 if (limit) {
220 if (p->pack_size >= limit)
221 string_list_append(packs, p->pack_name);
222 } else if (!base || base->pack_size < p->pack_size) {
223 base = p;
224 }
225 }
226
227 if (base)
228 string_list_append(packs, base->pack_name);
229
230 return base;
231 }
232
233 static int too_many_packs(void)
234 {
235 struct packed_git *p;
236 int cnt;
237
238 if (gc_auto_pack_limit <= 0)
239 return 0;
240
241 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
242 if (!p->pack_local)
243 continue;
244 if (p->pack_keep)
245 continue;
246 /*
247 * Perhaps check the size of the pack and count only
248 * very small ones here?
249 */
250 cnt++;
251 }
252 return gc_auto_pack_limit < cnt;
253 }
254
255 static uint64_t total_ram(void)
256 {
257 #if defined(HAVE_SYSINFO)
258 struct sysinfo si;
259
260 if (!sysinfo(&si))
261 return si.totalram;
262 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
263 int64_t physical_memory;
264 int mib[2];
265 size_t length;
266
267 mib[0] = CTL_HW;
268 # if defined(HW_MEMSIZE)
269 mib[1] = HW_MEMSIZE;
270 # else
271 mib[1] = HW_PHYSMEM;
272 # endif
273 length = sizeof(int64_t);
274 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
275 return physical_memory;
276 #elif defined(GIT_WINDOWS_NATIVE)
277 MEMORYSTATUSEX memInfo;
278
279 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
280 if (GlobalMemoryStatusEx(&memInfo))
281 return memInfo.ullTotalPhys;
282 #endif
283 return 0;
284 }
285
286 static uint64_t estimate_repack_memory(struct packed_git *pack)
287 {
288 unsigned long nr_objects = approximate_object_count();
289 size_t os_cache, heap;
290
291 if (!pack || !nr_objects)
292 return 0;
293
294 /*
295 * First we have to scan through at least one pack.
296 * Assume enough room in OS file cache to keep the entire pack
297 * or we may accidentally evict data of other processes from
298 * the cache.
299 */
300 os_cache = pack->pack_size + pack->index_size;
301 /* then pack-objects needs lots more for book keeping */
302 heap = sizeof(struct object_entry) * nr_objects;
303 /*
304 * internal rev-list --all --objects takes up some memory too,
305 * let's say half of it is for blobs
306 */
307 heap += sizeof(struct blob) * nr_objects / 2;
308 /*
309 * and the other half is for trees (commits and tags are
310 * usually insignificant)
311 */
312 heap += sizeof(struct tree) * nr_objects / 2;
313 /* and then obj_hash[], underestimated in fact */
314 heap += sizeof(struct object *) * nr_objects;
315 /* revindex is used also */
316 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
317 /*
318 * read_sha1_file() (either at delta calculation phase, or
319 * writing phase) also fills up the delta base cache
320 */
321 heap += delta_base_cache_limit;
322 /* and of course pack-objects has its own delta cache */
323 heap += max_delta_cache_size;
324
325 return os_cache + heap;
326 }
327
328 static int keep_one_pack(struct string_list_item *item, void *data UNUSED)
329 {
330 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
331 return 0;
332 }
333
334 static void add_repack_all_option(struct string_list *keep_pack)
335 {
336 if (prune_expire && !strcmp(prune_expire, "now"))
337 strvec_push(&repack, "-a");
338 else if (cruft_packs) {
339 strvec_push(&repack, "--cruft");
340 if (prune_expire)
341 strvec_pushf(&repack, "--cruft-expiration=%s", prune_expire);
342 } else {
343 strvec_push(&repack, "-A");
344 if (prune_expire)
345 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
346 }
347
348 if (keep_pack)
349 for_each_string_list(keep_pack, keep_one_pack, NULL);
350 }
351
352 static void add_repack_incremental_option(void)
353 {
354 strvec_push(&repack, "--no-write-bitmap-index");
355 }
356
357 static int need_to_gc(void)
358 {
359 /*
360 * Setting gc.auto to 0 or negative can disable the
361 * automatic gc.
362 */
363 if (gc_auto_threshold <= 0)
364 return 0;
365
366 /*
367 * If there are too many loose objects, but not too many
368 * packs, we run "repack -d -l". If there are too many packs,
369 * we run "repack -A -d -l". Otherwise we tell the caller
370 * there is no need.
371 */
372 if (too_many_packs()) {
373 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
374
375 if (big_pack_threshold) {
376 find_base_packs(&keep_pack, big_pack_threshold);
377 if (keep_pack.nr >= gc_auto_pack_limit) {
378 big_pack_threshold = 0;
379 string_list_clear(&keep_pack, 0);
380 find_base_packs(&keep_pack, 0);
381 }
382 } else {
383 struct packed_git *p = find_base_packs(&keep_pack, 0);
384 uint64_t mem_have, mem_want;
385
386 mem_have = total_ram();
387 mem_want = estimate_repack_memory(p);
388
389 /*
390 * Only allow 1/2 of memory for pack-objects, leave
391 * the rest for the OS and other processes in the
392 * system.
393 */
394 if (!mem_have || mem_want < mem_have / 2)
395 string_list_clear(&keep_pack, 0);
396 }
397
398 add_repack_all_option(&keep_pack);
399 string_list_clear(&keep_pack, 0);
400 } else if (too_many_loose_objects())
401 add_repack_incremental_option();
402 else
403 return 0;
404
405 if (run_hooks("pre-auto-gc"))
406 return 0;
407 return 1;
408 }
409
410 /* return NULL on success, else hostname running the gc */
411 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
412 {
413 struct lock_file lock = LOCK_INIT;
414 char my_host[HOST_NAME_MAX + 1];
415 struct strbuf sb = STRBUF_INIT;
416 struct stat st;
417 uintmax_t pid;
418 FILE *fp;
419 int fd;
420 char *pidfile_path;
421
422 if (is_tempfile_active(pidfile))
423 /* already locked */
424 return NULL;
425
426 if (xgethostname(my_host, sizeof(my_host)))
427 xsnprintf(my_host, sizeof(my_host), "unknown");
428
429 pidfile_path = git_pathdup("gc.pid");
430 fd = hold_lock_file_for_update(&lock, pidfile_path,
431 LOCK_DIE_ON_ERROR);
432 if (!force) {
433 static char locking_host[HOST_NAME_MAX + 1];
434 static char *scan_fmt;
435 int should_exit;
436
437 if (!scan_fmt)
438 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
439 fp = fopen(pidfile_path, "r");
440 memset(locking_host, 0, sizeof(locking_host));
441 should_exit =
442 fp != NULL &&
443 !fstat(fileno(fp), &st) &&
444 /*
445 * 12 hour limit is very generous as gc should
446 * never take that long. On the other hand we
447 * don't really need a strict limit here,
448 * running gc --auto one day late is not a big
449 * problem. --force can be used in manual gc
450 * after the user verifies that no gc is
451 * running.
452 */
453 time(NULL) - st.st_mtime <= 12 * 3600 &&
454 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
455 /* be gentle to concurrent "gc" on remote hosts */
456 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
457 if (fp)
458 fclose(fp);
459 if (should_exit) {
460 if (fd >= 0)
461 rollback_lock_file(&lock);
462 *ret_pid = pid;
463 free(pidfile_path);
464 return locking_host;
465 }
466 }
467
468 strbuf_addf(&sb, "%"PRIuMAX" %s",
469 (uintmax_t) getpid(), my_host);
470 write_in_full(fd, sb.buf, sb.len);
471 strbuf_release(&sb);
472 commit_lock_file(&lock);
473 pidfile = register_tempfile(pidfile_path);
474 free(pidfile_path);
475 return NULL;
476 }
477
478 /*
479 * Returns 0 if there was no previous error and gc can proceed, 1 if
480 * gc should not proceed due to an error in the last run. Prints a
481 * message and returns with a non-[01] status code if an error occurred
482 * while reading gc.log
483 */
484 static int report_last_gc_error(void)
485 {
486 struct strbuf sb = STRBUF_INIT;
487 int ret = 0;
488 ssize_t len;
489 struct stat st;
490 char *gc_log_path = git_pathdup("gc.log");
491
492 if (stat(gc_log_path, &st)) {
493 if (errno == ENOENT)
494 goto done;
495
496 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
497 goto done;
498 }
499
500 if (st.st_mtime < gc_log_expire_time)
501 goto done;
502
503 len = strbuf_read_file(&sb, gc_log_path, 0);
504 if (len < 0)
505 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
506 else if (len > 0) {
507 /*
508 * A previous gc failed. Report the error, and don't
509 * bother with an automatic gc run since it is likely
510 * to fail in the same way.
511 */
512 warning(_("The last gc run reported the following. "
513 "Please correct the root cause\n"
514 "and remove %s\n"
515 "Automatic cleanup will not be performed "
516 "until the file is removed.\n\n"
517 "%s"),
518 gc_log_path, sb.buf);
519 ret = 1;
520 }
521 strbuf_release(&sb);
522 done:
523 free(gc_log_path);
524 return ret;
525 }
526
527 static void gc_before_repack(void)
528 {
529 /*
530 * We may be called twice, as both the pre- and
531 * post-daemonized phases will call us, but running these
532 * commands more than once is pointless and wasteful.
533 */
534 static int done = 0;
535 if (done++)
536 return;
537
538 if (pack_refs && maintenance_task_pack_refs(NULL))
539 die(FAILED_RUN, "pack-refs");
540
541 if (prune_reflogs) {
542 struct child_process cmd = CHILD_PROCESS_INIT;
543
544 cmd.git_cmd = 1;
545 strvec_pushv(&cmd.args, reflog.v);
546 if (run_command(&cmd))
547 die(FAILED_RUN, reflog.v[0]);
548 }
549 }
550
551 int cmd_gc(int argc, const char **argv, const char *prefix)
552 {
553 int aggressive = 0;
554 int auto_gc = 0;
555 int quiet = 0;
556 int force = 0;
557 const char *name;
558 pid_t pid;
559 int daemonized = 0;
560 int keep_largest_pack = -1;
561 timestamp_t dummy;
562 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
563
564 struct option builtin_gc_options[] = {
565 OPT__QUIET(&quiet, N_("suppress progress reporting")),
566 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
567 N_("prune unreferenced objects"),
568 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
569 OPT_BOOL(0, "cruft", &cruft_packs, N_("pack unreferenced objects separately")),
570 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
571 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
572 PARSE_OPT_NOCOMPLETE),
573 OPT_BOOL_F(0, "force", &force,
574 N_("force running gc even if there may be another gc running"),
575 PARSE_OPT_NOCOMPLETE),
576 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
577 N_("repack all other packs except the largest pack")),
578 OPT_END()
579 };
580
581 if (argc == 2 && !strcmp(argv[1], "-h"))
582 usage_with_options(builtin_gc_usage, builtin_gc_options);
583
584 strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
585 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
586 strvec_pushl(&prune, "prune", "--expire", NULL);
587 strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
588 strvec_pushl(&rerere, "rerere", "gc", NULL);
589
590 /* default expiry time, overwritten in gc_config */
591 gc_config();
592 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
593 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire);
594
595 if (pack_refs < 0)
596 pack_refs = !is_bare_repository();
597
598 argc = parse_options(argc, argv, prefix, builtin_gc_options,
599 builtin_gc_usage, 0);
600 if (argc > 0)
601 usage_with_options(builtin_gc_usage, builtin_gc_options);
602
603 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
604 die(_("failed to parse prune expiry value %s"), prune_expire);
605
606 prepare_repo_settings(the_repository);
607 if (cruft_packs < 0)
608 cruft_packs = the_repository->settings.gc_cruft_packs;
609
610 if (aggressive) {
611 strvec_push(&repack, "-f");
612 if (aggressive_depth > 0)
613 strvec_pushf(&repack, "--depth=%d", aggressive_depth);
614 if (aggressive_window > 0)
615 strvec_pushf(&repack, "--window=%d", aggressive_window);
616 }
617 if (quiet)
618 strvec_push(&repack, "-q");
619
620 if (auto_gc) {
621 /*
622 * Auto-gc should be least intrusive as possible.
623 */
624 if (!need_to_gc())
625 return 0;
626 if (!quiet) {
627 if (detach_auto)
628 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
629 else
630 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
631 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
632 }
633 if (detach_auto) {
634 int ret = report_last_gc_error();
635
636 if (ret == 1)
637 /* Last gc --auto failed. Skip this one. */
638 return 0;
639 else if (ret)
640 /* an I/O error occurred, already reported */
641 return ret;
642
643 if (lock_repo_for_gc(force, &pid))
644 return 0;
645 gc_before_repack(); /* dies on failure */
646 delete_tempfile(&pidfile);
647
648 /*
649 * failure to daemonize is ok, we'll continue
650 * in foreground
651 */
652 daemonized = !daemonize();
653 }
654 } else {
655 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
656
657 if (keep_largest_pack != -1) {
658 if (keep_largest_pack)
659 find_base_packs(&keep_pack, 0);
660 } else if (big_pack_threshold) {
661 find_base_packs(&keep_pack, big_pack_threshold);
662 }
663
664 add_repack_all_option(&keep_pack);
665 string_list_clear(&keep_pack, 0);
666 }
667
668 name = lock_repo_for_gc(force, &pid);
669 if (name) {
670 if (auto_gc)
671 return 0; /* be quiet on --auto */
672 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
673 name, (uintmax_t)pid);
674 }
675
676 if (daemonized) {
677 hold_lock_file_for_update(&log_lock,
678 git_path("gc.log"),
679 LOCK_DIE_ON_ERROR);
680 dup2(get_lock_file_fd(&log_lock), 2);
681 sigchain_push_common(process_log_file_on_signal);
682 atexit(process_log_file_at_exit);
683 }
684
685 gc_before_repack();
686
687 if (!repository_format_precious_objects) {
688 struct child_process repack_cmd = CHILD_PROCESS_INIT;
689
690 repack_cmd.git_cmd = 1;
691 repack_cmd.close_object_store = 1;
692 strvec_pushv(&repack_cmd.args, repack.v);
693 if (run_command(&repack_cmd))
694 die(FAILED_RUN, repack.v[0]);
695
696 if (prune_expire) {
697 struct child_process prune_cmd = CHILD_PROCESS_INIT;
698
699 /* run `git prune` even if using cruft packs */
700 strvec_push(&prune, prune_expire);
701 if (quiet)
702 strvec_push(&prune, "--no-progress");
703 if (has_promisor_remote())
704 strvec_push(&prune,
705 "--exclude-promisor-objects");
706 prune_cmd.git_cmd = 1;
707 strvec_pushv(&prune_cmd.args, prune.v);
708 if (run_command(&prune_cmd))
709 die(FAILED_RUN, prune.v[0]);
710 }
711 }
712
713 if (prune_worktrees_expire) {
714 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
715
716 strvec_push(&prune_worktrees, prune_worktrees_expire);
717 prune_worktrees_cmd.git_cmd = 1;
718 strvec_pushv(&prune_worktrees_cmd.args, prune_worktrees.v);
719 if (run_command(&prune_worktrees_cmd))
720 die(FAILED_RUN, prune_worktrees.v[0]);
721 }
722
723 rerere_cmd.git_cmd = 1;
724 strvec_pushv(&rerere_cmd.args, rerere.v);
725 if (run_command(&rerere_cmd))
726 die(FAILED_RUN, rerere.v[0]);
727
728 report_garbage = report_pack_garbage;
729 reprepare_packed_git(the_repository);
730 if (pack_garbage.nr > 0) {
731 close_object_store(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->odb,
737 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
738 NULL);
739
740 if (auto_gc && too_many_loose_objects())
741 warning(_("There are too many unreachable loose objects; "
742 "run 'git prune' to remove them."));
743
744 if (!daemonized)
745 unlink(git_path("gc.log"));
746
747 return 0;
748 }
749
750 static const char *const builtin_maintenance_run_usage[] = {
751 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
752 NULL
753 };
754
755 enum schedule_priority {
756 SCHEDULE_NONE = 0,
757 SCHEDULE_WEEKLY = 1,
758 SCHEDULE_DAILY = 2,
759 SCHEDULE_HOURLY = 3,
760 };
761
762 static enum schedule_priority parse_schedule(const char *value)
763 {
764 if (!value)
765 return SCHEDULE_NONE;
766 if (!strcasecmp(value, "hourly"))
767 return SCHEDULE_HOURLY;
768 if (!strcasecmp(value, "daily"))
769 return SCHEDULE_DAILY;
770 if (!strcasecmp(value, "weekly"))
771 return SCHEDULE_WEEKLY;
772 return SCHEDULE_NONE;
773 }
774
775 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
776 int unset)
777 {
778 enum schedule_priority *priority = opt->value;
779
780 if (unset)
781 die(_("--no-schedule is not allowed"));
782
783 *priority = parse_schedule(arg);
784
785 if (!*priority)
786 die(_("unrecognized --schedule argument '%s'"), arg);
787
788 return 0;
789 }
790
791 struct maintenance_run_opts {
792 int auto_flag;
793 int quiet;
794 enum schedule_priority schedule;
795 };
796
797 /* Remember to update object flag allocation in object.h */
798 #define SEEN (1u<<0)
799
800 struct cg_auto_data {
801 int num_not_in_graph;
802 int limit;
803 };
804
805 static int dfs_on_ref(const char *refname UNUSED,
806 const struct object_id *oid,
807 int flags UNUSED,
808 void *cb_data)
809 {
810 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
811 int result = 0;
812 struct object_id peeled;
813 struct commit_list *stack = NULL;
814 struct commit *commit;
815
816 if (!peel_iterated_oid(oid, &peeled))
817 oid = &peeled;
818 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
819 return 0;
820
821 commit = lookup_commit(the_repository, oid);
822 if (!commit)
823 return 0;
824 if (parse_commit(commit) ||
825 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
826 return 0;
827
828 data->num_not_in_graph++;
829
830 if (data->num_not_in_graph >= data->limit)
831 return 1;
832
833 commit_list_append(commit, &stack);
834
835 while (!result && stack) {
836 struct commit_list *parent;
837
838 commit = pop_commit(&stack);
839
840 for (parent = commit->parents; parent; parent = parent->next) {
841 if (parse_commit(parent->item) ||
842 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
843 parent->item->object.flags & SEEN)
844 continue;
845
846 parent->item->object.flags |= SEEN;
847 data->num_not_in_graph++;
848
849 if (data->num_not_in_graph >= data->limit) {
850 result = 1;
851 break;
852 }
853
854 commit_list_append(parent->item, &stack);
855 }
856 }
857
858 free_commit_list(stack);
859 return result;
860 }
861
862 static int should_write_commit_graph(void)
863 {
864 int result;
865 struct cg_auto_data data;
866
867 data.num_not_in_graph = 0;
868 data.limit = 100;
869 git_config_get_int("maintenance.commit-graph.auto",
870 &data.limit);
871
872 if (!data.limit)
873 return 0;
874 if (data.limit < 0)
875 return 1;
876
877 result = for_each_ref(dfs_on_ref, &data);
878
879 repo_clear_commit_marks(the_repository, SEEN);
880
881 return result;
882 }
883
884 static int run_write_commit_graph(struct maintenance_run_opts *opts)
885 {
886 struct child_process child = CHILD_PROCESS_INIT;
887
888 child.git_cmd = child.close_object_store = 1;
889 strvec_pushl(&child.args, "commit-graph", "write",
890 "--split", "--reachable", NULL);
891
892 if (opts->quiet)
893 strvec_push(&child.args, "--no-progress");
894
895 return !!run_command(&child);
896 }
897
898 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
899 {
900 prepare_repo_settings(the_repository);
901 if (!the_repository->settings.core_commit_graph)
902 return 0;
903
904 if (run_write_commit_graph(opts)) {
905 error(_("failed to write commit-graph"));
906 return 1;
907 }
908
909 return 0;
910 }
911
912 static int fetch_remote(struct remote *remote, void *cbdata)
913 {
914 struct maintenance_run_opts *opts = cbdata;
915 struct child_process child = CHILD_PROCESS_INIT;
916
917 if (remote->skip_default_update)
918 return 0;
919
920 child.git_cmd = 1;
921 strvec_pushl(&child.args, "fetch", remote->name,
922 "--prefetch", "--prune", "--no-tags",
923 "--no-write-fetch-head", "--recurse-submodules=no",
924 NULL);
925
926 if (opts->quiet)
927 strvec_push(&child.args, "--quiet");
928
929 return !!run_command(&child);
930 }
931
932 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
933 {
934 if (for_each_remote(fetch_remote, opts)) {
935 error(_("failed to prefetch remotes"));
936 return 1;
937 }
938
939 return 0;
940 }
941
942 static int maintenance_task_gc(struct maintenance_run_opts *opts)
943 {
944 struct child_process child = CHILD_PROCESS_INIT;
945
946 child.git_cmd = child.close_object_store = 1;
947 strvec_push(&child.args, "gc");
948
949 if (opts->auto_flag)
950 strvec_push(&child.args, "--auto");
951 if (opts->quiet)
952 strvec_push(&child.args, "--quiet");
953 else
954 strvec_push(&child.args, "--no-quiet");
955
956 return run_command(&child);
957 }
958
959 static int prune_packed(struct maintenance_run_opts *opts)
960 {
961 struct child_process child = CHILD_PROCESS_INIT;
962
963 child.git_cmd = 1;
964 strvec_push(&child.args, "prune-packed");
965
966 if (opts->quiet)
967 strvec_push(&child.args, "--quiet");
968
969 return !!run_command(&child);
970 }
971
972 struct write_loose_object_data {
973 FILE *in;
974 int count;
975 int batch_size;
976 };
977
978 static int loose_object_auto_limit = 100;
979
980 static int loose_object_count(const struct object_id *oid UNUSED,
981 const char *path UNUSED,
982 void *data)
983 {
984 int *count = (int*)data;
985 if (++(*count) >= loose_object_auto_limit)
986 return 1;
987 return 0;
988 }
989
990 static int loose_object_auto_condition(void)
991 {
992 int count = 0;
993
994 git_config_get_int("maintenance.loose-objects.auto",
995 &loose_object_auto_limit);
996
997 if (!loose_object_auto_limit)
998 return 0;
999 if (loose_object_auto_limit < 0)
1000 return 1;
1001
1002 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
1003 loose_object_count,
1004 NULL, NULL, &count);
1005 }
1006
1007 static int bail_on_loose(const struct object_id *oid UNUSED,
1008 const char *path UNUSED,
1009 void *data UNUSED)
1010 {
1011 return 1;
1012 }
1013
1014 static int write_loose_object_to_stdin(const struct object_id *oid,
1015 const char *path UNUSED,
1016 void *data)
1017 {
1018 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1019
1020 fprintf(d->in, "%s\n", oid_to_hex(oid));
1021
1022 return ++(d->count) > d->batch_size;
1023 }
1024
1025 static int pack_loose(struct maintenance_run_opts *opts)
1026 {
1027 struct repository *r = the_repository;
1028 int result = 0;
1029 struct write_loose_object_data data;
1030 struct child_process pack_proc = CHILD_PROCESS_INIT;
1031
1032 /*
1033 * Do not start pack-objects process
1034 * if there are no loose objects.
1035 */
1036 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1037 bail_on_loose,
1038 NULL, NULL, NULL))
1039 return 0;
1040
1041 pack_proc.git_cmd = 1;
1042
1043 strvec_push(&pack_proc.args, "pack-objects");
1044 if (opts->quiet)
1045 strvec_push(&pack_proc.args, "--quiet");
1046 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1047
1048 pack_proc.in = -1;
1049
1050 if (start_command(&pack_proc)) {
1051 error(_("failed to start 'git pack-objects' process"));
1052 return 1;
1053 }
1054
1055 data.in = xfdopen(pack_proc.in, "w");
1056 data.count = 0;
1057 data.batch_size = 50000;
1058
1059 for_each_loose_file_in_objdir(r->objects->odb->path,
1060 write_loose_object_to_stdin,
1061 NULL,
1062 NULL,
1063 &data);
1064
1065 fclose(data.in);
1066
1067 if (finish_command(&pack_proc)) {
1068 error(_("failed to finish 'git pack-objects' process"));
1069 result = 1;
1070 }
1071
1072 return result;
1073 }
1074
1075 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1076 {
1077 return prune_packed(opts) || pack_loose(opts);
1078 }
1079
1080 static int incremental_repack_auto_condition(void)
1081 {
1082 struct packed_git *p;
1083 int incremental_repack_auto_limit = 10;
1084 int count = 0;
1085
1086 prepare_repo_settings(the_repository);
1087 if (!the_repository->settings.core_multi_pack_index)
1088 return 0;
1089
1090 git_config_get_int("maintenance.incremental-repack.auto",
1091 &incremental_repack_auto_limit);
1092
1093 if (!incremental_repack_auto_limit)
1094 return 0;
1095 if (incremental_repack_auto_limit < 0)
1096 return 1;
1097
1098 for (p = get_packed_git(the_repository);
1099 count < incremental_repack_auto_limit && p;
1100 p = p->next) {
1101 if (!p->multi_pack_index)
1102 count++;
1103 }
1104
1105 return count >= incremental_repack_auto_limit;
1106 }
1107
1108 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1109 {
1110 struct child_process child = CHILD_PROCESS_INIT;
1111
1112 child.git_cmd = 1;
1113 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1114
1115 if (opts->quiet)
1116 strvec_push(&child.args, "--no-progress");
1117
1118 if (run_command(&child))
1119 return error(_("failed to write multi-pack-index"));
1120
1121 return 0;
1122 }
1123
1124 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1125 {
1126 struct child_process child = CHILD_PROCESS_INIT;
1127
1128 child.git_cmd = child.close_object_store = 1;
1129 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1130
1131 if (opts->quiet)
1132 strvec_push(&child.args, "--no-progress");
1133
1134 if (run_command(&child))
1135 return error(_("'git multi-pack-index expire' failed"));
1136
1137 return 0;
1138 }
1139
1140 #define TWO_GIGABYTES (INT32_MAX)
1141
1142 static off_t get_auto_pack_size(void)
1143 {
1144 /*
1145 * The "auto" value is special: we optimize for
1146 * one large pack-file (i.e. from a clone) and
1147 * expect the rest to be small and they can be
1148 * repacked quickly.
1149 *
1150 * The strategy we select here is to select a
1151 * size that is one more than the second largest
1152 * pack-file. This ensures that we will repack
1153 * at least two packs if there are three or more
1154 * packs.
1155 */
1156 off_t max_size = 0;
1157 off_t second_largest_size = 0;
1158 off_t result_size;
1159 struct packed_git *p;
1160 struct repository *r = the_repository;
1161
1162 reprepare_packed_git(r);
1163 for (p = get_all_packs(r); p; p = p->next) {
1164 if (p->pack_size > max_size) {
1165 second_largest_size = max_size;
1166 max_size = p->pack_size;
1167 } else if (p->pack_size > second_largest_size)
1168 second_largest_size = p->pack_size;
1169 }
1170
1171 result_size = second_largest_size + 1;
1172
1173 /* But limit ourselves to a batch size of 2g */
1174 if (result_size > TWO_GIGABYTES)
1175 result_size = TWO_GIGABYTES;
1176
1177 return result_size;
1178 }
1179
1180 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1181 {
1182 struct child_process child = CHILD_PROCESS_INIT;
1183
1184 child.git_cmd = child.close_object_store = 1;
1185 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1186
1187 if (opts->quiet)
1188 strvec_push(&child.args, "--no-progress");
1189
1190 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1191 (uintmax_t)get_auto_pack_size());
1192
1193 if (run_command(&child))
1194 return error(_("'git multi-pack-index repack' failed"));
1195
1196 return 0;
1197 }
1198
1199 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1200 {
1201 prepare_repo_settings(the_repository);
1202 if (!the_repository->settings.core_multi_pack_index) {
1203 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1204 return 0;
1205 }
1206
1207 if (multi_pack_index_write(opts))
1208 return 1;
1209 if (multi_pack_index_expire(opts))
1210 return 1;
1211 if (multi_pack_index_repack(opts))
1212 return 1;
1213 return 0;
1214 }
1215
1216 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1217
1218 /*
1219 * An auto condition function returns 1 if the task should run
1220 * and 0 if the task should NOT run. See needs_to_gc() for an
1221 * example.
1222 */
1223 typedef int maintenance_auto_fn(void);
1224
1225 struct maintenance_task {
1226 const char *name;
1227 maintenance_task_fn *fn;
1228 maintenance_auto_fn *auto_condition;
1229 unsigned enabled:1;
1230
1231 enum schedule_priority schedule;
1232
1233 /* -1 if not selected. */
1234 int selected_order;
1235 };
1236
1237 enum maintenance_task_label {
1238 TASK_PREFETCH,
1239 TASK_LOOSE_OBJECTS,
1240 TASK_INCREMENTAL_REPACK,
1241 TASK_GC,
1242 TASK_COMMIT_GRAPH,
1243 TASK_PACK_REFS,
1244
1245 /* Leave as final value */
1246 TASK__COUNT
1247 };
1248
1249 static struct maintenance_task tasks[] = {
1250 [TASK_PREFETCH] = {
1251 "prefetch",
1252 maintenance_task_prefetch,
1253 },
1254 [TASK_LOOSE_OBJECTS] = {
1255 "loose-objects",
1256 maintenance_task_loose_objects,
1257 loose_object_auto_condition,
1258 },
1259 [TASK_INCREMENTAL_REPACK] = {
1260 "incremental-repack",
1261 maintenance_task_incremental_repack,
1262 incremental_repack_auto_condition,
1263 },
1264 [TASK_GC] = {
1265 "gc",
1266 maintenance_task_gc,
1267 need_to_gc,
1268 1,
1269 },
1270 [TASK_COMMIT_GRAPH] = {
1271 "commit-graph",
1272 maintenance_task_commit_graph,
1273 should_write_commit_graph,
1274 },
1275 [TASK_PACK_REFS] = {
1276 "pack-refs",
1277 maintenance_task_pack_refs,
1278 NULL,
1279 },
1280 };
1281
1282 static int compare_tasks_by_selection(const void *a_, const void *b_)
1283 {
1284 const struct maintenance_task *a = a_;
1285 const struct maintenance_task *b = b_;
1286
1287 return b->selected_order - a->selected_order;
1288 }
1289
1290 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1291 {
1292 int i, found_selected = 0;
1293 int result = 0;
1294 struct lock_file lk;
1295 struct repository *r = the_repository;
1296 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1297
1298 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1299 /*
1300 * Another maintenance command is running.
1301 *
1302 * If --auto was provided, then it is likely due to a
1303 * recursive process stack. Do not report an error in
1304 * that case.
1305 */
1306 if (!opts->auto_flag && !opts->quiet)
1307 warning(_("lock file '%s' exists, skipping maintenance"),
1308 lock_path);
1309 free(lock_path);
1310 return 0;
1311 }
1312 free(lock_path);
1313
1314 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1315 found_selected = tasks[i].selected_order >= 0;
1316
1317 if (found_selected)
1318 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1319
1320 for (i = 0; i < TASK__COUNT; i++) {
1321 if (found_selected && tasks[i].selected_order < 0)
1322 continue;
1323
1324 if (!found_selected && !tasks[i].enabled)
1325 continue;
1326
1327 if (opts->auto_flag &&
1328 (!tasks[i].auto_condition ||
1329 !tasks[i].auto_condition()))
1330 continue;
1331
1332 if (opts->schedule && tasks[i].schedule < opts->schedule)
1333 continue;
1334
1335 trace2_region_enter("maintenance", tasks[i].name, r);
1336 if (tasks[i].fn(opts)) {
1337 error(_("task '%s' failed"), tasks[i].name);
1338 result = 1;
1339 }
1340 trace2_region_leave("maintenance", tasks[i].name, r);
1341 }
1342
1343 rollback_lock_file(&lk);
1344 return result;
1345 }
1346
1347 static void initialize_maintenance_strategy(void)
1348 {
1349 char *config_str;
1350
1351 if (git_config_get_string("maintenance.strategy", &config_str))
1352 return;
1353
1354 if (!strcasecmp(config_str, "incremental")) {
1355 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1356 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1357 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1358 tasks[TASK_PREFETCH].enabled = 1;
1359 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1360 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1361 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1362 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1363 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1364 tasks[TASK_PACK_REFS].enabled = 1;
1365 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1366 }
1367 }
1368
1369 static void initialize_task_config(int schedule)
1370 {
1371 int i;
1372 struct strbuf config_name = STRBUF_INIT;
1373 gc_config();
1374
1375 if (schedule)
1376 initialize_maintenance_strategy();
1377
1378 for (i = 0; i < TASK__COUNT; i++) {
1379 int config_value;
1380 char *config_str;
1381
1382 strbuf_reset(&config_name);
1383 strbuf_addf(&config_name, "maintenance.%s.enabled",
1384 tasks[i].name);
1385
1386 if (!git_config_get_bool(config_name.buf, &config_value))
1387 tasks[i].enabled = config_value;
1388
1389 strbuf_reset(&config_name);
1390 strbuf_addf(&config_name, "maintenance.%s.schedule",
1391 tasks[i].name);
1392
1393 if (!git_config_get_string(config_name.buf, &config_str)) {
1394 tasks[i].schedule = parse_schedule(config_str);
1395 free(config_str);
1396 }
1397 }
1398
1399 strbuf_release(&config_name);
1400 }
1401
1402 static int task_option_parse(const struct option *opt,
1403 const char *arg, int unset)
1404 {
1405 int i, num_selected = 0;
1406 struct maintenance_task *task = NULL;
1407
1408 BUG_ON_OPT_NEG(unset);
1409
1410 for (i = 0; i < TASK__COUNT; i++) {
1411 if (tasks[i].selected_order >= 0)
1412 num_selected++;
1413 if (!strcasecmp(tasks[i].name, arg)) {
1414 task = &tasks[i];
1415 }
1416 }
1417
1418 if (!task) {
1419 error(_("'%s' is not a valid task"), arg);
1420 return 1;
1421 }
1422
1423 if (task->selected_order >= 0) {
1424 error(_("task '%s' cannot be selected multiple times"), arg);
1425 return 1;
1426 }
1427
1428 task->selected_order = num_selected + 1;
1429
1430 return 0;
1431 }
1432
1433 static int maintenance_run(int argc, const char **argv, const char *prefix)
1434 {
1435 int i;
1436 struct maintenance_run_opts opts;
1437 struct option builtin_maintenance_run_options[] = {
1438 OPT_BOOL(0, "auto", &opts.auto_flag,
1439 N_("run tasks based on the state of the repository")),
1440 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1441 N_("run tasks based on frequency"),
1442 maintenance_opt_schedule),
1443 OPT_BOOL(0, "quiet", &opts.quiet,
1444 N_("do not report progress or other information over stderr")),
1445 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1446 N_("run a specific task"),
1447 PARSE_OPT_NONEG, task_option_parse),
1448 OPT_END()
1449 };
1450 memset(&opts, 0, sizeof(opts));
1451
1452 opts.quiet = !isatty(2);
1453
1454 for (i = 0; i < TASK__COUNT; i++)
1455 tasks[i].selected_order = -1;
1456
1457 argc = parse_options(argc, argv, prefix,
1458 builtin_maintenance_run_options,
1459 builtin_maintenance_run_usage,
1460 PARSE_OPT_STOP_AT_NON_OPTION);
1461
1462 if (opts.auto_flag && opts.schedule)
1463 die(_("use at most one of --auto and --schedule=<frequency>"));
1464
1465 initialize_task_config(opts.schedule);
1466
1467 if (argc != 0)
1468 usage_with_options(builtin_maintenance_run_usage,
1469 builtin_maintenance_run_options);
1470 return maintenance_run_tasks(&opts);
1471 }
1472
1473 static char *get_maintpath(void)
1474 {
1475 struct strbuf sb = STRBUF_INIT;
1476 const char *p = the_repository->worktree ?
1477 the_repository->worktree : the_repository->gitdir;
1478
1479 strbuf_realpath(&sb, p, 1);
1480 return strbuf_detach(&sb, NULL);
1481 }
1482
1483 static char const * const builtin_maintenance_register_usage[] = {
1484 "git maintenance register [--config-file <path>]",
1485 NULL
1486 };
1487
1488 static int maintenance_register(int argc, const char **argv, const char *prefix)
1489 {
1490 char *config_file = NULL;
1491 struct option options[] = {
1492 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1493 OPT_END(),
1494 };
1495 int found = 0;
1496 const char *key = "maintenance.repo";
1497 char *config_value;
1498 char *maintpath = get_maintpath();
1499 struct string_list_item *item;
1500 const struct string_list *list;
1501
1502 argc = parse_options(argc, argv, prefix, options,
1503 builtin_maintenance_register_usage, 0);
1504 if (argc)
1505 usage_with_options(builtin_maintenance_register_usage,
1506 options);
1507
1508 /* Disable foreground maintenance */
1509 git_config_set("maintenance.auto", "false");
1510
1511 /* Set maintenance strategy, if unset */
1512 if (!git_config_get_string("maintenance.strategy", &config_value))
1513 free(config_value);
1514 else
1515 git_config_set("maintenance.strategy", "incremental");
1516
1517 list = git_config_get_value_multi(key);
1518 if (list) {
1519 for_each_string_list_item(item, list) {
1520 if (!strcmp(maintpath, item->string)) {
1521 found = 1;
1522 break;
1523 }
1524 }
1525 }
1526
1527 if (!found) {
1528 int rc;
1529 char *user_config = NULL, *xdg_config = NULL;
1530
1531 if (!config_file) {
1532 git_global_config(&user_config, &xdg_config);
1533 config_file = user_config;
1534 if (!user_config)
1535 die(_("$HOME not set"));
1536 }
1537 rc = git_config_set_multivar_in_file_gently(
1538 config_file, "maintenance.repo", maintpath,
1539 CONFIG_REGEX_NONE, 0);
1540 free(user_config);
1541 free(xdg_config);
1542
1543 if (rc)
1544 die(_("unable to add '%s' value of '%s'"),
1545 key, maintpath);
1546 }
1547
1548 free(maintpath);
1549 return 0;
1550 }
1551
1552 static char const * const builtin_maintenance_unregister_usage[] = {
1553 "git maintenance unregister [--config-file <path>] [--force]",
1554 NULL
1555 };
1556
1557 static int maintenance_unregister(int argc, const char **argv, const char *prefix)
1558 {
1559 int force = 0;
1560 char *config_file = NULL;
1561 struct option options[] = {
1562 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1563 OPT__FORCE(&force,
1564 N_("return success even if repository was not registered"),
1565 PARSE_OPT_NOCOMPLETE),
1566 OPT_END(),
1567 };
1568 const char *key = "maintenance.repo";
1569 char *maintpath = get_maintpath();
1570 int found = 0;
1571 struct string_list_item *item;
1572 const struct string_list *list;
1573 struct config_set cs = { { 0 } };
1574
1575 argc = parse_options(argc, argv, prefix, options,
1576 builtin_maintenance_unregister_usage, 0);
1577 if (argc)
1578 usage_with_options(builtin_maintenance_unregister_usage,
1579 options);
1580
1581 if (config_file) {
1582 git_configset_init(&cs);
1583 git_configset_add_file(&cs, config_file);
1584 list = git_configset_get_value_multi(&cs, key);
1585 } else {
1586 list = git_config_get_value_multi(key);
1587 }
1588 if (list) {
1589 for_each_string_list_item(item, list) {
1590 if (!strcmp(maintpath, item->string)) {
1591 found = 1;
1592 break;
1593 }
1594 }
1595 }
1596
1597 if (found) {
1598 int rc;
1599 char *user_config = NULL, *xdg_config = NULL;
1600 if (!config_file) {
1601 git_global_config(&user_config, &xdg_config);
1602 config_file = user_config;
1603 if (!user_config)
1604 die(_("$HOME not set"));
1605 }
1606 rc = git_config_set_multivar_in_file_gently(
1607 config_file, key, NULL, maintpath,
1608 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
1609 free(user_config);
1610 free(xdg_config);
1611
1612 if (rc &&
1613 (!force || rc == CONFIG_NOTHING_SET))
1614 die(_("unable to unset '%s' value of '%s'"),
1615 key, maintpath);
1616 } else if (!force) {
1617 die(_("repository '%s' is not registered"), maintpath);
1618 }
1619
1620 git_configset_clear(&cs);
1621 free(maintpath);
1622 return 0;
1623 }
1624
1625 static const char *get_frequency(enum schedule_priority schedule)
1626 {
1627 switch (schedule) {
1628 case SCHEDULE_HOURLY:
1629 return "hourly";
1630 case SCHEDULE_DAILY:
1631 return "daily";
1632 case SCHEDULE_WEEKLY:
1633 return "weekly";
1634 default:
1635 BUG("invalid schedule %d", schedule);
1636 }
1637 }
1638
1639 /*
1640 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1641 * to mock the schedulers that `git maintenance start` rely on.
1642 *
1643 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1644 * list of colon-separated key/value pairs where each pair contains a scheduler
1645 * and its corresponding mock.
1646 *
1647 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1648 * arguments unmodified.
1649 *
1650 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1651 * In this case, the *cmd value is read as input.
1652 *
1653 * * if the input value *cmd is the key of one of the comma-separated list
1654 * item, then *is_available is set to true and *cmd is modified and becomes
1655 * the mock command.
1656 *
1657 * * if the input value *cmd isn’t the key of any of the comma-separated list
1658 * item, then *is_available is set to false.
1659 *
1660 * Ex.:
1661 * GIT_TEST_MAINT_SCHEDULER not set
1662 * +-------+-------------------------------------------------+
1663 * | Input | Output |
1664 * | *cmd | return code | *cmd | *is_available |
1665 * +-------+-------------+-------------------+---------------+
1666 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1667 * +-------+-------------+-------------------+---------------+
1668 *
1669 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1670 * +-------+-------------------------------------------------+
1671 * | Input | Output |
1672 * | *cmd | return code | *cmd | *is_available |
1673 * +-------+-------------+-------------------+---------------+
1674 * | "foo" | true | "./mock.foo.sh" | true |
1675 * | "qux" | true | "qux" (unchanged) | false |
1676 * +-------+-------------+-------------------+---------------+
1677 */
1678 static int get_schedule_cmd(const char **cmd, int *is_available)
1679 {
1680 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1681 struct string_list_item *item;
1682 struct string_list list = STRING_LIST_INIT_NODUP;
1683
1684 if (!testing)
1685 return 0;
1686
1687 if (is_available)
1688 *is_available = 0;
1689
1690 string_list_split_in_place(&list, testing, ',', -1);
1691 for_each_string_list_item(item, &list) {
1692 struct string_list pair = STRING_LIST_INIT_NODUP;
1693
1694 if (string_list_split_in_place(&pair, item->string, ':', 2) != 2)
1695 continue;
1696
1697 if (!strcmp(*cmd, pair.items[0].string)) {
1698 *cmd = pair.items[1].string;
1699 if (is_available)
1700 *is_available = 1;
1701 string_list_clear(&list, 0);
1702 UNLEAK(testing);
1703 return 1;
1704 }
1705 }
1706
1707 string_list_clear(&list, 0);
1708 free(testing);
1709 return 1;
1710 }
1711
1712 static int is_launchctl_available(void)
1713 {
1714 const char *cmd = "launchctl";
1715 int is_available;
1716 if (get_schedule_cmd(&cmd, &is_available))
1717 return is_available;
1718
1719 #ifdef __APPLE__
1720 return 1;
1721 #else
1722 return 0;
1723 #endif
1724 }
1725
1726 static char *launchctl_service_name(const char *frequency)
1727 {
1728 struct strbuf label = STRBUF_INIT;
1729 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1730 return strbuf_detach(&label, NULL);
1731 }
1732
1733 static char *launchctl_service_filename(const char *name)
1734 {
1735 char *expanded;
1736 struct strbuf filename = STRBUF_INIT;
1737 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1738
1739 expanded = interpolate_path(filename.buf, 1);
1740 if (!expanded)
1741 die(_("failed to expand path '%s'"), filename.buf);
1742
1743 strbuf_release(&filename);
1744 return expanded;
1745 }
1746
1747 static char *launchctl_get_uid(void)
1748 {
1749 return xstrfmt("gui/%d", getuid());
1750 }
1751
1752 static int launchctl_boot_plist(int enable, const char *filename)
1753 {
1754 const char *cmd = "launchctl";
1755 int result;
1756 struct child_process child = CHILD_PROCESS_INIT;
1757 char *uid = launchctl_get_uid();
1758
1759 get_schedule_cmd(&cmd, NULL);
1760 strvec_split(&child.args, cmd);
1761 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1762 filename, NULL);
1763
1764 child.no_stderr = 1;
1765 child.no_stdout = 1;
1766
1767 if (start_command(&child))
1768 die(_("failed to start launchctl"));
1769
1770 result = finish_command(&child);
1771
1772 free(uid);
1773 return result;
1774 }
1775
1776 static int launchctl_remove_plist(enum schedule_priority schedule)
1777 {
1778 const char *frequency = get_frequency(schedule);
1779 char *name = launchctl_service_name(frequency);
1780 char *filename = launchctl_service_filename(name);
1781 int result = launchctl_boot_plist(0, filename);
1782 unlink(filename);
1783 free(filename);
1784 free(name);
1785 return result;
1786 }
1787
1788 static int launchctl_remove_plists(void)
1789 {
1790 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1791 launchctl_remove_plist(SCHEDULE_DAILY) ||
1792 launchctl_remove_plist(SCHEDULE_WEEKLY);
1793 }
1794
1795 static int launchctl_list_contains_plist(const char *name, const char *cmd)
1796 {
1797 struct child_process child = CHILD_PROCESS_INIT;
1798
1799 strvec_split(&child.args, cmd);
1800 strvec_pushl(&child.args, "list", name, NULL);
1801
1802 child.no_stderr = 1;
1803 child.no_stdout = 1;
1804
1805 if (start_command(&child))
1806 die(_("failed to start launchctl"));
1807
1808 /* Returns failure if 'name' doesn't exist. */
1809 return !finish_command(&child);
1810 }
1811
1812 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1813 {
1814 int i, fd;
1815 const char *preamble, *repeat;
1816 const char *frequency = get_frequency(schedule);
1817 char *name = launchctl_service_name(frequency);
1818 char *filename = launchctl_service_filename(name);
1819 struct lock_file lk = LOCK_INIT;
1820 static unsigned long lock_file_timeout_ms = ULONG_MAX;
1821 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
1822 struct stat st;
1823 const char *cmd = "launchctl";
1824
1825 get_schedule_cmd(&cmd, NULL);
1826 preamble = "<?xml version=\"1.0\"?>\n"
1827 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1828 "<plist version=\"1.0\">"
1829 "<dict>\n"
1830 "<key>Label</key><string>%s</string>\n"
1831 "<key>ProgramArguments</key>\n"
1832 "<array>\n"
1833 "<string>%s/git</string>\n"
1834 "<string>--exec-path=%s</string>\n"
1835 "<string>for-each-repo</string>\n"
1836 "<string>--config=maintenance.repo</string>\n"
1837 "<string>maintenance</string>\n"
1838 "<string>run</string>\n"
1839 "<string>--schedule=%s</string>\n"
1840 "</array>\n"
1841 "<key>StartCalendarInterval</key>\n"
1842 "<array>\n";
1843 strbuf_addf(&plist, preamble, name, exec_path, exec_path, frequency);
1844
1845 switch (schedule) {
1846 case SCHEDULE_HOURLY:
1847 repeat = "<dict>\n"
1848 "<key>Hour</key><integer>%d</integer>\n"
1849 "<key>Minute</key><integer>0</integer>\n"
1850 "</dict>\n";
1851 for (i = 1; i <= 23; i++)
1852 strbuf_addf(&plist, repeat, i);
1853 break;
1854
1855 case SCHEDULE_DAILY:
1856 repeat = "<dict>\n"
1857 "<key>Day</key><integer>%d</integer>\n"
1858 "<key>Hour</key><integer>0</integer>\n"
1859 "<key>Minute</key><integer>0</integer>\n"
1860 "</dict>\n";
1861 for (i = 1; i <= 6; i++)
1862 strbuf_addf(&plist, repeat, i);
1863 break;
1864
1865 case SCHEDULE_WEEKLY:
1866 strbuf_addstr(&plist,
1867 "<dict>\n"
1868 "<key>Day</key><integer>0</integer>\n"
1869 "<key>Hour</key><integer>0</integer>\n"
1870 "<key>Minute</key><integer>0</integer>\n"
1871 "</dict>\n");
1872 break;
1873
1874 default:
1875 /* unreachable */
1876 break;
1877 }
1878 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
1879
1880 if (safe_create_leading_directories(filename))
1881 die(_("failed to create directories for '%s'"), filename);
1882
1883 if ((long)lock_file_timeout_ms < 0 &&
1884 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1885 &lock_file_timeout_ms))
1886 lock_file_timeout_ms = 150;
1887
1888 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
1889 lock_file_timeout_ms);
1890
1891 /*
1892 * Does this file already exist? With the intended contents? Is it
1893 * registered already? Then it does not need to be re-registered.
1894 */
1895 if (!stat(filename, &st) && st.st_size == plist.len &&
1896 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
1897 !strbuf_cmp(&plist, &plist2) &&
1898 launchctl_list_contains_plist(name, cmd))
1899 rollback_lock_file(&lk);
1900 else {
1901 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
1902 commit_lock_file(&lk))
1903 die_errno(_("could not write '%s'"), filename);
1904
1905 /* bootout might fail if not already running, so ignore */
1906 launchctl_boot_plist(0, filename);
1907 if (launchctl_boot_plist(1, filename))
1908 die(_("failed to bootstrap service %s"), filename);
1909 }
1910
1911 free(filename);
1912 free(name);
1913 strbuf_release(&plist);
1914 strbuf_release(&plist2);
1915 return 0;
1916 }
1917
1918 static int launchctl_add_plists(void)
1919 {
1920 const char *exec_path = git_exec_path();
1921
1922 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1923 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1924 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1925 }
1926
1927 static int launchctl_update_schedule(int run_maintenance, int fd)
1928 {
1929 if (run_maintenance)
1930 return launchctl_add_plists();
1931 else
1932 return launchctl_remove_plists();
1933 }
1934
1935 static int is_schtasks_available(void)
1936 {
1937 const char *cmd = "schtasks";
1938 int is_available;
1939 if (get_schedule_cmd(&cmd, &is_available))
1940 return is_available;
1941
1942 #ifdef GIT_WINDOWS_NATIVE
1943 return 1;
1944 #else
1945 return 0;
1946 #endif
1947 }
1948
1949 static char *schtasks_task_name(const char *frequency)
1950 {
1951 struct strbuf label = STRBUF_INIT;
1952 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1953 return strbuf_detach(&label, NULL);
1954 }
1955
1956 static int schtasks_remove_task(enum schedule_priority schedule)
1957 {
1958 const char *cmd = "schtasks";
1959 struct child_process child = CHILD_PROCESS_INIT;
1960 const char *frequency = get_frequency(schedule);
1961 char *name = schtasks_task_name(frequency);
1962
1963 get_schedule_cmd(&cmd, NULL);
1964 strvec_split(&child.args, cmd);
1965 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
1966 free(name);
1967
1968 return run_command(&child);
1969 }
1970
1971 static int schtasks_remove_tasks(void)
1972 {
1973 return schtasks_remove_task(SCHEDULE_HOURLY) ||
1974 schtasks_remove_task(SCHEDULE_DAILY) ||
1975 schtasks_remove_task(SCHEDULE_WEEKLY);
1976 }
1977
1978 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
1979 {
1980 const char *cmd = "schtasks";
1981 int result;
1982 struct child_process child = CHILD_PROCESS_INIT;
1983 const char *xml;
1984 struct tempfile *tfile;
1985 const char *frequency = get_frequency(schedule);
1986 char *name = schtasks_task_name(frequency);
1987 struct strbuf tfilename = STRBUF_INIT;
1988
1989 get_schedule_cmd(&cmd, NULL);
1990
1991 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1992 get_git_common_dir(), frequency);
1993 tfile = xmks_tempfile(tfilename.buf);
1994 strbuf_release(&tfilename);
1995
1996 if (!fdopen_tempfile(tfile, "w"))
1997 die(_("failed to create temp xml file"));
1998
1999 xml = "<?xml version=\"1.0\" ?>\n"
2000 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2001 "<Triggers>\n"
2002 "<CalendarTrigger>\n";
2003 fputs(xml, tfile->fp);
2004
2005 switch (schedule) {
2006 case SCHEDULE_HOURLY:
2007 fprintf(tfile->fp,
2008 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
2009 "<Enabled>true</Enabled>\n"
2010 "<ScheduleByDay>\n"
2011 "<DaysInterval>1</DaysInterval>\n"
2012 "</ScheduleByDay>\n"
2013 "<Repetition>\n"
2014 "<Interval>PT1H</Interval>\n"
2015 "<Duration>PT23H</Duration>\n"
2016 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2017 "</Repetition>\n");
2018 break;
2019
2020 case SCHEDULE_DAILY:
2021 fprintf(tfile->fp,
2022 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2023 "<Enabled>true</Enabled>\n"
2024 "<ScheduleByWeek>\n"
2025 "<DaysOfWeek>\n"
2026 "<Monday />\n"
2027 "<Tuesday />\n"
2028 "<Wednesday />\n"
2029 "<Thursday />\n"
2030 "<Friday />\n"
2031 "<Saturday />\n"
2032 "</DaysOfWeek>\n"
2033 "<WeeksInterval>1</WeeksInterval>\n"
2034 "</ScheduleByWeek>\n");
2035 break;
2036
2037 case SCHEDULE_WEEKLY:
2038 fprintf(tfile->fp,
2039 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2040 "<Enabled>true</Enabled>\n"
2041 "<ScheduleByWeek>\n"
2042 "<DaysOfWeek>\n"
2043 "<Sunday />\n"
2044 "</DaysOfWeek>\n"
2045 "<WeeksInterval>1</WeeksInterval>\n"
2046 "</ScheduleByWeek>\n");
2047 break;
2048
2049 default:
2050 break;
2051 }
2052
2053 xml = "</CalendarTrigger>\n"
2054 "</Triggers>\n"
2055 "<Principals>\n"
2056 "<Principal id=\"Author\">\n"
2057 "<LogonType>InteractiveToken</LogonType>\n"
2058 "<RunLevel>LeastPrivilege</RunLevel>\n"
2059 "</Principal>\n"
2060 "</Principals>\n"
2061 "<Settings>\n"
2062 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2063 "<Enabled>true</Enabled>\n"
2064 "<Hidden>true</Hidden>\n"
2065 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2066 "<WakeToRun>false</WakeToRun>\n"
2067 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2068 "<Priority>7</Priority>\n"
2069 "</Settings>\n"
2070 "<Actions Context=\"Author\">\n"
2071 "<Exec>\n"
2072 "<Command>\"%s\\git.exe\"</Command>\n"
2073 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2074 "</Exec>\n"
2075 "</Actions>\n"
2076 "</Task>\n";
2077 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
2078 strvec_split(&child.args, cmd);
2079 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2080 get_tempfile_path(tfile), NULL);
2081 close_tempfile_gently(tfile);
2082
2083 child.no_stdout = 1;
2084 child.no_stderr = 1;
2085
2086 if (start_command(&child))
2087 die(_("failed to start schtasks"));
2088 result = finish_command(&child);
2089
2090 delete_tempfile(&tfile);
2091 free(name);
2092 return result;
2093 }
2094
2095 static int schtasks_schedule_tasks(void)
2096 {
2097 const char *exec_path = git_exec_path();
2098
2099 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2100 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2101 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
2102 }
2103
2104 static int schtasks_update_schedule(int run_maintenance, int fd)
2105 {
2106 if (run_maintenance)
2107 return schtasks_schedule_tasks();
2108 else
2109 return schtasks_remove_tasks();
2110 }
2111
2112 MAYBE_UNUSED
2113 static int check_crontab_process(const char *cmd)
2114 {
2115 struct child_process child = CHILD_PROCESS_INIT;
2116
2117 strvec_split(&child.args, cmd);
2118 strvec_push(&child.args, "-l");
2119 child.no_stdin = 1;
2120 child.no_stdout = 1;
2121 child.no_stderr = 1;
2122 child.silent_exec_failure = 1;
2123
2124 if (start_command(&child))
2125 return 0;
2126 /* Ignore exit code, as an empty crontab will return error. */
2127 finish_command(&child);
2128 return 1;
2129 }
2130
2131 static int is_crontab_available(void)
2132 {
2133 const char *cmd = "crontab";
2134 int is_available;
2135
2136 if (get_schedule_cmd(&cmd, &is_available))
2137 return is_available;
2138
2139 #ifdef __APPLE__
2140 /*
2141 * macOS has cron, but it requires special permissions and will
2142 * create a UI alert when attempting to run this command.
2143 */
2144 return 0;
2145 #else
2146 return check_crontab_process(cmd);
2147 #endif
2148 }
2149
2150 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2151 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2152
2153 static int crontab_update_schedule(int run_maintenance, int fd)
2154 {
2155 const char *cmd = "crontab";
2156 int result = 0;
2157 int in_old_region = 0;
2158 struct child_process crontab_list = CHILD_PROCESS_INIT;
2159 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2160 FILE *cron_list, *cron_in;
2161 struct strbuf line = STRBUF_INIT;
2162 struct tempfile *tmpedit = NULL;
2163
2164 get_schedule_cmd(&cmd, NULL);
2165 strvec_split(&crontab_list.args, cmd);
2166 strvec_push(&crontab_list.args, "-l");
2167 crontab_list.in = -1;
2168 crontab_list.out = dup(fd);
2169 crontab_list.git_cmd = 0;
2170
2171 if (start_command(&crontab_list))
2172 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2173
2174 /* Ignore exit code, as an empty crontab will return error. */
2175 finish_command(&crontab_list);
2176
2177 tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2178 if (!tmpedit) {
2179 result = error(_("failed to create crontab temporary file"));
2180 goto out;
2181 }
2182 cron_in = fdopen_tempfile(tmpedit, "w");
2183 if (!cron_in) {
2184 result = error(_("failed to open temporary file"));
2185 goto out;
2186 }
2187
2188 /*
2189 * Read from the .lock file, filtering out the old
2190 * schedule while appending the new schedule.
2191 */
2192 cron_list = fdopen(fd, "r");
2193 rewind(cron_list);
2194
2195 while (!strbuf_getline_lf(&line, cron_list)) {
2196 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2197 in_old_region = 1;
2198 else if (in_old_region && !strcmp(line.buf, END_LINE))
2199 in_old_region = 0;
2200 else if (!in_old_region)
2201 fprintf(cron_in, "%s\n", line.buf);
2202 }
2203 strbuf_release(&line);
2204
2205 if (run_maintenance) {
2206 struct strbuf line_format = STRBUF_INIT;
2207 const char *exec_path = git_exec_path();
2208
2209 fprintf(cron_in, "%s\n", BEGIN_LINE);
2210 fprintf(cron_in,
2211 "# The following schedule was created by Git\n");
2212 fprintf(cron_in, "# Any edits made in this region might be\n");
2213 fprintf(cron_in,
2214 "# replaced in the future by a Git command.\n\n");
2215
2216 strbuf_addf(&line_format,
2217 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2218 exec_path, exec_path);
2219 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2220 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2221 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2222 strbuf_release(&line_format);
2223
2224 fprintf(cron_in, "\n%s\n", END_LINE);
2225 }
2226
2227 fflush(cron_in);
2228
2229 strvec_split(&crontab_edit.args, cmd);
2230 strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2231 crontab_edit.git_cmd = 0;
2232
2233 if (start_command(&crontab_edit)) {
2234 result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2235 goto out;
2236 }
2237
2238 if (finish_command(&crontab_edit))
2239 result = error(_("'crontab' died"));
2240 else
2241 fclose(cron_list);
2242 out:
2243 delete_tempfile(&tmpedit);
2244 return result;
2245 }
2246
2247 static int real_is_systemd_timer_available(void)
2248 {
2249 struct child_process child = CHILD_PROCESS_INIT;
2250
2251 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2252 child.no_stdin = 1;
2253 child.no_stdout = 1;
2254 child.no_stderr = 1;
2255 child.silent_exec_failure = 1;
2256
2257 if (start_command(&child))
2258 return 0;
2259 if (finish_command(&child))
2260 return 0;
2261 return 1;
2262 }
2263
2264 static int is_systemd_timer_available(void)
2265 {
2266 const char *cmd = "systemctl";
2267 int is_available;
2268
2269 if (get_schedule_cmd(&cmd, &is_available))
2270 return is_available;
2271
2272 return real_is_systemd_timer_available();
2273 }
2274
2275 static char *xdg_config_home_systemd(const char *filename)
2276 {
2277 return xdg_config_home_for("systemd/user", filename);
2278 }
2279
2280 static int systemd_timer_enable_unit(int enable,
2281 enum schedule_priority schedule)
2282 {
2283 const char *cmd = "systemctl";
2284 struct child_process child = CHILD_PROCESS_INIT;
2285 const char *frequency = get_frequency(schedule);
2286
2287 /*
2288 * Disabling the systemd unit while it is already disabled makes
2289 * systemctl print an error.
2290 * Let's ignore it since it means we already are in the expected state:
2291 * the unit is disabled.
2292 *
2293 * On the other hand, enabling a systemd unit which is already enabled
2294 * produces no error.
2295 */
2296 if (!enable)
2297 child.no_stderr = 1;
2298
2299 get_schedule_cmd(&cmd, NULL);
2300 strvec_split(&child.args, cmd);
2301 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2302 "--now", NULL);
2303 strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2304
2305 if (start_command(&child))
2306 return error(_("failed to start systemctl"));
2307 if (finish_command(&child))
2308 /*
2309 * Disabling an already disabled systemd unit makes
2310 * systemctl fail.
2311 * Let's ignore this failure.
2312 *
2313 * Enabling an enabled systemd unit doesn't fail.
2314 */
2315 if (enable)
2316 return error(_("failed to run systemctl"));
2317 return 0;
2318 }
2319
2320 static int systemd_timer_delete_unit_templates(void)
2321 {
2322 int ret = 0;
2323 char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2324 if (unlink(filename) && !is_missing_file_error(errno))
2325 ret = error_errno(_("failed to delete '%s'"), filename);
2326 FREE_AND_NULL(filename);
2327
2328 filename = xdg_config_home_systemd("git-maintenance@.service");
2329 if (unlink(filename) && !is_missing_file_error(errno))
2330 ret = error_errno(_("failed to delete '%s'"), filename);
2331
2332 free(filename);
2333 return ret;
2334 }
2335
2336 static int systemd_timer_delete_units(void)
2337 {
2338 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2339 systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2340 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2341 systemd_timer_delete_unit_templates();
2342 }
2343
2344 static int systemd_timer_write_unit_templates(const char *exec_path)
2345 {
2346 char *filename;
2347 FILE *file;
2348 const char *unit;
2349
2350 filename = xdg_config_home_systemd("git-maintenance@.timer");
2351 if (safe_create_leading_directories(filename)) {
2352 error(_("failed to create directories for '%s'"), filename);
2353 goto error;
2354 }
2355 file = fopen_or_warn(filename, "w");
2356 if (!file)
2357 goto error;
2358
2359 unit = "# This file was created and is maintained by Git.\n"
2360 "# Any edits made in this file might be replaced in the future\n"
2361 "# by a Git command.\n"
2362 "\n"
2363 "[Unit]\n"
2364 "Description=Optimize Git repositories data\n"
2365 "\n"
2366 "[Timer]\n"
2367 "OnCalendar=%i\n"
2368 "Persistent=true\n"
2369 "\n"
2370 "[Install]\n"
2371 "WantedBy=timers.target\n";
2372 if (fputs(unit, file) == EOF) {
2373 error(_("failed to write to '%s'"), filename);
2374 fclose(file);
2375 goto error;
2376 }
2377 if (fclose(file) == EOF) {
2378 error_errno(_("failed to flush '%s'"), filename);
2379 goto error;
2380 }
2381 free(filename);
2382
2383 filename = xdg_config_home_systemd("git-maintenance@.service");
2384 file = fopen_or_warn(filename, "w");
2385 if (!file)
2386 goto error;
2387
2388 unit = "# This file was created and is maintained by Git.\n"
2389 "# Any edits made in this file might be replaced in the future\n"
2390 "# by a Git command.\n"
2391 "\n"
2392 "[Unit]\n"
2393 "Description=Optimize Git repositories data\n"
2394 "\n"
2395 "[Service]\n"
2396 "Type=oneshot\n"
2397 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2398 "LockPersonality=yes\n"
2399 "MemoryDenyWriteExecute=yes\n"
2400 "NoNewPrivileges=yes\n"
2401 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2402 "RestrictNamespaces=yes\n"
2403 "RestrictRealtime=yes\n"
2404 "RestrictSUIDSGID=yes\n"
2405 "SystemCallArchitectures=native\n"
2406 "SystemCallFilter=@system-service\n";
2407 if (fprintf(file, unit, exec_path, exec_path) < 0) {
2408 error(_("failed to write to '%s'"), filename);
2409 fclose(file);
2410 goto error;
2411 }
2412 if (fclose(file) == EOF) {
2413 error_errno(_("failed to flush '%s'"), filename);
2414 goto error;
2415 }
2416 free(filename);
2417 return 0;
2418
2419 error:
2420 free(filename);
2421 systemd_timer_delete_unit_templates();
2422 return -1;
2423 }
2424
2425 static int systemd_timer_setup_units(void)
2426 {
2427 const char *exec_path = git_exec_path();
2428
2429 int ret = systemd_timer_write_unit_templates(exec_path) ||
2430 systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2431 systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2432 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2433 if (ret)
2434 systemd_timer_delete_units();
2435 return ret;
2436 }
2437
2438 static int systemd_timer_update_schedule(int run_maintenance, int fd)
2439 {
2440 if (run_maintenance)
2441 return systemd_timer_setup_units();
2442 else
2443 return systemd_timer_delete_units();
2444 }
2445
2446 enum scheduler {
2447 SCHEDULER_INVALID = -1,
2448 SCHEDULER_AUTO,
2449 SCHEDULER_CRON,
2450 SCHEDULER_SYSTEMD,
2451 SCHEDULER_LAUNCHCTL,
2452 SCHEDULER_SCHTASKS,
2453 };
2454
2455 static const struct {
2456 const char *name;
2457 int (*is_available)(void);
2458 int (*update_schedule)(int run_maintenance, int fd);
2459 } scheduler_fn[] = {
2460 [SCHEDULER_CRON] = {
2461 .name = "crontab",
2462 .is_available = is_crontab_available,
2463 .update_schedule = crontab_update_schedule,
2464 },
2465 [SCHEDULER_SYSTEMD] = {
2466 .name = "systemctl",
2467 .is_available = is_systemd_timer_available,
2468 .update_schedule = systemd_timer_update_schedule,
2469 },
2470 [SCHEDULER_LAUNCHCTL] = {
2471 .name = "launchctl",
2472 .is_available = is_launchctl_available,
2473 .update_schedule = launchctl_update_schedule,
2474 },
2475 [SCHEDULER_SCHTASKS] = {
2476 .name = "schtasks",
2477 .is_available = is_schtasks_available,
2478 .update_schedule = schtasks_update_schedule,
2479 },
2480 };
2481
2482 static enum scheduler parse_scheduler(const char *value)
2483 {
2484 if (!value)
2485 return SCHEDULER_INVALID;
2486 else if (!strcasecmp(value, "auto"))
2487 return SCHEDULER_AUTO;
2488 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2489 return SCHEDULER_CRON;
2490 else if (!strcasecmp(value, "systemd") ||
2491 !strcasecmp(value, "systemd-timer"))
2492 return SCHEDULER_SYSTEMD;
2493 else if (!strcasecmp(value, "launchctl"))
2494 return SCHEDULER_LAUNCHCTL;
2495 else if (!strcasecmp(value, "schtasks"))
2496 return SCHEDULER_SCHTASKS;
2497 else
2498 return SCHEDULER_INVALID;
2499 }
2500
2501 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2502 int unset)
2503 {
2504 enum scheduler *scheduler = opt->value;
2505
2506 BUG_ON_OPT_NEG(unset);
2507
2508 *scheduler = parse_scheduler(arg);
2509 if (*scheduler == SCHEDULER_INVALID)
2510 return error(_("unrecognized --scheduler argument '%s'"), arg);
2511 return 0;
2512 }
2513
2514 struct maintenance_start_opts {
2515 enum scheduler scheduler;
2516 };
2517
2518 static enum scheduler resolve_scheduler(enum scheduler scheduler)
2519 {
2520 if (scheduler != SCHEDULER_AUTO)
2521 return scheduler;
2522
2523 #if defined(__APPLE__)
2524 return SCHEDULER_LAUNCHCTL;
2525
2526 #elif defined(GIT_WINDOWS_NATIVE)
2527 return SCHEDULER_SCHTASKS;
2528
2529 #elif defined(__linux__)
2530 if (is_systemd_timer_available())
2531 return SCHEDULER_SYSTEMD;
2532 else if (is_crontab_available())
2533 return SCHEDULER_CRON;
2534 else
2535 die(_("neither systemd timers nor crontab are available"));
2536
2537 #else
2538 return SCHEDULER_CRON;
2539 #endif
2540 }
2541
2542 static void validate_scheduler(enum scheduler scheduler)
2543 {
2544 if (scheduler == SCHEDULER_INVALID)
2545 BUG("invalid scheduler");
2546 if (scheduler == SCHEDULER_AUTO)
2547 BUG("resolve_scheduler should have been called before");
2548
2549 if (!scheduler_fn[scheduler].is_available())
2550 die(_("%s scheduler is not available"),
2551 scheduler_fn[scheduler].name);
2552 }
2553
2554 static int update_background_schedule(const struct maintenance_start_opts *opts,
2555 int enable)
2556 {
2557 unsigned int i;
2558 int result = 0;
2559 struct lock_file lk;
2560 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2561
2562 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2563 free(lock_path);
2564 return error(_("another process is scheduling background maintenance"));
2565 }
2566
2567 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2568 if (enable && opts->scheduler == i)
2569 continue;
2570 if (!scheduler_fn[i].is_available())
2571 continue;
2572 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2573 }
2574
2575 if (enable)
2576 result = scheduler_fn[opts->scheduler].update_schedule(
2577 1, get_lock_file_fd(&lk));
2578
2579 rollback_lock_file(&lk);
2580
2581 free(lock_path);
2582 return result;
2583 }
2584
2585 static const char *const builtin_maintenance_start_usage[] = {
2586 N_("git maintenance start [--scheduler=<scheduler>]"),
2587 NULL
2588 };
2589
2590 static int maintenance_start(int argc, const char **argv, const char *prefix)
2591 {
2592 struct maintenance_start_opts opts = { 0 };
2593 struct option options[] = {
2594 OPT_CALLBACK_F(
2595 0, "scheduler", &opts.scheduler, N_("scheduler"),
2596 N_("scheduler to trigger git maintenance run"),
2597 PARSE_OPT_NONEG, maintenance_opt_scheduler),
2598 OPT_END()
2599 };
2600 const char *register_args[] = { "register", NULL };
2601
2602 argc = parse_options(argc, argv, prefix, options,
2603 builtin_maintenance_start_usage, 0);
2604 if (argc)
2605 usage_with_options(builtin_maintenance_start_usage, options);
2606
2607 opts.scheduler = resolve_scheduler(opts.scheduler);
2608 validate_scheduler(opts.scheduler);
2609
2610 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL))
2611 warning(_("failed to add repo to global config"));
2612 return update_background_schedule(&opts, 1);
2613 }
2614
2615 static const char *const builtin_maintenance_stop_usage[] = {
2616 "git maintenance stop",
2617 NULL
2618 };
2619
2620 static int maintenance_stop(int argc, const char **argv, const char *prefix)
2621 {
2622 struct option options[] = {
2623 OPT_END()
2624 };
2625 argc = parse_options(argc, argv, prefix, options,
2626 builtin_maintenance_stop_usage, 0);
2627 if (argc)
2628 usage_with_options(builtin_maintenance_stop_usage, options);
2629 return update_background_schedule(NULL, 0);
2630 }
2631
2632 static const char * const builtin_maintenance_usage[] = {
2633 N_("git maintenance <subcommand> [<options>]"),
2634 NULL,
2635 };
2636
2637 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2638 {
2639 parse_opt_subcommand_fn *fn = NULL;
2640 struct option builtin_maintenance_options[] = {
2641 OPT_SUBCOMMAND("run", &fn, maintenance_run),
2642 OPT_SUBCOMMAND("start", &fn, maintenance_start),
2643 OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
2644 OPT_SUBCOMMAND("register", &fn, maintenance_register),
2645 OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
2646 OPT_END(),
2647 };
2648
2649 argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
2650 builtin_maintenance_usage, 0);
2651 return fn(argc, argv, prefix);
2652 }