3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
8 import os, sys, struct, subprocess
10 from bup import options, git
11 from bup.git import MissingObject
12 from bup.helpers import (Conn, debug1, debug2, linereader, lines_until_sentinel,
17 dumb_server_mode = False
20 def do_help(conn, junk):
21 conn.write('Commands:\n %s\n' % '\n '.join(sorted(commands)))
26 global dumb_server_mode
27 dumb_server_mode = os.path.exists(git.repo('bup-dumb-server'))
28 debug1('bup server: serving in %s mode\n'
29 % (dumb_server_mode and 'dumb' or 'smart'))
32 def _init_session(reinit_with_new_repopath=None):
33 if reinit_with_new_repopath is None and git.repodir:
35 git.check_repo_or_die(reinit_with_new_repopath)
36 # OK. we now know the path is a proper repository. Record this path in the
37 # environment so that subprocesses inherit it and know where to operate.
38 os.environ['BUP_DIR'] = git.repodir
39 debug1('bup server: bupdir is %r\n' % git.repodir)
43 def init_dir(conn, arg):
45 debug1('bup server: bupdir initialized: %r\n' % git.repodir)
50 def set_dir(conn, arg):
55 def list_indexes(conn, junk):
60 for f in os.listdir(git.repo('objects/pack')):
61 if f.endswith('.idx'):
62 conn.write('%s%s\n' % (f, suffix))
66 def send_index(conn, name):
68 assert(name.find('/') < 0)
69 assert(name.endswith('.idx'))
70 idx = git.open_idx(git.repo('objects/pack/%s' % name))
71 conn.write(struct.pack('!I', len(idx.map)))
76 def receive_objects_v2(conn, junk):
85 w = git.PackWriter(objcache_maker=None)
92 raise Exception('object read: expected length header, got EOF\n')
93 n = struct.unpack('!I', ns)[0]
94 #debug2('expecting %d bytes\n' % n)
96 debug1('bup server: received %d object%s.\n'
97 % (w.count, w.count!=1 and "s" or ''))
98 fullpath = w.close(run_midx=not dumb_server_mode)
100 (dir, name) = os.path.split(fullpath)
101 conn.write('%s.idx\n' % name)
104 elif n == 0xffffffff:
105 debug2('bup server: receive-objects suspended.\n')
111 crcr = struct.unpack('!I', conn.read(4))[0]
113 buf = conn.read(n) # object sizes in bup are reasonably small
114 #debug2('read %d bytes\n' % n)
115 _check(w, n, len(buf), 'object read: expected %d bytes, got %d\n')
116 if not dumb_server_mode:
117 oldpack = w.exists(shar, want_source=True)
119 assert(not oldpack == True)
120 assert(oldpack.endswith('.idx'))
121 (dir,name) = os.path.split(oldpack)
122 if not (name in suggested):
123 debug1("bup server: suggesting index %s\n"
124 % git.shorten_hash(name))
125 debug1("bup server: because of object %s\n"
126 % shar.encode('hex'))
127 conn.write('index %s\n' % name)
130 nw, crc = w._raw_write((buf,), sha=shar)
131 _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
135 def _check(w, expected, actual, msg):
136 if expected != actual:
138 raise Exception(msg % (expected, actual))
141 def read_ref(conn, refname):
143 r = git.read_ref(refname)
144 conn.write('%s\n' % (r or '').encode('hex'))
148 def update_ref(conn, refname):
150 newval = conn.readline().strip()
151 oldval = conn.readline().strip()
152 git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
158 for blob in git.cp().join(id):
159 conn.write(struct.pack('!I', len(blob)))
161 except KeyError as e:
162 log('server: error: %s\n' % e)
163 conn.write('\0\0\0\0')
166 conn.write('\0\0\0\0')
169 def cat_batch(conn, dummy):
172 # For now, avoid potential deadlock by just reading them all
173 for ref in tuple(lines_until_sentinel(conn, '\n', Exception)):
175 it = cat_pipe.get(ref)
178 conn.write('missing\n')
180 conn.write('%s %s %d\n' % info)
185 def refs(conn, args):
186 limit_to_heads, limit_to_tags = args.split()
187 assert limit_to_heads in ('0', '1')
188 assert limit_to_tags in ('0', '1')
189 limit_to_heads = int(limit_to_heads)
190 limit_to_tags = int(limit_to_tags)
192 patterns = tuple(x[:-1] for x in lines_until_sentinel(conn, '\n', Exception))
193 for name, oid in git.list_refs(patterns=patterns,
194 limit_to_heads=limit_to_heads,
195 limit_to_tags=limit_to_tags):
196 assert '\n' not in name
197 conn.write('%s %s\n' % (oid.encode('hex'), name))
201 def rev_list(conn, _):
203 count = conn.readline()
205 raise Exception('Unexpected EOF while reading rev-list count')
206 count = None if count == '\n' else int(count)
207 fmt = conn.readline()
209 raise Exception('Unexpected EOF while reading rev-list format')
210 fmt = None if fmt == '\n' else fmt[:-1]
211 refs = tuple(x[:-1] for x in lines_until_sentinel(conn, '\n', Exception))
212 args = git.rev_list_invocation(refs, count=count, format=fmt)
213 p = subprocess.Popen(git.rev_list_invocation(refs, count=count, format=fmt),
214 preexec_fn=git._gitenv(git.repodir),
215 stdout=subprocess.PIPE)
217 out = p.stdout.read(64 * 1024)
221 rv = p.wait() # not fatal
223 msg = 'git rev-list returned error %d' % rv
232 o = options.Options(optspec)
233 (opt, flags, extra) = o.parse(sys.argv[1:])
236 o.fatal('no arguments expected')
238 debug2('bup server: reading from stdin.\n')
243 'init-dir': init_dir,
245 'list-indexes': list_indexes,
246 'send-index': send_index,
247 'receive-objects-v2': receive_objects_v2,
248 'read-ref': read_ref,
249 'update-ref': update_ref,
251 'cat': join, # apocryphal alias
252 'cat-batch' : cat_batch,
257 # FIXME: this protocol is totally lame and not at all future-proof.
258 # (Especially since we abort completely as soon as *anything* bad happens)
259 conn = Conn(sys.stdin, sys.stdout)
260 lr = linereader(conn)
265 debug1('bup server: command: %r\n' % line)
266 words = line.split(' ', 1)
268 rest = len(words)>1 and words[1] or ''
272 cmd = commands.get(cmd)
276 raise Exception('unknown server command: %r\n' % line)
278 debug1('bup server: done\n')