client.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # client.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008-2009 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. report_activity=None):
  60. """Create a new GitClient instance.
  61. :param can_read: Function that returns True if there is data available
  62. to be read.
  63. :param read: Callback for reading data, takes number of bytes to read
  64. :param write: Callback for writing data
  65. :param thin_packs: Whether or not thin packs should be retrieved
  66. :param report_activity: Optional callback for reporting transport
  67. activity.
  68. """
  69. self.proto = Protocol(read, write, report_activity)
  70. self._can_read = can_read
  71. self._capabilities = list(CAPABILITIES)
  72. if thin_packs:
  73. self._capabilities.append("thin-pack")
  74. def capabilities(self):
  75. return " ".join(self._capabilities)
  76. def read_refs(self):
  77. server_capabilities = None
  78. refs = {}
  79. # Receive refs from server
  80. for pkt in self.proto.read_pkt_seq():
  81. (sha, ref) = pkt.rstrip("\n").split(" ", 1)
  82. if server_capabilities is None:
  83. (ref, server_capabilities) = extract_capabilities(ref)
  84. refs[ref] = sha
  85. return refs, server_capabilities
  86. def send_pack(self, path, get_changed_refs, generate_pack_contents):
  87. """Upload a pack to a remote repository.
  88. :param path: Repository path
  89. :param generate_pack_contents: Function that can return the shas of the
  90. objects to upload.
  91. """
  92. refs, server_capabilities = self.read_refs()
  93. changed_refs = get_changed_refs(refs)
  94. if not changed_refs:
  95. self.proto.write_pkt_line(None)
  96. return {}
  97. want = []
  98. have = []
  99. sent_capabilities = False
  100. for changed_ref, (old_sha1, new_sha1) in changed_refs.iteritems():
  101. if old_sha1 is None:
  102. old_sha1 = "0" * 40
  103. if sent_capabilities:
  104. self.proto.write_pkt_line("%s %s %s" % (old_sha1, new_sha1, changed_ref))
  105. else:
  106. self.proto.write_pkt_line("%s %s %s\0%s" % (old_sha1, new_sha1, changed_ref, self.capabilities()))
  107. sent_capabilities = True
  108. want.append(new_sha1)
  109. if old_sha1 != "0"*40:
  110. have.append(old_sha1)
  111. self.proto.write_pkt_line(None)
  112. shas = generate_pack_contents(want, have)
  113. (entries, sha) = write_pack_data(self.proto, shas, len(shas))
  114. self.proto.write(sha)
  115. # read the final confirmation sha
  116. sha = self.proto.read(20)
  117. if sha:
  118. pass # FIXME: Check that this sha is valid
  119. return changed_refs
  120. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  121. progress):
  122. """Retrieve a pack from a git smart server.
  123. :param determine_wants: Callback that returns list of commits to fetch
  124. :param graph_walker: Object with next() and ack().
  125. :param pack_data: Callback called for each bit of data in the pack
  126. :param progress: Callback for progress reports (strings)
  127. """
  128. (refs, server_capabilities) = self.read_refs()
  129. wants = determine_wants(refs)
  130. if not wants:
  131. self.proto.write_pkt_line(None)
  132. return
  133. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  134. for want in wants[1:]:
  135. self.proto.write_pkt_line("want %s\n" % want)
  136. self.proto.write_pkt_line(None)
  137. have = graph_walker.next()
  138. while have:
  139. self.proto.write_pkt_line("have %s\n" % have)
  140. if self._can_read():
  141. pkt = self.proto.read_pkt_line()
  142. parts = pkt.rstrip("\n").split(" ")
  143. if parts[0] == "ACK":
  144. graph_walker.ack(parts[1])
  145. assert parts[2] == "continue"
  146. have = graph_walker.next()
  147. self.proto.write_pkt_line("done\n")
  148. pkt = self.proto.read_pkt_line()
  149. while pkt:
  150. parts = pkt.rstrip("\n").split(" ")
  151. if parts[0] == "ACK":
  152. graph_walker.ack(pkt.split(" ")[1])
  153. if len(parts) < 3 or parts[2] != "continue":
  154. break
  155. pkt = self.proto.read_pkt_line()
  156. for pkt in self.proto.read_pkt_seq():
  157. channel = ord(pkt[0])
  158. pkt = pkt[1:]
  159. if channel == 1:
  160. pack_data(pkt)
  161. elif channel == 2:
  162. progress(pkt)
  163. else:
  164. raise AssertionError("Invalid sideband channel %d" % channel)
  165. return refs
  166. class TCPGitClient(GitClient):
  167. """A Git Client that works over TCP directly (i.e. git://)."""
  168. def __init__(self, host, port=None, *args, **kwargs):
  169. self._socket = socket.socket(type=socket.SOCK_STREAM)
  170. if port is None:
  171. port = TCP_GIT_PORT
  172. self._socket.connect((host, port))
  173. self.rfile = self._socket.makefile('rb', -1)
  174. self.wfile = self._socket.makefile('wb', 0)
  175. self.host = host
  176. super(TCPGitClient, self).__init__(lambda: _fileno_can_read(self._socket.fileno()), self.rfile.read, self.wfile.write, *args, **kwargs)
  177. def send_pack(self, path, changed_refs, generate_pack_contents):
  178. """Send a pack to a remote host.
  179. :param path: Path of the repository on the remote host
  180. """
  181. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  182. return super(TCPGitClient, self).send_pack(path, changed_refs, generate_pack_contents)
  183. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  184. """Fetch a pack from the remote host.
  185. :param path: Path of the reposiutory on the remote host
  186. :param determine_wants: Callback that receives available refs dict and
  187. should return list of sha's to fetch.
  188. :param graph_walker: GraphWalker instance used to find missing shas
  189. :param pack_data: Callback for writing pack data
  190. :param progress: Callback for writing progress
  191. """
  192. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  193. return super(TCPGitClient, self).fetch_pack(path, determine_wants,
  194. graph_walker, pack_data, progress)
  195. class SubprocessGitClient(GitClient):
  196. def __init__(self, *args, **kwargs):
  197. self.proc = None
  198. self._args = args
  199. self._kwargs = kwargs
  200. def _connect(self, service, *args):
  201. argv = [service] + list(args)
  202. self.proc = subprocess.Popen(argv, bufsize=0,
  203. stdin=subprocess.PIPE,
  204. stdout=subprocess.PIPE)
  205. def read_fn(size):
  206. return self.proc.stdout.read(size)
  207. def write_fn(data):
  208. self.proc.stdin.write(data)
  209. self.proc.stdin.flush()
  210. return GitClient(lambda: _fileno_can_read(self.proc.stdout.fileno()), read_fn, write_fn, *args, **kwargs)
  211. def send_pack(self, path, changed_refs, generate_pack_contents):
  212. client = self._connect("git-receive-pack", path)
  213. return client.send_pack(path, changed_refs, generate_pack_contents)
  214. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  215. progress):
  216. client = self._connect("git-upload-pack", path)
  217. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  218. progress)
  219. class SSHSubprocess(object):
  220. """A socket-like object that talks to an ssh subprocess via pipes."""
  221. def __init__(self, proc):
  222. self.proc = proc
  223. def send(self, data):
  224. return os.write(self.proc.stdin.fileno(), data)
  225. def recv(self, count):
  226. return self.proc.stdout.read(count)
  227. def close(self):
  228. self.proc.stdin.close()
  229. self.proc.stdout.close()
  230. self.proc.wait()
  231. class SSHVendor(object):
  232. def connect_ssh(self, host, command, username=None, port=None):
  233. #FIXME: This has no way to deal with passwords..
  234. args = ['ssh', '-x']
  235. if port is not None:
  236. args.extend(['-p', str(port)])
  237. if username is not None:
  238. host = "%s@%s" % (username, host)
  239. args.append(host)
  240. proc = subprocess.Popen(args + command,
  241. stdin=subprocess.PIPE,
  242. stdout=subprocess.PIPE)
  243. return SSHSubprocess(proc)
  244. # Can be overridden by users
  245. get_ssh_vendor = SSHVendor
  246. class SSHGitClient(GitClient):
  247. def __init__(self, host, port=None, *args, **kwargs):
  248. self.host = host
  249. self.port = port
  250. self._args = args
  251. self._kwargs = kwargs
  252. def send_pack(self, path, get_changed_refs, generate_pack_contents):
  253. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack %s" % path], port=self.port)
  254. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  255. return client.send_pack(path, get_changed_refs, generate_pack_contents)
  256. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  257. progress):
  258. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack %s" % path], port=self.port)
  259. client = GitClient(lambda: _fileno_can_read(remote.proc.stdout.fileno()), remote.recv, remote.send, *self._args, **self._kwargs)
  260. return client.fetch_pack(path, determine_wants, graph_walker, pack_data,
  261. progress)