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