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