client.py 10 KB

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