server.py 7.2 KB

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