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