]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
save: make save tree collisions a deferred error
[bup.git] / cmd / save-cmd.py
1 #!/usr/bin/env python
2 import sys, stat, time, math
3 from cStringIO import StringIO
4 from errno import EACCES
5
6 from bup import hashsplit, git, options, index, client, metadata, hlinkdb
7 from bup.helpers import *
8 from bup.hashsplit import GIT_MODE_TREE, GIT_MODE_FILE, GIT_MODE_SYMLINK
9
10
11 optspec = """
12 bup save [-tc] [-n name] <filenames...>
13 --
14 r,remote=  hostname:/path/to/repo of remote repository
15 t,tree     output a tree id
16 c,commit   output a commit id
17 n,name=    name of backup set to update (if any)
18 d,date=    date for the commit (seconds since the epoch)
19 v,verbose  increase log output (can be used more than once)
20 q,quiet    don't show progress meter
21 smaller=   only back up files smaller than n bytes
22 bwlimit=   maximum bytes/sec to transmit to server
23 f,indexfile=  the name of the index file (normally BUP_DIR/bupindex)
24 strip      strips the path to every filename given
25 strip-path= path-prefix to be stripped when saving
26 graft=     a graft point *old_path*=*new_path* (can be used more than once)
27 #,compress=  set compression level to # (0-9, 9 is highest) [1]
28 """
29 o = options.Options(optspec)
30 (opt, flags, extra) = o.parse(sys.argv[1:])
31
32 git.check_repo_or_die()
33 if not (opt.tree or opt.commit or opt.name):
34     o.fatal("use one or more of -t, -c, -n")
35 if not extra:
36     o.fatal("no filenames given")
37
38 opt.progress = (istty2 and not opt.quiet)
39 opt.smaller = parse_num(opt.smaller or 0)
40 if opt.bwlimit:
41     client.bwlimit = parse_num(opt.bwlimit)
42
43 if opt.date:
44     date = parse_date_or_fatal(opt.date, o.fatal)
45 else:
46     date = time.time()
47
48 if opt.strip and opt.strip_path:
49     o.fatal("--strip is incompatible with --strip-path")
50
51 graft_points = []
52 if opt.graft:
53     if opt.strip:
54         o.fatal("--strip is incompatible with --graft")
55
56     if opt.strip_path:
57         o.fatal("--strip-path is incompatible with --graft")
58
59     for (option, parameter) in flags:
60         if option == "--graft":
61             splitted_parameter = parameter.split('=')
62             if len(splitted_parameter) != 2:
63                 o.fatal("a graft point must be of the form old_path=new_path")
64             old_path, new_path = splitted_parameter
65             if not (old_path and new_path):
66                 o.fatal("a graft point cannot be empty")
67             graft_points.append((realpath(old_path), realpath(new_path)))
68
69 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
70 if is_reverse and opt.remote:
71     o.fatal("don't use -r in reverse mode; it's automatic")
72
73 if opt.name and opt.name.startswith('.'):
74     o.fatal("'%s' is not a valid branch name" % opt.name)
75 refname = opt.name and 'refs/heads/%s' % opt.name or None
76 if opt.remote or is_reverse:
77     try:
78         cli = client.Client(opt.remote)
79     except client.ClientError, e:
80         log('error: %s' % e)
81         sys.exit(1)
82     oldref = refname and cli.read_ref(refname) or None
83     w = cli.new_packwriter(compression_level=opt.compress)
84 else:
85     cli = None
86     oldref = refname and git.read_ref(refname) or None
87     w = git.PackWriter(compression_level=opt.compress)
88
89 handle_ctrl_c()
90
91
92 def eatslash(dir):
93     if dir.endswith('/'):
94         return dir[:-1]
95     else:
96         return dir
97
98
99 # Metadata is stored in a file named .bupm in each directory.  The
100 # first metadata entry will be the metadata for the current directory.
101 # The remaining entries will be for each of the other directory
102 # elements, in the order they're listed in the index.
103 #
104 # Since the git tree elements are sorted according to
105 # git.shalist_item_sort_key, the metalist items are accumulated as
106 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
107 # created.  The sort_key must be computed using the element's real
108 # name and mode rather than the git mode and (possibly mangled) name.
109
110 # Maintain a stack of information representing the current location in
111 # the archive being constructed.  The current path is recorded in
112 # parts, which will be something like ['', 'home', 'someuser'], and
113 # the accumulated content and metadata for of the dirs in parts is
114 # stored in parallel stacks in shalists and metalists.
115
116 parts = [] # Current archive position (stack of dir names).
117 shalists = [] # Hashes for each dir in paths.
118 metalists = [] # Metadata for each dir in paths.
119
120
121 def _push(part, metadata):
122     # Enter a new archive directory -- make it the current directory.
123     parts.append(part)
124     shalists.append([])
125     metalists.append([('', metadata)]) # This dir's metadata (no name).
126
127
128 def _pop(force_tree, dir_metadata=None):
129     # Leave the current archive directory and add its tree to its parent.
130     assert(len(parts) >= 1)
131     part = parts.pop()
132     shalist = shalists.pop()
133     metalist = metalists.pop()
134     if metalist and not force_tree:
135         if dir_metadata: # Override the original metadata pushed for this dir.
136             metalist = [('', dir_metadata)] + metalist[1:]
137         sorted_metalist = sorted(metalist, key = lambda x : x[0])
138         metadata = ''.join([m[1].encode() for m in sorted_metalist])
139         metadata_f = StringIO(metadata)
140         mode, id = hashsplit.split_to_blob_or_tree(w.new_blob, w.new_tree,
141                                                    [metadata_f],
142                                                    keep_boundaries=False)
143         shalist.append((mode, '.bupm', id))
144     # FIXME: only test if collision is possible (i.e. given --strip, etc.)?
145     if force_tree:
146         tree = force_tree
147     else:
148         names_seen = set()
149         clean_list = []
150         for x in shalist:
151             name = x[1]
152             if name in names_seen:
153                 parent_path = '/'.join(parts) + '/'
154                 add_error('error: ignoring duplicate path %r in %r'
155                           % (name, parent_path))
156             else:
157                 names_seen.add(name)
158                 clean_list.append(x)
159         tree = w.new_tree(clean_list)
160     if shalists:
161         shalists[-1].append((GIT_MODE_TREE,
162                              git.mangle_name(part,
163                                              GIT_MODE_TREE, GIT_MODE_TREE),
164                              tree))
165     return tree
166
167
168 lastremain = None
169 def progress_report(n):
170     global count, subcount, lastremain
171     subcount += n
172     cc = count + subcount
173     pct = total and (cc*100.0/total) or 0
174     now = time.time()
175     elapsed = now - tstart
176     kps = elapsed and int(cc/1024./elapsed)
177     kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
178     kps = int(kps/kps_frac)*kps_frac
179     if cc:
180         remain = elapsed*1.0/cc * (total-cc)
181     else:
182         remain = 0.0
183     if (lastremain and (remain > lastremain)
184           and ((remain - lastremain)/lastremain < 0.05)):
185         remain = lastremain
186     else:
187         lastremain = remain
188     hours = int(remain/60/60)
189     mins = int(remain/60 - hours*60)
190     secs = int(remain - hours*60*60 - mins*60)
191     if elapsed < 30:
192         remainstr = ''
193         kpsstr = ''
194     else:
195         kpsstr = '%dk/s' % kps
196         if hours:
197             remainstr = '%dh%dm' % (hours, mins)
198         elif mins:
199             remainstr = '%dm%d' % (mins, secs)
200         else:
201             remainstr = '%ds' % secs
202     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
203               % (pct, cc/1024, total/1024, fcount, ftotal,
204                  remainstr, kpsstr))
205
206
207 indexfile = opt.indexfile or git.repo('bupindex')
208 r = index.Reader(indexfile)
209 try:
210     msr = index.MetaStoreReader(indexfile + '.meta')
211 except IOError, ex:
212     if ex.errno != EACCES:
213         raise
214     log('error: cannot access %r; have you run bup index?' % indexfile)
215     sys.exit(1)
216 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
217
218 def already_saved(ent):
219     return ent.is_valid() and w.exists(ent.sha) and ent.sha
220
221 def wantrecurse_pre(ent):
222     return not already_saved(ent)
223
224 def wantrecurse_during(ent):
225     return not already_saved(ent) or ent.sha_missing()
226
227 def find_hardlink_target(hlink_db, ent):
228     if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
229         link_paths = hlink_db.node_paths(ent.dev, ent.ino)
230         if link_paths:
231             return link_paths[0]
232
233 total = ftotal = 0
234 if opt.progress:
235     for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
236         if not (ftotal % 10024):
237             qprogress('Reading index: %d\r' % ftotal)
238         exists = ent.exists()
239         hashvalid = already_saved(ent)
240         ent.set_sha_missing(not hashvalid)
241         if not opt.smaller or ent.size < opt.smaller:
242             if exists and not hashvalid:
243                 total += ent.size
244         ftotal += 1
245     progress('Reading index: %d, done.\n' % ftotal)
246     hashsplit.progress_callback = progress_report
247
248 # Root collisions occur when strip or graft options map more than one
249 # path to the same directory (paths which originally had separate
250 # parents).  When that situation is detected, use empty metadata for
251 # the parent.  Otherwise, use the metadata for the common parent.
252 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
253
254 # FIXME: Add collision tests, or handle collisions some other way.
255
256 # FIXME: Detect/handle strip/graft name collisions (other than root),
257 # i.e. if '/foo/bar' and '/bar' both map to '/'.
258
259 first_root = None
260 root_collision = None
261 tstart = time.time()
262 count = subcount = fcount = 0
263 lastskip_name = None
264 lastdir = ''
265 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
266     (dir, file) = os.path.split(ent.name)
267     exists = (ent.flags & index.IX_EXISTS)
268     hashvalid = already_saved(ent)
269     wasmissing = ent.sha_missing()
270     oldsize = ent.size
271     if opt.verbose:
272         if not exists:
273             status = 'D'
274         elif not hashvalid:
275             if ent.sha == index.EMPTY_SHA:
276                 status = 'A'
277             else:
278                 status = 'M'
279         else:
280             status = ' '
281         if opt.verbose >= 2:
282             log('%s %-70s\n' % (status, ent.name))
283         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
284             if not lastdir.startswith(dir):
285                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
286             lastdir = dir
287
288     if opt.progress:
289         progress_report(0)
290     fcount += 1
291     
292     if not exists:
293         continue
294     if opt.smaller and ent.size >= opt.smaller:
295         if exists and not hashvalid:
296             if opt.verbose:
297                 log('skipping large file "%s"\n' % ent.name)
298             lastskip_name = ent.name
299         continue
300
301     assert(dir.startswith('/'))
302     if opt.strip:
303         dirp = stripped_path_components(dir, extra)
304     elif opt.strip_path:
305         dirp = stripped_path_components(dir, [opt.strip_path])
306     elif graft_points:
307         dirp = grafted_path_components(graft_points, dir)
308     else:
309         dirp = path_components(dir)
310
311     # At this point, dirp contains a representation of the archive
312     # path that looks like [(archive_dir_name, real_fs_path), ...].
313     # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
314     # might look like this at some point:
315     #   [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
316
317     # This dual representation supports stripping/grafting, where the
318     # archive path may not have a direct correspondence with the
319     # filesystem.  The root directory is represented by an initial
320     # component named '', and any component that doesn't have a
321     # corresponding filesystem directory (due to grafting, for
322     # example) will have a real_fs_path of None, i.e. [('', None),
323     # ...].
324
325     if first_root == None:
326         first_root = dirp[0]
327     elif first_root != dirp[0]:
328         root_collision = True
329
330     # If switching to a new sub-tree, finish the current sub-tree.
331     while parts > [x[0] for x in dirp]:
332         _pop(force_tree = None)
333
334     # If switching to a new sub-tree, start a new sub-tree.
335     for path_component in dirp[len(parts):]:
336         dir_name, fs_path = path_component
337         # Not indexed, so just grab the FS metadata or use empty metadata.
338         try:
339            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
340         except (OSError, IOError), e:
341             add_error(e)
342             lastskip_name = dir_name
343             meta = metadata.Metadata()
344         _push(dir_name, meta)
345
346     if not file:
347         if len(parts) == 1:
348             continue # We're at the top level -- keep the current root dir
349         # Since there's no filename, this is a subdir -- finish it.
350         oldtree = already_saved(ent) # may be None
351         newtree = _pop(force_tree = oldtree)
352         if not oldtree:
353             if lastskip_name and lastskip_name.startswith(ent.name):
354                 ent.invalidate()
355             else:
356                 ent.validate(GIT_MODE_TREE, newtree)
357             ent.repack()
358         if exists and wasmissing:
359             count += oldsize
360         continue
361
362     # it's not a directory
363     id = None
364     if hashvalid:
365         id = ent.sha
366         git_name = git.mangle_name(file, ent.mode, ent.gitmode)
367         git_info = (ent.gitmode, git_name, id)
368         shalists[-1].append(git_info)
369         sort_key = git.shalist_item_sort_key((ent.mode, file, id))
370         meta = msr.metadata_at(ent.meta_ofs)
371         meta.hardlink_target = find_hardlink_target(hlink_db, ent)
372         # Restore the times that were cleared to 0 in the metastore.
373         (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
374         metalists[-1].append((sort_key, meta))
375     else:
376         if stat.S_ISREG(ent.mode):
377             try:
378                 f = hashsplit.open_noatime(ent.name)
379             except (IOError, OSError), e:
380                 add_error(e)
381                 lastskip_name = ent.name
382             else:
383                 try:
384                     (mode, id) = hashsplit.split_to_blob_or_tree(
385                                             w.new_blob, w.new_tree, [f],
386                                             keep_boundaries=False)
387                 except (IOError, OSError), e:
388                     add_error('%s: %s' % (ent.name, e))
389                     lastskip_name = ent.name
390         else:
391             if stat.S_ISDIR(ent.mode):
392                 assert(0)  # handled above
393             elif stat.S_ISLNK(ent.mode):
394                 try:
395                     rl = os.readlink(ent.name)
396                 except (OSError, IOError), e:
397                     add_error(e)
398                     lastskip_name = ent.name
399                 else:
400                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
401             else:
402                 # Everything else should be fully described by its
403                 # metadata, so just record an empty blob, so the paths
404                 # in the tree and .bupm will match up.
405                 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
406
407         if id:
408             ent.validate(mode, id)
409             ent.repack()
410             git_name = git.mangle_name(file, ent.mode, ent.gitmode)
411             git_info = (mode, git_name, id)
412             shalists[-1].append(git_info)
413             sort_key = git.shalist_item_sort_key((ent.mode, file, id))
414             hlink = find_hardlink_target(hlink_db, ent)
415             try:
416                 meta = metadata.from_path(ent.name, hardlink_target=hlink)
417             except (OSError, IOError), e:
418                 add_error(e)
419                 lastskip_name = ent.name
420             else:
421                 metalists[-1].append((sort_key, meta))
422
423     if exists and wasmissing:
424         count += oldsize
425         subcount = 0
426
427
428 if opt.progress:
429     pct = total and count*100.0/total or 100
430     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
431              % (pct, count/1024, total/1024, fcount, ftotal))
432
433 while len(parts) > 1: # _pop() all the parts above the root
434     _pop(force_tree = None)
435 assert(len(shalists) == 1)
436 assert(len(metalists) == 1)
437
438 # Finish the root directory.
439 tree = _pop(force_tree = None,
440             # When there's a collision, use empty metadata for the root.
441             dir_metadata = metadata.Metadata() if root_collision else None)
442
443 if opt.tree:
444     print tree.encode('hex')
445 if opt.commit or opt.name:
446     msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
447     commit = w.new_commit(oldref, tree, date, msg)
448     if opt.commit:
449         print commit.encode('hex')
450
451 msr.close()
452 w.close()  # must close before we can update the ref
453         
454 if opt.name:
455     if cli:
456         cli.update_ref(refname, commit, oldref)
457     else:
458         git.update_ref(refname, commit, oldref)
459
460 if cli:
461     cli.close()
462
463 if saved_errors:
464     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
465     sys.exit(1)