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