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