1 import re, struct, errno, time, zlib
2 from bup import git, ssh
3 from bup.helpers import *
8 class ClientError(Exception):
12 def _raw_write_bwlimit(f, buf, bwcount, bwtime):
15 return (len(buf), time.time())
17 # We want to write in reasonably large blocks, but not so large that
18 # they're likely to overflow a router's queue. So our bwlimit timing
19 # has to be pretty granular. Also, if it takes too long from one
20 # transmit to the next, we can't just make up for lost time to bring
21 # the average back up to bwlimit - that will risk overflowing the
22 # outbound queue, which defeats the purpose. So if we fall behind
23 # by more than one block delay, we shouldn't ever try to catch up.
24 for i in xrange(0,len(buf),4096):
26 next = max(now, bwtime + 1.0*bwcount/bwlimit)
30 bwcount = len(sub) # might be less than 4096
32 return (bwcount, bwtime)
35 def parse_remote(remote):
36 protocol = r'([a-z]+)://'
37 host = r'(?P<sb>\[)?((?(sb)[0-9a-f:]+|[^:/]+))(?(sb)\])'
41 '%s(?:%s%s)?%s' % (protocol, host, port, path), remote, re.I)
43 if not url_match.group(1) in ('ssh', 'bup', 'file'):
44 raise ClientError, 'unexpected protocol: %s' % url_match.group(1)
45 return url_match.group(1,3,4,5)
47 rs = remote.split(':', 1)
48 if len(rs) == 1 or rs[0] in ('', '-'):
49 return 'file', None, None, rs[-1]
51 return 'ssh', rs[0], None, rs[1]
55 def __init__(self, remote, create=False):
56 self._busy = self.conn = None
57 self.sock = self.p = self.pout = self.pin = None
58 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
61 remote = '%s:' % is_reverse
62 (self.protocol, self.host, self.port, self.dir) = parse_remote(remote)
63 self.cachedir = git.repo('index-cache/%s'
64 % re.sub(r'[^@\w]', '_',
65 "%s:%s" % (self.host, self.dir)))
67 self.pout = os.fdopen(3, 'rb')
68 self.pin = os.fdopen(4, 'wb')
69 self.conn = Conn(self.pout, self.pin)
71 if self.protocol in ('ssh', 'file'):
73 # FIXME: ssh and file shouldn't use the same module
74 self.p = ssh.connect(self.host, self.port, 'server')
75 self.pout = self.p.stdout
76 self.pin = self.p.stdin
77 self.conn = Conn(self.pout, self.pin)
79 raise ClientError, 'connect: %s' % e, sys.exc_info()[2]
80 elif self.protocol == 'bup':
81 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
82 self.sock.connect((self.host, atoi(self.port) or 1982))
83 self.sockw = self.sock.makefile('wb')
84 self.conn = DemuxConn(self.sock.fileno(), self.sockw)
86 self.dir = re.sub(r'[\r\n]', ' ', self.dir)
88 self.conn.write('init-dir %s\n' % self.dir)
90 self.conn.write('set-dir %s\n' % self.dir)
98 if e.errno == errno.EPIPE:
104 if self.conn and not self._busy:
105 self.conn.write('quit\n')
108 if self.sock and self.sockw:
110 self.sock.shutdown(socket.SHUT_WR)
121 raise ClientError('server tunnel returned exit code %d' % rv)
123 self.sock = self.p = self.pin = self.pout = None
129 raise ClientError('server exited unexpectedly with code %r'
132 return self.conn.check_ok()
134 raise ClientError, e, sys.exc_info()[2]
136 def check_busy(self):
138 raise ClientError('already busy with command %r' % self._busy)
140 def ensure_busy(self):
142 raise ClientError('expected to be busy, but not busy?!')
147 def sync_indexes(self):
150 mkdirp(self.cachedir)
151 # All cached idxs are extra until proven otherwise
153 for f in os.listdir(self.cachedir):
155 if f.endswith('.idx'):
158 conn.write('list-indexes\n')
159 for line in linereader(conn):
162 assert(line.find('/') < 0)
163 parts = line.split(' ')
165 if len(parts) == 2 and parts[1] == 'load' and idx not in extra:
166 # If the server requests that we load an idx and we don't
167 # already have a copy of it, it is needed
169 # Any idx that the server has heard of is proven not extra
173 debug1('client: removing extra indexes: %s\n' % extra)
175 os.unlink(os.path.join(self.cachedir, idx))
176 debug1('client: server requested load of: %s\n' % needed)
179 git.auto_midx(self.cachedir)
181 def sync_index(self, name):
182 #debug1('requesting %r\n' % name)
184 mkdirp(self.cachedir)
185 fn = os.path.join(self.cachedir, name)
186 if os.path.exists(fn):
187 msg = "won't request existing .idx, try `bup bloom --check %s`" % fn
188 raise ClientError(msg)
189 self.conn.write('send-index %s\n' % name)
190 n = struct.unpack('!I', self.conn.read(4))[0]
192 with atomically_replaced_file(fn, 'w') as f:
194 progress('Receiving index from server: %d/%d\r' % (count, n))
195 for b in chunkyreader(self.conn, n):
198 qprogress('Receiving index from server: %d/%d\r' % (count, n))
199 progress('Receiving index from server: %d/%d, done.\n' % (count, n))
202 def _make_objcache(self):
203 return git.PackIdxList(self.cachedir)
205 def _suggest_packs(self):
208 assert(ob == 'receive-objects-v2')
209 self.conn.write('\xff\xff\xff\xff') # suspend receive-objects-v2
211 for line in linereader(self.conn):
214 debug2('%s\n' % line)
215 if line.startswith('index '):
217 debug1('client: received index suggestion: %s\n'
218 % git.shorten_hash(idx))
219 suggested.append(idx)
221 assert(line.endswith('.idx'))
222 debug1('client: completed writing pack, idx: %s\n'
223 % git.shorten_hash(line))
224 suggested.append(line)
229 for idx in suggested:
231 git.auto_midx(self.cachedir)
234 self.conn.write('%s\n' % ob)
237 def new_packwriter(self, compression_level = 1):
240 self._busy = 'receive-objects-v2'
241 self.conn.write('receive-objects-v2\n')
242 return PackWriter_Remote(self.conn,
243 objcache_maker = self._make_objcache,
244 suggest_packs = self._suggest_packs,
246 onclose = self._not_busy,
247 ensure_busy = self.ensure_busy,
248 compression_level = compression_level)
250 def read_ref(self, refname):
252 self.conn.write('read-ref %s\n' % refname)
253 r = self.conn.readline().strip()
256 assert(len(r) == 40) # hexified sha
257 return r.decode('hex')
259 return None # nonexistent ref
261 def update_ref(self, refname, newval, oldval):
263 self.conn.write('update-ref %s\n%s\n%s\n'
264 % (refname, newval.encode('hex'),
265 (oldval or '').encode('hex')))
271 self.conn.write('cat %s\n' % re.sub(r'[\n\r]', '_', id))
273 sz = struct.unpack('!I', self.conn.read(4))[0]
275 yield self.conn.read(sz)
279 raise KeyError(str(e))
282 class PackWriter_Remote(git.PackWriter):
283 def __init__(self, conn, objcache_maker, suggest_packs,
286 compression_level=1):
287 git.PackWriter.__init__(self, objcache_maker)
289 self.filename = 'remote socket'
290 self.suggest_packs = suggest_packs
292 self.onclose = onclose
293 self.ensure_busy = ensure_busy
294 self._packopen = False
296 self._bwtime = time.time()
299 if not self._packopen:
301 self._packopen = True
304 if self._packopen and self.file:
305 self.file.write('\0\0\0\0')
306 self._packopen = False
307 self.onclose() # Unbusy
309 return self.suggest_packs() # Returns last idx received
317 raise ClientError("don't know how to abort remote pack writing")
319 def _raw_write(self, datalist, sha):
321 if not self._packopen:
324 data = ''.join(datalist)
327 crc = zlib.crc32(data) & 0xffffffff
328 outbuf = ''.join((struct.pack('!I', len(data) + 20 + 4),
330 struct.pack('!I', crc),
333 (self._bwcount, self._bwtime) = _raw_write_bwlimit(
334 self.file, outbuf, self._bwcount, self._bwtime)
336 raise ClientError, e, sys.exc_info()[2]
337 self.outbytes += len(data)
340 if self.file.has_input():
342 self.objcache.refresh()