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