]> arthur.barton.de Git - bup.git/blob - cmd/server-cmd.py
Dumb server doesn't need objcache
[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 def _set_mode():
10     global dumb_server_mode
11     dumb_server_mode = os.path.exists(git.repo('bup-dumb-server'))
12     debug1('bup server: serving in %s mode\n' 
13            % (dumb_server_mode and 'dumb' or 'smart'))
14
15
16 def init_dir(conn, arg):
17     git.init_repo(arg)
18     debug1('bup server: bupdir initialized: %r\n' % git.repodir)
19     _set_mode()
20     conn.ok()
21
22
23 def set_dir(conn, arg):
24     git.check_repo_or_die(arg)
25     debug1('bup server: bupdir is %r\n' % git.repodir)
26     _set_mode()
27     conn.ok()
28
29     
30 def list_indexes(conn, junk):
31     git.check_repo_or_die()
32     suffix = ''
33     if dumb_server_mode:
34         suffix = ' load'
35     for f in os.listdir(git.repo('objects/pack')):
36         if f.endswith('.idx'):
37             conn.write('%s%s\n' % (f, suffix))
38     conn.ok()
39
40
41 def send_index(conn, name):
42     git.check_repo_or_die()
43     assert(name.find('/') < 0)
44     assert(name.endswith('.idx'))
45     idx = git.open_idx(git.repo('objects/pack/%s' % name))
46     conn.write(struct.pack('!I', len(idx.map)))
47     conn.write(idx.map)
48     conn.ok()
49
50
51 def receive_objects_v2(conn, junk):
52     global suspended_w
53     git.check_repo_or_die()
54     suggested = {}
55     if suspended_w:
56         w = suspended_w
57         suspended_w = None
58     else:
59         if dumb_server_mode:
60             w = git.PackWriter(objcache_maker=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=not dumb_server_mode)
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 not dumb_server_mode:
95             oldpack = w.exists(shar)
96             # FIXME: we only suggest a single index per cycle, because the client
97             # is currently too dumb to download more than one per cycle anyway.
98             # Actually we should fix the client, but this is a minor optimization
99             # on the server side.
100             if not suggested and \
101               oldpack and (oldpack == True or oldpack.endswith('.midx')):
102                 # FIXME: we shouldn't really have to know about midx files
103                 # at this layer.  But exists() on a midx doesn't return the
104                 # packname (since it doesn't know)... probably we should just
105                 # fix that deficiency of midx files eventually, although it'll
106                 # make the files bigger.  This method is certainly not very
107                 # efficient.
108                 oldpack = w.objcache.packname_containing(shar)
109                 debug2('new suggestion: %r\n' % oldpack)
110                 assert(oldpack)
111                 assert(oldpack != True)
112                 assert(not oldpack.endswith('.midx'))
113                 w.objcache.refresh()
114             if not suggested and oldpack:
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" % name)
119                     conn.write('index %s\n' % name)
120                     suggested[name] = 1
121                 continue
122         nw, crc = w._raw_write([buf], sha=shar)
123         _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
124         _check(w, n, nw, 'object read: expected %d bytes, got %d\n')
125     # NOTREACHED
126     
127
128 def _check(w, expected, actual, msg):
129     if expected != actual:
130         w.abort()
131         raise Exception(msg % (expected, actual))
132
133
134 def read_ref(conn, refname):
135     git.check_repo_or_die()
136     r = git.read_ref(refname)
137     conn.write('%s\n' % (r or '').encode('hex'))
138     conn.ok()
139
140
141 def update_ref(conn, refname):
142     git.check_repo_or_die()
143     newval = conn.readline().strip()
144     oldval = conn.readline().strip()
145     git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
146     conn.ok()
147
148
149 cat_pipe = None
150 def cat(conn, id):
151     global cat_pipe
152     git.check_repo_or_die()
153     if not cat_pipe:
154         cat_pipe = git.CatPipe()
155     try:
156         for blob in cat_pipe.join(id):
157             conn.write(struct.pack('!I', len(blob)))
158             conn.write(blob)
159     except KeyError, e:
160         log('server: error: %s\n' % e)
161         conn.write('\0\0\0\0')
162         conn.error(e)
163     else:
164         conn.write('\0\0\0\0')
165         conn.ok()
166
167
168 optspec = """
169 bup server
170 """
171 o = options.Options('bup server', optspec)
172 (opt, flags, extra) = o.parse(sys.argv[1:])
173
174 if extra:
175     o.fatal('no arguments expected')
176
177 debug2('bup server: reading from stdin.\n')
178
179 commands = {
180     'init-dir': init_dir,
181     'set-dir': set_dir,
182     'list-indexes': list_indexes,
183     'send-index': send_index,
184     'receive-objects-v2': receive_objects_v2,
185     'read-ref': read_ref,
186     'update-ref': update_ref,
187     'cat': cat,
188 }
189
190 # FIXME: this protocol is totally lame and not at all future-proof.
191 # (Especially since we abort completely as soon as *anything* bad happens)
192 conn = Conn(sys.stdin, sys.stdout)
193 lr = linereader(conn)
194 for _line in lr:
195     line = _line.strip()
196     if not line:
197         continue
198     debug1('bup server: command: %r\n' % line)
199     words = line.split(' ', 1)
200     cmd = words[0]
201     rest = len(words)>1 and words[1] or ''
202     if cmd == 'quit':
203         break
204     else:
205         cmd = commands.get(cmd)
206         if cmd:
207             cmd(conn, rest)
208         else:
209             raise Exception('unknown server command: %r\n' % line)
210
211 debug1('bup server: done\n')