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 assert(url_match.group(1) in ('ssh', 'bup', 'file'))
44 return url_match.group(1,3,4,5)
46 rs = remote.split(':', 1)
47 if len(rs) == 1 or rs[0] in ('', '-'):
48 return 'file', None, None, rs[-1]
50 return 'ssh', rs[0], None, rs[1]
54 def __init__(self, remote, create=False):
55 self._busy = self.conn = None
56 self.sock = self.p = self.pout = self.pin = None
57 is_reverse = os.environ.get('BUP_SERVER_REVERSE')
60 remote = '%s:' % is_reverse
61 (self.protocol, self.host, self.port, self.dir) = parse_remote(remote)
62 self.cachedir = git.repo('index-cache/%s'
63 % re.sub(r'[^@\w]', '_',
64 "%s:%s" % (self.host, self.dir)))
66 self.pout = os.fdopen(3, 'rb')
67 self.pin = os.fdopen(4, 'wb')
68 self.conn = Conn(self.pout, self.pin)
70 if self.protocol in ('ssh', 'file'):
72 # FIXME: ssh and file shouldn't use the same module
73 self.p = ssh.connect(self.host, self.port, 'server')
74 self.pout = self.p.stdout
75 self.pin = self.p.stdin
76 self.conn = Conn(self.pout, self.pin)
78 raise ClientError, 'connect: %s' % e, sys.exc_info()[2]
79 elif self.protocol == 'bup':
80 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
81 self.sock.connect((self.host, atoi(self.port) or 1982))
82 self.sockw = self.sock.makefile('wb')
83 self.conn = DemuxConn(self.sock.fileno(), self.sockw)
85 self.dir = re.sub(r'[\r\n]', ' ', self.dir)
87 self.conn.write('init-dir %s\n' % self.dir)
89 self.conn.write('set-dir %s\n' % self.dir)
97 if e.errno == errno.EPIPE:
103 if self.conn and not self._busy:
104 self.conn.write('quit\n')
107 if self.sock and self.sockw:
109 self.sock.shutdown(socket.SHUT_WR)
120 raise ClientError('server tunnel returned exit code %d' % rv)
122 self.sock = self.p = self.pin = self.pout = None
128 raise ClientError('server exited unexpectedly with code %r'
131 return self.conn.check_ok()
133 raise ClientError, e, sys.exc_info()[2]
135 def check_busy(self):
137 raise ClientError('already busy with command %r' % self._busy)
139 def ensure_busy(self):
141 raise ClientError('expected to be busy, but not busy?!')
146 def sync_indexes(self):
149 mkdirp(self.cachedir)
150 # All cached idxs are extra until proven otherwise
152 for f in os.listdir(self.cachedir):
154 if f.endswith('.idx'):
157 conn.write('list-indexes\n')
158 for line in linereader(conn):
161 assert(line.find('/') < 0)
162 parts = line.split(' ')
164 if len(parts) == 2 and parts[1] == 'load' and idx not in extra:
165 # If the server requests that we load an idx and we don't
166 # already have a copy of it, it is needed
168 # Any idx that the server has heard of is proven not extra
172 debug1('client: removing extra indexes: %s\n' % extra)
174 os.unlink(os.path.join(self.cachedir, idx))
175 debug1('client: server requested load of: %s\n' % needed)
178 git.auto_midx(self.cachedir)
181 def sync_index(self, name):
182 #debug1('requesting %r\n' % name)
184 mkdirp(self.cachedir)
185 self.conn.write('send-index %s\n' % name)
186 n = struct.unpack('!I', self.conn.read(4))[0]
188 fn = os.path.join(self.cachedir, name)
189 f = open(fn + '.tmp', 'w')
191 progress('Receiving index from server: %d/%d\r' % (count, n))
192 for b in chunkyreader(self.conn, n):
195 progress('Receiving index from server: %d/%d\r' % (count, n))
196 progress('Receiving index from server: %d/%d, done.\n' % (count, n))
199 os.rename(fn + '.tmp', fn)
201 def _make_objcache(self):
202 return git.PackIdxList(self.cachedir)
204 def _suggest_packs(self):
207 assert(ob == 'receive-objects-v2')
208 self.conn.write('\xff\xff\xff\xff') # suspend receive-objects-v2
210 for line in linereader(self.conn):
213 debug2('%s\n' % line)
214 if line.startswith('index '):
216 debug1('client: received index suggestion: %s\n' % idx)
217 suggested.append(idx)
219 assert(line.endswith('.idx'))
220 debug1('client: completed writing pack, idx: %s\n' % line)
221 suggested.append(line)
226 for idx in suggested:
228 git.auto_midx(self.cachedir)
231 self.conn.write('%s\n' % ob)
234 def new_packwriter(self):
237 self._busy = 'receive-objects-v2'
238 self.conn.write('receive-objects-v2\n')
239 return PackWriter_Remote(self.conn,
240 objcache_maker = self._make_objcache,
241 suggest_packs = self._suggest_packs,
243 onclose = self._not_busy,
244 ensure_busy = self.ensure_busy)
246 def read_ref(self, refname):
248 self.conn.write('read-ref %s\n' % refname)
249 r = self.conn.readline().strip()
252 assert(len(r) == 40) # hexified sha
253 return r.decode('hex')
255 return None # nonexistent ref
257 def update_ref(self, refname, newval, oldval):
259 self.conn.write('update-ref %s\n%s\n%s\n'
260 % (refname, newval.encode('hex'),
261 (oldval or '').encode('hex')))
267 self.conn.write('cat %s\n' % re.sub(r'[\n\r]', '_', id))
269 sz = struct.unpack('!I', self.conn.read(4))[0]
271 yield self.conn.read(sz)
275 raise KeyError(str(e))
278 class PackWriter_Remote(git.PackWriter):
279 def __init__(self, conn, objcache_maker, suggest_packs,
282 git.PackWriter.__init__(self, objcache_maker)
284 self.filename = 'remote socket'
285 self.suggest_packs = suggest_packs
287 self.onclose = onclose
288 self.ensure_busy = ensure_busy
289 self._packopen = False
291 self._bwtime = time.time()
294 if not self._packopen:
296 self._packopen = True
299 if self._packopen and self.file:
300 self.file.write('\0\0\0\0')
301 self._packopen = False
302 self.onclose() # Unbusy
304 return self.suggest_packs() # Returns last idx received
312 raise ClientError("don't know how to abort remote pack writing")
314 def _raw_write(self, datalist, sha):
316 if not self._packopen:
319 data = ''.join(datalist)
322 crc = zlib.crc32(data) & 0xffffffff
323 outbuf = ''.join((struct.pack('!I', len(data) + 20 + 4),
325 struct.pack('!I', crc),
328 (self._bwcount, self._bwtime) = _raw_write_bwlimit(
329 self.file, outbuf, self._bwcount, self._bwtime)
331 raise ClientError, e, sys.exc_info()[2]
332 self.outbytes += len(data)
335 if self.file.has_input():
337 self.objcache.refresh()