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