server.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. 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 PackData, Pack, write_pack_data
  22. import os, sha, tempfile
  23. class Backend(object):
  24. def get_refs(self):
  25. """
  26. Get all the refs in the repository
  27. :return: list of tuple(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_waker, 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. def get_refs(self):
  50. refs = []
  51. if self.repo.head():
  52. refs.append(('HEAD', self.repo.head()))
  53. for ref, sha in self.repo.heads().items():
  54. refs.append(('refs/heads/'+ref,sha))
  55. return refs
  56. def apply_pack(self, refs, read):
  57. # store the incoming pack in the repository
  58. fd, name = tempfile.mkstemp(suffix='.pack', prefix='pack-', dir=self.repo.pack_dir())
  59. os.write(fd, read())
  60. os.close(fd)
  61. # strip '.pack' off our filename
  62. basename = name[:-5]
  63. # generate an index for it
  64. pd = PackData(name)
  65. pd.create_index_v2(basename+".idx")
  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. def __init__(self, backend, read, write):
  74. self.backend = backend
  75. self.proto = Protocol(read, write)
  76. def capabilities(self):
  77. return " ".join(self.default_capabilities())
  78. class UploadPackHandler(Handler):
  79. def default_capabilities(self):
  80. return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
  81. def handle(self):
  82. def determine_wants(heads):
  83. keys = heads.keys()
  84. if keys:
  85. self.proto.write_pkt_line("%s %s\x00%s\n" % (keys[0], heads[keys[0]], self.capabilities()))
  86. for k in keys[1:]:
  87. self.proto.write_pkt_line("%s %s\n" % (k, heads[k]))
  88. # i'm done..
  89. self.proto.write("0000")
  90. # Now client will either send "0000", meaning that it doesnt want to pull.
  91. # or it will start sending want want want commands
  92. want = self.proto.read_pkt_line()
  93. if want == None:
  94. return []
  95. want, self.client_capabilities = extract_capabilities(want)
  96. want_revs = []
  97. while want and want[:4] == 'want':
  98. want_rev = want[5:45]
  99. # FIXME: This check probably isnt needed?
  100. want_revs.append(want_rev)
  101. want = self.proto.read_pkt_line()
  102. return want_revs
  103. progress = lambda x: self.proto.write_sideband(2, x)
  104. class ProtocolGraphWalker(object):
  105. def __init__(self):
  106. self._last_sha = None
  107. def ack(self, have_ref):
  108. self.proto.write_pkt_line("ACK %s continue\n" % have_ref)
  109. def next(self):
  110. have = self.proto.read_pkt_line()
  111. if have[:4] == 'have':
  112. return have[5:45]
  113. if have[:4] == 'done':
  114. return None
  115. if self._last_sha:
  116. # Oddness: Git seems to resend the last ACK, without the "continue" statement
  117. self.proto.write_pkt_line("ACK %s\n" % self._last_sha)
  118. # The exchange finishes with a NAK
  119. self.proto.write_pkt_line("NAK\n")
  120. objects = list(self.backend.fetch_objects(determine_wants, graph_walker, progress))
  121. progress("dul-daemon says what\n")
  122. progress("counting objects: %d, done.\n" % len(objects))
  123. write_pack_data(ProtocolFile(None, write), objects, len(objects))
  124. progress("how was that, then?\n")
  125. # we are done
  126. self.proto.write("0000")
  127. class ReceivePackHandler(Handler):
  128. def default_capabilities(self):
  129. return ("report-status", "delete-refs")
  130. def handle(self):
  131. refs = self.backend.get_refs()
  132. if refs:
  133. self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
  134. for i in range(1, len(refs)):
  135. ref = refs[i]
  136. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  137. else:
  138. self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
  139. self.proto.write("0000")
  140. client_refs = []
  141. ref = self.proto.read_pkt_line()
  142. # if ref is none then client doesnt want to send us anything..
  143. if ref is None:
  144. return
  145. ref, client_capabilities = extract_capabilities(ref)
  146. # client will now send us a list of (oldsha, newsha, ref)
  147. while ref:
  148. client_refs.append(ref.split())
  149. ref = self.proto.read_pkt_line()
  150. # backend can now deal with this refs and read a pack using self.read
  151. self.backend.apply_pack(client_refs, self.proto.read)
  152. # when we have read all the pack from the client, it assumes everything worked OK
  153. # there is NO ack from the server before it reports victory.
  154. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  155. def handle(self):
  156. proto = Protocol(self.rfile.read, self.wfile.write)
  157. command, args = proto.read_cmd()
  158. # switch case to handle the specific git command
  159. if command == 'git-upload-pack':
  160. cls = UploadPackHandler
  161. elif command == 'git-receive-pack':
  162. cls = ReceivePackHandler
  163. else:
  164. return
  165. h = cls(self.server.backend, self.rfile.read, self.wfile.write)
  166. h.handle()
  167. class TCPGitServer(SocketServer.TCPServer):
  168. allow_reuse_address = True
  169. serve = SocketServer.TCPServer.serve_forever
  170. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  171. self.backend = backend
  172. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)