client.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # server.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  3. # Copyright (C) 2008 John Carr
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # or (at your option) a later version of the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Client side support for the Git protocol."""
  20. __docformat__ = 'restructuredText'
  21. import os
  22. import select
  23. import socket
  24. import subprocess
  25. from dulwich.protocol import (
  26. Protocol,
  27. TCP_GIT_PORT,
  28. extract_capabilities,
  29. )
  30. from dulwich.pack import (
  31. write_pack_data,
  32. )
  33. def _fileno_can_read(fileno):
  34. return len(select.select([fileno], [], [], 0)[0]) > 0
  35. class SimpleFetchGraphWalker(object):
  36. def __init__(self, local_heads, get_parents):
  37. self.heads = set(local_heads)
  38. self.get_parents = get_parents
  39. self.parents = {}
  40. def ack(self, ref):
  41. if ref in self.heads:
  42. self.heads.remove(ref)
  43. if ref in self.parents:
  44. for p in self.parents[ref]:
  45. self.ack(p)
  46. def next(self):
  47. if self.heads:
  48. ret = self.heads.pop()
  49. ps = self.get_parents(ret)
  50. self.parents[ret] = ps
  51. self.heads.update(ps)
  52. return ret
  53. return None
  54. CAPABILITIES = ["multi_ack", "side-band-64k", "ofs-delta"]
  55. class GitClient(object):
  56. """Git smart server client.
  57. """
  58. def __init__(self, can_read, read, write, thin_packs=True):
  59. self.proto = Protocol(read, write)
  60. self._can_read = can_read
  61. self._capabilities = list(CAPABILITIES)
  62. if thin_packs:
  63. self._capabilities.append("thin-pack")
  64. def capabilities(self):
  65. return " ".join(self._capabilities)
  66. def read_refs(self):
  67. server_capabilities = None
  68. refs = {}
  69. # Receive refs from server
  70. for pkt in self.proto.read_pkt_seq():
  71. (sha, ref) = pkt.rstrip("\n").split(" ", 1)
  72. if server_capabilities is None:
  73. (ref, server_capabilities) = extract_capabilities(ref)
  74. refs[ref] = sha
  75. return refs, server_capabilities
  76. def send_pack(self, path, generate_pack_contents):
  77. """Upload a pack to a remote repository.
  78. :param path: Repository path
  79. :param generate_pack_contents: Function that can return the shas of the
  80. objects to upload.
  81. """
  82. refs, server_capabilities = self.read_refs()
  83. changed_refs = [] # FIXME
  84. if not changed_refs:
  85. self.proto.write_pkt_line(None)
  86. return
  87. self.proto.write_pkt_line("%s %s %s\0%s" % (changed_refs[0][0], changed_refs[0][1], changed_refs[0][2], self.capabilities()))
  88. want = []
  89. have = []
  90. for changed_ref in changed_refs[:]:
  91. self.proto.write_pkt_line("%s %s %s" % changed_refs)
  92. want.append(changed_refs[1])
  93. if changed_refs[0] != "0"*40:
  94. have.append(changed_refs[0])
  95. self.proto.write_pkt_line(None)
  96. shas = generate_pack_contents(want, have, None)
  97. write_pack_data(self.write, shas, len(shas))
  98. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  99. """Retrieve a pack from a git smart server.
  100. :param determine_wants: Callback that returns list of commits to fetch
  101. :param graph_walker: Object with next() and ack().
  102. :param pack_data: Callback called for each bit of data in the pack
  103. :param progress: Callback for progress reports (strings)
  104. """
  105. (refs, server_capabilities) = self.read_refs()
  106. wants = determine_wants(refs)
  107. if not wants:
  108. self.proto.write_pkt_line(None)
  109. return
  110. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  111. for want in wants[1:]:
  112. self.proto.write_pkt_line("want %s\n" % want)
  113. self.proto.write_pkt_line(None)
  114. have = graph_walker.next()
  115. while have:
  116. self.proto.write_pkt_line("have %s\n" % have)
  117. if self._can_read():
  118. pkt = self.proto.read_pkt_line()
  119. parts = pkt.rstrip("\n").split(" ")
  120. if parts[0] == "ACK":
  121. graph_walker.ack(parts[1])
  122. assert parts[2] == "continue"
  123. have = graph_walker.next()
  124. self.proto.write_pkt_line("done\n")
  125. pkt = self.proto.read_pkt_line()
  126. while pkt:
  127. parts = pkt.rstrip("\n").split(" ")
  128. if parts[0] == "ACK":
  129. graph_walker.ack(pkt.split(" ")[1])
  130. if len(parts) < 3 or parts[2] != "continue":
  131. break
  132. pkt = self.proto.read_pkt_line()
  133. for pkt in self.proto.read_pkt_seq():
  134. channel = ord(pkt[0])
  135. pkt = pkt[1:]
  136. if channel == 1:
  137. pack_data(pkt)
  138. elif channel == 2:
  139. progress(pkt)
  140. else:
  141. raise AssertionError("Invalid sideband channel %d" % channel)
  142. class TCPGitClient(GitClient):
  143. """A Git Client that works over TCP directly (i.e. git://)."""
  144. def __init__(self, host, port=TCP_GIT_PORT, *args, **kwargs):
  145. self._socket = socket.socket(type=socket.SOCK_STREAM)
  146. self._socket.connect((host, port))
  147. self.rfile = self._socket.makefile('rb', -1)
  148. self.wfile = self._socket.makefile('wb', 0)
  149. self.host = host
  150. super(TCPGitClient, self).__init__(lambda: _fileno_can_read(self._socket.fileno()), self.rfile.read, self.wfile.write, *args, **kwargs)
  151. def send_pack(self, path):
  152. """Send a pack to a remote host.
  153. :param path: Path of the repository on the remote host
  154. """
  155. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  156. super(TCPGitClient, self).send_pack(path)
  157. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  158. """Fetch a pack from the remote host.
  159. :param path: Path of the reposiutory on the remote host
  160. :param determine_wants: Callback that receives available refs dict and
  161. should return list of sha's to fetch.
  162. :param graph_walker: GraphWalker instance used to find missing shas
  163. :param pack_data: Callback for writing pack data
  164. :param progress: Callback for writing progress
  165. """
  166. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  167. super(TCPGitClient, self).fetch_pack(path, determine_wants, graph_walker, pack_data, progress)
  168. class SubprocessGitClient(GitClient):
  169. def __init__(self, *args, **kwargs):
  170. self.proc = None
  171. self._args = args
  172. self._kwargs = kwargs
  173. def _connect(self, service, *args):
  174. argv = [service] + list(args)
  175. self.proc = subprocess.Popen(argv, bufsize=0,
  176. stdin=subprocess.PIPE,
  177. stdout=subprocess.PIPE)
  178. def read_fn(size):
  179. return self.proc.stdout.read(size)
  180. def write_fn(data):
  181. self.proc.stdin.write(data)
  182. self.proc.stdin.flush()
  183. return GitClient(lambda: _fileno_can_read(self.proc.stdout.fileno()), read_fn, write_fn, *args, **kwargs)
  184. def send_pack(self, path):
  185. client = self._connect("git-receive-pack", path)
  186. client.send_pack(path)
  187. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  188. progress):
  189. client = self._connect("git-upload-pack", path)
  190. client.fetch_pack(path, determine_wants, graph_walker, pack_data, progress)
  191. class SSHSubprocess(object):
  192. """A socket-like object that talks to an ssh subprocess via pipes."""
  193. def __init__(self, proc):
  194. self.proc = proc
  195. def send(self, data):
  196. return os.write(self.proc.stdin.fileno(), data)
  197. def recv(self, count):
  198. return self.proc.stdout.read(count)
  199. def close(self):
  200. self.proc.stdin.close()
  201. self.proc.stdout.close()
  202. self.proc.wait()
  203. class SSHVendor(object):
  204. def connect_ssh(self, host, command, username=None, port=None):
  205. #FIXME: This has no way to deal with passwords..
  206. args = ['ssh', '-x']
  207. if port is not None:
  208. args.extend(['-p', str(port)])
  209. if username is not None:
  210. host = "%s@%s" % (username, host)
  211. args.append(host)
  212. proc = subprocess.Popen(args + command,
  213. stdin=subprocess.PIPE,
  214. stdout=subprocess.PIPE)
  215. return SSHSubprocess(proc)
  216. # Can be overridden by users
  217. get_ssh_vendor = SSHVendor
  218. class SSHGitClient(GitClient):
  219. def __init__(self, host, port=None, thin_packs=True):
  220. self.host = host
  221. self.port = port
  222. self._thin_packs = thin_packs
  223. def send_pack(self, path):
  224. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack %s" % path], port=self.port)
  225. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, thin_packs=self._thin_packs)
  226. client.send_pack(path)
  227. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  228. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack %s" % path], port=self.port)
  229. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, thin_packs=self._thin_packs)
  230. client.fetch_pack(path, determine_wants, graph_walker, pack_data, progress)