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