81ecdc5ffa5006391db7ec9c7585f19a4016d24f
   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 "repository.h"
  15#include "config.h"
  16#include "tempfile.h"
  17#include "lockfile.h"
  18#include "parse-options.h"
  19#include "run-command.h"
  20#include "sigchain.h"
  21#include "argv-array.h"
  22#include "commit.h"
  23#include "packfile.h"
  24#include "object-store.h"
  25
  26#define FAILED_RUN "failed to run %s"
  27
  28static const char * const builtin_gc_usage[] = {
  29        N_("git gc [<options>]"),
  30        NULL
  31};
  32
  33static int pack_refs = 1;
  34static int prune_reflogs = 1;
  35static int aggressive_depth = 50;
  36static int aggressive_window = 250;
  37static int gc_auto_threshold = 6700;
  38static int gc_auto_pack_limit = 50;
  39static int detach_auto = 1;
  40static timestamp_t gc_log_expire_time;
  41static const char *gc_log_expire = "1.day.ago";
  42static const char *prune_expire = "2.weeks.ago";
  43static const char *prune_worktrees_expire = "3.months.ago";
  44static unsigned long big_pack_threshold;
  45
  46static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
  47static struct argv_array reflog = ARGV_ARRAY_INIT;
  48static struct argv_array repack = ARGV_ARRAY_INIT;
  49static struct argv_array prune = ARGV_ARRAY_INIT;
  50static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
  51static struct argv_array rerere = ARGV_ARRAY_INIT;
  52
  53static struct tempfile *pidfile;
  54static struct lock_file log_lock;
  55
  56static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
  57
  58static void clean_pack_garbage(void)
  59{
  60        int i;
  61        for (i = 0; i < pack_garbage.nr; i++)
  62                unlink_or_warn(pack_garbage.items[i].string);
  63        string_list_clear(&pack_garbage, 0);
  64}
  65
  66static void report_pack_garbage(unsigned seen_bits, const char *path)
  67{
  68        if (seen_bits == PACKDIR_FILE_IDX)
  69                string_list_append(&pack_garbage, path);
  70}
  71
  72static void process_log_file(void)
  73{
  74        struct stat st;
  75        if (fstat(get_lock_file_fd(&log_lock), &st)) {
  76                /*
  77                 * Perhaps there was an i/o error or another
  78                 * unlikely situation.  Try to make a note of
  79                 * this in gc.log along with any existing
  80                 * messages.
  81                 */
  82                int saved_errno = errno;
  83                fprintf(stderr, _("Failed to fstat %s: %s"),
  84                        get_tempfile_path(log_lock.tempfile),
  85                        strerror(saved_errno));
  86                fflush(stderr);
  87                commit_lock_file(&log_lock);
  88                errno = saved_errno;
  89        } else if (st.st_size) {
  90                /* There was some error recorded in the lock file */
  91                commit_lock_file(&log_lock);
  92        } else {
  93                /* No error, clean up any old gc.log */
  94                unlink(git_path("gc.log"));
  95                rollback_lock_file(&log_lock);
  96        }
  97}
  98
  99static void process_log_file_at_exit(void)
 100{
 101        fflush(stderr);
 102        process_log_file();
 103}
 104
 105static void process_log_file_on_signal(int signo)
 106{
 107        process_log_file();
 108        sigchain_pop(signo);
 109        raise(signo);
 110}
 111
 112static void gc_config(void)
 113{
 114        const char *value;
 115
 116        if (!git_config_get_value("gc.packrefs", &value)) {
 117                if (value && !strcmp(value, "notbare"))
 118                        pack_refs = -1;
 119                else
 120                        pack_refs = git_config_bool("gc.packrefs", value);
 121        }
 122
 123        git_config_get_int("gc.aggressivewindow", &aggressive_window);
 124        git_config_get_int("gc.aggressivedepth", &aggressive_depth);
 125        git_config_get_int("gc.auto", &gc_auto_threshold);
 126        git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
 127        git_config_get_bool("gc.autodetach", &detach_auto);
 128        git_config_get_expiry("gc.pruneexpire", &prune_expire);
 129        git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
 130        git_config_get_expiry("gc.logexpiry", &gc_log_expire);
 131
 132        git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
 133
 134        git_config(git_default_config, NULL);
 135}
 136
 137static int too_many_loose_objects(void)
 138{
 139        /*
 140         * Quickly check if a "gc" is needed, by estimating how
 141         * many loose objects there are.  Because SHA-1 is evenly
 142         * distributed, we can check only one and get a reasonable
 143         * estimate.
 144         */
 145        DIR *dir;
 146        struct dirent *ent;
 147        int auto_threshold;
 148        int num_loose = 0;
 149        int needed = 0;
 150
 151        if (gc_auto_threshold <= 0)
 152                return 0;
 153
 154        dir = opendir(git_path("objects/17"));
 155        if (!dir)
 156                return 0;
 157
 158        auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
 159        while ((ent = readdir(dir)) != NULL) {
 160                if (strspn(ent->d_name, "0123456789abcdef") != 38 ||
 161                    ent->d_name[38] != '\0')
 162                        continue;
 163                if (++num_loose > auto_threshold) {
 164                        needed = 1;
 165                        break;
 166                }
 167        }
 168        closedir(dir);
 169        return needed;
 170}
 171
 172static void find_base_packs(struct string_list *packs, unsigned long limit)
 173{
 174        struct packed_git *p, *base = NULL;
 175
 176        for (p = get_packed_git(the_repository); p; p = p->next) {
 177                if (!p->pack_local)
 178                        continue;
 179                if (limit) {
 180                        if (p->pack_size >= limit)
 181                                string_list_append(packs, p->pack_name);
 182                } else if (!base || base->pack_size < p->pack_size) {
 183                        base = p;
 184                }
 185        }
 186
 187        if (base)
 188                string_list_append(packs, base->pack_name);
 189}
 190
 191static int too_many_packs(void)
 192{
 193        struct packed_git *p;
 194        int cnt;
 195
 196        if (gc_auto_pack_limit <= 0)
 197                return 0;
 198
 199        for (cnt = 0, p = get_packed_git(the_repository); p; p = p->next) {
 200                if (!p->pack_local)
 201                        continue;
 202                if (p->pack_keep)
 203                        continue;
 204                /*
 205                 * Perhaps check the size of the pack and count only
 206                 * very small ones here?
 207                 */
 208                cnt++;
 209        }
 210        return gc_auto_pack_limit < cnt;
 211}
 212
 213static int keep_one_pack(struct string_list_item *item, void *data)
 214{
 215        argv_array_pushf(&repack, "--keep-pack=%s", basename(item->string));
 216        return 0;
 217}
 218
 219static void add_repack_all_option(struct string_list *keep_pack)
 220{
 221        if (prune_expire && !strcmp(prune_expire, "now"))
 222                argv_array_push(&repack, "-a");
 223        else {
 224                argv_array_push(&repack, "-A");
 225                if (prune_expire)
 226                        argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
 227        }
 228
 229        if (keep_pack)
 230                for_each_string_list(keep_pack, keep_one_pack, NULL);
 231}
 232
 233static void add_repack_incremental_option(void)
 234{
 235       argv_array_push(&repack, "--no-write-bitmap-index");
 236}
 237
 238static int need_to_gc(void)
 239{
 240        /*
 241         * Setting gc.auto to 0 or negative can disable the
 242         * automatic gc.
 243         */
 244        if (gc_auto_threshold <= 0)
 245                return 0;
 246
 247        /*
 248         * If there are too many loose objects, but not too many
 249         * packs, we run "repack -d -l".  If there are too many packs,
 250         * we run "repack -A -d -l".  Otherwise we tell the caller
 251         * there is no need.
 252         */
 253        if (too_many_packs()) {
 254                struct string_list keep_pack = STRING_LIST_INIT_NODUP;
 255
 256                if (big_pack_threshold)
 257                        find_base_packs(&keep_pack, big_pack_threshold);
 258
 259                add_repack_all_option(&keep_pack);
 260                string_list_clear(&keep_pack, 0);
 261        } else if (too_many_loose_objects())
 262                add_repack_incremental_option();
 263        else
 264                return 0;
 265
 266        if (run_hook_le(NULL, "pre-auto-gc", NULL))
 267                return 0;
 268        return 1;
 269}
 270
 271/* return NULL on success, else hostname running the gc */
 272static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
 273{
 274        static struct lock_file lock;
 275        char my_host[HOST_NAME_MAX + 1];
 276        struct strbuf sb = STRBUF_INIT;
 277        struct stat st;
 278        uintmax_t pid;
 279        FILE *fp;
 280        int fd;
 281        char *pidfile_path;
 282
 283        if (is_tempfile_active(pidfile))
 284                /* already locked */
 285                return NULL;
 286
 287        if (xgethostname(my_host, sizeof(my_host)))
 288                xsnprintf(my_host, sizeof(my_host), "unknown");
 289
 290        pidfile_path = git_pathdup("gc.pid");
 291        fd = hold_lock_file_for_update(&lock, pidfile_path,
 292                                       LOCK_DIE_ON_ERROR);
 293        if (!force) {
 294                static char locking_host[HOST_NAME_MAX + 1];
 295                static char *scan_fmt;
 296                int should_exit;
 297
 298                if (!scan_fmt)
 299                        scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
 300                fp = fopen(pidfile_path, "r");
 301                memset(locking_host, 0, sizeof(locking_host));
 302                should_exit =
 303                        fp != NULL &&
 304                        !fstat(fileno(fp), &st) &&
 305                        /*
 306                         * 12 hour limit is very generous as gc should
 307                         * never take that long. On the other hand we
 308                         * don't really need a strict limit here,
 309                         * running gc --auto one day late is not a big
 310                         * problem. --force can be used in manual gc
 311                         * after the user verifies that no gc is
 312                         * running.
 313                         */
 314                        time(NULL) - st.st_mtime <= 12 * 3600 &&
 315                        fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
 316                        /* be gentle to concurrent "gc" on remote hosts */
 317                        (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
 318                if (fp != NULL)
 319                        fclose(fp);
 320                if (should_exit) {
 321                        if (fd >= 0)
 322                                rollback_lock_file(&lock);
 323                        *ret_pid = pid;
 324                        free(pidfile_path);
 325                        return locking_host;
 326                }
 327        }
 328
 329        strbuf_addf(&sb, "%"PRIuMAX" %s",
 330                    (uintmax_t) getpid(), my_host);
 331        write_in_full(fd, sb.buf, sb.len);
 332        strbuf_release(&sb);
 333        commit_lock_file(&lock);
 334        pidfile = register_tempfile(pidfile_path);
 335        free(pidfile_path);
 336        return NULL;
 337}
 338
 339static int report_last_gc_error(void)
 340{
 341        struct strbuf sb = STRBUF_INIT;
 342        int ret = 0;
 343        struct stat st;
 344        char *gc_log_path = git_pathdup("gc.log");
 345
 346        if (stat(gc_log_path, &st)) {
 347                if (errno == ENOENT)
 348                        goto done;
 349
 350                ret = error_errno(_("Can't stat %s"), gc_log_path);
 351                goto done;
 352        }
 353
 354        if (st.st_mtime < gc_log_expire_time)
 355                goto done;
 356
 357        ret = strbuf_read_file(&sb, gc_log_path, 0);
 358        if (ret > 0)
 359                ret = error(_("The last gc run reported the following. "
 360                               "Please correct the root cause\n"
 361                               "and remove %s.\n"
 362                               "Automatic cleanup will not be performed "
 363                               "until the file is removed.\n\n"
 364                               "%s"),
 365                            gc_log_path, sb.buf);
 366        strbuf_release(&sb);
 367done:
 368        free(gc_log_path);
 369        return ret;
 370}
 371
 372static int gc_before_repack(void)
 373{
 374        if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
 375                return error(FAILED_RUN, pack_refs_cmd.argv[0]);
 376
 377        if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
 378                return error(FAILED_RUN, reflog.argv[0]);
 379
 380        pack_refs = 0;
 381        prune_reflogs = 0;
 382        return 0;
 383}
 384
 385int cmd_gc(int argc, const char **argv, const char *prefix)
 386{
 387        int aggressive = 0;
 388        int auto_gc = 0;
 389        int quiet = 0;
 390        int force = 0;
 391        const char *name;
 392        pid_t pid;
 393        int daemonized = 0;
 394        int keep_base_pack = -1;
 395
 396        struct option builtin_gc_options[] = {
 397                OPT__QUIET(&quiet, N_("suppress progress reporting")),
 398                { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
 399                        N_("prune unreferenced objects"),
 400                        PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
 401                OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
 402                OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
 403                           PARSE_OPT_NOCOMPLETE),
 404                OPT_BOOL_F(0, "force", &force,
 405                           N_("force running gc even if there may be another gc running"),
 406                           PARSE_OPT_NOCOMPLETE),
 407                OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
 408                         N_("repack all other packs except the largest pack")),
 409                OPT_END()
 410        };
 411
 412        if (argc == 2 && !strcmp(argv[1], "-h"))
 413                usage_with_options(builtin_gc_usage, builtin_gc_options);
 414
 415        argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
 416        argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
 417        argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
 418        argv_array_pushl(&prune, "prune", "--expire", NULL);
 419        argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
 420        argv_array_pushl(&rerere, "rerere", "gc", NULL);
 421
 422        /* default expiry time, overwritten in gc_config */
 423        gc_config();
 424        if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
 425                die(_("Failed to parse gc.logexpiry value %s"), gc_log_expire);
 426
 427        if (pack_refs < 0)
 428                pack_refs = !is_bare_repository();
 429
 430        argc = parse_options(argc, argv, prefix, builtin_gc_options,
 431                             builtin_gc_usage, 0);
 432        if (argc > 0)
 433                usage_with_options(builtin_gc_usage, builtin_gc_options);
 434
 435        if (aggressive) {
 436                argv_array_push(&repack, "-f");
 437                if (aggressive_depth > 0)
 438                        argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
 439                if (aggressive_window > 0)
 440                        argv_array_pushf(&repack, "--window=%d", aggressive_window);
 441        }
 442        if (quiet)
 443                argv_array_push(&repack, "-q");
 444
 445        if (auto_gc) {
 446                /*
 447                 * Auto-gc should be least intrusive as possible.
 448                 */
 449                if (!need_to_gc())
 450                        return 0;
 451                if (!quiet) {
 452                        if (detach_auto)
 453                                fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
 454                        else
 455                                fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
 456                        fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
 457                }
 458                if (detach_auto) {
 459                        if (report_last_gc_error())
 460                                return -1;
 461
 462                        if (lock_repo_for_gc(force, &pid))
 463                                return 0;
 464                        if (gc_before_repack())
 465                                return -1;
 466                        delete_tempfile(&pidfile);
 467
 468                        /*
 469                         * failure to daemonize is ok, we'll continue
 470                         * in foreground
 471                         */
 472                        daemonized = !daemonize();
 473                }
 474        } else {
 475                struct string_list keep_pack = STRING_LIST_INIT_NODUP;
 476
 477                if (keep_base_pack != -1) {
 478                        if (keep_base_pack)
 479                                find_base_packs(&keep_pack, 0);
 480                } else if (big_pack_threshold) {
 481                        find_base_packs(&keep_pack, big_pack_threshold);
 482                }
 483
 484                add_repack_all_option(&keep_pack);
 485                string_list_clear(&keep_pack, 0);
 486        }
 487
 488        name = lock_repo_for_gc(force, &pid);
 489        if (name) {
 490                if (auto_gc)
 491                        return 0; /* be quiet on --auto */
 492                die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
 493                    name, (uintmax_t)pid);
 494        }
 495
 496        if (daemonized) {
 497                hold_lock_file_for_update(&log_lock,
 498                                          git_path("gc.log"),
 499                                          LOCK_DIE_ON_ERROR);
 500                dup2(get_lock_file_fd(&log_lock), 2);
 501                sigchain_push_common(process_log_file_on_signal);
 502                atexit(process_log_file_at_exit);
 503        }
 504
 505        if (gc_before_repack())
 506                return -1;
 507
 508        if (!repository_format_precious_objects) {
 509                if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
 510                        return error(FAILED_RUN, repack.argv[0]);
 511
 512                if (prune_expire) {
 513                        argv_array_push(&prune, prune_expire);
 514                        if (quiet)
 515                                argv_array_push(&prune, "--no-progress");
 516                        if (repository_format_partial_clone)
 517                                argv_array_push(&prune,
 518                                                "--exclude-promisor-objects");
 519                        if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
 520                                return error(FAILED_RUN, prune.argv[0]);
 521                }
 522        }
 523
 524        if (prune_worktrees_expire) {
 525                argv_array_push(&prune_worktrees, prune_worktrees_expire);
 526                if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
 527                        return error(FAILED_RUN, prune_worktrees.argv[0]);
 528        }
 529
 530        if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
 531                return error(FAILED_RUN, rerere.argv[0]);
 532
 533        report_garbage = report_pack_garbage;
 534        reprepare_packed_git(the_repository);
 535        if (pack_garbage.nr > 0)
 536                clean_pack_garbage();
 537
 538        if (auto_gc && too_many_loose_objects())
 539                warning(_("There are too many unreachable loose objects; "
 540                        "run 'git prune' to remove them."));
 541
 542        if (!daemonized)
 543                unlink(git_path("gc.log"));
 544
 545        return 0;
 546}