2 import sys, stat, time, math
3 from cStringIO import StringIO
4 from bup import hashsplit, git, options, index, client, metadata, hlinkdb
5 from bup.helpers import *
6 from bup.hashsplit import GIT_MODE_TREE, GIT_MODE_FILE, GIT_MODE_SYMLINK
10 bup save [-tc] [-n name] <filenames...>
12 r,remote= hostname:/path/to/repo of remote repository
13 t,tree output a tree id
14 c,commit output a commit id
15 n,name= name of backup set to update (if any)
16 d,date= date for the commit (seconds since the epoch)
17 v,verbose increase log output (can be used more than once)
18 q,quiet don't show progress meter
19 smaller= only back up files smaller than n bytes
20 bwlimit= maximum bytes/sec to transmit to server
21 f,indexfile= the name of the index file (normally BUP_DIR/bupindex)
22 strip strips the path to every filename given
23 strip-path= path-prefix to be stripped when saving
24 graft= a graft point *old_path*=*new_path* (can be used more than once)
25 #,compress= set compression level to # (0-9, 9 is highest) [1]
27 o = options.Options(optspec)
28 (opt, flags, extra) = o.parse(sys.argv[1:])
30 git.check_repo_or_die()
31 if not (opt.tree or opt.commit or opt.name):
32 o.fatal("use one or more of -t, -c, -n")
34 o.fatal("no filenames given")
36 opt.progress = (istty2 and not opt.quiet)
37 opt.smaller = parse_num(opt.smaller or 0)
39 client.bwlimit = parse_num(opt.bwlimit)
42 date = parse_date_or_fatal(opt.date, o.fatal)
46 if opt.strip and opt.strip_path:
47 o.fatal("--strip is incompatible with --strip-path")
52 o.fatal("--strip is incompatible with --graft")
55 o.fatal("--strip-path is incompatible with --graft")
57 for (option, parameter) in flags:
58 if option == "--graft":
59 splitted_parameter = parameter.split('=')
60 if len(splitted_parameter) != 2:
61 o.fatal("a graft point must be of the form old_path=new_path")
62 old_path, new_path = splitted_parameter
63 if not (old_path and new_path):
64 o.fatal("a graft point cannot be empty")
65 graft_points.append((realpath(old_path), realpath(new_path)))
67 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
68 if is_reverse and opt.remote:
69 o.fatal("don't use -r in reverse mode; it's automatic")
71 if opt.name and opt.name.startswith('.'):
72 o.fatal("'%s' is not a valid branch name" % opt.name)
73 refname = opt.name and 'refs/heads/%s' % opt.name or None
74 if opt.remote or is_reverse:
75 cli = client.Client(opt.remote)
76 oldref = refname and cli.read_ref(refname) or None
77 w = cli.new_packwriter(compression_level=opt.compress)
80 oldref = refname and git.read_ref(refname) or None
81 w = git.PackWriter(compression_level=opt.compress)
93 # Metadata is stored in a file named .bupm in each directory. The
94 # first metadata entry will be the metadata for the current directory.
95 # The remaining entries will be for each of the other directory
96 # elements, in the order they're listed in the index.
98 # Since the git tree elements are sorted according to
99 # git.shalist_item_sort_key, the metalist items are accumulated as
100 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
101 # created. The sort_key must be computed using the element's real
102 # name and mode rather than the git mode and (possibly mangled) name.
104 # Maintain a stack of information representing the current location in
105 # the archive being constructed. The current path is recorded in
106 # parts, which will be something like ['', 'home', 'someuser'], and
107 # the accumulated content and metadata for of the dirs in parts is
108 # stored in parallel stacks in shalists and metalists.
110 parts = [] # Current archive position (stack of dir names).
111 shalists = [] # Hashes for each dir in paths.
112 metalists = [] # Metadata for each dir in paths.
115 def _push(part, metadata):
116 # Enter a new archive directory -- make it the current directory.
119 metalists.append([('', metadata)]) # This dir's metadata (no name).
122 def _pop(force_tree, dir_metadata=None):
123 # Leave the current archive directory and add its tree to its parent.
124 assert(len(parts) >= 1)
126 shalist = shalists.pop()
127 metalist = metalists.pop()
128 if metalist and not force_tree:
129 if dir_metadata: # Override the original metadata pushed for this dir.
130 metalist = [('', dir_metadata)] + metalist[1:]
131 sorted_metalist = sorted(metalist, key = lambda x : x[0])
132 metadata = ''.join([m[1].encode() for m in sorted_metalist])
133 metadata_f = StringIO(metadata)
134 mode, id = hashsplit.split_to_blob_or_tree(w.new_blob, w.new_tree,
136 keep_boundaries=False)
137 shalist.append((mode, '.bupm', id))
138 tree = force_tree or w.new_tree(shalist)
140 shalists[-1].append((GIT_MODE_TREE,
141 git.mangle_name(part,
142 GIT_MODE_TREE, GIT_MODE_TREE),
148 def progress_report(n):
149 global count, subcount, lastremain
151 cc = count + subcount
152 pct = total and (cc*100.0/total) or 0
154 elapsed = now - tstart
155 kps = elapsed and int(cc/1024./elapsed)
156 kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
157 kps = int(kps/kps_frac)*kps_frac
159 remain = elapsed*1.0/cc * (total-cc)
162 if (lastremain and (remain > lastremain)
163 and ((remain - lastremain)/lastremain < 0.05)):
167 hours = int(remain/60/60)
168 mins = int(remain/60 - hours*60)
169 secs = int(remain - hours*60*60 - mins*60)
174 kpsstr = '%dk/s' % kps
176 remainstr = '%dh%dm' % (hours, mins)
178 remainstr = '%dm%d' % (mins, secs)
180 remainstr = '%ds' % secs
181 qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
182 % (pct, cc/1024, total/1024, fcount, ftotal,
186 indexfile = opt.indexfile or git.repo('bupindex')
187 r = index.Reader(indexfile)
188 if not os.access(indexfile + '.meta', os.W_OK|os.R_OK):
189 log('error: cannot access "%s"; have you run bup index?' % indexfile)
191 msr = index.MetaStoreReader(indexfile + '.meta')
192 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
194 def already_saved(ent):
195 return ent.is_valid() and w.exists(ent.sha) and ent.sha
197 def wantrecurse_pre(ent):
198 return not already_saved(ent)
200 def wantrecurse_during(ent):
201 return not already_saved(ent) or ent.sha_missing()
203 def find_hardlink_target(hlink_db, ent):
204 if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
205 link_paths = hlink_db.node_paths(ent.dev, ent.ino)
211 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
212 if not (ftotal % 10024):
213 qprogress('Reading index: %d\r' % ftotal)
214 exists = ent.exists()
215 hashvalid = already_saved(ent)
216 ent.set_sha_missing(not hashvalid)
217 if not opt.smaller or ent.size < opt.smaller:
218 if exists and not hashvalid:
221 progress('Reading index: %d, done.\n' % ftotal)
222 hashsplit.progress_callback = progress_report
224 # Root collisions occur when strip or graft options map more than one
225 # path to the same directory (paths which originally had separate
226 # parents). When that situation is detected, use empty metadata for
227 # the parent. Otherwise, use the metadata for the common parent.
228 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
230 # FIXME: Add collision tests, or handle collisions some other way.
232 # FIXME: Detect/handle strip/graft name collisions (other than root),
233 # i.e. if '/foo/bar' and '/bar' both map to '/'.
236 root_collision = None
238 count = subcount = fcount = 0
241 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
242 (dir, file) = os.path.split(ent.name)
243 exists = (ent.flags & index.IX_EXISTS)
244 hashvalid = already_saved(ent)
245 wasmissing = ent.sha_missing()
251 if ent.sha == index.EMPTY_SHA:
258 log('%s %-70s\n' % (status, ent.name))
259 elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
260 if not lastdir.startswith(dir):
261 log('%s %-70s\n' % (status, os.path.join(dir, '')))
270 if opt.smaller and ent.size >= opt.smaller:
271 if exists and not hashvalid:
272 add_error('skipping large file "%s"' % ent.name)
273 lastskip_name = ent.name
276 assert(dir.startswith('/'))
278 dirp = stripped_path_components(dir, extra)
280 dirp = stripped_path_components(dir, [opt.strip_path])
282 dirp = grafted_path_components(graft_points, dir)
284 dirp = path_components(dir)
286 # At this point, dirp contains a representation of the archive
287 # path that looks like [(archive_dir_name, real_fs_path), ...].
288 # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
289 # might look like this at some point:
290 # [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
292 # This dual representation supports stripping/grafting, where the
293 # archive path may not have a direct correspondence with the
294 # filesystem. The root directory is represented by an initial
295 # component named '', and any component that doesn't have a
296 # corresponding filesystem directory (due to grafting, for
297 # example) will have a real_fs_path of None, i.e. [('', None),
300 if first_root == None:
301 dir_name, fs_path = dirp[0]
303 # Not indexed, so just grab the FS metadata or use empty metadata.
305 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
306 except (OSError, IOError), e:
308 lastskip_name = dir_name
310 _push(dir_name, meta)
311 elif first_root != dirp[0]:
312 root_collision = True
314 # If switching to a new sub-tree, finish the current sub-tree.
315 while parts > [x[0] for x in dirp]:
316 _pop(force_tree = None)
318 # If switching to a new sub-tree, start a new sub-tree.
319 for path_component in dirp[len(parts):]:
320 dir_name, fs_path = path_component
321 # Not indexed, so just grab the FS metadata or use empty metadata.
323 meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
324 except (OSError, IOError), e:
326 lastskip_name = dir_name
328 _push(dir_name, meta)
332 continue # We're at the top level -- keep the current root dir
333 # Since there's no filename, this is a subdir -- finish it.
334 oldtree = already_saved(ent) # may be None
335 newtree = _pop(force_tree = oldtree)
337 if lastskip_name and lastskip_name.startswith(ent.name):
340 ent.validate(GIT_MODE_TREE, newtree)
342 if exists and wasmissing:
346 # it's not a directory
350 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
351 git_info = (ent.gitmode, git_name, id)
352 shalists[-1].append(git_info)
353 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
354 meta = msr.metadata_at(ent.meta_ofs)
355 meta.hardlink_target = find_hardlink_target(hlink_db, ent)
356 # Restore the times that were cleared to 0 in the metastore.
357 (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
358 metalists[-1].append((sort_key, meta))
360 if stat.S_ISREG(ent.mode):
362 f = hashsplit.open_noatime(ent.name)
363 except (IOError, OSError), e:
365 lastskip_name = ent.name
368 (mode, id) = hashsplit.split_to_blob_or_tree(
369 w.new_blob, w.new_tree, [f],
370 keep_boundaries=False)
371 except (IOError, OSError), e:
372 add_error('%s: %s' % (ent.name, e))
373 lastskip_name = ent.name
375 if stat.S_ISDIR(ent.mode):
376 assert(0) # handled above
377 elif stat.S_ISLNK(ent.mode):
379 rl = os.readlink(ent.name)
380 except (OSError, IOError), e:
382 lastskip_name = ent.name
384 (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
386 # Everything else should be fully described by its
387 # metadata, so just record an empty blob, so the paths
388 # in the tree and .bupm will match up.
389 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
392 ent.validate(mode, id)
394 git_name = git.mangle_name(file, ent.mode, ent.gitmode)
395 git_info = (mode, git_name, id)
396 shalists[-1].append(git_info)
397 sort_key = git.shalist_item_sort_key((ent.mode, file, id))
398 hlink = find_hardlink_target(hlink_db, ent)
400 meta = metadata.from_path(ent.name, hardlink_target=hlink)
401 except (OSError, IOError), e:
403 lastskip_name = ent.name
405 metalists[-1].append((sort_key, meta))
407 if exists and wasmissing:
413 pct = total and count*100.0/total or 100
414 progress('Saving: %.2f%% (%d/%dk, %d/%d files), done. \n'
415 % (pct, count/1024, total/1024, fcount, ftotal))
417 while len(parts) > 1: # _pop() all the parts above the root
418 _pop(force_tree = None)
419 assert(len(shalists) == 1)
420 assert(len(metalists) == 1)
422 # Finish the root directory.
423 tree = _pop(force_tree = None,
424 # When there's a collision, use empty metadata for the root.
425 dir_metadata = metadata.Metadata() if root_collision else None)
428 print tree.encode('hex')
429 if opt.commit or opt.name:
430 msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
431 commit = w.new_commit(oldref, tree, date, msg)
433 print commit.encode('hex')
436 w.close() # must close before we can update the ref
440 cli.update_ref(refname, commit, oldref)
442 git.update_ref(refname, commit, oldref)
448 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))