]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/gc.c
The eleventh batch
[thirdparty/git.git] / builtin / gc.c
CommitLineData
6757ada4
JB
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 */
41f43b82 12
03eae9af 13#define USE_THE_REPOSITORY_VARIABLE
41f43b82
PS
14#define DISABLE_SIGN_COMPARE_WARNINGS
15
baffc0e7 16#include "builtin.h"
0b027f6c 17#include "abspath.h"
d4a4f929 18#include "date.h"
283621a5 19#include "dir.h"
32a8f510 20#include "environment.h"
41771fa4 21#include "hex.h"
b2141fc1 22#include "config.h"
ebebeaea 23#include "tempfile.h"
697cc8ef 24#include "lockfile.h"
44c637c8 25#include "parse-options.h"
6757ada4 26#include "run-command.h"
4c5baf02 27#include "sigchain.h"
dbbcd44f 28#include "strvec.h"
eab3296c 29#include "commit.h"
d5d5d7b6 30#include "commit-graph.h"
0abe14f6 31#include "packfile.h"
1a793261 32#include "object-file.h"
9806f5a7
NTND
33#include "pack.h"
34#include "pack-objects.h"
c339932b 35#include "path.h"
8e0a1ec0 36#include "reflog.h"
283621a5 37#include "rerere.h"
9806f5a7
NTND
38#include "blob.h"
39#include "tree.h"
b14ed5ad 40#include "promisor-remote.h"
4ddc79b2 41#include "refs.h"
28cb5e66 42#include "remote.h"
2fec604f 43#include "exec-cmd.h"
f394e093 44#include "gettext.h"
bad62a8c 45#include "hook.h"
e38da487 46#include "setup.h"
74ea5c95 47#include "trace2.h"
ec314746 48#include "worktree.h"
6757ada4
JB
49
50#define FAILED_RUN "failed to run %s"
51
44c637c8 52static const char * const builtin_gc_usage[] = {
9c9b4f2f 53 N_("git gc [<options>]"),
44c637c8
JB
54 NULL
55};
6757ada4 56
dddbad72 57static timestamp_t gc_log_expire_time;
22f9b7f3 58static struct strvec repack = STRVEC_INIT;
076aa2cb 59static struct tempfile *pidfile;
329e6e87 60static struct lock_file log_lock;
478f34d2
DK
61static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
62
63static 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
71static 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
329e6e87
NTND
77static void process_log_file(void)
78{
79 struct stat st;
a831c06a
DT
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"),
d4a49766 89 get_lock_file_path(&log_lock),
a831c06a
DT
90 strerror(saved_errno));
91 fflush(stderr);
329e6e87 92 commit_lock_file(&log_lock);
a831c06a
DT
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 {
88dd321c 98 char *path = repo_git_path(the_repository, "gc.log");
a831c06a 99 /* No error, clean up any old gc.log */
88dd321c 100 unlink(path);
329e6e87 101 rollback_lock_file(&log_lock);
88dd321c 102 free(path);
a831c06a 103 }
329e6e87
NTND
104}
105
106static void process_log_file_at_exit(void)
107{
108 fflush(stderr);
109 process_log_file();
110}
111
bf3d70fe
ÆAB
112static int gc_config_is_timestamp_never(const char *var)
113{
114 const char *value;
115 timestamp_t expire;
116
117 if (!git_config_get_value(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
d1ae15d6
PS
125struct 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;
0ce44e22
PS
135 char *gc_log_expire;
136 char *prune_expire;
137 char *prune_worktrees_expire;
d1ae15d6
PS
138 char *repack_filter;
139 char *repack_filter_to;
08032fa3 140 char *repack_expire_to;
d1ae15d6
PS
141 unsigned long big_pack_threshold;
142 unsigned long max_delta_cache_size;
d6b2d21f
KN
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;
d1ae15d6
PS
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, \
0ce44e22
PS
159 .gc_log_expire = xstrdup("1.day.ago"), \
160 .prune_expire = xstrdup("2.weeks.ago"), \
161 .prune_worktrees_expire = xstrdup("3.months.ago"), \
d1ae15d6 162 .max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE, \
d6b2d21f 163 .delta_base_cache_limit = DEFAULT_DELTA_BASE_CACHE_LIMIT, \
d1ae15d6
PS
164}
165
0ce44e22
PS
166static 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
d1ae15d6 175static void gc_config(struct gc_config *cfg)
6757ada4 176{
5801d3b4 177 const char *value;
0ce44e22 178 char *owned = NULL;
d6b2d21f 179 unsigned long ulongval;
5801d3b4
TA
180
181 if (!git_config_get_value("gc.packrefs", &value)) {
c5e5a2c0 182 if (value && !strcmp(value, "notbare"))
d1ae15d6 183 cfg->pack_refs = -1;
6757ada4 184 else
d1ae15d6 185 cfg->pack_refs = git_config_bool("gc.packrefs", value);
17815501 186 }
5801d3b4 187
bf3d70fe
ÆAB
188 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
189 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
d1ae15d6 190 cfg->prune_reflogs = 0;
bf3d70fe 191
d1ae15d6
PS
192 git_config_get_int("gc.aggressivewindow", &cfg->aggressive_window);
193 git_config_get_int("gc.aggressivedepth", &cfg->aggressive_depth);
194 git_config_get_int("gc.auto", &cfg->gc_auto_threshold);
195 git_config_get_int("gc.autopacklimit", &cfg->gc_auto_pack_limit);
196 git_config_get_bool("gc.autodetach", &cfg->detach_auto);
197 git_config_get_bool("gc.cruftpacks", &cfg->cruft_packs);
198 git_config_get_ulong("gc.maxcruftsize", &cfg->max_cruft_size);
0ce44e22 199
1e8962ee 200 if (!repo_config_get_expiry(the_repository, "gc.pruneexpire", &owned)) {
0ce44e22
PS
201 free(cfg->prune_expire);
202 cfg->prune_expire = owned;
203 }
bf3d70fe 204
1e8962ee 205 if (!repo_config_get_expiry(the_repository, "gc.worktreepruneexpire", &owned)) {
0ce44e22
PS
206 free(cfg->prune_worktrees_expire);
207 cfg->prune_worktrees_expire = owned;
208 }
209
1e8962ee 210 if (!repo_config_get_expiry(the_repository, "gc.logexpiry", &owned)) {
0ce44e22
PS
211 free(cfg->gc_log_expire);
212 cfg->gc_log_expire = owned;
213 }
a831c06a 214
d1ae15d6
PS
215 git_config_get_ulong("gc.bigpackthreshold", &cfg->big_pack_threshold);
216 git_config_get_ulong("pack.deltacachesize", &cfg->max_delta_cache_size);
55dfe13d 217
d6b2d21f
KN
218 if (!git_config_get_ulong("core.deltabasecachelimit", &ulongval))
219 cfg->delta_base_cache_limit = ulongval;
220
0ce44e22
PS
221 if (!git_config_get_string("gc.repackfilter", &owned)) {
222 free(cfg->repack_filter);
223 cfg->repack_filter = owned;
224 }
225
226 if (!git_config_get_string("gc.repackfilterto", &owned)) {
227 free(cfg->repack_filter_to);
228 cfg->repack_filter_to = owned;
229 }
1cd43a9e 230
5801d3b4 231 git_config(git_default_config, NULL);
6757ada4
JB
232}
233
0e05d539
PS
234enum schedule_priority {
235 SCHEDULE_NONE = 0,
236 SCHEDULE_WEEKLY = 1,
237 SCHEDULE_DAILY = 2,
238 SCHEDULE_HOURLY = 3,
239};
240
241static 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
38a8fa5a
PS
254enum 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
0e05d539 269struct maintenance_run_opts {
38a8fa5a
PS
270 enum maintenance_task_label *tasks;
271 size_t tasks_nr, tasks_alloc;
0e05d539 272 int auto_flag;
c7185df0 273 int detach;
0e05d539
PS
274 int quiet;
275 enum schedule_priority schedule;
276};
c7185df0
PS
277#define MAINTENANCE_RUN_OPTS_INIT { \
278 .detach = -1, \
279}
0e05d539 280
38a8fa5a
PS
281static void maintenance_run_opts_release(struct maintenance_run_opts *opts)
282{
283 free(opts->tasks);
284}
285
d1ae15d6 286static int pack_refs_condition(UNUSED struct gc_config *cfg)
9f6714ab
PS
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
3cdddcf6 296static int maintenance_task_pack_refs(struct maintenance_run_opts *opts,
d1ae15d6 297 UNUSED struct gc_config *cfg)
41abfe15 298{
ddbb47fd 299 struct child_process cmd = CHILD_PROCESS_INIT;
55916bba 300
ddbb47fd
RS
301 cmd.git_cmd = 1;
302 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
bfc2f9eb
PS
303 if (opts->auto_flag)
304 strvec_push(&cmd.args, "--auto");
305
ddbb47fd 306 return run_command(&cmd);
41abfe15
DS
307}
308
8e0a1ec0
PS
309struct count_reflog_entries_data {
310 struct expire_reflog_policy_cb policy;
311 size_t count;
312 size_t limit;
313};
314
315static int count_reflog_entries(struct object_id *old_oid, struct object_id *new_oid,
316 const char *committer, timestamp_t timestamp,
317 int tz, const char *msg, void *cb_data)
318{
319 struct count_reflog_entries_data *data = cb_data;
320 if (should_expire_reflog_ent(old_oid, new_oid, committer, timestamp, tz, msg, &data->policy))
321 data->count++;
322 return data->count >= data->limit;
323}
324
325static int reflog_expire_condition(struct gc_config *cfg UNUSED)
326{
327 timestamp_t now = time(NULL);
328 struct count_reflog_entries_data data = {
329 .policy = {
330 .opts = REFLOG_EXPIRE_OPTIONS_INIT(now),
331 },
332 };
333 int limit = 100;
334
335 git_config_get_int("maintenance.reflog-expire.auto", &limit);
336 if (!limit)
337 return 0;
338 if (limit < 0)
339 return 1;
340 data.limit = limit;
341
342 repo_config(the_repository, reflog_expire_config, &data.policy.opts);
343
344 reflog_expire_options_set_refname(&data.policy.opts, "HEAD");
345 refs_for_each_reflog_ent(get_main_ref_store(the_repository), "HEAD",
346 count_reflog_entries, &data);
347
348 reflog_expiry_cleanup(&data.policy);
349 return data.count >= data.limit;
350}
351
3fef24ac
PS
352static int maintenance_task_reflog_expire(struct maintenance_run_opts *opts UNUSED,
353 struct gc_config *cfg UNUSED)
354{
355 struct child_process cmd = CHILD_PROCESS_INIT;
356 cmd.git_cmd = 1;
357 strvec_pushl(&cmd.args, "reflog", "expire", "--all", NULL);
358 return run_command(&cmd);
359}
360
ae76c1c9
PS
361static int maintenance_task_worktree_prune(struct maintenance_run_opts *opts UNUSED,
362 struct gc_config *cfg)
363{
364 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
365
366 prune_worktrees_cmd.git_cmd = 1;
367 strvec_pushl(&prune_worktrees_cmd.args, "worktree", "prune", "--expire", NULL);
368 strvec_push(&prune_worktrees_cmd.args, cfg->prune_worktrees_expire);
369
370 return run_command(&prune_worktrees_cmd);
371}
372
ec314746
PS
373static int worktree_prune_condition(struct gc_config *cfg)
374{
375 struct strbuf buf = STRBUF_INIT;
376 int should_prune = 0, limit = 1;
377 timestamp_t expiry_date;
378 struct dirent *d;
379 DIR *dir = NULL;
380
381 git_config_get_int("maintenance.worktree-prune.auto", &limit);
382 if (limit <= 0) {
383 should_prune = limit < 0;
384 goto out;
385 }
386
387 if (parse_expiry_date(cfg->prune_worktrees_expire, &expiry_date))
388 goto out;
389
390 dir = opendir(repo_git_path_replace(the_repository, &buf, "worktrees"));
391 if (!dir)
392 goto out;
393
394 while (limit && (d = readdir_skip_dot_and_dotdot(dir))) {
395 char *wtpath;
396 strbuf_reset(&buf);
397 if (should_prune_worktree(d->d_name, &buf, &wtpath, expiry_date))
398 limit--;
399 free(wtpath);
400 }
401
402 should_prune = !limit;
403
404out:
405 if (dir)
406 closedir(dir);
407 strbuf_release(&buf);
408 return should_prune;
409}
410
255251cc
PS
411static int maintenance_task_rerere_gc(struct maintenance_run_opts *opts UNUSED,
412 struct gc_config *cfg UNUSED)
413{
414 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
415 rerere_cmd.git_cmd = 1;
416 strvec_pushl(&rerere_cmd.args, "rerere", "gc", NULL);
417 return run_command(&rerere_cmd);
418}
419
283621a5
PS
420static int rerere_gc_condition(struct gc_config *cfg UNUSED)
421{
422 struct strbuf path = STRBUF_INIT;
423 int should_gc = 0, limit = 1;
424 DIR *dir = NULL;
425
426 git_config_get_int("maintenance.rerere-gc.auto", &limit);
427 if (limit <= 0) {
428 should_gc = limit < 0;
429 goto out;
430 }
431
432 /*
433 * We skip garbage collection in case we either have no "rr-cache"
434 * directory or when it doesn't contain at least one entry.
435 */
436 repo_git_path_replace(the_repository, &path, "rr-cache");
437 dir = opendir(path.buf);
438 if (!dir)
439 goto out;
440 should_gc = !!readdir_skip_dot_and_dotdot(dir);
441
442out:
443 strbuf_release(&path);
444 if (dir)
445 closedir(dir);
446 return should_gc;
447}
448
d1ae15d6 449static int too_many_loose_objects(struct gc_config *cfg)
2c3c4399
JH
450{
451 /*
452 * Quickly check if a "gc" is needed, by estimating how
453 * many loose objects there are. Because SHA-1 is evenly
454 * distributed, we can check only one and get a reasonable
455 * estimate.
456 */
2c3c4399
JH
457 DIR *dir;
458 struct dirent *ent;
459 int auto_threshold;
460 int num_loose = 0;
461 int needed = 0;
e5cdbd5f 462 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
88dd321c 463 char *path;
2c3c4399 464
88dd321c
PS
465 path = repo_git_path(the_repository, "objects/17");
466 dir = opendir(path);
467 free(path);
2c3c4399
JH
468 if (!dir)
469 return 0;
470
d1ae15d6 471 auto_threshold = DIV_ROUND_UP(cfg->gc_auto_threshold, 256);
2c3c4399 472 while ((ent = readdir(dir)) != NULL) {
e5cdbd5f
ÆAB
473 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
474 ent->d_name[hexsz_loose] != '\0')
2c3c4399
JH
475 continue;
476 if (++num_loose > auto_threshold) {
477 needed = 1;
478 break;
479 }
480 }
481 closedir(dir);
482 return needed;
483}
484
9806f5a7
NTND
485static struct packed_git *find_base_packs(struct string_list *packs,
486 unsigned long limit)
ae4e89e5
NTND
487{
488 struct packed_git *p, *base = NULL;
489
454ea2e4 490 for (p = get_all_packs(the_repository); p; p = p->next) {
05b9013b 491 if (!p->pack_local || p->is_cruft)
ae4e89e5 492 continue;
55dfe13d
NTND
493 if (limit) {
494 if (p->pack_size >= limit)
495 string_list_append(packs, p->pack_name);
496 } else if (!base || base->pack_size < p->pack_size) {
ae4e89e5
NTND
497 base = p;
498 }
499 }
500
501 if (base)
502 string_list_append(packs, base->pack_name);
9806f5a7
NTND
503
504 return base;
ae4e89e5
NTND
505}
506
d1ae15d6 507static int too_many_packs(struct gc_config *cfg)
17815501
JH
508{
509 struct packed_git *p;
510 int cnt;
511
d1ae15d6 512 if (cfg->gc_auto_pack_limit <= 0)
17815501
JH
513 return 0;
514
454ea2e4 515 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
17815501
JH
516 if (!p->pack_local)
517 continue;
01af249f 518 if (p->pack_keep)
17815501
JH
519 continue;
520 /*
521 * Perhaps check the size of the pack and count only
522 * very small ones here?
523 */
524 cnt++;
525 }
d1ae15d6 526 return cfg->gc_auto_pack_limit < cnt;
17815501
JH
527}
528
9806f5a7
NTND
529static uint64_t total_ram(void)
530{
531#if defined(HAVE_SYSINFO)
532 struct sysinfo si;
533
c9a51775
RJ
534 if (!sysinfo(&si)) {
535 uint64_t total = si.totalram;
536
537 if (si.mem_unit > 1)
538 total *= (uint64_t)si.mem_unit;
539 return total;
540 }
35c1d592 541#elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
781c1cf5 542 uint64_t physical_memory;
9806f5a7
NTND
543 int mib[2];
544 size_t length;
545
546 mib[0] = CTL_HW;
547# if defined(HW_MEMSIZE)
548 mib[1] = HW_MEMSIZE;
35c1d592
BS
549# elif defined(HW_PHYSMEM64)
550 mib[1] = HW_PHYSMEM64;
9806f5a7
NTND
551# else
552 mib[1] = HW_PHYSMEM;
553# endif
781c1cf5
CMAB
554 length = sizeof(physical_memory);
555 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0)) {
556 if (length == 4) {
557 uint32_t mem;
558
559 if (!sysctl(mib, 2, &mem, &length, NULL, 0))
560 physical_memory = mem;
561 }
9806f5a7 562 return physical_memory;
781c1cf5 563 }
9806f5a7
NTND
564#elif defined(GIT_WINDOWS_NATIVE)
565 MEMORYSTATUSEX memInfo;
566
567 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
568 if (GlobalMemoryStatusEx(&memInfo))
569 return memInfo.ullTotalPhys;
570#endif
571 return 0;
572}
573
d1ae15d6
PS
574static uint64_t estimate_repack_memory(struct gc_config *cfg,
575 struct packed_git *pack)
9806f5a7 576{
afe27c88 577 unsigned long nr_objects = repo_approximate_object_count(the_repository);
9806f5a7
NTND
578 size_t os_cache, heap;
579
580 if (!pack || !nr_objects)
581 return 0;
582
583 /*
584 * First we have to scan through at least one pack.
585 * Assume enough room in OS file cache to keep the entire pack
586 * or we may accidentally evict data of other processes from
587 * the cache.
588 */
589 os_cache = pack->pack_size + pack->index_size;
590 /* then pack-objects needs lots more for book keeping */
591 heap = sizeof(struct object_entry) * nr_objects;
592 /*
593 * internal rev-list --all --objects takes up some memory too,
594 * let's say half of it is for blobs
595 */
596 heap += sizeof(struct blob) * nr_objects / 2;
597 /*
598 * and the other half is for trees (commits and tags are
599 * usually insignificant)
600 */
601 heap += sizeof(struct tree) * nr_objects / 2;
602 /* and then obj_hash[], underestimated in fact */
603 heap += sizeof(struct object *) * nr_objects;
604 /* revindex is used also */
2891b434 605 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
9806f5a7
NTND
606 /*
607 * read_sha1_file() (either at delta calculation phase, or
608 * writing phase) also fills up the delta base cache
609 */
d6b2d21f 610 heap += cfg->delta_base_cache_limit;
9806f5a7 611 /* and of course pack-objects has its own delta cache */
d1ae15d6 612 heap += cfg->max_delta_cache_size;
9806f5a7
NTND
613
614 return os_cache + heap;
615}
616
1ee34710 617static int keep_one_pack(struct string_list_item *item, void *data UNUSED)
ae4e89e5 618{
22f9b7f3 619 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
ae4e89e5
NTND
620 return 0;
621}
622
d1ae15d6
PS
623static void add_repack_all_option(struct gc_config *cfg,
624 struct string_list *keep_pack)
7e52f566 625{
08032fa3
ZH
626 if (cfg->prune_expire && !strcmp(cfg->prune_expire, "now")
627 && !(cfg->cruft_packs && cfg->repack_expire_to))
22f9b7f3 628 strvec_push(&repack, "-a");
d1ae15d6 629 else if (cfg->cruft_packs) {
5b92477f 630 strvec_push(&repack, "--cruft");
d1ae15d6
PS
631 if (cfg->prune_expire)
632 strvec_pushf(&repack, "--cruft-expiration=%s", cfg->prune_expire);
633 if (cfg->max_cruft_size)
37dc6d81 634 strvec_pushf(&repack, "--max-cruft-size=%lu",
d1ae15d6 635 cfg->max_cruft_size);
08032fa3
ZH
636 if (cfg->repack_expire_to)
637 strvec_pushf(&repack, "--expire-to=%s", cfg->repack_expire_to);
5b92477f 638 } else {
22f9b7f3 639 strvec_push(&repack, "-A");
d1ae15d6
PS
640 if (cfg->prune_expire)
641 strvec_pushf(&repack, "--unpack-unreachable=%s", cfg->prune_expire);
7e52f566 642 }
ae4e89e5
NTND
643
644 if (keep_pack)
645 for_each_string_list(keep_pack, keep_one_pack, NULL);
1cd43a9e 646
d1ae15d6
PS
647 if (cfg->repack_filter && *cfg->repack_filter)
648 strvec_pushf(&repack, "--filter=%s", cfg->repack_filter);
649 if (cfg->repack_filter_to && *cfg->repack_filter_to)
650 strvec_pushf(&repack, "--filter-to=%s", cfg->repack_filter_to);
7e52f566
JK
651}
652
bdf56de8
DT
653static void add_repack_incremental_option(void)
654{
22f9b7f3 655 strvec_push(&repack, "--no-write-bitmap-index");
bdf56de8
DT
656}
657
d1ae15d6 658static int need_to_gc(struct gc_config *cfg)
a087cc98
JH
659{
660 /*
b14d255b
BC
661 * Setting gc.auto to 0 or negative can disable the
662 * automatic gc.
a087cc98 663 */
d1ae15d6 664 if (cfg->gc_auto_threshold <= 0)
95143f9e
JH
665 return 0;
666
17815501
JH
667 /*
668 * If there are too many loose objects, but not too many
669 * packs, we run "repack -d -l". If there are too many packs,
670 * we run "repack -A -d -l". Otherwise we tell the caller
671 * there is no need.
672 */
d1ae15d6 673 if (too_many_packs(cfg)) {
55dfe13d
NTND
674 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
675
d1ae15d6
PS
676 if (cfg->big_pack_threshold) {
677 find_base_packs(&keep_pack, cfg->big_pack_threshold);
678 if (keep_pack.nr >= cfg->gc_auto_pack_limit) {
679 cfg->big_pack_threshold = 0;
8fc67762
NTND
680 string_list_clear(&keep_pack, 0);
681 find_base_packs(&keep_pack, 0);
682 }
9806f5a7
NTND
683 } else {
684 struct packed_git *p = find_base_packs(&keep_pack, 0);
685 uint64_t mem_have, mem_want;
686
687 mem_have = total_ram();
d1ae15d6 688 mem_want = estimate_repack_memory(cfg, p);
9806f5a7
NTND
689
690 /*
691 * Only allow 1/2 of memory for pack-objects, leave
692 * the rest for the OS and other processes in the
693 * system.
694 */
695 if (!mem_have || mem_want < mem_have / 2)
696 string_list_clear(&keep_pack, 0);
8fc67762 697 }
55dfe13d 698
d1ae15d6 699 add_repack_all_option(cfg, &keep_pack);
55dfe13d 700 string_list_clear(&keep_pack, 0);
d1ae15d6 701 } else if (too_many_loose_objects(cfg))
bdf56de8
DT
702 add_repack_incremental_option();
703 else
17815501 704 return 0;
bde30540 705
169c9797 706 if (run_hooks(the_repository, "pre-auto-gc"))
bde30540 707 return 0;
95143f9e 708 return 1;
a087cc98
JH
709}
710
64a99eb4
NTND
711/* return NULL on success, else hostname running the gc */
712static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
713{
b2275868 714 struct lock_file lock = LOCK_INIT;
da25bdb7 715 char my_host[HOST_NAME_MAX + 1];
64a99eb4
NTND
716 struct strbuf sb = STRBUF_INIT;
717 struct stat st;
718 uintmax_t pid;
719 FILE *fp;
4f1c0b21 720 int fd;
00539cef 721 char *pidfile_path;
64a99eb4 722
076aa2cb 723 if (is_tempfile_active(pidfile))
4c5baf02
JN
724 /* already locked */
725 return NULL;
726
5781a9a2 727 if (xgethostname(my_host, sizeof(my_host)))
5096d490 728 xsnprintf(my_host, sizeof(my_host), "unknown");
64a99eb4 729
bba59f58 730 pidfile_path = repo_git_path(the_repository, "gc.pid");
00539cef 731 fd = hold_lock_file_for_update(&lock, pidfile_path,
64a99eb4
NTND
732 LOCK_DIE_ON_ERROR);
733 if (!force) {
da25bdb7
RS
734 static char locking_host[HOST_NAME_MAX + 1];
735 static char *scan_fmt;
4f1c0b21 736 int should_exit;
da25bdb7
RS
737
738 if (!scan_fmt)
afe2fab7 739 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
00539cef 740 fp = fopen(pidfile_path, "r");
64a99eb4
NTND
741 memset(locking_host, 0, sizeof(locking_host));
742 should_exit =
743 fp != NULL &&
744 !fstat(fileno(fp), &st) &&
745 /*
746 * 12 hour limit is very generous as gc should
747 * never take that long. On the other hand we
748 * don't really need a strict limit here,
749 * running gc --auto one day late is not a big
750 * problem. --force can be used in manual gc
751 * after the user verifies that no gc is
752 * running.
753 */
754 time(NULL) - st.st_mtime <= 12 * 3600 &&
da25bdb7 755 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
64a99eb4 756 /* be gentle to concurrent "gc" on remote hosts */
ed7eda8b 757 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
afe8a907 758 if (fp)
64a99eb4
NTND
759 fclose(fp);
760 if (should_exit) {
761 if (fd >= 0)
762 rollback_lock_file(&lock);
763 *ret_pid = pid;
00539cef 764 free(pidfile_path);
64a99eb4
NTND
765 return locking_host;
766 }
767 }
768
769 strbuf_addf(&sb, "%"PRIuMAX" %s",
770 (uintmax_t) getpid(), my_host);
771 write_in_full(fd, sb.buf, sb.len);
772 strbuf_release(&sb);
773 commit_lock_file(&lock);
076aa2cb 774 pidfile = register_tempfile(pidfile_path);
ebebeaea 775 free(pidfile_path);
64a99eb4
NTND
776 return NULL;
777}
778
30299702
JN
779/*
780 * Returns 0 if there was no previous error and gc can proceed, 1 if
781 * gc should not proceed due to an error in the last run. Prints a
24f6e6d6
ÆAB
782 * message and returns with a non-[01] status code if an error occurred
783 * while reading gc.log
30299702
JN
784 */
785static int report_last_gc_error(void)
329e6e87
NTND
786{
787 struct strbuf sb = STRBUF_INIT;
30299702 788 int ret = 0;
3c426ecc 789 ssize_t len;
a831c06a 790 struct stat st;
bba59f58 791 char *gc_log_path = repo_git_path(the_repository, "gc.log");
329e6e87 792
a831c06a
DT
793 if (stat(gc_log_path, &st)) {
794 if (errno == ENOENT)
795 goto done;
796
24f6e6d6 797 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
30299702 798 goto done;
a831c06a
DT
799 }
800
801 if (st.st_mtime < gc_log_expire_time)
802 goto done;
803
3c426ecc
JN
804 len = strbuf_read_file(&sb, gc_log_path, 0);
805 if (len < 0)
24f6e6d6 806 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
30299702
JN
807 else if (len > 0) {
808 /*
809 * A previous gc failed. Report the error, and don't
810 * bother with an automatic gc run since it is likely
811 * to fail in the same way.
812 */
813 warning(_("The last gc run reported the following. "
329e6e87 814 "Please correct the root cause\n"
b45c172e 815 "and remove %s\n"
329e6e87
NTND
816 "Automatic cleanup will not be performed "
817 "until the file is removed.\n\n"
818 "%s"),
a831c06a 819 gc_log_path, sb.buf);
30299702
JN
820 ret = 1;
821 }
329e6e87 822 strbuf_release(&sb);
a831c06a
DT
823done:
824 free(gc_log_path);
30299702 825 return ret;
329e6e87
NTND
826}
827
1b5074e6
PS
828static int gc_foreground_tasks(struct maintenance_run_opts *opts,
829 struct gc_config *cfg)
62aad184 830{
d1ae15d6 831 if (cfg->pack_refs && maintenance_task_pack_refs(opts, cfg))
d2b084c6 832 return error(FAILED_RUN, "pack-refs");
3fef24ac 833 if (cfg->prune_reflogs && maintenance_task_reflog_expire(opts, cfg))
d2b084c6
PS
834 return error(FAILED_RUN, "reflog");
835 return 0;
62aad184
NTND
836}
837
9b1cb507 838int cmd_gc(int argc,
58f62837
PS
839 const char **argv,
840 const char *prefix,
841 struct repository *repo UNUSED)
6757ada4 842{
44c637c8 843 int aggressive = 0;
64a99eb4
NTND
844 int force = 0;
845 const char *name;
846 pid_t pid;
329e6e87 847 int daemonized = 0;
793c1464 848 int keep_largest_pack = -1;
1b5074e6 849 int skip_foreground_tasks = 0;
8ab5aa4b 850 timestamp_t dummy;
c7185df0 851 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
d1ae15d6 852 struct gc_config cfg = GC_CONFIG_INIT;
0ce44e22
PS
853 const char *prune_expire_sentinel = "sentinel";
854 const char *prune_expire_arg = prune_expire_sentinel;
855 int ret;
44c637c8 856 struct option builtin_gc_options[] = {
bd19b94a 857 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
d012ceb5
PS
858 {
859 .type = OPTION_STRING,
860 .long_name = "prune",
861 .value = &prune_expire_arg,
862 .argh = N_("date"),
863 .help = N_("prune unreferenced objects"),
864 .flags = PARSE_OPT_OPTARG,
865 .defval = (intptr_t)prune_expire_arg,
866 },
d1ae15d6 867 OPT_BOOL(0, "cruft", &cfg.cruft_packs, N_("pack unreferenced objects separately")),
785c17df
PS
868 OPT_UNSIGNED(0, "max-cruft-size", &cfg.max_cruft_size,
869 N_("with --cruft, limit the size of new cruft packs")),
d5d09d47 870 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
bfc2f9eb 871 OPT_BOOL_F(0, "auto", &opts.auto_flag, N_("enable auto-gc mode"),
7e1eeaa4 872 PARSE_OPT_NOCOMPLETE),
c7185df0
PS
873 OPT_BOOL(0, "detach", &opts.detach,
874 N_("perform garbage collection in the background")),
7e1eeaa4
NTND
875 OPT_BOOL_F(0, "force", &force,
876 N_("force running gc even if there may be another gc running"),
877 PARSE_OPT_NOCOMPLETE),
793c1464 878 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
ae4e89e5 879 N_("repack all other packs except the largest pack")),
08032fa3
ZH
880 OPT_STRING(0, "expire-to", &cfg.repack_expire_to, N_("dir"),
881 N_("pack prefix to store a pack containing pruned objects")),
1b5074e6
PS
882 OPT_HIDDEN_BOOL(0, "skip-foreground-tasks", &skip_foreground_tasks,
883 N_("skip maintenance tasks typically done in the foreground")),
44c637c8
JB
884 OPT_END()
885 };
886
b821c999
JH
887 show_usage_with_options_if_asked(argc, argv,
888 builtin_gc_usage, builtin_gc_options);
0c8151b6 889
22f9b7f3 890 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
234587fc 891
d1ae15d6 892 gc_config(&cfg);
0ce44e22 893
d1ae15d6
PS
894 if (parse_expiry_date(cfg.gc_log_expire, &gc_log_expire_time))
895 die(_("failed to parse gc.logExpiry value %s"), cfg.gc_log_expire);
6757ada4 896
d1ae15d6
PS
897 if (cfg.pack_refs < 0)
898 cfg.pack_refs = !is_bare_repository();
6757ada4 899
37782920
SB
900 argc = parse_options(argc, argv, prefix, builtin_gc_options,
901 builtin_gc_usage, 0);
44c637c8
JB
902 if (argc > 0)
903 usage_with_options(builtin_gc_usage, builtin_gc_options);
904
0ce44e22
PS
905 if (prune_expire_arg != prune_expire_sentinel) {
906 free(cfg.prune_expire);
907 cfg.prune_expire = xstrdup_or_null(prune_expire_arg);
908 }
d1ae15d6
PS
909 if (cfg.prune_expire && parse_expiry_date(cfg.prune_expire, &dummy))
910 die(_("failed to parse prune expiry value %s"), cfg.prune_expire);
8ab5aa4b 911
44c637c8 912 if (aggressive) {
22f9b7f3 913 strvec_push(&repack, "-f");
d1ae15d6
PS
914 if (cfg.aggressive_depth > 0)
915 strvec_pushf(&repack, "--depth=%d", cfg.aggressive_depth);
916 if (cfg.aggressive_window > 0)
917 strvec_pushf(&repack, "--window=%d", cfg.aggressive_window);
6757ada4 918 }
bd19b94a 919 if (opts.quiet)
22f9b7f3 920 strvec_push(&repack, "-q");
6757ada4 921
bfc2f9eb 922 if (opts.auto_flag) {
c7185df0
PS
923 if (cfg.detach_auto && opts.detach < 0)
924 opts.detach = 1;
925
2c3c4399
JH
926 /*
927 * Auto-gc should be least intrusive as possible.
928 */
0ce44e22
PS
929 if (!need_to_gc(&cfg)) {
930 ret = 0;
931 goto out;
932 }
933
bd19b94a 934 if (!opts.quiet) {
c7185df0 935 if (opts.detach > 0)
9f673f94
NTND
936 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
937 else
938 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
939 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
940 }
ae4e89e5
NTND
941 } else {
942 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
943
793c1464
ÆAB
944 if (keep_largest_pack != -1) {
945 if (keep_largest_pack)
55dfe13d 946 find_base_packs(&keep_pack, 0);
d1ae15d6
PS
947 } else if (cfg.big_pack_threshold) {
948 find_base_packs(&keep_pack, cfg.big_pack_threshold);
ae4e89e5
NTND
949 }
950
d1ae15d6 951 add_repack_all_option(&cfg, &keep_pack);
ae4e89e5
NTND
952 string_list_clear(&keep_pack, 0);
953 }
2c3c4399 954
c7185df0
PS
955 if (opts.detach > 0) {
956 ret = report_last_gc_error();
957 if (ret == 1) {
958 /* Last gc --auto failed. Skip this one. */
959 ret = 0;
960 goto out;
961
962 } else if (ret) {
963 /* an I/O error occurred, already reported */
964 goto out;
965 }
966
1b5074e6
PS
967 if (!skip_foreground_tasks) {
968 if (lock_repo_for_gc(force, &pid)) {
969 ret = 0;
970 goto out;
971 }
c7185df0 972
1b5074e6
PS
973 if (gc_foreground_tasks(&opts, &cfg) < 0)
974 die(NULL);
975 delete_tempfile(&pidfile);
976 }
c7185df0
PS
977
978 /*
979 * failure to daemonize is ok, we'll continue
980 * in foreground
981 */
982 daemonized = !daemonize();
983 }
984
64a99eb4
NTND
985 name = lock_repo_for_gc(force, &pid);
986 if (name) {
0ce44e22
PS
987 if (opts.auto_flag) {
988 ret = 0;
989 goto out; /* be quiet on --auto */
990 }
991
64a99eb4
NTND
992 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
993 name, (uintmax_t)pid);
994 }
995
329e6e87 996 if (daemonized) {
88dd321c
PS
997 char *path = repo_git_path(the_repository, "gc.log");
998 hold_lock_file_for_update(&log_lock, path,
329e6e87 999 LOCK_DIE_ON_ERROR);
076c8278 1000 dup2(get_lock_file_fd(&log_lock), 2);
329e6e87 1001 atexit(process_log_file_at_exit);
88dd321c 1002 free(path);
329e6e87
NTND
1003 }
1004
1b5074e6
PS
1005 if (opts.detach <= 0 && !skip_foreground_tasks)
1006 gc_foreground_tasks(&opts, &cfg);
6757ada4 1007
44e300a9 1008 if (!the_repository->repository_format_precious_objects) {
ddbb47fd
RS
1009 struct child_process repack_cmd = CHILD_PROCESS_INIT;
1010
1011 repack_cmd.git_cmd = 1;
1012 repack_cmd.close_object_store = 1;
1013 strvec_pushv(&repack_cmd.args, repack.v);
1014 if (run_command(&repack_cmd))
d70a9eb6 1015 die(FAILED_RUN, repack.v[0]);
067fbd41 1016
d1ae15d6 1017 if (cfg.prune_expire) {
ddbb47fd
RS
1018 struct child_process prune_cmd = CHILD_PROCESS_INIT;
1019
e3a69d72 1020 strvec_pushl(&prune_cmd.args, "prune", "--expire", NULL);
5b92477f 1021 /* run `git prune` even if using cruft packs */
e3a69d72 1022 strvec_push(&prune_cmd.args, cfg.prune_expire);
bd19b94a 1023 if (opts.quiet)
e3a69d72 1024 strvec_push(&prune_cmd.args, "--no-progress");
a5183d76 1025 if (repo_has_promisor_remote(the_repository))
e3a69d72 1026 strvec_push(&prune_cmd.args,
f6d8942b 1027 "--exclude-promisor-objects");
ddbb47fd 1028 prune_cmd.git_cmd = 1;
e3a69d72 1029
ddbb47fd 1030 if (run_command(&prune_cmd))
e3a69d72 1031 die(FAILED_RUN, prune_cmd.args.v[0]);
067fbd41 1032 }
58e9d9d4 1033 }
6757ada4 1034
ae76c1c9
PS
1035 if (cfg.prune_worktrees_expire &&
1036 maintenance_task_worktree_prune(&opts, &cfg))
1037 die(FAILED_RUN, "worktree");
ddbb47fd 1038
255251cc
PS
1039 if (maintenance_task_rerere_gc(&opts, &cfg))
1040 die(FAILED_RUN, "rerere");
6757ada4 1041
478f34d2 1042 report_garbage = report_pack_garbage;
a49d2834 1043 reprepare_packed_git(the_repository);
5bdece0d 1044 if (pack_garbage.nr > 0) {
2d511cfc 1045 close_object_store(the_repository->objects);
478f34d2 1046 clean_pack_garbage();
5bdece0d 1047 }
478f34d2 1048
7211b9e7 1049 if (the_repository->settings.gc_write_commit_graph == 1)
a1e2581a 1050 write_commit_graph_reachable(the_repository->objects->sources,
bd19b94a 1051 !opts.quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
7211b9e7 1052 NULL);
d5d5d7b6 1053
d1ae15d6 1054 if (opts.auto_flag && too_many_loose_objects(&cfg))
fea6128b
ÆAB
1055 warning(_("There are too many unreachable loose objects; "
1056 "run 'git prune' to remove them."));
a087cc98 1057
88dd321c
PS
1058 if (!daemonized) {
1059 char *path = repo_git_path(the_repository, "gc.log");
1060 unlink(path);
1061 free(path);
1062 }
a831c06a 1063
0ce44e22 1064out:
38a8fa5a 1065 maintenance_run_opts_release(&opts);
0ce44e22 1066 gc_config_release(&cfg);
6757ada4
JB
1067 return 0;
1068}
2057d750 1069
b08ff1fe
DS
1070static const char *const builtin_maintenance_run_usage[] = {
1071 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
2057d750
DS
1072 NULL
1073};
1074
b08ff1fe
DS
1075static int maintenance_opt_schedule(const struct option *opt, const char *arg,
1076 int unset)
1077{
1078 enum schedule_priority *priority = opt->value;
1079
1080 if (unset)
1081 die(_("--no-schedule is not allowed"));
1082
1083 *priority = parse_schedule(arg);
1084
1085 if (!*priority)
1086 die(_("unrecognized --schedule argument '%s'"), arg);
1087
1088 return 0;
1089}
1090
4ddc79b2
DS
1091/* Remember to update object flag allocation in object.h */
1092#define SEEN (1u<<0)
1093
1094struct cg_auto_data {
1095 int num_not_in_graph;
1096 int limit;
1097};
1098
5cf88fd8 1099static int dfs_on_ref(const char *refname UNUSED,
e8207717 1100 const char *referent UNUSED,
63e14ee2 1101 const struct object_id *oid,
5cf88fd8 1102 int flags UNUSED,
4ddc79b2
DS
1103 void *cb_data)
1104{
1105 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
1106 int result = 0;
1107 struct object_id peeled;
1108 struct commit_list *stack = NULL;
1109 struct commit *commit;
1110
30aaff43 1111 if (!peel_iterated_oid(the_repository, oid, &peeled))
4ddc79b2 1112 oid = &peeled;
e989dd96 1113 if (odb_read_object_info(the_repository->objects, oid, NULL) != OBJ_COMMIT)
4ddc79b2
DS
1114 return 0;
1115
1116 commit = lookup_commit(the_repository, oid);
1117 if (!commit)
1118 return 0;
ecb5091f 1119 if (repo_parse_commit(the_repository, commit) ||
8f801804 1120 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
4ddc79b2
DS
1121 return 0;
1122
8f801804
DS
1123 data->num_not_in_graph++;
1124
1125 if (data->num_not_in_graph >= data->limit)
1126 return 1;
1127
4ddc79b2
DS
1128 commit_list_append(commit, &stack);
1129
1130 while (!result && stack) {
1131 struct commit_list *parent;
1132
1133 commit = pop_commit(&stack);
1134
1135 for (parent = commit->parents; parent; parent = parent->next) {
ecb5091f 1136 if (repo_parse_commit(the_repository, parent->item) ||
4ddc79b2
DS
1137 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
1138 parent->item->object.flags & SEEN)
1139 continue;
1140
1141 parent->item->object.flags |= SEEN;
1142 data->num_not_in_graph++;
1143
1144 if (data->num_not_in_graph >= data->limit) {
1145 result = 1;
1146 break;
1147 }
1148
1149 commit_list_append(parent->item, &stack);
1150 }
1151 }
1152
1153 free_commit_list(stack);
1154 return result;
1155}
1156
551e4de8 1157static int should_write_commit_graph(struct gc_config *cfg UNUSED)
4ddc79b2
DS
1158{
1159 int result;
1160 struct cg_auto_data data;
1161
1162 data.num_not_in_graph = 0;
1163 data.limit = 100;
1164 git_config_get_int("maintenance.commit-graph.auto",
1165 &data.limit);
1166
1167 if (!data.limit)
1168 return 0;
1169 if (data.limit < 0)
1170 return 1;
1171
2e5c4758
PS
1172 result = refs_for_each_ref(get_main_ref_store(the_repository),
1173 dfs_on_ref, &data);
4ddc79b2 1174
cd888845 1175 repo_clear_commit_marks(the_repository, SEEN);
4ddc79b2
DS
1176
1177 return result;
1178}
1179
663b2b1b
DS
1180static int run_write_commit_graph(struct maintenance_run_opts *opts)
1181{
1182 struct child_process child = CHILD_PROCESS_INIT;
1183
c4dee2c0 1184 child.git_cmd = child.close_object_store = 1;
663b2b1b
DS
1185 strvec_pushl(&child.args, "commit-graph", "write",
1186 "--split", "--reachable", NULL);
1187
1188 if (opts->quiet)
1189 strvec_push(&child.args, "--no-progress");
286183da
DS
1190 else
1191 strvec_push(&child.args, "--progress");
663b2b1b
DS
1192
1193 return !!run_command(&child);
1194}
1195
d1ae15d6 1196static int maintenance_task_commit_graph(struct maintenance_run_opts *opts,
551e4de8 1197 struct gc_config *cfg UNUSED)
663b2b1b 1198{
d334107c
DS
1199 prepare_repo_settings(the_repository);
1200 if (!the_repository->settings.core_commit_graph)
1201 return 0;
1202
663b2b1b
DS
1203 if (run_write_commit_graph(opts)) {
1204 error(_("failed to write commit-graph"));
1205 return 1;
1206 }
1207
1208 return 0;
1209}
1210
a039a1fc 1211static int fetch_remote(struct remote *remote, void *cbdata)
28cb5e66 1212{
a039a1fc 1213 struct maintenance_run_opts *opts = cbdata;
28cb5e66
DS
1214 struct child_process child = CHILD_PROCESS_INIT;
1215
32f67888
DS
1216 if (remote->skip_default_update)
1217 return 0;
1218
28cb5e66 1219 child.git_cmd = 1;
cfd781ea
DS
1220 strvec_pushl(&child.args, "fetch", remote->name,
1221 "--prefetch", "--prune", "--no-tags",
28cb5e66 1222 "--no-write-fetch-head", "--recurse-submodules=no",
cfd781ea 1223 NULL);
28cb5e66
DS
1224
1225 if (opts->quiet)
1226 strvec_push(&child.args, "--quiet");
1227
28cb5e66
DS
1228 return !!run_command(&child);
1229}
1230
d1ae15d6 1231static int maintenance_task_prefetch(struct maintenance_run_opts *opts,
551e4de8 1232 struct gc_config *cfg UNUSED)
28cb5e66 1233{
a039a1fc
DS
1234 if (for_each_remote(fetch_remote, opts)) {
1235 error(_("failed to prefetch remotes"));
1236 return 1;
28cb5e66
DS
1237 }
1238
a039a1fc 1239 return 0;
28cb5e66
DS
1240}
1241
1b5074e6
PS
1242static int maintenance_task_gc_foreground(struct maintenance_run_opts *opts,
1243 struct gc_config *cfg)
1244{
1245 return gc_foreground_tasks(opts, cfg);
1246}
1247
1248static int maintenance_task_gc_background(struct maintenance_run_opts *opts,
1249 struct gc_config *cfg UNUSED)
2057d750
DS
1250{
1251 struct child_process child = CHILD_PROCESS_INIT;
1252
c4dee2c0 1253 child.git_cmd = child.close_object_store = 1;
2057d750
DS
1254 strvec_push(&child.args, "gc");
1255
1256 if (opts->auto_flag)
1257 strvec_push(&child.args, "--auto");
3ddaad0e
DS
1258 if (opts->quiet)
1259 strvec_push(&child.args, "--quiet");
1260 else
1261 strvec_push(&child.args, "--no-quiet");
98077d06 1262 strvec_push(&child.args, "--no-detach");
1b5074e6 1263 strvec_push(&child.args, "--skip-foreground-tasks");
2057d750 1264
2057d750
DS
1265 return run_command(&child);
1266}
1267
252cfb7c
DS
1268static int prune_packed(struct maintenance_run_opts *opts)
1269{
1270 struct child_process child = CHILD_PROCESS_INIT;
1271
1272 child.git_cmd = 1;
1273 strvec_push(&child.args, "prune-packed");
1274
1275 if (opts->quiet)
1276 strvec_push(&child.args, "--quiet");
1277
1278 return !!run_command(&child);
1279}
1280
1281struct write_loose_object_data {
1282 FILE *in;
1283 int count;
1284 int batch_size;
1285};
1286
3e220e60
DS
1287static int loose_object_auto_limit = 100;
1288
be252d33
JK
1289static int loose_object_count(const struct object_id *oid UNUSED,
1290 const char *path UNUSED,
1291 void *data)
3e220e60
DS
1292{
1293 int *count = (int*)data;
1294 if (++(*count) >= loose_object_auto_limit)
1295 return 1;
1296 return 0;
1297}
1298
551e4de8 1299static int loose_object_auto_condition(struct gc_config *cfg UNUSED)
3e220e60
DS
1300{
1301 int count = 0;
1302
1303 git_config_get_int("maintenance.loose-objects.auto",
1304 &loose_object_auto_limit);
1305
1306 if (!loose_object_auto_limit)
1307 return 0;
1308 if (loose_object_auto_limit < 0)
1309 return 1;
1310
a1e2581a 1311 return for_each_loose_file_in_objdir(the_repository->objects->sources->path,
3e220e60
DS
1312 loose_object_count,
1313 NULL, NULL, &count);
1314}
1315
be252d33
JK
1316static int bail_on_loose(const struct object_id *oid UNUSED,
1317 const char *path UNUSED,
1318 void *data UNUSED)
252cfb7c
DS
1319{
1320 return 1;
1321}
1322
1323static int write_loose_object_to_stdin(const struct object_id *oid,
be252d33 1324 const char *path UNUSED,
252cfb7c
DS
1325 void *data)
1326{
1327 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1328
1329 fprintf(d->in, "%s\n", oid_to_hex(oid));
1330
6540560f 1331 /* If batch_size is INT_MAX, then this will return 0 always. */
252cfb7c
DS
1332 return ++(d->count) > d->batch_size;
1333}
1334
1335static int pack_loose(struct maintenance_run_opts *opts)
1336{
1337 struct repository *r = the_repository;
1338 int result = 0;
1339 struct write_loose_object_data data;
1340 struct child_process pack_proc = CHILD_PROCESS_INIT;
1341
1342 /*
1343 * Do not start pack-objects process
1344 * if there are no loose objects.
1345 */
a1e2581a 1346 if (!for_each_loose_file_in_objdir(r->objects->sources->path,
252cfb7c
DS
1347 bail_on_loose,
1348 NULL, NULL, NULL))
1349 return 0;
1350
1351 pack_proc.git_cmd = 1;
1352
1353 strvec_push(&pack_proc.args, "pack-objects");
1354 if (opts->quiet)
1355 strvec_push(&pack_proc.args, "--quiet");
286183da
DS
1356 else
1357 strvec_push(&pack_proc.args, "--no-quiet");
a1e2581a 1358 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->sources->path);
252cfb7c
DS
1359
1360 pack_proc.in = -1;
1361
8311e3b5
PS
1362 /*
1363 * git-pack-objects(1) ends up writing the pack hash to stdout, which
1364 * we do not care for.
1365 */
1366 pack_proc.out = -1;
1367
252cfb7c
DS
1368 if (start_command(&pack_proc)) {
1369 error(_("failed to start 'git pack-objects' process"));
1370 return 1;
1371 }
1372
1373 data.in = xfdopen(pack_proc.in, "w");
1374 data.count = 0;
1375 data.batch_size = 50000;
1376
6540560f
DS
1377 repo_config_get_int(r, "maintenance.loose-objects.batchSize",
1378 &data.batch_size);
1379
1380 /* If configured as 0, then remove limit. */
1381 if (!data.batch_size)
1382 data.batch_size = INT_MAX;
1383 else if (data.batch_size > 0)
1384 data.batch_size--; /* Decrease for equality on limit. */
1385
a1e2581a 1386 for_each_loose_file_in_objdir(r->objects->sources->path,
252cfb7c
DS
1387 write_loose_object_to_stdin,
1388 NULL,
1389 NULL,
1390 &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
d1ae15d6 1402static int maintenance_task_loose_objects(struct maintenance_run_opts *opts,
551e4de8 1403 struct gc_config *cfg UNUSED)
252cfb7c
DS
1404{
1405 return prune_packed(opts) || pack_loose(opts);
1406}
1407
551e4de8 1408static int incremental_repack_auto_condition(struct gc_config *cfg UNUSED)
e841a79a
DS
1409{
1410 struct packed_git *p;
e841a79a
DS
1411 int incremental_repack_auto_limit = 10;
1412 int count = 0;
1413
a897ab7e
GC
1414 prepare_repo_settings(the_repository);
1415 if (!the_repository->settings.core_multi_pack_index)
e841a79a
DS
1416 return 0;
1417
1418 git_config_get_int("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
52fe41ff
DS
1436static 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");
286183da
DS
1445 else
1446 strvec_push(&child.args, "--progress");
52fe41ff
DS
1447
1448 if (run_command(&child))
1449 return error(_("failed to write multi-pack-index"));
1450
1451 return 0;
1452}
1453
1454static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1455{
1456 struct child_process child = CHILD_PROCESS_INIT;
1457
c4dee2c0 1458 child.git_cmd = child.close_object_store = 1;
52fe41ff
DS
1459 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1460
1461 if (opts->quiet)
1462 strvec_push(&child.args, "--no-progress");
286183da
DS
1463 else
1464 strvec_push(&child.args, "--progress");
52fe41ff 1465
52fe41ff
DS
1466 if (run_command(&child))
1467 return error(_("'git multi-pack-index expire' failed"));
1468
1469 return 0;
1470}
1471
a13e3d0e
DS
1472#define TWO_GIGABYTES (INT32_MAX)
1473
1474static 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
52fe41ff
DS
1512static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1513{
1514 struct child_process child = CHILD_PROCESS_INIT;
1515
c4dee2c0 1516 child.git_cmd = child.close_object_store = 1;
52fe41ff
DS
1517 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1518
1519 if (opts->quiet)
1520 strvec_push(&child.args, "--no-progress");
286183da
DS
1521 else
1522 strvec_push(&child.args, "--progress");
52fe41ff 1523
a13e3d0e
DS
1524 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1525 (uintmax_t)get_auto_pack_size());
52fe41ff 1526
52fe41ff
DS
1527 if (run_command(&child))
1528 return error(_("'git multi-pack-index repack' failed"));
1529
1530 return 0;
1531}
1532
d1ae15d6 1533static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts,
551e4de8 1534 struct gc_config *cfg UNUSED)
52fe41ff
DS
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
3236e03c
PS
1551typedef int (*maintenance_task_fn)(struct maintenance_run_opts *opts,
1552 struct gc_config *cfg);
3236e03c 1553typedef int (*maintenance_auto_fn)(struct gc_config *cfg);
916d0626 1554
3103e984
DS
1555struct maintenance_task {
1556 const char *name;
090511bc 1557
5bb4298a
PS
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;
3103e984 1564
5bb4298a
PS
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;
3103e984 1570
5bb4298a
PS
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 */
3236e03c 1575 maintenance_auto_fn auto_condition;
3103e984
DS
1576};
1577
38a8fa5a 1578static const struct maintenance_task tasks[] = {
28cb5e66 1579 [TASK_PREFETCH] = {
95b5039f 1580 .name = "prefetch",
5bb4298a 1581 .background = maintenance_task_prefetch,
28cb5e66 1582 },
252cfb7c 1583 [TASK_LOOSE_OBJECTS] = {
95b5039f 1584 .name = "loose-objects",
5bb4298a 1585 .background = maintenance_task_loose_objects,
95b5039f 1586 .auto_condition = loose_object_auto_condition,
252cfb7c 1587 },
52fe41ff 1588 [TASK_INCREMENTAL_REPACK] = {
95b5039f 1589 .name = "incremental-repack",
5bb4298a 1590 .background = maintenance_task_incremental_repack,
95b5039f 1591 .auto_condition = incremental_repack_auto_condition,
52fe41ff 1592 },
3103e984 1593 [TASK_GC] = {
95b5039f 1594 .name = "gc",
1b5074e6
PS
1595 .foreground = maintenance_task_gc_foreground,
1596 .background = maintenance_task_gc_background,
95b5039f 1597 .auto_condition = need_to_gc,
3103e984 1598 },
663b2b1b 1599 [TASK_COMMIT_GRAPH] = {
95b5039f 1600 .name = "commit-graph",
5bb4298a 1601 .background = maintenance_task_commit_graph,
95b5039f 1602 .auto_condition = should_write_commit_graph,
663b2b1b 1603 },
41abfe15 1604 [TASK_PACK_REFS] = {
95b5039f 1605 .name = "pack-refs",
c367852d 1606 .foreground = maintenance_task_pack_refs,
95b5039f 1607 .auto_condition = pack_refs_condition,
41abfe15 1608 },
8e0a1ec0 1609 [TASK_REFLOG_EXPIRE] = {
95b5039f 1610 .name = "reflog-expire",
c367852d 1611 .foreground = maintenance_task_reflog_expire,
95b5039f 1612 .auto_condition = reflog_expire_condition,
8e0a1ec0 1613 },
ec314746 1614 [TASK_WORKTREE_PRUNE] = {
95b5039f 1615 .name = "worktree-prune",
5bb4298a 1616 .background = maintenance_task_worktree_prune,
95b5039f 1617 .auto_condition = worktree_prune_condition,
ec314746 1618 },
283621a5 1619 [TASK_RERERE_GC] = {
95b5039f 1620 .name = "rerere-gc",
5bb4298a 1621 .background = maintenance_task_rerere_gc,
95b5039f 1622 .auto_condition = rerere_gc_condition,
283621a5 1623 },
3103e984
DS
1624};
1625
5bb4298a
PS
1626enum task_phase {
1627 TASK_PHASE_FOREGROUND,
1628 TASK_PHASE_BACKGROUND,
1629};
1630
2aa9ee7e
PS
1631static int maybe_run_task(const struct maintenance_task *task,
1632 struct repository *repo,
1633 struct maintenance_run_opts *opts,
5bb4298a
PS
1634 struct gc_config *cfg,
1635 enum task_phase phase)
090511bc 1636{
5bb4298a
PS
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";
2aa9ee7e 1640 int ret = 0;
090511bc 1641
5bb4298a
PS
1642 if (!fn)
1643 return 0;
2aa9ee7e
PS
1644 if (opts->auto_flag &&
1645 (!task->auto_condition || !task->auto_condition(cfg)))
1646 return 0;
1647
5bb4298a
PS
1648 trace2_region_enter(region, task->name, repo);
1649 if (fn(opts, cfg)) {
2aa9ee7e
PS
1650 error(_("task '%s' failed"), task->name);
1651 ret = 1;
1652 }
5bb4298a 1653 trace2_region_leave(region, task->name, repo);
2aa9ee7e
PS
1654
1655 return ret;
090511bc
DS
1656}
1657
d1ae15d6
PS
1658static int maintenance_run_tasks(struct maintenance_run_opts *opts,
1659 struct gc_config *cfg)
3103e984 1660{
3103e984 1661 int result = 0;
d7514f6e
DS
1662 struct lock_file lk;
1663 struct repository *r = the_repository;
a1e2581a 1664 char *lock_path = xstrfmt("%s/maintenance", r->objects->sources->path);
d7514f6e
DS
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);
3103e984 1681
5bb4298a
PS
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
a6affd33 1687 /* Failure to daemonize is ok, we'll continue in foreground. */
51a0b8a2
PS
1688 if (opts->detach > 0) {
1689 trace2_region_enter("maintenance", "detach", the_repository);
a6affd33 1690 daemonize();
51a0b8a2
PS
1691 trace2_region_leave("maintenance", "detach", the_repository);
1692 }
a6affd33 1693
2aa9ee7e 1694 for (size_t i = 0; i < opts->tasks_nr; i++)
5bb4298a
PS
1695 if (maybe_run_task(&tasks[opts->tasks[i]], r, opts, cfg,
1696 TASK_PHASE_BACKGROUND))
3103e984 1697 result = 1;
3103e984 1698
d7514f6e 1699 rollback_lock_file(&lk);
3103e984
DS
1700 return result;
1701}
1702
38a8fa5a
PS
1703struct maintenance_strategy {
1704 struct {
1705 int enabled;
1706 enum schedule_priority schedule;
1707 } tasks[TASK__COUNT];
1708};
1709
1710static const struct maintenance_strategy none_strategy = { 0 };
1711static const struct maintenance_strategy default_strategy = {
1712 .tasks = {
1713 [TASK_GC].enabled = 1,
1714 },
1715};
1716static 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
1731static void initialize_task_config(struct maintenance_run_opts *opts,
1732 const struct string_list *selected_tasks)
a4cb1a23 1733{
38a8fa5a
PS
1734 struct strbuf config_name = STRBUF_INIT;
1735 struct maintenance_strategy strategy;
84e9fc36 1736 const char *config_str;
a4cb1a23 1737
38a8fa5a
PS
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 }
a4cb1a23 1749
38a8fa5a 1750 return;
a4cb1a23 1751 }
a4cb1a23 1752
38a8fa5a
PS
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;
916d0626 1767
38a8fa5a
PS
1768 if (!git_config_get_string_tmp("maintenance.strategy", &config_str)) {
1769 if (!strcasecmp(config_str, "incremental"))
1770 strategy = incremental_strategy;
1771 }
1772 } else {
1773 strategy = default_strategy;
1bb6bdb6 1774 }
a4cb1a23 1775
1bb6bdb6 1776 for (size_t i = 0; i < TASK__COUNT; i++) {
65d655b5
DS
1777 int config_value;
1778
b08ff1fe 1779 strbuf_reset(&config_name);
65d655b5
DS
1780 strbuf_addf(&config_name, "maintenance.%s.enabled",
1781 tasks[i].name);
65d655b5 1782 if (!git_config_get_bool(config_name.buf, &config_value))
38a8fa5a
PS
1783 strategy.tasks[i].enabled = config_value;
1784 if (!strategy.tasks[i].enabled)
1785 continue;
b08ff1fe 1786
38a8fa5a
PS
1787 if (opts->schedule) {
1788 strbuf_reset(&config_name);
1789 strbuf_addf(&config_name, "maintenance.%s.schedule",
1790 tasks[i].name);
1791 if (!git_config_get_string_tmp(config_name.buf, &config_str))
1792 strategy.tasks[i].schedule = parse_schedule(config_str);
1793 if (strategy.tasks[i].schedule < opts->schedule)
1794 continue;
b08ff1fe 1795 }
38a8fa5a
PS
1796
1797 ALLOC_GROW(opts->tasks, opts->tasks_nr + 1, opts->tasks_alloc);
1798 opts->tasks[opts->tasks_nr++] = i;
65d655b5
DS
1799 }
1800
1801 strbuf_release(&config_name);
1802}
1803
1bb6bdb6 1804static int task_option_parse(const struct option *opt,
090511bc
DS
1805 const char *arg, int unset)
1806{
1bb6bdb6
PS
1807 struct string_list *selected_tasks = opt->value;
1808 size_t i;
090511bc
DS
1809
1810 BUG_ON_OPT_NEG(unset);
1811
1bb6bdb6
PS
1812 for (i = 0; i < TASK__COUNT; i++)
1813 if (!strcasecmp(tasks[i].name, arg))
1814 break;
1815 if (i >= TASK__COUNT) {
090511bc
DS
1816 error(_("'%s' is not a valid task"), arg);
1817 return 1;
1818 }
1819
1bb6bdb6 1820 if (unsorted_string_list_has_string(selected_tasks, arg)) {
090511bc
DS
1821 error(_("task '%s' cannot be selected multiple times"), arg);
1822 return 1;
1823 }
1824
38a8fa5a 1825 string_list_append(selected_tasks, arg)->util = (void *)(intptr_t)i;
090511bc
DS
1826
1827 return 0;
1828}
1829
6f33d8e2
KN
1830static int maintenance_run(int argc, const char **argv, const char *prefix,
1831 struct repository *repo UNUSED)
2057d750 1832{
c7185df0 1833 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
1bb6bdb6 1834 struct string_list selected_tasks = STRING_LIST_INIT_DUP;
d1ae15d6 1835 struct gc_config cfg = GC_CONFIG_INIT;
2057d750
DS
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")),
a6affd33
PS
1839 OPT_BOOL(0, "detach", &opts.detach,
1840 N_("perform maintenance in the background")),
b08ff1fe
DS
1841 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1842 N_("run tasks based on frequency"),
1843 maintenance_opt_schedule),
3ddaad0e
DS
1844 OPT_BOOL(0, "quiet", &opts.quiet,
1845 N_("do not report progress or other information over stderr")),
1bb6bdb6 1846 OPT_CALLBACK_F(0, "task", &selected_tasks, N_("task"),
090511bc
DS
1847 N_("run a specific task"),
1848 PARSE_OPT_NONEG, task_option_parse),
2057d750
DS
1849 OPT_END()
1850 };
0ce44e22 1851 int ret;
2057d750 1852
3ddaad0e
DS
1853 opts.quiet = !isatty(2);
1854
2057d750
DS
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
a7c86d32
PS
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=");
b08ff1fe 1864
d1ae15d6 1865 gc_config(&cfg);
38a8fa5a 1866 initialize_task_config(&opts, &selected_tasks);
a4cb1a23 1867
2057d750
DS
1868 if (argc != 0)
1869 usage_with_options(builtin_maintenance_run_usage,
1870 builtin_maintenance_run_options);
0ce44e22
PS
1871
1872 ret = maintenance_run_tasks(&opts, &cfg);
1bb6bdb6
PS
1873
1874 string_list_clear(&selected_tasks, 0);
38a8fa5a 1875 maintenance_run_opts_release(&opts);
0ce44e22
PS
1876 gc_config_release(&cfg);
1877 return ret;
2057d750
DS
1878}
1879
26c79743
ES
1880static 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
0d330a53 1890static char const * const builtin_maintenance_register_usage[] = {
1f80129d 1891 "git maintenance register [--config-file <path>]",
0d330a53
JK
1892 NULL
1893};
1894
6f33d8e2
KN
1895static int maintenance_register(int argc, const char **argv, const char *prefix,
1896 struct repository *repo UNUSED)
0c18b700 1897{
1f80129d 1898 char *config_file = NULL;
0d330a53 1899 struct option options[] = {
1f80129d 1900 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
0d330a53
JK
1901 OPT_END(),
1902 };
50a044f1
DS
1903 int found = 0;
1904 const char *key = "maintenance.repo";
26c79743 1905 char *maintpath = get_maintpath();
50a044f1
DS
1906 struct string_list_item *item;
1907 const struct string_list *list;
0c18b700 1908
0d330a53
JK
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
61f7a383
DS
1915 /* Disable foreground maintenance */
1916 git_config_set("maintenance.auto", "false");
1917
1918 /* Set maintenance strategy, if unset */
b83efcec 1919 if (git_config_get("maintenance.strategy"))
61f7a383
DS
1920 git_config_set("maintenance.strategy", "incremental");
1921
9e2d884d 1922 if (!git_config_get_string_multi(key, &list)) {
50a044f1
DS
1923 for_each_string_list_item(item, list) {
1924 if (!strcmp(maintpath, item->string)) {
1925 found = 1;
1926 break;
1927 }
1928 }
26c79743 1929 }
0c18b700 1930
50a044f1
DS
1931 if (!found) {
1932 int rc;
74e12192 1933 char *global_config_file = NULL;
1f80129d
RP
1934
1935 if (!config_file) {
74e12192
KH
1936 global_config_file = git_global_config();
1937 config_file = global_config_file;
1f80129d 1938 }
74e12192
KH
1939 if (!config_file)
1940 die(_("$HOME not set"));
50a044f1 1941 rc = git_config_set_multivar_in_file_gently(
1f80129d 1942 config_file, "maintenance.repo", maintpath,
42d5c033 1943 CONFIG_REGEX_NONE, NULL, 0);
74e12192 1944 free(global_config_file);
50a044f1
DS
1945
1946 if (rc)
1947 die(_("unable to add '%s' value of '%s'"),
1948 key, maintpath);
26c79743 1949 }
0c18b700 1950
26c79743 1951 free(maintpath);
50a044f1 1952 return 0;
0c18b700
DS
1953}
1954
0d330a53 1955static char const * const builtin_maintenance_unregister_usage[] = {
1f80129d 1956 "git maintenance unregister [--config-file <path>] [--force]",
0d330a53
JK
1957 NULL
1958};
1959
6f33d8e2
KN
1960static int maintenance_unregister(int argc, const char **argv, const char *prefix,
1961 struct repository *repo UNUSED)
0c18b700 1962{
1ebe6b02 1963 int force = 0;
1f80129d 1964 char *config_file = NULL;
0d330a53 1965 struct option options[] = {
1f80129d 1966 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1ebe6b02
DS
1967 OPT__FORCE(&force,
1968 N_("return success even if repository was not registered"),
1969 PARSE_OPT_NOCOMPLETE),
0d330a53
JK
1970 OPT_END(),
1971 };
1ebe6b02 1972 const char *key = "maintenance.repo";
26c79743 1973 char *maintpath = get_maintpath();
1ebe6b02
DS
1974 int found = 0;
1975 struct string_list_item *item;
1976 const struct string_list *list;
03744bbd 1977 struct config_set cs = { { 0 } };
0c18b700 1978
0d330a53
JK
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
1f80129d
RP
1985 if (config_file) {
1986 git_configset_init(&cs);
1987 git_configset_add_file(&cs, config_file);
1f80129d 1988 }
a4286193 1989 if (!(config_file
9e2d884d
ÆAB
1990 ? git_configset_get_string_multi(&cs, key, &list)
1991 : git_config_get_string_multi(key, &list))) {
1ebe6b02
DS
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) {
50a044f1 2001 int rc;
74e12192
KH
2002 char *global_config_file = NULL;
2003
1f80129d 2004 if (!config_file) {
74e12192
KH
2005 global_config_file = git_global_config();
2006 config_file = global_config_file;
1f80129d 2007 }
74e12192
KH
2008 if (!config_file)
2009 die(_("$HOME not set"));
50a044f1 2010 rc = git_config_set_multivar_in_file_gently(
42d5c033 2011 config_file, key, NULL, maintpath, NULL,
50a044f1 2012 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
74e12192 2013 free(global_config_file);
50a044f1
DS
2014
2015 if (rc &&
2016 (!force || rc == CONFIG_NOTHING_SET))
2017 die(_("unable to unset '%s' value of '%s'"),
2018 key, maintpath);
1ebe6b02
DS
2019 } else if (!force) {
2020 die(_("repository '%s' is not registered"), maintpath);
2021 }
0c18b700 2022
03744bbd 2023 git_configset_clear(&cs);
26c79743 2024 free(maintpath);
50a044f1 2025 return 0;
0c18b700
DS
2026}
2027
2afe7e35
DS
2028static 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
4f555195
DS
2042static const char *extraconfig[] = {
2043 "credential.interactive=false",
2044 "core.askPass=true", /* 'true' returns success, but no output. */
2045 NULL
2046};
2047
2048static 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
2062static 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
eba1ba9d
LH
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 *
b6c3f8e1
PS
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
eba1ba9d
LH
2094 * the mock command.
2095 *
2096 * * if the input value *cmd isn’t the key of any of the comma-separated list
b6c3f8e1
PS
2097 * item, then *is_available is set to false and *out is set to the original
2098 * command.
eba1ba9d
LH
2099 *
2100 * Ex.:
2101 * GIT_TEST_MAINT_SCHEDULER not set
2102 * +-------+-------------------------------------------------+
2103 * | Input | Output |
b6c3f8e1 2104 * | *cmd | return code | *out | *is_available |
eba1ba9d 2105 * +-------+-------------+-------------------+---------------+
c95547a3 2106 * | "foo" | false | "foo" (allocated) | (unchanged) |
eba1ba9d
LH
2107 * +-------+-------------+-------------------+---------------+
2108 *
2109 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
2110 * +-------+-------------------------------------------------+
2111 * | Input | Output |
b6c3f8e1 2112 * | *cmd | return code | *out | *is_available |
eba1ba9d
LH
2113 * +-------+-------------+-------------------+---------------+
2114 * | "foo" | true | "./mock.foo.sh" | true |
b6c3f8e1 2115 * | "qux" | true | "qux" (allocated) | false |
eba1ba9d
LH
2116 * +-------+-------------+-------------------+---------------+
2117 */
b6c3f8e1 2118static int get_schedule_cmd(const char *cmd, int *is_available, char **out)
eba1ba9d
LH
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
c95547a3
PS
2124 if (!testing) {
2125 if (out)
2126 *out = xstrdup(cmd);
eba1ba9d 2127 return 0;
c95547a3 2128 }
eba1ba9d
LH
2129
2130 if (is_available)
2131 *is_available = 0;
2132
52acddf3 2133 string_list_split_in_place(&list, testing, ",", -1);
eba1ba9d
LH
2134 for_each_string_list_item(item, &list) {
2135 struct string_list pair = STRING_LIST_INIT_NODUP;
2136
52acddf3 2137 if (string_list_split_in_place(&pair, item->string, ":", 2) != 2)
eba1ba9d
LH
2138 continue;
2139
b6c3f8e1
PS
2140 if (!strcmp(cmd, pair.items[0].string)) {
2141 if (out)
2142 *out = xstrdup(pair.items[1].string);
eba1ba9d
LH
2143 if (is_available)
2144 *is_available = 1;
b6c3f8e1
PS
2145 string_list_clear(&pair, 0);
2146 goto out;
eba1ba9d 2147 }
b6c3f8e1
PS
2148
2149 string_list_clear(&pair, 0);
eba1ba9d
LH
2150 }
2151
b6c3f8e1
PS
2152 if (out)
2153 *out = xstrdup(cmd);
2154
2155out:
eba1ba9d
LH
2156 string_list_clear(&list, 0);
2157 free(testing);
2158 return 1;
2159}
2160
89024a0a
DS
2161static 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
1568d156 2167 return git_rand(0) % 60;
89024a0a
DS
2168}
2169
eba1ba9d
LH
2170static int is_launchctl_available(void)
2171{
eba1ba9d 2172 int is_available;
b6c3f8e1 2173 if (get_schedule_cmd("launchctl", &is_available, NULL))
eba1ba9d
LH
2174 return is_available;
2175
2176#ifdef __APPLE__
2177 return 1;
2178#else
2179 return 0;
2180#endif
2181}
2182
2afe7e35
DS
2183static 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
2190static 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
a03b097d 2196 expanded = interpolate_path(filename.buf, 1);
2afe7e35
DS
2197 if (!expanded)
2198 die(_("failed to expand path '%s'"), filename.buf);
2199
2200 strbuf_release(&filename);
2201 return expanded;
2202}
2203
2204static char *launchctl_get_uid(void)
2205{
2206 return xstrfmt("gui/%d", getuid());
2207}
2208
eba1ba9d 2209static int launchctl_boot_plist(int enable, const char *filename)
2afe7e35 2210{
b6c3f8e1 2211 char *cmd;
2afe7e35
DS
2212 int result;
2213 struct child_process child = CHILD_PROCESS_INIT;
2214 char *uid = launchctl_get_uid();
2215
b6c3f8e1 2216 get_schedule_cmd("launchctl", NULL, &cmd);
2afe7e35 2217 strvec_split(&child.args, cmd);
eba1ba9d
LH
2218 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
2219 filename, NULL);
2afe7e35
DS
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
b6c3f8e1 2229 free(cmd);
2afe7e35
DS
2230 free(uid);
2231 return result;
2232}
2233
eba1ba9d 2234static int launchctl_remove_plist(enum schedule_priority schedule)
2afe7e35
DS
2235{
2236 const char *frequency = get_frequency(schedule);
2237 char *name = launchctl_service_name(frequency);
2238 char *filename = launchctl_service_filename(name);
eba1ba9d 2239 int result = launchctl_boot_plist(0, filename);
2afe7e35
DS
2240 unlink(filename);
2241 free(filename);
2242 free(name);
2243 return result;
2244}
2245
eba1ba9d 2246static int launchctl_remove_plists(void)
2afe7e35 2247{
eba1ba9d
LH
2248 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
2249 launchctl_remove_plist(SCHEDULE_DAILY) ||
2250 launchctl_remove_plist(SCHEDULE_WEEKLY);
2afe7e35
DS
2251}
2252
a16eb6b1
DS
2253static int launchctl_list_contains_plist(const char *name, const char *cmd)
2254{
a16eb6b1 2255 struct child_process child = CHILD_PROCESS_INIT;
a16eb6b1
DS
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
a16eb6b1 2266 /* Returns failure if 'name' doesn't exist. */
3218cb75 2267 return !finish_command(&child);
a16eb6b1
DS
2268}
2269
eba1ba9d 2270static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
2afe7e35 2271{
bb01122a 2272 int i, fd;
2afe7e35
DS
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);
bb01122a
JS
2277 struct lock_file lk = LOCK_INIT;
2278 static unsigned long lock_file_timeout_ms = ULONG_MAX;
a16eb6b1
DS
2279 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
2280 struct stat st;
b6c3f8e1 2281 char *cmd;
ec5d9d68 2282 int minute = get_random_minute();
2afe7e35 2283
b6c3f8e1 2284 get_schedule_cmd("launchctl", NULL, &cmd);
3797a0a7 2285 preamble = "<?xml version=\"1.0\"?>\n"
2afe7e35
DS
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"
4f555195 2294 "%s" /* For extra config parameters. */
2afe7e35 2295 "<string>for-each-repo</string>\n"
c75662bf 2296 "<string>--keep-going</string>\n"
2afe7e35
DS
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";
4f555195
DS
2304 strbuf_addf(&plist, preamble, name, exec_path, exec_path,
2305 get_extra_launchctl_strings(), frequency);
2afe7e35
DS
2306
2307 switch (schedule) {
2308 case SCHEDULE_HOURLY:
2309 repeat = "<dict>\n"
2310 "<key>Hour</key><integer>%d</integer>\n"
ec5d9d68 2311 "<key>Minute</key><integer>%d</integer>\n"
2afe7e35
DS
2312 "</dict>\n";
2313 for (i = 1; i <= 23; i++)
ec5d9d68 2314 strbuf_addf(&plist, repeat, i, minute);
2afe7e35
DS
2315 break;
2316
2317 case SCHEDULE_DAILY:
2318 repeat = "<dict>\n"
eb2d7beb 2319 "<key>Weekday</key><integer>%d</integer>\n"
2afe7e35 2320 "<key>Hour</key><integer>0</integer>\n"
ec5d9d68 2321 "<key>Minute</key><integer>%d</integer>\n"
2afe7e35
DS
2322 "</dict>\n";
2323 for (i = 1; i <= 6; i++)
ec5d9d68 2324 strbuf_addf(&plist, repeat, i, minute);
2afe7e35
DS
2325 break;
2326
2327 case SCHEDULE_WEEKLY:
ec5d9d68
DS
2328 strbuf_addf(&plist,
2329 "<dict>\n"
eb2d7beb 2330 "<key>Weekday</key><integer>0</integer>\n"
ec5d9d68
DS
2331 "<key>Hour</key><integer>0</integer>\n"
2332 "<key>Minute</key><integer>%d</integer>\n"
2333 "</dict>\n",
2334 minute);
2afe7e35
DS
2335 break;
2336
2337 default:
2338 /* unreachable */
2339 break;
2340 }
bb01122a
JS
2341 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
2342
1a99fe80 2343 if (safe_create_leading_directories(the_repository, filename))
bb01122a
JS
2344 die(_("failed to create directories for '%s'"), filename);
2345
2346 if ((long)lock_file_timeout_ms < 0 &&
2347 git_config_get_ulong("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);
2afe7e35 2353
a16eb6b1
DS
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 */
ed8794ef
JH
2369 launchctl_boot_plist(0, filename);
2370 if (launchctl_boot_plist(1, filename))
a16eb6b1
DS
2371 die(_("failed to bootstrap service %s"), filename);
2372 }
2afe7e35
DS
2373
2374 free(filename);
2375 free(name);
b6c3f8e1 2376 free(cmd);
bb01122a 2377 strbuf_release(&plist);
a16eb6b1 2378 strbuf_release(&plist2);
2afe7e35
DS
2379 return 0;
2380}
2381
eba1ba9d 2382static int launchctl_add_plists(void)
2afe7e35
DS
2383{
2384 const char *exec_path = git_exec_path();
2385
eba1ba9d
LH
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);
2afe7e35
DS
2389}
2390
316b3a22 2391static int launchctl_update_schedule(int run_maintenance, int fd UNUSED)
2afe7e35
DS
2392{
2393 if (run_maintenance)
eba1ba9d 2394 return launchctl_add_plists();
2afe7e35 2395 else
eba1ba9d
LH
2396 return launchctl_remove_plists();
2397}
2398
2399static int is_schtasks_available(void)
2400{
eba1ba9d 2401 int is_available;
b6c3f8e1 2402 if (get_schedule_cmd("schtasks", &is_available, NULL))
eba1ba9d
LH
2403 return is_available;
2404
2405#ifdef GIT_WINDOWS_NATIVE
2406 return 1;
2407#else
2408 return 0;
2409#endif
2afe7e35
DS
2410}
2411
3797a0a7
DS
2412static 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
eba1ba9d 2419static int schtasks_remove_task(enum schedule_priority schedule)
3797a0a7 2420{
b6c3f8e1 2421 char *cmd;
0e906739 2422 struct child_process child = CHILD_PROCESS_INIT;
3797a0a7
DS
2423 const char *frequency = get_frequency(schedule);
2424 char *name = schtasks_task_name(frequency);
2425
b6c3f8e1 2426 get_schedule_cmd("schtasks", NULL, &cmd);
0e906739
RS
2427 strvec_split(&child.args, cmd);
2428 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
3797a0a7 2429 free(name);
b6c3f8e1 2430 free(cmd);
0e906739
RS
2431
2432 return run_command(&child);
3797a0a7
DS
2433}
2434
eba1ba9d 2435static int schtasks_remove_tasks(void)
3797a0a7 2436{
eba1ba9d
LH
2437 return schtasks_remove_task(SCHEDULE_HOURLY) ||
2438 schtasks_remove_task(SCHEDULE_DAILY) ||
2439 schtasks_remove_task(SCHEDULE_WEEKLY);
3797a0a7
DS
2440}
2441
eba1ba9d 2442static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
3797a0a7 2443{
b6c3f8e1 2444 char *cmd;
3797a0a7
DS
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;
62a23998 2452 int minute = get_random_minute();
3797a0a7 2453
b6c3f8e1 2454 get_schedule_cmd("schtasks", NULL, &cmd);
eba1ba9d 2455
3797a0a7 2456 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
661624a4 2457 repo_get_common_dir(the_repository), frequency);
3797a0a7
DS
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,
62a23998 2473 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
3797a0a7
DS
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"
62a23998
DS
2482 "</Repetition>\n",
2483 minute);
3797a0a7
DS
2484 break;
2485
2486 case SCHEDULE_DAILY:
2487 fprintf(tfile->fp,
62a23998 2488 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
3797a0a7
DS
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"
62a23998
DS
2500 "</ScheduleByWeek>\n",
2501 minute);
3797a0a7
DS
2502 break;
2503
2504 case SCHEDULE_WEEKLY:
2505 fprintf(tfile->fp,
62a23998 2506 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
3797a0a7
DS
2507 "<Enabled>true</Enabled>\n"
2508 "<ScheduleByWeek>\n"
2509 "<DaysOfWeek>\n"
2510 "<Sunday />\n"
2511 "</DaysOfWeek>\n"
2512 "<WeeksInterval>1</WeeksInterval>\n"
62a23998
DS
2513 "</ScheduleByWeek>\n",
2514 minute);
3797a0a7
DS
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"
0050f8e4 2540 "<Command>\"%s\\headless-git.exe\"</Command>\n"
4f555195 2541 "<Arguments>--exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
3797a0a7
DS
2542 "</Exec>\n"
2543 "</Actions>\n"
2544 "</Task>\n";
4f555195
DS
2545 fprintf(tfile->fp, xml, exec_path, exec_path,
2546 get_extra_config_parameters(), frequency);
3797a0a7
DS
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);
b6c3f8e1 2561 free(cmd);
3797a0a7
DS
2562 return result;
2563}
2564
eba1ba9d 2565static int schtasks_schedule_tasks(void)
3797a0a7
DS
2566{
2567 const char *exec_path = git_exec_path();
2568
eba1ba9d
LH
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);
3797a0a7
DS
2572}
2573
316b3a22 2574static int schtasks_update_schedule(int run_maintenance, int fd UNUSED)
3797a0a7
DS
2575{
2576 if (run_maintenance)
eba1ba9d 2577 return schtasks_schedule_tasks();
3797a0a7 2578 else
eba1ba9d
LH
2579 return schtasks_remove_tasks();
2580}
2581
689a2aa7
DS
2582MAYBE_UNUSED
2583static int check_crontab_process(const char *cmd)
eba1ba9d 2584{
eba1ba9d
LH
2585 struct child_process child = CHILD_PROCESS_INIT;
2586
eba1ba9d
LH
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;
3797a0a7
DS
2599}
2600
689a2aa7
DS
2601static int is_crontab_available(void)
2602{
b6c3f8e1 2603 char *cmd;
689a2aa7 2604 int is_available;
b6c3f8e1 2605 int ret;
689a2aa7 2606
b6c3f8e1
PS
2607 if (get_schedule_cmd("crontab", &is_available, &cmd)) {
2608 ret = is_available;
2609 goto out;
2610 }
689a2aa7
DS
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 */
b6c3f8e1 2617 ret = 0;
689a2aa7 2618#else
b6c3f8e1 2619 ret = check_crontab_process(cmd);
689a2aa7 2620#endif
b6c3f8e1
PS
2621
2622out:
2623 free(cmd);
2624 return ret;
689a2aa7
DS
2625}
2626
2fec604f
DS
2627#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2628#define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2629
eba1ba9d 2630static int crontab_update_schedule(int run_maintenance, int fd)
2fec604f 2631{
b6c3f8e1 2632 char *cmd;
2fec604f
DS
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;
2fec604f 2638 struct strbuf line = STRBUF_INIT;
ee69e788 2639 struct tempfile *tmpedit = NULL;
9b433990 2640 int minute = get_random_minute();
2fec604f 2641
b6c3f8e1 2642 get_schedule_cmd("crontab", NULL, &cmd);
31345d55 2643 strvec_split(&crontab_list.args, cmd);
2fec604f
DS
2644 strvec_push(&crontab_list.args, "-l");
2645 crontab_list.in = -1;
31345d55 2646 crontab_list.out = dup(fd);
2fec604f
DS
2647 crontab_list.git_cmd = 0;
2648
b6c3f8e1
PS
2649 if (start_command(&crontab_list)) {
2650 result = error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2651 goto out;
2652 }
2fec604f
DS
2653
2654 /* Ignore exit code, as an empty crontab will return error. */
2655 finish_command(&crontab_list);
2656
ee69e788 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
2fec604f
DS
2668 /*
2669 * Read from the .lock file, filtering out the old
2670 * schedule while appending the new schedule.
2671 */
31345d55 2672 cron_list = fdopen(fd, "r");
2fec604f
DS
2673 rewind(cron_list);
2674
2fec604f
DS
2675 while (!strbuf_getline_lf(&line, cron_list)) {
2676 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2677 in_old_region = 1;
66dc0a36 2678 else if (in_old_region && !strcmp(line.buf, END_LINE))
2fec604f 2679 in_old_region = 0;
66dc0a36
2680 else if (!in_old_region)
2681 fprintf(cron_in, "%s\n", line.buf);
2fec604f 2682 }
c5d0b12a 2683 strbuf_release(&line);
2fec604f
DS
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,
4f555195
DS
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());
9b433990
DS
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");
2fec604f
DS
2702 strbuf_release(&line_format);
2703
2704 fprintf(cron_in, "\n%s\n", END_LINE);
2705 }
2706
2707 fflush(cron_in);
2fec604f 2708
ee69e788 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
31345d55 2718 if (finish_command(&crontab_edit))
2fec604f 2719 result = error(_("'crontab' died"));
31345d55
DS
2720 else
2721 fclose(cron_list);
b6c3f8e1 2722
ee69e788 2723out:
2724 delete_tempfile(&tmpedit);
b6c3f8e1 2725 free(cmd);
31345d55
DS
2726 return result;
2727}
2728
b681b191
LH
2729static 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
2746static int is_systemd_timer_available(void)
2747{
b681b191
LH
2748 int is_available;
2749
b6c3f8e1 2750 if (get_schedule_cmd("systemctl", &is_available, NULL))
b681b191
LH
2751 return is_available;
2752
2753 return real_is_systemd_timer_available();
2754}
2755
2756static char *xdg_config_home_systemd(const char *filename)
2757{
2758 return xdg_config_home_for("systemd/user", filename);
2759}
2760
daa78701 2761#define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
b681b191 2762
daa78701 2763static int systemd_timer_delete_timer_file(enum schedule_priority priority)
b681b191
LH
2764{
2765 int ret = 0;
daa78701
DS
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);
b681b191 2769
b681b191
LH
2770 if (unlink(filename) && !is_missing_file_error(errno))
2771 ret = error_errno(_("failed to delete '%s'"), filename);
2772
2773 free(filename);
daa78701 2774 free(local_timer_name);
b681b191
LH
2775 return ret;
2776}
2777
daa78701 2778static int systemd_timer_delete_service_template(void)
b681b191 2779{
daa78701
DS
2780 int ret = 0;
2781 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2782 char *filename = xdg_config_home_systemd(local_service_name);
b681b191
LH
2783 if (unlink(filename) && !is_missing_file_error(errno))
2784 ret = error_errno(_("failed to delete '%s'"), filename);
2785
2786 free(filename);
daa78701 2787 free(local_service_name);
b681b191 2788 return ret;
b681b191
LH
2789}
2790
daa78701
DS
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 */
2796static int systemd_timer_write_timer_file(enum schedule_priority schedule,
2797 int minute)
b681b191 2798{
daa78701 2799 int res = -1;
b681b191
LH
2800 char *filename;
2801 FILE *file;
2802 const char *unit;
daa78701
DS
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);
b681b191 2808
1a99fe80 2809 if (safe_create_leading_directories(the_repository, filename)) {
b681b191
LH
2810 error(_("failed to create directories for '%s'"), filename);
2811 goto error;
2812 }
2813 file = fopen_or_warn(filename, "w");
afe8a907 2814 if (!file)
b681b191
LH
2815 goto error;
2816
daa78701
DS
2817 switch (schedule) {
2818 case SCHEDULE_HOURLY:
c97ec037 2819 schedule_pattern = xstrfmt("*-*-* 1..23:%02d:00", minute);
daa78701
DS
2820 break;
2821
2822 case SCHEDULE_DAILY:
c97ec037 2823 schedule_pattern = xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute);
daa78701
DS
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
b681b191
LH
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"
daa78701 2842 "OnCalendar=%s\n"
b681b191
LH
2843 "Persistent=true\n"
2844 "\n"
2845 "[Install]\n"
2846 "WantedBy=timers.target\n";
daa78701 2847 if (fprintf(file, unit, schedule_pattern) < 0) {
b681b191
LH
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 }
daa78701
DS
2856
2857 res = 0;
2858
2859error:
2860 free(schedule_pattern);
2861 free(local_timer_name);
b681b191 2862 free(filename);
daa78701
DS
2863 return res;
2864}
b681b191 2865
daa78701
DS
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 */
2873static 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);
1a99fe80 2882 if (safe_create_leading_directories(the_repository, filename)) {
daa78701
DS
2883 error(_("failed to create directories for '%s'"), filename);
2884 goto error;
2885 }
b681b191 2886 file = fopen_or_warn(filename, "w");
afe8a907 2887 if (!file)
b681b191
LH
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"
4f555195 2899 "ExecStart=\"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
b681b191
LH
2900 "LockPersonality=yes\n"
2901 "MemoryDenyWriteExecute=yes\n"
2902 "NoNewPrivileges=yes\n"
5e8515e8 2903 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
b681b191
LH
2904 "RestrictNamespaces=yes\n"
2905 "RestrictRealtime=yes\n"
2906 "RestrictSUIDSGID=yes\n"
2907 "SystemCallArchitectures=native\n"
2908 "SystemCallFilter=@system-service\n";
4f555195 2909 if (fprintf(file, unit, exec_path, exec_path, get_extra_config_parameters()) < 0) {
b681b191
LH
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 }
daa78701
DS
2918
2919 res = 0;
b681b191
LH
2920
2921error:
daa78701 2922 free(local_service_name);
b681b191 2923 free(filename);
daa78701 2924 return res;
b681b191
LH
2925}
2926
f44d7d00 2927static int systemd_timer_enable_unit(int enable,
daa78701
DS
2928 enum schedule_priority schedule,
2929 int minute)
f44d7d00 2930{
b6c3f8e1 2931 char *cmd = NULL;
f44d7d00
DS
2932 struct child_process child = CHILD_PROCESS_INIT;
2933 const char *frequency = get_frequency(schedule);
b6c3f8e1 2934 int ret;
f44d7d00
DS
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 */
b6c3f8e1 2945 if (!enable) {
f44d7d00 2946 child.no_stderr = 1;
b6c3f8e1
PS
2947 } else if (systemd_timer_write_timer_file(schedule, minute)) {
2948 ret = -1;
2949 goto out;
2950 }
f44d7d00 2951
b6c3f8e1 2952 get_schedule_cmd("systemctl", NULL, &cmd);
f44d7d00
DS
2953 strvec_split(&child.args, cmd);
2954 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2955 "--now", NULL);
daa78701 2956 strvec_pushf(&child.args, SYSTEMD_UNIT_FORMAT, frequency, "timer");
f44d7d00 2957
b6c3f8e1
PS
2958 if (start_command(&child)) {
2959 ret = error(_("failed to start systemctl"));
2960 goto out;
2961 }
2962
2963 if (finish_command(&child)) {
f44d7d00
DS
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 */
b6c3f8e1
PS
2971 if (enable) {
2972 ret = error(_("failed to run systemctl"));
2973 goto out;
2974 }
2975 }
2976
2977 ret = 0;
2978
2979out:
2980 free(cmd);
2981 return ret;
f44d7d00
DS
2982}
2983
daa78701
DS
2984/*
2985 * A previous version of Git wrote the timer units as template files.
2986 * Clean these up, if they exist.
2987 */
2988static 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);
b681b191 2995
b681b191 2996 free(filename);
daa78701
DS
2997 free(timer_template_name);
2998}
2999
3000static 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
f44d7d00
DS
3011static int systemd_timer_delete_units(void)
3012{
daa78701
DS
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();
b681b191
LH
3019}
3020
3021static int systemd_timer_setup_units(void)
3022{
daa78701 3023 int minute = get_random_minute();
b681b191
LH
3024 const char *exec_path = git_exec_path();
3025
daa78701
DS
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
b681b191
LH
3031 if (ret)
3032 systemd_timer_delete_units();
daa78701
DS
3033 else
3034 systemd_timer_delete_stale_timer_templates();
3035
b681b191
LH
3036 return ret;
3037}
3038
316b3a22 3039static int systemd_timer_update_schedule(int run_maintenance, int fd UNUSED)
b681b191
LH
3040{
3041 if (run_maintenance)
3042 return systemd_timer_setup_units();
3043 else
3044 return systemd_timer_delete_units();
3045}
3046
eba1ba9d
LH
3047enum scheduler {
3048 SCHEDULER_INVALID = -1,
3049 SCHEDULER_AUTO,
3050 SCHEDULER_CRON,
b681b191 3051 SCHEDULER_SYSTEMD,
eba1ba9d
LH
3052 SCHEDULER_LAUNCHCTL,
3053 SCHEDULER_SCHTASKS,
3054};
3055
3056static 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 },
b681b191
LH
3066 [SCHEDULER_SYSTEMD] = {
3067 .name = "systemctl",
3068 .is_available = is_systemd_timer_available,
3069 .update_schedule = systemd_timer_update_schedule,
3070 },
eba1ba9d
LH
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
3083static 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;
b681b191
LH
3091 else if (!strcasecmp(value, "systemd") ||
3092 !strcasecmp(value, "systemd-timer"))
3093 return SCHEDULER_SYSTEMD;
eba1ba9d
LH
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
3102static 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
3115struct maintenance_start_opts {
3116 enum scheduler scheduler;
3117};
3118
3119static enum scheduler resolve_scheduler(enum scheduler scheduler)
3120{
3121 if (scheduler != SCHEDULER_AUTO)
3122 return scheduler;
3123
2afe7e35 3124#if defined(__APPLE__)
eba1ba9d
LH
3125 return SCHEDULER_LAUNCHCTL;
3126
3797a0a7 3127#elif defined(GIT_WINDOWS_NATIVE)
eba1ba9d
LH
3128 return SCHEDULER_SCHTASKS;
3129
b681b191
LH
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
2afe7e35 3138#else
eba1ba9d 3139 return SCHEDULER_CRON;
2afe7e35 3140#endif
eba1ba9d 3141}
31345d55 3142
eba1ba9d 3143static void validate_scheduler(enum scheduler scheduler)
31345d55 3144{
eba1ba9d
LH
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
3155static int update_background_schedule(const struct maintenance_start_opts *opts,
3156 int enable)
3157{
3158 unsigned int i;
3159 int result = 0;
31345d55 3160 struct lock_file lk;
a1e2581a 3161 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->sources->path);
31345d55 3162
eba1ba9d 3163 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
656ca920
PS
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"));
eba1ba9d 3173 free(lock_path);
656ca920 3174 return -1;
2fec604f 3175 }
2fec604f 3176
eba1ba9d
LH
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));
c5d0b12a 3183 }
31345d55 3184
eba1ba9d
LH
3185 if (enable)
3186 result = scheduler_fn[opts->scheduler].update_schedule(
3187 1, get_lock_file_fd(&lk));
31345d55 3188
2fec604f 3189 rollback_lock_file(&lk);
c5d0b12a 3190
c5d0b12a 3191 free(lock_path);
2fec604f
DS
3192 return result;
3193}
3194
eba1ba9d
LH
3195static const char *const builtin_maintenance_start_usage[] = {
3196 N_("git maintenance start [--scheduler=<scheduler>]"),
3197 NULL
3198};
3199
6f33d8e2
KN
3200static int maintenance_start(int argc, const char **argv, const char *prefix,
3201 struct repository *repo)
2fec604f 3202{
eba1ba9d
LH
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 };
0d330a53 3211 const char *register_args[] = { "register", NULL };
eba1ba9d
LH
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
69ecfcac
DS
3221 if (update_background_schedule(&opts, 1))
3222 die(_("failed to set up maintenance schedule"));
3223
6f33d8e2 3224 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL, repo))
2fec604f 3225 warning(_("failed to add repo to global config"));
69ecfcac 3226 return 0;
2fec604f
DS
3227}
3228
0d330a53 3229static const char *const builtin_maintenance_stop_usage[] = {
8b744921 3230 "git maintenance stop",
0d330a53
JK
3231 NULL
3232};
3233
6f33d8e2
KN
3234static int maintenance_stop(int argc, const char **argv, const char *prefix,
3235 struct repository *repo UNUSED)
2fec604f 3236{
0d330a53
JK
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);
eba1ba9d 3244 return update_background_schedule(NULL, 0);
2fec604f
DS
3245}
3246
03509544
SG
3247static const char * const builtin_maintenance_usage[] = {
3248 N_("git maintenance <subcommand> [<options>]"),
3249 NULL,
3250};
2057d750 3251
9b1cb507
JC
3252int cmd_maintenance(int argc,
3253 const char **argv,
3254 const char *prefix,
6f33d8e2 3255 struct repository *repo)
2057d750 3256{
03509544
SG
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);
6f33d8e2 3269 return fn(argc, argv, prefix, repo);
2057d750 3270}