client.py 12 KB

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