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