server.py 7.3 KB

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