2 from __future__ import absolute_import, print_function
3 from shutil import rmtree
4 from subprocess import PIPE
5 from tempfile import mkdtemp
6 from binascii import hexlify
7 import glob, os, subprocess, sys
9 from bup import options, git
10 from bup.compat import argv_bytes
11 from bup.helpers import Sha1, chunkyreader, istty2, log, progress
12 from bup.io import byte_stream
16 nullf = open(os.devnull, 'wb+')
24 # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
25 # doesn't actually work, because subprocess closes fd #2 right before
26 # execing for some reason. So we work around it by duplicating the fd
28 fd = os.dup(2) # copy stderr
30 p = subprocess.Popen(argv, stdout=fd, close_fds=False)
39 p = subprocess.Popen([b'par2', b'--help'],
40 stdout=nullf, stderr=nullf, stdin=nullf)
43 log('fsck: warning: par2 not found; disabling recovery features.\n')
47 def is_par2_parallel():
48 # A true result means it definitely allows -t1; a false result is
49 # technically inconclusive, but likely means no.
50 tmpdir = mkdtemp(prefix=b'bup-fsck')
52 canary = tmpdir + b'/canary'
53 with open(canary, 'wb') as f:
55 p = subprocess.Popen((b'par2', b'create', b'-qq', b'-t1', canary),
56 stderr=PIPE, stdin=nullf)
57 _, err = p.communicate()
58 parallel = p.returncode == 0
60 if len(err) > 0 and err != b'Invalid option specified: -t1\n':
61 log('Unexpected par2 error output\n')
64 log('Assuming par2 supports parallel processing\n')
66 log('Assuming par2 does not support parallel processing\n')
73 def par2(action, args, verb_floor=0):
75 if _par2_parallel is None:
76 _par2_parallel = is_par2_parallel()
77 cmd = [b'par2', action]
78 if opt.verbose >= verb_floor and not istty2:
87 def par2_generate(base):
88 return par2(b'create',
89 [b'-n1', b'-c200', b'--', base, base + b'.pack', base + b'.idx'],
92 def par2_verify(base):
93 return par2(b'verify', [b'--', base], verb_floor=3)
95 def par2_repair(base):
96 return par2(b'repair', [b'--', base], verb_floor=2)
98 def quick_verify(base):
99 f = open(base + b'.pack', 'rb')
102 assert(len(wantsum) == 20)
105 for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
107 if sum.digest() != wantsum:
108 raise ValueError('expected %r, got %r' % (hexlify(wantsum),
112 def git_verify(base):
116 except Exception as e:
117 log('error: %s\n' % e)
121 return run([b'git', b'verify-pack', b'--', base])
124 def do_pack(base, last, par2_exists, out):
126 if par2_ok and par2_exists and (opt.repair or not opt.generate):
127 vresult = par2_verify(base)
130 rresult = par2_repair(base)
132 action_result = b'failed'
133 log('%s par2 repair: failed (%d)\n' % (last, rresult))
136 action_result = b'repaired'
137 log('%s par2 repair: succeeded (0)\n' % last)
140 action_result = b'failed'
141 log('%s par2 verify: failed (%d)\n' % (last, vresult))
144 action_result = b'ok'
145 elif not opt.generate or (par2_ok and not par2_exists):
146 gresult = git_verify(base)
148 action_result = b'failed'
149 log('%s git verify: failed (%d)\n' % (last, gresult))
152 if par2_ok and opt.generate:
153 presult = par2_generate(base)
155 action_result = b'failed'
156 log('%s par2 create: failed (%d)\n' % (last, presult))
159 action_result = b'generated'
161 action_result = b'ok'
163 assert(opt.generate and (not par2_ok or par2_exists))
164 action_result = b'exists' if par2_exists else b'skipped'
166 out.write(last + b' ' + action_result + b'\n')
171 bup fsck [options...] [filenames...]
173 r,repair attempt to repair errors using par2 (dangerous!)
174 g,generate generate auto-repair information using par2
175 v,verbose increase verbosity (can be used more than once)
176 quick just check pack sha1sum, don't use git verify-pack
177 j,jobs= run 'n' jobs in parallel
178 par2-ok immediately return 0 if par2 is ok, 1 if not
179 disable-par2 ignore par2 even if it is available
185 o = options.Options(optspec)
186 opt, flags, extra = o.parse_bytes(argv[1:])
187 opt.verbose = opt.verbose or 0
192 sys.exit(0) # 'true' in sh
198 git.check_repo_or_die()
201 extra = [argv_bytes(x) for x in extra]
203 debug('fsck: No filenames given: checking all packs.\n')
204 extra = glob.glob(git.repo(b'objects/pack/*.pack'))
207 out = byte_stream(sys.stdout)
212 if name.endswith(b'.pack'):
214 elif name.endswith(b'.idx'):
216 elif name.endswith(b'.par2'):
218 elif os.path.exists(name + b'.pack'):
221 raise Exception('%r is not a pack file!' % name)
222 (dir,last) = os.path.split(base)
223 par2_exists = os.path.exists(base + b'.par2')
224 if par2_exists and os.stat(base + b'.par2').st_size == 0:
226 sys.stdout.flush() # Not sure we still need this, but it'll flush out too
227 debug('fsck: checking %r (%s)\n'
228 % (last, par2_ok and par2_exists and 'par2' or 'git'))
230 progress('fsck (%d/%d)\r' % (count, len(extra)))
233 nc = do_pack(base, last, par2_exists, out)
237 while len(outstanding) >= opt.jobs:
240 if pid in outstanding:
249 sys.exit(do_pack(base, last, par2_exists, out))
250 except Exception as e:
251 log('exception: %r\n' % e)
254 while len(outstanding):
257 if pid in outstanding:
262 progress('fsck (%d/%d)\r' % (count, len(extra)))
265 debug('fsck done. \n')