server.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. # or (at your option) any later version 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. """Git smart network protocol server implementation."""
  19. import SocketServer
  20. import tempfile
  21. from dulwich.protocol import (
  22. Protocol,
  23. ProtocolFile,
  24. TCP_GIT_PORT,
  25. extract_capabilities,
  26. )
  27. from dulwich.repo import (
  28. Repo,
  29. )
  30. from dulwich.pack import (
  31. write_pack_data,
  32. )
  33. class Backend(object):
  34. def get_refs(self):
  35. """
  36. Get all the refs in the repository
  37. :return: dict of name -> sha
  38. """
  39. raise NotImplementedError
  40. def apply_pack(self, refs, read):
  41. """ Import a set of changes into a repository and update the refs
  42. :param refs: list of tuple(name, sha)
  43. :param read: callback to read from the incoming pack
  44. """
  45. raise NotImplementedError
  46. def fetch_objects(self, determine_wants, graph_walker, progress):
  47. """
  48. Yield the objects required for a list of commits.
  49. :param progress: is a callback to send progress messages to the client
  50. """
  51. raise NotImplementedError
  52. class GitBackend(Backend):
  53. def __init__(self, gitdir=None):
  54. self.gitdir = gitdir
  55. if not self.gitdir:
  56. self.gitdir = tempfile.mkdtemp()
  57. Repo.create(self.gitdir)
  58. self.repo = Repo(self.gitdir)
  59. self.fetch_objects = self.repo.fetch_objects
  60. self.get_refs = self.repo.get_refs
  61. def apply_pack(self, refs, read):
  62. f, commit = self.repo.object_store.add_thin_pack()
  63. try:
  64. f.write(read())
  65. finally:
  66. commit()
  67. for oldsha, sha, ref in refs:
  68. if ref == "0" * 40:
  69. del self.repo.refs[ref]
  70. else:
  71. self.repo.refs[ref] = sha
  72. print "pack applied"
  73. class Handler(object):
  74. """Smart protocol command handler base class."""
  75. def __init__(self, backend, read, write):
  76. self.backend = backend
  77. self.proto = Protocol(read, write)
  78. def capabilities(self):
  79. return " ".join(self.default_capabilities())
  80. class UploadPackHandler(Handler):
  81. """Protocol handler for uploading a pack to the server."""
  82. def default_capabilities(self):
  83. return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
  84. def handle(self):
  85. def determine_wants(heads):
  86. keys = heads.keys()
  87. if keys:
  88. self.proto.write_pkt_line("%s %s\x00%s\n" % ( heads[keys[0]], keys[0], self.capabilities()))
  89. for k in keys[1:]:
  90. self.proto.write_pkt_line("%s %s\n" % (heads[k], k))
  91. # i'm done..
  92. self.proto.write("0000")
  93. # Now client will either send "0000", meaning that it doesnt want to pull.
  94. # or it will start sending want want want commands
  95. want = self.proto.read_pkt_line()
  96. if want == None:
  97. return []
  98. want, self.client_capabilities = extract_capabilities(want)
  99. want_revs = []
  100. while want and want[:4] == 'want':
  101. want_revs.append(want[5:45])
  102. want = self.proto.read_pkt_line()
  103. if want == None:
  104. self.proto.write_pkt_line("ACK %s\n" % want_revs[-1])
  105. return want_revs
  106. progress = lambda x: self.proto.write_sideband(2, x)
  107. write = lambda x: self.proto.write_sideband(1, x)
  108. class ProtocolGraphWalker(object):
  109. def __init__(self, proto):
  110. self.proto = proto
  111. self._last_sha = None
  112. self._cached = False
  113. self._cache = []
  114. self._cache_index = 0
  115. def ack(self, have_ref):
  116. self.proto.write_pkt_line("ACK %s continue\n" % have_ref)
  117. def reset(self):
  118. self._cached = True
  119. self._cache_index = 0
  120. def next(self):
  121. if not self._cached:
  122. return self.next_from_proto()
  123. self._cache_index = self._cache_index + 1
  124. if self._cache_index > len(self._cache):
  125. return None
  126. return self._cache[self._cache_index]
  127. def next_from_proto(self):
  128. have = self.proto.read_pkt_line()
  129. if have is None:
  130. self.proto.write_pkt_line("ACK %s\n" % self._last_sha)
  131. return None
  132. if have[:4] == 'have':
  133. self._cache.append(have[5:45])
  134. return have[5:45]
  135. #if have[:4] == 'done':
  136. # return None
  137. if self._last_sha:
  138. # Oddness: Git seems to resend the last ACK, without the "continue" statement
  139. self.proto.write_pkt_line("ACK %s\n" % self._last_sha)
  140. # The exchange finishes with a NAK
  141. self.proto.write_pkt_line("NAK\n")
  142. graph_walker = ProtocolGraphWalker(self.proto)
  143. objects_iter = self.backend.fetch_objects(determine_wants, graph_walker, progress)
  144. # Do they want any objects?
  145. if len(objects_iter) == 0:
  146. return
  147. progress("dul-daemon says what\n")
  148. progress("counting objects: %d, done.\n" % len(objects_iter))
  149. write_pack_data(ProtocolFile(None, write), objects_iter,
  150. len(objects_iter))
  151. progress("how was that, then?\n")
  152. # we are done
  153. self.proto.write("0000")
  154. class ReceivePackHandler(Handler):
  155. """Protocol handler for downloading a pack to the client."""
  156. def default_capabilities(self):
  157. return ("report-status", "delete-refs")
  158. def handle(self):
  159. refs = self.backend.get_refs().items()
  160. if refs:
  161. self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
  162. for i in range(1, len(refs)):
  163. ref = refs[i]
  164. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  165. else:
  166. self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
  167. self.proto.write("0000")
  168. client_refs = []
  169. ref = self.proto.read_pkt_line()
  170. # if ref is none then client doesnt want to send us anything..
  171. if ref is None:
  172. return
  173. ref, client_capabilities = extract_capabilities(ref)
  174. # client will now send us a list of (oldsha, newsha, ref)
  175. while ref:
  176. client_refs.append(ref.split())
  177. ref = self.proto.read_pkt_line()
  178. # backend can now deal with this refs and read a pack using self.read
  179. self.backend.apply_pack(client_refs, self.proto.read)
  180. # when we have read all the pack from the client, it assumes
  181. # everything worked OK.
  182. # there is NO ack from the server before it reports victory.
  183. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  184. def handle(self):
  185. proto = Protocol(self.rfile.read, self.wfile.write)
  186. command, args = proto.read_cmd()
  187. # switch case to handle the specific git command
  188. if command == 'git-upload-pack':
  189. cls = UploadPackHandler
  190. elif command == 'git-receive-pack':
  191. cls = ReceivePackHandler
  192. else:
  193. return
  194. h = cls(self.server.backend, self.rfile.read, self.wfile.write)
  195. h.handle()
  196. class TCPGitServer(SocketServer.TCPServer):
  197. allow_reuse_address = True
  198. serve = SocketServer.TCPServer.serve_forever
  199. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  200. self.backend = backend
  201. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)