]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
327d36677db12526ae115986e71941e3772ac62a
[bup.git] / cmd / save-cmd.py
1 #!/usr/bin/env python
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
7
8
9 optspec = """
10 bup save [-tc] [-n name] <filenames...>
11 --
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]
26 """
27 o = options.Options(optspec)
28 (opt, flags, extra) = o.parse(sys.argv[1:])
29
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")
33 if not extra:
34     o.fatal("no filenames given")
35
36 opt.progress = (istty2 and not opt.quiet)
37 opt.smaller = parse_num(opt.smaller or 0)
38 if opt.bwlimit:
39     client.bwlimit = parse_num(opt.bwlimit)
40
41 if opt.date:
42     date = parse_date_or_fatal(opt.date, o.fatal)
43 else:
44     date = time.time()
45
46 if opt.strip and opt.strip_path:
47     o.fatal("--strip is incompatible with --strip-path")
48
49 graft_points = []
50 if opt.graft:
51     if opt.strip:
52         o.fatal("--strip is incompatible with --graft")
53
54     if opt.strip_path:
55         o.fatal("--strip-path is incompatible with --graft")
56
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)))
66
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")
70
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)
78 else:
79     cli = None
80     oldref = refname and git.read_ref(refname) or None
81     w = git.PackWriter(compression_level=opt.compress)
82
83 handle_ctrl_c()
84
85
86 def eatslash(dir):
87     if dir.endswith('/'):
88         return dir[:-1]
89     else:
90         return dir
91
92
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.
97 #
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.
103
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.
109
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.
113
114
115 def _push(part, metadata):
116     # Enter a new archive directory -- make it the current directory.
117     parts.append(part)
118     shalists.append([])
119     metalists.append([('', metadata)]) # This dir's metadata (no name).
120
121
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)
125     part = parts.pop()
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,
135                                                    [metadata_f],
136                                                    keep_boundaries=False)
137         shalist.append((mode, '.bupm', id))
138     tree = force_tree or w.new_tree(shalist)
139     if shalists:
140         shalists[-1].append((GIT_MODE_TREE,
141                              git.mangle_name(part,
142                                              GIT_MODE_TREE, GIT_MODE_TREE),
143                              tree))
144     return tree
145
146
147 lastremain = None
148 def progress_report(n):
149     global count, subcount, lastremain
150     subcount += n
151     cc = count + subcount
152     pct = total and (cc*100.0/total) or 0
153     now = time.time()
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
158     if cc:
159         remain = elapsed*1.0/cc * (total-cc)
160     else:
161         remain = 0.0
162     if (lastremain and (remain > lastremain)
163           and ((remain - lastremain)/lastremain < 0.05)):
164         remain = lastremain
165     else:
166         lastremain = remain
167     hours = int(remain/60/60)
168     mins = int(remain/60 - hours*60)
169     secs = int(remain - hours*60*60 - mins*60)
170     if elapsed < 30:
171         remainstr = ''
172         kpsstr = ''
173     else:
174         kpsstr = '%dk/s' % kps
175         if hours:
176             remainstr = '%dh%dm' % (hours, mins)
177         elif mins:
178             remainstr = '%dm%d' % (mins, secs)
179         else:
180             remainstr = '%ds' % secs
181     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
182               % (pct, cc/1024, total/1024, fcount, ftotal,
183                  remainstr, kpsstr))
184
185
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)
190     sys.exit(1)
191 msr = index.MetaStoreReader(indexfile + '.meta')
192 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
193
194 def already_saved(ent):
195     return ent.is_valid() and w.exists(ent.sha) and ent.sha
196
197 def wantrecurse_pre(ent):
198     return not already_saved(ent)
199
200 def wantrecurse_during(ent):
201     return not already_saved(ent) or ent.sha_missing()
202
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)
206         if link_paths:
207             return link_paths[0]
208
209 total = ftotal = 0
210 if opt.progress:
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:
219                 total += ent.size
220         ftotal += 1
221     progress('Reading index: %d, done.\n' % ftotal)
222     hashsplit.progress_callback = progress_report
223
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".
229
230 # FIXME: Add collision tests, or handle collisions some other way.
231
232 # FIXME: Detect/handle strip/graft name collisions (other than root),
233 # i.e. if '/foo/bar' and '/bar' both map to '/'.
234
235 first_root = None
236 root_collision = None
237 tstart = time.time()
238 count = subcount = fcount = 0
239 lastskip_name = None
240 lastdir = ''
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()
246     oldsize = ent.size
247     if opt.verbose:
248         if not exists:
249             status = 'D'
250         elif not hashvalid:
251             if ent.sha == index.EMPTY_SHA:
252                 status = 'A'
253             else:
254                 status = 'M'
255         else:
256             status = ' '
257         if opt.verbose >= 2:
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, '')))
262             lastdir = dir
263
264     if opt.progress:
265         progress_report(0)
266     fcount += 1
267     
268     if not exists:
269         continue
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
274         continue
275
276     assert(dir.startswith('/'))
277     if opt.strip:
278         dirp = stripped_path_components(dir, extra)
279     elif opt.strip_path:
280         dirp = stripped_path_components(dir, [opt.strip_path])
281     elif graft_points:
282         dirp = grafted_path_components(graft_points, dir)
283     else:
284         dirp = path_components(dir)
285
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'), ...].
291
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),
298     # ...].
299
300     if first_root == None:
301         dir_name, fs_path = dirp[0]
302         first_root = dirp[0]
303         # Not indexed, so just grab the FS metadata or use empty metadata.
304         try:
305            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
306         except (OSError, IOError), e:
307             add_error(e)
308             lastskip_name = dir_name
309         else:
310            _push(dir_name, meta)
311     elif first_root != dirp[0]:
312         root_collision = True
313
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)
317
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.
322         try:
323            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
324         except (OSError, IOError), e:
325             add_error(e)
326             lastskip_name = dir_name
327         else:
328            _push(dir_name, meta)
329
330     if not file:
331         if len(parts) == 1:
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)
336         if not oldtree:
337             if lastskip_name and lastskip_name.startswith(ent.name):
338                 ent.invalidate()
339             else:
340                 ent.validate(GIT_MODE_TREE, newtree)
341             ent.repack()
342         if exists and wasmissing:
343             count += oldsize
344         continue
345
346     # it's not a directory
347     id = None
348     if hashvalid:
349         id = ent.sha
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))
359     else:
360         if stat.S_ISREG(ent.mode):
361             try:
362                 f = hashsplit.open_noatime(ent.name)
363             except (IOError, OSError), e:
364                 add_error(e)
365                 lastskip_name = ent.name
366             else:
367                 try:
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
374         else:
375             if stat.S_ISDIR(ent.mode):
376                 assert(0)  # handled above
377             elif stat.S_ISLNK(ent.mode):
378                 try:
379                     rl = os.readlink(ent.name)
380                 except (OSError, IOError), e:
381                     add_error(e)
382                     lastskip_name = ent.name
383                 else:
384                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
385             else:
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(""))
390
391         if id:
392             ent.validate(mode, id)
393             ent.repack()
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)
399             try:
400                 meta = metadata.from_path(ent.name, hardlink_target=hlink)
401             except (OSError, IOError), e:
402                 add_error(e)
403                 lastskip_name = ent.name
404             else:
405                 metalists[-1].append((sort_key, meta))
406
407     if exists and wasmissing:
408         count += oldsize
409         subcount = 0
410
411
412 if opt.progress:
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))
416
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)
421
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)
426
427 if opt.tree:
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)
432     if opt.commit:
433         print commit.encode('hex')
434
435 msr.close()
436 w.close()  # must close before we can update the ref
437         
438 if opt.name:
439     if cli:
440         cli.update_ref(refname, commit, oldref)
441     else:
442         git.update_ref(refname, commit, oldref)
443
444 if cli:
445     cli.close()
446
447 if saved_errors:
448     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
449     sys.exit(1)