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