]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
save-cmd.py: hashsplit .bupm metadata files.
[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:
72     if opt.name.startswith('.'):
73         o.fatal('backup set names cannot start with "."')
74     if '/' in opt.name:
75         o.fatal('backup set names cannot contain "/"')
76 refname = opt.name and 'refs/heads/%s' % opt.name or None
77 if opt.remote or is_reverse:
78     cli = client.Client(opt.remote)
79     oldref = refname and cli.read_ref(refname) or None
80     w = cli.new_packwriter(compression_level=opt.compress)
81 else:
82     cli = None
83     oldref = refname and git.read_ref(refname) or None
84     w = git.PackWriter(compression_level=opt.compress)
85
86 handle_ctrl_c()
87
88
89 def eatslash(dir):
90     if dir.endswith('/'):
91         return dir[:-1]
92     else:
93         return dir
94
95
96 # Metadata is stored in a file named .bupm in each directory.  The
97 # first metadata entry will be the metadata for the current directory.
98 # The remaining entries will be for each of the other directory
99 # elements, in the order they're listed in the index.
100 #
101 # Since the git tree elements are sorted according to
102 # git.shalist_item_sort_key, the metalist items are accumulated as
103 # (sort_key, metadata) tuples, and then sorted when the .bupm file is
104 # created.  The sort_key must be computed using the element's real
105 # name and mode rather than the git mode and (possibly mangled) name.
106
107 # Maintain a stack of information representing the current location in
108 # the archive being constructed.  The current path is recorded in
109 # parts, which will be something like ['', 'home', 'someuser'], and
110 # the accumulated content and metadata for of the dirs in parts is
111 # stored in parallel stacks in shalists and metalists.
112
113 parts = [] # Current archive position (stack of dir names).
114 shalists = [] # Hashes for each dir in paths.
115 metalists = [] # Metadata for each dir in paths.
116
117
118 def _push(part, metadata):
119     # Enter a new archive directory -- make it the current directory.
120     parts.append(part)
121     shalists.append([])
122     metalists.append([('', metadata)]) # This dir's metadata (no name).
123
124
125 def _pop(force_tree, dir_metadata=None):
126     # Leave the current archive directory and add its tree to its parent.
127     assert(len(parts) >= 1)
128     part = parts.pop()
129     shalist = shalists.pop()
130     metalist = metalists.pop()
131     if metalist and not force_tree:
132         if dir_metadata: # Override the original metadata pushed for this dir.
133             metalist = [('', dir_metadata)] + metalist[1:]
134         sorted_metalist = sorted(metalist, key = lambda x : x[0])
135         metadata = ''.join([m[1].encode() for m in sorted_metalist])
136         metadata_f = StringIO(metadata)
137         mode, id = hashsplit.split_to_blob_or_tree(w.new_blob, w.new_tree,
138                                                    [metadata_f],
139                                                    keep_boundaries=False)
140         shalist.append((mode, '.bupm', id))
141     tree = force_tree or w.new_tree(shalist)
142     if shalists:
143         shalists[-1].append((GIT_MODE_TREE,
144                              git.mangle_name(part,
145                                              GIT_MODE_TREE, GIT_MODE_TREE),
146                              tree))
147     return tree
148
149
150 lastremain = None
151 def progress_report(n):
152     global count, subcount, lastremain
153     subcount += n
154     cc = count + subcount
155     pct = total and (cc*100.0/total) or 0
156     now = time.time()
157     elapsed = now - tstart
158     kps = elapsed and int(cc/1024./elapsed)
159     kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
160     kps = int(kps/kps_frac)*kps_frac
161     if cc:
162         remain = elapsed*1.0/cc * (total-cc)
163     else:
164         remain = 0.0
165     if (lastremain and (remain > lastremain)
166           and ((remain - lastremain)/lastremain < 0.05)):
167         remain = lastremain
168     else:
169         lastremain = remain
170     hours = int(remain/60/60)
171     mins = int(remain/60 - hours*60)
172     secs = int(remain - hours*60*60 - mins*60)
173     if elapsed < 30:
174         remainstr = ''
175         kpsstr = ''
176     else:
177         kpsstr = '%dk/s' % kps
178         if hours:
179             remainstr = '%dh%dm' % (hours, mins)
180         elif mins:
181             remainstr = '%dm%d' % (mins, secs)
182         else:
183             remainstr = '%ds' % secs
184     qprogress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
185               % (pct, cc/1024, total/1024, fcount, ftotal,
186                  remainstr, kpsstr))
187
188
189 indexfile = opt.indexfile or git.repo('bupindex')
190 r = index.Reader(indexfile)
191 if not os.access(indexfile + '.meta', os.W_OK|os.R_OK):
192     log('error: cannot access "%s"; have you run bup index?' % indexfile)
193     sys.exit(1)
194 msr = index.MetaStoreReader(indexfile + '.meta')
195 hlink_db = hlinkdb.HLinkDB(indexfile + '.hlink')
196
197 def already_saved(ent):
198     return ent.is_valid() and w.exists(ent.sha) and ent.sha
199
200 def wantrecurse_pre(ent):
201     return not already_saved(ent)
202
203 def wantrecurse_during(ent):
204     return not already_saved(ent) or ent.sha_missing()
205
206 def find_hardlink_target(hlink_db, ent):
207     if hlink_db and not stat.S_ISDIR(ent.mode) and ent.nlink > 1:
208         link_paths = hlink_db.node_paths(ent.dev, ent.ino)
209         if link_paths:
210             return link_paths[0]
211
212 total = ftotal = 0
213 if opt.progress:
214     for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
215         if not (ftotal % 10024):
216             qprogress('Reading index: %d\r' % ftotal)
217         exists = ent.exists()
218         hashvalid = already_saved(ent)
219         ent.set_sha_missing(not hashvalid)
220         if not opt.smaller or ent.size < opt.smaller:
221             if exists and not hashvalid:
222                 total += ent.size
223         ftotal += 1
224     progress('Reading index: %d, done.\n' % ftotal)
225     hashsplit.progress_callback = progress_report
226
227 # Root collisions occur when strip or graft options map more than one
228 # path to the same directory (paths which originally had separate
229 # parents).  When that situation is detected, use empty metadata for
230 # the parent.  Otherwise, use the metadata for the common parent.
231 # Collision example: "bup save ... --strip /foo /foo/bar /bar".
232
233 # FIXME: Add collision tests, or handle collisions some other way.
234
235 # FIXME: Detect/handle strip/graft name collisions (other than root),
236 # i.e. if '/foo/bar' and '/bar' both map to '/'.
237
238 first_root = None
239 root_collision = None
240 tstart = time.time()
241 count = subcount = fcount = 0
242 lastskip_name = None
243 lastdir = ''
244 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
245     (dir, file) = os.path.split(ent.name)
246     exists = (ent.flags & index.IX_EXISTS)
247     hashvalid = already_saved(ent)
248     wasmissing = ent.sha_missing()
249     oldsize = ent.size
250     if opt.verbose:
251         if not exists:
252             status = 'D'
253         elif not hashvalid:
254             if ent.sha == index.EMPTY_SHA:
255                 status = 'A'
256             else:
257                 status = 'M'
258         else:
259             status = ' '
260         if opt.verbose >= 2:
261             log('%s %-70s\n' % (status, ent.name))
262         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
263             if not lastdir.startswith(dir):
264                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
265             lastdir = dir
266
267     if opt.progress:
268         progress_report(0)
269     fcount += 1
270     
271     if not exists:
272         continue
273     if opt.smaller and ent.size >= opt.smaller:
274         if exists and not hashvalid:
275             add_error('skipping large file "%s"' % ent.name)
276             lastskip_name = ent.name
277         continue
278
279     assert(dir.startswith('/'))
280     if opt.strip:
281         dirp = stripped_path_components(dir, extra)
282     elif opt.strip_path:
283         dirp = stripped_path_components(dir, [opt.strip_path])
284     elif graft_points:
285         dirp = grafted_path_components(graft_points, dir)
286     else:
287         dirp = path_components(dir)
288
289     # At this point, dirp contains a representation of the archive
290     # path that looks like [(archive_dir_name, real_fs_path), ...].
291     # So given "bup save ... --strip /foo/bar /foo/bar/baz", dirp
292     # might look like this at some point:
293     #   [('', '/foo/bar'), ('baz', '/foo/bar/baz'), ...].
294
295     # This dual representation supports stripping/grafting, where the
296     # archive path may not have a direct correspondence with the
297     # filesystem.  The root directory is represented by an initial
298     # component named '', and any component that doesn't have a
299     # corresponding filesystem directory (due to grafting, for
300     # example) will have a real_fs_path of None, i.e. [('', None),
301     # ...].
302
303     if first_root == None:
304         dir_name, fs_path = dirp[0]
305         first_root = dirp[0]
306         # Not indexed, so just grab the FS metadata or use empty metadata.
307         try:
308            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
309         except (OSError, IOError), e:
310             add_error(e)
311             lastskip_name = dir_name
312         else:
313            _push(dir_name, meta)
314     elif first_root != dirp[0]:
315         root_collision = True
316
317     # If switching to a new sub-tree, finish the current sub-tree.
318     while parts > [x[0] for x in dirp]:
319         _pop(force_tree = None)
320
321     # If switching to a new sub-tree, start a new sub-tree.
322     for path_component in dirp[len(parts):]:
323         dir_name, fs_path = path_component
324         # Not indexed, so just grab the FS metadata or use empty metadata.
325         try:
326            meta = metadata.from_path(fs_path) if fs_path else metadata.Metadata()
327         except (OSError, IOError), e:
328             add_error(e)
329             lastskip_name = dir_name
330         else:
331            _push(dir_name, meta)
332
333     if not file:
334         if len(parts) == 1:
335             continue # We're at the top level -- keep the current root dir
336         # Since there's no filename, this is a subdir -- finish it.
337         oldtree = already_saved(ent) # may be None
338         newtree = _pop(force_tree = oldtree)
339         if not oldtree:
340             if lastskip_name and lastskip_name.startswith(ent.name):
341                 ent.invalidate()
342             else:
343                 ent.validate(GIT_MODE_TREE, newtree)
344             ent.repack()
345         if exists and wasmissing:
346             count += oldsize
347         continue
348
349     # it's not a directory
350     id = None
351     if hashvalid:
352         id = ent.sha
353         git_name = git.mangle_name(file, ent.mode, ent.gitmode)
354         git_info = (ent.gitmode, git_name, id)
355         shalists[-1].append(git_info)
356         sort_key = git.shalist_item_sort_key((ent.mode, file, id))
357         meta = msr.metadata_at(ent.meta_ofs)
358         meta.hardlink_target = find_hardlink_target(hlink_db, ent)
359         # Restore the times that were cleared to 0 in the metastore.
360         (meta.atime, meta.mtime, meta.ctime) = (ent.atime, ent.mtime, ent.ctime)
361         metalists[-1].append((sort_key, meta))
362     else:
363         if stat.S_ISREG(ent.mode):
364             try:
365                 f = hashsplit.open_noatime(ent.name)
366             except (IOError, OSError), e:
367                 add_error(e)
368                 lastskip_name = ent.name
369             else:
370                 try:
371                     (mode, id) = hashsplit.split_to_blob_or_tree(
372                                             w.new_blob, w.new_tree, [f],
373                                             keep_boundaries=False)
374                 except (IOError, OSError), e:
375                     add_error('%s: %s' % (ent.name, e))
376                     lastskip_name = ent.name
377         else:
378             if stat.S_ISDIR(ent.mode):
379                 assert(0)  # handled above
380             elif stat.S_ISLNK(ent.mode):
381                 try:
382                     rl = os.readlink(ent.name)
383                 except (OSError, IOError), e:
384                     add_error(e)
385                     lastskip_name = ent.name
386                 else:
387                     (mode, id) = (GIT_MODE_SYMLINK, w.new_blob(rl))
388             else:
389                 # Everything else should be fully described by its
390                 # metadata, so just record an empty blob, so the paths
391                 # in the tree and .bupm will match up.
392                 (mode, id) = (GIT_MODE_FILE, w.new_blob(""))
393
394         if id:
395             ent.validate(mode, id)
396             ent.repack()
397             git_name = git.mangle_name(file, ent.mode, ent.gitmode)
398             git_info = (mode, git_name, id)
399             shalists[-1].append(git_info)
400             sort_key = git.shalist_item_sort_key((ent.mode, file, id))
401             hlink = find_hardlink_target(hlink_db, ent)
402             try:
403                 meta = metadata.from_path(ent.name, hardlink_target=hlink)
404             except (OSError, IOError), e:
405                 add_error(e)
406                 lastskip_name = ent.name
407             else:
408                 metalists[-1].append((sort_key, meta))
409
410     if exists and wasmissing:
411         count += oldsize
412         subcount = 0
413
414
415 if opt.progress:
416     pct = total and count*100.0/total or 100
417     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
418              % (pct, count/1024, total/1024, fcount, ftotal))
419
420 while len(parts) > 1: # _pop() all the parts above the root
421     _pop(force_tree = None)
422 assert(len(shalists) == 1)
423 assert(len(metalists) == 1)
424
425 # Finish the root directory.
426 tree = _pop(force_tree = None,
427             # When there's a collision, use empty metadata for the root.
428             dir_metadata = metadata.Metadata() if root_collision else None)
429
430 if opt.tree:
431     print tree.encode('hex')
432 if opt.commit or opt.name:
433     msg = 'bup save\n\nGenerated by command:\n%r\n' % sys.argv
434     commit = w.new_commit(oldref, tree, date, msg)
435     if opt.commit:
436         print commit.encode('hex')
437
438 msr.close()
439 w.close()  # must close before we can update the ref
440         
441 if opt.name:
442     if cli:
443         cli.update_ref(refname, commit, oldref)
444     else:
445         git.update_ref(refname, commit, oldref)
446
447 if cli:
448     cli.close()
449
450 if saved_errors:
451     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
452     sys.exit(1)