2 import sys, stat, time, math
3 from cStringIO import StringIO
4 from errno import EACCES
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
12 bup save [-tc] [-n name] <filenames...>
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]
29 o = options.Options(optspec)
30 (opt, flags, extra) = o.parse(sys.argv[1:])
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")
36 o.fatal("no filenames given")
38 opt.progress = (istty2 and not opt.quiet)
39 opt.smaller = parse_num(opt.smaller or 0)
41 client.bwlimit = parse_num(opt.bwlimit)
44 date = parse_date_or_fatal(opt.date, o.fatal)
48 if opt.strip and opt.strip_path:
49 o.fatal("--strip is incompatible with --strip-path")
54 o.fatal("--strip is incompatible with --graft")
57 o.fatal("--strip-path is incompatible with --graft")
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)))
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")
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:
78 cli = client.Client(opt.remote)
79 except client.ClientError, e:
82 oldref = refname and cli.read_ref(refname) or None
83 w = cli.new_packwriter(compression_level=opt.compress)
86 oldref = refname and git.read_ref(refname) or None
87 w = git.PackWriter(compression_level=opt.compress)
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.
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.
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.
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.
121 def _push(part, metadata):
122 # Enter a new archive directory -- make it the current directory.
125 metalists.append([('', metadata)]) # This dir's metadata (no name).
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)
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,
142 keep_boundaries=False)
143 shalist.append((mode, '.bupm', id))
144 tree = force_tree or w.new_tree(shalist)
146 shalists[-1].append((GIT_MODE_TREE,
147 git.mangle_name(part,
148 GIT_MODE_TREE, GIT_MODE_TREE),
154 def progress_report(n):
155 global count, subcount, lastremain
157 cc = count + subcount
158 pct = total and (cc*100.0/total) or 0
160 elapsed = now - tstart
161 kps = elapsed and int(cc/1024./elapsed)
162 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
163 kps = int(kps/kps_frac)*kps_frac
165 remain = elapsed*1.0/cc * (total-cc)
168 if (lastremain and (remain > lastremain)
169 and ((remain - lastremain)/lastremain < 0.05)):
173 hours = int(remain/60/60)
174 mins = int(remain/60 - hours*60)
175 secs = int(remain - hours*60*60 - mins*60)
180 kpsstr = '%dk/s' % kps
182 remainstr = '%dh%dm' % (hours, mins)
184 remainstr = '%dm%d' % (mins, secs)
186 remainstr = '%ds' % secs
187 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
188 % (pct, cc/1024, total/1024, fcount, ftotal,
192 indexfile = opt.indexfile or git.repo('bupindex')
193 r = index.Reader(indexfile)
195 msr = index.MetaStoreReader(indexfile + '.meta')
197 if ex.errno != EACCES:
199 log('error: cannot access %r; have you run bup index?' % indexfile)
201 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
203 def already_saved(ent):
204 return ent.is_valid() and w.exists(ent.sha) and ent.sha
206 def wantrecurse_pre(ent):
207 return not already_saved(ent)
209 def wantrecurse_during(ent):
210 return not already_saved(ent) or ent.sha_missing()
212 def find_hardlink_target(hlink_db, ent):
213 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
214 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
220 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
221 if not (ftotal % 10024):
222 qprogress('Reading index: %d\r' % ftotal)
223 exists = ent.exists()
224 hashvalid = already_saved(ent)
225 ent.set_sha_missing(not hashvalid)
226 if not opt.smaller or ent.size < opt.smaller:
227 if exists and not hashvalid:
230 progress('Reading index: %d, done.\n' % ftotal)
231 hashsplit.progress_callback = progress_report
233 # Root collisions occur when strip or graft options map more than one
234 # path to the same directory (paths which originally had separate
235 # parents). When that situation is detected, use empty metadata for
236 # the parent. Otherwise, use the metadata for the common parent.
237 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
239 # FIXME: Add collision tests, or handle collisions some other way.
241 # FIXME: Detect/handle strip/graft name collisions (other than root),
242 # i.e. if '/foo/bar' and '/bar' both map to '/'.
245 root_collision = None
247 count = subcount = fcount = 0
250 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
251 (dir, file) = os.path.split(ent.name)
252 exists = (ent.flags & index.IX_EXISTS)
253 hashvalid = already_saved(ent)
254 wasmissing = ent.sha_missing()
260 if ent.sha == index.EMPTY_SHA:
267 log('%s %-70s\n' % (status, ent.name))
268 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
269 if not lastdir.startswith(dir):
270 log('%s %-70s\n' % (status, os.path.join(dir, '')))
279 if opt.smaller and ent.size >= opt.smaller:
280 if exists and not hashvalid:
282 log('skipping large file "%s"\n' % ent.name)
283 lastskip_name = ent.name
286 assert(dir.startswith('/'))
288 dirp = stripped_path_components(dir, extra)
290 dirp = stripped_path_components(dir, [opt.strip_path])
292 dirp = grafted_path_components(graft_points, dir)
294 dirp = path_components(dir)
296 # At this point, dirp contains a representation of the archive
297 # path that looks like [(archive_dir_name, real_fs_path), ...].
298 # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
299 # might look like this at some point:
300 # [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
302 # This dual representation supports stripping/grafting, where the
303 # archive path may not have a direct correspondence with the
304 # filesystem. The root directory is represented by an initial
305 # component named '', and any component that doesn't have a
306 # corresponding filesystem directory (due to grafting, for
307 # example) will have a real_fs_path of None, i.e. [('', None),
310 if first_root == None:
312 elif first_root != dirp[0]:
313 root_collision = True
315 # If switching to a new sub-tree, finish the current sub-tree.
316 while parts > [x[0] for x in dirp]:
317 _pop(force_tree = None)
319 # If switching to a new sub-tree, start a new sub-tree.
320 for path_component in dirp[len(parts):]:
321 dir_name, fs_path = path_component
322 # Not indexed, so just grab the FS metadata or use empty metadata.
324 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
325 except (OSError, IOError), e:
327 lastskip_name = dir_name
328 meta = metadata.Metadata()
329 _push(dir_name, meta)
333 continue # We're at the top level -- keep the current root dir
334 # Since there's no filename, this is a subdir -- finish it.
335 oldtree = already_saved(ent) # may be None
336 newtree = _pop(force_tree = oldtree)
338 if lastskip_name and lastskip_name.startswith(ent.name):
341 ent.validate(GIT_MODE_TREE, newtree)
343 if exists and wasmissing:
347 # it's not a directory
351 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
352 git_info = (ent.gitmode, git_name, id)
353 shalists[-1].append(git_info)
354 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
355 meta = msr.metadata_at(ent.meta_ofs)
356 meta.hardlink_target = find_hardlink_target(hlink_db, ent)
357 # Restore the times that were cleared to 0 in the metastore.
358 (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
359 metalists[-1].append((sort_key, meta))
361 if stat.S_ISREG(ent.mode):
363 f = hashsplit.open_noatime(ent.name)
364 except (IOError, OSError), e:
366 lastskip_name = ent.name
369 (mode, id) = hashsplit.split_to_blob_or_tree(
370 w.new_blob, w.new_tree, [f],
371 keep_boundaries=False)
372 except (IOError, OSError), e:
373 add_error('%s: %s' % (ent.name, e))
374 lastskip_name = ent.name
376 if stat.S_ISDIR(ent.mode):
377 assert(0) # handled above
378 elif stat.S_ISLNK(ent.mode):
380 rl = os.readlink(ent.name)
381 except (OSError, IOError), e:
383 lastskip_name = ent.name
385 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
387 # Everything else should be fully described by its
388 # metadata, so just record an empty blob, so the paths
389 # in the tree and .bupm will match up.
390 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
393 ent.validate(mode, id)
395 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
396 git_info = (mode, git_name, id)
397 shalists[-1].append(git_info)
398 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
399 hlink = find_hardlink_target(hlink_db, ent)
401 meta = metadata.from_path(ent.name, hardlink_target=hlink)
402 except (OSError, IOError), e:
404 lastskip_name = ent.name
406 metalists[-1].append((sort_key, meta))
408 if exists and wasmissing:
414 pct = total and count*100.0/total or 100
415 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
416 % (pct, count/1024, total/1024, fcount, ftotal))
418 while len(parts) > 1: # _pop() all the parts above the root
419 _pop(force_tree = None)
420 assert(len(shalists) == 1)
421 assert(len(metalists) == 1)
423 # Finish the root directory.
424 tree = _pop(force_tree = None,
425 # When there's a collision, use empty metadata for the root.
426 dir_metadata = metadata.Metadata() if root_collision else None)
429 print tree.encode('hex')
430 if opt.commit or opt.name:
431 msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
432 commit = w.new_commit(oldref, tree, date, msg)
434 print commit.encode('hex')
437 w.close() # must close before we can update the ref
441 cli.update_ref(refname, commit, oldref)
443 git.update_ref(refname, commit, oldref)
449 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))