c90f6fac8e8143efb83b55880650f80218ca6cca
[jelmer/dulwich-libgit2.git] / dulwich / server.py
1 # server.py -- Implementation of the server side git protocols
2 # Copryight (C) 2008 John Carr <john.carr@unrouted.co.uk>
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; version 2
7 # of the License.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
17 # MA  02110-1301, USA.
18
19 import SocketServer
20 from dulwich.protocol import Protocol, ProtocolFile, TCP_GIT_PORT, extract_capabilities
21 from dulwich.repo import Repo
22 from dulwich.pack import PackData, Pack, write_pack_data
23 import os, sha, tempfile
24
25 class Backend(object):
26
27     def get_refs(self):
28         """
29         Get all the refs in the repository
30
31         :return: list of tuple(name, sha)
32         """
33         raise NotImplementedError
34
35     def has_revision(self, sha):
36         """
37         Is a given sha in this repository?
38
39         :return: True or False
40         """
41         raise NotImplementedError
42
43     def apply_pack(self, refs, read):
44         """ Import a set of changes into a repository and update the refs
45
46         :param refs: list of tuple(name, sha)
47         :param read: callback to read from the incoming pack
48         """
49         raise NotImplementedError
50
51     def generate_pack(self, want, have, write, progress):
52         """
53         Generate a pack containing all commits a client is missing
54
55         :param want: is a list of sha's the client desires
56         :param have: is a list of sha's the client has (allowing us to send the minimal pack)
57         :param write: is a callback to write pack data to the client
58         :param progress: is a callback to send progress messages to the client
59         """
60         raise NotImplementedError
61
62
63 class GitBackend(Backend):
64
65     def __init__(self, gitdir=None):
66         self.gitdir = gitdir
67
68         if not self.gitdir:
69             self.gitdir = tempfile.mkdtemp()
70             Repo.create(self.gitdir)
71
72         self.repo = Repo(self.gitdir)
73
74     def get_refs(self):
75         refs = []
76         if self.repo.head():
77             refs.append(('HEAD', self.repo.head()))
78         for ref, sha in self.repo.heads().items():
79             refs.append(('refs/heads/'+ref,sha))
80         return refs
81
82     def has_revision(self, sha):
83         return self.repo.get_object(sha) != None
84
85     def apply_pack(self, refs, read):
86         # store the incoming pack in the repository
87         fd, name = tempfile.mkstemp(suffix='.pack', prefix='pack-', dir=self.repo.pack_dir())
88         os.write(fd, read())
89         os.close(fd)
90
91         # strip '.pack' off our filename
92         basename = name[:-5]
93
94         # generate an index for it
95         pd = PackData(name)
96         pd.create_index_v2(basename+".idx")
97
98         for oldsha, sha, ref in refs:
99             if ref == "0" * 40:
100                 self.repo.remove_ref(ref)
101             else:
102                 self.repo.set_ref(ref, sha)
103
104         print "pack applied"
105
106     def generate_pack(self, want, have, write, progress):
107         progress("dul-daemon says what\n")
108
109         sha_queue = []
110
111         commits_to_send = want[:]
112         for sha in commits_to_send:
113             if sha in sha_queue:
114                 continue
115
116             sha_queue.append(sha)
117
118             c = self.repo.commit(sha)
119             for p in c.parents:
120                 if not p in commits_to_send:
121                     commits_to_send.append(p)
122
123             def parse_tree(tree, sha_queue):
124                 for mode, name, x in tree.entries():
125                     if not x in sha_queue:
126                         try:
127                             t = self.repo.tree(x)
128                             sha_queue.append(x)
129                             parse_tree(t, sha_queue)
130                         except:
131                             sha_queue.append(x)
132
133             treesha = c.tree
134             if treesha not in sha_queue:
135                 sha_queue.append(treesha)
136                 t = self.repo.tree(treesha)
137                 parse_tree(t, sha_queue)
138
139             progress("counting objects: %d\r" % len(sha_queue))
140
141         progress("counting objects: %d, done.\n" % len(sha_queue))
142
143         write_pack_data(ProtocolFile(None, write), (self.repo.get_object(sha) for sha in sha_queue), len(sha_queue))
144
145         progress("how was that, then?\n")
146
147
148 class Handler(object):
149
150     def __init__(self, backend, read, write):
151         self.backend = backend
152         self.proto = Protocol(read, write)
153
154     def capabilities(self):
155         return " ".join(self.default_capabilities())
156
157
158 class UploadPackHandler(Handler):
159
160     def default_capabilities(self):
161         return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
162
163     def handle(self):
164         refs = self.backend.get_refs()
165
166         if refs:
167             self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
168             for i in range(1, len(refs)):
169                 ref = refs[i]
170                 self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
171
172         # i'm done..
173         self.proto.write("0000")
174
175         # Now client will either send "0000", meaning that it doesnt want to pull.
176         # or it will start sending want want want commands
177         want = self.proto.read_pkt_line()
178         if want == None:
179             return
180
181         want, client_capabilities = extract_capabilities(want)
182
183         # Keep reading the list of demands until we hit another "0000" 
184         want_revs = []
185         while want and want[:4] == 'want':
186             want_rev = want[5:45]
187             # FIXME: This check probably isnt needed?
188             if self.backend.has_revision(want_rev):
189                want_revs.append(want_rev)
190             want = self.proto.read_pkt_line()
191         
192         # Client will now tell us which commits it already has - if we have them we ACK them
193         # this allows client to stop looking at that commits parents (main reason why git pull is fast)
194         last_sha = None
195         have_revs = []
196         have = self.proto.read_pkt_line()
197         while have and have[:4] == 'have':
198             have_ref = have[5:45]
199             if self.backend.has_revision(have_ref):
200                 self.proto.write_pkt_line("ACK %s continue\n" % have_ref)
201                 last_sha = have_ref
202                 have_revs.append(have_ref)
203             have = self.proto.read_pkt_line()
204
205         # At some point client will stop sending commits and will tell us it is done
206         assert(have[:4] == "done")
207
208         # Oddness: Git seems to resend the last ACK, without the "continue" statement
209         if last_sha:
210             self.proto.write_pkt_line("ACK %s\n" % last_sha)
211
212         # The exchange finishes with a NAK
213         self.proto.write_pkt_line("NAK\n")
214       
215         self.backend.generate_pack(want_revs, have_revs, lambda x: self.proto.write_sideband(1, x), lambda x: self.proto.write_sideband(2, x))
216
217         # we are done
218         self.proto.write("0000")
219
220
221 class ReceivePackHandler(Handler):
222
223     def default_capabilities(self):
224         return ("report-status", "delete-refs")
225
226     def handle(self):
227         refs = self.backend.get_refs()
228
229         if refs:
230             self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
231             for i in range(1, len(refs)):
232                 ref = refs[i]
233                 self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
234         else:
235             self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
236
237         self.proto.write("0000")
238
239         client_refs = []
240         ref = self.proto.read_pkt_line()
241
242         # if ref is none then client doesnt want to send us anything..
243         if ref is None:
244             return
245
246         ref, client_capabilities = extract_capabilities(ref)
247
248         # client will now send us a list of (oldsha, newsha, ref)
249         while ref:
250             client_refs.append(ref.split())
251             ref = self.proto.read_pkt_line()
252
253         # backend can now deal with this refs and read a pack using self.read
254         self.backend.apply_pack(client_refs, self.proto.read)
255
256         # when we have read all the pack from the client, it assumes everything worked OK
257         # there is NO ack from the server before it reports victory.
258
259
260 class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
261
262     def handle(self):
263         proto = Protocol(self.rfile.read, self.wfile.write)
264         command, args = proto.read_cmd()
265
266         # switch case to handle the specific git command
267         if command == 'git-upload-pack':
268             cls = UploadPackHandler
269         elif command == 'git-receive-pack':
270             cls = ReceivePackHandler
271         else:
272             return
273
274         h = cls(self.server.backend, self.rfile.read, self.wfile.write)
275         h.handle()
276
277
278 class TCPGitServer(SocketServer.TCPServer):
279
280     allow_reuse_address = True
281     serve = SocketServer.TCPServer.serve_forever
282
283     def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
284         self.backend = backend
285         SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)
286
287