2
0

client.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # server.py -- Implementation of the server side git protocols
  2. # Copryight (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  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; either version 2
  7. # or (at your option) a 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 os
  19. import select
  20. import socket
  21. import subprocess
  22. from dulwich.protocol import Protocol, TCP_GIT_PORT, extract_capabilities
  23. from dulwich.pack import write_pack_data
  24. class SimpleFetchGraphWalker(object):
  25. def __init__(self, local_heads, get_parents):
  26. self.heads = set(local_heads)
  27. self.get_parents = get_parents
  28. self.parents = {}
  29. def ack(self, ref):
  30. if ref in self.heads:
  31. self.heads.remove(ref)
  32. if ref in self.parents:
  33. for p in self.parents[ref]:
  34. self.ack(p)
  35. def next(self):
  36. if self.heads:
  37. ret = self.heads.pop()
  38. ps = self.get_parents(ret)
  39. self.parents[ret] = ps
  40. self.heads.update(ps)
  41. return ret
  42. return None
  43. DEFAULT_CAPABILITIES = ["multi_ack", "side-band-64k", "thin-pack", "ofs-delta"]
  44. class GitClient(object):
  45. """Git smart server client.
  46. """
  47. def __init__(self, fileno, read, write, capabilities=None):
  48. self.proto = Protocol(read, write)
  49. self.fileno = fileno
  50. if capabilities is None:
  51. self.capabilities = DEFAULT_CAPABILITIES
  52. else:
  53. self.capabilities = capabilities
  54. def capabilities(self):
  55. return " ".join(self.capabilities)
  56. def read_refs(self):
  57. server_capabilities = None
  58. refs = {}
  59. # Receive refs from server
  60. for pkt in self.proto.read_pkt_seq():
  61. (sha, ref) = pkt.rstrip("\n").split(" ", 1)
  62. if server_capabilities is None:
  63. (ref, server_capabilities) = extract_capabilities(ref)
  64. if not (ref == "capabilities^{}" and sha == "0" * 40):
  65. refs[ref] = sha
  66. return refs, server_capabilities
  67. def send_pack(self, path, generate_pack_contents):
  68. refs, server_capabilities = self.read_refs()
  69. changed_refs = [] # FIXME
  70. if not changed_refs:
  71. self.proto.write_pkt_line(None)
  72. return
  73. self.proto.write_pkt_line("%s %s %s\0%s" % (changed_refs[0][0], changed_refs[0][1], changed_refs[0][2], self.capabilities()))
  74. want = []
  75. have = []
  76. for changed_ref in changed_refs[:]:
  77. self.proto.write_pkt_line("%s %s %s" % changed_refs)
  78. want.append(changed_refs[1])
  79. if changed_refs[0] != "0"*40:
  80. have.append(changed_refs[0])
  81. self.proto.write_pkt_line(None)
  82. shas = generate_pack_contents(want, have, None)
  83. write_pack_data(self.write, shas, len(shas))
  84. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  85. """Retrieve a pack from a git smart server.
  86. :param determine_wants: Callback that returns list of commits to fetch
  87. :param graph_walker: Object with next() and ack().
  88. :param pack_data: Callback called for each bit of data in the pack
  89. :param progress: Callback for progress reports (strings)
  90. """
  91. (refs, server_capabilities) = self.read_refs()
  92. wants = determine_wants(refs)
  93. if not wants:
  94. self.proto.write_pkt_line(None)
  95. return
  96. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  97. for want in wants[1:]:
  98. self.proto.write_pkt_line("want %s\n" % want)
  99. self.proto.write_pkt_line(None)
  100. have = graph_walker.next()
  101. while have:
  102. self.proto.write_pkt_line("have %s\n" % have)
  103. if len(select.select([self.fileno], [], [], 0)[0]) > 0:
  104. pkt = self.proto.read_pkt_line()
  105. parts = pkt.rstrip("\n").split(" ")
  106. if parts[0] == "ACK":
  107. graph_walker.ack(parts[1])
  108. assert parts[2] == "continue"
  109. have = graph_walker.next()
  110. self.proto.write_pkt_line("done\n")
  111. pkt = self.proto.read_pkt_line()
  112. while pkt:
  113. parts = pkt.rstrip("\n").split(" ")
  114. if parts[0] == "ACK":
  115. graph_walker.ack(pkt.split(" ")[1])
  116. if len(parts) < 3 or parts[2] != "continue":
  117. break
  118. pkt = self.proto.read_pkt_line()
  119. for pkt in self.proto.read_pkt_seq():
  120. channel = ord(pkt[0])
  121. pkt = pkt[1:]
  122. if channel == 1:
  123. pack_data(pkt)
  124. elif channel == 2:
  125. progress(pkt)
  126. else:
  127. raise AssertionError("Invalid sideband channel %d" % channel)
  128. class TCPGitClient(GitClient):
  129. def __init__(self, host, port=TCP_GIT_PORT, capabilities=None):
  130. self._socket = socket.socket(type=socket.SOCK_STREAM)
  131. self._socket.connect((host, port))
  132. self.rfile = self._socket.makefile('rb', -1)
  133. self.wfile = self._socket.makefile('wb', 0)
  134. self.host = host
  135. super(TCPGitClient, self).__init__(self._socket.fileno(), self.rfile.read, self.wfile.write, capabilities=capabilities)
  136. def send_pack(self, path):
  137. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  138. super(TCPGitClient, self).send_pack(path)
  139. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  140. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  141. super(TCPGitClient, self).fetch_pack(path, determine_wants, graph_walker, pack_data, progress)
  142. class SubprocessGitClient(GitClient):
  143. def __init__(self, capabilities=None):
  144. self.proc = None
  145. self.capabilities = capabilities
  146. def _connect(self, service, *args):
  147. argv = [service] + list(args)
  148. self.proc = subprocess.Popen(argv, bufsize=0,
  149. stdin=subprocess.PIPE,
  150. stdout=subprocess.PIPE)
  151. def read_fn(size):
  152. return self.proc.stdout.read(size)
  153. def write_fn(data):
  154. self.proc.stdin.write(data)
  155. self.proc.stdin.flush()
  156. return GitClient(self.proc.stdout.fileno(), read_fn, write_fn, capabilities=self.capabilities)
  157. def send_pack(self, path):
  158. client = self._connect("git-receive-pack", path)
  159. client.send_pack(path)
  160. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  161. client = self._connect("git-upload-pack", path)
  162. client.fetch_pack(path, determine_wants, graph_walker, pack_data, progress)
  163. class SSHSubprocess(object):
  164. """A socket-like object that talks to an ssh subprocess via pipes."""
  165. def __init__(self, proc):
  166. self.proc = proc
  167. def send(self, data):
  168. return os.write(self.proc.stdin.fileno(), data)
  169. def recv(self, count):
  170. return self.proc.stdout.read(count)
  171. def close(self):
  172. self.proc.stdin.close()
  173. self.proc.stdout.close()
  174. self.proc.wait()
  175. class SSHVendor(object):
  176. def connect_ssh(self, host, command, username=None, port=None):
  177. #FIXME: This has no way to deal with passwords..
  178. args = ['ssh', '-x']
  179. if port is not None:
  180. args.extend(['-p', str(port)])
  181. if username is not None:
  182. host = "%s@%s" % (username, host)
  183. args.append(host)
  184. proc = subprocess.Popen(args + command,
  185. stdin=subprocess.PIPE,
  186. stdout=subprocess.PIPE)
  187. return SSHSubprocess(proc)
  188. # Can be overridden by users
  189. get_ssh_vendor = SSHVendor
  190. class SSHGitClient(GitClient):
  191. def __init__(self, host, port=None):
  192. self.host = host
  193. self.port = port
  194. def send_pack(self, path):
  195. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack %s" % path], port=self.port)
  196. client = GitClient(remote.proc.stdout.fileno(), remote.recv, remote.send)
  197. client.send_pack(path)
  198. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  199. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack %s" % path], port=self.port)
  200. client = GitClient(remote.proc.stdout.fileno(), remote.recv, remote.send)
  201. client.fetch_pack(path, determine_wants, graph_walker, pack_data, progress)