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