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