builtin / gc.con commit Merge branch 'jc/log-p-cc' (2ba6183)
   1/*
   2 * git gc builtin command
   3 *
   4 * Cleanup unreachable files and optimize the repository.
   5 *
   6 * Copyright (c) 2007 James Bowes
   7 *
   8 * Based on git-gc.sh, which is
   9 *
  10 * Copyright (c) 2006 Shawn O. Pearce
  11 */
  12
  13#include "builtin.h"
  14#include "tempfile.h"
  15#include "lockfile.h"
  16#include "parse-options.h"
  17#include "run-command.h"
  18#include "sigchain.h"
  19#include "argv-array.h"
  20#include "commit.h"
  21
  22#define FAILED_RUN "failed to run %s"
  23
  24static const char * const builtin_gc_usage[] = {
  25        N_("git gc [<options>]"),
  26        NULL
  27};
  28
  29static int pack_refs = 1;
  30static int prune_reflogs = 1;
  31static int aggressive_depth = 250;
  32static int aggressive_window = 250;
  33static int gc_auto_threshold = 6700;
  34static int gc_auto_pack_limit = 50;
  35static int detach_auto = 1;
  36static const char *prune_expire = "2.weeks.ago";
  37static const char *prune_worktrees_expire = "3.months.ago";
  38
  39static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
  40static struct argv_array reflog = ARGV_ARRAY_INIT;
  41static struct argv_array repack = ARGV_ARRAY_INIT;
  42static struct argv_array prune = ARGV_ARRAY_INIT;
  43static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
  44static struct argv_array rerere = ARGV_ARRAY_INIT;
  45
  46static struct tempfile pidfile;
  47
  48static void git_config_date_string(const char *key, const char **output)
  49{
  50        if (git_config_get_string_const(key, output))
  51                return;
  52        if (strcmp(*output, "now")) {
  53                unsigned long now = approxidate("now");
  54                if (approxidate(*output) >= now)
  55                        git_die_config(key, _("Invalid %s: '%s'"), key, *output);
  56        }
  57}
  58
  59static void gc_config(void)
  60{
  61        const char *value;
  62
  63        if (!git_config_get_value("gc.packrefs", &value)) {
  64                if (value && !strcmp(value, "notbare"))
  65                        pack_refs = -1;
  66                else
  67                        pack_refs = git_config_bool("gc.packrefs", value);
  68        }
  69
  70        git_config_get_int("gc.aggressivewindow", &aggressive_window);
  71        git_config_get_int("gc.aggressivedepth", &aggressive_depth);
  72        git_config_get_int("gc.auto", &gc_auto_threshold);
  73        git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
  74        git_config_get_bool("gc.autodetach", &detach_auto);
  75        git_config_date_string("gc.pruneexpire", &prune_expire);
  76        git_config_date_string("gc.worktreepruneexpire", &prune_worktrees_expire);
  77        git_config(git_default_config, NULL);
  78}
  79
  80static int too_many_loose_objects(void)
  81{
  82        /*
  83         * Quickly check if a "gc" is needed, by estimating how
  84         * many loose objects there are.  Because SHA-1 is evenly
  85         * distributed, we can check only one and get a reasonable
  86         * estimate.
  87         */
  88        char path[PATH_MAX];
  89        const char *objdir = get_object_directory();
  90        DIR *dir;
  91        struct dirent *ent;
  92        int auto_threshold;
  93        int num_loose = 0;
  94        int needed = 0;
  95
  96        if (gc_auto_threshold <= 0)
  97                return 0;
  98
  99        if (sizeof(path) <= snprintf(path, sizeof(path), "%s/17", objdir)) {
 100                warning(_("insanely long object directory %.*s"), 50, objdir);
 101                return 0;
 102        }
 103        dir = opendir(path);
 104        if (!dir)
 105                return 0;
 106
 107        auto_threshold = (gc_auto_threshold + 255) / 256;
 108        while ((ent = readdir(dir)) != NULL) {
 109                if (strspn(ent->d_name, "0123456789abcdef") != 38 ||
 110                    ent->d_name[38] != '\0')
 111                        continue;
 112                if (++num_loose > auto_threshold) {
 113                        needed = 1;
 114                        break;
 115                }
 116        }
 117        closedir(dir);
 118        return needed;
 119}
 120
 121static int too_many_packs(void)
 122{
 123        struct packed_git *p;
 124        int cnt;
 125
 126        if (gc_auto_pack_limit <= 0)
 127                return 0;
 128
 129        prepare_packed_git();
 130        for (cnt = 0, p = packed_git; p; p = p->next) {
 131                if (!p->pack_local)
 132                        continue;
 133                if (p->pack_keep)
 134                        continue;
 135                /*
 136                 * Perhaps check the size of the pack and count only
 137                 * very small ones here?
 138                 */
 139                cnt++;
 140        }
 141        return gc_auto_pack_limit <= cnt;
 142}
 143
 144static void add_repack_all_option(void)
 145{
 146        if (prune_expire && !strcmp(prune_expire, "now"))
 147                argv_array_push(&repack, "-a");
 148        else {
 149                argv_array_push(&repack, "-A");
 150                if (prune_expire)
 151                        argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
 152        }
 153}
 154
 155static int need_to_gc(void)
 156{
 157        /*
 158         * Setting gc.auto to 0 or negative can disable the
 159         * automatic gc.
 160         */
 161        if (gc_auto_threshold <= 0)
 162                return 0;
 163
 164        /*
 165         * If there are too many loose objects, but not too many
 166         * packs, we run "repack -d -l".  If there are too many packs,
 167         * we run "repack -A -d -l".  Otherwise we tell the caller
 168         * there is no need.
 169         */
 170        if (too_many_packs())
 171                add_repack_all_option();
 172        else if (!too_many_loose_objects())
 173                return 0;
 174
 175        if (run_hook_le(NULL, "pre-auto-gc", NULL))
 176                return 0;
 177        return 1;
 178}
 179
 180/* return NULL on success, else hostname running the gc */
 181static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
 182{
 183        static struct lock_file lock;
 184        char my_host[128];
 185        struct strbuf sb = STRBUF_INIT;
 186        struct stat st;
 187        uintmax_t pid;
 188        FILE *fp;
 189        int fd;
 190        char *pidfile_path;
 191
 192        if (is_tempfile_active(&pidfile))
 193                /* already locked */
 194                return NULL;
 195
 196        if (gethostname(my_host, sizeof(my_host)))
 197                strcpy(my_host, "unknown");
 198
 199        pidfile_path = git_pathdup("gc.pid");
 200        fd = hold_lock_file_for_update(&lock, pidfile_path,
 201                                       LOCK_DIE_ON_ERROR);
 202        if (!force) {
 203                static char locking_host[128];
 204                int should_exit;
 205                fp = fopen(pidfile_path, "r");
 206                memset(locking_host, 0, sizeof(locking_host));
 207                should_exit =
 208                        fp != NULL &&
 209                        !fstat(fileno(fp), &st) &&
 210                        /*
 211                         * 12 hour limit is very generous as gc should
 212                         * never take that long. On the other hand we
 213                         * don't really need a strict limit here,
 214                         * running gc --auto one day late is not a big
 215                         * problem. --force can be used in manual gc
 216                         * after the user verifies that no gc is
 217                         * running.
 218                         */
 219                        time(NULL) - st.st_mtime <= 12 * 3600 &&
 220                        fscanf(fp, "%"PRIuMAX" %127c", &pid, locking_host) == 2 &&
 221                        /* be gentle to concurrent "gc" on remote hosts */
 222                        (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
 223                if (fp != NULL)
 224                        fclose(fp);
 225                if (should_exit) {
 226                        if (fd >= 0)
 227                                rollback_lock_file(&lock);
 228                        *ret_pid = pid;
 229                        free(pidfile_path);
 230                        return locking_host;
 231                }
 232        }
 233
 234        strbuf_addf(&sb, "%"PRIuMAX" %s",
 235                    (uintmax_t) getpid(), my_host);
 236        write_in_full(fd, sb.buf, sb.len);
 237        strbuf_release(&sb);
 238        commit_lock_file(&lock);
 239        register_tempfile(&pidfile, pidfile_path);
 240        free(pidfile_path);
 241        return NULL;
 242}
 243
 244static int gc_before_repack(void)
 245{
 246        if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
 247                return error(FAILED_RUN, pack_refs_cmd.argv[0]);
 248
 249        if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
 250                return error(FAILED_RUN, reflog.argv[0]);
 251
 252        pack_refs = 0;
 253        prune_reflogs = 0;
 254        return 0;
 255}
 256
 257int cmd_gc(int argc, const char **argv, const char *prefix)
 258{
 259        int aggressive = 0;
 260        int auto_gc = 0;
 261        int quiet = 0;
 262        int force = 0;
 263        const char *name;
 264        pid_t pid;
 265
 266        struct option builtin_gc_options[] = {
 267                OPT__QUIET(&quiet, N_("suppress progress reporting")),
 268                { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
 269                        N_("prune unreferenced objects"),
 270                        PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
 271                OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
 272                OPT_BOOL(0, "auto", &auto_gc, N_("enable auto-gc mode")),
 273                OPT_BOOL(0, "force", &force, N_("force running gc even if there may be another gc running")),
 274                OPT_END()
 275        };
 276
 277        if (argc == 2 && !strcmp(argv[1], "-h"))
 278                usage_with_options(builtin_gc_usage, builtin_gc_options);
 279
 280        argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
 281        argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
 282        argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
 283        argv_array_pushl(&prune, "prune", "--expire", NULL);
 284        argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
 285        argv_array_pushl(&rerere, "rerere", "gc", NULL);
 286
 287        gc_config();
 288
 289        if (pack_refs < 0)
 290                pack_refs = !is_bare_repository();
 291
 292        argc = parse_options(argc, argv, prefix, builtin_gc_options,
 293                             builtin_gc_usage, 0);
 294        if (argc > 0)
 295                usage_with_options(builtin_gc_usage, builtin_gc_options);
 296
 297        if (aggressive) {
 298                argv_array_push(&repack, "-f");
 299                if (aggressive_depth > 0)
 300                        argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
 301                if (aggressive_window > 0)
 302                        argv_array_pushf(&repack, "--window=%d", aggressive_window);
 303        }
 304        if (quiet)
 305                argv_array_push(&repack, "-q");
 306
 307        if (auto_gc) {
 308                /*
 309                 * Auto-gc should be least intrusive as possible.
 310                 */
 311                if (!need_to_gc())
 312                        return 0;
 313                if (!quiet) {
 314                        if (detach_auto)
 315                                fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
 316                        else
 317                                fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
 318                        fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
 319                }
 320                if (detach_auto) {
 321                        if (gc_before_repack())
 322                                return -1;
 323                        /*
 324                         * failure to daemonize is ok, we'll continue
 325                         * in foreground
 326                         */
 327                        daemonize();
 328                }
 329        } else
 330                add_repack_all_option();
 331
 332        name = lock_repo_for_gc(force, &pid);
 333        if (name) {
 334                if (auto_gc)
 335                        return 0; /* be quiet on --auto */
 336                die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
 337                    name, (uintmax_t)pid);
 338        }
 339
 340        if (gc_before_repack())
 341                return -1;
 342
 343        if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
 344                return error(FAILED_RUN, repack.argv[0]);
 345
 346        if (prune_expire) {
 347                argv_array_push(&prune, prune_expire);
 348                if (quiet)
 349                        argv_array_push(&prune, "--no-progress");
 350                if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
 351                        return error(FAILED_RUN, prune.argv[0]);
 352        }
 353
 354        if (prune_worktrees_expire) {
 355                argv_array_push(&prune_worktrees, prune_worktrees_expire);
 356                if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
 357                        return error(FAILED_RUN, prune_worktrees.argv[0]);
 358        }
 359
 360        if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
 361                return error(FAILED_RUN, rerere.argv[0]);
 362
 363        if (auto_gc && too_many_loose_objects())
 364                warning(_("There are too many unreachable loose objects; "
 365                        "run 'git prune' to remove them."));
 366
 367        return 0;
 368}