3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
7 import sys, stat, time, math
8 from cStringIO import StringIO
9 from errno import EACCES
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
17 bup save [-tc] [-n name] <filenames...>
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]
34 o = options.Options(optspec)
35 (opt, flags, extra) = o.parse(sys.argv[1:])
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")
41 o.fatal("no filenames given")
43 opt.progress = (istty2 and not opt.quiet)
44 opt.smaller = parse_num(opt.smaller or 0)
46 client.bwlimit = parse_num(opt.bwlimit)
49 date = parse_date_or_fatal(opt.date, o.fatal)
53 if opt.strip and opt.strip_path:
54 o.fatal("--strip is incompatible with --strip-path")
59 o.fatal("--strip is incompatible with --graft")
62 o.fatal("--strip-path is incompatible with --graft")
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((realpath(old_path), realpath(new_path)))
74 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
75 if is_reverse and opt.remote:
76 o.fatal("don't use -r in reverse mode; it's automatic")
78 if opt.name and opt.name.startswith('.'):
79 o.fatal("'%s' is not a valid branch name" % opt.name)
80 refname = opt.name and 'refs/heads/%s' % opt.name or None
81 if opt.remote or is_reverse:
83 cli = client.Client(opt.remote)
84 except client.ClientError, e:
87 oldref = refname and cli.read_ref(refname) or None
88 w = cli.new_packwriter(compression_level=opt.compress)
91 oldref = refname and git.read_ref(refname) or None
92 w = git.PackWriter(compression_level=opt.compress)
104 # Metadata is stored in a file named .bupm in each directory. The
105 # first metadata entry will be the metadata for the current directory.
106 # The remaining entries will be for each of the other directory
107 # elements, in the order they're listed in the index.
109 # Since the git tree elements are sorted according to
110 # git.shalist_item_sort_key, the metalist items are accumulated as
111 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
112 # created. The sort_key must be computed using the element's real
113 # name and mode rather than the git mode and (possibly mangled) name.
115 # Maintain a stack of information representing the current location in
116 # the archive being constructed. The current path is recorded in
117 # parts, which will be something like ['', 'home', 'someuser'], and
118 # the accumulated content and metadata for of the dirs in parts is
119 # stored in parallel stacks in shalists and metalists.
121 parts = [] # Current archive position (stack of dir names).
122 shalists = [] # Hashes for each dir in paths.
123 metalists = [] # Metadata for each dir in paths.
126 def _push(part, metadata):
127 # Enter a new archive directory -- make it the current directory.
130 metalists.append([('', metadata)]) # This dir's metadata (no name).
133 def _pop(force_tree, dir_metadata=None):
134 # Leave the current archive directory and add its tree to its parent.
135 assert(len(parts) >= 1)
137 shalist = shalists.pop()
138 metalist = metalists.pop()
139 if metalist and not force_tree:
140 if dir_metadata: # Override the original metadata pushed for this dir.
141 metalist = [('', dir_metadata)] + metalist[1:]
142 sorted_metalist = sorted(metalist, key = lambda x : x[0])
143 metadata = ''.join([m[1].encode() for m in sorted_metalist])
144 metadata_f = StringIO(metadata)
145 mode, id = hashsplit.split_to_blob_or_tree(w.new_blob, w.new_tree,
147 keep_boundaries=False)
148 shalist.append((mode, '.bupm', id))
149 # FIXME: only test if collision is possible (i.e. given --strip, etc.)?
157 if name in names_seen:
158 parent_path = '/'.join(parts) + '/'
159 add_error('error: ignoring duplicate path %r in %r'
160 % (name, parent_path))
164 tree = w.new_tree(clean_list)
166 shalists[-1].append((GIT_MODE_TREE,
167 git.mangle_name(part,
168 GIT_MODE_TREE, GIT_MODE_TREE),
174 def progress_report(n):
175 global count, subcount, lastremain
177 cc = count + subcount
178 pct = total and (cc*100.0/total) or 0
180 elapsed = now - tstart
181 kps = elapsed and int(cc/1024./elapsed)
182 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
183 kps = int(kps/kps_frac)*kps_frac
185 remain = elapsed*1.0/cc * (total-cc)
188 if (lastremain and (remain > lastremain)
189 and ((remain - lastremain)/lastremain < 0.05)):
193 hours = int(remain/60/60)
194 mins = int(remain/60 - hours*60)
195 secs = int(remain - hours*60*60 - mins*60)
200 kpsstr = '%dk/s' % kps
202 remainstr = '%dh%dm' % (hours, mins)
204 remainstr = '%dm%d' % (mins, secs)
206 remainstr = '%ds' % secs
207 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
208 % (pct, cc/1024, total/1024, fcount, ftotal,
212 indexfile = opt.indexfile or git.repo('bupindex')
213 r = index.Reader(indexfile)
215 msr = index.MetaStoreReader(indexfile + '.meta')
217 if ex.errno != EACCES:
219 log('error: cannot access %r; have you run bup index?' % indexfile)
221 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
223 def already_saved(ent):
224 return ent.is_valid() and w.exists(ent.sha) and ent.sha
226 def wantrecurse_pre(ent):
227 return not already_saved(ent)
229 def wantrecurse_during(ent):
230 return not already_saved(ent) or ent.sha_missing()
232 def find_hardlink_target(hlink_db, ent):
233 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
234 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
240 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
241 if not (ftotal % 10024):
242 qprogress('Reading index: %d\r' % ftotal)
243 exists = ent.exists()
244 hashvalid = already_saved(ent)
245 ent.set_sha_missing(not hashvalid)
246 if not opt.smaller or ent.size < opt.smaller:
247 if exists and not hashvalid:
250 progress('Reading index: %d, done.\n' % ftotal)
251 hashsplit.progress_callback = progress_report
253 # Root collisions occur when strip or graft options map more than one
254 # path to the same directory (paths which originally had separate
255 # parents). When that situation is detected, use empty metadata for
256 # the parent. Otherwise, use the metadata for the common parent.
257 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
259 # FIXME: Add collision tests, or handle collisions some other way.
261 # FIXME: Detect/handle strip/graft name collisions (other than root),
262 # i.e. if '/foo/bar' and '/bar' both map to '/'.
265 root_collision = None
267 count = subcount = fcount = 0
270 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
271 (dir, file) = os.path.split(ent.name)
272 exists = (ent.flags & index.IX_EXISTS)
273 hashvalid = already_saved(ent)
274 wasmissing = ent.sha_missing()
280 if ent.sha == index.EMPTY_SHA:
287 log('%s %-70s\n' % (status, ent.name))
288 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
289 if not lastdir.startswith(dir):
290 log('%s %-70s\n' % (status, os.path.join(dir, '')))
299 if opt.smaller and ent.size >= opt.smaller:
300 if exists and not hashvalid:
302 log('skipping large file "%s"\n' % ent.name)
303 lastskip_name = ent.name
306 assert(dir.startswith('/'))
308 dirp = stripped_path_components(dir, extra)
310 dirp = stripped_path_components(dir, [opt.strip_path])
312 dirp = grafted_path_components(graft_points, dir)
314 dirp = path_components(dir)
316 # At this point, dirp contains a representation of the archive
317 # path that looks like [(archive_dir_name, real_fs_path), ...].
318 # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
319 # might look like this at some point:
320 # [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
322 # This dual representation supports stripping/grafting, where the
323 # archive path may not have a direct correspondence with the
324 # filesystem. The root directory is represented by an initial
325 # component named '', and any component that doesn't have a
326 # corresponding filesystem directory (due to grafting, for
327 # example) will have a real_fs_path of None, i.e. [('', None),
330 if first_root == None:
332 elif first_root != dirp[0]:
333 root_collision = True
335 # If switching to a new sub-tree, finish the current sub-tree.
336 while parts > [x[0] for x in dirp]:
337 _pop(force_tree = None)
339 # If switching to a new sub-tree, start a new sub-tree.
340 for path_component in dirp[len(parts):]:
341 dir_name, fs_path = path_component
342 # Not indexed, so just grab the FS metadata or use empty metadata.
344 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
345 except (OSError, IOError), e:
347 lastskip_name = dir_name
348 meta = metadata.Metadata()
349 _push(dir_name, meta)
353 continue # We're at the top level -- keep the current root dir
354 # Since there's no filename, this is a subdir -- finish it.
355 oldtree = already_saved(ent) # may be None
356 newtree = _pop(force_tree = oldtree)
358 if lastskip_name and lastskip_name.startswith(ent.name):
361 ent.validate(GIT_MODE_TREE, newtree)
363 if exists and wasmissing:
367 # it's not a directory
371 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
372 git_info = (ent.gitmode, git_name, id)
373 shalists[-1].append(git_info)
374 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
375 meta = msr.metadata_at(ent.meta_ofs)
376 meta.hardlink_target = find_hardlink_target(hlink_db, ent)
377 # Restore the times that were cleared to 0 in the metastore.
378 (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
379 metalists[-1].append((sort_key, meta))
381 if stat.S_ISREG(ent.mode):
383 f = hashsplit.open_noatime(ent.name)
384 except (IOError, OSError), e:
386 lastskip_name = ent.name
389 (mode, id) = hashsplit.split_to_blob_or_tree(
390 w.new_blob, w.new_tree, [f],
391 keep_boundaries=False)
392 except (IOError, OSError), e:
393 add_error('%s: %s' % (ent.name, e))
394 lastskip_name = ent.name
396 if stat.S_ISDIR(ent.mode):
397 assert(0) # handled above
398 elif stat.S_ISLNK(ent.mode):
400 rl = os.readlink(ent.name)
401 except (OSError, IOError), e:
403 lastskip_name = ent.name
405 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
407 # Everything else should be fully described by its
408 # metadata, so just record an empty blob, so the paths
409 # in the tree and .bupm will match up.
410 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
413 ent.validate(mode, id)
415 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
416 git_info = (mode, git_name, id)
417 shalists[-1].append(git_info)
418 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
419 hlink = find_hardlink_target(hlink_db, ent)
421 meta = metadata.from_path(ent.name, hardlink_target=hlink)
422 except (OSError, IOError), e:
424 lastskip_name = ent.name
426 metalists[-1].append((sort_key, meta))
428 if exists and wasmissing:
434 pct = total and count*100.0/total or 100
435 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
436 % (pct, count/1024, total/1024, fcount, ftotal))
438 while len(parts) > 1: # _pop() all the parts above the root
439 _pop(force_tree = None)
440 assert(len(shalists) == 1)
441 assert(len(metalists) == 1)
443 # Finish the root directory.
444 tree = _pop(force_tree = None,
445 # When there's a collision, use empty metadata for the root.
446 dir_metadata = metadata.Metadata() if root_collision else None)
449 print tree.encode('hex')
450 if opt.commit or opt.name:
451 msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
452 commit = w.new_commit(oldref, tree, date, msg)
454 print commit.encode('hex')
457 w.close() # must close before we can update the ref
461 cli.update_ref(refname, commit, oldref)
463 git.update_ref(refname, commit, oldref)
469 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))