gc.sh: do not always ignore non pack-<40hex>*.pack files
[girocco/readme.git] / jobd / gc.sh
blob554721fd45e02fafb65c95e2ca0fafd748218a58
1 #!/bin/sh
3 # NOTE: additional options can be passed to git repack by specifying
4 # them after the project name, for example:
5 # gc.sh my-project -f
7 . @basedir@/shlib.sh
9 set -e
11 if [ $# -lt 1 ]; then
12 echo "Usage: gc.sh projname [extra-repack-args]" >&2
13 exit 1
16 # Includes
17 _shlib_done=1
18 unset GIROCCO_SUPPRESS_AUTO_GC_UPDATE
19 . "$cfg_basedir/jobd/maintain-auto-gc-hack.sh"
20 . "$cfg_basedir/jobd/generate-auto-gc-update.sh"
21 GIROCCO_SUPPRESS_AUTO_GC_UPDATE=1 && export GIROCCO_SUPPRESS_AUTO_GC_UPDATE
23 # packing options
24 packopts="--depth=50 --window=50 --window-memory=${var_window_memory:-1g}"
25 quiet=; [ -n "$show_progress" ] || quiet=-q
27 umask 002
28 [ "$cfg_permission_control" != "Hooks" ] || umask 000
29 clean_git_env
31 pidactive() {
32 if _result="$(kill -0 "$1" 2>&1)"; then
33 # process exists and we have permission to signal it
34 return 0
36 case "$_result" in *"not permitted"*)
37 # we do not have permission to signal the process
38 return 0
39 esac
40 # process does not exist
41 return 1
44 createlock() {
45 # A .lock file should only exist for much less than a second.
46 # If we see a stale lock file (> 1h old), remove it and then,
47 # just in case, wait 30 seconds for any process whose .lock
48 # we might have just removed (it's racy) to finish doing what
49 # should take much less than a second to do.
50 _stalelock="$(find -L "$1.lock" -maxdepth 1 -mmin +60 -print 2>/dev/null)" || :
51 if [ -n "$_stalelock" ]; then
52 rm -f "$_stalelock"
53 sleep 30
55 for _try in p p n; do
56 if (set -C; >"$1.lock") 2>/dev/null; then
57 echo "$1.lock"
58 return 0
60 # delay and try again
61 [ "$_try" != "p" ] || sleep 1
62 done
63 # cannot create lock file
64 return 1
67 # The pre-receive script creates one ref log file per push but we want them to
68 # be coalesced into one ref log file per day. We are guaranteed that any files
69 # we find to coalesce are NOT currently being written to since they are always
70 # written first as temporary files and then moved into place. We attempt to
71 # transfer the most recent modification time to the coalesced log file which
72 # would step on its mod time if it were being written to directly, but if we
73 # find per-process ref log files then it must be a push project and the only
74 # thing that would write directly to the main per-day log file would be a
75 # mirror project so there's actually no conflict.
76 # Also, if the clock is wonky (or was futzed with) we may have both YYYYMMDD
77 # and YYYYMMDD.gz present in which case combine them into YYYYMMDD
78 coalesce_reflogs() {
79 [ -d reflogs ] || return 0
80 rm -f .gc_failed
81 find -L reflogs -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -print |
82 while read -r rname; do
83 if [ -e "$rname.gz" ]; then
84 if [ -s "$rname" ]; then
85 # Presumably the .gz file must have been created before the non-gz
86 # file since it had to be uncompressed at some point therefore
87 # we need to append the non-gz contents to it but keep the non-gz
88 # contents timestamp so we rename to YYYYMMDD_ which will sort first
89 # and be picked up in the next step if we are interrupted in the middle.
90 # If a YYYYMMDD_ file already exists we append to it and transfer the
91 # timestamp. Finally we transfer the YYYYMMDD_ timestamp to the result
92 # and remove the YYYYMMDD_ temporary file leaving the result uncompressed.
93 if [ -e "${rname}_" ]; then
94 cat "$rname" >>"${rname}_"
95 touch -r "$rname" "${rname}_"
96 rm -f "$rname"
97 ! [ -e "$rname" ]
98 else
99 mv "$rname" "${rname}_"
101 gzip -d "$rname.gz" </dev/null
102 [ -e "$rname" ] && ! [ -e "$rname.gz" ]
103 cat "${rname}_" >>"$rname"
104 touch -r "${rname}_" "$rname"
105 rm -f "${rname}_"
106 else
107 # Just remove the empty file to resolve the problem
108 rm -f "$rname"
111 done
112 find -L reflogs -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_*" -print | LC_ALL=C sort |
113 while read -r rname; do
114 logname="${rname%%_*}"
115 # If someone's been futzing with the date, the file we want to
116 # append to could already have been compressed, so we just uncompress
117 # it here. The previous block guarantees we do not have both a compressed
118 # and uncompressed version present at the same time.
119 if [ -e "$logname.gz" ]; then
120 gzip -d "$logname.gz" </dev/null
121 [ -e "$logname" ] && ! [ -e "$logname.gz" ]
123 cat "$rname" >>"$logname"
124 touch -r "$rname" "$logname"
125 rm -f "$rname"
126 if [ -e "$rname" ]; then
127 >.gc_failed
128 echo "! [$proj] failed to remove $rname" >&2
129 exit 1 # will only exit subshell created by "|"
131 done
132 ! [ -e .gc_failed ]
135 # Remove any files in reflogs that are older than $cfg_reflogs_lifetime days
136 prune_reflogs() {
137 [ -d reflogs ] || return 0
138 exp="$(( ${cfg_reflogs_lifetime:-1} * 1440 ))"
139 [ $exp -gt 0 ] || exp=1440
140 [ $exp -le 43200 ] || exp=43200
141 find -L reflogs -maxdepth 1 -type f -mmin "+$exp" -exec rm -f '{}' + || :
144 # Compact any reflogs that are not today's UTC date unless a .gz version exists
145 compact_reflogs() {
146 [ -d reflogs ] || return 0
147 _td="reflogs/$(TZ=UTC date '+%Y%m%d')"
148 find -L reflogs -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -print |
149 while read -r rname; do
150 [ "$rname" != "$_td" ] || continue
151 ! [ -e "$rname.gz" ] || continue
152 gzip -9 "$rname" </dev/null
153 done
156 # return true if there's more than one objects/pack-<sha>.pack file or
157 # ANY sha-1 files in objects
158 is_dirty() {
159 _packs=$(find -L objects/pack -type f -name "pack-$octet20*.pack" -print | head -n 2 | LC_ALL=C wc -l)
160 if [ $_packs != 1 ] && [ $_packs != 0 ]; then
161 return 0
163 _objs=$(find -L objects/$octet -type f -name "$octet19*" -print 2>/dev/null | head -n 1 | LC_ALL=C wc -l)
164 [ $_objs -ne 0 ]
167 # make sure combine-packs uses the correct Git executable
168 run_combine_packs() {
169 PATH="$var_git_exec_path:$cfg_basedir/bin:$PATH" @basedir@/jobd/combine-packs.sh "$@"
172 # rename_pack oldnamepath newnamepath
173 # note that .keep and .bndl files are left untouched and not moved at all!
174 rename_pack() {
175 [ $# -eq 2 ] && [ "$1" != "$2" ] || {
176 echo >&2 "[$proj] incorrect use of rename_pack function"
177 exit 1
179 # Git assumes that if the destination of the rename already exists
180 # that it is, in fact, a copy of the same bytes so silently succeeds
181 # without doing anything. We duplicate that logic here.
182 # Git checks for the .idx file first before even trying to use a pack
183 # so it should be the last moved and the first removed.
184 for ext in pack bitmap idx; do
185 [ -f "$1.$ext" ] || continue
186 ln "$1.$ext" "$2.$ext" >/dev/null 2>&1 ||
187 [ -f "$2.$ext" ] || {
188 echo >&2 "[$proj] unable to move $1.$ext to $2.$ext"
189 exit 1
191 done
192 for ext in idx pack bitmap; do
193 rm -f "$1.$ext"
194 done
195 return 0
198 # combine the input pack(s) into a new pack (or possibly packs if packSizeLimit set)
199 # input pack names are read from standard input one per line delimited by the first
200 # ':', ' ' or '\n' character on the line (which allows gfi-packs to be read directly)
201 # all arguments, if any, are passed to pack-objects as additional options
202 # returns non-zero on failure AND creates .gc_failed in that case
203 combine_packs() {
204 rm -f .gc_failed
205 find -L objects/pack -maxdepth 1 -type f -name '*.zap*' -exec rm -f '{}' + || :
206 run_combine_packs --replace "$@" $packopts --all-progress-implied $quiet --non-empty || {
207 >.gc_failed
208 return 1
210 return 0
213 # if the current directory is_gfi_mirror then repack all packs listed in gfi-packs
214 repack_gfi_packs() {
215 [ -n "$gfi_mirror" ] || return 0
216 [ -d objects/pack ] || { rm -f gfi-packs; return 0; }
217 progress "~ [$proj] redeltifying poor quality git fast-import packs"
218 combine_packs --ignore-missing --no-reuse-delta <gfi-packs
219 rm -f gfi-packs
220 return 0
223 # combine small packs into larger pack(s)
224 # we avoid any keep, bndl or bitmap packs
225 # if the optional argument is non-empty even a single small pack will be redeltad
226 combine_small_packs() {
227 _didprogress=
228 _minsmallpacks=2
229 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
230 _minsmallpacks=1
232 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
233 _lpo="$_lpo --exclude-sfx _u --exclude-sfx _o"
234 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
235 while
236 _cnt="$(list_packs --count $_lpo)" || :
237 test "${_cnt:-0}" -ge $_minsmallpacks
239 [ -n "$_didprogress" ] || {
240 progress "~ [$proj] combining small packs into a single larger pack"
241 _didprogress=1
243 _newp="$(list_packs $_lpo | combine_packs --names $noreusedeltaopt)"
244 _newc="$(( $(echo "$_newp" | LC_ALL=C wc -w) ))"
245 # be paranoid and exit the loop if we haven't reduced the number of packs
246 [ $_newc -lt $_cnt ] || break
247 _minsmallpacks=2
248 done
249 return 0
252 # Unfortunately git-svn lacks the ability to store newly fetched revisions as a pack.
253 # However, the fetch code conveniently sets .svnpack just before it runs git-svn fetch
254 # so that it's easy to find all the objects that have been fetched by git-svn and
255 # combine them into a pack. The --no-reuse-delta option is meaningless here since
256 # everything to be packed is a loose object and therefore not a delta so deltification
257 # will always take place.
258 make_svn_pack() {
259 [ -f .svnpack ] && [ -n "$svn_mirror" ] || return 0
260 rm -f .svnpackgc
261 mv -f .svnpack .svnpackgc
262 progress "~ [$proj] combining loose git-svn objects into a pack"
263 _newp="$(find -L objects/$octet -maxdepth 1 -type f -newer .svnpackgc -name "$octet19*" -print 2>/dev/null |
264 LC_ALL=C awk -F / '{print $2 $3}' |
265 run_combine_packs --objects --names $packopts --incremental --all-progress-implied $quiet --non-empty)" || {
266 mv -f .svnpackgc .svnpack
267 >.gc_failed
268 return 1
270 if [ -n "$_newp" ]; then
271 # remove the now-redundant loose objects -- this is always safe
272 # even during a concurrent push because a reprepare_packed_git
273 # will be triggered if an object that should be there is not
274 # found thereby finding it in the new pack instead
275 git prune-packed $quiet
277 rm -f .svnpackgc
280 # HEADSHA="$(pack_is_complete /full/path/to/some.pack /full/path/to/packed-refs "$(cat HEAD)")"
281 pack_is_complete() {
282 # Must have a matching .idx file and a non-empty packed-refs file
283 [ -s "${1%.pack}.idx" ] || return 1
284 [ -s "$2" ] || return 1
285 _headsha=
286 case "$3" in
287 $octet20*)
288 _headsha="$3"
290 "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
291 _headmatch="${3#ref:}"
292 _headmatch="${_headmatch# }"
293 _headmatchpat="$(echo "$_headmatch" | LC_ALL=C sed -e 's/\([.$]\)/\\\1/g')"
294 _headsha="$(LC_ALL=C grep -e "^$octet20$hexdig* $_headmatchpat\$" <"$2" |
295 LC_ALL=C cut -d ' ' -f 1)"
296 case "$_headsha" in $octet20*) :;; *)
297 return 1
298 esac
301 # bad HEAD
302 return 1
303 esac
304 rm -rf pack_is_complete_test
305 mkdir pack_is_complete_test
306 mkdir pack_is_complete_test/refs
307 mkdir pack_is_complete_test/objects
308 mkdir pack_is_complete_test/objects/pack
309 echo "$_headsha" >pack_is_complete_test/HEAD
310 ln -s "$1" pack_is_complete_test/objects/pack/
311 ln -s "${1%.pack}.idx" pack_is_complete_test/objects/pack/
312 ln -s "$2" pack_is_complete_test/packed-refs
313 _count="$(git --git-dir=pack_is_complete_test rev-list --count --all 2>/dev/null)" || :
314 rm -rf pack_is_complete_test
315 [ -n "$_count" ] || return 1
316 [ "$_count" -gt 0 ] 2>/dev/null || return 1
317 echo "$_headsha"
320 # On return a "$lockf" will have been created that must be removed when gc is done
321 lock_gc() {
322 # be compatibile with gc.pid file from newer Git releases
323 lockf=gc.pid
324 hn="$(hostname)"
325 active=
326 if [ "$(createlock "$lockf")" ]; then
327 # If $lockf is:
328 # 1) less than 12 hours old
329 # 2) contains two fields (pid hostname) NO trailing NL
330 # 3) the hostname is different OR the pid is still alive
331 # then we exit as another active process is holding the lock
332 if [ "$(find -L "$lockf" -maxdepth 1 -mmin -720 -print 2>/dev/null)" ]; then
333 apid=
334 ahost=
335 read -r apid ahost ajunk <"$lockf" || :
336 if [ "$apid" ] && [ "$ahost" ]; then
337 if [ "$ahost" != "$hn" ] || pidactive "$apid"; then
338 active=1
342 else
343 echo >&2 "[$proj] unable to create gc.pid.lock file"
344 exit 1
346 if [ -n "$active" ]; then
347 rm -f "$lockf.lock"
348 echo >&2 "[$proj] gc already running on machine '$ahost' pid '$apid'"
349 exit 1
351 printf "%s %s" "$$" "$hn" >"$lockf.lock"
352 chmod 0664 "$lockf.lock"
353 mv -f "$lockf.lock" "$lockf"
356 # Create a repack subdirectory such that running repack in it will pack the
357 # same things that a pack in the normal directory would except that the pack
358 # is guaranteed to be generated in an optimized order by adding a suitable
359 # synthesized ref in the refs/tags namespace (yes, pack-objects.c really does
360 # behave differently depending on the contents of the refs/tags namespace).
361 # Before calling this, pack-refs --all MUST be performed or the wrong pack
362 # will end up being made.
364 # If a ref deletion is pushed after making the repack subdir but before the
365 # the actual repack, the discarded objects will be packed -- no big deal,
366 # they'll get discarded the next time gc runs.
368 # If a fast-forward ref update is pushed after making the repack subdir but
369 # before the actual repack, it will be picked up and the new objects packed
370 # (subject to the normal git repack race about picking such updates up).
372 # If a non-fast-forward ref update is pushed after making the repack subdir but
373 # before the actual repack, it will be picked up like a fast-forward update but
374 # the discarded objects will be included like a ref deletion (until the next
375 # scheduled gc takes place).
377 # We retain a copy of the original packed-refs file as repack/packed-refs.orig
378 # If ref deletions come in while we're repacking, the original packed-refs
379 # file will be modified, but we'll still pack the deleted ref(s).
380 # If the packed-refs.orig file is used to create the bundle header we avoid
381 # a situation where the bundle contains a ref state that never actually
382 # existed in reality (for example a new branch is pushed and then an old
383 # branch deleted afterwards -- the deletion would show up in the bundle
384 # because it will cause the original packed-refs file to be re-written, but
385 # the new branch creation will not unless we do another pack-refs which might
386 # lead to having in incomplete bundle). Therefore we want to keep a copy of
387 # the original packed-refs file around. We do the same thing for HEAD.
389 # It's possible that the "objects" subdirectory is a symbolic link.
390 # Git does support this. However, during the repacking process, new packs
391 # will be created in repack/alt/pack and then moved into objects/pack.
392 # In order for this to work seemlessly, they must both be on the same
393 # filesystem. But when objects (or even objects/pack) is a symbolic link they
394 # might not be. For this reason a "repack" subdirectory is created under
395 # objects/pack and the repack/alt/pack directory symbolicly linked to it.
397 # Git allows not just HEAD to be a symbolic-ref, but any ref anywhere in the
398 # refs namespace. We are concerned about ref name collisions and getting the
399 # right tag set to get an optimal pack. We can safely duplicate the ref space
400 # under refs/heads, refs/notes and refs/remotes without any risk of unwanted
401 # collisions and this will likely make over 99%+ of all symbolic refs found
402 # in the wild work properly. Girocco itself never creates any symbolic refs
403 # inside the refs namespace; this is a nod to simultaneously using a Girocco
404 # repository for other purposes.
405 make_repack_dir() {
406 ! [ -d repack ] || rm -rf repack
407 ! [ -d repack ] || { echo >&2 "[$proj] cannot remove repack subdirectory"; exit 1; }
408 [ -d objects/pack ] || mkdir -p objects/pack
409 ! [ -d objects/pack/repack ] || rm -rf objects/pack/repack
410 ! [ -d objects/pack/repack ] || { echo >&2 "[$proj] cannot remove objects/pack/repack subdirectory"; exit 1; }
411 mkdir repack repack/refs repack/alt objects/pack/repack
412 [ -d info ] || mkdir info
413 ln -s ../config repack/config
414 ln -s ../info repack/info
415 ln -s ../objects repack/objects
416 ln -s "$PWD/objects/pack/repack" repack/alt/pack
417 ln -s ../../refs repack/refs/refs
418 _lines=$(( $(LC_ALL=C wc -l <packed-refs) ))
419 cat HEAD >repack/HEAD.orig
420 cat packed-refs >repack/packed-refs.orig
421 if [ $(LC_ALL=C wc -l <repack/packed-refs.orig) -ne "$_lines" ]; then
422 echo >&2 "[$proj] error: make_repack_dir failed original packed-refs line count sanity check"
423 exit 1
425 # Note: Git v1.5.0 introduced the "# pack-refs with:" header line for the packed-refs file
426 sed '/^# pack-refs/d; s, refs/, refs/!/,' <repack/packed-refs.orig >repack/packed-refs
427 nohead=
428 headref="$(git rev-parse --verify --quiet HEAD)" || :
429 if [ -n "$headref" ]; then
430 echo "$headref refs/!=/HEAD" >>repack/packed-refs
431 echo "$headref refs/heads/!" >>repack/packed-refs
432 nohead='\, refs/heads/!$,d; '
433 _lines=$(( $_lines + 2 ))
435 if [ $(( $(LC_ALL=C wc -l <repack/packed-refs) + 1 )) -ne "$_lines" ]; then
436 echo >&2 "[$proj] error: make_repack_dir failed packed-refs initial line count sanity check"
437 exit 1
439 sed -n "$nohead"'\, refs/heads/,p; \, refs/notes/,p; \, refs/remotes/,p' <repack/packed-refs.orig >>repack/packed-refs
440 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs) ))"
441 if [ $(( $_newlines + 1 )) -lt "$_lines" ]; then
442 echo >&2 "[$proj] error: make_repack_dir failed packed-refs extra line count sanity check"
443 exit 1
445 _lines="$_newlines"
446 optref="$(git rev-list -n 1 --all 2>/dev/null)" || :
447 if [ -n "$optref" ]; then
448 echo "$optref refs/tags/!" >>repack/packed-refs
449 _lines=$(( $_lines + 1 ))
450 echo "$optref" >repack/HEAD
451 else
452 cat HEAD >repack/HEAD
454 if [ $(LC_ALL=C wc -l <repack/packed-refs) -ne "$_lines" ]; then
455 echo >&2 "[$proj] error: make_repack_dir failed packed-refs line count sanity check"
456 exit 1
460 # Remove any crud that's been left behind by interrupted operations
461 # that did not clean up after themselves
462 remove_crud() {
463 # Remove any existing FETCH_HEAD
464 # There can only be a FETCH_HEAD if we've been fetching, not if we've been
465 # receiving pushes (those never create a FETCH_HEAD).
466 # And if we're fetching because we're a mirror, we know we're not fetching right
467 # now since jobd.pl never runs a project's fetch simultaneously with its gc.
468 # Therefore any existing FETCH_HEAD is junk. And it may be many megabytes if
469 # there were a lot of refs.
470 rm -f FETCH_HEAD
472 # remove any existing pack_is_complete_test or repack subdirectories
473 # If either exists when this function is called it's crud
474 rm -rf pack_is_complete_test repack objects/pack/repack
476 # Remove any stale pack remnants that are more than an hour old.
477 # Stale pack fragments are defined as any pack-<sha1>.ext where .ext is NOT
478 # .pack AND the corresponding .pack DOES NOT exist. A bunch of stale
479 # pack-<sha1>.idx files without their corresponding .pack files are worthless
480 # and just waste space. Normally there shouldn't be any remnants but actually
481 # this can happen when things are interrupted at just the wrong time.
482 # Note that the objects/pack directory is created by git init and should
483 # always exist.
484 find -L objects/pack -maxdepth 1 -type f -mmin +60 -name "pack-$octet20*.?*" -print |
485 LC_ALL=C sed -e 's/^objects\/pack\/pack-//; s/\..*$//' | LC_ALL=C sort -u |
486 while read packsha; do
487 ! [ -e "objects/pack/pack-$packsha.pack" ] || continue
488 rm -f "objects/pack/pack-$packsha".?*
489 done
491 # Remove any stale tmp reflogs files that are more than one hour old.
492 # Since they are created only while the pre-receive hook is running and
493 # all it does is process a bunch of refs passed to it on standard input
494 # it's inconceivable that it would ever take as much as an hour to run.
495 if [ -d reflogs ]; then
496 find -L reflogs -maxdepth 1 -type f -mmin +60 -name "tmp_*" -exec rm -f '{}' + || :
499 # Remove any stale object tmp_obj_* files that are more than 3 hours old.
500 # Really these files should only exist very briefly so there shouldn't be any
501 # but things happen that can end up leaving them behind.
502 find -L objects/$octet -maxdepth 1 -type f -mmin +180 -name "tmp_obj_?*" -exec rm -f '{}' + 2>/dev/null || :
504 # Remove any stale pack .keep files that are more than 12 hours old.
505 # We don't do anything to create any permanent pack .keep files, so they must
506 # be remnants from some failed push or something. Removing the .keep will
507 # allow the pack to be properly repacked.
508 find -L objects/pack -maxdepth 1 -type f -mmin +720 -name "pack-$octet20*.keep" -exec rm -f '{}' + || :
510 # Remove any stale tmp_pack_*, tmp_idx_*, tmp_bitmap_*, packtmp-* or .tmp-*-pack* files
511 # that are more than 12 hours old.
512 find -L objects/pack -maxdepth 1 -type f -mmin +720 \( \
513 -name "tmp_pack_?*" -o -name "tmp_idx_?*" -o -name "tmp_bitmap_?*" -o \
514 -name "packtmp-?*" -o -name ".tmp-?*-pack*" \
515 \) -exec rm -f '{}' + || :
517 # Remove any stale incoming-* object quarantine directories that are
518 # more than 12 hours old. These are new with Git >= 2.11.0.
519 find -L objects -maxdepth 1 -type d -name 'incoming-?*' -mmin +720 \
520 -exec rm -rf '{}' + || :
522 # Remove any stale shallow_* files that are more than 12 hours old.
523 # These can be left behind by Git >= 1.8.4.2 and < 2.0.0 when a client
524 # requests a shallow clone. Also discard stale .refs-temp* and
525 # .refs-new* files at the same time.
526 find -L . -maxdepth 1 -type f -mmin +720 \( \
527 -name "shallow_?*" -o -name ".refs-temp*" -o -name ".refs-new*" \
528 \) -exec rm -f '{}' + || :
530 # Remove any stale *.temp files in the objects area that are more than 12 hours old.
531 # This can be stale sha1.temp, or stale *.pack.temp so we kill all stale *.temp.
532 find -L objects -type f -mmin +720 -name "*.temp" -exec rm -f '{}' + || :
534 # Remove any stale *.lock files in the htmlcache area that might have been left
535 # behind after an abnormal exit during an attempt to update a cached file and
536 # are more than 1 hour old.
537 ! [ -d htmlcache ] || find -L htmlcache -type f -mmin +60 -name "*.lock" -exec rm -f '{}' + || :
539 # Remove any stale git-svn temp files that are more than 12 hours old.
540 # The git-svn process creates temp files with random 10 character names
541 # in the root of $GIT_DIR. Unfortunately they do not have a recognizable
542 # prefix, so we just have to kill any files with a 10-character name. We
543 # do this only for git-svn mirrors. All characters are chosen from
544 # [A-Za-z0-9_] so we can at least check that and fortunately the only
545 # collision is 'FETCH_HEAD' but that shouldn't matter.
546 # There may also be temp files with a Git_ prefix as well.
547 if [ -n "$svn_mirror" ]; then
548 _randchar='[A-Za-z0-9_]'
549 _randchar2="$_randchar$_randchar"
550 _randchar4="$_randchar2$_randchar2"
551 _randchar10="$_randchar4$_randchar4$_randchar2"
552 find -L . -maxdepth 1 -type f -mmin +720 -name "$_randchar10" -exec rm -f '{}' + || :
553 find -L . -maxdepth 1 -type f -mmin +720 -name "Git_*" -exec rm -f '{}' + || :
556 # Remove any stale fast_import_crash_<pid> files that are more than 3 days old.
557 if [ -n "$gfi_mirror" ]; then
558 find -L . -maxdepth 1 -type f -mmin +4320 -name "fast_import_crash_?*" -exec rm -f '{}' + || :
561 # Remove any stale core or *.core or core.* files that are more than 3 days old.
562 find -L . -maxdepth 1 -type f -mmin +4320 \( -name "core" -o -name "*.core" -o -name "core.*" \) \
563 -exec rm -f '{}' + || :
567 ## Garbage Collection Types
569 ## There are two kinds of possible garbage collection (gc) operations:
571 ## 1. A normal, full gc
572 ## 2. A "mini" gc
574 ## If the full garbage collection interval has expired (or gc has never been
575 ## run), then a normal, full gc will take place. Otherwise, a "mini" gc will
576 ## take place if the file .needsgc exists.
578 ## A "mini" gc is similar to "git gc --auto" in that it may not end up actually
579 ## doing anything unless the right conditions are present so it's not a burden
580 ## to run it often. If the file .needsgc exists, a "mini" gc will occur at
581 ## the next opportunity.
583 ## Note, however, that the .nogc file suppresses ALL gc activity (normal or mini).
586 proj="${1%.git}"
587 shift
588 cd "$cfg_reporoot/$proj.git"
589 [ -d objects/pack ] || { rm -f gfi-packs; mkdir -p objects/pack; }
590 mirror_url="$(get_mirror_url)" || :
591 svn_mirror=
592 ! is_svn_mirror_url "$mirror_url" || svn_mirror=1
593 gfi_mirror=
594 if [ -f gfi-packs ] && [ -s gfi-packs ] && is_gfi_mirror_url "$mirror_url"; then
595 gfi_mirror=1
598 # If git config --bool --get girocco.redelta is explicitly false then automatic
599 # redelta when there are less than $var_redelta_threshold objects will be suppressed.
600 # On the other hand, if git config --get girocco.redelta is "always" then, on a full
601 # gc only, for the final repack, deltas will always be recomputed.
602 # This can be set on a per-project basis to avoid unusual pathological gc behavior.
603 # Setting this will hurt efficiency of the affected repository.
604 # Note that fast-import packs ALWAYS get new deltas regardless of this setting.
605 noreusedeltaopt="--no-reuse-delta"
606 [ "$(git config --bool --get girocco.redelta 2>/dev/null || :)" != "false" ] || noreusedeltaopt=
607 alwaysredelta=
608 [ "$(git config --get girocco.redelta 2>/dev/null || :)" != "always" ] || alwaysredelta=1
610 # Extract any -f or -F or --no-reuse-object or --no-reuse-delta options
611 # to be compatible with the old and new gc.sh versions and avoid ugly argument
612 # duplication in process lists at the same time
613 # Any options found will override the "girocco.redelta" setting
614 recompress=
615 idx=$#
616 while [ $idx -gt 0 ]; do
617 idx=$(( $idx - 1 ))
618 opt="$1"
619 shift
620 case "$opt" in
621 -f|--no-reuse-delta)
622 alwaysredelta=1
623 continue
625 -F|--no-reuse-object)
626 alwaysredelta=1
627 recompress=1
628 continue
630 -?*)
633 printf >&2 '%s\n' "bad non-option argument: $opt"
634 echo >&2 "(Did you perhaps intend to use a --xxx=yyy form?)"
635 exit 1
636 esac
637 [ -z "$opt" ] || set -- "$@" "$opt"
638 done
639 if [ -n "$alwaysredelta" ]; then
640 noreusedeltaopt="--no-reuse-delta"
641 [ -z "$recompress" ] || noreusedeltaopt="--no-reuse-object"
644 trap 'e=$?; rm -f .gc_in_progress; if [ $e != 0 ]; then echo "gc failed dir: $PWD" >&2; fi' EXIT
645 trap 'exit 130' INT
646 trap 'exit 143' TERM
648 # date -R is linux-only, POSIX equivalent is '+%a, %d %b %Y %T %z'
649 datefmt='+%a, %d %b %Y %T %z'
651 isminigc=
652 if [ "${force_gc:-0}" = "0" ] && check_interval lastgc $cfg_min_gc_interval; then
653 if [ -e .needsgc ]; then
654 isminigc=1
655 else
656 progress "= [$proj] garbage check skip (last at $(config_get lastgc))"
657 exit 0
660 if [ -e .nogc ]; then
661 progress "x [$proj] garbage check disabled"
662 exit 0
664 if [ -z "$isminigc" ] && [ -e .delaygc ] && [ -e .needsgc ]; then
665 # Eligible for a full gc but .delaygc is set so it would be skipped
666 # However .needsgc is also set so transform it into a mini instead
667 isminigc=1
668 progress "~ [$proj] garbage check delayed but checking mini because .needsgc"
671 if [ -n "$isminigc" ]; then
672 # Perform a "mini" gc
673 # Note that .delaygc is ignored here as that's only intended for full gc
674 lock_gc
675 rm -f .allowgc .needsgc
676 rm -f objects/pack/pack-*_r.keep
677 remove_crud
678 coalesce_reflogs
679 prune_reflogs
680 compact_reflogs
681 maintain_auto_gc_hack
682 generate_auto_gc_update
683 miniactive=
684 if [ -f .svnpack ] && [ -n "$svn_mirror" ]; then
685 miniactive=1
686 progress "+ [$proj] mini garbage check ($(date))"
687 make_svn_pack
689 if [ -z "$cfg_delay_gfi_redelta" ] && [ -n "$gfi_mirror" ]; then
690 # $Girocco::Config::delay_gfi_redelta is false, force redeltification now
691 if [ -z "$miniactive" ]; then
692 miniactive=1
693 progress "+ [$proj] mini garbage check ($(date))"
695 repack_gfi_packs
697 # If there aren't at least 10 non-keep, non-bitmap, non-bndl packs then
698 # don't actually process them yet
699 lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl --quiet"
700 packcnt="$(list_packs --count $lpo objects/pack)" || :
701 if [ "${packcnt:-0}" -ge 10 ]; then
702 if [ -z "$miniactive" ]; then
703 miniactive=1
704 progress "+ [$proj] mini garbage check ($(date))"
706 if [ -n "$gfi_mirror" ]; then
707 repack_gfi_packs
708 packcnt="$(list_packs --count $lpo objects/pack)" || :
710 # if repack_gfi_packs dropped the pack count to < 10 don't combine
711 if [ "${packcnt:-0}" -ge 10 ]; then
712 combine_small_packs
713 packcnt="$(list_packs --count $lpo objects/pack)" || :
715 # if we still have more than 10 packs trigger a full gc
716 if [ "${packcnt:-0}" -ge 10 ]; then
717 # We shouldn't be in a .delaygc state at this point, but if
718 # we are then nuke it because we really need a full gc now
719 rm -f .delaygc
720 git config --unset gitweb.lastgc
721 rm -f "$lockf"
722 git update-server-info # just in case
723 progress "- [$proj] mini garbage check triggering full gc too many packs ($(date))"
724 exit 0
727 rm -f "$lockf"
728 if [ -n "$miniactive" ]; then
729 git update-server-info
730 progress "- [$proj] mini garbage check ($(date))"
731 else
732 progress "= [$proj] mini garbage check nothing but crud removal to do ($(date))"
734 exit 0
737 # Avoid unnecessary garbage collections:
738 # 1. If lastreceive is set and is older than lastgc
739 # -AND-
740 # 2. We are not a fork (! -s alternates) -OR- lastparentgc is older than lastgc
742 # If lastgc is NOT set or lastreceive is NOT set we MUST run gc
743 # If we are a fork and lastparentgc is NOT set we MUST run gc
745 # If the repo is dirty after removing any crud we MUST run gc
747 gcstart="$(date "$datefmt")"
748 skipgc=
749 isfork=
750 ! [ -s objects/info/alternates ] || isfork=1
751 lastparentgcsecs=
752 [ -z "$isfork" ] || lastparentgcsecs="$(config_get_date_seconds lastparentgc)" || :
753 lastreceivesecs=
754 if lastreceivesecs="$(config_get_date_seconds lastreceive)" &&
755 [ "${force_gc:-0}" = "0" ] &&
756 lastgcsecs="$(config_get_date_seconds lastgc)" &&
757 [ $lastreceivesecs -lt $lastgcsecs ]; then
758 # We've run gc since we last received, so maybe we can skip,
759 # check if not fork or fork and lastparentgc < lastgc
760 if [ -n "$isfork" ]; then
761 if [ -n "$lastparentgcsecs" ] &&
762 [ $lastparentgcsecs -lt $lastgcsecs ]; then
763 # We've run gc since our parent ran gc so we can skip
764 skipgc=1
766 else
767 # We don't have any alternates (we're not a forK) so we can skip
768 skipgc=1
772 # Prevent any other simultaneous gc operations
773 lock_gc
775 # At this point, if .allowgc or .gc_failed exists, it's now crud to be removed
776 rm -f .allowgc .gc_failed
778 # Ideally we would do this in post-receive, but that would mean duplicating the
779 # logic so it's available in the chroot jail and that's highly undesirable
780 # Instead, since the first gc will be triggered immediately following the first
781 # push, we do the check here as it's quick and harmless if HEAD is already valid
782 check_and_set_head || :
784 # Always get rid of crud
785 remove_crud
787 # Always perform reflogs maintenance
788 coalesce_reflogs
789 prune_reflogs
790 compact_reflogs
792 # Always maintain auto gc hack
793 maintain_auto_gc_hack
794 generate_auto_gc_update
796 # Run 'git svn gc' now for svn mirrors
797 if [ -n "$svn_mirror" ]; then
798 git svn gc || :
801 # Skip the actual gc if .delaygc is set
802 if [ -e .delaygc ]; then
803 progress "x [$proj] garbage check delayed (except for crud removal)"
804 rm -f "$lockf"
805 exit 0
808 # Do not skip gc if the repo is dirty
809 if [ -n "$skipgc" ] && ! is_dirty; then
810 progress "= [$proj] garbage check nothing but crud removal to do ($(date))"
811 config_set lastgc "$gcstart"
812 rm -f "$lockf"
813 exit 0
816 bumptime=
817 if [ -n "$isfork" ] && [ -z "$lastparentgcsecs" ]; then
818 # set lastparentgc and then update gcstart to be at least 1 second later
819 config_set lastparentgc "$gcstart"
820 bumptime=1
822 if [ -z "$lastreceivesecs" ]; then
823 # set lastreceive and then update gcstart to be at least 1 second later
824 config_set lastreceive "$gcstart"
825 bumptime=1
827 if [ -n "$bumptime" ]; then
828 sleep 1
829 gcstart="$(date "$datefmt")"
832 progress "+ [$proj] garbage check ($(date))"
834 newdeltas=
835 [ -z "$alwaysredelta" ] || newdeltas="$noreusedeltaopt"
836 if [ -z "$newdeltas" ] && [ -n "$gfi_mirror" ]; then
837 if [ $(list_packs --exclude-no-idx --count objects/pack) -le \
838 $(list_packs --exclude-no-idx --count --quiet --only gfi-packs) ]; then
839 # Don't bother with repack_gfi_packs since everything's being repacked
840 newdeltas="--no-reuse-delta"
843 if [ -z "$newdeltas" ] && [ -n "$noreusedeltaopt" ] &&
844 [ $(list_packs --all --exclude-no-idx --count-objects objects/pack) -le $var_redelta_threshold ]; then
845 # There aren't enough objects to worry about so just redelta to get the best pack
846 newdeltas="--no-reuse-delta"
848 if [ -z "$newdeltas" ]; then
849 # Since we're not going to recompute deltas overall, we need to do the
850 # "mini" maintenance so that we can get more optimal deltas
851 [ -z "$noreusedeltaopt" ] || make_svn_pack
852 repack_gfi_packs
853 force_single_pack_redelta=
854 [ -n "$gfi_mirror" ] || [ -n "$svn_mirror" ] || force_single_pack_redelta=1
855 [ -z "$noreusedeltaopt" ] || combine_small_packs $force_single_pack_redelta
859 ## Safe Pruning In Forks
861 ## We are about to perform garbage collection. We do NOT use the "git gc" or
862 ## the "git repack" commands directly as they do not provide enough control over
863 ## the fine details. However, we DO maintain a "gc.pid" file during our garbage
864 ## collection so that a simultaneous "git gc" by an administrator will be
865 ## blocked (and similarly we refuse to start garbage collection if we cannot
866 ## create the "gc.pid" file).
868 ## When we say "gc" in the below description we are referring to our "gc.sh"
869 ## script, NOT the "git gc" command.
871 ## If the project we are running garbage collection (gc) on has any forks we
872 ## must be careful not to remove any objects that while no longer referenced by
873 ## this project (the parent) are still referenced by one or more forks (the
874 ## children) otherwise the children will become corrupt and we can't abide
875 ## corrupt children.
877 ## One way to accomplish this is to simply hard-link all currently existing
878 ## loose objects and packs in the parent into all the children that refer to the
879 ## parent (via a line in their objects/info/alternates file) before beginning
880 ## the gc operation and then relying on a subsequent gc in the child to clean up
881 ## any excess objects/packs. We used to use this strategy but it's very
882 ## inefficient because:
884 ## 1. The disk space used by the old pack(s)/object(s) will not be reclaimed
885 ## until all children (and their children, if any) run gc by which time
886 ## it's quite possible the topmost parent will have run gc again and
887 ## hard-linked yet another old pack down to its children (not to mention
888 ## loose objects).
890 ## 2. When using the "-A" option with "git repack", any new objects in the
891 ## parent that are not referenced by children will continually get
892 ## exploded out of the hard-linked pack in the children whenever the
893 ## children run gc.
895 ## 3. To avoid suboptimal and/or unnecessarily many packs being hard-linked
896 ## into child forks, we must run the "mini" gc maintenance before we
897 ## perform the hard-linking into the children which provides yet another
898 ## source of inefficiency.
900 ## While we were still using the "-A" option to "git repack" (that was not
901 ## always the case) to guarantee we can access old ref values for long enough
902 ## to send out a meaningful mail.sh notification, another, more efficient,
903 ## option became available to prevent corruption of child forks that continue
904 ## to refer to objects that are no longer reachable from any ref in the parent.
906 ## The only things that need be copied (or hard-linked) into the child fork(s)
907 ## are those objects that have become unreachable from any ref in the parent.
909 ## When we were using the "git repack -A -d" + "git prune --expire=1.day.ago"
910 ## technique, the only objects that could ever be removed were loose objects
911 ## that "git prune" determined were expired. In that case, loose objects were
912 ## all that need be hard-linked down to child forks in order to avoid
913 ## corruption of any child fork(s).
915 ## The "git repack -A -d" + "git prune --expire=1.day.ago" + hard-linking loose
916 ## objects to child forks technique remains fundamentally sound from the
917 ## perspective of supporting simultaneous gc and push and keeping newly
918 ## unreachable objects around long enough to be sure we can send out meaningful
919 ## ref change notifications and never corrupting any child forks and never
920 ## persisting the lifetime of large old packs containing mostly duplicate or
921 ## unreachable objects as gc percolates through a project's entire fork tree.
923 ## However, that technique suffers from one potential prodigious pitfall.
925 ## Unreachable objects come flying out of their packs to splatter all over the
926 ## objects subdirectories possibly creating a huge, inefficient mess.
928 ## Often this is not an issue. Even with a lot of rebasing going on, usually
929 ## the only objects that will splatter are some commits, trees and the odd blob
930 ## here and there. Not enough to be overly concerned about.
932 ## However, for the reppository that frequently experiences a lot of non-fast-
933 ## forward updates and/or outright ref deletion, the number of objects suddenly
934 ## popping out of their packs at "git repack -A -d" time can be overwhelming.
936 ## To avoid this issue we now use a four phase pack creation strategy.
937 ## This will result in creation of up to four packs (instead of at most one).
939 ## I. A complete pack (with bitmaps if appropriate) gets created including
940 ## only "reachable" objects from all refs/... refs plus HEAD. This will
941 ## also serve as the virtual bundle for the repository.
943 ## II. A pack of recently-became-unreachable objects and friends is created.
944 ## (The "friends" are ref logs, linked working tree HEADs and indicies.)
945 ## Because both the pre-receive and update.sh script record all ref
946 ## changes we can easily choose the cut off point for "recently".
947 ## It is only the fact we maintain those logs in the reflogs subdirectory
948 ## that allows this step to be possible.
950 ## III. If the repository has any forks with a non-zero length alternates file,
951 ## yet another pack of "--keep-unreachable" objects is generated that will
952 ## not actually be kept in the parent, but hard-linked into all the forks.
954 ## IV. Finally, after running "git prune-packed", any remaining loose objects
955 ## are migrated into a pack of their own.
957 ## We then remove any non-.keep packs that existed before we started the
958 ## process being careful to keep any same-pack pushes for the "Push Pack Redux"
959 ## race condition (see README-GC).
961 ## By using "git pack-objects" directly we are able to accomplish this with
962 ## very little additional effort.
964 ## The packs produced by (III) are treated almost like ".keep" packs by child
965 ## forks in that the objects in them are never repacked into any other
966 ## "--keep-unreachable" packs (but they can migrate into phase I or II packs)
967 ## and those phase III packs are then hard-linked into any grandchild forks.
969 ## This avoids the space explosion that could occur if each fork level ended
970 ## up duplicating the "--keep-unreachable" pack space by repacking those
971 ## objects (essentially breaking the hard-link to the single copy of those
972 ## objects).
974 ## While it is true that each level of forks could potentially add yet another
975 ## phase III pack to be hard-linked down to its children, such packs will only
976 ## include unreachable objects not already in any phase III packs that were
977 ## received from the parent.
979 ## The space for the phase III packs will not be reclaimed until the gc
980 ## finishes percolating through the entire "fork tree" of a project.
982 ## This is not much different than the "git repack -A -d" situation where
983 ## all the loose objects are hard-linked down into child forks. In that
984 ## case forks that actually need any of those objects could gradually reduce
985 ## the number of objects hard-linked into deeper fork levels.
987 ## The difference with a phase III "--keep-unreachable" pack is that there
988 ## cannot be any gradual reduction like that since it would require repacking
989 ## the pack and breaking the hard-link thereby increasing storage space. The
990 ## storage will instead always be reclaimed all at once when all of the
991 ## projects in the "fork tree" complete their gc.
993 ## However, the belief is that the huge space win by having all the
994 ## unreachable objects packed up together far eclipses (when many objects are
995 ## involved, the single-pack version can end up using 1/20th or less of the
996 ## disk space compared to having them all as loose objects) any brief minor
997 ## space savings that might occur under the "git repack -A -d" loose object
998 ## system prior to the gc collection completing for all the projects in the
999 ## "fork tree".
1003 ## utility functions
1006 make_packs_ugw() {
1007 find -L "$1" -maxdepth 1 -type f ! -perm -ug+w \
1008 -name "pack-$octet20*.pack" -exec chmod ug+w '{}' + || :
1009 } 2>/dev/null
1011 vcnt() {
1012 eval "$1="'$(( $# - 1 ))'
1015 get_index_tree() {
1016 if [ -s "$1" ]; then
1017 GIT_INDEX_FILE="$1"
1018 export GIT_INDEX_FILE
1019 git write-tree 2>/dev/null || :
1020 unset GIT_INDEX_FILE
1024 get_detached_head() {
1025 if [ -s "$1" ] && read -r _head <"$1" 2>/dev/null; then
1026 case "$_head" in $octet20*)
1027 echo "$_head"
1028 esac
1032 # compute_extra_reachables
1033 # create lines suitable for a packed-refs file mentioning all the
1034 # other refs we might like to keep.
1035 # the current directory MUST be set to the repository's --git-dir
1036 # the following are included:
1037 # * refs mentioned in reflogs/... files
1038 # * tree(s) created from index file(s)
1039 # * detached linked working tree heads
1040 # Resulting objects are tested for existence and uniqified then output
1041 # one per line under a refs/z* namespace
1042 compute_extra_reachables() {
1044 digits8='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
1045 find -L reflogs -mindepth 1 -maxdepth 1 -type f -name "$digits8*" -exec gzip -c -d -f '{}' + |
1046 awk '{print $2; print $3}'
1047 ! [ -f index ] || get_index_tree index
1048 if [ -d worktrees ]; then
1049 find -L worktrees -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1050 while read -r lwth; do
1051 get_detached_head "$lwth"
1052 get_index_tree "${lwth%HEAD}index"
1053 done
1055 } | LC_ALL=C sort -u |
1056 git cat-file ${var_have_git_260:+--buffer} --batch-check"${var_have_git_185:+=%(objectname)}" |
1057 awk '!/missing/ {num++; print $1 " " "refs/" substr("zzzzzzzzzzzz", 1, length(num)) "/" num}'
1061 ## main gc logic
1064 # Everything else is more efficient if we do this first
1065 # The "--prune" option is the default since v1.5.0 but it serves as "documentation" here
1066 git pack-refs --all --prune
1067 [ -e packed-refs ] || >>packed-refs # should never happen...
1069 # If we have a logs directory or a worktrees directory expire the ref logs now
1070 # Note that Git itself does not use either --rewrite or --updateref, so neither do we
1071 ! [ -d logs ] && ! [ -d worktrees ] || eval git reflog expire --all "${quiet:+>/dev/null 2>&1}" || :
1073 make_repack_dir
1074 ! [ -e .gc_failed ] || exit 1
1075 rm -f .gc_in_progress # make sure
1076 touch .gc_in_progress # it's truly fresh
1077 rm -f bundles/* objects/pack/pack-*.bndl
1078 # This is perhaps a bit aggressive in that if we're suffering from "Push Pack Redux"
1079 # and somehow we get run again immediately after the run where "Push Pack Redux" happened
1080 # and we have garbage collection forced, there's just the barest, almost negligible,
1081 # possibility that the "Push Pack Redux" ref updates _still_ have not happened and we
1082 # should not be removing _r .keep files. None of the normal Girocco processing can
1083 # cause this. The second run of this script would have to use the force gc option
1084 # for it to even be possible in the first place. What's much more likely is that
1085 # the initial run of this script was somehow interrupted in the middle before it
1086 # could get rid of the _r .keep file itself in which case it's better to get rid of
1087 # it now to avoid keeping something around that would perturb our nice and neat gc
1088 rm -f objects/pack/pack-*_r.keep
1089 # We will add .keep files for _u packs if and when we run phase III
1090 # Otherwise they need to not have any .keep files during phases I and II
1091 rm -f objects/pack/pack-*_u.keep
1093 # We need to make sure that any non-Girocco (barely tolerated) Git object creation
1094 # activity will be able to "freshen" the pack containing a pre-existing object
1095 # that's being written. This really should not be necessary as the pre-receive
1096 # hook should make sure this takes place for any incoming pushes.
1097 # However, do it here anyway just in case.
1098 make_packs_ugw objects/pack
1100 # This is only effective with Git v2.3.5 and later and it will only matter when
1101 # we are using one of the "internal_rev_list" modes of pack-objects
1102 # (the combine-packs.sh script never uses any of those modes)
1103 # The "git repack" and "git prune" commands always sets this internally themselves
1104 # It makes no difference if there's no repository corruption
1105 GIT_REF_PARANOIA=1 && export GIT_REF_PARANOIA
1107 # All of the options we might want to use with pack-objects were supported
1108 # at some point prior to Git version v1.6.6 which is the minimum version that
1109 # Girocco now requires. Except for one (--use-bitmap-index). Several of them
1110 # are "boiler plate" options we always want to use so we bundle them up here.
1111 pkopt="--delta-base-offset --keep-true-parents --non-empty --all-progress-implied"
1112 # We want to use --include-tag, but before Git v2.10.1 it would leave out
1113 # "middle" tags (e.g. a tag of a tag of a commit would omit the tagged tag)
1114 # See http://repo.or.cz/git.git/b773ddea2cd3b08c for details
1115 # ("pack-objects: walk tag chains for --include-tag", 2016-09-07, v2.10.1)
1116 # This is not a free check as it matches all refs against refs/tags/ then
1117 # peels all the annotated tags and checks for inclusion. The situation in
1118 # which it would add a tag that was not already included by a reachability
1119 # trace that included tag starting points can only occur if a new tag gets
1120 # pushed during gc pointing to something that would have been packed anyway.
1121 # But, it could happen and, really, campared to gc as a whole it's not that
1122 # expensive to perform (provided we do not get an unconnected pack).
1123 [ -z "$var_have_git_2101" ] || pkopt="$pkopt --include-tag"
1124 pkopt="$pkopt ${quiet:---progress} $packopts"
1126 # The git pack-objects command only supports bitmaps if all objects are being
1127 # packed (the "--all" option) and the "--stdout" option is NOT being used.
1128 # Additionally, while packing, if any encountered reachable objects are
1129 # determined to be "not wanted" then no bitmap index will be written anyway.
1130 # While it is theoretically possible that a project with a non-empty alternates
1131 # file ends up packing all objects (because it does not actually use any of the
1132 # objects found in the alternates), it's very unlikely. And, in the unlikely
1133 # event that did occur, clients would see a message about only using one bitmap
1134 # because Git can only use one bitmap at a time and at least one of the
1135 # alternates is bound to have a bitmap. Therefore if we see a non-empty
1136 # alternates file, we disable writing bitmaps which avoids the warning and any
1137 # possibility of a client warning as well. Also if we are running anything
1138 # before Git v2.1.0 (the effective version for repack.writeBitmaps=true) then
1139 # we also always disable bitmap writing.
1140 wbmopt=
1141 [ -z "$var_have_git_210" ] || wbmopt="--write-bitmap-index"
1142 # More recent versions of pack-objects have optimizations when not using the
1143 # --local option. If we do not have any alternates it's a pointless option.
1144 # If we do have alternates we need to skip writing a bitmap and we cannot
1145 # have a bundle since it must contain all objects.
1146 if [ -n "$isfork" ]; then
1147 lclopt="--local"
1148 wbmopt=
1149 makebndl=
1150 else
1151 lclopt=
1152 makebndl=1
1156 ## Phase I
1159 wbmstr=
1160 [ -n "$wbmopt" ] || wbmstr=" (bitmaps disabled)"
1161 progress "~ [$proj] running primary full gc pack-objects$wbmstr ($(date))"
1163 gotforks=
1164 ! has_forks_with_alternates "$proj" || gotforks=1
1166 # To avoid "Push Pack Redux" (see README-GC), after collecting the initial
1167 # preexisting non-keep pack list, we rename them so that an incoming push
1168 # pack cannot possibly experience a pack name collision. Git does not require
1169 # use of the "default" pack names, simply that the proper extensions are used.
1170 # We rename to insert an "_r" just before the extension to avoid "Push Pack Redux"
1171 # name collisions. Later on we may create an "unreachable" pack for hard-linking
1172 # down into forks and it will have an "_u" inserted just before its extension.
1173 packlist="$(list_packs -C objects/pack --all --exclude-no-idx --exclude-keep --quiet .)" || :
1174 oldpacks=
1175 for oldpack in $packlist; do
1176 oldpack="${oldpack%.pack}"
1177 [ -f "objects/pack/$oldpack.pack" ] || {
1178 echo >&2 "[$proj] unable to list old pack files"
1179 exit 1
1181 case "$oldpack" in pre-auto-gc-[12])
1182 # we never disturb pre-auto-gc-1 or pre-auto-gc-2 packs
1183 continue
1184 esac
1185 oldpackhex="${oldpack#pack-}"
1186 if [ "${oldpackhex#*[!0-9a-fA-F]}" != "$oldpackhex" ]; then
1187 # names not exclusively hexadecimal do not need renaming
1188 oldpacks="${oldpacks:+$oldpacks }$oldpack"
1189 continue
1191 rename_pack "objects/pack/$oldpack" "objects/pack/${oldpack}_r" || {
1192 echo >&2 "[$proj] unable to rename old pack files"
1193 exit 1
1195 # If the oldpack has a .keep now it means a "Push Pack Redux" is actually
1196 # in progress at this moment and we need to .keep the renamed pack,
1197 # otherwise no "Push Pack Redux" has started yet or it has already finished.
1198 # In either case we're okay because if it's just finished then all ref
1199 # changes have already been made so we don't need a .keep and we will
1200 # see the ref changes and grab all the objects via a reachability trace.
1201 # If it hasn't started yet that's okay because we're done moving that
1202 # name so a complete pack will appear under the old name that we'll
1203 # leave alone.
1204 if [ -f "objects/pack/$oldpack.keep" ]; then
1205 echo "Push Pack Redux" >"objects/pack/${oldpack}_r.keep"
1206 else
1207 oldpacks="${oldpacks:+$oldpacks }${oldpack}_r"
1209 done
1211 # We wish to keep deltas from our last full pack so if we're not redeltaing
1212 # then make sure the .pack associated with the .bitmap has a newer mod time
1213 # (If there is no .bitmap then touch the pack with the most objects instead.)
1214 if [ -z "$newdeltas" ]; then
1215 bmpack="$(list_packs --exclude-no-bitmap --exclude-no-idx --max-matches 1 objects/pack)"
1216 [ -n "$bmpack" ] || bmpack="$(list_packs --exclude-no-idx --max-matches 1 --object-limit -1 --include-boundary objects/pack)"
1217 if [ -n "$bmpack" ] && [ -f "$bmpack" ] && [ -s "$bmpack" ]; then
1218 sleep 1
1219 touch -c "$bmpack" 2>/dev/null || :
1220 # We must touch .gc_in_progress here to avoid $bmpack looking
1221 # like it's been "freshened" when redundant packs are removed
1222 # It's okay if they have the same mod time, but POSIX does not
1223 # guarantee an ordering for the "touching" that occurs which is
1224 # why this must be a separate command but needs no "sleep 1"
1225 touch .gc_in_progress
1229 # Now we need to make sure that any "freshening" that takes place will actually
1230 # result in a "newer" modification time than the .gc_in_progress file now has
1231 sleep 1
1233 # We run git pack-objects from the repack subdirectory so we can force
1234 # optimized packs to be generated even for repositories that do not have any
1235 # tagged commits
1236 packs="$(git --git-dir=repack pack-objects </dev/null \
1237 $pkopt --all $newdeltas $lclopt ${wbmopt:---honor-pack-keep} "$@" repack/alt/pack/pack)"
1238 vcnt packcnt $packs
1239 [ $packcnt -eq 1 ] || makebndl=
1242 ## Phase II
1245 progress "~ [$proj] running supplementary gc pack-objects ($(date))"
1247 # Add the "supplementary" refs
1248 compute_extra_reachables >>repack/packed-refs
1250 # Subtract the primary refs
1251 GIT_ALTERNATE_OBJECT_DIRECTORIES="$PWD/repack/alt"
1252 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1254 # For this one we MUST use --local and MUST NOT use --write-bitmap-index
1255 # However, if there is a "logs" subdirectory we need to use --reflog
1256 # We do add it, just in case, if the linked working trees dir is present
1257 # We do not add --indexed-objects as that requires v2.2.0 and it's unclear
1258 # if it properly includes linked working tree index files or not. The
1259 # above compute_extra_reachables has already included all index trees (thereby
1260 # providing proper --indexed-objects support for all Git versions) making the
1261 # option completely unnecessary.
1262 rflopt=
1263 ! [ -d logs ] && ! [ -d worktrees ] || rflopt=--reflog
1264 spacks="$(git --git-dir=repack pack-objects </dev/null \
1265 $pkopt --honor-pack-keep --all $rflopt $newdeltas --local "$@" repack/alt/pack/pack)"
1268 ## Phase III
1271 # There's nothing to do for Phase III unless we have forks that refer to our
1272 # project from their alternates file
1273 hlpacks=
1274 upacks=
1275 if [ -n "$gotforks" ]; then
1277 progress "~ [$proj] running keep-unreachable gc pack-objects for forks ($(date))"
1279 # If we are a fork, any pre-existing _u packs need to have a .keep
1280 # for this phase and be added to the hlpacks list otherwise (we are
1281 # not a fork) pre-existing _u packs are anomalies to be treated like
1282 # regular non-_u packs
1283 if [ -n "$isfork" ]; then
1284 for upack in $(find -L objects/pack -mindepth 1 -maxdepth 1 -name "pack-$octet20*_u.pack" -print); do
1285 upack="${upack%.pack}"
1286 [ -e "$upack.keep" ] || echo "unreachable" >"$upack.keep"
1287 hlpacks="${hlpacks:+$hlpacks }${upack#objects/pack/pack-}"
1288 done
1290 # Using either --no-reuse-delta or --no-reuse-object together with the
1291 # --keep-unreachable option is a very, very, very bad idea when good
1292 # packs are the desired outcome. If newdeltas are being generated
1293 # then we pack to a temp name, and use combine-packs.sh to get a better
1294 # pack as the result to avoid making a bad --keep-unreachable pack
1295 pfx=
1296 [ -z "$newdeltas" ] || pfx="ku"
1297 upacks="$(git --git-dir=repack pack-objects </dev/null \
1298 $pkopt --honor-pack-keep --all $rflopt --keep-unreachable --local "$@" repack/alt/pack/${pfx}pack)"
1299 if [ -n "$upacks" ] && [ -n "$newdeltas" ]; then
1300 progress "~ [$proj] rebuilding keep-unreachable pack deltas"
1301 oldupacks="$upacks"
1302 upacks="$(
1303 printf "repack/alt/pack/${pfx}pack-%s.pack\n" $oldupacks |
1304 run_combine_packs --names --weak-naming --non-empty --all-progress-implied ${quiet:---progress} \
1305 $packopts $newdeltas "$@" repack/alt/pack/pack)"
1306 eval rm -f "$(printf \""repack/alt/pack/${pfx}pack-%s.*"\"" " $oldupacks)"
1308 for upack in $upacks; do
1309 rename_pack "repack/alt/pack/pack-$upack" "repack/alt/pack/pack-${upack}_u"
1310 done
1311 rm -f objects/pack/pack-*_u.keep
1312 [ -z "$hlpacks" ] && [ -z "$upacks" ] ||
1313 progress "~ [$proj] hard-linking keep-unreachable pack(s) into immediate child forks"
1315 # We have to update the lastparentgc time in the child forks even if they do not get any
1316 # new "unreachable packs" because they need to run gc just in case the parent now has some
1317 # objects that used to only be in the child so they can be removed from the child.
1318 # For example, a "patch" might be developed first in a fork and then later accepted into
1319 # the parent in which case the objects making up the patch in the child fork are now
1320 # redundant (since they're now in the parent as well) and need to be removed from the
1321 # child fork which can only happen if the child fork runs gc.
1322 lastparentgc="$(date "$datefmt")"
1324 # It is enough to copy objects just one level down and get_repo_list
1325 # takes a regular expression (which is automatically prefixed with '^')
1326 # so we can easily match forks exactly one level down from this project
1327 forkdir="$proj"
1328 get_repo_list "$forkdir/[^/:][^/:]*:" |
1329 while read fork; do
1330 # Ignore forks that do not exist or are symbolic links
1331 ! [ -L "$cfg_reporoot/$fork.git" ] && [ -d "$cfg_reporoot/$fork.git" ] ||
1332 continue
1333 # Or do not have a non-zero length alternates file
1334 [ -s "$cfg_reporoot/$fork.git/objects/info/alternates" ] ||
1335 continue
1336 runupdate=
1337 # Match hlpacks in parent project if any
1338 if [ -n "$hlpacks" ]; then
1339 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1340 eval ln -f "$(printf '"objects/pack/pack-%s.pack" ' $hlpacks)" \
1341 "$(printf '"objects/pack/pack-%s.idx" ' $hlpacks)" \
1342 '"$cfg_reporoot/$fork.git/objects/pack/"'
1343 runupdate=1
1345 # Match upacks in repack/alt area if any
1346 if [ -n "$upacks" ]; then
1347 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1348 eval ln -f "$(printf '"repack/alt/pack/pack-%s_u.pack" ' $upacks)" \
1349 "$(printf '"repack/alt/pack/pack-%s_u.idx" ' $upacks)" \
1350 '"$cfg_reporoot/$fork.git/objects/pack/"'
1351 runupdate=1
1353 if ! [ -e "$cfg_reporoot/$fork.git/.needsgc" ]; then
1354 # Trigger a mini gc in the fork if it now has too many packs
1355 packs="$(list_packs --quiet --count --exclude-no-idx --exclude-keep "$cfg_reporoot/$fork.git/objects/pack")" || :
1356 if [ -n "$packs" ] && [ "$packs" -ge 20 ]; then
1357 >"$cfg_reporoot/$fork.git/.needsgc"
1360 [ -z "$runupdate" ] || git --git-dir="$cfg_reporoot/$fork.git" update-server-info
1361 # Update the fork's lastparentgc date (must be more recent than $gcstart)
1362 git --git-dir="$cfg_reporoot/$fork.git" config gitweb.lastparentgc "$lastparentgc"
1363 done
1366 # Now move any primary/supplementary packs back into objects/pack
1367 # then drop any "unfreshened" redundant packs and clear repack/alt
1369 # First make sure the primary pack(s) have the most recent mod time
1370 if [ -n "$packs" ]; then
1371 [ -z "$spacks" ] || sleep 1
1372 printf 'repack/alt/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1375 # Move the packs into place
1376 for pack in $packs $spacks; do
1377 rename_pack "repack/alt/pack/pack-$pack" "objects/pack/pack-$pack"
1378 done
1380 # It's possible that one of the $oldpacks had a .bitmap, got renamed (along
1381 # with its .bitmap) and then got "freshened" causing us to not remove it
1382 # However, if $wbmopt is set we most likely now have TWO .bitmap packs!
1383 # This can produce ugly warnings we don't want and possibly get the wrong
1384 # bitmap used since only one .bitmap file can ever be used by Git.
1385 # If this has happened, the .bitmap we want to discard will always have
1386 # an _r infix so we can just zap any such now since it will leave the pack.
1387 [ -z "$wbmopt" ] || rm -f objects/pack/pack-*_r.bitmap || :
1389 # Remove the redundant packs that have not since been "freshened"
1390 # This does not completely eliminate the race condition window (Girocco's own
1391 # activites -- gc/fetch/receive are immune to the race) but it substantially
1392 # shrinks it down to just the time after the find but before the following rm
1393 >repack/oldpacks
1394 [ -z "$oldpacks" ] ||
1395 printf 'objects/pack/%s.pack\n' $oldpacks |
1396 LC_ALL=C sort >repack/oldpacks
1397 find -L objects/pack -maxdepth 1 -type f -name "pack-$octet20*.pack" -newer .gc_in_progress -print |
1398 LC_ALL=C sort >repack/freshened
1399 deadpacks="$(LC_ALL=C join -v 1 repack/oldpacks repack/freshened | LC_ALL=C sed 's/\.pack$//')"
1400 [ -z "$deadpacks" ] ||
1401 eval echo "$(printf '"%s".* ' $deadpacks)" | xargs rm -f || :
1403 # No need for this anymore
1404 rm -rf repack/alt objects/pack/repack
1405 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1408 ## Phase IV
1411 progress "~ [$proj] running gc prune-packed"
1413 # We do not want the redundant packs or any new "--keep-unreachable" pack(s) to be
1414 # present while running prune-packed. We try to guarantee that any loose object
1415 # that's unreachable persists for at least one $Girocco::Config::min_gc_interval
1416 # (not withstanding administrator interference to force earlier gc to occur).
1417 # If we were to include the redundant/keep-unreachable pack(s) when running
1418 # prune-packed and a loose unreachable object happened to be duplicated in one
1419 # of them we would end up removing it too soon and void our guarantee.
1420 git prune-packed $quiet
1422 progress "~ [$proj] running loose objects gc pack-objects ($(date))"
1424 # Although Git v2.10.0 and later support a --pack-loose-unreachable option,
1425 # we MUST NOT use it for these reasons:
1426 # 1) We're not interested in expensive "unreachable" at this point, only "loose"
1427 # 2) It produces simply horrid packs about 3.8x times larger than they should be
1428 # 3) We don't require anything more than Git v1.6.6
1429 lpacks="$(run_combine_packs </dev/null --names --loose --weak-naming --non-empty --all-progress-implied ${quiet:---progress} $packopts $newdeltas "$@")"
1431 if [ -n "$lpacks" ]; then
1432 # Make sure any primary pack(s) have a more recent mod time than "unreachable" objects packs
1433 if [ -n "$packs" ]; then
1434 sleep 1
1435 printf 'objects/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1437 # We need to identify these packs later so we don't combine_packs them
1438 for objpack in $lpacks; do
1439 rename_pack "objects/pack/pack-$objpack" "objects/pack/pack-${objpack}_o" || :
1440 done
1441 # Finally zap the corresponding loose objects
1442 progress "~ [$proj] running packed loose objects gc prune-packed"
1443 git prune-packed $quiet
1446 ! [ -e .gc_failed ] || exit 1
1447 # These, if they exist, are now meaningless and need to be removed
1448 rm -f gfi-packs .needsgc .svnpack .svnpackgc
1450 # Make sure this stays up to date
1451 git update-server-info
1453 # We must make loose objects group writable so that they
1454 # can be freshened by other pushers. Technically we need only do this for
1455 # push projects but to enable mirror projects to be more easily converted to
1456 # push projects, we go ahead and do it for all projects.
1457 # By the time we get here we really shouldn't have any of these, but just in case.
1458 { find -L objects/$octet -type f -name "$octet19*" -exec chmod ug+w '{}' + || :; } 2>/dev/null
1460 # darcs:// mirrors have a xxx.log file that will grow endlessly
1461 # if this is a mirror and the file exists, shorten it to 10000 lines
1462 # also take this opportunity to optimize the darcs repo
1463 if ! [ -e .nofetch ] && [ -n "$cfg_mirror" ]; then
1464 url="$(config_get baseurl)" || :
1465 case "$url" in darcs://*)
1466 if [ -n "$cfg_mirror_darcs" ]; then
1467 url="${url%/}"
1468 basedarcs="$(basename "${url#darcs:/}")"
1469 if [ -f "$basedarcs.log" ]; then
1470 tail -n 10000 "$basedarcs.log" >"$basedarcs.log.$$"
1471 mv -f "$basedarcs.log.$$" "$basedarcs.log"
1473 if [ -d "$basedarcs.darcs" ]; then
1475 cd "$basedarcs.darcs"
1476 # without show_progress suppress non-error output
1477 [ -n "$show_progress" ] || exec >/dev/null
1478 # Note that this does not optimize _darcs/inventories/ :(
1479 darcs optimize || :
1483 esac
1486 # Create a matching .bndl header file for the all-in-one pack we just created
1487 # but only if we're not a fork (otherwise the bundle would not be complete)
1488 # and we are running at least Git version 1.7.2 (pack_is_complete always fails otherwise)
1489 if [ -n "$makebndl" ] && [ -n "$var_have_git_172" ]; then
1490 # There should only be one pack in $packs but do some checking...
1491 # The one we just created will have a .idx and will NOT have a .keep
1492 progress "~ [$proj] creating downloadble bundle header"
1493 pkbase=
1494 pkhead=
1495 IFS= read -r curhead <repack/HEAD.orig || :
1497 [ -s "objects/pack/pack-$packs.pack" ] &&
1498 [ -s "objects/pack/pack-$packs.idx" ] &&
1499 ! [ -e "objects/pack/pack-$packs.keep" ] &&
1500 pkhead="$(pack_is_complete "$PWD/objects/pack/pack-$packs.pack" \
1501 "$PWD/repack/packed-refs.orig" "$curhead")"
1502 then
1503 pkbase="objects/pack/pack-$packs"
1505 if [ -n "$pkbase" ] && [ -n "$pkhead" ]; then
1507 symref=
1508 case "$curhead" in "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
1509 symref="${curhead#ref:}"
1510 symref="${symref# }"
1511 esac
1512 bndlurl=
1513 [ -z "$cfg_httpbundleurl" ] || bndlurl=" url=$cfg_httpbundleurl/$proj.git/clone.bundle"
1514 echo "# v2 git bundle"
1515 LC_ALL=C sed -ne "/^$octet20$hexdig* refs\/[^ $tab]*\$/ p" <repack/packed-refs.orig
1516 if [ -n "$symref" ]; then
1517 printf "$pkhead HEAD\0symref=HEAD:%s%s\n" "$symref" "$bndlurl"
1518 else
1519 if [ -n "$bndlurl" ]; then
1520 printf "$pkhead HEAD\0%s\n" "${bndlurl:# }"
1521 else
1522 echo "$pkhead HEAD"
1525 echo ""
1526 } >"$pkbase.bndl"
1527 bndletag="$("$cfg_basedir/bin/rangecgi" --etag -m 1 "$pkbase.bndl" "$pkbase.pack")" || :
1528 bndlsha="$(printf '%s' "$bndletag" | git hash-object --stdin)" || :
1529 if [ -n "$bndletag" ]; then
1530 case "$bndlsha" in $octet20*)
1531 bndlshatrailer="${bndlsha#????????}"
1532 bndlshaprefix="${bndlsha%$bndlshatrailer}"
1533 bndlname="$(TZ=UTC date +%Y%m%d_%H%M%S)-${bndlshaprefix:-0}"
1534 [ -d bundles ] || mkdir bundles
1535 echo "${pkbase#objects/pack/}.bndl" >"bundles/$bndlname"
1536 echo "${pkbase#objects/pack/}.pack" >>"bundles/$bndlname"
1537 ln -s -f -n "$bndlname" bundles/latest
1538 esac
1543 # Record the size of this repo as the sum of its clone packed-refs + *.pack sizes as 1024-byte blocks
1544 eval "reposizek=$(( $(
1545 echo 0 $(du -k repack/packed-refs.orig $(printf 'objects/pack/pack-%s.pack ' $packs) 2>/dev/null |
1546 LC_ALL=C awk '{print $1}') |
1547 LC_ALL=C sed -e 's/ / + /g') ))"
1548 config_set_raw girocco.reposizek "${reposizek:-0}"
1550 # Now we're finally done with this
1551 rm -rf repack
1553 # We didn't used to do anything about rerere or worktrees but we're
1554 # trying to make nice with linked working trees these days :)
1555 # Maybe even non-bare repositories too, but *shush* about those ;)
1556 if [ -n "$var_have_git_250" ] && [ -d worktrees ]; then
1557 # The value "3.months.ago" is hard-coded into gc.c rather than
1558 # having the default be in worktree.c so we must provide it if
1559 # we get nothing out of the gc.worktreePruneExpire config item
1560 # Prior to Git v2.6.0 the config item was gc.pruneworktreesexpire
1561 # however we just always use the newer name no matter what Git version
1562 expiry="$(git config --get gc.worktreePruneExpire 2>/dev/null)" || :
1563 eval git worktree prune --expire '"${expiry:-3.months.ago}"' "${quiet:+>/dev/null 2>&1}" || :
1565 # git rerere does it right and handles its own default/config'd expiration values
1566 ! [ -d rr-cache ] || eval git rerere gc "${quiet:+>/dev/null 2>&1}" || :
1568 # We use $gcstart here to avoid a race where a push occurs during the gc itself
1569 # and the next future gc could be incorrectly skipped if we used the current
1570 # timestamp here instead
1571 config_set lastgc "$gcstart"
1572 rm -f "$lockf"
1574 progress "- [$proj] garbage check ($(date))"