server.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. fd, commit = self.repo.object_store.add_thin_pack()
  63. fd.write(read())
  64. fd.close()
  65. commit()
  66. for oldsha, sha, ref in refs:
  67. if ref == "0" * 40:
  68. self.repo.remove_ref(ref)
  69. else:
  70. self.repo.set_ref(ref, sha)
  71. print "pack applied"
  72. class Handler(object):
  73. """Smart protocol command handler base class."""
  74. def __init__(self, backend, read, write):
  75. self.backend = backend
  76. self.proto = Protocol(read, write)
  77. def capabilities(self):
  78. return " ".join(self.default_capabilities())
  79. class UploadPackHandler(Handler):
  80. """Protocol handler for uploading a pack to the server."""
  81. def default_capabilities(self):
  82. return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
  83. def handle(self):
  84. def determine_wants(heads):
  85. keys = heads.keys()
  86. if keys:
  87. self.proto.write_pkt_line("%s %s\x00%s\n" % ( heads[keys[0]], keys[0], self.capabilities()))
  88. for k in keys[1:]:
  89. self.proto.write_pkt_line("%s %s\n" % (heads[k], k))
  90. # i'm done..
  91. self.proto.write("0000")
  92. # Now client will either send "0000", meaning that it doesnt want to pull.
  93. # or it will start sending want want want commands
  94. want = self.proto.read_pkt_line()
  95. if want == None:
  96. return []
  97. want, self.client_capabilities = extract_capabilities(want)
  98. want_revs = []
  99. while want and want[:4] == 'want':
  100. want_revs.append(want[5:45])
  101. want = self.proto.read_pkt_line()
  102. return want_revs
  103. progress = lambda x: self.proto.write_sideband(2, x)
  104. write = lambda x: self.proto.write_sideband(1, x)
  105. class ProtocolGraphWalker(object):
  106. def __init__(self, proto):
  107. self.proto = proto
  108. self._last_sha = None
  109. def ack(self, have_ref):
  110. self.proto.write_pkt_line("ACK %s continue\n" % have_ref)
  111. def next(self):
  112. have = self.proto.read_pkt_line()
  113. if have[:4] == 'have':
  114. return have[5:45]
  115. #if have[:4] == 'done':
  116. # return None
  117. if self._last_sha:
  118. # Oddness: Git seems to resend the last ACK, without the "continue" statement
  119. self.proto.write_pkt_line("ACK %s\n" % self._last_sha)
  120. # The exchange finishes with a NAK
  121. self.proto.write_pkt_line("NAK\n")
  122. graph_walker = ProtocolGraphWalker(self.proto)
  123. num_objects, objects_iter = self.backend.fetch_objects(determine_wants, graph_walker, progress)
  124. # Do they want any objects?
  125. if num_objects == 0:
  126. return
  127. progress("dul-daemon says what\n")
  128. progress("counting objects: %d, done.\n" % num_objects)
  129. write_pack_data(ProtocolFile(None, write), objects_iter, num_objects)
  130. progress("how was that, then?\n")
  131. # we are done
  132. self.proto.write("0000")
  133. class ReceivePackHandler(Handler):
  134. """Protocol handler for downloading a pack to the client."""
  135. def default_capabilities(self):
  136. return ("report-status", "delete-refs")
  137. def handle(self):
  138. refs = self.backend.get_refs().items()
  139. if refs:
  140. self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
  141. for i in range(1, len(refs)):
  142. ref = refs[i]
  143. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  144. else:
  145. self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
  146. self.proto.write("0000")
  147. client_refs = []
  148. ref = self.proto.read_pkt_line()
  149. # if ref is none then client doesnt want to send us anything..
  150. if ref is None:
  151. return
  152. ref, client_capabilities = extract_capabilities(ref)
  153. # client will now send us a list of (oldsha, newsha, ref)
  154. while ref:
  155. client_refs.append(ref.split())
  156. ref = self.proto.read_pkt_line()
  157. # backend can now deal with this refs and read a pack using self.read
  158. self.backend.apply_pack(client_refs, self.proto.read)
  159. # when we have read all the pack from the client, it assumes
  160. # everything worked OK.
  161. # there is NO ack from the server before it reports victory.
  162. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  163. def handle(self):
  164. proto = Protocol(self.rfile.read, self.wfile.write)
  165. command, args = proto.read_cmd()
  166. # switch case to handle the specific git command
  167. if command == 'git-upload-pack':
  168. cls = UploadPackHandler
  169. elif command == 'git-receive-pack':
  170. cls = ReceivePackHandler
  171. else:
  172. return
  173. h = cls(self.server.backend, self.rfile.read, self.wfile.write)
  174. h.handle()
  175. class TCPGitServer(SocketServer.TCPServer):
  176. allow_reuse_address = True
  177. serve = SocketServer.TCPServer.serve_forever
  178. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  179. self.backend = backend
  180. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)