From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:16:59
This is based on ds/maintenance-part-2, but with some local updates to
review feedback. It won't apply cleanly right now. This RFC is for early
feedback and not intended to make a new tracking branch until v2.
This RFC is intended to show how I hope to integrate true background
maintenance into Git. As opposed to my original RFC [1], this entirely
integrates with cron (through crontab [-e|-l]) to launch maintenance
commands in the background.
[1]
https://lore.kernel.org/git/pull.597.git.1585946894.gitgitgadget@gmail.com/
Some preliminary work is done to allow a new --scheduled option that
triggers enabled tasks only if they have not been run in some amount of
time. The timestamp of the previous run is stored in the
maintenance.<task>.lastRun config value while the interval is stored in the
maintenance.<task>.schedule config value.
A new for-each-repo builtin runs Git commands on every repo in a given list.
Currently, the list is stored as a config setting, allowing a new
maintenance.repos config list to store the repositories registered for
background maintenance. Others may want to add a --file=<file> option for
their own workflows, but I focused on making this as simple as possible for
now.
The updates to the git maintenance builtin include new register/unregister
subcommands and start/stop subcommands. The register subcommand initializes
the config while the start subcommand does everything register does plus
update the cron table. The unregister and stop commands reverse this
process.
The very last patch is entirely optional. It sets a recommended schedule
based on my own experience with very large repositories. I'm open to other
suggestions, but these are ones that I think work well and don't cause a
"rewrite the world" scenario like running nightly 'gc' would do.
I've been testing this scenario on my macOS laptop for a while and my Linux
machine. I have modified my cron task to provide logging via trace2 so I can
see what's happening. A future direction here would be to add some
maintenance logs to the repository so we can track what is happening and
diagnose whether the maintenance strategy is working on real repos.
It could be helpful for contributors to suggest ways to configure certain
jobs to run "nightly" or "overnight on a weekend" instead of just "whenever
the last run was long enough ago." One way to do this would be to set the
lastRun config to be at the time of day that the job should run. Another
option would be to make the cron table more complicated with multiple rows,
but I would prefer to avoid that option if there is a simpler mechanism.
Note: git maintenance (start|stop) only works on machines with cron by
design. The proper thing to do on Windows will come later. Perhaps this
command should be marked as unavailable on Windows somehow, or at least a
better error than "cron may not be available on your system". I did find
that that message is helpful sometimes: macOS worker agents for CI builds
typically do not have cron available.
Thanks, -Stolee
Derrick Stolee (7):
maintenance: optionally skip --auto process
maintenance: store the "last run" time in config
maintenance: add --scheduled option and config
for-each-repo: run subcommands on configured repos
maintenance: add [un]register subcommands
maintenance: add start/stop subcommands
maintenance: recommended schedule in register/start
.gitignore | 1 +
Documentation/config/maintenance.txt | 19 ++
Documentation/git-for-each-repo.txt | 45 +++++
Documentation/git-maintenance.txt | 44 ++++-
Makefile | 2 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 ++++++
builtin/gc.c | 282 ++++++++++++++++++++++++++-
git-gvfs-helper | Bin 0 -> 11171736 bytes
git.c | 1 +
run-command.c | 8 +
t/helper/test-crontab.c | 35 ++++
t/helper/test-gvfs-protocol | Bin 0 -> 10946928 bytes
t/helper/test-tool.c | 1 +
t/helper/test-tool.h | 1 +
t/t0068-for-each-repo.sh | 30 +++
t/t7900-maintenance.sh | 95 ++++++++-
t/test-lib.sh | 6 +
18 files changed, 625 insertions(+), 4 deletions(-)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100755 git-gvfs-helper
create mode 100644 t/helper/test-crontab.c
create mode 100755 t/helper/test-gvfs-protocol
create mode 100755 t/t0068-for-each-repo.sh
base-commit: 0c43c64dd2fb41ac14038f1c3143bddbc6c35585
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-680%2Fderrickstolee%2Fmaintenance%2Fscheduled-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-680/derrickstolee/maintenance/scheduled-v1
Pull-Request: https://github.com/gitgitgadget/git/pull/680
--
gitgitgadget
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:17:05
From: Derrick Stolee <redacted>
Some commands run 'git maintenance run --auto --[no-]quiet' after doing
their normal work, as a way to keep repositories clean as they are used.
Currently, users who do not want this maintenance to occur would set the
'gc.auto' config option to 0 to avoid the 'gc' task from running.
However, this does not stop the extra process invocation. On Windows,
this extra process invocation can be more expensive than necessary.
Allow users to drop this extra process by setting 'maintenance.auto' to
'false'.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 5 +++++
run-command.c | 8 ++++++++
t/t7900-maintenance.sh | 13 +++++++++++++
3 files changed, 26 insertions(+)
@@ -1,3 +1,8 @@+maintenance.auto::+ This boolean config option controls whether some commands run+ `git maintenance run --auto` after doing their normal work. Defaults+ to true.+ maintenance.<task>.enabled:: This boolean config option controls whether the maintenance task with name `<task>` is run when no `--task` option is specified to
@@ -1868,8 +1869,15 @@ int run_processes_parallel_tr2(int n, get_next_task_fn get_next_task,intrun_auto_maintenance(intquiet){+intenabled;structchild_processmaint=CHILD_PROCESS_INIT;+if(!git_config_get_bool("maintenance.auto",&enabled)&&+!enabled){+fprintf(stderr,"enabled: %d\n",enabled);+return0;+}+maint.git_cmd=1;strvec_pushl(&maint.args,"maintenance","run","--auto",NULL);strvec_push(&maint.args,quiet?"--quiet":"--no-quiet");
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:17:25
From: Derrick Stolee <redacted>
It can be helpful to store a list of repositories in global or system
config and then iterate Git commands on that list. Create a new builtin
that makes this process simple for experts. We will use this builtin to
run scheduled maintenance on all configured repositories in a future
change.
The test is very simple, but does highlight that the "--" argument is
optional.
Signed-off-by: Derrick Stolee <redacted>
---
.gitignore | 1 +
Documentation/git-for-each-repo.txt | 45 ++++++++++++++++++++++
Makefile | 1 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 +++++++++++++++++++++++++++++
git.c | 1 +
t/t0068-for-each-repo.sh | 30 +++++++++++++++
7 files changed, 137 insertions(+)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100755 t/t0068-for-each-repo.sh
@@ -0,0 +1,45 @@+git-for-each-repo(1)+====================++NAME+----+git-for-each-repo - Run a Git command on a list of repositories+++SYNOPSIS+--------+[verse]+'git for-each-repo' --config=<config> [--] <arguments>+++DESCRIPTION+-----------+Run a Git commands on a list of repositories. The arguments after the+known options or `--` indicator are used as the arguments for the Git+command.++For example, we could run maintenance on each of a list of repositories+stored in a `maintenance.repo` config variable using++-------------+git for-each-repo --config=maintenance.repo maintenance run+-------------++This will run `git -C <repo> maintenance run` for each value `<repo>`+in the multi-valued config variable `maintenance.repo`.+++OPTIONS+-------+--config=<config>::+ Use the given config variable as a multi-valued list storing+ absolute path names. Iterate on that list of paths to run+ the given arguments.+++These config values are loaded from system, global, and local Git config,+as available. If `git for-each-repo` is run in a directory that is not a+Git repository, then only the system and global config is used.++GIT+---+Part of the linkgit:git[1] suite
@@ -0,0 +1,58 @@+#include"cache.h"+#include"config.h"+#include"builtin.h"+#include"parse-options.h"+#include"run-command.h"+#include"string-list.h"++staticconstchar*constfor_each_repo_usage[]={+N_("git for-each-repo --config=<config> <command-args>"),+NULL+};++staticintrun_command_on_repo(constchar*path,+void*cbdata)+{+inti;+structchild_processchild=CHILD_PROCESS_INIT;+structstrvec*args=(structstrvec*)cbdata;++child.git_cmd=1;+strvec_pushl(&child.args,"-C",path,NULL);++for(i=0;i<args->nr;i++)+strvec_push(&child.args,args->v[i]);++returnrun_command(&child);+}++intcmd_for_each_repo(intargc,constchar**argv,constchar*prefix)+{+staticconstchar*config_key=NULL;+inti,result=0;+conststructstring_list*values;+structstrvecargs=STRVEC_INIT;++conststructoptionoptions[]={+OPT_STRING(0,"config",&config_key,N_("config"),+N_("config key storing a list of repository paths")),+OPT_END()+};++argc=parse_options(argc,argv,prefix,options,for_each_repo_usage,+PARSE_OPT_STOP_AT_NON_OPTION);++if(!config_key)+die(_("missing --config=<config>"));++for(i=0;i<argc;i++)+strvec_push(&args,argv[i]);++values=repo_config_get_value_multi(the_repository,+config_key);++for(i=0;!result&&i<values->nr;i++)+result=run_command_on_repo(values->items[i].string,&args);++returnresult;+}
@@ -0,0 +1,30 @@+#!/bin/sh++test_description='git for-each-repo builtin'++../test-lib.sh++test_expect_success'run based on configured value''+gitinitone&&+gitinittwo&&+gitinitthree&&+git-Ctwocommit--allow-empty-m"DID NOT RUN"&&+gitconfigrun.key"$TRASH_DIRECTORY/one"&&+gitconfig--addrun.key"$TRASH_DIRECTORY/three"&&+gitfor-each-repo--config=run.keycommit--allow-empty-m"ran"&&+git-Conelog-1--pretty=format:%s>message&&+grepranmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepranmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepranmessage&&+gitfor-each-repo--config=run.key--commit--allow-empty-m"ran again"&&+git-Conelog-1--pretty=format:%s>message&&+grepagainmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepagainmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepagainmessage+'++test_done
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:17:28
From: Derrick Stolee <redacted>
A user may want to run certain maintenance tasks based on frequency, not
conditions given in the repository. For example, the user may want to
perform a 'prefetch' task every hour, or 'gc' task every day. To assist,
update the 'git maintenance run --scheduled' command to check the config
for the last run of that task and add a number of seconds. The task
would then run only if the current time is beyond that minimum
timestamp.
Add a '--scheduled' option to 'git maintenance run' to only run tasks
that have had enough time pass since their last run. This is done for
each enabled task by checking if the current timestamp is at least as
large as the sum of 'maintenance.<task>.lastRun' and
'maintenance.<task>.schedule' in the Git config. This second value is
new to this commit, storing a number of seconds intended between runs.
A user could then set up an hourly maintenance run with the following
cron table:
0 * * * * git -C <repo> maintenance run --scheduled
Then, the user could configure the repository with the following config
values:
maintenance.prefetch.schedule 3000
maintenance.gc.schedule 86000
These numbers are slightly lower than one hour and one day (in seconds).
The cron schedule will enforce the hourly run rate, but we can use these
schedules to ensure the 'gc' task runs once a day. The error is given
because the *.lastRun config option is specified at the _start_ of the
task run. Otherwise, a slow task run could shift the "daily" job of 'gc'
from a 10:00pm run to 11:00pm run, or later.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 9 +++++
Documentation/git-maintenance.txt | 13 +++++++-
builtin/gc.c | 50 +++++++++++++++++++++++++++-
t/t7900-maintenance.sh | 20 +++++++++++
4 files changed, 90 insertions(+), 2 deletions(-)
@@ -15,6 +15,15 @@ maintenance.<task>.lastRun:: `<task>` is run. It stores a timestamp representing the most-recent run of the `<task>`.+maintenance.<task>.schedule::+ This config option controls whether or not the given `<task>` runs+ during a `git maintenance run --scheduled` command. If the option+ is an integer value `S`, then the `<task>` is run when the current+ time is `S` seconds after the timestamp stored in+ `maintenance.<task>.lastRun`. If the option has no value or a+ non-integer value, then the task will never run with the `--scheduled`+ option.+ maintenance.commit-graph.auto:: This integer config option controls how often the `commit-graph` task should be run as part of `git maintenance run --auto`. If zero, then
@@ -110,7 +110,18 @@ OPTIONS only if certain thresholds are met. For example, the `gc` task runs when the number of loose objects exceeds the number stored in the `gc.auto` config setting, or when the number of pack-files- exceeds the `gc.autoPackLimit` config setting.+ exceeds the `gc.autoPackLimit` config setting. Not compatible with+ the `--scheduled` option.++--scheduled::+ When combined with the `run` subcommand, run maintenance tasks+ only if certain time conditions are met, as specified by the+ `maintenance.<task>.schedule` config value for each `<task>`.+ This config value specifies a number of seconds since the last+ time that task ran, according to the `maintenance.<task>.lastRun`+ config value. The tasks that are tested are those provided by+ the `--task=<task>` option(s) or those with+ `maintenance.<task>.enabled` set to true. --quiet:: Do not report progress or other information over `stderr`.
@@ -1409,6 +1452,8 @@ int cmd_maintenance(int argc, const char **argv, const char *prefix)structoptionbuiltin_maintenance_options[]={OPT_BOOL(0,"auto",&opts.auto_flag,N_("run tasks based on the state of the repository")),+OPT_BOOL(0,"scheduled",&opts.scheduled,+N_("run tasks based on time intervals")),OPT_BOOL(0,"quiet",&opts.quiet,N_("do not report progress or other information over stderr")),OPT_CALLBACK_F(0,"task",NULL,N_("task"),
@@ -1434,6 +1479,9 @@ int cmd_maintenance(int argc, const char **argv, const char *prefix)builtin_maintenance_usage,PARSE_OPT_KEEP_UNKNOWN);+if(opts.auto_flag+opts.scheduled>1)+die(_("use at most one of the --auto and --scheduled options"));+if(argc!=1)usage_with_options(builtin_maintenance_usage,builtin_maintenance_options);
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:17:40
From: Derrick Stolee <redacted>
In preparation for launching background maintenance from the 'git
maintenance' builtin, create register/unregister subcommands. These
commands update the new 'maintenance.repos' config option in the global
config so the background maintenance job knows which repositories to
maintain.
These commands allow users to add a repository to the background
maintenance list without disrupting the actual maintenance mechanism.
For example, a user can run 'git maintenance register' when no
background maintenance is running and it will not start the background
maintenance. A later update to start running background maintenance will
then pick up this repository automatically.
The opposite example is that a user can run 'git maintenance unregister'
to remove the current repository from background maintenance without
halting maintenance for other repositories.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 14 ++++++++
builtin/gc.c | 55 ++++++++++++++++++++++++++++++-
t/t7900-maintenance.sh | 17 +++++++++-
3 files changed, 84 insertions(+), 2 deletions(-)
@@ -29,6 +29,15 @@ Git repository. SUBCOMMANDS -----------+register::+ Initialize Git config values so any scheduled maintenance will+ start running on this repository. This adds the repository to the+ `maintenance.repo` config variable in the current user's global+ config and enables some recommended configuration values for+ `maintenance.<task>.schedule`. The tasks that are enabled are safe+ for running in the background without disrupting foreground+ processes.+ run:: Run one or more maintenance tasks. If one or more `--task` options are specified, then those tasks are run in that order. Otherwise,
@@ -36,6 +45,11 @@ run:: config options are true. By default, only `maintenance.gc.enabled` is true.+unregister::+ Remove the current repository from background maintenance. This+ only removes the repository from the configured list. It does not+ stop the background maintenance processes from running.+ TASKS -----
@@ -705,7 +705,7 @@ int cmd_gc(int argc, const char **argv, const char *prefix)}staticconstchar*constbuiltin_maintenance_usage[]={-N_("git maintenance run [<options>]"),+N_("git maintenance <subcommand> [<options>]"),NULL};
@@ -1445,6 +1445,55 @@ static int task_option_parse(const struct option *opt,return0;}+staticintmaintenance_register(void)+{+structchild_processconfig_set=CHILD_PROCESS_INIT;+structchild_processconfig_get=CHILD_PROCESS_INIT;++/* There is no current repository, so skip registering it */+if(!the_repository||!the_repository->gitdir)+return0;++config_get.git_cmd=1;+strvec_pushl(&config_get.args,"config","--global","--get","maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);+config_get.out=-1;++if(start_command(&config_get))+returnerror(_("failed to run 'git config'"));++/* We already have this value in our config! */+if(!finish_command(&config_get))+return0;++config_set.git_cmd=1;+strvec_pushl(&config_set.args,"config","--add","--global","maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);++returnrun_command(&config_set);+}++staticintmaintenance_unregister(void)+{+structchild_processconfig_unset=CHILD_PROCESS_INIT;++if(!the_repository||!the_repository->gitdir)+returnerror(_("no current repository to unregister"));++config_unset.git_cmd=1;+strvec_pushl(&config_unset.args,"config","--global","--unset",+"maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);++returnrun_command(&config_unset);+}+intcmd_maintenance(intargc,constchar**argv,constchar*prefix){inti;
@@ -294,4 +294,19 @@ test_expect_success '--scheduled with specific time' 'test_cmp_config1595000100maintenance.commit-graph.lastrun'+test_expect_success'register and unregister''+test_when_finishedgitconfig--global--unset-allmaintenance.repo&&+gitconfig--global--addmaintenance.repo/existing1&&+gitconfig--global--addmaintenance.repo/existing2&&+gitconfig--global--get-allmaintenance.repo>before&&+gitmaintenanceregister&&+gitconfig--global--get-allmaintenance.repo>actual&&+cpbeforeafter&&+pwd>>after&&+test_cmpafteractual&&+gitmaintenanceunregister&&+gitconfig--global--get-allmaintenance.repo>actual&&+test_cmpbeforeactual+'+ test_done
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:17:43
From: Derrick Stolee <redacted>
Add new subcommands to 'git maintenance' that start or stop background
maintenance using 'cron', when available. This integration is as simple
as I could make it, barring some implementation complications.
For now, the background maintenance is scheduled to run hourly via the
following cron table row (ignore line breaks):
0 * * * * $p/git --exec-path=$p
for-each-repo --config=maintenance.repo
maintenance run --scheduled
Future extensions may want to add more complex schedules or some form of
logging. For now, hourly runs seem frequent enough to satisfy the needs
of tasks like 'prefetch' without being so frequent that users would
complain about many no-op commands.
Here, "$p" is a placeholder for the path to the current Git executable.
This is critical for systems with multiple versions of Git.
Specifically, macOS has a system version at '/usr/bin/git' while the
version that users can install resides at '/usr/local/bin/git' (symlinked
to '/usr/local/libexec/git-core/git'). This will also use your
locally-built version if you build and run this in your development
environment without installing first.
The GIT_TEST_CRONTAB environment variable is not intended for users to
edit, but instead as a way to mock the 'crontab [-l]' command. This
variable is set in test-lib.sh to avoid a future test from accidentally
running anything with the cron integration from modifying the user's
schedule. We use GIT_TEST_CRONTAB='test-tool crontab <file>' in our
tests to check how the schedule is modified in 'git maintenance
(start|stop)' commands.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 11 +++
Makefile | 1 +
builtin/gc.c | 117 ++++++++++++++++++++++++++++++
t/helper/test-crontab.c | 35 +++++++++
t/helper/test-tool.c | 1 +
t/helper/test-tool.h | 1 +
t/t7900-maintenance.sh | 30 ++++++++
t/test-lib.sh | 6 ++
8 files changed, 202 insertions(+)
create mode 100644 t/helper/test-crontab.c
@@ -45,6 +45,17 @@ run:: config options are true. By default, only `maintenance.gc.enabled` is true.+start::+ Start running maintenance on the current repository. This performs+ the same config updates as the `register` subcommand, then updates+ the background scheduler to run `git maintenance run --scheduled`+ on an hourly basis.++stop::+ Halt the background maintenance schedule. The current repository+ is not removed from the list of maintained repositories, in case+ the background maintenance is restarted later.+ unregister:: Remove the current repository from background maintenance. This only removes the repository from the configured list. It does not
@@ -32,6 +32,7 @@#include"remote.h"#include"midx.h"#include"object-store.h"+#include"exec-cmd.h"#define FAILED_RUN "failed to run %s"
@@ -1494,6 +1495,118 @@ static int maintenance_unregister(void)returnrun_command(&config_unset);}+#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"+#define END_LINE "# END GIT MAINTENANCE SCHEDULE"++staticintupdate_background_schedule(intrun_maintenance)+{+intresult=0;+intin_old_region=0;+structchild_processcrontab_list=CHILD_PROCESS_INIT;+structchild_processcrontab_edit=CHILD_PROCESS_INIT;+FILE*cron_list,*cron_in;+constchar*crontab_name;+structstrbufline=STRBUF_INIT;+structlock_filelk;+char*lock_path=xstrfmt("%s/schedule",the_repository->objects->odb->path);++if(hold_lock_file_for_update(&lk,lock_path,LOCK_NO_DEREF)<0)+returnerror(_("another process is scheduling background maintenance"));++crontab_name=getenv("GIT_TEST_CRONTAB");+if(!crontab_name)+crontab_name="crontab";++strvec_split(&crontab_list.args,crontab_name);+strvec_push(&crontab_list.args,"-l");+crontab_list.in=-1;+crontab_list.out=dup(lk.tempfile->fd);+crontab_list.git_cmd=0;++if(start_command(&crontab_list)){+result=error(_("failed to run 'crontab -l'; your system might not support 'cron'"));+gotocleanup;+}++/* Ignore exit code, as an empty crontab will return error. */+finish_command(&crontab_list);++/*+*Readfromthe.lockfile,filteringouttheold+*schedulewhileappendingthenewschedule.+*/+cron_list=fdopen(lk.tempfile->fd,"r");+rewind(cron_list);++strvec_split(&crontab_edit.args,crontab_name);+crontab_edit.in=-1;+crontab_edit.git_cmd=0;++if(start_command(&crontab_edit)){+result=error(_("failed to run 'crontab'; your system might not support 'cron'"));+gotocleanup;+}++cron_in=fdopen(crontab_edit.in,"w");+if(!cron_in){+result=error(_("failed to open stdin of 'crontab'"));+gotodone_editing;+}++while(!strbuf_getline_lf(&line,cron_list)){+if(!in_old_region&&!strcmp(line.buf,BEGIN_LINE))+in_old_region=1;+if(in_old_region)+continue;+fprintf(cron_in,"%s\n",line.buf);+if(in_old_region&&!strcmp(line.buf,END_LINE))+in_old_region=0;+}++if(run_maintenance){+constchar*exec_path=git_exec_path();++fprintf(cron_in,"\n%s\n",BEGIN_LINE);+fprintf(cron_in,"# The following schedule was created by Git\n");+fprintf(cron_in,"# Any edits made in this region might be\n");+fprintf(cron_in,"# replaced in the future by a Git command.\n\n");++fprintf(cron_in,+"0 * * * * \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --scheduled\n",+exec_path,exec_path);++fprintf(cron_in,"\n%s\n",END_LINE);+}++fflush(cron_in);+fclose(cron_in);+close(crontab_edit.in);++done_editing:+if(finish_command(&crontab_edit)){+result=error(_("'crontab' died"));+gotocleanup;+}+fclose(cron_list);++cleanup:+rollback_lock_file(&lk);+returnresult;+}++staticintmaintenance_start(void)+{+if(maintenance_register())+warning(_("failed to add repo to global config"));++returnupdate_background_schedule(1);+}++staticintmaintenance_stop(void)+{+returnupdate_background_schedule(0);+}+intcmd_maintenance(intargc,constchar**argv,constchar*prefix){inti;
@@ -309,4 +309,34 @@ test_expect_success 'register and unregister' 'test_cmpbeforeactual'+test_expect_success'start from empty cron table''+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestart&&++# start registers the repo+gitconfig--get--globalmaintenance.repo"$(pwd)"&&++grep"for-each-repo --config=maintenance.repo maintenance run --scheduled"cron.txt+'++test_expect_success'stop from existing schedule''+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestop&&++# stop does not unregister the repo+gitconfig--get--globalmaintenance.repo"$(pwd)"&&++# The newline is preserved+echo>empty&&+test_cmpemptycron.txt&&++# Operation is idempotent+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestop&&+test_cmpemptycron.txt+'++test_expect_success'start preserves existing schedule''+echo"Important information!">cron.txt&&+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestart&&+grep"Important information!"cron.txt+'+ test_done
@@ -1702,3 +1702,9 @@ test_lazy_prereq SHA1 ' test_lazy_prereqREBASE_P'test-z"$GIT_TEST_SKIP_REBASE_P"'++# Ensure that no test accidentally triggers a Git command+# that runs 'crontab', affecting a user's cron schedule.+# Tests that verify the cron integration must set this locally+# to avoid errors.+GIT_TEST_CRONTAB="exit 1"
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-19 17:17:45
From: Derrick Stolee <redacted>
The 'git maintenance (register|start)' subcommands add the current
repository to the global Git config so maintenance will operate on that
repository. It does not specify what maintenance should occur or how
often.
If a user sets any 'maintenance.<task>.scheduled' config value, then
they have chosen a specific schedule for themselves and Git should
respect that.
However, in an effort to recommend a good schedule for repositories of
all sizes, set new config values for recommended tasks that are safe to
run in the background while users run foreground Git commands. These
commands are generally everything but the 'gc' task.
Author's Note: I feel we should do _something_ to recommend a good
schedule to users, but I'm not 100% set on this schedule. This is the
schedule we use in Scalar and VFS for Git for very large repositories
using the GVFS protocol. While the schedule works in that environment,
it is possible that "normal" Git repositories could benefit from
something more obvious (such as running 'gc' once a day). However, this
patch gives us a place to start a conversation on what we should
recommend. For my purposes, Scalar will set these config values so we
can always differ from core Git's recommendations.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 6 +++++
builtin/gc.c | 44 +++++++++++++++++++++++++++++++
t/t7900-maintenance.sh | 5 ++++
3 files changed, 55 insertions(+)
@@ -37,6 +37,12 @@ register:: `maintenance.<task>.schedule`. The tasks that are enabled are safe for running in the background without disrupting foreground processes.+++If your repository has no 'maintenance.<task>.schedule' configuration+values set, then Git will set configuration values to some recommended+settings. These settings disable foreground maintenance while performing+maintenance tasks in the background that will not interrupt foreground Git+operations. run:: Run one or more maintenance tasks. If one or more `--task` options
From: Đoàn Trần Công Danh <hidden> Date: 2020-08-20 02:07:05
On 2020-08-19 17:16:42+0000, Derrick Stolee via GitGitGadget [off-list ref] wrote:
quoted hunk
From: Derrick Stolee <redacted>
@@ -1868,8 +1869,15 @@ int run_processes_parallel_tr2(int n, get_next_task_fn get_next_task, int run_auto_maintenance(int quiet) {+ int enabled; struct child_process maint = CHILD_PROCESS_INIT;+ if (!git_config_get_bool("maintenance.auto", &enabled) &&+ !enabled) {+ fprintf(stderr, "enabled: %d\n", enabled);+ return 0;+ }
Nit: This block of code is mis-indented (mixed space and tab).
If we're running into inner block, "enabled" will always be "0"
We can just write:
fprintf(stderr, "enabled: 0\n");
instead. Writing like that, we have one less thing to worry about
(whether "enabled" is initialised in git_config_get_bool or not).
--
Danh
On 2020-08-19 17:16:42+0000, Derrick Stolee via GitGitGadget [off-list ref] wrote:
quoted
From: Derrick Stolee <redacted>
@@ -1868,8 +1869,15 @@ int run_processes_parallel_tr2(int n, get_next_task_fn get_next_task, int run_auto_maintenance(int quiet) {+ int enabled; struct child_process maint = CHILD_PROCESS_INIT;+ if (!git_config_get_bool("maintenance.auto", &enabled) &&+ !enabled) {+ fprintf(stderr, "enabled: %d\n", enabled);+ return 0;+ }
Nit: This block of code is mis-indented (mixed space and tab).
Thanks.
If we're running into inner block, "enabled" will always be "0"
We can just write:
fprintf(stderr, "enabled: 0\n");
instead. Writing like that, we have one less thing to worry about
(whether "enabled" is initialised in git_config_get_bool or not).
Whoops! This fprintf shouldn't even be here, but got accidentally
added during a debugging session. Thanks for noticing!
-Stolee
I see this pattern in both previous patch and this patch,
should we create a helper (if not exist) to get current timestamp
instead, parsing "now" every now and then is not a good idea, in my
very opinionated opinion.
It looks like we have a simple and better named alias for this:
strbuf_reset(&config_name)
_reset has 400+ occurences in this code base, compare to 20 of _setlen
--
Danh
From: Đoàn Trần Công Danh <hidden> Date: 2020-08-20 15:00:59
On 2020-08-19 17:16:45+0000, Derrick Stolee via GitGitGadget [off-list ref] wrote:
From: Derrick Stolee <redacted>
It can be helpful to store a list of repositories in global or system
config and then iterate Git commands on that list. Create a new builtin
that makes this process simple for experts. We will use this builtin to
run scheduled maintenance on all configured repositories in a future
change.
Nice, I like this new command.
However, I'm not sure if we could declare this command as plumbing or
porcelain command.
I guess this command is meant more for scripting purpose, hence, it
should be plumbing, thus we need to define clear protocol for this
command, e.g, where it will redirect other command output, error to,
where for-each-repo write its own output/error.
Also, I think it would be nice to declare this is experimental for now.
Like we declared git-switch and git-restore.
--
Danh
quoted hunk
The test is very simple, but does highlight that the "--" argument is
optional.
Signed-off-by: Derrick Stolee <redacted>
---
.gitignore | 1 +
Documentation/git-for-each-repo.txt | 45 ++++++++++++++++++++++
Makefile | 1 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 +++++++++++++++++++++++++++++
git.c | 1 +
t/t0068-for-each-repo.sh | 30 +++++++++++++++
7 files changed, 137 insertions(+)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100755 t/t0068-for-each-repo.sh
@@ -0,0 +1,45 @@+git-for-each-repo(1)+====================++NAME+----+git-for-each-repo - Run a Git command on a list of repositories+++SYNOPSIS+--------+[verse]+'git for-each-repo' --config=<config> [--] <arguments>+++DESCRIPTION+-----------+Run a Git commands on a list of repositories. The arguments after the+known options or `--` indicator are used as the arguments for the Git+command.++For example, we could run maintenance on each of a list of repositories+stored in a `maintenance.repo` config variable using++-------------+git for-each-repo --config=maintenance.repo maintenance run+-------------++This will run `git -C <repo> maintenance run` for each value `<repo>`+in the multi-valued config variable `maintenance.repo`.+++OPTIONS+-------+--config=<config>::+ Use the given config variable as a multi-valued list storing+ absolute path names. Iterate on that list of paths to run+ the given arguments.+++These config values are loaded from system, global, and local Git config,+as available. If `git for-each-repo` is run in a directory that is not a+Git repository, then only the system and global config is used.++GIT+---+Part of the linkgit:git[1] suite
@@ -0,0 +1,58 @@+#include"cache.h"+#include"config.h"+#include"builtin.h"+#include"parse-options.h"+#include"run-command.h"+#include"string-list.h"++staticconstchar*constfor_each_repo_usage[]={+N_("git for-each-repo --config=<config> <command-args>"),+NULL+};++staticintrun_command_on_repo(constchar*path,+void*cbdata)+{+inti;+structchild_processchild=CHILD_PROCESS_INIT;+structstrvec*args=(structstrvec*)cbdata;++child.git_cmd=1;+strvec_pushl(&child.args,"-C",path,NULL);++for(i=0;i<args->nr;i++)+strvec_push(&child.args,args->v[i]);++returnrun_command(&child);+}++intcmd_for_each_repo(intargc,constchar**argv,constchar*prefix)+{+staticconstchar*config_key=NULL;+inti,result=0;+conststructstring_list*values;+structstrvecargs=STRVEC_INIT;++conststructoptionoptions[]={+OPT_STRING(0,"config",&config_key,N_("config"),+N_("config key storing a list of repository paths")),+OPT_END()+};++argc=parse_options(argc,argv,prefix,options,for_each_repo_usage,+PARSE_OPT_STOP_AT_NON_OPTION);++if(!config_key)+die(_("missing --config=<config>"));++for(i=0;i<argc;i++)+strvec_push(&args,argv[i]);++values=repo_config_get_value_multi(the_repository,+config_key);++for(i=0;!result&&i<values->nr;i++)+result=run_command_on_repo(values->items[i].string,&args);++returnresult;+}
@@ -0,0 +1,30 @@+#!/bin/sh++test_description='git for-each-repo builtin'++../test-lib.sh++test_expect_success'run based on configured value''+gitinitone&&+gitinittwo&&+gitinitthree&&+git-Ctwocommit--allow-empty-m"DID NOT RUN"&&+gitconfigrun.key"$TRASH_DIRECTORY/one"&&+gitconfig--addrun.key"$TRASH_DIRECTORY/three"&&+gitfor-each-repo--config=run.keycommit--allow-empty-m"ran"&&+git-Conelog-1--pretty=format:%s>message&&+grepranmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepranmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepranmessage&&+gitfor-each-repo--config=run.key--commit--allow-empty-m"ran again"&&+git-Conelog-1--pretty=format:%s>message&&+grepagainmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepagainmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepagainmessage+'++test_done
I see this pattern in both previous patch and this patch,
should we create a helper (if not exist) to get current timestamp
instead, parsing "now" every now and then is not a good idea, in my
very opinionated opinion.
Parsing "now" is not that much work, and it is done only once per
maintenance task. To make a helper that avoids these string comparisons
(specifically to avoid iterating through the "special" array in date.c)
is unlikely to be worth the effort and code duplication.
If you mean it would be good to use a macro here, then that would be
easy:
#define approxidate_now() approxidate("now")
One important thing for using this over time(NULL) is that we really
want this to work with GIT_TEST_DATE_NOW.
It looks like we have a simple and better named alias for this:
strbuf_reset(&config_name)
_reset has 400+ occurences in this code base, compare to 20 of _setlen
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:12
This is based on v3 of Part II (ds/maintenance-part-2) [1].
[1]
https://lore.kernel.org/git/pull.696.v3.git.1598380599.gitgitgadget@gmail.com/
This RFC is intended to show how I hope to integrate true background
maintenance into Git. As opposed to my original RFC [2], this entirely
integrates with cron (through crontab [-e|-l]) to launch maintenance
commands in the background.
[2]
https://lore.kernel.org/git/pull.597.git.1585946894.gitgitgadget@gmail.com/
Some preliminary work is done to allow a new --scheduled option that
triggers enabled tasks only if they have not been run in some amount of
time. The timestamp of the previous run is stored in the
maintenance.<task>.lastRun config value while the interval is stored in the
maintenance.<task>.schedule config value.
A new for-each-repo builtin runs Git commands on every repo in a given list.
Currently, the list is stored as a config setting, allowing a new
maintenance.repos config list to store the repositories registered for
background maintenance. Others may want to add a --file=<file> option for
their own workflows, but I focused on making this as simple as possible for
now.
The updates to the git maintenance builtin include new register/unregister
subcommands and start/stop subcommands. The register subcommand initializes
the config while the start subcommand does everything register does plus
update the cron table. The unregister and stop commands reverse this
process.
The very last patch is entirely optional. It sets a recommended schedule
based on my own experience with very large repositories. I'm open to other
suggestions, but these are ones that I think work well and don't cause a
"rewrite the world" scenario like running nightly 'gc' would do.
I've been testing this scenario on my macOS laptop for a while and my Linux
machine. I have modified my cron task to provide logging via trace2 so I can
see what's happening. A future direction here would be to add some
maintenance logs to the repository so we can track what is happening and
diagnose whether the maintenance strategy is working on real repos.
It could be helpful for contributors to suggest ways to configure certain
jobs to run "nightly" or "overnight on a weekend" instead of just "whenever
the last run was long enough ago." One way to do this would be to set the
lastRun config to be at the time of day that the job should run. Another
option would be to make the cron table more complicated with multiple rows,
but I would prefer to avoid that option if there is a simpler mechanism.
Note: git maintenance (start|stop) only works on machines with cron by
design. The proper thing to do on Windows will come later. Perhaps this
command should be marked as unavailable on Windows somehow, or at least a
better error than "cron may not be available on your system". I did find
that that message is helpful sometimes: macOS worker agents for CI builds
typically do not have cron available.
Updates since RFC v1
====================
* Some fallout from rewriting the option parsing in "Maintenance I"
* This applies cleanly on v3 of "Maintenance II"
* Several helpful feedback items from Đoàn Trần Công Danh are applied.
* There is an unresolved comment around the use of approxidate("now").
These calls are untouched from v1.
Thanks, -Stolee
Derrick Stolee (7):
maintenance: optionally skip --auto process
maintenance: store the "last run" time in config
maintenance: add --scheduled option and config
for-each-repo: run subcommands on configured repos
maintenance: add [un]register subcommands
maintenance: add start/stop subcommands
maintenance: recommended schedule in register/start
.gitignore | 1 +
Documentation/config/maintenance.txt | 19 ++
Documentation/git-for-each-repo.txt | 59 ++++++
Documentation/git-maintenance.txt | 44 ++++-
Makefile | 2 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 ++++++
builtin/gc.c | 286 ++++++++++++++++++++++++++-
command-list.txt | 1 +
git.c | 1 +
run-command.c | 6 +
t/helper/test-crontab.c | 35 ++++
t/helper/test-tool.c | 1 +
t/helper/test-tool.h | 1 +
t/t0068-for-each-repo.sh | 30 +++
t/t7900-maintenance.sh | 95 ++++++++-
t/test-lib.sh | 6 +
17 files changed, 640 insertions(+), 6 deletions(-)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100644 t/helper/test-crontab.c
create mode 100755 t/t0068-for-each-repo.sh
base-commit: e9bb32f53ade2067f773bfe6e5c13ed1a5d694a6
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-680%2Fderrickstolee%2Fmaintenance%2Fscheduled-v2
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-680/derrickstolee/maintenance/scheduled-v2
Pull-Request: https://github.com/gitgitgadget/git/pull/680
Range-diff vs v1:
1: 90de25d128 ! 1: 5fdd8188b1 maintenance: optionally skip --auto process
@@ run-command.c: int run_processes_parallel_tr2(int n, get_next_task_fn get_next_t
struct child_process maint = CHILD_PROCESS_INIT;
+ if (!git_config_get_bool("maintenance.auto", &enabled) &&
-+ !enabled) {
-+ fprintf(stderr, "enabled: %d\n", enabled);
++ !enabled)
+ return 0;
-+ }
+
maint.git_cmd = 1;
strvec_pushl(&maint.args, "maintenance", "run", "--auto", NULL);
2: bdc27fa28e ! 2: e3ef0b9bea maintenance: store the "last run" time in config
@@ builtin/gc.c: static int compare_tasks_by_selection(const void *a_, const void *
+ strbuf_release(&value);
+}
+
- static int maintenance_run(struct maintenance_opts *opts)
+ static int maintenance_run_tasks(struct maintenance_run_opts *opts)
{
int i, found_selected = 0;
-@@ builtin/gc.c: static int maintenance_run(struct maintenance_opts *opts)
+@@ builtin/gc.c: static int maintenance_run_tasks(struct maintenance_run_opts *opts)
!tasks[i].auto_condition()))
continue;
@@ builtin/gc.c: static int maintenance_run(struct maintenance_opts *opts)
if (tasks[i].fn(opts)) {
error(_("task '%s' failed"), tasks[i].name);
- ## git-gvfs-helper (new) ##
- Binary files /dev/null and git-gvfs-helper differ
-
- ## t/helper/test-gvfs-protocol (new) ##
- Binary files /dev/null and t/helper/test-gvfs-protocol differ
-
## t/t7900-maintenance.sh ##
@@ t/t7900-maintenance.sh: test_expect_success 'maintenance.incremental-repack.auto' '
done
3: 4473c93b11 ! 3: c728c57d85 maintenance: add --scheduled option and config
@@ Documentation/git-maintenance.txt: OPTIONS
Do not report progress or other information over `stderr`.
## builtin/gc.c ##
-@@ builtin/gc.c: static const char * const builtin_maintenance_usage[] = {
+@@ builtin/gc.c: int cmd_gc(int argc, const char **argv, const char *prefix)
+ }
+
+ static const char * const builtin_maintenance_run_usage[] = {
+- N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>]"),
++ N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--scheduled]"),
+ NULL
+ };
- struct maintenance_opts {
+ struct maintenance_run_opts {
int auto_flag;
+ int scheduled;
int quiet;
@@ builtin/gc.c: struct maintenance_task {
/* -1 if not selected. */
int selected_order;
-@@ builtin/gc.c: static int maintenance_run(struct maintenance_opts *opts)
+@@ builtin/gc.c: static int maintenance_run_tasks(struct maintenance_run_opts *opts)
!tasks[i].auto_condition()))
continue;
@@ builtin/gc.c: static int maintenance_run(struct maintenance_opts *opts)
update_last_run(&tasks[i]);
trace2_region_enter("maintenance", tasks[i].name, r);
-@@ builtin/gc.c: static int maintenance_run(struct maintenance_opts *opts)
+@@ builtin/gc.c: static int maintenance_run_tasks(struct maintenance_run_opts *opts)
return result;
}
@@ builtin/gc.c: static void initialize_task_config(void)
int config_value;
+ char *config_str;
- strbuf_setlen(&config_name, 0);
+- strbuf_setlen(&config_name, 0);
++ strbuf_reset(&config_name);
strbuf_addf(&config_name, "maintenance.%s.enabled",
-@@ builtin/gc.c: static void initialize_task_config(void)
+ tasks[i].name);
if (!git_config_get_bool(config_name.buf, &config_value))
tasks[i].enabled = config_value;
+
-+ strbuf_setlen(&config_name, 0);
++ strbuf_reset(&config_name);
+ strbuf_addf(&config_name, "maintenance.%s.schedule",
+ tasks[i].name);
+
@@ builtin/gc.c: static void initialize_task_config(void)
}
strbuf_release(&config_name);
-@@ builtin/gc.c: int cmd_maintenance(int argc, const char **argv, const char *prefix)
- struct option builtin_maintenance_options[] = {
+@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char *prefix)
+ struct option builtin_maintenance_run_options[] = {
OPT_BOOL(0, "auto", &opts.auto_flag,
N_("run tasks based on the state of the repository")),
+ OPT_BOOL(0, "scheduled", &opts.scheduled,
@@ builtin/gc.c: int cmd_maintenance(int argc, const char **argv, const char *prefi
OPT_BOOL(0, "quiet", &opts.quiet,
N_("do not report progress or other information over stderr")),
OPT_CALLBACK_F(0, "task", NULL, N_("task"),
-@@ builtin/gc.c: int cmd_maintenance(int argc, const char **argv, const char *prefix)
- builtin_maintenance_usage,
- PARSE_OPT_KEEP_UNKNOWN);
+@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char *prefix)
+ builtin_maintenance_run_usage,
+ PARSE_OPT_STOP_AT_NON_OPTION);
+ if (opts.auto_flag + opts.scheduled > 1)
+ die(_("use at most one of the --auto and --scheduled options"));
+
- if (argc != 1)
- usage_with_options(builtin_maintenance_usage,
- builtin_maintenance_options);
+ if (argc != 0)
+ usage_with_options(builtin_maintenance_run_usage,
+ builtin_maintenance_run_options);
## t/t7900-maintenance.sh ##
@@ t/t7900-maintenance.sh: test_expect_success 'maintenance.incremental-repack.auto' '
4: ccb667dc6f ! 4: 0314258c5c for-each-repo: run subcommands on configured repos
@@ Documentation/git-for-each-repo.txt (new)
+
+DESCRIPTION
+-----------
-+Run a Git commands on a list of repositories. The arguments after the
++Run a Git command on a list of repositories. The arguments after the
+known options or `--` indicator are used as the arguments for the Git
-+command.
++subprocess.
++
++THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.
+
+For example, we could run maintenance on each of a list of repositories
+stored in a `maintenance.repo` config variable using
@@ Documentation/git-for-each-repo.txt (new)
+as available. If `git for-each-repo` is run in a directory that is not a
+Git repository, then only the system and global config is used.
+
++
++SUBPROCESS BEHAVIOR
++-------------------
++
++If any `git -C <repo> <arguments>` subprocess returns a non-zero exit code,
++then the `git for-each-repo` process returns that exit code without running
++more subprocesses.
++
++Each `git -C <repo> <arguments>` subprocess inherits the standard file
++descriptors `stdin`, `stdout`, and `stderr`.
++
++
+GIT
+---
+Part of the linkgit:git[1] suite
@@ builtin/for-each-repo.c (new)
+ return result;
+}
+ ## command-list.txt ##
+@@ command-list.txt: git-fetch-pack synchingrepositories
+ git-filter-branch ancillarymanipulators
+ git-fmt-merge-msg purehelpers
+ git-for-each-ref plumbinginterrogators
++git-for-each-repo plumbinginterrogators
+ git-format-patch mainporcelain
+ git-fsck ancillaryinterrogators complete
+ git-gc mainporcelain
+
## git.c ##
@@ git.c: static struct cmd_struct commands[] = {
{ "fetch-pack", cmd_fetch_pack, RUN_SETUP | NO_PARSEOPT },
5: f44c6a0f20 ! 5: c0ce1267a9 maintenance: add [un]register subcommands
@@ Documentation/git-maintenance.txt: run::
## builtin/gc.c ##
-@@ builtin/gc.c: int cmd_gc(int argc, const char **argv, const char *prefix)
- }
-
- static const char * const builtin_maintenance_usage[] = {
-- N_("git maintenance run [<options>]"),
-+ N_("git maintenance <subcommand> [<options>]"),
- NULL
- };
-
-@@ builtin/gc.c: static int task_option_parse(const struct option *opt,
- return 0;
+@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char *prefix)
+ return maintenance_run_tasks(&opts);
}
+-static const char builtin_maintenance_usage[] = N_("git maintenance run [<options>]");
+static int maintenance_register(void)
+{
+ struct child_process config_set = CHILD_PROCESS_INIT;
@@ builtin/gc.c: static int task_option_parse(const struct option *opt,
+ return run_command(&config_unset);
+}
+
++static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
+
int cmd_maintenance(int argc, const char **argv, const char *prefix)
{
- int i;
@@ builtin/gc.c: int cmd_maintenance(int argc, const char **argv, const char *prefix)
- usage_with_options(builtin_maintenance_usage,
- builtin_maintenance_options);
-+ if (!strcmp(argv[0], "register"))
+ if (!strcmp(argv[1], "run"))
+ return maintenance_run(argc - 1, argv + 1, prefix);
++ if (!strcmp(argv[1], "register"))
+ return maintenance_register();
- if (!strcmp(argv[0], "run"))
- return maintenance_run(&opts);
-+ if (!strcmp(argv[0], "unregister"))
++ if (!strcmp(argv[1], "unregister"))
+ return maintenance_unregister();
- die(_("invalid subcommand: %s"), argv[0]);
+ die(_("invalid subcommand: %s"), argv[1]);
}
## t/t7900-maintenance.sh ##
6: 2442071fd0 ! 6: 8a7c34035a maintenance: add start/stop subcommands
@@ builtin/gc.c: static int maintenance_unregister(void)
+ return update_background_schedule(0);
+}
+
+ static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
+
int cmd_maintenance(int argc, const char **argv, const char *prefix)
- {
- int i;
@@ builtin/gc.c: int cmd_maintenance(int argc, const char **argv, const char *prefix)
- return maintenance_register();
- if (!strcmp(argv[0], "run"))
- return maintenance_run(&opts);
-+ if (!strcmp(argv[0], "start"))
+
+ if (!strcmp(argv[1], "run"))
+ return maintenance_run(argc - 1, argv + 1, prefix);
++ if (!strcmp(argv[1], "start"))
+ return maintenance_start();
-+ if (!strcmp(argv[0], "stop"))
++ if (!strcmp(argv[1], "stop"))
+ return maintenance_stop();
- if (!strcmp(argv[0], "unregister"))
- return maintenance_unregister();
-
+ if (!strcmp(argv[1], "register"))
+ return maintenance_register();
+ if (!strcmp(argv[1], "unregister"))
## t/helper/test-crontab.c (new) ##
@@
7: 40b1a0546c ! 7: 9ecabeb055 maintenance: recommended schedule in register/start
@@ Documentation/git-maintenance.txt: register::
Run one or more maintenance tasks. If one or more `--task` options
## builtin/gc.c ##
-@@ builtin/gc.c: static int task_option_parse(const struct option *opt,
- return 0;
+@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char *prefix)
+ return maintenance_run_tasks(&opts);
}
+static int has_schedule_config(void)
--
gitgitgadget
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:13
From: Derrick Stolee <redacted>
Some commands run 'git maintenance run --auto --[no-]quiet' after doing
their normal work, as a way to keep repositories clean as they are used.
Currently, users who do not want this maintenance to occur would set the
'gc.auto' config option to 0 to avoid the 'gc' task from running.
However, this does not stop the extra process invocation. On Windows,
this extra process invocation can be more expensive than necessary.
Allow users to drop this extra process by setting 'maintenance.auto' to
'false'.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 5 +++++
run-command.c | 6 ++++++
t/t7900-maintenance.sh | 13 +++++++++++++
3 files changed, 24 insertions(+)
@@ -1,3 +1,8 @@+maintenance.auto::+ This boolean config option controls whether some commands run+ `git maintenance run --auto` after doing their normal work. Defaults+ to true.+ maintenance.<task>.enabled:: This boolean config option controls whether the maintenance task with name `<task>` is run when no `--task` option is specified to
@@ -1868,8 +1869,13 @@ int run_processes_parallel_tr2(int n, get_next_task_fn get_next_task,intrun_auto_maintenance(intquiet){+intenabled;structchild_processmaint=CHILD_PROCESS_INIT;+if(!git_config_get_bool("maintenance.auto",&enabled)&&+!enabled)+return0;+maint.git_cmd=1;strvec_pushl(&maint.args,"maintenance","run","--auto",NULL);strvec_push(&maint.args,quiet?"--quiet":"--no-quiet");
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:18
From: Derrick Stolee <redacted>
Users may want to run certain maintenance tasks only so often. Update
the local config with a new 'maintenance.<task>.lastRun' config option
that stores the timestamp just before running the maintenance task.
I selected the timestamp before the task, as opposed to after the task,
for a couple reasons:
1. The time the task takes to execute should not contribute to the
interval between running the tasks. If a daily task takes 10 minutes
to run, then every day the execution will drift by at least 10
minutes.
2. If the task fails for some unforseen reason, it would be good to
indicate that we _attempted_ the task at a certain timestamp. This
will avoid spamming a repository that is in a bad state.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 5 +++++
builtin/gc.c | 16 ++++++++++++++++
t/t7900-maintenance.sh | 10 ++++++++++
3 files changed, 31 insertions(+)
@@ -10,6 +10,11 @@ maintenance.<task>.enabled:: `--task` option exists. By default, only `maintenance.gc.enabled` is true.+maintenance.<task>.lastRun::+ This config value is automatically updated by Git when the task+ `<task>` is run. It stores a timestamp representing the most-recent+ run of the `<task>`.+ maintenance.commit-graph.auto:: This integer config option controls how often the `commit-graph` task should be run as part of `git maintenance run --auto`. If zero, then
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:19
From: Derrick Stolee <redacted>
A user may want to run certain maintenance tasks based on frequency, not
conditions given in the repository. For example, the user may want to
perform a 'prefetch' task every hour, or 'gc' task every day. To assist,
update the 'git maintenance run --scheduled' command to check the config
for the last run of that task and add a number of seconds. The task
would then run only if the current time is beyond that minimum
timestamp.
Add a '--scheduled' option to 'git maintenance run' to only run tasks
that have had enough time pass since their last run. This is done for
each enabled task by checking if the current timestamp is at least as
large as the sum of 'maintenance.<task>.lastRun' and
'maintenance.<task>.schedule' in the Git config. This second value is
new to this commit, storing a number of seconds intended between runs.
A user could then set up an hourly maintenance run with the following
cron table:
0 * * * * git -C <repo> maintenance run --scheduled
Then, the user could configure the repository with the following config
values:
maintenance.prefetch.schedule 3000
maintenance.gc.schedule 86000
These numbers are slightly lower than one hour and one day (in seconds).
The cron schedule will enforce the hourly run rate, but we can use these
schedules to ensure the 'gc' task runs once a day. The error is given
because the *.lastRun config option is specified at the _start_ of the
task run. Otherwise, a slow task run could shift the "daily" job of 'gc'
from a 10:00pm run to 11:00pm run, or later.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 9 +++++
Documentation/git-maintenance.txt | 13 ++++++-
builtin/gc.c | 54 ++++++++++++++++++++++++++--
t/t7900-maintenance.sh | 20 +++++++++++
4 files changed, 92 insertions(+), 4 deletions(-)
@@ -15,6 +15,15 @@ maintenance.<task>.lastRun:: `<task>` is run. It stores a timestamp representing the most-recent run of the `<task>`.+maintenance.<task>.schedule::+ This config option controls whether or not the given `<task>` runs+ during a `git maintenance run --scheduled` command. If the option+ is an integer value `S`, then the `<task>` is run when the current+ time is `S` seconds after the timestamp stored in+ `maintenance.<task>.lastRun`. If the option has no value or a+ non-integer value, then the task will never run with the `--scheduled`+ option.+ maintenance.commit-graph.auto:: This integer config option controls how often the `commit-graph` task should be run as part of `git maintenance run --auto`. If zero, then
@@ -107,7 +107,18 @@ OPTIONS only if certain thresholds are met. For example, the `gc` task runs when the number of loose objects exceeds the number stored in the `gc.auto` config setting, or when the number of pack-files- exceeds the `gc.autoPackLimit` config setting.+ exceeds the `gc.autoPackLimit` config setting. Not compatible with+ the `--scheduled` option.++--scheduled::+ When combined with the `run` subcommand, run maintenance tasks+ only if certain time conditions are met, as specified by the+ `maintenance.<task>.schedule` config value for each `<task>`.+ This config value specifies a number of seconds since the last+ time that task ran, according to the `maintenance.<task>.lastRun`+ config value. The tasks that are tested are those provided by+ the `--task=<task>` option(s) or those with+ `maintenance.<task>.enabled` set to true. --quiet:: Do not report progress or other information over `stderr`.
@@ -1340,6 +1383,8 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)structoptionbuiltin_maintenance_run_options[]={OPT_BOOL(0,"auto",&opts.auto_flag,N_("run tasks based on the state of the repository")),+OPT_BOOL(0,"scheduled",&opts.scheduled,+N_("run tasks based on time intervals")),OPT_BOOL(0,"quiet",&opts.quiet,N_("do not report progress or other information over stderr")),OPT_CALLBACK_F(0,"task",NULL,N_("task"),
@@ -1360,6 +1405,9 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)builtin_maintenance_run_usage,PARSE_OPT_STOP_AT_NON_OPTION);+if(opts.auto_flag+opts.scheduled>1)+die(_("use at most one of the --auto and --scheduled options"));+if(argc!=0)usage_with_options(builtin_maintenance_run_usage,builtin_maintenance_run_options);
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:22
From: Derrick Stolee <redacted>
It can be helpful to store a list of repositories in global or system
config and then iterate Git commands on that list. Create a new builtin
that makes this process simple for experts. We will use this builtin to
run scheduled maintenance on all configured repositories in a future
change.
The test is very simple, but does highlight that the "--" argument is
optional.
Signed-off-by: Derrick Stolee <redacted>
---
.gitignore | 1 +
Documentation/git-for-each-repo.txt | 59 +++++++++++++++++++++++++++++
Makefile | 1 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 ++++++++++++++++++++++++++++
command-list.txt | 1 +
git.c | 1 +
t/t0068-for-each-repo.sh | 30 +++++++++++++++
8 files changed, 152 insertions(+)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100755 t/t0068-for-each-repo.sh
@@ -0,0 +1,59 @@+git-for-each-repo(1)+====================++NAME+----+git-for-each-repo - Run a Git command on a list of repositories+++SYNOPSIS+--------+[verse]+'git for-each-repo' --config=<config> [--] <arguments>+++DESCRIPTION+-----------+Run a Git command on a list of repositories. The arguments after the+known options or `--` indicator are used as the arguments for the Git+subprocess.++THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.++For example, we could run maintenance on each of a list of repositories+stored in a `maintenance.repo` config variable using++-------------+git for-each-repo --config=maintenance.repo maintenance run+-------------++This will run `git -C <repo> maintenance run` for each value `<repo>`+in the multi-valued config variable `maintenance.repo`.+++OPTIONS+-------+--config=<config>::+ Use the given config variable as a multi-valued list storing+ absolute path names. Iterate on that list of paths to run+ the given arguments.+++These config values are loaded from system, global, and local Git config,+as available. If `git for-each-repo` is run in a directory that is not a+Git repository, then only the system and global config is used.+++SUBPROCESS BEHAVIOR+-------------------++If any `git -C <repo> <arguments>` subprocess returns a non-zero exit code,+then the `git for-each-repo` process returns that exit code without running+more subprocesses.++Each `git -C <repo> <arguments>` subprocess inherits the standard file+descriptors `stdin`, `stdout`, and `stderr`.+++GIT+---+Part of the linkgit:git[1] suite
@@ -0,0 +1,58 @@+#include"cache.h"+#include"config.h"+#include"builtin.h"+#include"parse-options.h"+#include"run-command.h"+#include"string-list.h"++staticconstchar*constfor_each_repo_usage[]={+N_("git for-each-repo --config=<config> <command-args>"),+NULL+};++staticintrun_command_on_repo(constchar*path,+void*cbdata)+{+inti;+structchild_processchild=CHILD_PROCESS_INIT;+structstrvec*args=(structstrvec*)cbdata;++child.git_cmd=1;+strvec_pushl(&child.args,"-C",path,NULL);++for(i=0;i<args->nr;i++)+strvec_push(&child.args,args->v[i]);++returnrun_command(&child);+}++intcmd_for_each_repo(intargc,constchar**argv,constchar*prefix)+{+staticconstchar*config_key=NULL;+inti,result=0;+conststructstring_list*values;+structstrvecargs=STRVEC_INIT;++conststructoptionoptions[]={+OPT_STRING(0,"config",&config_key,N_("config"),+N_("config key storing a list of repository paths")),+OPT_END()+};++argc=parse_options(argc,argv,prefix,options,for_each_repo_usage,+PARSE_OPT_STOP_AT_NON_OPTION);++if(!config_key)+die(_("missing --config=<config>"));++for(i=0;i<argc;i++)+strvec_push(&args,argv[i]);++values=repo_config_get_value_multi(the_repository,+config_key);++for(i=0;!result&&i<values->nr;i++)+result=run_command_on_repo(values->items[i].string,&args);++returnresult;+}
@@ -0,0 +1,30 @@+#!/bin/sh++test_description='git for-each-repo builtin'++../test-lib.sh++test_expect_success'run based on configured value''+gitinitone&&+gitinittwo&&+gitinitthree&&+git-Ctwocommit--allow-empty-m"DID NOT RUN"&&+gitconfigrun.key"$TRASH_DIRECTORY/one"&&+gitconfig--addrun.key"$TRASH_DIRECTORY/three"&&+gitfor-each-repo--config=run.keycommit--allow-empty-m"ran"&&+git-Conelog-1--pretty=format:%s>message&&+grepranmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepranmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepranmessage&&+gitfor-each-repo--config=run.key--commit--allow-empty-m"ran again"&&+git-Conelog-1--pretty=format:%s>message&&+grepagainmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepagainmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepagainmessage+'++test_done
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:34
From: Derrick Stolee <redacted>
Add new subcommands to 'git maintenance' that start or stop background
maintenance using 'cron', when available. This integration is as simple
as I could make it, barring some implementation complications.
For now, the background maintenance is scheduled to run hourly via the
following cron table row (ignore line breaks):
0 * * * * $p/git --exec-path=$p
for-each-repo --config=maintenance.repo
maintenance run --scheduled
Future extensions may want to add more complex schedules or some form of
logging. For now, hourly runs seem frequent enough to satisfy the needs
of tasks like 'prefetch' without being so frequent that users would
complain about many no-op commands.
Here, "$p" is a placeholder for the path to the current Git executable.
This is critical for systems with multiple versions of Git.
Specifically, macOS has a system version at '/usr/bin/git' while the
version that users can install resides at '/usr/local/bin/git' (symlinked
to '/usr/local/libexec/git-core/git'). This will also use your
locally-built version if you build and run this in your development
environment without installing first.
The GIT_TEST_CRONTAB environment variable is not intended for users to
edit, but instead as a way to mock the 'crontab [-l]' command. This
variable is set in test-lib.sh to avoid a future test from accidentally
running anything with the cron integration from modifying the user's
schedule. We use GIT_TEST_CRONTAB='test-tool crontab <file>' in our
tests to check how the schedule is modified in 'git maintenance
(start|stop)' commands.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 11 +++
Makefile | 1 +
builtin/gc.c | 117 ++++++++++++++++++++++++++++++
t/helper/test-crontab.c | 35 +++++++++
t/helper/test-tool.c | 1 +
t/helper/test-tool.h | 1 +
t/t7900-maintenance.sh | 30 ++++++++
t/test-lib.sh | 6 ++
8 files changed, 202 insertions(+)
create mode 100644 t/helper/test-crontab.c
@@ -45,6 +45,17 @@ run:: config options are true. By default, only `maintenance.gc.enabled` is true.+start::+ Start running maintenance on the current repository. This performs+ the same config updates as the `register` subcommand, then updates+ the background scheduler to run `git maintenance run --scheduled`+ on an hourly basis.++stop::+ Halt the background maintenance schedule. The current repository+ is not removed from the list of maintained repositories, in case+ the background maintenance is restarted later.+ unregister:: Remove the current repository from background maintenance. This only removes the repository from the configured list. It does not
@@ -32,6 +32,7 @@#include"remote.h"#include"midx.h"#include"object-store.h"+#include"exec-cmd.h"#define FAILED_RUN "failed to run %s"
@@ -1463,6 +1464,118 @@ static int maintenance_unregister(void)returnrun_command(&config_unset);}+#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"+#define END_LINE "# END GIT MAINTENANCE SCHEDULE"++staticintupdate_background_schedule(intrun_maintenance)+{+intresult=0;+intin_old_region=0;+structchild_processcrontab_list=CHILD_PROCESS_INIT;+structchild_processcrontab_edit=CHILD_PROCESS_INIT;+FILE*cron_list,*cron_in;+constchar*crontab_name;+structstrbufline=STRBUF_INIT;+structlock_filelk;+char*lock_path=xstrfmt("%s/schedule",the_repository->objects->odb->path);++if(hold_lock_file_for_update(&lk,lock_path,LOCK_NO_DEREF)<0)+returnerror(_("another process is scheduling background maintenance"));++crontab_name=getenv("GIT_TEST_CRONTAB");+if(!crontab_name)+crontab_name="crontab";++strvec_split(&crontab_list.args,crontab_name);+strvec_push(&crontab_list.args,"-l");+crontab_list.in=-1;+crontab_list.out=dup(lk.tempfile->fd);+crontab_list.git_cmd=0;++if(start_command(&crontab_list)){+result=error(_("failed to run 'crontab -l'; your system might not support 'cron'"));+gotocleanup;+}++/* Ignore exit code, as an empty crontab will return error. */+finish_command(&crontab_list);++/*+*Readfromthe.lockfile,filteringouttheold+*schedulewhileappendingthenewschedule.+*/+cron_list=fdopen(lk.tempfile->fd,"r");+rewind(cron_list);++strvec_split(&crontab_edit.args,crontab_name);+crontab_edit.in=-1;+crontab_edit.git_cmd=0;++if(start_command(&crontab_edit)){+result=error(_("failed to run 'crontab'; your system might not support 'cron'"));+gotocleanup;+}++cron_in=fdopen(crontab_edit.in,"w");+if(!cron_in){+result=error(_("failed to open stdin of 'crontab'"));+gotodone_editing;+}++while(!strbuf_getline_lf(&line,cron_list)){+if(!in_old_region&&!strcmp(line.buf,BEGIN_LINE))+in_old_region=1;+if(in_old_region)+continue;+fprintf(cron_in,"%s\n",line.buf);+if(in_old_region&&!strcmp(line.buf,END_LINE))+in_old_region=0;+}++if(run_maintenance){+constchar*exec_path=git_exec_path();++fprintf(cron_in,"\n%s\n",BEGIN_LINE);+fprintf(cron_in,"# The following schedule was created by Git\n");+fprintf(cron_in,"# Any edits made in this region might be\n");+fprintf(cron_in,"# replaced in the future by a Git command.\n\n");++fprintf(cron_in,+"0 * * * * \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --scheduled\n",+exec_path,exec_path);++fprintf(cron_in,"\n%s\n",END_LINE);+}++fflush(cron_in);+fclose(cron_in);+close(crontab_edit.in);++done_editing:+if(finish_command(&crontab_edit)){+result=error(_("'crontab' died"));+gotocleanup;+}+fclose(cron_list);++cleanup:+rollback_lock_file(&lk);+returnresult;+}++staticintmaintenance_start(void)+{+if(maintenance_register())+warning(_("failed to add repo to global config"));++returnupdate_background_schedule(1);+}++staticintmaintenance_stop(void)+{+returnupdate_background_schedule(0);+}+staticconstcharbuiltin_maintenance_usage[]=N_("git maintenance <subcommand> [<options>]");intcmd_maintenance(intargc,constchar**argv,constchar*prefix)
@@ -309,4 +309,34 @@ test_expect_success 'register and unregister' 'test_cmpbeforeactual'+test_expect_success'start from empty cron table''+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestart&&++# start registers the repo+gitconfig--get--globalmaintenance.repo"$(pwd)"&&++grep"for-each-repo --config=maintenance.repo maintenance run --scheduled"cron.txt+'++test_expect_success'stop from existing schedule''+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestop&&++# stop does not unregister the repo+gitconfig--get--globalmaintenance.repo"$(pwd)"&&++# The newline is preserved+echo>empty&&+test_cmpemptycron.txt&&++# Operation is idempotent+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestop&&+test_cmpemptycron.txt+'++test_expect_success'start preserves existing schedule''+echo"Important information!">cron.txt&&+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestart&&+grep"Important information!"cron.txt+'+ test_done
@@ -1702,3 +1702,9 @@ test_lazy_prereq SHA1 ' test_lazy_prereqREBASE_P'test-z"$GIT_TEST_SKIP_REBASE_P"'++# Ensure that no test accidentally triggers a Git command+# that runs 'crontab', affecting a user's cron schedule.+# Tests that verify the cron integration must set this locally+# to avoid errors.+GIT_TEST_CRONTAB="exit 1"
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:37
From: Derrick Stolee <redacted>
The 'git maintenance (register|start)' subcommands add the current
repository to the global Git config so maintenance will operate on that
repository. It does not specify what maintenance should occur or how
often.
If a user sets any 'maintenance.<task>.scheduled' config value, then
they have chosen a specific schedule for themselves and Git should
respect that.
However, in an effort to recommend a good schedule for repositories of
all sizes, set new config values for recommended tasks that are safe to
run in the background while users run foreground Git commands. These
commands are generally everything but the 'gc' task.
Author's Note: I feel we should do _something_ to recommend a good
schedule to users, but I'm not 100% set on this schedule. This is the
schedule we use in Scalar and VFS for Git for very large repositories
using the GVFS protocol. While the schedule works in that environment,
it is possible that "normal" Git repositories could benefit from
something more obvious (such as running 'gc' once a day). However, this
patch gives us a place to start a conversation on what we should
recommend. For my purposes, Scalar will set these config values so we
can always differ from core Git's recommendations.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 6 +++++
builtin/gc.c | 44 +++++++++++++++++++++++++++++++
t/t7900-maintenance.sh | 5 ++++
3 files changed, 55 insertions(+)
@@ -37,6 +37,12 @@ register:: `maintenance.<task>.schedule`. The tasks that are enabled are safe for running in the background without disrupting foreground processes.+++If your repository has no 'maintenance.<task>.schedule' configuration+values set, then Git will set configuration values to some recommended+settings. These settings disable foreground maintenance while performing+maintenance tasks in the background that will not interrupt foreground Git+operations. run:: Run one or more maintenance tasks. If one or more `--task` options
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-25 18:40:40
From: Derrick Stolee <redacted>
In preparation for launching background maintenance from the 'git
maintenance' builtin, create register/unregister subcommands. These
commands update the new 'maintenance.repos' config option in the global
config so the background maintenance job knows which repositories to
maintain.
These commands allow users to add a repository to the background
maintenance list without disrupting the actual maintenance mechanism.
For example, a user can run 'git maintenance register' when no
background maintenance is running and it will not start the background
maintenance. A later update to start running background maintenance will
then pick up this repository automatically.
The opposite example is that a user can run 'git maintenance unregister'
to remove the current repository from background maintenance without
halting maintenance for other repositories.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 14 ++++++++
builtin/gc.c | 55 ++++++++++++++++++++++++++++++-
t/t7900-maintenance.sh | 17 +++++++++-
3 files changed, 84 insertions(+), 2 deletions(-)
@@ -29,6 +29,15 @@ Git repository. SUBCOMMANDS -----------+register::+ Initialize Git config values so any scheduled maintenance will+ start running on this repository. This adds the repository to the+ `maintenance.repo` config variable in the current user's global+ config and enables some recommended configuration values for+ `maintenance.<task>.schedule`. The tasks that are enabled are safe+ for running in the background without disrupting foreground+ processes.+ run:: Run one or more maintenance tasks. If one or more `--task` options are specified, then those tasks are run in that order. Otherwise,
@@ -36,6 +45,11 @@ run:: config options are true. By default, only `maintenance.gc.enabled` is true.+unregister::+ Remove the current repository from background maintenance. This+ only removes the repository from the configured list. It does not+ stop the background maintenance processes from running.+ TASKS -----
@@ -1414,7 +1414,56 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)returnmaintenance_run_tasks(&opts);}-staticconstcharbuiltin_maintenance_usage[]=N_("git maintenance run [<options>]");+staticintmaintenance_register(void)+{+structchild_processconfig_set=CHILD_PROCESS_INIT;+structchild_processconfig_get=CHILD_PROCESS_INIT;++/* There is no current repository, so skip registering it */+if(!the_repository||!the_repository->gitdir)+return0;++config_get.git_cmd=1;+strvec_pushl(&config_get.args,"config","--global","--get","maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);+config_get.out=-1;++if(start_command(&config_get))+returnerror(_("failed to run 'git config'"));++/* We already have this value in our config! */+if(!finish_command(&config_get))+return0;++config_set.git_cmd=1;+strvec_pushl(&config_set.args,"config","--add","--global","maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);++returnrun_command(&config_set);+}++staticintmaintenance_unregister(void)+{+structchild_processconfig_unset=CHILD_PROCESS_INIT;++if(!the_repository||!the_repository->gitdir)+returnerror(_("no current repository to unregister"));++config_unset.git_cmd=1;+strvec_pushl(&config_unset.args,"config","--global","--unset",+"maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);++returnrun_command(&config_unset);+}++staticconstcharbuiltin_maintenance_usage[]=N_("git maintenance <subcommand> [<options>]");intcmd_maintenance(intargc,constchar**argv,constchar*prefix){
@@ -294,4 +294,19 @@ test_expect_success '--scheduled with specific time' 'test_cmp_config1595000100maintenance.commit-graph.lastrun'+test_expect_success'register and unregister''+test_when_finishedgitconfig--global--unset-allmaintenance.repo&&+gitconfig--global--addmaintenance.repo/existing1&&+gitconfig--global--addmaintenance.repo/existing2&&+gitconfig--global--get-allmaintenance.repo>before&&+gitmaintenanceregister&&+gitconfig--global--get-allmaintenance.repo>actual&&+cpbeforeafter&&+pwd>>after&&+test_cmpafteractual&&+gitmaintenanceunregister&&+gitconfig--global--get-allmaintenance.repo>actual&&+test_cmpbeforeactual+'+ test_done
From: Michal Suchánek <hidden> Date: 2020-08-26 12:42:44
On Wed, Aug 19, 2020 at 05:16:41PM +0000, Derrick Stolee via GitGitGadget wrote:
This is based on ds/maintenance-part-2, but with some local updates to
review feedback. It won't apply cleanly right now. This RFC is for early
feedback and not intended to make a new tracking branch until v2.
This RFC is intended to show how I hope to integrate true background
maintenance into Git. As opposed to my original RFC [1], this entirely
integrates with cron (through crontab [-e|-l]) to launch maintenance
commands in the background.
[1]
https://lore.kernel.org/git/pull.597.git.1585946894.gitgitgadget@gmail.com/
Some preliminary work is done to allow a new --scheduled option that
triggers enabled tasks only if they have not been run in some amount of
time. The timestamp of the previous run is stored in the
maintenance.<task>.lastRun config value while the interval is stored in the
maintenance.<task>.schedule config value.
This changes the config file from read-mostly to continuously updated. Is
that desirable?
In particular it significanly increases the risk of race with the user
editing the file.
I think timestamps are not configuration and should be written to some
other file.
Or is there already a core git feature that continuously updates the
config file?
Thanks
Michal
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:45:41
This is based on v3 of Part II (ds/maintenance-part-2) [1].
[1]
https://lore.kernel.org/git/pull.696.v3.git.1598380599.gitgitgadget@gmail.com/
This RFC is intended to show how I hope to integrate true background
maintenance into Git. As opposed to my original RFC [2], this entirely
integrates with cron (through crontab [-e|-l]) to launch maintenance
commands in the background.
[2]
https://lore.kernel.org/git/pull.597.git.1585946894.gitgitgadget@gmail.com/
Some preliminary work is done to allow a new --schedule option that tells
the command which tasks to run based on a maintenance.<task>.schedule config
option. The timing is not enforced by Git, but instead is expected to be
provided as a hint from a cron schedule.
A new for-each-repo builtin runs Git commands on every repo in a given list.
Currently, the list is stored as a config setting, allowing a new
maintenance.repos config list to store the repositories registered for
background maintenance. Others may want to add a --file=<file> option for
their own workflows, but I focused on making this as simple as possible for
now.
The updates to the git maintenance builtin include new register/unregister
subcommands and start/stop subcommands. The register subcommand initializes
the config while the start subcommand does everything register does plus
update the cron table. The unregister and stop commands reverse this
process.
The very last patch is entirely optional. It sets a recommended schedule
based on my own experience with very large repositories. I'm open to other
suggestions, but these are ones that I think work well and don't cause a
"rewrite the world" scenario like running nightly 'gc' would do.
I've been testing this scenario on my macOS laptop for a while and my Linux
machine. I have modified my cron task to provide logging via trace2 so I can
see what's happening. A future direction here would be to add some
maintenance logs to the repository so we can track what is happening and
diagnose whether the maintenance strategy is working on real repos.
Note: git maintenance (start|stop) only works on machines with cron by
design. The proper thing to do on Windows will come later. Perhaps this
command should be marked as unavailable on Windows somehow, or at least a
better error than "cron may not be available on your system". I did find
that that message is helpful sometimes: macOS worker agents for CI builds
typically do not have cron available.
Updates since RFC v2
====================
* Update the cron schedule with three lines saying "run hourly except at
midnight", "run daily except on first day of week", and "run weekly".
This avoids parallel processes competing for the object database lock.
* Update the --schedule= and 'maintenance..schedule' config options. This
is reflected in the recommended schedule at the end.
* Drop the *.lastRun config option. It was going to trash config files but
it is also not needed by the new cron schedule.
I expect this to be my final RFC version before restarting the thread with a
v1 next week. Please throw any and all critique at the plan here!
Updates since RFC v1
====================
* Some fallout from rewriting the option parsing in "Maintenance I"
* This applies cleanly on v3 of "Maintenance II"
* Several helpful feedback items from Đoàn Trần Công Danh are applied.
* There is an unresolved comment around the use of approxidate("now").
These calls are untouched from v1.
Thanks, -Stolee
Cc: sandals@crustytoothpaste.net [sandals@crustytoothpaste.net],
steadmon@google.com [steadmon@google.com], jrnieder@gmail.com
[jrnieder@gmail.com], peff@peff.net [peff@peff.net], congdanhqx@gmail.com
[congdanhqx@gmail.com], phillip.wood123@gmail.com
[phillip.wood123@gmail.com], emilyshaffer@google.com
[emilyshaffer@google.com], sluongng@gmail.com [sluongng@gmail.com],
jonathantanmy@google.com [jonathantanmy@google.com]
Derrick Stolee (6):
maintenance: optionally skip --auto process
maintenance: add --schedule option and config
for-each-repo: run subcommands on configured repos
maintenance: add [un]register subcommands
maintenance: add start/stop subcommands
maintenance: recommended schedule in register/start
.gitignore | 1 +
Documentation/config/maintenance.txt | 10 +
Documentation/git-for-each-repo.txt | 59 ++++++
Documentation/git-maintenance.txt | 44 +++-
Makefile | 2 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 ++++++
builtin/gc.c | 292 ++++++++++++++++++++++++++-
command-list.txt | 1 +
git.c | 1 +
run-command.c | 6 +
t/helper/test-crontab.c | 35 ++++
t/helper/test-tool.c | 1 +
t/helper/test-tool.h | 1 +
t/t0068-for-each-repo.sh | 30 +++
t/t7900-maintenance.sh | 114 ++++++++++-
t/test-lib.sh | 6 +
17 files changed, 654 insertions(+), 8 deletions(-)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100644 t/helper/test-crontab.c
create mode 100755 t/t0068-for-each-repo.sh
base-commit: e9bb32f53ade2067f773bfe6e5c13ed1a5d694a6
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-680%2Fderrickstolee%2Fmaintenance%2Fscheduled-v3
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-680/derrickstolee/maintenance/scheduled-v3
Pull-Request: https://github.com/gitgitgadget/git/pull/680
Range-diff vs v2:
1: 5fdd8188b1 = 1: 5fdd8188b1 maintenance: optionally skip --auto process
2: e3ef0b9bea < -: ---------- maintenance: store the "last run" time in config
3: c728c57d85 ! 2: 41a067894d maintenance: add --scheduled option and config
@@ Metadata
Author: Derrick Stolee [off-list ref]
## Commit message ##
- maintenance: add --scheduled option and config
+ maintenance: add --schedule option and config
A user may want to run certain maintenance tasks based on frequency, not
conditions given in the repository. For example, the user may want to
perform a 'prefetch' task every hour, or 'gc' task every day. To assist,
- update the 'git maintenance run --scheduled' command to check the config
- for the last run of that task and add a number of seconds. The task
- would then run only if the current time is beyond that minimum
- timestamp.
+ update the 'git maintenance run' command to include a
+ '--schedule=<frequency>' option. The allowed frequencies are 'hourly',
+ 'daily', and 'weekly'. These values are also allowed in a new config
+ value 'maintenance.<task>.schedule'.
- Add a '--scheduled' option to 'git maintenance run' to only run tasks
- that have had enough time pass since their last run. This is done for
- each enabled task by checking if the current timestamp is at least as
- large as the sum of 'maintenance.<task>.lastRun' and
- 'maintenance.<task>.schedule' in the Git config. This second value is
- new to this commit, storing a number of seconds intended between runs.
+ The 'git maintenance run --schedule=<frequency>' checks the '*.schedule'
+ config value for each enabled task to see if the configured frequency is
+ at least as frequent as the frequency from the '--schedule' argument. We
+ use the following order, for full clarity:
- A user could then set up an hourly maintenance run with the following
- cron table:
+ 'hourly' > 'daily' > 'weekly'
- 0 * * * * git -C <repo> maintenance run --scheduled
+ Use new 'enum schedule_priority' to track these values numerically.
- Then, the user could configure the repository with the following config
- values:
+ The following cron table would run the scheduled tasks with the correct
+ frequencies:
- maintenance.prefetch.schedule 3000
- maintenance.gc.schedule 86000
+ 0 1-23 * * * git -C <repo> maintenance run --scheduled=hourly
+ 0 0 * * 1-6 git -C <repo> maintenance run --scheduled=daily
+ 0 0 * * 0 git -C <repo> maintenance run --scheduled=weekly
- These numbers are slightly lower than one hour and one day (in seconds).
- The cron schedule will enforce the hourly run rate, but we can use these
- schedules to ensure the 'gc' task runs once a day. The error is given
- because the *.lastRun config option is specified at the _start_ of the
- task run. Otherwise, a slow task run could shift the "daily" job of 'gc'
- from a 10:00pm run to 11:00pm run, or later.
+ This cron schedule will run --scheduled=hourly every hour except at
+ midnight. This avoids a concurrent run with the --scheduled=daily that
+ runs at midnight every day except the first day of the week. This avoids
+ a concurrent run with the --scheduled=weekly that runs at midnight on
+ the first day of the week. Since --scheduled=daily also runs the
+ 'hourly' tasks and --scheduled=weekly runs the 'hourly' and 'daily'
+ tasks, we will still see all tasks run with the proper frequencies.
Signed-off-by: Derrick Stolee [off-list ref]
## Documentation/config/maintenance.txt ##
-@@ Documentation/config/maintenance.txt: maintenance.<task>.lastRun::
- `<task>` is run. It stores a timestamp representing the most-recent
- run of the `<task>`.
+@@ Documentation/config/maintenance.txt: maintenance.<task>.enabled::
+ `--task` option exists. By default, only `maintenance.gc.enabled`
+ is true.
+maintenance.<task>.schedule::
+ This config option controls whether or not the given `<task>` runs
-+ during a `git maintenance run --scheduled` command. If the option
-+ is an integer value `S`, then the `<task>` is run when the current
-+ time is `S` seconds after the timestamp stored in
-+ `maintenance.<task>.lastRun`. If the option has no value or a
-+ non-integer value, then the task will never run with the `--scheduled`
-+ option.
++ during a `git maintenance run --schedule=<frequency>` command. The
++ value must be one of "hourly", "daily", or "weekly".
+
maintenance.commit-graph.auto::
This integer config option controls how often the `commit-graph` task
@@ Documentation/git-maintenance.txt: OPTIONS
in the `gc.auto` config setting, or when the number of pack-files
- exceeds the `gc.autoPackLimit` config setting.
+ exceeds the `gc.autoPackLimit` config setting. Not compatible with
-+ the `--scheduled` option.
++ the `--schedule` option.
+
-+--scheduled::
++--schedule::
+ When combined with the `run` subcommand, run maintenance tasks
+ only if certain time conditions are met, as specified by the
+ `maintenance.<task>.schedule` config value for each `<task>`.
@@ Documentation/git-maintenance.txt: OPTIONS
## builtin/gc.c ##
@@ builtin/gc.c: int cmd_gc(int argc, const char **argv, const char *prefix)
+ return 0;
}
- static const char * const builtin_maintenance_run_usage[] = {
+-static const char * const builtin_maintenance_run_usage[] = {
- N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>]"),
-+ N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--scheduled]"),
++static const char *const builtin_maintenance_run_usage[] = {
++ N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
NULL
};
++enum schedule_priority {
++ SCHEDULE_NONE = 0,
++ SCHEDULE_WEEKLY = 1,
++ SCHEDULE_DAILY = 2,
++ SCHEDULE_HOURLY = 3,
++};
++
++static enum schedule_priority parse_schedule(const char *value)
++{
++ if (!value)
++ return SCHEDULE_NONE;
++ if (!strcasecmp(value, "hourly"))
++ return SCHEDULE_HOURLY;
++ if (!strcasecmp(value, "daily"))
++ return SCHEDULE_DAILY;
++ if (!strcasecmp(value, "weekly"))
++ return SCHEDULE_WEEKLY;
++ return SCHEDULE_NONE;
++}
++
++static int maintenance_opt_schedule(const struct option *opt, const char *arg,
++ int unset)
++{
++ enum schedule_priority *priority = opt->value;
++
++ if (unset)
++ die(_("--no-schedule is not allowed"));
++
++ *priority = parse_schedule(arg);
++
++ if (!*priority)
++ die(_("unrecognized --schedule argument '%s'"), arg);
++
++ return 0;
++}
++
struct maintenance_run_opts {
int auto_flag;
-+ int scheduled;
int quiet;
++ enum schedule_priority schedule;
};
+ /* Remember to update object flag allocation in object.h */
@@ builtin/gc.c: struct maintenance_task {
- const char *name;
- maintenance_task_fn *fn;
maintenance_auto_fn *auto_condition;
-- unsigned enabled:1;
-+ unsigned enabled:1,
-+ scheduled:1;
+ unsigned enabled:1;
++ enum schedule_priority schedule;
++
/* -1 if not selected. */
int selected_order;
+ };
@@ builtin/gc.c: static int maintenance_run_tasks(struct maintenance_run_opts *opts)
- !tasks[i].auto_condition()))
continue;
-+ if (opts->scheduled && !tasks[i].scheduled)
+ if (opts->auto_flag &&
+- (!tasks[i].auto_condition ||
+- !tasks[i].auto_condition()))
++ (!tasks[i].auto_condition || !tasks[i].auto_condition()))
+ continue;
+
- update_last_run(&tasks[i]);
++ if (opts->schedule && tasks[i].schedule < opts->schedule)
+ continue;
trace2_region_enter("maintenance", tasks[i].name, r);
-@@ builtin/gc.c: static int maintenance_run_tasks(struct maintenance_run_opts *opts)
- return result;
- }
-
-+static void fill_schedule_info(struct maintenance_task *task,
-+ const char *config_name,
-+ timestamp_t schedule_delay)
-+{
-+ timestamp_t now = approxidate("now");
-+ char *value = NULL;
-+ struct strbuf last_run = STRBUF_INIT;
-+ int64_t previous_run;
-+
-+ strbuf_addf(&last_run, "maintenance.%s.lastrun", task->name);
-+
-+ if (git_config_get_string(last_run.buf, &value))
-+ task->scheduled = 1;
-+ else {
-+ previous_run = git_config_int64(last_run.buf, value);
-+ if (now >= previous_run + schedule_delay)
-+ task->scheduled = 1;
-+ }
-+
-+ free(value);
-+ strbuf_release(&last_run);
-+}
-+
- static void initialize_task_config(void)
- {
- int i;
@@ builtin/gc.c: static void initialize_task_config(void)
for (i = 0; i < TASK__COUNT; i++) {
@@ builtin/gc.c: static void initialize_task_config(void)
+ tasks[i].name);
+
+ if (!git_config_get_string(config_name.buf, &config_str)) {
-+ timestamp_t schedule_delay = git_config_int64(
-+ config_name.buf,
-+ config_str);
-+ fill_schedule_info(&tasks[i],
-+ config_name.buf,
-+ schedule_delay);
++ tasks[i].schedule = parse_schedule(config_str);
+ free(config_str);
+ }
}
@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char
struct option builtin_maintenance_run_options[] = {
OPT_BOOL(0, "auto", &opts.auto_flag,
N_("run tasks based on the state of the repository")),
-+ OPT_BOOL(0, "scheduled", &opts.scheduled,
-+ N_("run tasks based on time intervals")),
++ OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
++ N_("run tasks based on frequency"),
++ maintenance_opt_schedule),
OPT_BOOL(0, "quiet", &opts.quiet,
N_("do not report progress or other information over stderr")),
OPT_CALLBACK_F(0, "task", NULL, N_("task"),
@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char
builtin_maintenance_run_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
-+ if (opts.auto_flag + opts.scheduled > 1)
-+ die(_("use at most one of the --auto and --scheduled options"));
++ if (opts.auto_flag && opts.schedule)
++ die(_("use at most one of --auto and --schedule=<frequency>"));
+
if (argc != 0)
usage_with_options(builtin_maintenance_run_usage,
@@ t/t7900-maintenance.sh: test_expect_success 'maintenance.incremental-repack.auto
done
'
-+test_expect_success '--auto and --scheduled incompatible' '
-+ test_must_fail git maintenance run --auto --scheduled 2>err &&
++test_expect_success '--auto and --schedule incompatible' '
++ test_must_fail git maintenance run --auto --schedule=daily 2>err &&
+ test_i18ngrep "at most one" err
+'
+
- test_expect_success 'tasks update maintenance.<task>.lastRun' '
- git config --unset maintenance.commit-graph.lastrun &&
- GIT_TRACE2_EVENT="$(pwd)/run.txt" \
-@@ t/t7900-maintenance.sh: test_expect_success 'tasks update maintenance.<task>.lastRun' '
- test_cmp_config 1595000000 maintenance.commit-graph.lastrun
- '
-
-+test_expect_success '--scheduled with specific time' '
-+ git config maintenance.commit-graph.schedule 100 &&
-+ GIT_TRACE2_EVENT="$(pwd)/too-soon.txt" \
-+ GIT_TEST_DATE_NOW=1595000099 \
-+ git maintenance run --scheduled 2>/dev/null &&
++test_expect_success 'invalid --schedule value' '
++ test_must_fail git maintenance run --schedule=annually 2>err &&
++ test_i18ngrep "unrecognized --schedule" err
++'
++
++test_expect_success '--schedule inheritance weekly -> daily -> hourly' '
++ git config maintenance.loose-objects.enabled true &&
++ git config maintenance.loose-objects.schedule hourly &&
++ git config maintenance.commit-graph.enabled true &&
++ git config maintenance.commit-graph.schedule daily &&
++ git config maintenance.incremental-repack.enabled true &&
++ git config maintenance.incremental-repack.schedule weekly &&
++
++ GIT_TRACE2_EVENT="$(pwd)/hourly.txt" \
++ git maintenance run --schedule=hourly 2>/dev/null &&
++ test_subcommand git prune-packed --quiet <hourly.txt &&
+ test_subcommand ! git commit-graph write --split --reachable \
-+ --no-progress <too-soon.txt &&
-+ GIT_TRACE2_EVENT="$(pwd)/long-enough.txt" \
-+ GIT_TEST_DATE_NOW=1595000100 \
-+ git maintenance run --scheduled 2>/dev/null &&
++ --no-progress <hourly.txt &&
++ test_subcommand ! git multi-pack-index write --no-progress <hourly.txt &&
++
++ GIT_TRACE2_EVENT="$(pwd)/daily.txt" \
++ git maintenance run --schedule=daily 2>/dev/null &&
++ test_subcommand git prune-packed --quiet <daily.txt &&
++ test_subcommand git commit-graph write --split --reachable \
++ --no-progress <daily.txt &&
++ test_subcommand ! git multi-pack-index write --no-progress <daily.txt &&
++
++ GIT_TRACE2_EVENT="$(pwd)/weekly.txt" \
++ git maintenance run --schedule=weekly 2>/dev/null &&
++ test_subcommand git prune-packed --quiet <weekly.txt &&
+ test_subcommand git commit-graph write --split --reachable \
-+ --no-progress <long-enough.txt &&
-+ test_cmp_config 1595000100 maintenance.commit-graph.lastrun
++ --no-progress <weekly.txt &&
++ test_subcommand git multi-pack-index write --no-progress <weekly.txt
+'
+
test_done
4: 0314258c5c = 3: b29b68614b for-each-repo: run subcommands on configured repos
5: c0ce1267a9 ! 4: fc741fab5a maintenance: add [un]register subcommands
@@ t/t7900-maintenance.sh: GIT_TEST_MULTI_PACK_INDEX=0
test_expect_code 128 git maintenance barf 2>err &&
test_i18ngrep "invalid subcommand: barf" err
'
-@@ t/t7900-maintenance.sh: test_expect_success '--scheduled with specific time' '
- test_cmp_config 1595000100 maintenance.commit-graph.lastrun
+@@ t/t7900-maintenance.sh: test_expect_success '--schedule inheritance weekly -> daily -> hourly' '
+ test_subcommand git multi-pack-index write --no-progress <weekly.txt
'
+test_expect_success 'register and unregister' '
6: 8a7c34035a ! 5: e9672c6a6c maintenance: add start/stop subcommands
@@ Commit message
maintenance using 'cron', when available. This integration is as simple
as I could make it, barring some implementation complications.
- For now, the background maintenance is scheduled to run hourly via the
- following cron table row (ignore line breaks):
+ The schedule is laid out as follows:
- 0 * * * * $p/git --exec-path=$p
- for-each-repo --config=maintenance.repo
- maintenance run --scheduled
+ 0 1-23 * * * $cmd maintenance run --schedule=hourly
+ 0 0 * * 1-6 $cmd maintenance run --schedule=daily
+ 0 0 * * 0 $cmd maintenance run --schedule=weekly
- Future extensions may want to add more complex schedules or some form of
- logging. For now, hourly runs seem frequent enough to satisfy the needs
- of tasks like 'prefetch' without being so frequent that users would
- complain about many no-op commands.
+ where $cmd is a properly-qualified 'git for-each-repo' execution:
- Here, "$p" is a placeholder for the path to the current Git executable.
- This is critical for systems with multiple versions of Git.
- Specifically, macOS has a system version at '/usr/bin/git' while the
- version that users can install resides at '/usr/local/bin/git' (symlinked
- to '/usr/local/libexec/git-core/git'). This will also use your
- locally-built version if you build and run this in your development
+ $cmd=$path/git --exec-path=$path for-each-repo --config=maintenance.repo
+
+ where $path points to the location of the Git executable running 'git
+ maintenance start'. This is critical for systems with multiple versions
+ of Git. Specifically, macOS has a system version at '/usr/bin/git' while
+ the version that users can install resides at '/usr/local/bin/git'
+ (symlinked to '/usr/local/libexec/git-core/git'). This will also use
+ your locally-built version if you build and run this in your development
environment without installing first.
+ This conditional schedule avoids having cron launch multiple 'git
+ for-each-repo' commands in parallel. Such parallel commands would likely
+ lead to the 'hourly' and 'daily' tasks competing over the object
+ database lock. This could lead to to some tasks never being run! Since
+ the --schedule=<frequency> argument will run all tasks with _at least_
+ the given frequency, the daily runs will also run the hourly tasks.
+ Similarly, the weekly runs will also run the daily and hourly tasks.
+
The GIT_TEST_CRONTAB environment variable is not intended for users to
edit, but instead as a way to mock the 'crontab [-l]' command. This
variable is set in test-lib.sh to avoid a future test from accidentally
@@ builtin/gc.c: static int maintenance_unregister(void)
+ }
+
+ if (run_maintenance) {
++ struct strbuf line_format = STRBUF_INIT;
+ const char *exec_path = git_exec_path();
+
-+ fprintf(cron_in, "\n%s\n", BEGIN_LINE);
-+ fprintf(cron_in, "# The following schedule was created by Git\n");
++ fprintf(cron_in, "%s\n", BEGIN_LINE);
++ fprintf(cron_in,
++ "# The following schedule was created by Git\n");
+ fprintf(cron_in, "# Any edits made in this region might be\n");
-+ fprintf(cron_in, "# replaced in the future by a Git command.\n\n");
-+
+ fprintf(cron_in,
-+ "0 * * * * \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --scheduled\n",
-+ exec_path, exec_path);
++ "# replaced in the future by a Git command.\n\n");
++
++ strbuf_addf(&line_format,
++ "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
++ exec_path, exec_path);
++ fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
++ fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
++ fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
++ strbuf_release(&line_format);
+
+ fprintf(cron_in, "\n%s\n", END_LINE);
+ }
@@ t/t7900-maintenance.sh: test_expect_success 'register and unregister' '
+ # start registers the repo
+ git config --get --global maintenance.repo "$(pwd)" &&
+
-+ grep "for-each-repo --config=maintenance.repo maintenance run --scheduled" cron.txt
++ grep "for-each-repo --config=maintenance.repo maintenance run --schedule=daily" cron.txt &&
++ grep "for-each-repo --config=maintenance.repo maintenance run --schedule=hourly" cron.txt &&
++ grep "for-each-repo --config=maintenance.repo maintenance run --schedule=weekly" cron.txt
+'
+
+test_expect_success 'stop from existing schedule' '
@@ t/t7900-maintenance.sh: test_expect_success 'register and unregister' '
+ # stop does not unregister the repo
+ git config --get --global maintenance.repo "$(pwd)" &&
+
-+ # The newline is preserved
-+ echo >empty &&
-+ test_cmp empty cron.txt &&
-+
+ # Operation is idempotent
+ GIT_TEST_CRONTAB="test-tool crontab cron.txt" git maintenance stop &&
-+ test_cmp empty cron.txt
++ test_must_be_empty cron.txt
+'
+
+test_expect_success 'start preserves existing schedule' '
7: 9ecabeb055 ! 6: 62e8db8b2a maintenance: recommended schedule in register/start
@@ Commit message
repository. It does not specify what maintenance should occur or how
often.
- If a user sets any 'maintenance.<task>.scheduled' config value, then
+ If a user sets any 'maintenance.<task>.schedule' config value, then
they have chosen a specific schedule for themselves and Git should
respect that.
@@ Commit message
schedule we use in Scalar and VFS for Git for very large repositories
using the GVFS protocol. While the schedule works in that environment,
it is possible that "normal" Git repositories could benefit from
- something more obvious (such as running 'gc' once a day). However, this
+ something more obvious (such as running 'gc' weekly). However, this
patch gives us a place to start a conversation on what we should
recommend. For my purposes, Scalar will set these config values so we
can always differ from core Git's recommendations.
@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char
+ prefix = config_name.len;
+
+ for (i = 0; !found && i < TASK__COUNT; i++) {
-+ int value;
++ char *value;
+
+ strbuf_setlen(&config_name, prefix);
+ strbuf_addf(&config_name, "%s.schedule", tasks[i].name);
+
-+ if (!git_config_get_int(config_name.buf, &value))
++ if (!git_config_get_string(config_name.buf, &value)) {
+ found = 1;
++ FREE_AND_NULL(value);
++ }
+ }
+
+ strbuf_release(&config_name);
@@ builtin/gc.c: static int maintenance_run(int argc, const char **argv, const char
+ git_config_set("maintenance.gc.enabled", "false");
+
+ git_config_set("maintenance.prefetch.enabled", "true");
-+ git_config_set("maintenance.prefetch.schedule", "3500");
++ git_config_set("maintenance.prefetch.schedule", "hourly");
+
+ git_config_set("maintenance.commit-graph.enabled", "true");
-+ git_config_set("maintenance.commit-graph.schedule", "3500");
++ git_config_set("maintenance.commit-graph.schedule", "hourly");
+
+ git_config_set("maintenance.loose-objects.enabled", "true");
-+ git_config_set("maintenance.loose-objects.schedule", "86000");
++ git_config_set("maintenance.loose-objects.schedule", "daily");
+
+ git_config_set("maintenance.incremental-repack.enabled", "true");
-+ git_config_set("maintenance.incremental-repack.schedule", "86000");
++ git_config_set("maintenance.incremental-repack.schedule", "daily");
+}
+
static int maintenance_register(void)
@@ builtin/gc.c: static int maintenance_register(void)
if (!the_repository || !the_repository->gitdir)
return 0;
-+ if (has_schedule_config())
++ if (!has_schedule_config())
+ set_recommended_schedule();
+
config_get.git_cmd = 1;
@@ builtin/gc.c: static int maintenance_register(void)
## t/t7900-maintenance.sh ##
@@ t/t7900-maintenance.sh: test_expect_success 'register and unregister' '
+ git config --global --add maintenance.repo /existing1 &&
git config --global --add maintenance.repo /existing2 &&
git config --global --get-all maintenance.repo >before &&
++
++ # We still have maintenance.<task>.schedule config set,
++ # so this does not update the local schedule
++ git maintenance register &&
++ test_must_fail git config maintenance.auto &&
++
++ # Clear previous maintenance.<task>.schedule values
++ for task in loose-objects commit-graph incremental-repack
++ do
++ git config --unset maintenance.$task.schedule || return 1
++ done &&
git maintenance register &&
+ test_cmp_config false maintenance.auto &&
+ test_cmp_config false maintenance.gc.enabled &&
+ test_cmp_config true maintenance.prefetch.enabled &&
-+ test_cmp_config 3500 maintenance.commit-graph.schedule &&
-+ test_cmp_config 86000 maintenance.incremental-repack.schedule &&
++ test_cmp_config hourly maintenance.commit-graph.schedule &&
++ test_cmp_config daily maintenance.incremental-repack.schedule &&
git config --global --get-all maintenance.repo >actual &&
cp before after &&
pwd >>after &&
--
gitgitgadget
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:45:42
From: Derrick Stolee <redacted>
A user may want to run certain maintenance tasks based on frequency, not
conditions given in the repository. For example, the user may want to
perform a 'prefetch' task every hour, or 'gc' task every day. To assist,
update the 'git maintenance run' command to include a
'--schedule=<frequency>' option. The allowed frequencies are 'hourly',
'daily', and 'weekly'. These values are also allowed in a new config
value 'maintenance.<task>.schedule'.
The 'git maintenance run --schedule=<frequency>' checks the '*.schedule'
config value for each enabled task to see if the configured frequency is
at least as frequent as the frequency from the '--schedule' argument. We
use the following order, for full clarity:
'hourly' > 'daily' > 'weekly'
Use new 'enum schedule_priority' to track these values numerically.
The following cron table would run the scheduled tasks with the correct
frequencies:
0 1-23 * * * git -C <repo> maintenance run --scheduled=hourly
0 0 * * 1-6 git -C <repo> maintenance run --scheduled=daily
0 0 * * 0 git -C <repo> maintenance run --scheduled=weekly
This cron schedule will run --scheduled=hourly every hour except at
midnight. This avoids a concurrent run with the --scheduled=daily that
runs at midnight every day except the first day of the week. This avoids
a concurrent run with the --scheduled=weekly that runs at midnight on
the first day of the week. Since --scheduled=daily also runs the
'hourly' tasks and --scheduled=weekly runs the 'hourly' and 'daily'
tasks, we will still see all tasks run with the proper frequencies.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 5 +++
Documentation/git-maintenance.txt | 13 +++++-
builtin/gc.c | 67 +++++++++++++++++++++++++---
t/t7900-maintenance.sh | 40 +++++++++++++++++
4 files changed, 119 insertions(+), 6 deletions(-)
@@ -10,6 +10,11 @@ maintenance.<task>.enabled:: `--task` option exists. By default, only `maintenance.gc.enabled` is true.+maintenance.<task>.schedule::+ This config option controls whether or not the given `<task>` runs+ during a `git maintenance run --schedule=<frequency>` command. The+ value must be one of "hourly", "daily", or "weekly".+ maintenance.commit-graph.auto:: This integer config option controls how often the `commit-graph` task should be run as part of `git maintenance run --auto`. If zero, then
@@ -107,7 +107,18 @@ OPTIONS only if certain thresholds are met. For example, the `gc` task runs when the number of loose objects exceeds the number stored in the `gc.auto` config setting, or when the number of pack-files- exceeds the `gc.autoPackLimit` config setting.+ exceeds the `gc.autoPackLimit` config setting. Not compatible with+ the `--schedule` option.++--schedule::+ When combined with the `run` subcommand, run maintenance tasks+ only if certain time conditions are met, as specified by the+ `maintenance.<task>.schedule` config value for each `<task>`.+ This config value specifies a number of seconds since the last+ time that task ran, according to the `maintenance.<task>.lastRun`+ config value. The tasks that are tested are those provided by+ the `--task=<task>` option(s) or those with+ `maintenance.<task>.enabled` set to true. --quiet:: Do not report progress or other information over `stderr`.
@@ -704,14 +704,51 @@ int cmd_gc(int argc, const char **argv, const char *prefix)return0;}-staticconstchar*constbuiltin_maintenance_run_usage[]={-N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>]"),+staticconstchar*constbuiltin_maintenance_run_usage[]={+N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),NULL};+enumschedule_priority{+SCHEDULE_NONE=0,+SCHEDULE_WEEKLY=1,+SCHEDULE_DAILY=2,+SCHEDULE_HOURLY=3,+};++staticenumschedule_priorityparse_schedule(constchar*value)+{+if(!value)+returnSCHEDULE_NONE;+if(!strcasecmp(value,"hourly"))+returnSCHEDULE_HOURLY;+if(!strcasecmp(value,"daily"))+returnSCHEDULE_DAILY;+if(!strcasecmp(value,"weekly"))+returnSCHEDULE_WEEKLY;+returnSCHEDULE_NONE;+}++staticintmaintenance_opt_schedule(conststructoption*opt,constchar*arg,+intunset)+{+enumschedule_priority*priority=opt->value;++if(unset)+die(_("--no-schedule is not allowed"));++*priority=parse_schedule(arg);++if(!*priority)+die(_("unrecognized --schedule argument '%s'"),arg);++return0;+}+structmaintenance_run_opts{intauto_flag;intquiet;+enumschedule_priorityschedule;};/* Remember to update object flag allocation in object.h */
@@ -1159,6 +1196,8 @@ struct maintenance_task {maintenance_auto_fn*auto_condition;unsignedenabled:1;+enumschedule_priorityschedule;+/* -1 if not selected. */intselected_order;};
@@ -1250,8 +1289,10 @@ static int maintenance_run_tasks(struct maintenance_run_opts *opts)continue;if(opts->auto_flag&&-(!tasks[i].auto_condition||-!tasks[i].auto_condition()))+(!tasks[i].auto_condition||!tasks[i].auto_condition()))+continue;++if(opts->schedule&&tasks[i].schedule<opts->schedule)continue;trace2_region_enter("maintenance",tasks[i].name,r);
@@ -1324,6 +1375,9 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)structoptionbuiltin_maintenance_run_options[]={OPT_BOOL(0,"auto",&opts.auto_flag,N_("run tasks based on the state of the repository")),+OPT_CALLBACK(0,"schedule",&opts.schedule,N_("frequency"),+N_("run tasks based on frequency"),+maintenance_opt_schedule),OPT_BOOL(0,"quiet",&opts.quiet,N_("do not report progress or other information over stderr")),OPT_CALLBACK_F(0,"task",NULL,N_("task"),
@@ -1344,6 +1398,9 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)builtin_maintenance_run_usage,PARSE_OPT_STOP_AT_NON_OPTION);+if(opts.auto_flag&&opts.schedule)+die(_("use at most one of --auto and --schedule=<frequency>"));+if(argc!=0)usage_with_options(builtin_maintenance_run_usage,builtin_maintenance_run_options);
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:45:44
From: Derrick Stolee <redacted>
In preparation for launching background maintenance from the 'git
maintenance' builtin, create register/unregister subcommands. These
commands update the new 'maintenance.repos' config option in the global
config so the background maintenance job knows which repositories to
maintain.
These commands allow users to add a repository to the background
maintenance list without disrupting the actual maintenance mechanism.
For example, a user can run 'git maintenance register' when no
background maintenance is running and it will not start the background
maintenance. A later update to start running background maintenance will
then pick up this repository automatically.
The opposite example is that a user can run 'git maintenance unregister'
to remove the current repository from background maintenance without
halting maintenance for other repositories.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 14 ++++++++
builtin/gc.c | 55 ++++++++++++++++++++++++++++++-
t/t7900-maintenance.sh | 17 +++++++++-
3 files changed, 84 insertions(+), 2 deletions(-)
@@ -29,6 +29,15 @@ Git repository. SUBCOMMANDS -----------+register::+ Initialize Git config values so any scheduled maintenance will+ start running on this repository. This adds the repository to the+ `maintenance.repo` config variable in the current user's global+ config and enables some recommended configuration values for+ `maintenance.<task>.schedule`. The tasks that are enabled are safe+ for running in the background without disrupting foreground+ processes.+ run:: Run one or more maintenance tasks. If one or more `--task` options are specified, then those tasks are run in that order. Otherwise,
@@ -36,6 +45,11 @@ run:: config options are true. By default, only `maintenance.gc.enabled` is true.+unregister::+ Remove the current repository from background maintenance. This+ only removes the repository from the configured list. It does not+ stop the background maintenance processes from running.+ TASKS -----
@@ -1407,7 +1407,56 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)returnmaintenance_run_tasks(&opts);}-staticconstcharbuiltin_maintenance_usage[]=N_("git maintenance run [<options>]");+staticintmaintenance_register(void)+{+structchild_processconfig_set=CHILD_PROCESS_INIT;+structchild_processconfig_get=CHILD_PROCESS_INIT;++/* There is no current repository, so skip registering it */+if(!the_repository||!the_repository->gitdir)+return0;++config_get.git_cmd=1;+strvec_pushl(&config_get.args,"config","--global","--get","maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);+config_get.out=-1;++if(start_command(&config_get))+returnerror(_("failed to run 'git config'"));++/* We already have this value in our config! */+if(!finish_command(&config_get))+return0;++config_set.git_cmd=1;+strvec_pushl(&config_set.args,"config","--add","--global","maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);++returnrun_command(&config_set);+}++staticintmaintenance_unregister(void)+{+structchild_processconfig_unset=CHILD_PROCESS_INIT;++if(!the_repository||!the_repository->gitdir)+returnerror(_("no current repository to unregister"));++config_unset.git_cmd=1;+strvec_pushl(&config_unset.args,"config","--global","--unset",+"maintenance.repo",+the_repository->worktree?the_repository->worktree+:the_repository->gitdir,+NULL);++returnrun_command(&config_unset);+}++staticconstcharbuiltin_maintenance_usage[]=N_("git maintenance <subcommand> [<options>]");intcmd_maintenance(intargc,constchar**argv,constchar*prefix){
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:45:47
From: Derrick Stolee <redacted>
Some commands run 'git maintenance run --auto --[no-]quiet' after doing
their normal work, as a way to keep repositories clean as they are used.
Currently, users who do not want this maintenance to occur would set the
'gc.auto' config option to 0 to avoid the 'gc' task from running.
However, this does not stop the extra process invocation. On Windows,
this extra process invocation can be more expensive than necessary.
Allow users to drop this extra process by setting 'maintenance.auto' to
'false'.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/config/maintenance.txt | 5 +++++
run-command.c | 6 ++++++
t/t7900-maintenance.sh | 13 +++++++++++++
3 files changed, 24 insertions(+)
@@ -1,3 +1,8 @@+maintenance.auto::+ This boolean config option controls whether some commands run+ `git maintenance run --auto` after doing their normal work. Defaults+ to true.+ maintenance.<task>.enabled:: This boolean config option controls whether the maintenance task with name `<task>` is run when no `--task` option is specified to
@@ -1868,8 +1869,13 @@ int run_processes_parallel_tr2(int n, get_next_task_fn get_next_task,intrun_auto_maintenance(intquiet){+intenabled;structchild_processmaint=CHILD_PROCESS_INIT;+if(!git_config_get_bool("maintenance.auto",&enabled)&&+!enabled)+return0;+maint.git_cmd=1;strvec_pushl(&maint.args,"maintenance","run","--auto",NULL);strvec_push(&maint.args,quiet?"--quiet":"--no-quiet");
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:45:49
From: Derrick Stolee <redacted>
Add new subcommands to 'git maintenance' that start or stop background
maintenance using 'cron', when available. This integration is as simple
as I could make it, barring some implementation complications.
The schedule is laid out as follows:
0 1-23 * * * $cmd maintenance run --schedule=hourly
0 0 * * 1-6 $cmd maintenance run --schedule=daily
0 0 * * 0 $cmd maintenance run --schedule=weekly
where $cmd is a properly-qualified 'git for-each-repo' execution:
$cmd=$path/git --exec-path=$path for-each-repo --config=maintenance.repo
where $path points to the location of the Git executable running 'git
maintenance start'. This is critical for systems with multiple versions
of Git. Specifically, macOS has a system version at '/usr/bin/git' while
the version that users can install resides at '/usr/local/bin/git'
(symlinked to '/usr/local/libexec/git-core/git'). This will also use
your locally-built version if you build and run this in your development
environment without installing first.
This conditional schedule avoids having cron launch multiple 'git
for-each-repo' commands in parallel. Such parallel commands would likely
lead to the 'hourly' and 'daily' tasks competing over the object
database lock. This could lead to to some tasks never being run! Since
the --schedule=<frequency> argument will run all tasks with _at least_
the given frequency, the daily runs will also run the hourly tasks.
Similarly, the weekly runs will also run the daily and hourly tasks.
The GIT_TEST_CRONTAB environment variable is not intended for users to
edit, but instead as a way to mock the 'crontab [-l]' command. This
variable is set in test-lib.sh to avoid a future test from accidentally
running anything with the cron integration from modifying the user's
schedule. We use GIT_TEST_CRONTAB='test-tool crontab <file>' in our
tests to check how the schedule is modified in 'git maintenance
(start|stop)' commands.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 11 +++
Makefile | 1 +
builtin/gc.c | 124 ++++++++++++++++++++++++++++++
t/helper/test-crontab.c | 35 +++++++++
t/helper/test-tool.c | 1 +
t/helper/test-tool.h | 1 +
t/t7900-maintenance.sh | 28 +++++++
t/test-lib.sh | 6 ++
8 files changed, 207 insertions(+)
create mode 100644 t/helper/test-crontab.c
@@ -45,6 +45,17 @@ run:: config options are true. By default, only `maintenance.gc.enabled` is true.+start::+ Start running maintenance on the current repository. This performs+ the same config updates as the `register` subcommand, then updates+ the background scheduler to run `git maintenance run --scheduled`+ on an hourly basis.++stop::+ Halt the background maintenance schedule. The current repository+ is not removed from the list of maintained repositories, in case+ the background maintenance is restarted later.+ unregister:: Remove the current repository from background maintenance. This only removes the repository from the configured list. It does not
@@ -32,6 +32,7 @@#include"remote.h"#include"midx.h"#include"object-store.h"+#include"exec-cmd.h"#define FAILED_RUN "failed to run %s"
@@ -1456,6 +1457,125 @@ static int maintenance_unregister(void)returnrun_command(&config_unset);}+#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"+#define END_LINE "# END GIT MAINTENANCE SCHEDULE"++staticintupdate_background_schedule(intrun_maintenance)+{+intresult=0;+intin_old_region=0;+structchild_processcrontab_list=CHILD_PROCESS_INIT;+structchild_processcrontab_edit=CHILD_PROCESS_INIT;+FILE*cron_list,*cron_in;+constchar*crontab_name;+structstrbufline=STRBUF_INIT;+structlock_filelk;+char*lock_path=xstrfmt("%s/schedule",the_repository->objects->odb->path);++if(hold_lock_file_for_update(&lk,lock_path,LOCK_NO_DEREF)<0)+returnerror(_("another process is scheduling background maintenance"));++crontab_name=getenv("GIT_TEST_CRONTAB");+if(!crontab_name)+crontab_name="crontab";++strvec_split(&crontab_list.args,crontab_name);+strvec_push(&crontab_list.args,"-l");+crontab_list.in=-1;+crontab_list.out=dup(lk.tempfile->fd);+crontab_list.git_cmd=0;++if(start_command(&crontab_list)){+result=error(_("failed to run 'crontab -l'; your system might not support 'cron'"));+gotocleanup;+}++/* Ignore exit code, as an empty crontab will return error. */+finish_command(&crontab_list);++/*+*Readfromthe.lockfile,filteringouttheold+*schedulewhileappendingthenewschedule.+*/+cron_list=fdopen(lk.tempfile->fd,"r");+rewind(cron_list);++strvec_split(&crontab_edit.args,crontab_name);+crontab_edit.in=-1;+crontab_edit.git_cmd=0;++if(start_command(&crontab_edit)){+result=error(_("failed to run 'crontab'; your system might not support 'cron'"));+gotocleanup;+}++cron_in=fdopen(crontab_edit.in,"w");+if(!cron_in){+result=error(_("failed to open stdin of 'crontab'"));+gotodone_editing;+}++while(!strbuf_getline_lf(&line,cron_list)){+if(!in_old_region&&!strcmp(line.buf,BEGIN_LINE))+in_old_region=1;+if(in_old_region)+continue;+fprintf(cron_in,"%s\n",line.buf);+if(in_old_region&&!strcmp(line.buf,END_LINE))+in_old_region=0;+}++if(run_maintenance){+structstrbufline_format=STRBUF_INIT;+constchar*exec_path=git_exec_path();++fprintf(cron_in,"%s\n",BEGIN_LINE);+fprintf(cron_in,+"# The following schedule was created by Git\n");+fprintf(cron_in,"# Any edits made in this region might be\n");+fprintf(cron_in,+"# replaced in the future by a Git command.\n\n");++strbuf_addf(&line_format,+"%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",+exec_path,exec_path);+fprintf(cron_in,line_format.buf,"0","1-23","*","hourly");+fprintf(cron_in,line_format.buf,"0","0","1-6","daily");+fprintf(cron_in,line_format.buf,"0","0","0","weekly");+strbuf_release(&line_format);++fprintf(cron_in,"\n%s\n",END_LINE);+}++fflush(cron_in);+fclose(cron_in);+close(crontab_edit.in);++done_editing:+if(finish_command(&crontab_edit)){+result=error(_("'crontab' died"));+gotocleanup;+}+fclose(cron_list);++cleanup:+rollback_lock_file(&lk);+returnresult;+}++staticintmaintenance_start(void)+{+if(maintenance_register())+warning(_("failed to add repo to global config"));++returnupdate_background_schedule(1);+}++staticintmaintenance_stop(void)+{+returnupdate_background_schedule(0);+}+staticconstcharbuiltin_maintenance_usage[]=N_("git maintenance <subcommand> [<options>]");intcmd_maintenance(intargc,constchar**argv,constchar*prefix)
@@ -319,4 +319,32 @@ test_expect_success 'register and unregister' 'test_cmpbeforeactual'+test_expect_success'start from empty cron table''+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestart&&++# start registers the repo+gitconfig--get--globalmaintenance.repo"$(pwd)"&&++grep"for-each-repo --config=maintenance.repo maintenance run --schedule=daily"cron.txt&&+grep"for-each-repo --config=maintenance.repo maintenance run --schedule=hourly"cron.txt&&+grep"for-each-repo --config=maintenance.repo maintenance run --schedule=weekly"cron.txt+'++test_expect_success'stop from existing schedule''+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestop&&++# stop does not unregister the repo+gitconfig--get--globalmaintenance.repo"$(pwd)"&&++# Operation is idempotent+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestop&&+test_must_be_emptycron.txt+'++test_expect_success'start preserves existing schedule''+echo"Important information!">cron.txt&&+GIT_TEST_CRONTAB="test-tool crontab cron.txt"gitmaintenancestart&&+grep"Important information!"cron.txt+'+ test_done
@@ -1702,3 +1702,9 @@ test_lazy_prereq SHA1 ' test_lazy_prereqREBASE_P'test-z"$GIT_TEST_SKIP_REBASE_P"'++# Ensure that no test accidentally triggers a Git command+# that runs 'crontab', affecting a user's cron schedule.+# Tests that verify the cron integration must set this locally+# to avoid errors.+GIT_TEST_CRONTAB="exit 1"
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:45:54
From: Derrick Stolee <redacted>
The 'git maintenance (register|start)' subcommands add the current
repository to the global Git config so maintenance will operate on that
repository. It does not specify what maintenance should occur or how
often.
If a user sets any 'maintenance.<task>.schedule' config value, then
they have chosen a specific schedule for themselves and Git should
respect that.
However, in an effort to recommend a good schedule for repositories of
all sizes, set new config values for recommended tasks that are safe to
run in the background while users run foreground Git commands. These
commands are generally everything but the 'gc' task.
Author's Note: I feel we should do _something_ to recommend a good
schedule to users, but I'm not 100% set on this schedule. This is the
schedule we use in Scalar and VFS for Git for very large repositories
using the GVFS protocol. While the schedule works in that environment,
it is possible that "normal" Git repositories could benefit from
something more obvious (such as running 'gc' weekly). However, this
patch gives us a place to start a conversation on what we should
recommend. For my purposes, Scalar will set these config values so we
can always differ from core Git's recommendations.
Signed-off-by: Derrick Stolee <redacted>
---
Documentation/git-maintenance.txt | 6 ++++
builtin/gc.c | 46 +++++++++++++++++++++++++++++++
t/t7900-maintenance.sh | 16 +++++++++++
3 files changed, 68 insertions(+)
@@ -37,6 +37,12 @@ register:: `maintenance.<task>.schedule`. The tasks that are enabled are safe for running in the background without disrupting foreground processes.+++If your repository has no 'maintenance.<task>.schedule' configuration+values set, then Git will set configuration values to some recommended+settings. These settings disable foreground maintenance while performing+maintenance tasks in the background that will not interrupt foreground Git+operations. run:: Run one or more maintenance tasks. If one or more `--task` options
@@ -309,7 +309,23 @@ test_expect_success 'register and unregister' 'gitconfig--global--addmaintenance.repo/existing1&&gitconfig--global--addmaintenance.repo/existing2&&gitconfig--global--get-allmaintenance.repo>before&&++# We still have maintenance.<task>.schedule config set,+# so this does not update the local schedule+gitmaintenanceregister&&+test_must_failgitconfigmaintenance.auto&&++# Clear previous maintenance.<task>.schedule values+fortaskinloose-objectscommit-graphincremental-repack+do+gitconfig--unsetmaintenance.$task.schedule||return1+done&&gitmaintenanceregister&&+test_cmp_configfalsemaintenance.auto&&+test_cmp_configfalsemaintenance.gc.enabled&&+test_cmp_configtruemaintenance.prefetch.enabled&&+test_cmp_confighourlymaintenance.commit-graph.schedule&&+test_cmp_configdailymaintenance.incremental-repack.schedule&&gitconfig--global--get-allmaintenance.repo>actual&&cpbeforeafter&&pwd>>after&&
From: Derrick Stolee via GitGitGadget <hidden> Date: 2020-08-28 15:46:05
From: Derrick Stolee <redacted>
It can be helpful to store a list of repositories in global or system
config and then iterate Git commands on that list. Create a new builtin
that makes this process simple for experts. We will use this builtin to
run scheduled maintenance on all configured repositories in a future
change.
The test is very simple, but does highlight that the "--" argument is
optional.
Signed-off-by: Derrick Stolee <redacted>
---
.gitignore | 1 +
Documentation/git-for-each-repo.txt | 59 +++++++++++++++++++++++++++++
Makefile | 1 +
builtin.h | 1 +
builtin/for-each-repo.c | 58 ++++++++++++++++++++++++++++
command-list.txt | 1 +
git.c | 1 +
t/t0068-for-each-repo.sh | 30 +++++++++++++++
8 files changed, 152 insertions(+)
create mode 100644 Documentation/git-for-each-repo.txt
create mode 100644 builtin/for-each-repo.c
create mode 100755 t/t0068-for-each-repo.sh
@@ -0,0 +1,59 @@+git-for-each-repo(1)+====================++NAME+----+git-for-each-repo - Run a Git command on a list of repositories+++SYNOPSIS+--------+[verse]+'git for-each-repo' --config=<config> [--] <arguments>+++DESCRIPTION+-----------+Run a Git command on a list of repositories. The arguments after the+known options or `--` indicator are used as the arguments for the Git+subprocess.++THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.++For example, we could run maintenance on each of a list of repositories+stored in a `maintenance.repo` config variable using++-------------+git for-each-repo --config=maintenance.repo maintenance run+-------------++This will run `git -C <repo> maintenance run` for each value `<repo>`+in the multi-valued config variable `maintenance.repo`.+++OPTIONS+-------+--config=<config>::+ Use the given config variable as a multi-valued list storing+ absolute path names. Iterate on that list of paths to run+ the given arguments.+++These config values are loaded from system, global, and local Git config,+as available. If `git for-each-repo` is run in a directory that is not a+Git repository, then only the system and global config is used.+++SUBPROCESS BEHAVIOR+-------------------++If any `git -C <repo> <arguments>` subprocess returns a non-zero exit code,+then the `git for-each-repo` process returns that exit code without running+more subprocesses.++Each `git -C <repo> <arguments>` subprocess inherits the standard file+descriptors `stdin`, `stdout`, and `stderr`.+++GIT+---+Part of the linkgit:git[1] suite
@@ -0,0 +1,58 @@+#include"cache.h"+#include"config.h"+#include"builtin.h"+#include"parse-options.h"+#include"run-command.h"+#include"string-list.h"++staticconstchar*constfor_each_repo_usage[]={+N_("git for-each-repo --config=<config> <command-args>"),+NULL+};++staticintrun_command_on_repo(constchar*path,+void*cbdata)+{+inti;+structchild_processchild=CHILD_PROCESS_INIT;+structstrvec*args=(structstrvec*)cbdata;++child.git_cmd=1;+strvec_pushl(&child.args,"-C",path,NULL);++for(i=0;i<args->nr;i++)+strvec_push(&child.args,args->v[i]);++returnrun_command(&child);+}++intcmd_for_each_repo(intargc,constchar**argv,constchar*prefix)+{+staticconstchar*config_key=NULL;+inti,result=0;+conststructstring_list*values;+structstrvecargs=STRVEC_INIT;++conststructoptionoptions[]={+OPT_STRING(0,"config",&config_key,N_("config"),+N_("config key storing a list of repository paths")),+OPT_END()+};++argc=parse_options(argc,argv,prefix,options,for_each_repo_usage,+PARSE_OPT_STOP_AT_NON_OPTION);++if(!config_key)+die(_("missing --config=<config>"));++for(i=0;i<argc;i++)+strvec_push(&args,argv[i]);++values=repo_config_get_value_multi(the_repository,+config_key);++for(i=0;!result&&i<values->nr;i++)+result=run_command_on_repo(values->items[i].string,&args);++returnresult;+}
@@ -0,0 +1,30 @@+#!/bin/sh++test_description='git for-each-repo builtin'++../test-lib.sh++test_expect_success'run based on configured value''+gitinitone&&+gitinittwo&&+gitinitthree&&+git-Ctwocommit--allow-empty-m"DID NOT RUN"&&+gitconfigrun.key"$TRASH_DIRECTORY/one"&&+gitconfig--addrun.key"$TRASH_DIRECTORY/three"&&+gitfor-each-repo--config=run.keycommit--allow-empty-m"ran"&&+git-Conelog-1--pretty=format:%s>message&&+grepranmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepranmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepranmessage&&+gitfor-each-repo--config=run.key--commit--allow-empty-m"ran again"&&+git-Conelog-1--pretty=format:%s>message&&+grepagainmessage&&+git-Ctwolog-1--pretty=format:%s>message&&+!grepagainmessage&&+git-Cthreelog-1--pretty=format:%s>message&&+grepagainmessage+'++test_done