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