2
0

client.py 11 KB

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