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