]> arthur.barton.de Git - bup.git/blob - cmd/server-cmd.py
Don't generate midx files in dumb server mode
[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 server_mode = 'smart'
8
9 def _set_mode():
10     global server_mode
11     if os.path.exists(git.repo('bup-dumb-server')):
12         server_mode = 'dumb'
13     else:
14         server_mode = 'smart'
15     debug1('bup server: serving in %s mode\n' % server_mode)
16
17
18 def init_dir(conn, arg):
19     git.init_repo(arg)
20     debug1('bup server: bupdir initialized: %r\n' % git.repodir)
21     _set_mode()
22     conn.ok()
23
24
25 def set_dir(conn, arg):
26     git.check_repo_or_die(arg)
27     debug1('bup server: bupdir is %r\n' % git.repodir)
28     _set_mode()
29     conn.ok()
30
31     
32 def list_indexes(conn, junk):
33     global server_mode
34     git.check_repo_or_die()
35     suffix = ''
36     if server_mode == 'dumb':
37         suffix = ' load'
38     for f in os.listdir(git.repo('objects/pack')):
39         if f.endswith('.idx'):
40             conn.write('%s%s\n' % (f, suffix))
41     conn.ok()
42
43
44 def send_index(conn, name):
45     git.check_repo_or_die()
46     assert(name.find('/') < 0)
47     assert(name.endswith('.idx'))
48     idx = git.open_idx(git.repo('objects/pack/%s' % name))
49     conn.write(struct.pack('!I', len(idx.map)))
50     conn.write(idx.map)
51     conn.ok()
52
53
54 def receive_objects_v2(conn, junk):
55     global suspended_w, server_mode
56     git.check_repo_or_die()
57     suggested = {}
58     if suspended_w:
59         w = suspended_w
60         suspended_w = None
61     else:
62         w = git.PackWriter()
63     while 1:
64         ns = conn.read(4)
65         if not ns:
66             w.abort()
67             raise Exception('object read: expected length header, got EOF\n')
68         n = struct.unpack('!I', ns)[0]
69         #debug2('expecting %d bytes\n' % n)
70         if not n:
71             debug1('bup server: received %d object%s.\n' 
72                 % (w.count, w.count!=1 and "s" or ''))
73             fullpath = w.close(run_midx=(server_mode=='smart'))
74             if fullpath:
75                 (dir, name) = os.path.split(fullpath)
76                 conn.write('%s.idx\n' % name)
77             conn.ok()
78             return
79         elif n == 0xffffffff:
80             debug2('bup server: receive-objects suspended.\n')
81             suspended_w = w
82             conn.ok()
83             return
84             
85         shar = conn.read(20)
86         crcr = struct.unpack('!I', conn.read(4))[0]
87         n -= 20 + 4
88         buf = conn.read(n)  # object sizes in bup are reasonably small
89         #debug2('read %d bytes\n' % n)
90         if len(buf) < n:
91             w.abort()
92             raise Exception('object read: expected %d bytes, got %d\n'
93                             % (n, len(buf)))
94         if server_mode == 'smart':
95             oldpack = w.exists(shar)
96         else:
97             oldpack = None
98         # FIXME: we only suggest a single index per cycle, because the client
99         # is currently too dumb to download more than one per cycle anyway.
100         # Actually we should fix the client, but this is a minor optimization
101         # on the server side.
102         if not suggested and \
103           oldpack and (oldpack == True or oldpack.endswith('.midx')):
104             # FIXME: we shouldn't really have to know about midx files
105             # at this layer.  But exists() on a midx doesn't return the
106             # packname (since it doesn't know)... probably we should just
107             # fix that deficiency of midx files eventually, although it'll
108             # make the files bigger.  This method is certainly not very
109             # efficient.
110             oldpack = w.objcache.packname_containing(shar)
111             debug2('new suggestion: %r\n' % oldpack)
112             assert(oldpack)
113             assert(oldpack != True)
114             assert(not oldpack.endswith('.midx'))
115             w.objcache.refresh()
116         if not suggested and oldpack:
117             assert(oldpack.endswith('.idx'))
118             (dir,name) = os.path.split(oldpack)
119             if not (name in suggested):
120                 debug1("bup server: suggesting index %s\n" % name)
121                 conn.write('index %s\n' % name)
122                 suggested[name] = 1
123         else:
124             nw, crc = w._raw_write([buf], sha=shar)
125             _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
126             _check(w, n, nw, 'object read: expected %d bytes, 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     git.check_repo_or_die()
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     git.check_repo_or_die()
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     git.check_repo_or_die()
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('bup server', 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     'init-dir': init_dir,
183     'set-dir': set_dir,
184     'list-indexes': list_indexes,
185     'send-index': send_index,
186     'receive-objects-v2': receive_objects_v2,
187     'read-ref': read_ref,
188     'update-ref': update_ref,
189     'cat': cat,
190 }
191
192 # FIXME: this protocol is totally lame and not at all future-proof.
193 # (Especially since we abort completely as soon as *anything* bad happens)
194 conn = Conn(sys.stdin, sys.stdout)
195 lr = linereader(conn)
196 for _line in lr:
197     line = _line.strip()
198     if not line:
199         continue
200     debug1('bup server: command: %r\n' % line)
201     words = line.split(' ', 1)
202     cmd = words[0]
203     rest = len(words)>1 and words[1] or ''
204     if cmd == 'quit':
205         break
206     else:
207         cmd = commands.get(cmd)
208         if cmd:
209             cmd(conn, rest)
210         else:
211             raise Exception('unknown server command: %r\n' % line)
212
213 debug1('bup server: done\n')