2
0

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