client.py 13 KB

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