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