]> arthur.barton.de Git - bup.git/blob - cmd/server-cmd.py
Write idxs directly rather than using git-index-pack.
[bup.git] / cmd / server-cmd.py
1 #!/usr/bin/env python
2 import sys, struct
3 from bup import options, git
4 from bup.helpers import *
5
6 suspended_w = None
7
8
9 def init_dir(conn, arg):
10     git.init_repo(arg)
11     debug1('bup server: bupdir initialized: %r\n' % git.repodir)
12     conn.ok()
13
14
15 def set_dir(conn, arg):
16     git.check_repo_or_die(arg)
17     debug1('bup server: bupdir is %r\n' % git.repodir)
18     conn.ok()
19
20     
21 def list_indexes(conn, junk):
22     git.check_repo_or_die()
23     for f in os.listdir(git.repo('objects/pack')):
24         if f.endswith('.idx'):
25             conn.write('%s\n' % f)
26     conn.ok()
27
28
29 def send_index(conn, name):
30     git.check_repo_or_die()
31     assert(name.find('/') < 0)
32     assert(name.endswith('.idx'))
33     idx = git.open_idx(git.repo('objects/pack/%s' % name))
34     conn.write(struct.pack('!I', len(idx.map)))
35     conn.write(idx.map)
36     conn.ok()
37
38
39 def receive_objects(conn, junk):
40     global suspended_w
41     git.check_repo_or_die()
42     suggested = {}
43     if suspended_w:
44         w = suspended_w
45         suspended_w = None
46     else:
47         w = git.PackWriter()
48     while 1:
49         ns = conn.read(4)
50         if not ns:
51             w.abort()
52             raise Exception('object read: expected length header, got EOF\n')
53         n = struct.unpack('!I', ns)[0]
54         #debug2('expecting %d bytes\n' % n)
55         if not n:
56             debug1('bup server: received %d object%s.\n' 
57                 % (w.count, w.count!=1 and "s" or ''))
58             fullpath = w.close()
59             if fullpath:
60                 (dir, name) = os.path.split(fullpath)
61                 conn.write('%s.idx\n' % name)
62             conn.ok()
63             return
64         elif n == 0xffffffff:
65             debug2('bup server: receive-objects suspended.\n')
66             suspended_w = w
67             conn.ok()
68             return
69             
70         shar = conn.read(20)
71         crcr = struct.unpack('!I', conn.read(4))[0]
72         n -= 20 + 4
73         buf = conn.read(n)  # object sizes in bup are reasonably small
74         #debug2('read %d bytes\n' % n)
75         if len(buf) < n:
76             w.abort()
77             raise Exception('object read: expected %d bytes, got %d\n'
78                             % (n, len(buf)))
79         oldpack = w.exists(shar)
80         # FIXME: we only suggest a single index per cycle, because the client
81         # is currently too dumb to download more than one per cycle anyway.
82         # Actually we should fix the client, but this is a minor optimization
83         # on the server side.
84         if not suggested and \
85           oldpack and (oldpack == True or oldpack.endswith('.midx')):
86             # FIXME: we shouldn't really have to know about midx files
87             # at this layer.  But exists() on a midx doesn't return the
88             # packname (since it doesn't know)... probably we should just
89             # fix that deficiency of midx files eventually, although it'll
90             # make the files bigger.  This method is certainly not very
91             # efficient.
92             oldpack = w.objcache.packname_containing(shar)
93             debug2('new suggestion: %r\n' % oldpack)
94             assert(oldpack)
95             assert(oldpack != True)
96             assert(not oldpack.endswith('.midx'))
97             w.objcache.refresh()
98         if not suggested and oldpack:
99             assert(oldpack.endswith('.idx'))
100             (dir,name) = os.path.split(oldpack)
101             if not (name in suggested):
102                 debug1("bup server: suggesting index %s\n" % name)
103                 conn.write('index %s\n' % name)
104                 suggested[name] = 1
105         else:
106             nw, crc = w._raw_write([buf], sha=shar)
107             _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
108             _check(w, n, nw, 'object read: expected %d bytes, got %d\n')
109     # NOTREACHED
110     
111
112 def _check(w, expected, actual, msg):
113     if expected != actual:
114         w.abort()
115         raise Exception(msg % (expected, actual))
116
117
118 def read_ref(conn, refname):
119     git.check_repo_or_die()
120     r = git.read_ref(refname)
121     conn.write('%s\n' % (r or '').encode('hex'))
122     conn.ok()
123
124
125 def update_ref(conn, refname):
126     git.check_repo_or_die()
127     newval = conn.readline().strip()
128     oldval = conn.readline().strip()
129     git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
130     conn.ok()
131
132
133 cat_pipe = None
134 def cat(conn, id):
135     global cat_pipe
136     git.check_repo_or_die()
137     if not cat_pipe:
138         cat_pipe = git.CatPipe()
139     try:
140         for blob in cat_pipe.join(id):
141             conn.write(struct.pack('!I', len(blob)))
142             conn.write(blob)
143     except KeyError, e:
144         log('server: error: %s\n' % e)
145         conn.write('\0\0\0\0')
146         conn.error(e)
147     else:
148         conn.write('\0\0\0\0')
149         conn.ok()
150
151
152 optspec = """
153 bup server
154 """
155 o = options.Options('bup server', optspec)
156 (opt, flags, extra) = o.parse(sys.argv[1:])
157
158 if extra:
159     o.fatal('no arguments expected')
160
161 debug2('bup server: reading from stdin.\n')
162
163 commands = {
164     'init-dir': init_dir,
165     'set-dir': set_dir,
166     'list-indexes': list_indexes,
167     'send-index': send_index,
168     'receive-objects': receive_objects,
169     'read-ref': read_ref,
170     'update-ref': update_ref,
171     'cat': cat,
172 }
173
174 # FIXME: this protocol is totally lame and not at all future-proof.
175 # (Especially since we abort completely as soon as *anything* bad happens)
176 conn = Conn(sys.stdin, sys.stdout)
177 lr = linereader(conn)
178 for _line in lr:
179     line = _line.strip()
180     if not line:
181         continue
182     debug1('bup server: command: %r\n' % line)
183     words = line.split(' ', 1)
184     cmd = words[0]
185     rest = len(words)>1 and words[1] or ''
186     if cmd == 'quit':
187         break
188     else:
189         cmd = commands.get(cmd)
190         if cmd:
191             cmd(conn, rest)
192         else:
193             raise Exception('unknown server command: %r\n' % line)
194
195 debug1('bup server: done\n')