]> arthur.barton.de Git - bup.git/blob - cmd/server-cmd.py
Use absolute_import from the __future__ everywhere
[bup.git] / cmd / server-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
8 from __future__ import absolute_import
9 import os, sys, struct, subprocess
10
11 from bup import options, git
12 from bup.git import MissingObject
13 from bup.helpers import (Conn, debug1, debug2, linereader, lines_until_sentinel,
14                          log)
15
16
17 suspended_w = None
18 dumb_server_mode = False
19
20
21 def do_help(conn, junk):
22     conn.write('Commands:\n    %s\n' % '\n    '.join(sorted(commands)))
23     conn.ok()
24
25
26 def _set_mode():
27     global dumb_server_mode
28     dumb_server_mode = os.path.exists(git.repo('bup-dumb-server'))
29     debug1('bup server: serving in %s mode\n' 
30            % (dumb_server_mode and 'dumb' or 'smart'))
31
32
33 def _init_session(reinit_with_new_repopath=None):
34     if reinit_with_new_repopath is None and git.repodir:
35         return
36     git.check_repo_or_die(reinit_with_new_repopath)
37     # OK. we now know the path is a proper repository. Record this path in the
38     # environment so that subprocesses inherit it and know where to operate.
39     os.environ['BUP_DIR'] = git.repodir
40     debug1('bup server: bupdir is %r\n' % git.repodir)
41     _set_mode()
42
43
44 def init_dir(conn, arg):
45     git.init_repo(arg)
46     debug1('bup server: bupdir initialized: %r\n' % git.repodir)
47     _init_session(arg)
48     conn.ok()
49
50
51 def set_dir(conn, arg):
52     _init_session(arg)
53     conn.ok()
54
55     
56 def list_indexes(conn, junk):
57     _init_session()
58     suffix = ''
59     if dumb_server_mode:
60         suffix = ' load'
61     for f in os.listdir(git.repo('objects/pack')):
62         if f.endswith('.idx'):
63             conn.write('%s%s\n' % (f, suffix))
64     conn.ok()
65
66
67 def send_index(conn, name):
68     _init_session()
69     assert(name.find('/') < 0)
70     assert(name.endswith('.idx'))
71     idx = git.open_idx(git.repo('objects/pack/%s' % name))
72     conn.write(struct.pack('!I', len(idx.map)))
73     conn.write(idx.map)
74     conn.ok()
75
76
77 def receive_objects_v2(conn, junk):
78     global suspended_w
79     _init_session()
80     suggested = set()
81     if suspended_w:
82         w = suspended_w
83         suspended_w = None
84     else:
85         if dumb_server_mode:
86             w = git.PackWriter(objcache_maker=None)
87         else:
88             w = git.PackWriter()
89     while 1:
90         ns = conn.read(4)
91         if not ns:
92             w.abort()
93             raise Exception('object read: expected length header, got EOF\n')
94         n = struct.unpack('!I', ns)[0]
95         #debug2('expecting %d bytes\n' % n)
96         if not n:
97             debug1('bup server: received %d object%s.\n' 
98                 % (w.count, w.count!=1 and "s" or ''))
99             fullpath = w.close(run_midx=not dumb_server_mode)
100             if fullpath:
101                 (dir, name) = os.path.split(fullpath)
102                 conn.write('%s.idx\n' % name)
103             conn.ok()
104             return
105         elif n == 0xffffffff:
106             debug2('bup server: receive-objects suspended.\n')
107             suspended_w = w
108             conn.ok()
109             return
110             
111         shar = conn.read(20)
112         crcr = struct.unpack('!I', conn.read(4))[0]
113         n -= 20 + 4
114         buf = conn.read(n)  # object sizes in bup are reasonably small
115         #debug2('read %d bytes\n' % n)
116         _check(w, n, len(buf), 'object read: expected %d bytes, got %d\n')
117         if not dumb_server_mode:
118             oldpack = w.exists(shar, want_source=True)
119             if oldpack:
120                 assert(not oldpack == True)
121                 assert(oldpack.endswith('.idx'))
122                 (dir,name) = os.path.split(oldpack)
123                 if not (name in suggested):
124                     debug1("bup server: suggesting index %s\n"
125                            % git.shorten_hash(name))
126                     debug1("bup server:   because of object %s\n"
127                            % shar.encode('hex'))
128                     conn.write('index %s\n' % name)
129                     suggested.add(name)
130                 continue
131         nw, crc = w._raw_write((buf,), sha=shar)
132         _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
133     # NOTREACHED
134     
135
136 def _check(w, expected, actual, msg):
137     if expected != actual:
138         w.abort()
139         raise Exception(msg % (expected, actual))
140
141
142 def read_ref(conn, refname):
143     _init_session()
144     r = git.read_ref(refname)
145     conn.write('%s\n' % (r or '').encode('hex'))
146     conn.ok()
147
148
149 def update_ref(conn, refname):
150     _init_session()
151     newval = conn.readline().strip()
152     oldval = conn.readline().strip()
153     git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
154     conn.ok()
155
156 def join(conn, id):
157     _init_session()
158     try:
159         for blob in git.cp().join(id):
160             conn.write(struct.pack('!I', len(blob)))
161             conn.write(blob)
162     except KeyError as e:
163         log('server: error: %s\n' % e)
164         conn.write('\0\0\0\0')
165         conn.error(e)
166     else:
167         conn.write('\0\0\0\0')
168         conn.ok()
169
170 def cat_batch(conn, dummy):
171     _init_session()
172     cat_pipe = git.cp()
173     # For now, avoid potential deadlock by just reading them all
174     for ref in tuple(lines_until_sentinel(conn, '\n', Exception)):
175         ref = ref[:-1]
176         it = cat_pipe.get(ref)
177         info = next(it)
178         if not info[0]:
179             conn.write('missing\n')
180             continue
181         conn.write('%s %s %d\n' % info)
182         for buf in it:
183             conn.write(buf)
184     conn.ok()
185
186 def refs(conn, args):
187     limit_to_heads, limit_to_tags = args.split()
188     assert limit_to_heads in ('0', '1')
189     assert limit_to_tags in ('0', '1')
190     limit_to_heads = int(limit_to_heads)
191     limit_to_tags = int(limit_to_tags)
192     _init_session()
193     patterns = tuple(x[:-1] for x in lines_until_sentinel(conn, '\n', Exception))
194     for name, oid in git.list_refs(patterns=patterns,
195                                    limit_to_heads=limit_to_heads,
196                                    limit_to_tags=limit_to_tags):
197         assert '\n' not in name
198         conn.write('%s %s\n' % (oid.encode('hex'), name))
199     conn.write('\n')
200     conn.ok()
201
202 def rev_list(conn, _):
203     _init_session()
204     count = conn.readline()
205     if not count:
206         raise Exception('Unexpected EOF while reading rev-list count')
207     count = None if count == '\n' else int(count)
208     fmt = conn.readline()
209     if not fmt:
210         raise Exception('Unexpected EOF while reading rev-list format')
211     fmt = None if fmt == '\n' else fmt[:-1]
212     refs = tuple(x[:-1] for x in lines_until_sentinel(conn, '\n', Exception))
213     args = git.rev_list_invocation(refs, count=count, format=fmt)
214     p = subprocess.Popen(git.rev_list_invocation(refs, count=count, format=fmt),
215                          preexec_fn=git._gitenv(git.repodir),
216                          stdout=subprocess.PIPE)
217     while True:
218         out = p.stdout.read(64 * 1024)
219         if not out:
220             break
221         conn.write(out)
222     rv = p.wait()  # not fatal
223     if rv:
224         msg = 'git rev-list returned error %d' % rv
225         conn.error(msg)
226         raise GitError(msg)
227     conn.ok()
228
229
230 optspec = """
231 bup server
232 """
233 o = options.Options(optspec)
234 (opt, flags, extra) = o.parse(sys.argv[1:])
235
236 if extra:
237     o.fatal('no arguments expected')
238
239 debug2('bup server: reading from stdin.\n')
240
241 commands = {
242     'quit': None,
243     'help': do_help,
244     'init-dir': init_dir,
245     'set-dir': set_dir,
246     'list-indexes': list_indexes,
247     'send-index': send_index,
248     'receive-objects-v2': receive_objects_v2,
249     'read-ref': read_ref,
250     'update-ref': update_ref,
251     'join': join,
252     'cat': join,  # apocryphal alias
253     'cat-batch' : cat_batch,
254     'refs': refs,
255     'rev-list': rev_list
256 }
257
258 # FIXME: this protocol is totally lame and not at all future-proof.
259 # (Especially since we abort completely as soon as *anything* bad happens)
260 conn = Conn(sys.stdin, sys.stdout)
261 lr = linereader(conn)
262 for _line in lr:
263     line = _line.strip()
264     if not line:
265         continue
266     debug1('bup server: command: %r\n' % line)
267     words = line.split(' ', 1)
268     cmd = words[0]
269     rest = len(words)>1 and words[1] or ''
270     if cmd == 'quit':
271         break
272     else:
273         cmd = commands.get(cmd)
274         if cmd:
275             cmd(conn, rest)
276         else:
277             raise Exception('unknown server command: %r\n' % line)
278
279 debug1('bup server: done\n')