2
* git gc builtin command
4
* Cleanup unreachable files and optimize the repository.
6
* Copyright (c) 2007 James Bowes
8
* Based on git-gc.sh, which is
10
* Copyright (c) 2006 Shawn O. Pearce
16
#include "environment.h"
18
#include "repository.h"
22
#include "parse-options.h"
23
#include "run-command.h"
27
#include "commit-graph.h"
29
#include "object-file.h"
30
#include "object-store-ll.h"
32
#include "pack-objects.h"
36
#include "promisor-remote.h"
45
#define FAILED_RUN "failed to run %s"
47
static const char * const builtin_gc_usage[] = {
48
N_("git gc [<options>]"),
52
static timestamp_t gc_log_expire_time;
54
static struct strvec reflog = STRVEC_INIT;
55
static struct strvec repack = STRVEC_INIT;
56
static struct strvec prune = STRVEC_INIT;
57
static struct strvec prune_worktrees = STRVEC_INIT;
58
static struct strvec rerere = STRVEC_INIT;
60
static struct tempfile *pidfile;
61
static struct lock_file log_lock;
63
static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
65
static void clean_pack_garbage(void)
68
for (i = 0; i < pack_garbage.nr; i++)
69
unlink_or_warn(pack_garbage.items[i].string);
70
string_list_clear(&pack_garbage, 0);
73
static void report_pack_garbage(unsigned seen_bits, const char *path)
75
if (seen_bits == PACKDIR_FILE_IDX)
76
string_list_append(&pack_garbage, path);
79
static void process_log_file(void)
82
if (fstat(get_lock_file_fd(&log_lock), &st)) {
84
* Perhaps there was an i/o error or another
85
* unlikely situation. Try to make a note of
86
* this in gc.log along with any existing
89
int saved_errno = errno;
90
fprintf(stderr, _("Failed to fstat %s: %s"),
91
get_lock_file_path(&log_lock),
92
strerror(saved_errno));
94
commit_lock_file(&log_lock);
96
} else if (st.st_size) {
97
/* There was some error recorded in the lock file */
98
commit_lock_file(&log_lock);
100
/* No error, clean up any old gc.log */
101
unlink(git_path("gc.log"));
102
rollback_lock_file(&log_lock);
106
static void process_log_file_at_exit(void)
112
static int gc_config_is_timestamp_never(const char *var)
117
if (!git_config_get_value(var, &value) && value) {
118
if (parse_expiry_date(value, &expire))
119
die(_("failed to parse '%s' value '%s'"), var, value);
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;
137
char *prune_worktrees_expire;
139
char *repack_filter_to;
140
unsigned long big_pack_threshold;
141
unsigned long max_delta_cache_size;
144
#define GC_CONFIG_INIT { \
146
.prune_reflogs = 1, \
148
.aggressive_depth = 50, \
149
.aggressive_window = 250, \
150
.gc_auto_threshold = 6700, \
151
.gc_auto_pack_limit = 50, \
153
.gc_log_expire = xstrdup("1.day.ago"), \
154
.prune_expire = xstrdup("2.weeks.ago"), \
155
.prune_worktrees_expire = xstrdup("3.months.ago"), \
156
.max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE, \
159
static void gc_config_release(struct gc_config *cfg)
161
free(cfg->gc_log_expire);
162
free(cfg->prune_expire);
163
free(cfg->prune_worktrees_expire);
164
free(cfg->repack_filter);
165
free(cfg->repack_filter_to);
168
static void gc_config(struct gc_config *cfg)
173
if (!git_config_get_value("gc.packrefs", &value)) {
174
if (value && !strcmp(value, "notbare"))
177
cfg->pack_refs = git_config_bool("gc.packrefs", value);
180
if (gc_config_is_timestamp_never("gc.reflogexpire") &&
181
gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
182
cfg->prune_reflogs = 0;
184
git_config_get_int("gc.aggressivewindow", &cfg->aggressive_window);
185
git_config_get_int("gc.aggressivedepth", &cfg->aggressive_depth);
186
git_config_get_int("gc.auto", &cfg->gc_auto_threshold);
187
git_config_get_int("gc.autopacklimit", &cfg->gc_auto_pack_limit);
188
git_config_get_bool("gc.autodetach", &cfg->detach_auto);
189
git_config_get_bool("gc.cruftpacks", &cfg->cruft_packs);
190
git_config_get_ulong("gc.maxcruftsize", &cfg->max_cruft_size);
192
if (!repo_config_get_expiry(the_repository, "gc.pruneexpire", &owned)) {
193
free(cfg->prune_expire);
194
cfg->prune_expire = owned;
197
if (!repo_config_get_expiry(the_repository, "gc.worktreepruneexpire", &owned)) {
198
free(cfg->prune_worktrees_expire);
199
cfg->prune_worktrees_expire = owned;
202
if (!repo_config_get_expiry(the_repository, "gc.logexpiry", &owned)) {
203
free(cfg->gc_log_expire);
204
cfg->gc_log_expire = owned;
207
git_config_get_ulong("gc.bigpackthreshold", &cfg->big_pack_threshold);
208
git_config_get_ulong("pack.deltacachesize", &cfg->max_delta_cache_size);
210
if (!git_config_get_string("gc.repackfilter", &owned)) {
211
free(cfg->repack_filter);
212
cfg->repack_filter = owned;
215
if (!git_config_get_string("gc.repackfilterto", &owned)) {
216
free(cfg->repack_filter_to);
217
cfg->repack_filter_to = owned;
220
git_config(git_default_config, NULL);
223
enum schedule_priority {
230
static enum schedule_priority parse_schedule(const char *value)
233
return SCHEDULE_NONE;
234
if (!strcasecmp(value, "hourly"))
235
return SCHEDULE_HOURLY;
236
if (!strcasecmp(value, "daily"))
237
return SCHEDULE_DAILY;
238
if (!strcasecmp(value, "weekly"))
239
return SCHEDULE_WEEKLY;
240
return SCHEDULE_NONE;
243
struct maintenance_run_opts {
247
enum schedule_priority schedule;
249
#define MAINTENANCE_RUN_OPTS_INIT { \
253
static int pack_refs_condition(UNUSED struct gc_config *cfg)
256
* The auto-repacking logic for refs is handled by the ref backends and
257
* exposed via `git pack-refs --auto`. We thus always return truish
258
* here and let the backend decide for us.
263
static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts,
264
UNUSED struct gc_config *cfg)
266
struct child_process cmd = CHILD_PROCESS_INIT;
269
strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
271
strvec_push(&cmd.args, "--auto");
273
return run_command(&cmd);
276
static int too_many_loose_objects(struct gc_config *cfg)
279
* Quickly check if a "gc" is needed, by estimating how
280
* many loose objects there are. Because SHA-1 is evenly
281
* distributed, we can check only one and get a reasonable
289
const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
291
dir = opendir(git_path("objects/17"));
295
auto_threshold = DIV_ROUND_UP(cfg->gc_auto_threshold, 256);
296
while ((ent = readdir(dir)) != NULL) {
297
if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
298
ent->d_name[hexsz_loose] != '\0')
300
if (++num_loose > auto_threshold) {
309
static struct packed_git *find_base_packs(struct string_list *packs,
312
struct packed_git *p, *base = NULL;
314
for (p = get_all_packs(the_repository); p; p = p->next) {
315
if (!p->pack_local || p->is_cruft)
318
if (p->pack_size >= limit)
319
string_list_append(packs, p->pack_name);
320
} else if (!base || base->pack_size < p->pack_size) {
326
string_list_append(packs, base->pack_name);
331
static int too_many_packs(struct gc_config *cfg)
333
struct packed_git *p;
336
if (cfg->gc_auto_pack_limit <= 0)
339
for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
345
* Perhaps check the size of the pack and count only
346
* very small ones here?
350
return cfg->gc_auto_pack_limit < cnt;
353
static uint64_t total_ram(void)
355
#if defined(HAVE_SYSINFO)
360
#elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
361
int64_t physical_memory;
366
# if defined(HW_MEMSIZE)
371
length = sizeof(int64_t);
372
if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
373
return physical_memory;
374
#elif defined(GIT_WINDOWS_NATIVE)
375
MEMORYSTATUSEX memInfo;
377
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
378
if (GlobalMemoryStatusEx(&memInfo))
379
return memInfo.ullTotalPhys;
384
static uint64_t estimate_repack_memory(struct gc_config *cfg,
385
struct packed_git *pack)
387
unsigned long nr_objects = repo_approximate_object_count(the_repository);
388
size_t os_cache, heap;
390
if (!pack || !nr_objects)
394
* First we have to scan through at least one pack.
395
* Assume enough room in OS file cache to keep the entire pack
396
* or we may accidentally evict data of other processes from
399
os_cache = pack->pack_size + pack->index_size;
400
/* then pack-objects needs lots more for book keeping */
401
heap = sizeof(struct object_entry) * nr_objects;
403
* internal rev-list --all --objects takes up some memory too,
404
* let's say half of it is for blobs
406
heap += sizeof(struct blob) * nr_objects / 2;
408
* and the other half is for trees (commits and tags are
409
* usually insignificant)
411
heap += sizeof(struct tree) * nr_objects / 2;
412
/* and then obj_hash[], underestimated in fact */
413
heap += sizeof(struct object *) * nr_objects;
414
/* revindex is used also */
415
heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
417
* read_sha1_file() (either at delta calculation phase, or
418
* writing phase) also fills up the delta base cache
420
heap += delta_base_cache_limit;
421
/* and of course pack-objects has its own delta cache */
422
heap += cfg->max_delta_cache_size;
424
return os_cache + heap;
427
static int keep_one_pack(struct string_list_item *item, void *data UNUSED)
429
strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
433
static void add_repack_all_option(struct gc_config *cfg,
434
struct string_list *keep_pack)
436
if (cfg->prune_expire && !strcmp(cfg->prune_expire, "now"))
437
strvec_push(&repack, "-a");
438
else if (cfg->cruft_packs) {
439
strvec_push(&repack, "--cruft");
440
if (cfg->prune_expire)
441
strvec_pushf(&repack, "--cruft-expiration=%s", cfg->prune_expire);
442
if (cfg->max_cruft_size)
443
strvec_pushf(&repack, "--max-cruft-size=%lu",
444
cfg->max_cruft_size);
446
strvec_push(&repack, "-A");
447
if (cfg->prune_expire)
448
strvec_pushf(&repack, "--unpack-unreachable=%s", cfg->prune_expire);
452
for_each_string_list(keep_pack, keep_one_pack, NULL);
454
if (cfg->repack_filter && *cfg->repack_filter)
455
strvec_pushf(&repack, "--filter=%s", cfg->repack_filter);
456
if (cfg->repack_filter_to && *cfg->repack_filter_to)
457
strvec_pushf(&repack, "--filter-to=%s", cfg->repack_filter_to);
460
static void add_repack_incremental_option(void)
462
strvec_push(&repack, "--no-write-bitmap-index");
465
static int need_to_gc(struct gc_config *cfg)
468
* Setting gc.auto to 0 or negative can disable the
471
if (cfg->gc_auto_threshold <= 0)
475
* If there are too many loose objects, but not too many
476
* packs, we run "repack -d -l". If there are too many packs,
477
* we run "repack -A -d -l". Otherwise we tell the caller
480
if (too_many_packs(cfg)) {
481
struct string_list keep_pack = STRING_LIST_INIT_NODUP;
483
if (cfg->big_pack_threshold) {
484
find_base_packs(&keep_pack, cfg->big_pack_threshold);
485
if (keep_pack.nr >= cfg->gc_auto_pack_limit) {
486
cfg->big_pack_threshold = 0;
487
string_list_clear(&keep_pack, 0);
488
find_base_packs(&keep_pack, 0);
491
struct packed_git *p = find_base_packs(&keep_pack, 0);
492
uint64_t mem_have, mem_want;
494
mem_have = total_ram();
495
mem_want = estimate_repack_memory(cfg, p);
498
* Only allow 1/2 of memory for pack-objects, leave
499
* the rest for the OS and other processes in the
502
if (!mem_have || mem_want < mem_have / 2)
503
string_list_clear(&keep_pack, 0);
506
add_repack_all_option(cfg, &keep_pack);
507
string_list_clear(&keep_pack, 0);
508
} else if (too_many_loose_objects(cfg))
509
add_repack_incremental_option();
513
if (run_hooks(the_repository, "pre-auto-gc"))
518
/* return NULL on success, else hostname running the gc */
519
static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
521
struct lock_file lock = LOCK_INIT;
522
char my_host[HOST_NAME_MAX + 1];
523
struct strbuf sb = STRBUF_INIT;
530
if (is_tempfile_active(pidfile))
534
if (xgethostname(my_host, sizeof(my_host)))
535
xsnprintf(my_host, sizeof(my_host), "unknown");
537
pidfile_path = git_pathdup("gc.pid");
538
fd = hold_lock_file_for_update(&lock, pidfile_path,
541
static char locking_host[HOST_NAME_MAX + 1];
542
static char *scan_fmt;
546
scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
547
fp = fopen(pidfile_path, "r");
548
memset(locking_host, 0, sizeof(locking_host));
551
!fstat(fileno(fp), &st) &&
553
* 12 hour limit is very generous as gc should
554
* never take that long. On the other hand we
555
* don't really need a strict limit here,
556
* running gc --auto one day late is not a big
557
* problem. --force can be used in manual gc
558
* after the user verifies that no gc is
561
time(NULL) - st.st_mtime <= 12 * 3600 &&
562
fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
563
/* be gentle to concurrent "gc" on remote hosts */
564
(strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
569
rollback_lock_file(&lock);
576
strbuf_addf(&sb, "%"PRIuMAX" %s",
577
(uintmax_t) getpid(), my_host);
578
write_in_full(fd, sb.buf, sb.len);
580
commit_lock_file(&lock);
581
pidfile = register_tempfile(pidfile_path);
587
* Returns 0 if there was no previous error and gc can proceed, 1 if
588
* gc should not proceed due to an error in the last run. Prints a
589
* message and returns with a non-[01] status code if an error occurred
590
* while reading gc.log
592
static int report_last_gc_error(void)
594
struct strbuf sb = STRBUF_INIT;
598
char *gc_log_path = git_pathdup("gc.log");
600
if (stat(gc_log_path, &st)) {
604
ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
608
if (st.st_mtime < gc_log_expire_time)
611
len = strbuf_read_file(&sb, gc_log_path, 0);
613
ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
616
* A previous gc failed. Report the error, and don't
617
* bother with an automatic gc run since it is likely
618
* to fail in the same way.
620
warning(_("The last gc run reported the following. "
621
"Please correct the root cause\n"
623
"Automatic cleanup will not be performed "
624
"until the file is removed.\n\n"
626
gc_log_path, sb.buf);
635
static void gc_before_repack(struct maintenance_run_opts *opts,
636
struct gc_config *cfg)
639
* We may be called twice, as both the pre- and
640
* post-daemonized phases will call us, but running these
641
* commands more than once is pointless and wasteful.
647
if (cfg->pack_refs && maintenance_task_pack_refs(opts, cfg))
648
die(FAILED_RUN, "pack-refs");
650
if (cfg->prune_reflogs) {
651
struct child_process cmd = CHILD_PROCESS_INIT;
654
strvec_pushv(&cmd.args, reflog.v);
655
if (run_command(&cmd))
656
die(FAILED_RUN, reflog.v[0]);
660
int cmd_gc(int argc, const char **argv, const char *prefix)
668
int keep_largest_pack = -1;
670
struct child_process rerere_cmd = CHILD_PROCESS_INIT;
671
struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
672
struct gc_config cfg = GC_CONFIG_INIT;
673
const char *prune_expire_sentinel = "sentinel";
674
const char *prune_expire_arg = prune_expire_sentinel;
677
struct option builtin_gc_options[] = {
678
OPT__QUIET(&quiet, N_("suppress progress reporting")),
679
{ OPTION_STRING, 0, "prune", &prune_expire_arg, N_("date"),
680
N_("prune unreferenced objects"),
681
PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire_arg },
682
OPT_BOOL(0, "cruft", &cfg.cruft_packs, N_("pack unreferenced objects separately")),
683
OPT_MAGNITUDE(0, "max-cruft-size", &cfg.max_cruft_size,
684
N_("with --cruft, limit the size of new cruft packs")),
685
OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
686
OPT_BOOL_F(0, "auto", &opts.auto_flag, N_("enable auto-gc mode"),
687
PARSE_OPT_NOCOMPLETE),
688
OPT_BOOL(0, "detach", &opts.detach,
689
N_("perform garbage collection in the background")),
690
OPT_BOOL_F(0, "force", &force,
691
N_("force running gc even if there may be another gc running"),
692
PARSE_OPT_NOCOMPLETE),
693
OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
694
N_("repack all other packs except the largest pack")),
698
if (argc == 2 && !strcmp(argv[1], "-h"))
699
usage_with_options(builtin_gc_usage, builtin_gc_options);
701
strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
702
strvec_pushl(&repack, "repack", "-d", "-l", NULL);
703
strvec_pushl(&prune, "prune", "--expire", NULL);
704
strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
705
strvec_pushl(&rerere, "rerere", "gc", NULL);
709
if (parse_expiry_date(cfg.gc_log_expire, &gc_log_expire_time))
710
die(_("failed to parse gc.logExpiry value %s"), cfg.gc_log_expire);
712
if (cfg.pack_refs < 0)
713
cfg.pack_refs = !is_bare_repository();
715
argc = parse_options(argc, argv, prefix, builtin_gc_options,
716
builtin_gc_usage, 0);
718
usage_with_options(builtin_gc_usage, builtin_gc_options);
720
if (prune_expire_arg != prune_expire_sentinel) {
721
free(cfg.prune_expire);
722
cfg.prune_expire = xstrdup_or_null(prune_expire_arg);
724
if (cfg.prune_expire && parse_expiry_date(cfg.prune_expire, &dummy))
725
die(_("failed to parse prune expiry value %s"), cfg.prune_expire);
728
strvec_push(&repack, "-f");
729
if (cfg.aggressive_depth > 0)
730
strvec_pushf(&repack, "--depth=%d", cfg.aggressive_depth);
731
if (cfg.aggressive_window > 0)
732
strvec_pushf(&repack, "--window=%d", cfg.aggressive_window);
735
strvec_push(&repack, "-q");
737
if (opts.auto_flag) {
738
if (cfg.detach_auto && opts.detach < 0)
742
* Auto-gc should be least intrusive as possible.
744
if (!need_to_gc(&cfg)) {
751
fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
753
fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
754
fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
757
struct string_list keep_pack = STRING_LIST_INIT_NODUP;
759
if (keep_largest_pack != -1) {
760
if (keep_largest_pack)
761
find_base_packs(&keep_pack, 0);
762
} else if (cfg.big_pack_threshold) {
763
find_base_packs(&keep_pack, cfg.big_pack_threshold);
766
add_repack_all_option(&cfg, &keep_pack);
767
string_list_clear(&keep_pack, 0);
770
if (opts.detach > 0) {
771
ret = report_last_gc_error();
773
/* Last gc --auto failed. Skip this one. */
778
/* an I/O error occurred, already reported */
782
if (lock_repo_for_gc(force, &pid)) {
787
gc_before_repack(&opts, &cfg); /* dies on failure */
788
delete_tempfile(&pidfile);
791
* failure to daemonize is ok, we'll continue
794
daemonized = !daemonize();
797
name = lock_repo_for_gc(force, &pid);
799
if (opts.auto_flag) {
801
goto out; /* be quiet on --auto */
804
die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
805
name, (uintmax_t)pid);
809
hold_lock_file_for_update(&log_lock,
812
dup2(get_lock_file_fd(&log_lock), 2);
813
atexit(process_log_file_at_exit);
816
gc_before_repack(&opts, &cfg);
818
if (!repository_format_precious_objects) {
819
struct child_process repack_cmd = CHILD_PROCESS_INIT;
821
repack_cmd.git_cmd = 1;
822
repack_cmd.close_object_store = 1;
823
strvec_pushv(&repack_cmd.args, repack.v);
824
if (run_command(&repack_cmd))
825
die(FAILED_RUN, repack.v[0]);
827
if (cfg.prune_expire) {
828
struct child_process prune_cmd = CHILD_PROCESS_INIT;
830
/* run `git prune` even if using cruft packs */
831
strvec_push(&prune, cfg.prune_expire);
833
strvec_push(&prune, "--no-progress");
834
if (repo_has_promisor_remote(the_repository))
836
"--exclude-promisor-objects");
837
prune_cmd.git_cmd = 1;
838
strvec_pushv(&prune_cmd.args, prune.v);
839
if (run_command(&prune_cmd))
840
die(FAILED_RUN, prune.v[0]);
844
if (cfg.prune_worktrees_expire) {
845
struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
847
strvec_push(&prune_worktrees, cfg.prune_worktrees_expire);
848
prune_worktrees_cmd.git_cmd = 1;
849
strvec_pushv(&prune_worktrees_cmd.args, prune_worktrees.v);
850
if (run_command(&prune_worktrees_cmd))
851
die(FAILED_RUN, prune_worktrees.v[0]);
854
rerere_cmd.git_cmd = 1;
855
strvec_pushv(&rerere_cmd.args, rerere.v);
856
if (run_command(&rerere_cmd))
857
die(FAILED_RUN, rerere.v[0]);
859
report_garbage = report_pack_garbage;
860
reprepare_packed_git(the_repository);
861
if (pack_garbage.nr > 0) {
862
close_object_store(the_repository->objects);
863
clean_pack_garbage();
866
if (the_repository->settings.gc_write_commit_graph == 1)
867
write_commit_graph_reachable(the_repository->objects->odb,
868
!quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
871
if (opts.auto_flag && too_many_loose_objects(&cfg))
872
warning(_("There are too many unreachable loose objects; "
873
"run 'git prune' to remove them."));
876
unlink(git_path("gc.log"));
879
gc_config_release(&cfg);
883
static const char *const builtin_maintenance_run_usage[] = {
884
N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
888
static int maintenance_opt_schedule(const struct option *opt, const char *arg,
891
enum schedule_priority *priority = opt->value;
894
die(_("--no-schedule is not allowed"));
896
*priority = parse_schedule(arg);
899
die(_("unrecognized --schedule argument '%s'"), arg);
904
/* Remember to update object flag allocation in object.h */
908
int num_not_in_graph;
912
static int dfs_on_ref(const char *refname UNUSED,
913
const char *referent UNUSED,
914
const struct object_id *oid,
918
struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
920
struct object_id peeled;
921
struct commit_list *stack = NULL;
922
struct commit *commit;
924
if (!peel_iterated_oid(the_repository, oid, &peeled))
926
if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
929
commit = lookup_commit(the_repository, oid);
932
if (repo_parse_commit(the_repository, commit) ||
933
commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
936
data->num_not_in_graph++;
938
if (data->num_not_in_graph >= data->limit)
941
commit_list_append(commit, &stack);
943
while (!result && stack) {
944
struct commit_list *parent;
946
commit = pop_commit(&stack);
948
for (parent = commit->parents; parent; parent = parent->next) {
949
if (repo_parse_commit(the_repository, parent->item) ||
950
commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
951
parent->item->object.flags & SEEN)
954
parent->item->object.flags |= SEEN;
955
data->num_not_in_graph++;
957
if (data->num_not_in_graph >= data->limit) {
962
commit_list_append(parent->item, &stack);
966
free_commit_list(stack);
970
static int should_write_commit_graph(struct gc_config *cfg)
973
struct cg_auto_data data;
975
data.num_not_in_graph = 0;
977
git_config_get_int("maintenance.commit-graph.auto",
985
result = refs_for_each_ref(get_main_ref_store(the_repository),
988
repo_clear_commit_marks(the_repository, SEEN);
993
static int run_write_commit_graph(struct maintenance_run_opts *opts)
995
struct child_process child = CHILD_PROCESS_INIT;
997
child.git_cmd = child.close_object_store = 1;
998
strvec_pushl(&child.args, "commit-graph", "write",
999
"--split", "--reachable", NULL);
1002
strvec_push(&child.args, "--no-progress");
1004
return !!run_command(&child);
1007
static int maintenance_task_commit_graph(struct maintenance_run_opts *opts,
1008
struct gc_config *cfg)
1010
prepare_repo_settings(the_repository);
1011
if (!the_repository->settings.core_commit_graph)
1014
if (run_write_commit_graph(opts)) {
1015
error(_("failed to write commit-graph"));
1022
static int fetch_remote(struct remote *remote, void *cbdata)
1024
struct maintenance_run_opts *opts = cbdata;
1025
struct child_process child = CHILD_PROCESS_INIT;
1027
if (remote->skip_default_update)
1031
strvec_pushl(&child.args, "fetch", remote->name,
1032
"--prefetch", "--prune", "--no-tags",
1033
"--no-write-fetch-head", "--recurse-submodules=no",
1037
strvec_push(&child.args, "--quiet");
1039
return !!run_command(&child);
1042
static int maintenance_task_prefetch(struct maintenance_run_opts *opts,
1043
struct gc_config *cfg)
1045
if (for_each_remote(fetch_remote, opts)) {
1046
error(_("failed to prefetch remotes"));
1053
static int maintenance_task_gc(struct maintenance_run_opts *opts,
1054
struct gc_config *cfg)
1056
struct child_process child = CHILD_PROCESS_INIT;
1058
child.git_cmd = child.close_object_store = 1;
1059
strvec_push(&child.args, "gc");
1061
if (opts->auto_flag)
1062
strvec_push(&child.args, "--auto");
1064
strvec_push(&child.args, "--quiet");
1066
strvec_push(&child.args, "--no-quiet");
1067
strvec_push(&child.args, "--no-detach");
1069
return run_command(&child);
1072
static int prune_packed(struct maintenance_run_opts *opts)
1074
struct child_process child = CHILD_PROCESS_INIT;
1077
strvec_push(&child.args, "prune-packed");
1080
strvec_push(&child.args, "--quiet");
1082
return !!run_command(&child);
1085
struct write_loose_object_data {
1091
static int loose_object_auto_limit = 100;
1093
static int loose_object_count(const struct object_id *oid UNUSED,
1094
const char *path UNUSED,
1097
int *count = (int*)data;
1098
if (++(*count) >= loose_object_auto_limit)
1103
static int loose_object_auto_condition(struct gc_config *cfg)
1107
git_config_get_int("maintenance.loose-objects.auto",
1108
&loose_object_auto_limit);
1110
if (!loose_object_auto_limit)
1112
if (loose_object_auto_limit < 0)
1115
return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
1117
NULL, NULL, &count);
1120
static int bail_on_loose(const struct object_id *oid UNUSED,
1121
const char *path UNUSED,
1127
static int write_loose_object_to_stdin(const struct object_id *oid,
1128
const char *path UNUSED,
1131
struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1133
fprintf(d->in, "%s\n", oid_to_hex(oid));
1135
return ++(d->count) > d->batch_size;
1138
static int pack_loose(struct maintenance_run_opts *opts)
1140
struct repository *r = the_repository;
1142
struct write_loose_object_data data;
1143
struct child_process pack_proc = CHILD_PROCESS_INIT;
1146
* Do not start pack-objects process
1147
* if there are no loose objects.
1149
if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1154
pack_proc.git_cmd = 1;
1156
strvec_push(&pack_proc.args, "pack-objects");
1158
strvec_push(&pack_proc.args, "--quiet");
1159
strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1164
* git-pack-objects(1) ends up writing the pack hash to stdout, which
1165
* we do not care for.
1169
if (start_command(&pack_proc)) {
1170
error(_("failed to start 'git pack-objects' process"));
1174
data.in = xfdopen(pack_proc.in, "w");
1176
data.batch_size = 50000;
1178
for_each_loose_file_in_objdir(r->objects->odb->path,
1179
write_loose_object_to_stdin,
1186
if (finish_command(&pack_proc)) {
1187
error(_("failed to finish 'git pack-objects' process"));
1194
static int maintenance_task_loose_objects(struct maintenance_run_opts *opts,
1195
struct gc_config *cfg)
1197
return prune_packed(opts) || pack_loose(opts);
1200
static int incremental_repack_auto_condition(struct gc_config *cfg)
1202
struct packed_git *p;
1203
int incremental_repack_auto_limit = 10;
1206
prepare_repo_settings(the_repository);
1207
if (!the_repository->settings.core_multi_pack_index)
1210
git_config_get_int("maintenance.incremental-repack.auto",
1211
&incremental_repack_auto_limit);
1213
if (!incremental_repack_auto_limit)
1215
if (incremental_repack_auto_limit < 0)
1218
for (p = get_packed_git(the_repository);
1219
count < incremental_repack_auto_limit && p;
1221
if (!p->multi_pack_index)
1225
return count >= incremental_repack_auto_limit;
1228
static int multi_pack_index_write(struct maintenance_run_opts *opts)
1230
struct child_process child = CHILD_PROCESS_INIT;
1233
strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1236
strvec_push(&child.args, "--no-progress");
1238
if (run_command(&child))
1239
return error(_("failed to write multi-pack-index"));
1244
static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1246
struct child_process child = CHILD_PROCESS_INIT;
1248
child.git_cmd = child.close_object_store = 1;
1249
strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1252
strvec_push(&child.args, "--no-progress");
1254
if (run_command(&child))
1255
return error(_("'git multi-pack-index expire' failed"));
1260
#define TWO_GIGABYTES (INT32_MAX)
1262
static off_t get_auto_pack_size(void)
1265
* The "auto" value is special: we optimize for
1266
* one large pack-file (i.e. from a clone) and
1267
* expect the rest to be small and they can be
1270
* The strategy we select here is to select a
1271
* size that is one more than the second largest
1272
* pack-file. This ensures that we will repack
1273
* at least two packs if there are three or more
1277
off_t second_largest_size = 0;
1279
struct packed_git *p;
1280
struct repository *r = the_repository;
1282
reprepare_packed_git(r);
1283
for (p = get_all_packs(r); p; p = p->next) {
1284
if (p->pack_size > max_size) {
1285
second_largest_size = max_size;
1286
max_size = p->pack_size;
1287
} else if (p->pack_size > second_largest_size)
1288
second_largest_size = p->pack_size;
1291
result_size = second_largest_size + 1;
1293
/* But limit ourselves to a batch size of 2g */
1294
if (result_size > TWO_GIGABYTES)
1295
result_size = TWO_GIGABYTES;
1300
static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1302
struct child_process child = CHILD_PROCESS_INIT;
1304
child.git_cmd = child.close_object_store = 1;
1305
strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1308
strvec_push(&child.args, "--no-progress");
1310
strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1311
(uintmax_t)get_auto_pack_size());
1313
if (run_command(&child))
1314
return error(_("'git multi-pack-index repack' failed"));
1319
static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts,
1320
struct gc_config *cfg)
1322
prepare_repo_settings(the_repository);
1323
if (!the_repository->settings.core_multi_pack_index) {
1324
warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1328
if (multi_pack_index_write(opts))
1330
if (multi_pack_index_expire(opts))
1332
if (multi_pack_index_repack(opts))
1337
typedef int maintenance_task_fn(struct maintenance_run_opts *opts,
1338
struct gc_config *cfg);
1341
* An auto condition function returns 1 if the task should run
1342
* and 0 if the task should NOT run. See needs_to_gc() for an
1345
typedef int maintenance_auto_fn(struct gc_config *cfg);
1347
struct maintenance_task {
1349
maintenance_task_fn *fn;
1350
maintenance_auto_fn *auto_condition;
1353
enum schedule_priority schedule;
1355
/* -1 if not selected. */
1359
enum maintenance_task_label {
1362
TASK_INCREMENTAL_REPACK,
1367
/* Leave as final value */
1371
static struct maintenance_task tasks[] = {
1374
maintenance_task_prefetch,
1376
[TASK_LOOSE_OBJECTS] = {
1378
maintenance_task_loose_objects,
1379
loose_object_auto_condition,
1381
[TASK_INCREMENTAL_REPACK] = {
1382
"incremental-repack",
1383
maintenance_task_incremental_repack,
1384
incremental_repack_auto_condition,
1388
maintenance_task_gc,
1392
[TASK_COMMIT_GRAPH] = {
1394
maintenance_task_commit_graph,
1395
should_write_commit_graph,
1397
[TASK_PACK_REFS] = {
1399
maintenance_task_pack_refs,
1400
pack_refs_condition,
1404
static int compare_tasks_by_selection(const void *a_, const void *b_)
1406
const struct maintenance_task *a = a_;
1407
const struct maintenance_task *b = b_;
1409
return b->selected_order - a->selected_order;
1412
static int maintenance_run_tasks(struct maintenance_run_opts *opts,
1413
struct gc_config *cfg)
1415
int i, found_selected = 0;
1417
struct lock_file lk;
1418
struct repository *r = the_repository;
1419
char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1421
if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1423
* Another maintenance command is running.
1425
* If --auto was provided, then it is likely due to a
1426
* recursive process stack. Do not report an error in
1429
if (!opts->auto_flag && !opts->quiet)
1430
warning(_("lock file '%s' exists, skipping maintenance"),
1437
/* Failure to daemonize is ok, we'll continue in foreground. */
1438
if (opts->detach > 0) {
1439
trace2_region_enter("maintenance", "detach", the_repository);
1441
trace2_region_leave("maintenance", "detach", the_repository);
1444
for (i = 0; !found_selected && i < TASK__COUNT; i++)
1445
found_selected = tasks[i].selected_order >= 0;
1448
QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1450
for (i = 0; i < TASK__COUNT; i++) {
1451
if (found_selected && tasks[i].selected_order < 0)
1454
if (!found_selected && !tasks[i].enabled)
1457
if (opts->auto_flag &&
1458
(!tasks[i].auto_condition ||
1459
!tasks[i].auto_condition(cfg)))
1462
if (opts->schedule && tasks[i].schedule < opts->schedule)
1465
trace2_region_enter("maintenance", tasks[i].name, r);
1466
if (tasks[i].fn(opts, cfg)) {
1467
error(_("task '%s' failed"), tasks[i].name);
1470
trace2_region_leave("maintenance", tasks[i].name, r);
1473
rollback_lock_file(&lk);
1477
static void initialize_maintenance_strategy(void)
1481
if (git_config_get_string("maintenance.strategy", &config_str))
1484
if (!strcasecmp(config_str, "incremental")) {
1485
tasks[TASK_GC].schedule = SCHEDULE_NONE;
1486
tasks[TASK_COMMIT_GRAPH].enabled = 1;
1487
tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1488
tasks[TASK_PREFETCH].enabled = 1;
1489
tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1490
tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1491
tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1492
tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1493
tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1494
tasks[TASK_PACK_REFS].enabled = 1;
1495
tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1499
static void initialize_task_config(int schedule)
1502
struct strbuf config_name = STRBUF_INIT;
1505
initialize_maintenance_strategy();
1507
for (i = 0; i < TASK__COUNT; i++) {
1511
strbuf_reset(&config_name);
1512
strbuf_addf(&config_name, "maintenance.%s.enabled",
1515
if (!git_config_get_bool(config_name.buf, &config_value))
1516
tasks[i].enabled = config_value;
1518
strbuf_reset(&config_name);
1519
strbuf_addf(&config_name, "maintenance.%s.schedule",
1522
if (!git_config_get_string(config_name.buf, &config_str)) {
1523
tasks[i].schedule = parse_schedule(config_str);
1528
strbuf_release(&config_name);
1531
static int task_option_parse(const struct option *opt UNUSED,
1532
const char *arg, int unset)
1534
int i, num_selected = 0;
1535
struct maintenance_task *task = NULL;
1537
BUG_ON_OPT_NEG(unset);
1539
for (i = 0; i < TASK__COUNT; i++) {
1540
if (tasks[i].selected_order >= 0)
1542
if (!strcasecmp(tasks[i].name, arg)) {
1548
error(_("'%s' is not a valid task"), arg);
1552
if (task->selected_order >= 0) {
1553
error(_("task '%s' cannot be selected multiple times"), arg);
1557
task->selected_order = num_selected + 1;
1562
static int maintenance_run(int argc, const char **argv, const char *prefix)
1565
struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
1566
struct gc_config cfg = GC_CONFIG_INIT;
1567
struct option builtin_maintenance_run_options[] = {
1568
OPT_BOOL(0, "auto", &opts.auto_flag,
1569
N_("run tasks based on the state of the repository")),
1570
OPT_BOOL(0, "detach", &opts.detach,
1571
N_("perform maintenance in the background")),
1572
OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1573
N_("run tasks based on frequency"),
1574
maintenance_opt_schedule),
1575
OPT_BOOL(0, "quiet", &opts.quiet,
1576
N_("do not report progress or other information over stderr")),
1577
OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1578
N_("run a specific task"),
1579
PARSE_OPT_NONEG, task_option_parse),
1584
opts.quiet = !isatty(2);
1586
for (i = 0; i < TASK__COUNT; i++)
1587
tasks[i].selected_order = -1;
1589
argc = parse_options(argc, argv, prefix,
1590
builtin_maintenance_run_options,
1591
builtin_maintenance_run_usage,
1592
PARSE_OPT_STOP_AT_NON_OPTION);
1594
if (opts.auto_flag && opts.schedule)
1595
die(_("use at most one of --auto and --schedule=<frequency>"));
1598
initialize_task_config(opts.schedule);
1601
usage_with_options(builtin_maintenance_run_usage,
1602
builtin_maintenance_run_options);
1604
ret = maintenance_run_tasks(&opts, &cfg);
1605
gc_config_release(&cfg);
1609
static char *get_maintpath(void)
1611
struct strbuf sb = STRBUF_INIT;
1612
const char *p = the_repository->worktree ?
1613
the_repository->worktree : the_repository->gitdir;
1615
strbuf_realpath(&sb, p, 1);
1616
return strbuf_detach(&sb, NULL);
1619
static char const * const builtin_maintenance_register_usage[] = {
1620
"git maintenance register [--config-file <path>]",
1624
static int maintenance_register(int argc, const char **argv, const char *prefix)
1626
char *config_file = NULL;
1627
struct option options[] = {
1628
OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1632
const char *key = "maintenance.repo";
1633
char *maintpath = get_maintpath();
1634
struct string_list_item *item;
1635
const struct string_list *list;
1637
argc = parse_options(argc, argv, prefix, options,
1638
builtin_maintenance_register_usage, 0);
1640
usage_with_options(builtin_maintenance_register_usage,
1643
/* Disable foreground maintenance */
1644
git_config_set("maintenance.auto", "false");
1646
/* Set maintenance strategy, if unset */
1647
if (git_config_get("maintenance.strategy"))
1648
git_config_set("maintenance.strategy", "incremental");
1650
if (!git_config_get_string_multi(key, &list)) {
1651
for_each_string_list_item(item, list) {
1652
if (!strcmp(maintpath, item->string)) {
1661
char *global_config_file = NULL;
1664
global_config_file = git_global_config();
1665
config_file = global_config_file;
1668
die(_("$HOME not set"));
1669
rc = git_config_set_multivar_in_file_gently(
1670
config_file, "maintenance.repo", maintpath,
1671
CONFIG_REGEX_NONE, NULL, 0);
1672
free(global_config_file);
1675
die(_("unable to add '%s' value of '%s'"),
1683
static char const * const builtin_maintenance_unregister_usage[] = {
1684
"git maintenance unregister [--config-file <path>] [--force]",
1688
static int maintenance_unregister(int argc, const char **argv, const char *prefix)
1691
char *config_file = NULL;
1692
struct option options[] = {
1693
OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1695
N_("return success even if repository was not registered"),
1696
PARSE_OPT_NOCOMPLETE),
1699
const char *key = "maintenance.repo";
1700
char *maintpath = get_maintpath();
1702
struct string_list_item *item;
1703
const struct string_list *list;
1704
struct config_set cs = { { 0 } };
1706
argc = parse_options(argc, argv, prefix, options,
1707
builtin_maintenance_unregister_usage, 0);
1709
usage_with_options(builtin_maintenance_unregister_usage,
1713
git_configset_init(&cs);
1714
git_configset_add_file(&cs, config_file);
1717
? git_configset_get_string_multi(&cs, key, &list)
1718
: git_config_get_string_multi(key, &list))) {
1719
for_each_string_list_item(item, list) {
1720
if (!strcmp(maintpath, item->string)) {
1729
char *global_config_file = NULL;
1732
global_config_file = git_global_config();
1733
config_file = global_config_file;
1736
die(_("$HOME not set"));
1737
rc = git_config_set_multivar_in_file_gently(
1738
config_file, key, NULL, maintpath, NULL,
1739
CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
1740
free(global_config_file);
1743
(!force || rc == CONFIG_NOTHING_SET))
1744
die(_("unable to unset '%s' value of '%s'"),
1746
} else if (!force) {
1747
die(_("repository '%s' is not registered"), maintpath);
1750
git_configset_clear(&cs);
1755
static const char *get_frequency(enum schedule_priority schedule)
1758
case SCHEDULE_HOURLY:
1760
case SCHEDULE_DAILY:
1762
case SCHEDULE_WEEKLY:
1765
BUG("invalid schedule %d", schedule);
1770
* get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1771
* to mock the schedulers that `git maintenance start` rely on.
1773
* For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1774
* list of colon-separated key/value pairs where each pair contains a scheduler
1775
* and its corresponding mock.
1777
* * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1778
* arguments unmodified.
1780
* * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1781
* In this case, the *cmd value is read as input.
1783
* * if the input value *cmd is the key of one of the comma-separated list
1784
* item, then *is_available is set to true and *cmd is modified and becomes
1787
* * if the input value *cmd isn’t the key of any of the comma-separated list
1788
* item, then *is_available is set to false.
1791
* GIT_TEST_MAINT_SCHEDULER not set
1792
* +-------+-------------------------------------------------+
1793
* | Input | Output |
1794
* | *cmd | return code | *cmd | *is_available |
1795
* +-------+-------------+-------------------+---------------+
1796
* | "foo" | false | "foo" (unchanged) | (unchanged) |
1797
* +-------+-------------+-------------------+---------------+
1799
* GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1800
* +-------+-------------------------------------------------+
1801
* | Input | Output |
1802
* | *cmd | return code | *cmd | *is_available |
1803
* +-------+-------------+-------------------+---------------+
1804
* | "foo" | true | "./mock.foo.sh" | true |
1805
* | "qux" | true | "qux" (unchanged) | false |
1806
* +-------+-------------+-------------------+---------------+
1808
static int get_schedule_cmd(const char **cmd, int *is_available)
1810
char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1811
struct string_list_item *item;
1812
struct string_list list = STRING_LIST_INIT_NODUP;
1820
string_list_split_in_place(&list, testing, ",", -1);
1821
for_each_string_list_item(item, &list) {
1822
struct string_list pair = STRING_LIST_INIT_NODUP;
1824
if (string_list_split_in_place(&pair, item->string, ":", 2) != 2)
1827
if (!strcmp(*cmd, pair.items[0].string)) {
1828
*cmd = pair.items[1].string;
1831
string_list_clear(&list, 0);
1837
string_list_clear(&list, 0);
1842
static int get_random_minute(void)
1844
/* Use a static value when under tests. */
1845
if (getenv("GIT_TEST_MAINT_SCHEDULER"))
1848
return git_rand() % 60;
1851
static int is_launchctl_available(void)
1853
const char *cmd = "launchctl";
1855
if (get_schedule_cmd(&cmd, &is_available))
1856
return is_available;
1865
static char *launchctl_service_name(const char *frequency)
1867
struct strbuf label = STRBUF_INIT;
1868
strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1869
return strbuf_detach(&label, NULL);
1872
static char *launchctl_service_filename(const char *name)
1875
struct strbuf filename = STRBUF_INIT;
1876
strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1878
expanded = interpolate_path(filename.buf, 1);
1880
die(_("failed to expand path '%s'"), filename.buf);
1882
strbuf_release(&filename);
1886
static char *launchctl_get_uid(void)
1888
return xstrfmt("gui/%d", getuid());
1891
static int launchctl_boot_plist(int enable, const char *filename)
1893
const char *cmd = "launchctl";
1895
struct child_process child = CHILD_PROCESS_INIT;
1896
char *uid = launchctl_get_uid();
1898
get_schedule_cmd(&cmd, NULL);
1899
strvec_split(&child.args, cmd);
1900
strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1903
child.no_stderr = 1;
1904
child.no_stdout = 1;
1906
if (start_command(&child))
1907
die(_("failed to start launchctl"));
1909
result = finish_command(&child);
1915
static int launchctl_remove_plist(enum schedule_priority schedule)
1917
const char *frequency = get_frequency(schedule);
1918
char *name = launchctl_service_name(frequency);
1919
char *filename = launchctl_service_filename(name);
1920
int result = launchctl_boot_plist(0, filename);
1927
static int launchctl_remove_plists(void)
1929
return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1930
launchctl_remove_plist(SCHEDULE_DAILY) ||
1931
launchctl_remove_plist(SCHEDULE_WEEKLY);
1934
static int launchctl_list_contains_plist(const char *name, const char *cmd)
1936
struct child_process child = CHILD_PROCESS_INIT;
1938
strvec_split(&child.args, cmd);
1939
strvec_pushl(&child.args, "list", name, NULL);
1941
child.no_stderr = 1;
1942
child.no_stdout = 1;
1944
if (start_command(&child))
1945
die(_("failed to start launchctl"));
1947
/* Returns failure if 'name' doesn't exist. */
1948
return !finish_command(&child);
1951
static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1954
const char *preamble, *repeat;
1955
const char *frequency = get_frequency(schedule);
1956
char *name = launchctl_service_name(frequency);
1957
char *filename = launchctl_service_filename(name);
1958
struct lock_file lk = LOCK_INIT;
1959
static unsigned long lock_file_timeout_ms = ULONG_MAX;
1960
struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
1962
const char *cmd = "launchctl";
1963
int minute = get_random_minute();
1965
get_schedule_cmd(&cmd, NULL);
1966
preamble = "<?xml version=\"1.0\"?>\n"
1967
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1968
"<plist version=\"1.0\">"
1970
"<key>Label</key><string>%s</string>\n"
1971
"<key>ProgramArguments</key>\n"
1973
"<string>%s/git</string>\n"
1974
"<string>--exec-path=%s</string>\n"
1975
"<string>for-each-repo</string>\n"
1976
"<string>--keep-going</string>\n"
1977
"<string>--config=maintenance.repo</string>\n"
1978
"<string>maintenance</string>\n"
1979
"<string>run</string>\n"
1980
"<string>--schedule=%s</string>\n"
1982
"<key>StartCalendarInterval</key>\n"
1984
strbuf_addf(&plist, preamble, name, exec_path, exec_path, frequency);
1987
case SCHEDULE_HOURLY:
1989
"<key>Hour</key><integer>%d</integer>\n"
1990
"<key>Minute</key><integer>%d</integer>\n"
1992
for (i = 1; i <= 23; i++)
1993
strbuf_addf(&plist, repeat, i, minute);
1996
case SCHEDULE_DAILY:
1998
"<key>Day</key><integer>%d</integer>\n"
1999
"<key>Hour</key><integer>0</integer>\n"
2000
"<key>Minute</key><integer>%d</integer>\n"
2002
for (i = 1; i <= 6; i++)
2003
strbuf_addf(&plist, repeat, i, minute);
2006
case SCHEDULE_WEEKLY:
2009
"<key>Day</key><integer>0</integer>\n"
2010
"<key>Hour</key><integer>0</integer>\n"
2011
"<key>Minute</key><integer>%d</integer>\n"
2020
strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
2022
if (safe_create_leading_directories(filename))
2023
die(_("failed to create directories for '%s'"), filename);
2025
if ((long)lock_file_timeout_ms < 0 &&
2026
git_config_get_ulong("gc.launchctlplistlocktimeoutms",
2027
&lock_file_timeout_ms))
2028
lock_file_timeout_ms = 150;
2030
fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
2031
lock_file_timeout_ms);
2034
* Does this file already exist? With the intended contents? Is it
2035
* registered already? Then it does not need to be re-registered.
2037
if (!stat(filename, &st) && st.st_size == plist.len &&
2038
strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
2039
!strbuf_cmp(&plist, &plist2) &&
2040
launchctl_list_contains_plist(name, cmd))
2041
rollback_lock_file(&lk);
2043
if (write_in_full(fd, plist.buf, plist.len) < 0 ||
2044
commit_lock_file(&lk))
2045
die_errno(_("could not write '%s'"), filename);
2047
/* bootout might fail if not already running, so ignore */
2048
launchctl_boot_plist(0, filename);
2049
if (launchctl_boot_plist(1, filename))
2050
die(_("failed to bootstrap service %s"), filename);
2055
strbuf_release(&plist);
2056
strbuf_release(&plist2);
2060
static int launchctl_add_plists(void)
2062
const char *exec_path = git_exec_path();
2064
return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
2065
launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
2066
launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
2069
static int launchctl_update_schedule(int run_maintenance, int fd UNUSED)
2071
if (run_maintenance)
2072
return launchctl_add_plists();
2074
return launchctl_remove_plists();
2077
static int is_schtasks_available(void)
2079
const char *cmd = "schtasks";
2081
if (get_schedule_cmd(&cmd, &is_available))
2082
return is_available;
2084
#ifdef GIT_WINDOWS_NATIVE
2091
static char *schtasks_task_name(const char *frequency)
2093
struct strbuf label = STRBUF_INIT;
2094
strbuf_addf(&label, "Git Maintenance (%s)", frequency);
2095
return strbuf_detach(&label, NULL);
2098
static int schtasks_remove_task(enum schedule_priority schedule)
2100
const char *cmd = "schtasks";
2101
struct child_process child = CHILD_PROCESS_INIT;
2102
const char *frequency = get_frequency(schedule);
2103
char *name = schtasks_task_name(frequency);
2105
get_schedule_cmd(&cmd, NULL);
2106
strvec_split(&child.args, cmd);
2107
strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
2110
return run_command(&child);
2113
static int schtasks_remove_tasks(void)
2115
return schtasks_remove_task(SCHEDULE_HOURLY) ||
2116
schtasks_remove_task(SCHEDULE_DAILY) ||
2117
schtasks_remove_task(SCHEDULE_WEEKLY);
2120
static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
2122
const char *cmd = "schtasks";
2124
struct child_process child = CHILD_PROCESS_INIT;
2126
struct tempfile *tfile;
2127
const char *frequency = get_frequency(schedule);
2128
char *name = schtasks_task_name(frequency);
2129
struct strbuf tfilename = STRBUF_INIT;
2130
int minute = get_random_minute();
2132
get_schedule_cmd(&cmd, NULL);
2134
strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
2135
get_git_common_dir(), frequency);
2136
tfile = xmks_tempfile(tfilename.buf);
2137
strbuf_release(&tfilename);
2139
if (!fdopen_tempfile(tfile, "w"))
2140
die(_("failed to create temp xml file"));
2142
xml = "<?xml version=\"1.0\" ?>\n"
2143
"<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2145
"<CalendarTrigger>\n";
2146
fputs(xml, tfile->fp);
2149
case SCHEDULE_HOURLY:
2151
"<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2152
"<Enabled>true</Enabled>\n"
2154
"<DaysInterval>1</DaysInterval>\n"
2155
"</ScheduleByDay>\n"
2157
"<Interval>PT1H</Interval>\n"
2158
"<Duration>PT23H</Duration>\n"
2159
"<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2164
case SCHEDULE_DAILY:
2166
"<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2167
"<Enabled>true</Enabled>\n"
2168
"<ScheduleByWeek>\n"
2177
"<WeeksInterval>1</WeeksInterval>\n"
2178
"</ScheduleByWeek>\n",
2182
case SCHEDULE_WEEKLY:
2184
"<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2185
"<Enabled>true</Enabled>\n"
2186
"<ScheduleByWeek>\n"
2190
"<WeeksInterval>1</WeeksInterval>\n"
2191
"</ScheduleByWeek>\n",
2199
xml = "</CalendarTrigger>\n"
2202
"<Principal id=\"Author\">\n"
2203
"<LogonType>InteractiveToken</LogonType>\n"
2204
"<RunLevel>LeastPrivilege</RunLevel>\n"
2208
"<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2209
"<Enabled>true</Enabled>\n"
2210
"<Hidden>true</Hidden>\n"
2211
"<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2212
"<WakeToRun>false</WakeToRun>\n"
2213
"<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2214
"<Priority>7</Priority>\n"
2216
"<Actions Context=\"Author\">\n"
2218
"<Command>\"%s\\headless-git.exe\"</Command>\n"
2219
"<Arguments>--exec-path=\"%s\" for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2223
fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
2224
strvec_split(&child.args, cmd);
2225
strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2226
get_tempfile_path(tfile), NULL);
2227
close_tempfile_gently(tfile);
2229
child.no_stdout = 1;
2230
child.no_stderr = 1;
2232
if (start_command(&child))
2233
die(_("failed to start schtasks"));
2234
result = finish_command(&child);
2236
delete_tempfile(&tfile);
2241
static int schtasks_schedule_tasks(void)
2243
const char *exec_path = git_exec_path();
2245
return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2246
schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2247
schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
2250
static int schtasks_update_schedule(int run_maintenance, int fd UNUSED)
2252
if (run_maintenance)
2253
return schtasks_schedule_tasks();
2255
return schtasks_remove_tasks();
2259
static int check_crontab_process(const char *cmd)
2261
struct child_process child = CHILD_PROCESS_INIT;
2263
strvec_split(&child.args, cmd);
2264
strvec_push(&child.args, "-l");
2266
child.no_stdout = 1;
2267
child.no_stderr = 1;
2268
child.silent_exec_failure = 1;
2270
if (start_command(&child))
2272
/* Ignore exit code, as an empty crontab will return error. */
2273
finish_command(&child);
2277
static int is_crontab_available(void)
2279
const char *cmd = "crontab";
2282
if (get_schedule_cmd(&cmd, &is_available))
2283
return is_available;
2287
* macOS has cron, but it requires special permissions and will
2288
* create a UI alert when attempting to run this command.
2292
return check_crontab_process(cmd);
2296
#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2297
#define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2299
static int crontab_update_schedule(int run_maintenance, int fd)
2301
const char *cmd = "crontab";
2303
int in_old_region = 0;
2304
struct child_process crontab_list = CHILD_PROCESS_INIT;
2305
struct child_process crontab_edit = CHILD_PROCESS_INIT;
2306
FILE *cron_list, *cron_in;
2307
struct strbuf line = STRBUF_INIT;
2308
struct tempfile *tmpedit = NULL;
2309
int minute = get_random_minute();
2311
get_schedule_cmd(&cmd, NULL);
2312
strvec_split(&crontab_list.args, cmd);
2313
strvec_push(&crontab_list.args, "-l");
2314
crontab_list.in = -1;
2315
crontab_list.out = dup(fd);
2316
crontab_list.git_cmd = 0;
2318
if (start_command(&crontab_list))
2319
return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2321
/* Ignore exit code, as an empty crontab will return error. */
2322
finish_command(&crontab_list);
2324
tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2326
result = error(_("failed to create crontab temporary file"));
2329
cron_in = fdopen_tempfile(tmpedit, "w");
2331
result = error(_("failed to open temporary file"));
2336
* Read from the .lock file, filtering out the old
2337
* schedule while appending the new schedule.
2339
cron_list = fdopen(fd, "r");
2342
while (!strbuf_getline_lf(&line, cron_list)) {
2343
if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2345
else if (in_old_region && !strcmp(line.buf, END_LINE))
2347
else if (!in_old_region)
2348
fprintf(cron_in, "%s\n", line.buf);
2350
strbuf_release(&line);
2352
if (run_maintenance) {
2353
struct strbuf line_format = STRBUF_INIT;
2354
const char *exec_path = git_exec_path();
2356
fprintf(cron_in, "%s\n", BEGIN_LINE);
2358
"# The following schedule was created by Git\n");
2359
fprintf(cron_in, "# Any edits made in this region might be\n");
2361
"# replaced in the future by a Git command.\n\n");
2363
strbuf_addf(&line_format,
2364
"%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%s\n",
2365
exec_path, exec_path);
2366
fprintf(cron_in, line_format.buf, minute, "1-23", "*", "hourly");
2367
fprintf(cron_in, line_format.buf, minute, "0", "1-6", "daily");
2368
fprintf(cron_in, line_format.buf, minute, "0", "0", "weekly");
2369
strbuf_release(&line_format);
2371
fprintf(cron_in, "\n%s\n", END_LINE);
2376
strvec_split(&crontab_edit.args, cmd);
2377
strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2378
crontab_edit.git_cmd = 0;
2380
if (start_command(&crontab_edit)) {
2381
result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2385
if (finish_command(&crontab_edit))
2386
result = error(_("'crontab' died"));
2390
delete_tempfile(&tmpedit);
2394
static int real_is_systemd_timer_available(void)
2396
struct child_process child = CHILD_PROCESS_INIT;
2398
strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2400
child.no_stdout = 1;
2401
child.no_stderr = 1;
2402
child.silent_exec_failure = 1;
2404
if (start_command(&child))
2406
if (finish_command(&child))
2411
static int is_systemd_timer_available(void)
2413
const char *cmd = "systemctl";
2416
if (get_schedule_cmd(&cmd, &is_available))
2417
return is_available;
2419
return real_is_systemd_timer_available();
2422
static char *xdg_config_home_systemd(const char *filename)
2424
return xdg_config_home_for("systemd/user", filename);
2427
#define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2429
static int systemd_timer_delete_timer_file(enum schedule_priority priority)
2432
const char *frequency = get_frequency(priority);
2433
char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2434
char *filename = xdg_config_home_systemd(local_timer_name);
2436
if (unlink(filename) && !is_missing_file_error(errno))
2437
ret = error_errno(_("failed to delete '%s'"), filename);
2440
free(local_timer_name);
2444
static int systemd_timer_delete_service_template(void)
2447
char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2448
char *filename = xdg_config_home_systemd(local_service_name);
2449
if (unlink(filename) && !is_missing_file_error(errno))
2450
ret = error_errno(_("failed to delete '%s'"), filename);
2453
free(local_service_name);
2458
* Write the schedule information into a git-maintenance@<schedule>.timer
2459
* file using a custom minute. This timer file cannot use the templating
2460
* system, so we generate a specific file for each.
2462
static int systemd_timer_write_timer_file(enum schedule_priority schedule,
2469
char *schedule_pattern = NULL;
2470
const char *frequency = get_frequency(schedule);
2471
char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2473
filename = xdg_config_home_systemd(local_timer_name);
2475
if (safe_create_leading_directories(filename)) {
2476
error(_("failed to create directories for '%s'"), filename);
2479
file = fopen_or_warn(filename, "w");
2484
case SCHEDULE_HOURLY:
2485
schedule_pattern = xstrfmt("*-*-* 1..23:%02d:00", minute);
2488
case SCHEDULE_DAILY:
2489
schedule_pattern = xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute);
2492
case SCHEDULE_WEEKLY:
2493
schedule_pattern = xstrfmt("Mon 0:%02d:00", minute);
2497
BUG("Unhandled schedule_priority");
2500
unit = "# This file was created and is maintained by Git.\n"
2501
"# Any edits made in this file might be replaced in the future\n"
2502
"# by a Git command.\n"
2505
"Description=Optimize Git repositories data\n"
2512
"WantedBy=timers.target\n";
2513
if (fprintf(file, unit, schedule_pattern) < 0) {
2514
error(_("failed to write to '%s'"), filename);
2518
if (fclose(file) == EOF) {
2519
error_errno(_("failed to flush '%s'"), filename);
2526
free(schedule_pattern);
2527
free(local_timer_name);
2533
* No matter the schedule, we use the same service and can make use of the
2534
* templating system. When installing git-maintenance@<schedule>.timer,
2535
* systemd will notice that git-maintenance@.service exists as a template
2536
* and will use this file and insert the <schedule> into the template at
2537
* the position of "%i".
2539
static int systemd_timer_write_service_template(const char *exec_path)
2545
char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2547
filename = xdg_config_home_systemd(local_service_name);
2548
if (safe_create_leading_directories(filename)) {
2549
error(_("failed to create directories for '%s'"), filename);
2552
file = fopen_or_warn(filename, "w");
2556
unit = "# This file was created and is maintained by Git.\n"
2557
"# Any edits made in this file might be replaced in the future\n"
2558
"# by a Git command.\n"
2561
"Description=Optimize Git repositories data\n"
2565
"ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
2566
"LockPersonality=yes\n"
2567
"MemoryDenyWriteExecute=yes\n"
2568
"NoNewPrivileges=yes\n"
2569
"RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
2570
"RestrictNamespaces=yes\n"
2571
"RestrictRealtime=yes\n"
2572
"RestrictSUIDSGID=yes\n"
2573
"SystemCallArchitectures=native\n"
2574
"SystemCallFilter=@system-service\n";
2575
if (fprintf(file, unit, exec_path, exec_path) < 0) {
2576
error(_("failed to write to '%s'"), filename);
2580
if (fclose(file) == EOF) {
2581
error_errno(_("failed to flush '%s'"), filename);
2588
free(local_service_name);
2593
static int systemd_timer_enable_unit(int enable,
2594
enum schedule_priority schedule,
2597
const char *cmd = "systemctl";
2598
struct child_process child = CHILD_PROCESS_INIT;
2599
const char *frequency = get_frequency(schedule);
2602
* Disabling the systemd unit while it is already disabled makes
2603
* systemctl print an error.
2604
* Let's ignore it since it means we already are in the expected state:
2605
* the unit is disabled.
2607
* On the other hand, enabling a systemd unit which is already enabled
2608
* produces no error.
2611
child.no_stderr = 1;
2612
else if (systemd_timer_write_timer_file(schedule, minute))
2615
get_schedule_cmd(&cmd, NULL);
2616
strvec_split(&child.args, cmd);
2617
strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2619
strvec_pushf(&child.args, SYSTEMD_UNIT_FORMAT, frequency, "timer");
2621
if (start_command(&child))
2622
return error(_("failed to start systemctl"));
2623
if (finish_command(&child))
2625
* Disabling an already disabled systemd unit makes
2627
* Let's ignore this failure.
2629
* Enabling an enabled systemd unit doesn't fail.
2632
return error(_("failed to run systemctl"));
2637
* A previous version of Git wrote the timer units as template files.
2638
* Clean these up, if they exist.
2640
static void systemd_timer_delete_stale_timer_templates(void)
2642
char *timer_template_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "timer");
2643
char *filename = xdg_config_home_systemd(timer_template_name);
2645
if (unlink(filename) && !is_missing_file_error(errno))
2646
warning(_("failed to delete '%s'"), filename);
2649
free(timer_template_name);
2652
static int systemd_timer_delete_unit_files(void)
2654
systemd_timer_delete_stale_timer_templates();
2656
/* Purposefully not short-circuited to make sure all are called. */
2657
return systemd_timer_delete_timer_file(SCHEDULE_HOURLY) |
2658
systemd_timer_delete_timer_file(SCHEDULE_DAILY) |
2659
systemd_timer_delete_timer_file(SCHEDULE_WEEKLY) |
2660
systemd_timer_delete_service_template();
2663
static int systemd_timer_delete_units(void)
2665
int minute = get_random_minute();
2666
/* Purposefully not short-circuited to make sure all are called. */
2667
return systemd_timer_enable_unit(0, SCHEDULE_HOURLY, minute) |
2668
systemd_timer_enable_unit(0, SCHEDULE_DAILY, minute) |
2669
systemd_timer_enable_unit(0, SCHEDULE_WEEKLY, minute) |
2670
systemd_timer_delete_unit_files();
2673
static int systemd_timer_setup_units(void)
2675
int minute = get_random_minute();
2676
const char *exec_path = git_exec_path();
2678
int ret = systemd_timer_write_service_template(exec_path) ||
2679
systemd_timer_enable_unit(1, SCHEDULE_HOURLY, minute) ||
2680
systemd_timer_enable_unit(1, SCHEDULE_DAILY, minute) ||
2681
systemd_timer_enable_unit(1, SCHEDULE_WEEKLY, minute);
2684
systemd_timer_delete_units();
2686
systemd_timer_delete_stale_timer_templates();
2691
static int systemd_timer_update_schedule(int run_maintenance, int fd UNUSED)
2693
if (run_maintenance)
2694
return systemd_timer_setup_units();
2696
return systemd_timer_delete_units();
2700
SCHEDULER_INVALID = -1,
2704
SCHEDULER_LAUNCHCTL,
2708
static const struct {
2710
int (*is_available)(void);
2711
int (*update_schedule)(int run_maintenance, int fd);
2713
[SCHEDULER_CRON] = {
2715
.is_available = is_crontab_available,
2716
.update_schedule = crontab_update_schedule,
2718
[SCHEDULER_SYSTEMD] = {
2719
.name = "systemctl",
2720
.is_available = is_systemd_timer_available,
2721
.update_schedule = systemd_timer_update_schedule,
2723
[SCHEDULER_LAUNCHCTL] = {
2724
.name = "launchctl",
2725
.is_available = is_launchctl_available,
2726
.update_schedule = launchctl_update_schedule,
2728
[SCHEDULER_SCHTASKS] = {
2730
.is_available = is_schtasks_available,
2731
.update_schedule = schtasks_update_schedule,
2735
static enum scheduler parse_scheduler(const char *value)
2738
return SCHEDULER_INVALID;
2739
else if (!strcasecmp(value, "auto"))
2740
return SCHEDULER_AUTO;
2741
else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2742
return SCHEDULER_CRON;
2743
else if (!strcasecmp(value, "systemd") ||
2744
!strcasecmp(value, "systemd-timer"))
2745
return SCHEDULER_SYSTEMD;
2746
else if (!strcasecmp(value, "launchctl"))
2747
return SCHEDULER_LAUNCHCTL;
2748
else if (!strcasecmp(value, "schtasks"))
2749
return SCHEDULER_SCHTASKS;
2751
return SCHEDULER_INVALID;
2754
static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2757
enum scheduler *scheduler = opt->value;
2759
BUG_ON_OPT_NEG(unset);
2761
*scheduler = parse_scheduler(arg);
2762
if (*scheduler == SCHEDULER_INVALID)
2763
return error(_("unrecognized --scheduler argument '%s'"), arg);
2767
struct maintenance_start_opts {
2768
enum scheduler scheduler;
2771
static enum scheduler resolve_scheduler(enum scheduler scheduler)
2773
if (scheduler != SCHEDULER_AUTO)
2776
#if defined(__APPLE__)
2777
return SCHEDULER_LAUNCHCTL;
2779
#elif defined(GIT_WINDOWS_NATIVE)
2780
return SCHEDULER_SCHTASKS;
2782
#elif defined(__linux__)
2783
if (is_systemd_timer_available())
2784
return SCHEDULER_SYSTEMD;
2785
else if (is_crontab_available())
2786
return SCHEDULER_CRON;
2788
die(_("neither systemd timers nor crontab are available"));
2791
return SCHEDULER_CRON;
2795
static void validate_scheduler(enum scheduler scheduler)
2797
if (scheduler == SCHEDULER_INVALID)
2798
BUG("invalid scheduler");
2799
if (scheduler == SCHEDULER_AUTO)
2800
BUG("resolve_scheduler should have been called before");
2802
if (!scheduler_fn[scheduler].is_available())
2803
die(_("%s scheduler is not available"),
2804
scheduler_fn[scheduler].name);
2807
static int update_background_schedule(const struct maintenance_start_opts *opts,
2812
struct lock_file lk;
2813
char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2815
if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2817
return error(_("another process is scheduling background maintenance"));
2820
for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2821
if (enable && opts->scheduler == i)
2823
if (!scheduler_fn[i].is_available())
2825
scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2829
result = scheduler_fn[opts->scheduler].update_schedule(
2830
1, get_lock_file_fd(&lk));
2832
rollback_lock_file(&lk);
2838
static const char *const builtin_maintenance_start_usage[] = {
2839
N_("git maintenance start [--scheduler=<scheduler>]"),
2843
static int maintenance_start(int argc, const char **argv, const char *prefix)
2845
struct maintenance_start_opts opts = { 0 };
2846
struct option options[] = {
2848
0, "scheduler", &opts.scheduler, N_("scheduler"),
2849
N_("scheduler to trigger git maintenance run"),
2850
PARSE_OPT_NONEG, maintenance_opt_scheduler),
2853
const char *register_args[] = { "register", NULL };
2855
argc = parse_options(argc, argv, prefix, options,
2856
builtin_maintenance_start_usage, 0);
2858
usage_with_options(builtin_maintenance_start_usage, options);
2860
opts.scheduler = resolve_scheduler(opts.scheduler);
2861
validate_scheduler(opts.scheduler);
2863
if (update_background_schedule(&opts, 1))
2864
die(_("failed to set up maintenance schedule"));
2866
if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL))
2867
warning(_("failed to add repo to global config"));
2871
static const char *const builtin_maintenance_stop_usage[] = {
2872
"git maintenance stop",
2876
static int maintenance_stop(int argc, const char **argv, const char *prefix)
2878
struct option options[] = {
2881
argc = parse_options(argc, argv, prefix, options,
2882
builtin_maintenance_stop_usage, 0);
2884
usage_with_options(builtin_maintenance_stop_usage, options);
2885
return update_background_schedule(NULL, 0);
2888
static const char * const builtin_maintenance_usage[] = {
2889
N_("git maintenance <subcommand> [<options>]"),
2893
int cmd_maintenance(int argc, const char **argv, const char *prefix)
2895
parse_opt_subcommand_fn *fn = NULL;
2896
struct option builtin_maintenance_options[] = {
2897
OPT_SUBCOMMAND("run", &fn, maintenance_run),
2898
OPT_SUBCOMMAND("start", &fn, maintenance_start),
2899
OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
2900
OPT_SUBCOMMAND("register", &fn, maintenance_register),
2901
OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
2905
argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
2906
builtin_maintenance_usage, 0);
2907
return fn(argc, argv, prefix);