merge john.
[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, generate_pack_contents
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: dict of name -> sha
32         """
33         raise NotImplementedError
34
35     def apply_pack(self, refs, read):
36         """ Import a set of changes into a repository and update the refs
37
38         :param refs: list of tuple(name, sha)
39         :param read: callback to read from the incoming pack
40         """
41         raise NotImplementedError
42
43     def fetch_objects(self, determine_wants, graph_walker, progress):
44         """
45         Yield the objects required for a list of commits.
46
47         :param progress: is a callback to send progress messages to the client
48         """
49         raise NotImplementedError
50
51
52 class GitBackend(Backend):
53
54     def __init__(self, gitdir=None):
55         self.gitdir = gitdir
56
57         if not self.gitdir:
58             self.gitdir = tempfile.mkdtemp()
59             Repo.create(self.gitdir)
60
61         self.repo = Repo(self.gitdir)
62
63     def get_refs(self):
64         return self.repo.get_refs()
65
66     def apply_pack(self, refs, read):
67         # store the incoming pack in the repository
68         fd, name = tempfile.mkstemp(suffix='.pack', prefix='pack-', dir=self.repo.pack_dir())
69         os.write(fd, read())
70         os.close(fd)
71
72         # strip '.pack' off our filename
73         basename = name[:-5]
74
75         # generate an index for it
76         pd = PackData(name)
77         pd.create_index_v2(basename+".idx")
78
79         for oldsha, sha, ref in refs:
80             if ref == "0" * 40:
81                 self.repo.remove_ref(ref)
82             else:
83                 self.repo.set_ref(ref, sha)
84
85         print "pack applied"
86
87     def fetch_objects(self, determine_wants, graph_walker, progress):
88         shas = self.repo.find_missing_objects(determine_wants, graph_walker, progress)
89         for sha in shas:
90             yield self.repo.get_object(sha)
91
92
93 class Handler(object):
94
95     def __init__(self, backend, read, write):
96         self.backend = backend
97         self.proto = Protocol(read, write)
98
99     def capabilities(self):
100         return " ".join(self.default_capabilities())
101
102
103 class UploadPackHandler(Handler):
104
105     def default_capabilities(self):
106         return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
107
108     def handle(self):
109         def determine_wants(heads):
110             keys = heads.keys()
111             if keys:
112                 self.proto.write_pkt_line("%s %s\x00%s\n" % ( heads[keys[0]], keys[0], self.capabilities()))
113                 for k in keys[1:]:
114                     self.proto.write_pkt_line("%s %s\n" % (heads[k], k))
115
116             # i'm done..
117             self.proto.write("0000")
118
119             # Now client will either send "0000", meaning that it doesnt want to pull.
120             # or it will start sending want want want commands
121             want = self.proto.read_pkt_line()
122             if want == None:
123                 return []
124
125             want, self.client_capabilities = extract_capabilities(want)
126
127             want_revs = []
128             while want and want[:4] == 'want':
129                 want_revs.append(want[5:45])
130                 want = self.proto.read_pkt_line()
131             return want_revs
132
133         progress = lambda x: self.proto.write_sideband(2, x)
134         write = lambda x: self.proto.write_sideband(1, x)
135
136         class ProtocolGraphWalker(object):
137
138             def __init__(self, proto):
139                 self.proto = proto
140                 self._last_sha = None
141
142             def ack(self, have_ref):
143                 self.proto.write_pkt_line("ACK %s continue\n" % have_ref)
144
145             def next(self):
146                 have = self.proto.read_pkt_line()
147                 if have[:4] == 'have':
148                     return have[5:45]
149
150                 #if have[:4] == 'done':
151                 #    return None
152
153                 if self._last_sha:
154                     # Oddness: Git seems to resend the last ACK, without the "continue" statement
155                     self.proto.write_pkt_line("ACK %s\n" % self._last_sha)
156
157                 # The exchange finishes with a NAK
158                 self.proto.write_pkt_line("NAK\n")
159
160         graph_walker = ProtocolGraphWalker(self.proto)
161         objects = list(self.backend.fetch_objects(determine_wants, graph_walker, progress))
162         progress("dul-daemon says what\n")
163         progress("counting objects: %d, done.\n" % len(objects))
164         write_pack_data(ProtocolFile(None, write), objects, len(objects))
165         progress("how was that, then?\n")
166         # we are done
167         self.proto.write("0000")
168
169
170 class ReceivePackHandler(Handler):
171
172     def default_capabilities(self):
173         return ("report-status", "delete-refs")
174
175     def handle(self):
176         refs = self.backend.get_refs().items()
177
178         if refs:
179             self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
180             for i in range(1, len(refs)):
181                 ref = refs[i]
182                 self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
183         else:
184             self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
185
186         self.proto.write("0000")
187
188         client_refs = []
189         ref = self.proto.read_pkt_line()
190
191         # if ref is none then client doesnt want to send us anything..
192         if ref is None:
193             return
194
195         ref, client_capabilities = extract_capabilities(ref)
196
197         # client will now send us a list of (oldsha, newsha, ref)
198         while ref:
199             client_refs.append(ref.split())
200             ref = self.proto.read_pkt_line()
201
202         # backend can now deal with this refs and read a pack using self.read
203         self.backend.apply_pack(client_refs, self.proto.read)
204
205         # when we have read all the pack from the client, it assumes everything worked OK
206         # there is NO ack from the server before it reports victory.
207
208
209 class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
210
211     def handle(self):
212         proto = Protocol(self.rfile.read, self.wfile.write)
213         command, args = proto.read_cmd()
214
215         # switch case to handle the specific git command
216         if command == 'git-upload-pack':
217             cls = UploadPackHandler
218         elif command == 'git-receive-pack':
219             cls = ReceivePackHandler
220         else:
221             return
222
223         h = cls(self.server.backend, self.rfile.read, self.wfile.write)
224         h.handle()
225
226
227 class TCPGitServer(SocketServer.TCPServer):
228
229     allow_reuse_address = True
230     serve = SocketServer.TCPServer.serve_forever
231
232     def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
233         self.backend = backend
234         SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)
235
236