]> arthur.barton.de Git - bup.git/blob - cmd/save-cmd.py
cmd/{save,split}: add a --bwlimit option.
[bup.git] / cmd / save-cmd.py
1 #!/usr/bin/env python
2 import sys, re, errno, stat, time, math
3 from bup import hashsplit, git, options, index, client
4 from bup.helpers import *
5
6
7 optspec = """
8 bup save [-tc] [-n name] <filenames...>
9 --
10 r,remote=  remote repository path
11 t,tree     output a tree id
12 c,commit   output a commit id
13 n,name=    name of backup set to update (if any)
14 v,verbose  increase log output (can be used more than once)
15 q,quiet    don't show progress meter
16 smaller=   only back up files smaller than n bytes
17 bwlimit=   maximum bytes/sec to transmit to server
18 """
19 o = options.Options('bup save', optspec)
20 (opt, flags, extra) = o.parse(sys.argv[1:])
21
22 git.check_repo_or_die()
23 if not (opt.tree or opt.commit or opt.name):
24     o.fatal("use one or more of -t, -c, -n")
25 if not extra:
26     o.fatal("no filenames given")
27
28 opt.progress = (istty and not opt.quiet)
29 opt.smaller = parse_num(opt.smaller or 0)
30 if opt.bwlimit:
31     client.bwlimit = parse_num(opt.bwlimit)
32
33 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
34 if is_reverse and opt.remote:
35     o.fatal("don't use -r in reverse mode; it's automatic")
36
37 refname = opt.name and 'refs/heads/%s' % opt.name or None
38 if opt.remote or is_reverse:
39     cli = client.Client(opt.remote)
40     oldref = refname and cli.read_ref(refname) or None
41     w = cli.new_packwriter()
42 else:
43     cli = None
44     oldref = refname and git.read_ref(refname) or None
45     w = git.PackWriter()
46
47 handle_ctrl_c()
48
49
50 def eatslash(dir):
51     if dir.endswith('/'):
52         return dir[:-1]
53     else:
54         return dir
55
56
57 parts = ['']
58 shalists = [[]]
59
60 def _push(part):
61     assert(part)
62     parts.append(part)
63     shalists.append([])
64
65 def _pop(force_tree):
66     assert(len(parts) >= 1)
67     part = parts.pop()
68     shalist = shalists.pop()
69     tree = force_tree or w.new_tree(shalist)
70     if shalists:
71         shalists[-1].append(('40000', part, tree))
72     else:  # this was the toplevel, so put it back for sanity
73         shalists.append(shalist)
74     return tree
75
76 lastremain = None
77 def progress_report(n):
78     global count, subcount, lastremain
79     subcount += n
80     cc = count + subcount
81     pct = total and (cc*100.0/total) or 0
82     now = time.time()
83     elapsed = now - tstart
84     kps = elapsed and int(cc/1024./elapsed)
85     kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
86     kps = int(kps/kps_frac)*kps_frac
87     if cc:
88         remain = elapsed*1.0/cc * (total-cc)
89     else:
90         remain = 0.0
91     if (lastremain and (remain > lastremain)
92           and ((remain - lastremain)/lastremain < 0.05)):
93         remain = lastremain
94     else:
95         lastremain = remain
96     hours = int(remain/60/60)
97     mins = int(remain/60 - hours*60)
98     secs = int(remain - hours*60*60 - mins*60)
99     if elapsed < 30:
100         remainstr = ''
101         kpsstr = ''
102     else:
103         kpsstr = '%dk/s' % kps
104         if hours:
105             remainstr = '%dh%dm' % (hours, mins)
106         elif mins:
107             remainstr = '%dm%d' % (mins, secs)
108         else:
109             remainstr = '%ds' % secs
110     progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
111              % (pct, cc/1024, total/1024, fcount, ftotal,
112                 remainstr, kpsstr))
113
114
115 r = index.Reader(git.repo('bupindex'))
116
117 def already_saved(ent):
118     return ent.is_valid() and w.exists(ent.sha) and ent.sha
119
120 def wantrecurse_pre(ent):
121     return not already_saved(ent)
122
123 def wantrecurse_during(ent):
124     return not already_saved(ent) or ent.sha_missing()
125
126 total = ftotal = 0
127 if opt.progress:
128     for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
129         if not (ftotal % 10024):
130             progress('Reading index: %d\r' % ftotal)
131         exists = ent.exists()
132         hashvalid = already_saved(ent)
133         ent.set_sha_missing(not hashvalid)
134         if not opt.smaller or ent.size < opt.smaller:
135             if exists and not hashvalid:
136                 total += ent.size
137         ftotal += 1
138     progress('Reading index: %d, done.\n' % ftotal)
139     hashsplit.progress_callback = progress_report
140
141 tstart = time.time()
142 count = subcount = fcount = 0
143 lastskip_name = None
144 lastdir = ''
145 for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
146     (dir, file) = os.path.split(ent.name)
147     exists = (ent.flags & index.IX_EXISTS)
148     hashvalid = already_saved(ent)
149     wasmissing = ent.sha_missing()
150     oldsize = ent.size
151     if opt.verbose:
152         if not exists:
153             status = 'D'
154         elif not hashvalid:
155             if ent.sha == index.EMPTY_SHA:
156                 status = 'A'
157             else:
158                 status = 'M'
159         else:
160             status = ' '
161         if opt.verbose >= 2:
162             log('%s %-70s\n' % (status, ent.name))
163         elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
164             if not lastdir.startswith(dir):
165                 log('%s %-70s\n' % (status, os.path.join(dir, '')))
166             lastdir = dir
167
168     if opt.progress:
169         progress_report(0)
170     fcount += 1
171     
172     if not exists:
173         continue
174     if opt.smaller and ent.size >= opt.smaller:
175         if exists and not hashvalid:
176             add_error('skipping large file "%s"' % ent.name)
177             lastskip_name = ent.name
178         continue
179
180     assert(dir.startswith('/'))
181     dirp = dir.split('/')
182     while parts > dirp:
183         _pop(force_tree = None)
184     if dir != '/':
185         for part in dirp[len(parts):]:
186             _push(part)
187
188     if not file:
189         # no filename portion means this is a subdir.  But
190         # sub/parentdirectories already handled in the pop/push() part above.
191         oldtree = already_saved(ent) # may be None
192         newtree = _pop(force_tree = oldtree)
193         if not oldtree:
194             if lastskip_name and lastskip_name.startswith(ent.name):
195                 ent.invalidate()
196             else:
197                 ent.validate(040000, newtree)
198             ent.repack()
199         if exists and wasmissing:
200             count += oldsize
201         continue
202
203     # it's not a directory
204     id = None
205     if hashvalid:
206         mode = '%o' % ent.gitmode
207         id = ent.sha
208         shalists[-1].append((mode, 
209                              git.mangle_name(file, ent.mode, ent.gitmode),
210                              id))
211     else:
212         if stat.S_ISREG(ent.mode):
213             try:
214                 f = hashsplit.open_noatime(ent.name)
215             except IOError, e:
216                 add_error(e)
217                 lastskip_name = ent.name
218             except OSError, e:
219                 add_error(e)
220                 lastskip_name = ent.name
221             else:
222                 (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
223         else:
224             if stat.S_ISDIR(ent.mode):
225                 assert(0)  # handled above
226             elif stat.S_ISLNK(ent.mode):
227                 try:
228                     rl = os.readlink(ent.name)
229                 except OSError, e:
230                     add_error(e)
231                     lastskip_name = ent.name
232                 except IOError, e:
233                     add_error(e)
234                     lastskip_name = ent.name
235                 else:
236                     (mode, id) = ('120000', w.new_blob(rl))
237             else:
238                 add_error(Exception('skipping special file "%s"' % ent.name))
239                 lastskip_name = ent.name
240         if id:
241             ent.validate(int(mode, 8), id)
242             ent.repack()
243             shalists[-1].append((mode,
244                                  git.mangle_name(file, ent.mode, ent.gitmode),
245                                  id))
246     if exists and wasmissing:
247         count += oldsize
248         subcount = 0
249
250
251 if opt.progress:
252     pct = total and count*100.0/total or 100
253     progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
254              % (pct, count/1024, total/1024, fcount, ftotal))
255
256 while len(parts) > 1:
257     _pop(force_tree = None)
258 assert(len(shalists) == 1)
259 tree = w.new_tree(shalists[-1])
260 if opt.tree:
261     print tree.encode('hex')
262 if opt.commit or opt.name:
263     msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
264     ref = opt.name and ('refs/heads/%s' % opt.name) or None
265     commit = w.new_commit(oldref, tree, msg)
266     if opt.commit:
267         print commit.encode('hex')
268
269 w.close()  # must close before we can update the ref
270         
271 if opt.name:
272     if cli:
273         cli.update_ref(refname, commit, oldref)
274     else:
275         git.update_ref(refname, commit, oldref)
276
277 if cli:
278     cli.close()
279
280 if saved_errors:
281     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
282     sys.exit(1)