gc.sh: refactor lock_gc function for reuse
[girocco.git] / jobd / gc.sh
blobbb3de2ddb68142979d1e0516f43aef837fa9b538
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
8 . @basedir@/jobd/gc-util-functions.sh
10 set -e
12 if [ $# -lt 1 ]; then
13 echo "Usage: gc.sh projname [extra-repack-args]" >&2
14 exit 1
17 # Includes
18 _shlib_done=1
19 unset GIROCCO_SUPPRESS_AUTO_GC_UPDATE
20 . "$cfg_basedir/jobd/maintain-auto-gc-hack.sh"
21 . "$cfg_basedir/jobd/generate-auto-gc-update.sh"
22 GIROCCO_SUPPRESS_AUTO_GC_UPDATE=1 && export GIROCCO_SUPPRESS_AUTO_GC_UPDATE
24 umask 002
25 [ "$cfg_permission_control" != "Hooks" ] || umask 000
26 clean_git_env
28 pidactive() {
29 if _result="$(kill -0 "$1" 2>&1)"; then
30 # process exists and we have permission to signal it
31 return 0
33 case "$_result" in *"not permitted"*)
34 # we do not have permission to signal the process
35 return 0
36 esac
37 # process does not exist
38 return 1
41 createlock() {
42 # A .lock file should only exist for much less than a second.
43 # If we see a stale lock file (> 1h old), remove it and then,
44 # just in case, wait 30 seconds for any process whose .lock
45 # we might have just removed (it's racy) to finish doing what
46 # should take much less than a second to do.
47 _stalelock="$(find -L "$1.lock" -maxdepth 1 -mmin +60 -print 2>/dev/null)" || :
48 if [ -n "$_stalelock" ]; then
49 rm -f "$_stalelock"
50 sleep 30
52 for _try in p p n; do
53 if (set -C; >"$1.lock") 2>/dev/null; then
54 echo "$1.lock"
55 return 0
57 # delay and try again
58 [ "$_try" != "p" ] || sleep 1
59 done
60 # cannot create lock file
61 return 1
64 # The pre-receive script creates one ref log file per push but we want them to
65 # be coalesced into one ref log file per day. We are guaranteed that any files
66 # we find to coalesce are NOT currently being written to since they are always
67 # written first as temporary files and then moved into place. We attempt to
68 # transfer the most recent modification time to the coalesced log file which
69 # would step on its mod time if it were being written to directly, but if we
70 # find per-process ref log files then it must be a push project and the only
71 # thing that would write directly to the main per-day log file would be a
72 # mirror project so there's actually no conflict.
73 # Also, if the clock is wonky (or was futzed with) we may have both YYYYMMDD
74 # and YYYYMMDD.gz present in which case combine them into YYYYMMDD
75 coalesce_reflogs() {
76 [ -d reflogs ] || return 0
77 rm -f .gc_failed
78 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 |
79 while read -r rname; do
80 if [ -e "$rname.gz" ]; then
81 if [ -s "$rname" ]; then
82 # Presumably the .gz file must have been created before the non-gz
83 # file since it had to be uncompressed at some point therefore
84 # we need to append the non-gz contents to it but keep the non-gz
85 # contents timestamp so we rename to YYYYMMDD_ which will sort first
86 # and be picked up in the next step if we are interrupted in the middle.
87 # If a YYYYMMDD_ file already exists we append to it and transfer the
88 # timestamp. Finally we transfer the YYYYMMDD_ timestamp to the result
89 # and remove the YYYYMMDD_ temporary file leaving the result uncompressed.
90 if [ -e "${rname}_" ]; then
91 cat "$rname" >>"${rname}_"
92 touch -r "$rname" "${rname}_"
93 rm -f "$rname"
94 ! [ -e "$rname" ]
95 else
96 mv "$rname" "${rname}_"
98 gzip -d "$rname.gz" </dev/null
99 [ -e "$rname" ] && ! [ -e "$rname.gz" ]
100 cat "${rname}_" >>"$rname"
101 touch -r "${rname}_" "$rname"
102 rm -f "${rname}_"
103 else
104 # Just remove the empty file to resolve the problem
105 rm -f "$rname"
108 done
109 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 |
110 while read -r rname; do
111 logname="${rname%%_*}"
112 # If someone's been futzing with the date, the file we want to
113 # append to could already have been compressed, so we just uncompress
114 # it here. The previous block guarantees we do not have both a compressed
115 # and uncompressed version present at the same time.
116 if [ -e "$logname.gz" ]; then
117 gzip -d "$logname.gz" </dev/null
118 [ -e "$logname" ] && ! [ -e "$logname.gz" ]
120 cat "$rname" >>"$logname"
121 touch -r "$rname" "$logname"
122 rm -f "$rname"
123 if [ -e "$rname" ]; then
124 >.gc_failed
125 echo "! [$proj] failed to remove $rname" >&2
126 exit 1 # will only exit subshell created by "|"
128 done
129 ! [ -e .gc_failed ]
132 # Remove any files in reflogs that are older than $cfg_reflogs_lifetime days
133 prune_reflogs() {
134 [ -d reflogs ] || return 0
135 exp="$(( ${cfg_reflogs_lifetime:-1} * 1440 ))"
136 [ $exp -gt 0 ] || exp=1440
137 [ $exp -le 43200 ] || exp=43200
138 find -L reflogs -maxdepth 1 -type f -mmin "+$exp" -exec rm -f '{}' + || :
141 # Compact any reflogs that are not today's UTC date unless a .gz version exists
142 compact_reflogs() {
143 [ -d reflogs ] || return 0
144 _td="reflogs/$(TZ=UTC date '+%Y%m%d')"
145 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 |
146 while read -r rname; do
147 [ "$rname" != "$_td" ] || continue
148 ! [ -e "$rname.gz" ] || continue
149 gzip -9 "$rname" </dev/null
150 done
153 # return true if there's more than one objects/pack-<sha>.pack file or
154 # ANY sha-1 files in objects or
155 # there's one pack and it's not a normal pack name or
156 # there's one pack but not any refs
157 is_dirty() {
158 _packs="$(find -L objects/pack -name "pre-auto-gc-[12].pack" -prune -o -name "*.pack" -type f -print 2>/dev/null | head -n 2)"
159 v_cnt _packscnt $_packs
160 if [ $_packscnt -gt 1 ]; then
161 return 0
163 if [ $_packscnt -eq 1 ]; then
164 # the single pack name is in $_packs
165 _packs="${_packs%.pack}"
166 _packs="${_packs#objects/pack/}"
167 case "$_packs" in
168 pack-*)
169 _packs="${_packs#pack-}"
170 if [ "${#_packs}" -lt 40 ] || [ "${_packs#*[!0-9a-fA-F]}" != "$_packs" ]; then
171 # name not exclusively 40 or more hexadecimal digits makes it dirty
172 return 0
176 # abnormal name makes it dirty
177 return 0
179 esac
181 _objs=$(find -L objects/$octet -name "$octet19*" -type f -print 2>/dev/null | head -n 1 | LC_ALL=C wc -l)
182 [ $_objs -eq 0 ] || return 0
183 [ $_packscnt -eq 1 ] || return 1
184 # we do this check last because it's potentially the most expensive;
185 # at this point we know we do not have any loose objects, but we do
186 # have one pack that's named "normally"; empty refs => dirty
187 is_empty_refs_dir
190 # combine the input pack(s) into a new pack (or possibly packs if packSizeLimit set)
191 # input pack names are read from standard input one per line delimited by the first
192 # ':', ' ' or '\n' character on the line (which allows gfi-packs to be read directly)
193 # all arguments, if any, are passed to pack-objects as additional options
194 # returns non-zero on failure AND creates .gc_failed in that case
195 combine_packs() {
196 rm -f .gc_failed
197 combine_packs_std "$@" || {
198 >.gc_failed
199 return 1
201 return 0
204 # if the current directory is_gfi_mirror then repack all packs listed in gfi-packs
205 repack_gfi_packs() {
206 [ -n "$gfi_mirror" ] || return 0
207 [ -d objects/pack ] || { rm -f gfi-packs; return 0; }
208 progress "~ [$proj] redeltifying poor quality git fast-import packs"
209 combine_packs --ignore-missing --no-reuse-delta <gfi-packs
210 rm -f gfi-packs
211 return 0
214 # pack any existing loose objects into a new _l.pack file then run prune-packed
215 # note that prune-packed is NOT run beforehand -- the caller must do that if needed
216 # loose objects need not be part of complete commits/trees as --weak-naming is used
217 pack_loose_objects() {
218 _lpacks="$(run_combine_packs </dev/null --names --loose --weak-naming --non-empty --all-progress-implied ${quiet:---progress} $packopts)"
219 if [ -n "$_lpacks" ]; then
220 # We need to identify these packs later so we don't combine_packs them
221 for _objpack in $_lpacks; do
222 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
223 done
224 git prune-packed $quiet
228 # combine small packs into larger pack(s)
229 # we avoid any _[lo], keep, bndl or bitmap packs
230 # if the optional argument is non-empty even a single small pack will be redeltad
231 combine_small_packs() {
232 _didprogress=
233 _minsmallpacks=2
234 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
235 _minsmallpacks=1
237 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
238 _lpo="$_lpo --exclude-sfx _u --exclude-sfx _o --exclude-sfx _l"
239 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
240 while
241 _cnt="$(list_packs --count $_lpo)" || :
242 test "${_cnt:-0}" -ge $_minsmallpacks
244 [ -n "$_didprogress" ] || {
245 progress "~ [$proj] combining small packs into a single larger pack"
246 _didprogress=1
248 _newp="$(list_packs $_lpo | combine_packs --names $noreusedeltaopt)"
249 v_cnt _newc $_newp
250 # be paranoid and exit the loop if we haven't reduced the number of packs
251 [ $_newc -lt $_cnt ] || break
252 _minsmallpacks=2
253 done
254 return 0
257 # combine small _l packs into larger pack(s) using --weak-naming
258 # we avoid any non _l, keep, bndl or bitmap packs
259 # if the optional 2nd argument is non-empty even a single small pack will be redeltad
260 combine_small_loose_packs() {
261 _didprogress=
262 _minsmallpacks=2
263 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
264 _minsmallpacks=1
266 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
267 _lpo="$_lpo --exclude-no-sfx _l"
268 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
269 while
270 _cnt="$(list_packs --count $_lpo)" || :
271 test "${_cnt:-0}" -ge $_minsmallpacks
273 [ -n "$_didprogress" ] || {
274 progress "~ [$proj] combining small loose packs into a single larger pack"
275 _didprogress=1
277 _newp="$(list_packs $_lpo | combine_packs --names --weak-naming $noreusedeltaopt)"
278 # We need to identify these packs later so we don't combine_packs them
279 for _objpack in $_newp; do
280 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
281 done
282 v_cnt _newc $_newp
283 # be paranoid and exit the loop if we haven't reduced the number of packs
284 [ $_newc -lt $_cnt ] || break
285 _minsmallpacks=2
286 done
287 return 0
290 # Unfortunately, some fetch strategies (e.g. git-svn and non-smart HTTP) lack
291 # the ability to store newly fetched objects in a pack.
292 # However, the fetch code conveniently sets .needspack just before it fetches
293 # so that it's easy to find all the loose objects that have been fetched and
294 # combine them into a pack. The --no-reuse-delta option is meaningless here
295 # since everything to be packed is a loose object and therefore not a delta so
296 # deltification will always take place.
297 make_needs_pack() {
298 [ -f .needspack ] || return 0
299 rm -f .needspackgc
300 mv -f .needspack .needspackgc
301 progress "~ [$proj] combining fetched loose objects into a pack"
302 _newp="$(find -L objects/$octet -maxdepth 1 -type f -newer .needspackgc -name "$octet19*" -print 2>/dev/null |
303 LC_ALL=C awk -F / '{print $2 $3}' |
304 run_combine_packs --objects --names $packopts --incremental --all-progress-implied $quiet --non-empty)" || {
305 # We used to fail gc here.
306 # Now, however, we just ignore the failure because we have
307 # another mechanism to handle loose objects and it's possible
308 # that the fetcher somehow brought in unconnected objects which
309 # would cause the above combine-packs to fail.
310 # By ignoring the failure and just removing the .needspack file
311 # the loose objects will be treated as "ordinary" loose objects
312 # and packed using the "--weak-naming" option which can handle
313 # broken connectivity.
314 # That's a better solution than just failing here or leaving
315 # .needspack behind to potentially continue to fail again and
316 # again.
317 _newp=
319 if [ -n "$_newp" ]; then
320 # remove the now-redundant loose objects -- this is always safe
321 # even during a concurrent push because a reprepare_packed_git
322 # will be triggered if an object that should be there is not
323 # found thereby finding it in the new pack instead
324 git prune-packed $quiet
326 rm -f .needspackgc
329 # HEADSHA="$(pack_is_complete /full/path/to/some.pack /full/path/to/packed-refs "$(cat HEAD)")"
330 pack_is_complete() {
331 # Must have a matching .idx file and a non-empty packed-refs file
332 [ -s "${1%.pack}.idx" ] || return 1
333 [ -s "$2" ] || return 1
334 _headsha=
335 case "$3" in
336 $octet20*)
337 _headsha="$3"
339 "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
340 _headmatch="${3#ref:}"
341 _headmatch="${_headmatch# }"
342 _headmatchpat="$(echo "$_headmatch" | LC_ALL=C sed -e 's/\([.$]\)/\\\1/g')"
343 _headsha="$(LC_ALL=C grep -e "^$octet20$hexdig* $_headmatchpat\$" <"$2" |
344 LC_ALL=C cut -d ' ' -f 1)"
345 case "$_headsha" in $octet20*) :;; *)
346 return 1
347 esac
350 # bad HEAD
351 return 1
352 esac
353 rm -rf pack_is_complete_test
354 mkdir pack_is_complete_test
355 mkdir pack_is_complete_test/refs
356 mkdir pack_is_complete_test/objects
357 mkdir pack_is_complete_test/objects/pack
358 echo "$_headsha" >pack_is_complete_test/HEAD
359 ln -s "$1" pack_is_complete_test/objects/pack/
360 ln -s "${1%.pack}.idx" pack_is_complete_test/objects/pack/
361 ln -s "$2" pack_is_complete_test/packed-refs
362 _count="$(git --git-dir=pack_is_complete_test rev-list --count --all 2>/dev/null)" || :
363 rm -rf pack_is_complete_test
364 [ -n "$_count" ] || return 1
365 [ "$_count" -gt 0 ] 2>/dev/null || return 1
366 echo "$_headsha"
369 # On return a "$lockf" will have been created that must be removed when gc is done
370 # Create a gc.pid lockfile
371 # $1 => name of variable to store result in
372 # On success:
373 # variable named by $1 will contain the name of the newly create lockfile (i.e. "gc.pid")
374 # On failure:
375 # variable named by $1 will contain the failure reason
376 v_lock_gc() {
377 # be compatibile with gc.pid file from newer Git releases
378 _lockf='gc.pid'
379 _hn="$(hostname)"
380 _active=
381 if [ "$(createlock "$_lockf")" ]; then
382 # If $_lockf is:
383 # 1) less than 12 hours old
384 # 2) contains two fields (pid hostname) NO trailing NL
385 # 3) the hostname is different OR the pid is still alive
386 # then we exit as another active process is holding the lock
387 if [ "$(find -L "$_lockf" -maxdepth 1 -mmin -720 -print 2>/dev/null)" ]; then
388 _apid=
389 _ahost=
390 read -r _apid _ahost _ajunk <"$_lockf" || :
391 if [ "$_apid" ] && [ "$_ahost" ]; then
392 if [ "$_ahost" != "$_hn" ] || pidactive "$_apid"; then
393 _active=1
397 else
398 eval "$1="'"unable to create $_lockf.lock file"'
399 return 1
401 if [ -n "$_active" ]; then
402 rm -f "$_lockf.lock"
403 eval "$1="'"gc already running on machine '\''$_ahost'\'' pid '\''$_apid'\''"'
404 return 1
406 printf "%s %s" "$$" "$_hn" >"$_lockf.lock"
407 chmod 0664 "$_lockf.lock"
408 mv -f "$_lockf.lock" "$_lockf"
409 eval "$1="'"$_lockf"'
410 return 0
413 # On return a "$lockf" will have been created that must be removed when gc is done
414 lock_gc() {
415 v_lock_gc _lockresult || {
416 echo >&2 "[$proj] $_lockresult"
417 exit 1
419 lockf="$_lockresult"
422 # Create a repack subdirectory such that running repack in it will pack the
423 # same things that a pack in the normal directory would except that the pack
424 # is guaranteed to be generated in an optimized order by adding a suitable
425 # synthesized ref in the refs/tags namespace (yes, pack-objects.c really does
426 # behave differently depending on the contents of the refs/tags namespace).
427 # Before calling this, pack-refs --all MUST be performed or the wrong pack
428 # will end up being made.
430 # If a ref deletion is pushed after making the repack subdir but before the
431 # the actual repack, the discarded objects will be packed -- no big deal,
432 # they'll get discarded the next time gc runs.
434 # If a fast-forward ref update is pushed after making the repack subdir but
435 # before the actual repack, it will be picked up and the new objects packed
436 # (subject to the normal git repack race about picking such updates up).
438 # If a non-fast-forward ref update is pushed after making the repack subdir but
439 # before the actual repack, it will be picked up like a fast-forward update but
440 # the discarded objects will be included like a ref deletion (until the next
441 # scheduled gc takes place).
443 # We retain a copy of the original packed-refs file as repack/packed-refs.orig
444 # If ref deletions come in while we're repacking, the original packed-refs
445 # file will be modified, but we'll still pack the deleted ref(s).
446 # If the packed-refs.orig file is used to create the bundle header we avoid
447 # a situation where the bundle contains a ref state that never actually
448 # existed in reality (for example a new branch is pushed and then an old
449 # branch deleted afterwards -- the deletion would show up in the bundle
450 # because it will cause the original packed-refs file to be re-written, but
451 # the new branch creation will not unless we do another pack-refs which might
452 # lead to having in incomplete bundle). Therefore we want to keep a copy of
453 # the original packed-refs file around. We do the same thing for HEAD.
455 # It's possible that the "objects" subdirectory is a symbolic link.
456 # Git does support this. However, during the repacking process, new packs
457 # will be created in repack/alt/pack and then moved into objects/pack.
458 # In order for this to work seemlessly, they must both be on the same
459 # filesystem. But when objects (or even objects/pack) is a symbolic link they
460 # might not be. For this reason a "repack" subdirectory is created under
461 # objects/pack and the repack/alt/pack directory symbolicly linked to it.
463 # Git allows not just HEAD to be a symbolic-ref, but any ref anywhere in the
464 # refs namespace. We are concerned about ref name collisions and getting the
465 # right tag set to get an optimal pack. We can safely duplicate the ref space
466 # under refs/heads, refs/notes and refs/remotes without any risk of unwanted
467 # collisions and this will likely make over 99%+ of all symbolic refs found
468 # in the wild work properly. Girocco itself never creates any symbolic refs
469 # inside the refs namespace; this is a nod to simultaneously using a Girocco
470 # repository for other purposes.
471 make_repack_dir() {
472 ! [ -d repack ] || rm -rf repack
473 ! [ -d repack ] || { echo >&2 "[$proj] cannot remove repack subdirectory"; exit 1; }
474 [ -d objects/pack ] || mkdir -p objects/pack
475 ! [ -d objects/pack/repack ] || rm -rf objects/pack/repack
476 ! [ -d objects/pack/repack ] || { echo >&2 "[$proj] cannot remove objects/pack/repack subdirectory"; exit 1; }
477 mkdir repack repack/refs repack/alt objects/pack/repack
478 [ -d info ] || mkdir info
479 ln -s ../config repack/config
480 ln -s ../info repack/info
481 ln -s ../objects repack/objects
482 ln -s "$PWD/objects/pack/repack" repack/alt/pack
483 ln -s ../../refs repack/refs/refs
484 ! [ -d logs ] || ln -s ../logs repack/logs
485 ! [ -d worktrees ] || ln -s ../worktrees repack/worktrees
486 _lines=$(( $(LC_ALL=C wc -l <packed-refs) ))
487 cat HEAD >repack/HEAD.orig
488 >repack/packed-refs.extra
489 _xtralines=0
490 cat packed-refs >repack/packed-refs.orig
491 if [ $(LC_ALL=C wc -l <repack/packed-refs.orig) -ne "$_lines" ]; then
492 echo >&2 "[$proj] error: make_repack_dir failed original packed-refs line count sanity check"
493 exit 1
495 if [ "${cfg_fetch_stash_refs:-0}" = "0" ]; then
496 # migrate any refs/stash or refs/tgstash lines to repack/packed-refs.extra
497 <repack/packed-refs.orig LC_ALL=C awk -v xtra="repack/packed-refs.extra" '
498 BEGIN { peeling = 0 }
499 NR == 1 && /^#/ { print; next; }
500 peeling && /^\^/ { print >>xtra; next; }
501 /^[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]+ refs\/(stash|tgstash)(\/|$)/ {
502 peeling = 1
503 print >>xtra
504 next
506 { peeling = 0; print; }
507 ' >repack/packed-refs.new
508 _xtralines="$(( $(LC_ALL=C wc -l <repack/packed-refs.extra) + 0 ))"
509 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs.new) + 0 ))"
510 if [ "$(( $_newlines + $_xtralines ))" -ne "$_lines" ]; then
511 echo >&2 "[$proj] error: make_repack_dir failed packed-refs.extra line count sanity check"
512 exit 1
514 mv -f repack/packed-refs.new repack/packed-refs.orig
515 _lines="$_newlines"
517 # Note: Git v1.5.0 introduced the "# pack-refs with:" header line for the packed-refs file
518 sed '/^# pack-refs/d; s, refs/, refs/!/,' <repack/packed-refs.orig >repack/packed-refs
519 nohead=
520 headref="$(git rev-parse --verify --quiet HEAD)" || :
521 if [ -n "$headref" ]; then
522 echo "$headref refs/!=/HEAD" >>repack/packed-refs
523 echo "$headref refs/heads/!" >>repack/packed-refs
524 nohead='\, refs/heads/!$,d; '
525 _lines=$(( $_lines + 2 ))
527 if [ $(( $(LC_ALL=C wc -l <repack/packed-refs) + 1 )) -ne "$_lines" ]; then
528 echo >&2 "[$proj] error: make_repack_dir failed packed-refs initial line count sanity check"
529 exit 1
531 sed -n "$nohead"'\, refs/heads/,p; \, refs/notes/,p; \, refs/remotes/,p' <repack/packed-refs.orig >>repack/packed-refs
532 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs) ))"
533 if [ $(( $_newlines + 1 )) -lt "$_lines" ]; then
534 echo >&2 "[$proj] error: make_repack_dir failed packed-refs extra line count sanity check"
535 exit 1
537 _lines="$_newlines"
538 optref="$(git rev-list -n 1 --all 2>/dev/null)" || :
539 if [ -n "$optref" ]; then
540 echo "$optref refs/tags/!" >>repack/packed-refs
541 _lines=$(( $_lines + 1 ))
542 echo "$optref" >repack/HEAD
543 else
544 cat HEAD >repack/HEAD
546 if [ $(LC_ALL=C wc -l <repack/packed-refs) -ne "$_lines" ]; then
547 echo >&2 "[$proj] error: make_repack_dir failed packed-refs line count sanity check"
548 exit 1
552 # Remove any crud that's been left behind by interrupted operations
553 # that did not clean up after themselves
554 remove_crud() {
555 # Remove any existing FETCH_HEAD
556 # There can only be a FETCH_HEAD if we've been fetching, not if we've been
557 # receiving pushes (those never create a FETCH_HEAD).
558 # And if we're fetching because we're a mirror, we know we're not fetching right
559 # now since jobd.pl never runs a project's fetch simultaneously with its gc.
560 # Therefore any existing FETCH_HEAD is junk. And it may be many megabytes if
561 # there were a lot of refs.
562 rm -f FETCH_HEAD
564 # remove any existing pack_is_complete_test or repack subdirectories
565 # If either exists when this function is called it's crud
566 rm -rf pack_is_complete_test repack objects/pack/repack
568 # Remove any stale pack remnants that are more than an hour old.
569 # Stale pack fragments are defined as any pack-<sha1>.ext where .ext is NOT
570 # .pack AND the corresponding .pack DOES NOT exist. A bunch of stale
571 # pack-<sha1>.idx files without their corresponding .pack files are worthless
572 # and just waste space. Normally there shouldn't be any remnants but actually
573 # this can happen when things are interrupted at just the wrong time.
574 # Note that the objects/pack directory is created by git init and should
575 # always exist.
576 find -L objects/pack -maxdepth 1 -type f -mmin +60 -name "pack-$octet20*.?*" -print |
577 LC_ALL=C sed -e 's/^objects\/pack\/pack-//; s/\..*$//' | LC_ALL=C sort -u |
578 while read packsha; do
579 ! [ -e "objects/pack/pack-$packsha.pack" ] || continue
580 rm -f "objects/pack/pack-$packsha".?*
581 done
583 # Remove any stale tmp reflogs files that are more than one hour old.
584 # Since they are created only while the pre-receive hook is running and
585 # all it does is process a bunch of refs passed to it on standard input
586 # it's inconceivable that it would ever take as much as an hour to run.
587 if [ -d reflogs ]; then
588 find -L reflogs -maxdepth 1 -type f -mmin +60 -name "tmp_*" -exec rm -f '{}' + || :
591 # Remove any stale object tmp_obj_* files that are more than 3 hours old.
592 # Really these files should only exist very briefly so there shouldn't be any
593 # but things happen that can end up leaving them behind.
594 find -L objects/$octet -maxdepth 1 -type f -mmin +180 -name "tmp_obj_?*" -exec rm -f '{}' + 2>/dev/null || :
596 # Remove any stale pack .keep files that are more than 12 hours old.
597 # We don't do anything to create any permanent pack .keep files, so they must
598 # be remnants from some failed push or something. Removing the .keep will
599 # allow the pack to be properly repacked.
600 find -L objects/pack -maxdepth 1 -type f -mmin +720 -name "pack-$octet20*.keep" -exec rm -f '{}' + || :
602 # Remove any stale tmp_pack_*, tmp_idx_*, tmp_bitmap_*, packtmp-* or .tmp-*-pack* files
603 # that are more than 12 hours old.
604 find -L objects/pack -maxdepth 1 -type f -mmin +720 \( \
605 -name "tmp_pack_?*" -o -name "tmp_idx_?*" -o -name "tmp_bitmap_?*" -o \
606 -name "packtmp-?*" -o -name ".tmp-?*-pack*" \
607 \) -exec rm -f '{}' + || :
609 # Remove any stale incoming-* object quarantine directories that are
610 # more than 12 hours old. These are new with Git >= 2.11.0.
611 find -L objects -maxdepth 1 -type d -name 'incoming-?*' -mmin +720 \
612 -exec rm -rf '{}' + || :
614 # Remove any stale shallow_* files that are more than 12 hours old.
615 # These can be left behind by Git >= 1.8.4.2 and < 2.0.0 when a client
616 # requests a shallow clone. Also discard stale .refs-temp* and
617 # .refs-new* files at the same time.
618 find -L . -maxdepth 1 -type f -mmin +720 \( \
619 -name "shallow_?*" -o -name ".refs-temp*" -o -name ".refs-new*" \
620 \) -exec rm -f '{}' + || :
622 # Remove any stale cmbnpcks-* dirs that are more than 12 hours old.
623 # These can be left behind by abnormal exits (e.g. power failure).
624 find -L . -maxdepth 1 -type d -mmin +720 -name "cmbnpcks-?*" \
625 -exec rm -rf '{}' + || :
627 # Remove any stale *.temp files in the objects area that are more than 12 hours old.
628 # This can be stale sha1.temp, or stale *.pack.temp so we kill all stale *.temp.
629 find -L objects -type f -mmin +720 -name "*.temp" -exec rm -f '{}' + || :
631 # Remove any stale *.lock files in the htmlcache area that might have been left
632 # behind after an abnormal exit during an attempt to update a cached file and
633 # are more than 1 hour old.
634 ! [ -d htmlcache ] || find -L htmlcache -type f -mmin +60 -name "*.lock" -exec rm -f '{}' + || :
636 # Remove any stale git-svn temp files that are more than 12 hours old.
637 # The git-svn process creates temp files with random 10 character names
638 # in the root of $GIT_DIR. Unfortunately they do not have a recognizable
639 # prefix, so we just have to kill any files with a 10-character name. We
640 # do this only for git-svn mirrors. All characters are chosen from
641 # [A-Za-z0-9_] so we can at least check that and fortunately the only
642 # collision is 'FETCH_HEAD' but that shouldn't matter.
643 # There may also be temp files with a Git_ prefix as well.
644 if [ -n "$svn_mirror" ]; then
645 _randchar='[A-Za-z0-9_]'
646 _randchar2="$_randchar$_randchar"
647 _randchar4="$_randchar2$_randchar2"
648 _randchar10="$_randchar4$_randchar4$_randchar2"
649 find -L . -maxdepth 1 -type f -mmin +720 -name "$_randchar10" -exec rm -f '{}' + || :
650 find -L . -maxdepth 1 -type f -mmin +720 -name "Git_*" -exec rm -f '{}' + || :
653 # Remove any stale fast_import_crash_<pid> files that are more than 3 days old.
654 if [ -n "$gfi_mirror" ]; then
655 find -L . -maxdepth 1 -type f -mmin +4320 -name "fast_import_crash_?*" -exec rm -f '{}' + || :
658 # Remove any stale core or *.core or core.* files that are more than 3 days old.
659 find -L . -maxdepth 1 -type f -mmin +4320 \( -name "core" -o -name "*.core" -o -name "core.*" \) \
660 -exec rm -f '{}' + || :
664 ## Garbage Collection Types
666 ## There are two kinds of possible garbage collection (gc) operations:
668 ## 1. A normal, full gc
669 ## 2. A "mini" gc
671 ## If the full garbage collection interval has expired (or gc has never been
672 ## run), then a normal, full gc will take place. Otherwise, a "mini" gc will
673 ## take place if the file .needsgc exists.
675 ## A "mini" gc is similar to "git gc --auto" in that it may not end up actually
676 ## doing anything unless the right conditions are present so it's not a burden
677 ## to run it often. If the file .needsgc exists, a "mini" gc will occur at
678 ## the next opportunity.
680 ## See the docs/technical/gc.txt and docs/technical/gc-mini.txt files for more
681 ## of the gory details of how garbage collection is performed.
683 ## Note, however, that the .nogc file suppresses ALL gc activity (normal or mini).
686 proj="${1%.git}"
687 shift
688 cd "$cfg_reporoot/$proj.git"
689 [ -d objects/pack ] || { rm -f gfi-packs; mkdir -p objects/pack; }
690 mirror_url="$(get_mirror_url)" || :
691 svn_mirror=
692 ! is_svn_mirror_url "$mirror_url" || svn_mirror=1
693 gfi_mirror=
694 if [ -f gfi-packs ] && [ -s gfi-packs ] && is_gfi_mirror_url "$mirror_url"; then
695 gfi_mirror=1
698 # If git config --bool --get girocco.redelta is explicitly false then automatic
699 # redelta when there are less than $var_redelta_threshold objects will be suppressed.
700 # On the other hand, if git config --get girocco.redelta is "always" then, on a full
701 # gc only, for the final repack, deltas will always be recomputed.
702 # This can be set on a per-project basis to avoid unusual pathological gc behavior.
703 # Setting this will hurt efficiency of the affected repository.
704 # Note that fast-import packs ALWAYS get new deltas regardless of this setting.
705 noreusedeltaopt="--no-reuse-delta"
706 [ "$(git config --bool --get girocco.redelta 2>/dev/null || :)" != "false" ] || noreusedeltaopt=
707 alwaysredelta=
708 [ "$(git config --get girocco.redelta 2>/dev/null || :)" != "always" ] || alwaysredelta=1
710 # Extract any -f or -F or --no-reuse-object or --no-reuse-delta options
711 # to be compatible with the old and new gc.sh versions and avoid ugly argument
712 # duplication in process lists at the same time
713 # Any options found will override the "girocco.redelta" setting
714 recompress=
715 idx=$#
716 while [ $idx -gt 0 ]; do
717 idx=$(( $idx - 1 ))
718 opt="$1"
719 shift
720 case "$opt" in
721 -f|--no-reuse-delta)
722 alwaysredelta=1
723 continue
725 -F|--no-reuse-object)
726 alwaysredelta=1
727 recompress=1
728 continue
730 -?*)
733 printf >&2 '%s\n' "bad non-option argument: $opt"
734 echo >&2 "(Did you perhaps intend to use a --xxx=yyy form?)"
735 exit 1
736 esac
737 [ -z "$opt" ] || set -- "$@" "$opt"
738 done
739 if [ -n "$alwaysredelta" ]; then
740 noreusedeltaopt="--no-reuse-delta"
741 [ -z "$recompress" ] || noreusedeltaopt="--no-reuse-object"
744 trap 'e=$?; rm -f .gc_in_progress; if [ $e != 0 ]; then echo "gc failed dir: $PWD" >&2; fi' EXIT
745 trap 'exit 130' INT
746 trap 'exit 143' TERM
748 # date -R is linux-only, POSIX equivalent is '+%a, %d %b %Y %T %z'
749 datefmt='+%a, %d %b %Y %T %z'
751 isminigc=
752 if [ "${force_gc:-0}" = "0" ] && check_interval lastgc $cfg_min_gc_interval; then
753 if [ -e .needsgc ]; then
754 isminigc=1
755 else
756 progress "= [$proj] garbage check skip (last at $(config_get lastgc))"
757 exit 0
760 if [ -e .nogc ]; then
761 progress "x [$proj] garbage check disabled"
762 exit 0
764 if ! [ -e .nofetch ] && [ -e .clone_in_progress ] && ! [ -e .clone_failed ]; then
765 progress "x [$proj] garbage check disabled (clone in progress)"
766 exit 0
768 if [ -z "$isminigc" ] && [ -e .delaygc ] && [ -e .needsgc ]; then
769 # Eligible for a full gc but .delaygc is set so it would be skipped
770 # However .needsgc is also set so transform it into a mini instead
771 isminigc=1
772 progress "~ [$proj] garbage check delayed but checking mini because .needsgc"
775 if [ -n "$isminigc" ]; then
776 # Perform a "mini" gc
777 # Note that .delaygc is ignored here as that's only intended for full gc
778 lock_gc
779 rm -f .allowgc .needsgc
780 rm -f objects/pack/pack-*_[rful].keep
781 remove_crud
782 coalesce_reflogs
783 prune_reflogs
784 compact_reflogs
785 maintain_auto_gc_hack
786 generate_auto_gc_update
787 miniactive=
788 if [ -f .needspack ]; then
789 miniactive=1
790 progress "+ [$proj] mini garbage check ($(date))"
791 make_needs_pack
793 if [ -z "$cfg_delay_gfi_redelta" ] && [ -n "$gfi_mirror" ]; then
794 # $Girocco::Config::delay_gfi_redelta is false, force redeltification now
795 if [ -z "$miniactive" ]; then
796 miniactive=1
797 progress "+ [$proj] mini garbage check ($(date))"
799 repack_gfi_packs
801 if lotsa_loose_objects; then
802 if [ -z "$miniactive" ]; then
803 miniactive=1
804 progress "+ [$proj] mini garbage check ($(date))"
806 pack_loose_objects
808 # If there aren't at least 10 non-keep, non-bitmap, non-bndl packs then
809 # don't actually process them yet
810 lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl --quiet"
811 packcnt="$(list_packs --count $lpo objects/pack)" || :
812 if [ "${packcnt:-0}" -ge 10 ]; then
813 if [ -z "$miniactive" ]; then
814 miniactive=1
815 progress "+ [$proj] mini garbage check ($(date))"
817 # if we have at least 10 packs go ahead and pack all refs now too
818 git pack-refs --all --prune
819 if [ -n "$gfi_mirror" ]; then
820 repack_gfi_packs
821 packcnt="$(list_packs --count $lpo objects/pack)" || :
823 # if repack_gfi_packs dropped the pack count to < 10 don't combine
824 if [ "${packcnt:-0}" -ge 10 ]; then
825 combine_small_packs
826 combine_small_loose_packs
827 packcnt="$(list_packs --count $lpo objects/pack)" || :
829 # if we still have more than 10 packs trigger a full gc
830 if [ "${packcnt:-0}" -ge 10 ]; then
831 # We shouldn't be in a .delaygc state at this point, but if
832 # we are then nuke it because we really need a full gc now
833 rm -f .delaygc
834 git config --unset gitweb.lastgc
835 rm -f "$lockf"
836 git update-server-info # just in case
837 progress "- [$proj] mini garbage check triggering full gc too many packs ($(date))"
838 exit 0
841 rm -f "$lockf"
842 if [ -n "$miniactive" ]; then
843 git update-server-info
844 progress "- [$proj] mini garbage check ($(date))"
845 else
846 progress "= [$proj] mini garbage check nothing but crud removal to do ($(date))"
848 exit 0
851 # Avoid unnecessary garbage collections:
852 # 1. If lastreceive is set and is older than lastgc
853 # -AND-
854 # 2. We are not a fork (is_empty_alternates_file) -OR- lastparentgc is older than lastgc
856 # If lastgc is NOT set or lastreceive is NOT set we MUST run gc
857 # If we are a fork and lastparentgc is NOT set we MUST run gc
859 # If the repo is dirty after removing any crud we MUST run gc
861 gcstart="$(date "$datefmt")"
862 skipgc=
863 isfork=
864 is_empty_alternates_file objects/info/alternates || isfork=1
865 lastparentgcsecs=
866 [ -z "$isfork" ] || lastparentgcsecs="$(config_get_date_seconds lastparentgc)" || :
867 lastreceivesecs=
868 if lastreceivesecs="$(config_get_date_seconds lastreceive)" &&
869 [ "${force_gc:-0}" = "0" ] &&
870 lastgcsecs="$(config_get_date_seconds lastgc)" &&
871 [ $lastreceivesecs -lt $lastgcsecs ]; then
872 # We've run gc since we last received, so maybe we can skip,
873 # check if not fork or fork and lastparentgc < lastgc
874 if [ -n "$isfork" ]; then
875 if [ -n "$lastparentgcsecs" ] &&
876 [ $lastparentgcsecs -lt $lastgcsecs ]; then
877 # We've run gc since our parent ran gc so we can skip
878 skipgc=1
880 else
881 # We don't have any alternates (we're not a forK) so we can skip
882 skipgc=1
886 # Prevent any other simultaneous gc operations
887 lock_gc
889 # At this point, if .allowgc or .gc_failed exists, it's now crud to be removed
890 rm -f .allowgc .gc_failed
892 # Ideally we would do this in post-receive, but that would mean duplicating the
893 # logic so it's available in the chroot jail and that's highly undesirable
894 # Instead, since the first gc will be triggered immediately following the first
895 # push, we do the check here as it's quick and harmless if HEAD is already valid
896 check_and_set_head || :
898 # Always get rid of crud
899 remove_crud
901 # Always perform reflogs maintenance
902 coalesce_reflogs
903 prune_reflogs
904 compact_reflogs
906 # Always maintain auto gc hack
907 maintain_auto_gc_hack
908 generate_auto_gc_update
910 # Run 'git svn gc' now for svn mirrors
911 if [ -n "$svn_mirror" ]; then
912 git svn gc || :
915 # Skip the actual gc if .delaygc is set
916 if [ -e .delaygc ]; then
917 progress "x [$proj] garbage check delayed (except for crud removal)"
918 rm -f "$lockf"
919 exit 0
922 # Do not skip gc if the repo is dirty
923 if [ -n "$skipgc" ] && ! is_dirty; then
924 progress "= [$proj] garbage check nothing but crud removal to do ($(date))"
925 config_set lastgc "$gcstart"
926 rm -f "$lockf"
927 exit 0
930 bumptime=
931 if [ -n "$isfork" ] && [ -z "$lastparentgcsecs" ]; then
932 # set lastparentgc and then update gcstart to be at least 1 second later
933 config_set lastparentgc "$gcstart"
934 bumptime=1
936 if [ -z "$lastreceivesecs" ]; then
937 # set lastreceive and then update gcstart to be at least 1 second later
938 config_set lastreceive "$gcstart"
939 bumptime=1
941 if [ -n "$bumptime" ]; then
942 sleep 1
943 gcstart="$(date "$datefmt")"
946 progress "+ [$proj] garbage check ($(date))"
948 newdeltas=
949 [ -z "$alwaysredelta" ] || newdeltas="$noreusedeltaopt"
950 if [ -z "$newdeltas" ] && [ -n "$gfi_mirror" ]; then
951 if [ $(list_packs --exclude-no-idx --count objects/pack) -le \
952 $(list_packs --exclude-no-idx --count --quiet --only gfi-packs) ]; then
953 # Don't bother with repack_gfi_packs since everything's being repacked
954 newdeltas="--no-reuse-delta"
957 if [ -z "$newdeltas" ] && [ -n "$noreusedeltaopt" ] &&
958 [ $(list_packs --all --exclude-no-idx --count-objects objects/pack) -le $var_redelta_threshold ]; then
959 # There aren't enough objects to worry about so just redelta to get the best pack
960 newdeltas="--no-reuse-delta"
962 if [ -z "$newdeltas" ]; then
963 # Since we're not going to recompute deltas overall, we need to do the
964 # "mini" maintenance so that we can get more optimal deltas
965 [ -z "$noreusedeltaopt" ] || make_needs_pack
966 repack_gfi_packs
967 force_single_pack_redelta=
968 [ -n "$gfi_mirror" ] || [ -n "$svn_mirror" ] || force_single_pack_redelta=1
969 [ -z "$noreusedeltaopt" ] || combine_small_packs $force_single_pack_redelta
970 [ -z "$noreusedeltaopt" ] || combine_small_loose_packs $force_single_pack_redelta
974 ## Safe Pruning In Forks
976 ## We are about to perform garbage collection. We do NOT use the "git gc" or
977 ## the "git repack" commands directly as they do not provide enough control over
978 ## the fine details. However, we DO maintain a "gc.pid" file during our garbage
979 ## collection so that a simultaneous "git gc" by an administrator will be
980 ## blocked (and similarly we refuse to start garbage collection if we cannot
981 ## create the "gc.pid" file).
983 ## When we say "gc" in the below description we are referring to our "gc.sh"
984 ## script, NOT the "git gc" command.
986 ## If the project we are running garbage collection (gc) on has any forks we
987 ## must be careful not to remove any objects that while no longer referenced by
988 ## this project (the parent) are still referenced by one or more forks (the
989 ## children) otherwise the children will become corrupt and we can't abide
990 ## corrupt children.
992 ## One way to accomplish this is to simply hard-link all currently existing
993 ## loose objects and packs in the parent into all the children that refer to the
994 ## parent (via a line in their objects/info/alternates file) before beginning
995 ## the gc operation and then relying on a subsequent gc in the child to clean up
996 ## any excess objects/packs. We used to use this strategy but it's very
997 ## inefficient because:
999 ## 1. The disk space used by the old pack(s)/object(s) will not be reclaimed
1000 ## until all children (and their children, if any) run gc by which time
1001 ## it's quite possible the topmost parent will have run gc again and
1002 ## hard-linked yet another old pack down to its children (not to mention
1003 ## loose objects).
1005 ## 2. When using the "-A" option with "git repack", any new objects in the
1006 ## parent that are not referenced by children will continually get
1007 ## exploded out of the hard-linked pack in the children whenever the
1008 ## children run gc.
1010 ## 3. To avoid suboptimal and/or unnecessarily many packs being hard-linked
1011 ## into child forks, we must run the "mini" gc maintenance before we
1012 ## perform the hard-linking into the children which provides yet another
1013 ## source of inefficiency.
1015 ## While we were still using the "-A" option to "git repack" (that was not
1016 ## always the case) to guarantee we can access old ref values for long enough
1017 ## to send out a meaningful mail.sh notification, another, more efficient,
1018 ## option became available to prevent corruption of child forks that continue
1019 ## to refer to objects that are no longer reachable from any ref in the parent.
1021 ## The only things that need be copied (or hard-linked) into the child fork(s)
1022 ## are those objects that have become unreachable from any ref in the parent.
1024 ## When we were using the "git repack -A -d" + "git prune --expire=1.day.ago"
1025 ## technique, the only objects that could ever be removed were loose objects
1026 ## that "git prune" determined were expired. In that case, loose objects were
1027 ## all that need be hard-linked down to child forks in order to avoid
1028 ## corruption of any child fork(s).
1030 ## The "git repack -A -d" + "git prune --expire=1.day.ago" + hard-linking loose
1031 ## objects to child forks technique remains fundamentally sound from the
1032 ## perspective of supporting simultaneous gc and push and keeping newly
1033 ## unreachable objects around long enough to be sure we can send out meaningful
1034 ## ref change notifications and never corrupting any child forks and never
1035 ## persisting the lifetime of large old packs containing mostly duplicate or
1036 ## unreachable objects as gc percolates through a project's entire fork tree.
1038 ## However, that technique suffers from one potential prodigious pitfall.
1040 ## Unreachable objects come flying out of their packs to splatter all over the
1041 ## objects subdirectories possibly creating a huge, inefficient mess.
1043 ## Often this is not an issue. Even with a lot of rebasing going on, usually
1044 ## the only objects that will splatter are some commits, trees and the odd blob
1045 ## here and there. Not enough to be overly concerned about.
1047 ## However, for the reppository that frequently experiences a lot of non-fast-
1048 ## forward updates and/or outright ref deletion, the number of objects suddenly
1049 ## popping out of their packs at "git repack -A -d" time can be overwhelming.
1051 ## To avoid this issue we now use a four phase pack creation strategy.
1052 ## This will result in creation of up to four packs (instead of at most one).
1054 ## I. A complete pack (with bitmaps if appropriate) gets created including
1055 ## only "reachable" objects from all refs/... refs plus HEAD. This will
1056 ## also serve as the virtual bundle for the repository.
1058 ## II. A pack of recently-became-unreachable objects and friends is created.
1059 ## (The "friends" are ref logs, linked working tree HEADs and indicies.)
1060 ## Because both the pre-receive and update.sh script record all ref
1061 ## changes we can easily choose the cut off point for "recently".
1062 ## It is only the fact we maintain those logs in the reflogs subdirectory
1063 ## that allows this step to be possible.
1065 ## III. If the repository has any forks with a non-zero length alternates file,
1066 ## yet another pack of "--keep-unreachable" objects is generated that will
1067 ## not actually be kept in the parent, but hard-linked into all the forks.
1069 ## IV. Finally, after running "git prune-packed", any remaining loose objects
1070 ## are migrated into a pack of their own.
1072 ## We then remove any non-.keep packs that existed before we started the
1073 ## process being careful to keep any same-pack pushes for the "Push Pack Redux"
1074 ## race condition (see docs/technical/gc.txt).
1076 ## By using "git pack-objects" directly we are able to accomplish this with
1077 ## very little additional effort.
1079 ## The packs produced by (III) are treated almost like ".keep" packs by child
1080 ## forks in that the objects in them are never repacked into any other
1081 ## "--keep-unreachable" packs (but they can migrate into phase I or II packs)
1082 ## and those phase III packs are then hard-linked into any grandchild forks.
1084 ## This avoids the space explosion that could occur if each fork level ended
1085 ## up duplicating the "--keep-unreachable" pack space by repacking those
1086 ## objects (essentially breaking the hard-link to the single copy of those
1087 ## objects).
1089 ## While it is true that each level of forks could potentially add yet another
1090 ## phase III pack to be hard-linked down to its children, such packs will only
1091 ## include unreachable objects not already in any phase III packs that were
1092 ## received from the parent.
1094 ## The space for the phase III packs will not be reclaimed until the gc
1095 ## finishes percolating through the entire "fork tree" of a project.
1097 ## This is not much different than the "git repack -A -d" situation where
1098 ## all the loose objects are hard-linked down into child forks. In that
1099 ## case forks that actually need any of those objects could gradually reduce
1100 ## the number of objects hard-linked into deeper fork levels.
1102 ## The difference with a phase III "--keep-unreachable" pack is that there
1103 ## cannot be any gradual reduction like that since it would require repacking
1104 ## the pack and breaking the hard-link thereby increasing storage space. The
1105 ## storage will instead always be reclaimed all at once when all of the
1106 ## projects in the "fork tree" complete their gc.
1108 ## However, the belief is that the huge space win by having all the
1109 ## unreachable objects packed up together far eclipses (when many objects are
1110 ## involved, the single-pack version can end up using 1/20th or less of the
1111 ## disk space compared to having them all as loose objects) any brief minor
1112 ## space savings that might occur under the "git repack -A -d" loose object
1113 ## system prior to the gc collection completing for all the projects in the
1114 ## "fork tree".
1118 ## utility functions
1121 make_packs_ugw() {
1122 find -L "$1" -maxdepth 1 -type f ! -perm -ug+w \
1123 -name "pack-$octet20*.pack" -exec chmod ug+w '{}' + || :
1124 } 2>/dev/null
1126 get_index_tree() {
1127 if [ -s "$1" ]; then
1128 GIT_INDEX_FILE="$1"
1129 export GIT_INDEX_FILE
1130 git write-tree 2>/dev/null || :
1131 unset GIT_INDEX_FILE
1135 get_detached_head() {
1136 if [ -s "$1" ] && read -r _head <"$1" 2>/dev/null; then
1137 case "$_head" in $octet20*)
1138 echo "$_head"
1139 esac
1143 # single argument must be a top-level GIT_DIR
1144 # output will be (one per line, zero or more lines) full hash
1145 # values (i.e. 40 or more hex digits) from possible detached head
1146 # "single level" refs (e.g. "FETCH_HEAD" "MERGE_HEAD" etc.) from
1147 # files in the specified directory that have a "suitable" name and
1148 # have a length >= 40 and <= 1000 where EVERY line in a file MUST
1149 # match a 40 digit (or longer) hex string or that file will be ignored.
1150 # In a nod to Git each line first has any tab and anything following truncated.
1151 # NO sorting NOR "uniq"ing NOR "--batch-check"ing is performed on the output.
1152 # Also note that "HEAD" is NOT EXCLUDED and if detached will be output!
1153 get_detached_friends() {
1154 if [ -n "$1" ] && [ -d "$1" ]; then
1155 LC_ALL=C find -H "$1" -maxdepth 1 -name '[A-Za-z]*[A-Za-z0-9]' \
1156 -type f -size +39c -size -1001c -exec awk '
1157 BEGIN {exit}
1158 function process(fn, fnt, hashes, hcnt, fl, hi) {
1159 fnt = fn; sub(/^.*\//, "", fnt)
1160 if (length(fnt) > 31 || fnt !~ /^[A-Za-z][A-Za-z0-9_-]*[A-Za-z0-9]$/) return;
1161 hcnt = 0;
1162 while (getline fl < fn) {
1163 sub(/\t.*$/, "", fl)
1164 if (length(fl) < 40 || fl !~ /^[0-9a-fA-F][0-9a-fA-F]*$/) {hcnt = 0; break;}
1165 hashes[++hcnt] = fl;
1167 close(fn)
1168 for (hi=1;hi<=hcnt;++hi) print tolower(hashes[hi]);
1170 END {for (idx=1;idx<ARGC;++idx) process(ARGV[idx])}
1171 ' '{}' '+' 2>/dev/null || :
1175 # get_worktrees_friends
1176 # single argument is a (possibly relative) path to a "worktrees" subdir
1177 # if omitted it defaults to "worktrees"
1178 # any "friends" found in there are output to stdout
1179 get_worktrees_friends() {
1180 if [ -d "${1:-worktrees}" ]; then
1181 find -L "${1:-worktrees}" -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1182 while read -r _lwth; do
1183 get_detached_head "$_lwth"
1184 get_detached_friends "${_lwth%HEAD}"
1185 get_index_tree "${_lwth%HEAD}index"
1186 done
1190 # compute_extra_reachables
1191 # create lines suitable for a packed-refs file mentioning all the
1192 # other refs we might like to keep.
1193 # the current directory MUST be set to the repository's --git-dir
1194 # the following are included:
1195 # * refs mentioned in repack/packed-refs.extra (if it exists)
1196 # * refs mentioned in reflogs/... files
1197 # * tree(s) created from index file(s)
1198 # * detached linked working tree heads
1199 # Resulting objects are tested for existence and uniqified then output
1200 # one per line under a refs/z* namespace
1201 compute_extra_reachables() {
1203 if [ -s repack/packed-refs.extra ]; then
1204 LC_ALL=C sed <repack/packed-refs.extra -n \
1205 -e 's/^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p' \
1206 -e 's/^\^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p'
1208 digits8='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
1209 find -L reflogs -mindepth 1 -maxdepth 1 -type f -name "$digits8*" -exec gzip -c -d -f '{}' + |
1210 LC_ALL=C awk '{print $2; print $3}'
1211 get_detached_friends .
1212 ! [ -f index ] || get_index_tree index
1213 get_worktrees_friends
1215 is_git_dir private &&
1216 [ "$(cd objects && pwd -P)" = "$(cd private/objects && pwd -P)" ] &&
1217 [ "$(cd refs && pwd -P)" != "$(cd private/refs && pwd -P)" ]
1218 then
1219 git --git-dir=private show-ref --head --hash 2>/dev/null || :
1220 get_detached_friends private
1221 ! [ -f private/index ] || get_index_tree private/index
1222 get_worktrees_friends private/worktrees
1224 } | LC_ALL=C sort -u |
1225 git cat-file ${var_have_git_260:+--buffer} --batch-check"${var_have_git_185:+=%(objectname)}" |
1226 LC_ALL=C awk '!/missing/ {num++; print $1 " " "refs/" substr("zzzzzzzzzzzz", 1, length(num)) "/" num}'
1230 ## main gc logic
1233 # Everything else is more efficient if we do this first
1234 # The "--prune" option is the default since v1.5.0 but it serves as "documentation" here
1235 git pack-refs --all --prune
1236 [ -e packed-refs ] || >>packed-refs # should never happen...
1238 # If we have a logs directory or a worktrees directory expire the ref logs now
1239 # Note that Git itself does not use either --rewrite or --updateref, so neither do we
1240 ! [ -d logs ] && ! [ -d worktrees ] || eval git reflog expire --all "${quiet:+>/dev/null 2>&1}" || :
1242 make_repack_dir
1243 ! [ -e .gc_failed ] || exit 1
1244 rm -f .gc_in_progress # make sure
1245 touch .gc_in_progress # it's truly fresh
1246 rm -f bundles/* objects/pack/pack-*.bndl
1247 # These only exist for a brief time before the packs loose their _f suffix
1248 # "Push Pack Redux" does not apply to these since they were only ever present with _f
1249 rm -f objects/pack/pack-*_f.keep
1250 # This is perhaps a bit aggressive in that if we're suffering from "Push Pack Redux"
1251 # and somehow we get run again immediately after the run where "Push Pack Redux" happened
1252 # and we have garbage collection forced, there's just the barest, almost negligible,
1253 # possibility that the "Push Pack Redux" ref updates _still_ have not happened and we
1254 # should not be removing _r .keep files. None of the normal Girocco processing can
1255 # cause this. The second run of this script would have to use the force gc option
1256 # for it to even be possible in the first place. What's much more likely is that
1257 # the initial run of this script was somehow interrupted in the middle before it
1258 # could get rid of the _r .keep file itself in which case it's better to get rid of
1259 # it now to avoid keeping something around that would perturb our nice and neat gc
1260 rm -f objects/pack/pack-*_r.keep
1261 # We will add .keep files for _u and _l packs if and when we run phase III
1262 # Otherwise they need to not have any .keep files during phases I and II
1263 rm -f objects/pack/pack-*_[ul].keep
1265 # We need to make sure that any non-Girocco (barely tolerated) Git object creation
1266 # activity will be able to "freshen" the pack containing a pre-existing object
1267 # that's being written. This really should not be necessary as the pre-receive
1268 # hook should make sure this takes place for any incoming pushes.
1269 # However, do it here anyway just in case.
1270 make_packs_ugw objects/pack
1272 # This is only effective with Git v2.3.5 and later and it will only matter when
1273 # we are using one of the "internal_rev_list" modes of pack-objects
1274 # (the combine-packs.sh script never uses any of those modes)
1275 # The "git repack" and "git prune" commands always set this internally themselves
1276 # It makes no difference if there's no repository corruption
1277 GIT_REF_PARANOIA=1 && export GIT_REF_PARANOIA
1279 # All of the options we might want to use with pack-objects were supported
1280 # at some point prior to Git version v1.6.6 which is the minimum version that
1281 # Girocco now requires. Except for one (--use-bitmap-index). Several of them
1282 # are "boiler plate" options we always want to use so we bundle them up here.
1283 pkopt="--delta-base-offset --keep-true-parents --non-empty --all-progress-implied"
1284 # We want to use --include-tag, but before Git v2.10.1 it would leave out
1285 # "middle" tags (e.g. a tag of a tag of a commit would omit the tagged tag)
1286 # See http://repo.or.cz/git.git/b773ddea2cd3b08c for details
1287 # ("pack-objects: walk tag chains for --include-tag", 2016-09-07, v2.10.1)
1288 # This is not a free check as it matches all refs against refs/tags/ then
1289 # peels all the annotated tags and checks for inclusion. The situation in
1290 # which it would add a tag that was not already included by a reachability
1291 # trace that included tag starting points can only occur if a new tag gets
1292 # pushed during gc pointing to something that would have been packed anyway.
1293 # But, it could happen and, really, compared to gc as a whole it's not that
1294 # expensive to perform (provided we do not get an unconnected pack).
1295 [ -z "$var_have_git_2101" ] || pkopt="$pkopt --include-tag"
1296 pkopt="$pkopt ${quiet:---progress} $packopts"
1298 # The git pack-objects command only supports bitmaps if all objects are being
1299 # packed (the "--all" option) and the "--stdout" option is NOT being used.
1300 # Additionally, while packing, if any encountered reachable objects are
1301 # determined to be "not wanted" then no bitmap index will be written anyway.
1302 # While it is theoretically possible that a project with a non-empty alternates
1303 # file ends up packing all objects (because it does not actually use any of the
1304 # objects found in the alternates), it's very unlikely. And, in the unlikely
1305 # event that did occur, clients would see a message about only using one bitmap
1306 # because Git can only use one bitmap at a time and at least one of the
1307 # alternates is bound to have a bitmap. Therefore if we see a non-empty
1308 # alternates file, we disable writing bitmaps which avoids the warning and any
1309 # possibility of a client warning as well. Also if we are running anything
1310 # before Git v2.1.0 (the effective version for repack.writeBitmaps=true) then
1311 # we also always disable bitmap writing.
1312 wbmopt=
1313 [ -z "$var_have_git_210" ] || wbmopt="--write-bitmap-index"
1314 # More recent versions of pack-objects have optimizations when not using the
1315 # --local option. If we do not have any alternates it's a pointless option.
1316 # If we do have alternates we need to skip writing a bitmap and we cannot
1317 # have a bundle since it must contain all objects.
1318 if [ -n "$isfork" ]; then
1319 lclopt="--local"
1320 wbmopt=
1321 makebndl=
1322 else
1323 lclopt=
1324 makebndl=1
1328 ## Phase I
1331 wbmstr=
1332 [ -n "$wbmopt" ] || wbmstr=" (bitmaps disabled)"
1333 progress "~ [$proj] running primary full gc pack-objects$wbmstr ($(date))"
1335 gotforks=
1336 ! has_forks_with_alternates "$proj" || gotforks=1
1338 # To avoid "Push Pack Redux" (see docs/technical/gc.txt), after collecting the
1339 # initial preexisting non-keep pack list, we rename them so that an incoming push
1340 # pack cannot possibly experience a pack name collision. Git does not require
1341 # use of the "default" pack names, simply that the proper extensions are used.
1342 # We rename to insert an "_r" just before the extension to avoid "Push Pack Redux"
1343 # name collisions. Later on we may create an "unreachable" pack for hard-linking
1344 # down into forks and it will have an "_u" inserted just before its extension.
1345 packlist="$(list_packs -C objects/pack --all --exclude-no-idx --exclude-keep --quiet .)" || :
1346 oldpacks=
1347 for oldpack in $packlist; do
1348 oldpack="${oldpack%.pack}"
1349 [ -f "objects/pack/$oldpack.pack" ] || {
1350 echo >&2 "[$proj] unable to list old pack files"
1351 exit 1
1353 case "$oldpack" in pre-auto-gc-[12])
1354 # we never disturb pre-auto-gc-1 or pre-auto-gc-2 packs
1355 continue
1356 esac
1357 oldpackhex="${oldpack#pack-}"
1358 if [ "${oldpackhex#*[!0-9a-fA-F]}" != "$oldpackhex" ]; then
1359 # names not exclusively hexadecimal do not need renaming
1360 case "$oldpack" in
1361 pack-$octet20*_l)
1362 # _l packs are treated like still-unpacked loose objects
1363 continue;;
1364 *_f)
1365 # _f packs can only be left over from a previously interrupted gc;
1366 # they need to be renamed to _r now so they're not confused with
1367 # any freshly generated "final" packs (and we already removed
1368 # any pre-existing *_f.keep files so we're good to go)
1371 oldpacks="${oldpacks:+$oldpacks }$oldpack"
1372 continue;;
1373 esac
1375 rename_pack "objects/pack/$oldpack" "objects/pack/${oldpack%_f}_r" || {
1376 echo >&2 "[$proj] unable to rename old pack files"
1377 exit 1
1379 # If the oldpack has a .keep now it means a "Push Pack Redux" is actually
1380 # in progress at this moment and we need to .keep the renamed pack,
1381 # otherwise no "Push Pack Redux" has started yet or it has already finished.
1382 # In either case we're okay because if it's just finished then all ref
1383 # changes have already been made so we don't need a .keep and we will
1384 # see the ref changes and grab all the objects via a reachability trace.
1385 # If it hasn't started yet that's okay because we're done moving that
1386 # name so a complete pack will appear under the old name that we'll
1387 # leave alone.
1388 if [ -f "objects/pack/$oldpack.keep" ]; then
1389 echo "Push Pack Redux" >"objects/pack/${oldpack%_f}_r.keep"
1390 else
1391 oldpacks="${oldpacks:+$oldpacks }${oldpack%_f}_r"
1393 done
1395 # We wish to keep deltas from our last full pack so if we're not redeltaing
1396 # then make sure the .pack associated with the .bitmap has a newer mod time
1397 # (If there is no .bitmap then touch the pack with the most objects instead.)
1398 if [ -z "$newdeltas" ]; then
1399 bmpack="$(list_packs --exclude-no-bitmap --exclude-no-idx --max-matches 1 objects/pack)"
1400 [ -n "$bmpack" ] || bmpack="$(list_packs --exclude-no-idx --max-matches 1 --object-limit -1 --include-boundary objects/pack)"
1401 if [ -n "$bmpack" ] && [ -f "$bmpack" ] && [ -s "$bmpack" ]; then
1402 sleep 1
1403 touch -c "$bmpack" 2>/dev/null || :
1404 # We must touch .gc_in_progress here to avoid $bmpack looking
1405 # like it's been "freshened" when redundant packs are removed
1406 # It's okay if they have the same mod time, but POSIX does not
1407 # guarantee an ordering for the "touching" that occurs which is
1408 # why this must be a separate command but needs no "sleep 1"
1409 touch .gc_in_progress
1413 # Now we need to make sure that any "freshening" that takes place will actually
1414 # result in a "newer" modification time than the .gc_in_progress file now has
1415 sleep 1
1417 # We run git pack-objects from the repack subdirectory so we can force
1418 # optimized packs to be generated even for repositories that do not have any
1419 # tagged commits
1420 packs="$(git --git-dir=repack pack-objects </dev/null \
1421 $pkopt --all $newdeltas $lclopt ${wbmopt:---honor-pack-keep} "$@" repack/alt/pack/pack)"
1422 v_cnt packcnt $packs
1423 [ $packcnt -eq 1 ] || makebndl=
1426 ## Phase II
1429 progress "~ [$proj] running supplementary gc pack-objects ($(date))"
1431 # Add the "supplementary" refs
1432 compute_extra_reachables >>repack/packed-refs
1434 # Subtract the primary refs
1435 GIT_ALTERNATE_OBJECT_DIRECTORIES="$PWD/repack/alt"
1436 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1438 # For this one we MUST use --local and MUST NOT use --write-bitmap-index
1439 # However, if there is a "logs" subdirectory we need to use --reflog
1440 # We do add it, just in case, if the linked working trees dir is present
1441 # We do not add --indexed-objects as that requires v2.2.0 and it's unclear
1442 # if it properly includes linked working tree index files or not. The
1443 # above compute_extra_reachables has already included all index trees (thereby
1444 # providing proper --indexed-objects support for all Git versions) making the
1445 # option completely unnecessary.
1446 rflopt=
1447 ! [ -d logs ] && ! [ -d worktrees ] || rflopt=--reflog
1448 spacks="$(git --git-dir=repack pack-objects </dev/null \
1449 $pkopt --honor-pack-keep --all $rflopt $newdeltas --local "$@" repack/alt/pack/pack)"
1452 ## Phase III
1455 # There's nothing to do for Phase III unless we have forks that refer to our
1456 # project from their alternates file
1457 hlpacks=
1458 upacks=
1459 if [ -n "$gotforks" ]; then
1461 progress "~ [$proj] running keep-unreachable gc pack-objects for forks ($(date))"
1463 # If we are a fork, any pre-existing _u packs need to have a .keep
1464 # for this phase and be added to the hlpacks list otherwise (we are
1465 # not a fork) pre-existing _u packs are anomalies to be treated like
1466 # regular non-_u packs
1467 if [ -n "$isfork" ]; then
1468 for upack in $(find -L objects/pack -mindepth 1 -maxdepth 1 -name "pack-$octet20*_[ul].pack" -print); do
1469 upack="${upack%.pack}"
1470 [ -e "$upack.keep" ] || echo "unreachable" >"$upack.keep"
1471 case "$upack" in *_l);;*)
1472 hlpacks="${hlpacks:+$hlpacks }${upack#objects/pack/pack-}"
1473 esac
1474 done
1476 # Using either --no-reuse-delta or --no-reuse-object together with the
1477 # --keep-unreachable option is a very, very, very bad idea when good
1478 # packs are the desired outcome. If newdeltas are being generated
1479 # then we pack to a temp name, and use combine-packs.sh to get a better
1480 # pack as the result to avoid making a bad --keep-unreachable pack
1481 pfx=
1482 [ -z "$newdeltas" ] || pfx="ku"
1483 upacks="$(git --git-dir=repack pack-objects </dev/null \
1484 $pkopt --honor-pack-keep --all $rflopt --keep-unreachable --local "$@" repack/alt/pack/${pfx}pack)"
1485 if [ -n "$upacks" ] && [ -n "$newdeltas" ]; then
1486 progress "~ [$proj] rebuilding keep-unreachable pack deltas"
1487 oldupacks="$upacks"
1488 upacks="$(
1489 printf "repack/alt/pack/${pfx}pack-%s.pack\n" $oldupacks |
1490 run_combine_packs --names --weak-naming --non-empty --all-progress-implied ${quiet:---progress} \
1491 $packopts $newdeltas "$@" repack/alt/pack/pack)"
1492 eval rm -f "$(printf \""repack/alt/pack/${pfx}pack-%s.*"\"" " $oldupacks)"
1494 for upack in $upacks; do
1495 rename_pack "repack/alt/pack/pack-$upack" "repack/alt/pack/pack-${upack}_u"
1496 done
1497 rm -f objects/pack/pack-*_[ul].keep
1498 [ -z "$hlpacks" ] && [ -z "$upacks" ] ||
1499 progress "~ [$proj] hard-linking keep-unreachable pack(s) into immediate child forks"
1501 # We have to update the lastparentgc time in the child forks even if they do not get any
1502 # new "unreachable packs" because they need to run gc just in case the parent now has some
1503 # objects that used to only be in the child so they can be removed from the child.
1504 # For example, a "patch" might be developed first in a fork and then later accepted into
1505 # the parent in which case the objects making up the patch in the child fork are now
1506 # redundant (since they're now in the parent as well) and need to be removed from the
1507 # child fork which can only happen if the child fork runs gc.
1508 lastparentgc="$(date "$datefmt")"
1510 # It is enough to copy objects just one level down and get_repo_list
1511 # takes a regular expression (which is automatically prefixed with '^')
1512 # so we can easily match forks exactly one level down from this project
1513 forkdir="$proj"
1514 get_repo_list "$forkdir/[^/:][^/:]*:" |
1515 while read fork; do
1516 # Ignore forks that do not exist or are symbolic links
1517 ! [ -L "$cfg_reporoot/$fork.git" ] && [ -d "$cfg_reporoot/$fork.git" ] ||
1518 continue
1519 # Or have an empty alternates file
1520 ! is_empty_alternates_file "$cfg_reporoot/$fork.git/objects/info/alternates" ||
1521 continue
1522 runupdate=
1523 # Match hlpacks in parent project if any
1524 if [ -n "$hlpacks" ]; then
1525 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1526 eval ln -f "$(printf '"objects/pack/pack-%s.pack" ' $hlpacks)" \
1527 "$(printf '"objects/pack/pack-%s.idx" ' $hlpacks)" \
1528 '"$cfg_reporoot/$fork.git/objects/pack/"'
1529 runupdate=1
1531 # Match upacks in repack/alt area if any
1532 if [ -n "$upacks" ]; then
1533 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1534 eval ln -f "$(printf '"repack/alt/pack/pack-%s_u.pack" ' $upacks)" \
1535 "$(printf '"repack/alt/pack/pack-%s_u.idx" ' $upacks)" \
1536 '"$cfg_reporoot/$fork.git/objects/pack/"'
1537 runupdate=1
1539 if ! [ -e "$cfg_reporoot/$fork.git/.needsgc" ]; then
1540 # Trigger a mini gc in the fork if it now has too many packs
1541 packs="$(list_packs --quiet --count --exclude-no-idx --exclude-keep "$cfg_reporoot/$fork.git/objects/pack")" || :
1542 if [ -n "$packs" ] && [ "$packs" -ge 20 ]; then
1543 >"$cfg_reporoot/$fork.git/.needsgc"
1546 [ -z "$runupdate" ] || git --git-dir="$cfg_reporoot/$fork.git" update-server-info
1547 # Update the fork's lastparentgc date (must be more recent than $gcstart)
1548 git --git-dir="$cfg_reporoot/$fork.git" config gitweb.lastparentgc "$lastparentgc"
1549 done
1552 # Now move any primary/supplementary packs back into objects/pack
1553 # then drop any "unfreshened" redundant packs and clear repack/alt
1555 # First make sure the primary pack(s) have the most recent mod time
1556 if [ -n "$packs" ]; then
1557 [ -z "$spacks" ] || sleep 1
1558 printf 'repack/alt/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1561 # Move the packs into place but with a _f suffix and a .keep file for now
1562 for pack in $packs $spacks; do
1563 rename_pack "repack/alt/pack/pack-$pack" "objects/pack/pack-${pack}_f"
1564 [ -e "objects/pack/pack-${pack}_f.keep" ] ||
1565 echo "final" >"objects/pack/pack-${pack}_f.keep"
1566 done
1568 # It's possible that one of the $oldpacks had a .bitmap, got renamed (along
1569 # with its .bitmap) and then got "freshened" causing us to not remove it
1570 # However, if $wbmopt is set we most likely now have TWO .bitmap packs!
1571 # This can produce ugly warnings we don't want and possibly get the wrong
1572 # bitmap used since only one .bitmap file can ever be used by Git.
1573 # If this has happened, the .bitmap we want to discard will always have
1574 # an _r suffix so we can just zap any such now since it will leave the pack.
1575 [ -z "$wbmopt" ] || rm -f objects/pack/pack-*_r.bitmap || :
1577 # Remove the redundant packs that have not since been "freshened"
1578 # This does not completely eliminate the race condition window (Girocco's own
1579 # activites -- gc/fetch/receive are immune to the race) but it substantially
1580 # shrinks it down to just the time after the find but before the following rm
1581 >repack/oldpacks
1582 [ -z "$oldpacks" ] ||
1583 printf 'objects/pack/%s.pack\n' $oldpacks |
1584 LC_ALL=C sort >repack/oldpacks
1585 find -L objects/pack -maxdepth 1 -type f -name "pack-$octet20*.pack" -newer .gc_in_progress -print |
1586 LC_ALL=C sort >repack/freshened
1587 deadpacks="$(LC_ALL=C join -v 1 repack/oldpacks repack/freshened | LC_ALL=C sed 's/\.pack$//')"
1588 [ -z "$deadpacks" ] ||
1589 eval echo "$(printf '"%s".* ' $deadpacks)" | xargs rm -f || :
1591 # No need for this anymore
1592 rm -rf repack/alt objects/pack/repack
1593 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1596 ## Phase IV
1599 progress "~ [$proj] running gc prune-packed"
1601 # We do not want the redundant packs or any new "--keep-unreachable" pack(s) to be
1602 # present while running prune-packed. We try to guarantee that any loose object
1603 # (or any object present in a pack with an _l suffix which was created by mini gc)
1604 # that's unreachable persists for at least one $Girocco::Config::min_gc_interval
1605 # (not withstanding administrator interference to force earlier gc to occur).
1606 # If we were to include the redundant/keep-unreachable pack(s) when running
1607 # prune-packed and a loose unreachable object happened to be duplicated in one
1608 # of them we would end up removing it too soon and void our guarantee.
1609 git prune-packed $quiet
1611 progress "~ [$proj] running loose objects gc pack-objects ($(date))"
1613 # Although Git v2.10.0 and later support a --pack-loose-unreachable option,
1614 # we MUST NOT use it for these reasons:
1615 # 1) We're not interested in expensive "unreachable" at this point, only "loose"
1616 # 2) It produces simply horrid packs about 3.8x times larger than they should be
1617 # 3) We don't require anything more than Git v1.6.6
1618 # The only way we could see any _o pack files at this point is if one got
1619 # "freshened" while we were running gc. If that happens then it gets to live on
1620 # until the next full gc and we need to include it in the loose repack here.
1621 lpacks="$(list_packs --exclude-no-idx --exclude-no-sfx _l --exclude-no-sfx _o --quiet objects/pack |
1622 run_combine_packs --replace --names --loose --weak-naming --non-empty --honor-pack-keep \
1623 --all-progress-implied ${quiet:---progress} $packopts $newdeltas "$@")"
1625 if [ -n "$lpacks" ]; then
1626 # Make sure any primary pack(s) have a more recent mod time than "unreachable" objects packs
1627 if [ -n "$packs" ]; then
1628 sleep 1
1629 printf 'objects/pack/pack-%s_f.pack\n' $packs | xargs touch -c 2>/dev/null || :
1631 # We need to identify these packs later so we don't combine_packs them
1632 for objpack in $lpacks; do
1633 rename_pack "objects/pack/pack-$objpack" "objects/pack/pack-${objpack}_o" || :
1634 done
1637 # Polish up the final packs now
1638 rm -f objects/pack/pack-*_f.keep
1639 for pack in $packs $spacks; do
1640 rename_pack "objects/pack/pack-${pack}_f" "objects/pack/pack-$pack"
1641 done
1643 if [ -n "$lpacks" ]; then
1644 # Finally zap the corresponding loose objects
1645 progress "~ [$proj] running packed loose objects gc prune-packed"
1646 git prune-packed $quiet
1649 ! [ -e .gc_failed ] || exit 1
1650 # These, if they exist, are now meaningless and need to be removed
1651 rm -f gfi-packs .needsgc .needspack .needspackgc
1653 # Make sure this stays up to date
1654 git update-server-info
1656 # We must make loose objects group writable so that they
1657 # can be freshened by other pushers. Technically we need only do this for
1658 # push projects but to enable mirror projects to be more easily converted to
1659 # push projects, we go ahead and do it for all projects.
1660 # By the time we get here we really shouldn't have any of these, but just in case.
1661 { find -L objects/$octet -type f -name "$octet19*" -exec chmod ug+w '{}' + || :; } 2>/dev/null
1663 # darcs mirrors have a xxx.log file that will grow endlessly
1664 # if this is a mirror and the file exists, shorten it to 10000 lines
1665 # also take this opportunity to optimize the darcs repo
1666 if ! [ -e .nofetch ] && [ -n "$cfg_mirror" ]; then
1667 url="$(config_get baseurl)" || :
1668 case "$url" in darcs://* | darcs+http://* | darcs+https://*)
1669 if [ -n "$cfg_mirror_darcs" ]; then
1670 url="${url%/}"
1671 basedarcs="$(basename "${url#darcs*:/}")"
1672 if [ -f "$basedarcs.log" ]; then
1673 tail -n 10000 "$basedarcs.log" >"$basedarcs.log.$$"
1674 mv -f "$basedarcs.log.$$" "$basedarcs.log"
1676 if [ -d "$basedarcs.darcs" ]; then
1678 cd "$basedarcs.darcs"
1679 # without show_progress suppress non-error output
1680 [ "${show_progress:-0}" != "0" ] || exec >/dev/null
1681 # Note that this does not optimize _darcs/inventories/ :(
1682 darcs optimize || :
1686 esac
1689 # Create a matching .bndl header file for the all-in-one pack we just created
1690 # but only if we're not a fork (otherwise the bundle would not be complete)
1691 # and we are running at least Git version 1.7.2 (pack_is_complete always fails otherwise)
1692 if [ -n "$makebndl" ] && [ -n "$var_have_git_172" ]; then
1693 # There should only be one pack in $packs but do some checking...
1694 # The one we just created will have a .idx and will NOT have a .keep
1695 progress "~ [$proj] creating downloadable bundle header"
1696 pkbase=
1697 pkhead=
1698 IFS= read -r curhead <repack/HEAD.orig || :
1700 [ -s "objects/pack/pack-$packs.pack" ] &&
1701 [ -s "objects/pack/pack-$packs.idx" ] &&
1702 ! [ -e "objects/pack/pack-$packs.keep" ] &&
1703 pkhead="$(pack_is_complete "$PWD/objects/pack/pack-$packs.pack" \
1704 "$PWD/repack/packed-refs.orig" "$curhead")"
1705 then
1706 pkbase="objects/pack/pack-$packs"
1708 if [ -n "$pkbase" ] && [ -n "$pkhead" ]; then
1710 symref=
1711 case "$curhead" in "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
1712 symref="${curhead#ref:}"
1713 symref="${symref# }"
1714 esac
1715 bndlurl=
1716 [ -z "$cfg_httpbundleurl" ] || bndlurl=" url=$cfg_httpbundleurl/$proj.git/clone.bundle"
1717 echo "# v2 git bundle"
1718 LC_ALL=C sed -ne "/^$octet20$hexdig* refs\/[^ $tab]*\$/ p" <repack/packed-refs.orig
1719 if [ -n "$symref" ]; then
1720 printf "$pkhead HEAD\0symref=HEAD:%s%s\n" "$symref" "$bndlurl"
1721 else
1722 if [ -n "$bndlurl" ]; then
1723 printf "$pkhead HEAD\0%s\n" "${bndlurl# }"
1724 else
1725 echo "$pkhead HEAD"
1728 echo ""
1729 } >"$pkbase.bndl"
1730 bndletag="$("$cfg_basedir/bin/rangecgi" --etag -m 1 "$pkbase.bndl" "$pkbase.pack")" || :
1731 bndlsha="$(printf '%s' "$bndletag" | git hash-object --stdin)" || :
1732 if [ -n "$bndletag" ]; then
1733 case "$bndlsha" in $octet20*)
1734 bndlshatrailer="${bndlsha#????????}"
1735 bndlshaprefix="${bndlsha%$bndlshatrailer}"
1736 bndlname="$(TZ=UTC date +%Y%m%d_%H%M%S)-${bndlshaprefix:-0}"
1737 [ -d bundles ] || mkdir bundles
1738 echo "${pkbase#objects/pack/}.bndl" >"bundles/$bndlname"
1739 echo "${pkbase#objects/pack/}.pack" >>"bundles/$bndlname"
1740 ln -s -f -n "$bndlname" bundles/latest
1741 esac
1746 # Record the size of this repo as the sum of its clone packed-refs + *.pack sizes as 1024-byte blocks
1747 eval "reposizek=$(( $(
1748 echo 0 $(du -k repack/packed-refs.orig $(printf 'objects/pack/pack-%s.pack ' $packs) 2>/dev/null |
1749 LC_ALL=C awk '{print $1}') |
1750 LC_ALL=C sed -e 's/ / + /g') ))"
1751 config_set_raw girocco.reposizek "${reposizek:-0}"
1753 # Now we're finally done with this
1754 rm -rf repack
1756 # We didn't used to do anything about rerere or worktrees but we're
1757 # trying to make nice with linked working trees these days :)
1758 # Maybe even non-bare repositories too, but *shush* about those ;)
1759 if [ -n "$var_have_git_250" ] && [ -d worktrees ]; then
1760 # The value "3.months.ago" is hard-coded into gc.c rather than
1761 # having the default be in worktree.c so we must provide it if
1762 # we get nothing out of the gc.worktreePruneExpire config item
1763 # Prior to Git v2.6.0 the config item was gc.pruneworktreesexpire
1764 # however we just always use the newer name no matter what Git version
1765 expiry="$(git config --get gc.worktreePruneExpire 2>/dev/null)" || :
1766 eval git worktree prune --expire '"${expiry:-3.months.ago}"' "${quiet:+>/dev/null 2>&1}" || :
1768 # git rerere does it right and handles its own default/config'd expiration values
1769 ! [ -d rr-cache ] || eval git rerere gc "${quiet:+>/dev/null 2>&1}" || :
1771 # We use $gcstart here to avoid a race where a push occurs during the gc itself
1772 # and the next future gc could be incorrectly skipped if we used the current
1773 # timestamp here instead
1774 config_set lastgc "$gcstart"
1775 rm -f "$lockf"
1777 progress "- [$proj] garbage check ($(date))"