client.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # server.py -- Implementation of the server side git protocols
  2. # Copryight (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. import os
  19. import select
  20. import socket
  21. import subprocess
  22. from dulwich.protocol import Protocol, TCP_GIT_PORT, extract_capabilities
  23. from dulwich.pack import write_pack_data
  24. class SimpleFetchGraphWalker(object):
  25. def __init__(self, local_heads, get_parents):
  26. self.heads = set(local_heads)
  27. self.get_parents = get_parents
  28. self.parents = {}
  29. def ack(self, ref):
  30. if ref in self.heads:
  31. self.heads.remove(ref)
  32. if ref in self.parents:
  33. for p in self.parents[ref]:
  34. self.ack(p)
  35. def next(self):
  36. if self.heads:
  37. ret = self.heads.pop()
  38. ps = self.get_parents(ret)
  39. self.parents[ret] = ps
  40. self.heads.update(ps)
  41. return ret
  42. return None
  43. class GitClient(object):
  44. """Git smart server client.
  45. """
  46. def __init__(self, fileno, read, write):
  47. self.proto = Protocol(read, write)
  48. self.fileno = fileno
  49. def capabilities(self):
  50. return "multi_ack side-band-64k thin-pack ofs-delta"
  51. def read_refs(self):
  52. server_capabilities = None
  53. refs = {}
  54. # Receive refs from server
  55. for pkt in self.proto.read_pkt_seq():
  56. (sha, ref) = pkt.rstrip("\n").split(" ", 1)
  57. if server_capabilities is None:
  58. (ref, server_capabilities) = extract_capabilities(ref)
  59. if not (ref == "capabilities^{}" and sha == "0" * 40):
  60. refs[ref] = sha
  61. return refs, server_capabilities
  62. def send_pack(self, path, generate_pack_contents):
  63. refs, server_capabilities = self.read_refs()
  64. changed_refs = [] # FIXME
  65. if not changed_refs:
  66. self.proto.write_pkt_line(None)
  67. return
  68. self.proto.write_pkt_line("%s %s %s\0%s" % (changed_refs[0][0], changed_refs[0][1], changed_refs[0][2], self.capabilities()))
  69. want = []
  70. have = []
  71. for changed_ref in changed_refs[:]:
  72. self.proto.write_pkt_line("%s %s %s" % changed_refs)
  73. want.append(changed_refs[1])
  74. if changed_refs[0] != "0"*40:
  75. have.append(changed_refs[0])
  76. self.proto.write_pkt_line(None)
  77. shas = generate_pack_contents(want, have, None)
  78. write_pack_data(self.write, shas, len(shas))
  79. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  80. """Retrieve a pack from a git smart server.
  81. :param determine_wants: Callback that returns list of commits to fetch
  82. :param graph_walker: Object with next() and ack().
  83. :param pack_data: Callback called for each bit of data in the pack
  84. :param progress: Callback for progress reports (strings)
  85. """
  86. (refs, server_capabilities) = self.read_refs()
  87. wants = determine_wants(refs)
  88. if not wants:
  89. self.proto.write_pkt_line(None)
  90. return
  91. self.proto.write_pkt_line("want %s %s\n" % (wants[0], self.capabilities()))
  92. for want in wants[1:]:
  93. self.proto.write_pkt_line("want %s\n" % want)
  94. self.proto.write_pkt_line(None)
  95. have = graph_walker.next()
  96. while have:
  97. self.proto.write_pkt_line("have %s\n" % have)
  98. if len(select.select([self.fileno], [], [], 0)[0]) > 0:
  99. pkt = self.proto.read_pkt_line()
  100. parts = pkt.rstrip("\n").split(" ")
  101. if parts[0] == "ACK":
  102. graph_walker.ack(parts[1])
  103. assert parts[2] == "continue"
  104. have = graph_walker.next()
  105. self.proto.write_pkt_line("done\n")
  106. pkt = self.proto.read_pkt_line()
  107. while pkt:
  108. parts = pkt.rstrip("\n").split(" ")
  109. if parts[0] == "ACK":
  110. graph_walker.ack(pkt.split(" ")[1])
  111. if len(parts) < 3 or parts[2] != "continue":
  112. break
  113. pkt = self.proto.read_pkt_line()
  114. for pkt in self.proto.read_pkt_seq():
  115. channel = ord(pkt[0])
  116. pkt = pkt[1:]
  117. if channel == 1:
  118. pack_data(pkt)
  119. elif channel == 2:
  120. progress(pkt)
  121. else:
  122. raise AssertionError("Invalid sideband channel %d" % channel)
  123. class TCPGitClient(GitClient):
  124. def __init__(self, host, port=TCP_GIT_PORT):
  125. self._socket = socket.socket(type=socket.SOCK_STREAM)
  126. self._socket.connect((host, port))
  127. self.rfile = self._socket.makefile('rb', -1)
  128. self.wfile = self._socket.makefile('wb', 0)
  129. self.host = host
  130. super(TCPGitClient, self).__init__(self._socket.fileno(), self.rfile.read, self.wfile.write)
  131. def send_pack(self, path):
  132. self.proto.send_cmd("git-receive-pack", path, "host=%s" % self.host)
  133. super(TCPGitClient, self).send_pack(path)
  134. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  135. self.proto.send_cmd("git-upload-pack", path, "host=%s" % self.host)
  136. super(TCPGitClient, self).fetch_pack(path, determine_wants, graph_walker, pack_data, progress)
  137. class SubprocessGitClient(GitClient):
  138. def __init__(self):
  139. self.proc = None
  140. def _connect(self, service, *args):
  141. argv = [service] + list(args)
  142. self.proc = subprocess.Popen(argv, bufsize=0,
  143. stdin=subprocess.PIPE,
  144. stdout=subprocess.PIPE)
  145. def read_fn(size):
  146. return self.proc.stdout.read(size)
  147. def write_fn(data):
  148. self.proc.stdin.write(data)
  149. self.proc.stdin.flush()
  150. return GitClient(self.proc.stdout.fileno(), read_fn, write_fn)
  151. def send_pack(self, path):
  152. client = self._connect("git-receive-pack", path)
  153. client.send_pack(path)
  154. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  155. client = self._connect("git-upload-pack", path)
  156. client.fetch_pack(path, determine_wants, graph_walker, pack_data, progress)
  157. class SSHSubprocess(object):
  158. """A socket-like object that talks to an ssh subprocess via pipes."""
  159. def __init__(self, proc):
  160. self.proc = proc
  161. def send(self, data):
  162. return os.write(self.proc.stdin.fileno(), data)
  163. def recv(self, count):
  164. return self.proc.stdout.read(count)
  165. def close(self):
  166. self.proc.stdin.close()
  167. self.proc.stdout.close()
  168. self.proc.wait()
  169. class SSHVendor(object):
  170. def connect_ssh(self, host, command, username=None, port=None):
  171. #FIXME: This has no way to deal with passwords..
  172. args = ['ssh', '-x']
  173. if port is not None:
  174. args.extend(['-p', str(port)])
  175. if username is not None:
  176. host = "%s@%s" % (username, host)
  177. args.append(host)
  178. proc = subprocess.Popen(args + command,
  179. stdin=subprocess.PIPE,
  180. stdout=subprocess.PIPE)
  181. return SSHSubprocess(proc)
  182. # Can be overridden by users
  183. get_ssh_vendor = SSHVendor
  184. class SSHGitClient(GitClient):
  185. def __init__(self, host, port=None):
  186. self.host = host
  187. self.port = port
  188. def send_pack(self, path):
  189. remote = get_ssh_vendor().connect_ssh(self.host, ["git-receive-pack %s" % path], port=self.port)
  190. client = GitClient(remote.proc.stdout.fileno(), remote.recv, remote.send)
  191. client.send_pack(path)
  192. def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress):
  193. remote = get_ssh_vendor().connect_ssh(self.host, ["git-upload-pack %s" % path], port=self.port)
  194. client = GitClient(remote.proc.stdout.fileno(), remote.recv, remote.send)
  195. client.fetch_pack(path, determine_wants, graph_walker, pack_data, progress)