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