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
9 bup save [-tc] [-n name] <filenames...>
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]
26 o = options.Options(optspec)
27 (opt, flags, extra) = o.parse(sys.argv[1:])
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")
33 o.fatal("no filenames given")
35 opt.progress = (istty2 and not opt.quiet)
36 opt.smaller = parse_num(opt.smaller or 0)
38 client.bwlimit = parse_num(opt.bwlimit)
41 date = parse_date_or_fatal(opt.date, o.fatal)
45 if opt.strip and opt.strip_path:
46 o.fatal("--strip is incompatible with --strip-path")
51 o.fatal("--strip is incompatible with --graft")
54 o.fatal("--strip-path is incompatible with --graft")
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)))
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")
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()
79 oldref = refname and git.read_ref(refname) or None
80 w = git.PackWriter(compression_level=opt.compress)
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.
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.
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.
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.
114 def _push(part, metadata):
115 # Enter a new archive directory -- make it the current directory.
118 metalists.append([('', metadata)]) # This dir's metadata (no name).
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)
125 shalist = shalists.pop()
126 metalist = metalists.pop()
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)
135 shalists[-1].append((GIT_MODE_TREE,
136 git.mangle_name(part,
137 GIT_MODE_TREE, GIT_MODE_TREE),
143 def progress_report(n):
144 global count, subcount, lastremain
146 cc = count + subcount
147 pct = total and (cc*100.0/total) or 0
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
154 remain = elapsed*1.0/cc * (total-cc)
157 if (lastremain and (remain > lastremain)
158 and ((remain - lastremain)/lastremain < 0.05)):
162 hours = int(remain/60/60)
163 mins = int(remain/60 - hours*60)
164 secs = int(remain - hours*60*60 - mins*60)
169 kpsstr = '%dk/s' % kps
171 remainstr = '%dh%dm' % (hours, mins)
173 remainstr = '%dm%d' % (mins, secs)
175 remainstr = '%ds' % secs
176 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
177 % (pct, cc/1024, total/1024, fcount, ftotal,
181 indexfile = opt.indexfile or git.repo('bupindex')
182 r = index.Reader(indexfile)
183 msr = index.MetaStoreReader(indexfile + '.meta')
184 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
186 def already_saved(ent):
187 return ent.is_valid() and w.exists(ent.sha) and ent.sha
189 def wantrecurse_pre(ent):
190 return not already_saved(ent)
192 def wantrecurse_during(ent):
193 return not already_saved(ent) or ent.sha_missing()
195 def find_hardlink_target(hlink_db, ent):
196 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
197 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
203 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
204 if not (ftotal % 10024):
205 qprogress('Reading index: %d\r' % ftotal)
206 exists = ent.exists()
207 hashvalid = already_saved(ent)
208 ent.set_sha_missing(not hashvalid)
209 if not opt.smaller or ent.size < opt.smaller:
210 if exists and not hashvalid:
213 progress('Reading index: %d, done.\n' % ftotal)
214 hashsplit.progress_callback = progress_report
216 # Root collisions occur when strip or graft options map more than one
217 # path to the same directory (paths which originally had separate
218 # parents). When that situation is detected, use empty metadata for
219 # the parent. Otherwise, use the metadata for the common parent.
220 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
222 # FIXME: Add collision tests, or handle collisions some other way.
224 # FIXME: Detect/handle strip/graft name collisions (other than root),
225 # i.e. if '/foo/bar' and '/bar' both map to '/'.
228 root_collision = None
230 count = subcount = fcount = 0
233 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
234 (dir, file) = os.path.split(ent.name)
235 exists = (ent.flags & index.IX_EXISTS)
236 hashvalid = already_saved(ent)
237 wasmissing = ent.sha_missing()
243 if ent.sha == index.EMPTY_SHA:
250 log('%s %-70s\n' % (status, ent.name))
251 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
252 if not lastdir.startswith(dir):
253 log('%s %-70s\n' % (status, os.path.join(dir, '')))
262 if opt.smaller and ent.size >= opt.smaller:
263 if exists and not hashvalid:
264 add_error('skipping large file "%s"' % ent.name)
265 lastskip_name = ent.name
268 assert(dir.startswith('/'))
270 dirp = stripped_path_components(dir, extra)
272 dirp = stripped_path_components(dir, [opt.strip_path])
274 dirp = grafted_path_components(graft_points, dir)
276 dirp = path_components(dir)
278 # At this point, dirp contains a representation of the archive
279 # path that looks like [(archive_dir_name, real_fs_path), ...].
280 # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
281 # might look like this at some point:
282 # [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
284 # This dual representation supports stripping/grafting, where the
285 # archive path may not have a direct correspondence with the
286 # filesystem. The root directory is represented by an initial
287 # component named '', and any component that doesn't have a
288 # corresponding filesystem directory (due to grafting, for
289 # example) will have a real_fs_path of None, i.e. [('', None),
292 if first_root == None:
293 dir_name, fs_path = dirp[0]
295 # Not indexed, so just grab the FS metadata or use empty metadata.
296 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
297 _push(dir_name, meta)
298 elif first_root != dirp[0]:
299 root_collision = True
301 # If switching to a new sub-tree, finish the current sub-tree.
302 while parts > [x[0] for x in dirp]:
303 _pop(force_tree = None)
305 # If switching to a new sub-tree, start a new sub-tree.
306 for path_component in dirp[len(parts):]:
307 dir_name, fs_path = path_component
308 # Not indexed, so just grab the FS metadata or use empty metadata.
309 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
310 _push(dir_name, meta)
314 continue # We're at the top level -- keep the current root dir
315 # Since there's no filename, this is a subdir -- finish it.
316 oldtree = already_saved(ent) # may be None
317 newtree = _pop(force_tree = oldtree)
319 if lastskip_name and lastskip_name.startswith(ent.name):
322 ent.validate(GIT_MODE_TREE, newtree)
324 if exists and wasmissing:
328 # it's not a directory
332 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
333 git_info = (ent.gitmode, git_name, id)
334 shalists[-1].append(git_info)
335 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
336 meta = msr.metadata_at(ent.meta_ofs)
337 meta.hardlink_target = find_hardlink_target(hlink_db, ent)
338 # Restore the times that were cleared to 0 in the metastore.
339 (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
340 metalists[-1].append((sort_key, meta))
342 if stat.S_ISREG(ent.mode):
344 f = hashsplit.open_noatime(ent.name)
345 except (IOError, OSError), e:
347 lastskip_name = ent.name
350 (mode, id) = hashsplit.split_to_blob_or_tree(
351 w.new_blob, w.new_tree, [f],
352 keep_boundaries=False)
353 except (IOError, OSError), e:
354 add_error('%s: %s' % (ent.name, e))
355 lastskip_name = ent.name
357 if stat.S_ISDIR(ent.mode):
358 assert(0) # handled above
359 elif stat.S_ISLNK(ent.mode):
361 rl = os.readlink(ent.name)
362 except (OSError, IOError), e:
364 lastskip_name = ent.name
366 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
368 # Everything else should be fully described by its
369 # metadata, so just record an empty blob, so the paths
370 # in the tree and .bupm will match up.
371 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
374 ent.validate(mode, id)
376 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
377 git_info = (mode, git_name, id)
378 shalists[-1].append(git_info)
379 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
380 hlink = find_hardlink_target(hlink_db, ent)
381 metalists[-1].append((sort_key,
382 metadata.from_path(ent.name,
383 hardlink_target=hlink)))
384 if exists and wasmissing:
390 pct = total and count*100.0/total or 100
391 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
392 % (pct, count/1024, total/1024, fcount, ftotal))
394 while len(parts) > 1: # _pop() all the parts above the root
395 _pop(force_tree = None)
396 assert(len(shalists) == 1)
397 assert(len(metalists) == 1)
399 # Finish the root directory.
400 tree = _pop(force_tree = None,
401 # When there's a collision, use empty metadata for the root.
402 dir_metadata = metadata.Metadata() if root_collision else None)
405 print tree.encode('hex')
406 if opt.commit or opt.name:
407 msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
408 commit = w.new_commit(oldref, tree, date, msg)
410 print commit.encode('hex')
413 w.close() # must close before we can update the ref
417 cli.update_ref(refname, commit, oldref)
419 git.update_ref(refname, commit, oldref)
425 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))