2
0

server.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # server.py -- Implementation of the server side git protocols
  2. # Copryight (C) 2008 John Carr <john.carr@unrouted.co.uk>
  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; version 2
  7. # or (at your option) any 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. """Git smart network protocol server implementation.
  19. For more detailed implementation on the network protocol, see the
  20. Documentation/technical directory in the cgit distribution, and in particular:
  21. Documentation/technical/protocol-capabilities.txt
  22. Documentation/technical/pack-protocol.txt
  23. """
  24. import collections
  25. import SocketServer
  26. import tempfile
  27. from dulwich.errors import (
  28. GitProtocolError,
  29. )
  30. from dulwich.objects import (
  31. hex_to_sha,
  32. )
  33. from dulwich.protocol import (
  34. Protocol,
  35. ProtocolFile,
  36. TCP_GIT_PORT,
  37. extract_capabilities,
  38. extract_want_line_capabilities,
  39. SINGLE_ACK,
  40. MULTI_ACK,
  41. ack_type,
  42. )
  43. from dulwich.repo import (
  44. Repo,
  45. )
  46. from dulwich.pack import (
  47. write_pack_data,
  48. )
  49. class Backend(object):
  50. def get_refs(self):
  51. """
  52. Get all the refs in the repository
  53. :return: dict of name -> sha
  54. """
  55. raise NotImplementedError
  56. def apply_pack(self, refs, read):
  57. """ Import a set of changes into a repository and update the refs
  58. :param refs: list of tuple(name, sha)
  59. :param read: callback to read from the incoming pack
  60. """
  61. raise NotImplementedError
  62. def fetch_objects(self, determine_wants, graph_walker, progress):
  63. """
  64. Yield the objects required for a list of commits.
  65. :param progress: is a callback to send progress messages to the client
  66. """
  67. raise NotImplementedError
  68. class GitBackend(Backend):
  69. def __init__(self, repo=None):
  70. if repo is None:
  71. repo = Repo(tmpfile.mkdtemp())
  72. self.repo = repo
  73. self.object_store = self.repo.object_store
  74. self.fetch_objects = self.repo.fetch_objects
  75. self.get_refs = self.repo.get_refs
  76. def apply_pack(self, refs, read):
  77. f, commit = self.repo.object_store.add_thin_pack()
  78. try:
  79. f.write(read())
  80. finally:
  81. commit()
  82. for oldsha, sha, ref in refs:
  83. if ref == "0" * 40:
  84. del self.repo.refs[ref]
  85. else:
  86. self.repo.refs[ref] = sha
  87. print "pack applied"
  88. class Handler(object):
  89. """Smart protocol command handler base class."""
  90. def __init__(self, backend, read, write):
  91. self.backend = backend
  92. self.proto = Protocol(read, write)
  93. def capabilities(self):
  94. return " ".join(self.default_capabilities())
  95. class UploadPackHandler(Handler):
  96. """Protocol handler for uploading a pack to the server."""
  97. def __init__(self, backend, read, write):
  98. Handler.__init__(self, backend, read, write)
  99. self._client_capabilities = None
  100. self._graph_walker = None
  101. def default_capabilities(self):
  102. return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
  103. def set_client_capabilities(self, caps):
  104. my_caps = self.default_capabilities()
  105. for cap in caps:
  106. if '_ack' in cap and cap not in my_caps:
  107. raise GitProtocolError('Client asked for capability %s that '
  108. 'was not advertised.' % cap)
  109. self._client_capabilities = caps
  110. def get_client_capabilities(self):
  111. return self._client_capabilities
  112. client_capabilities = property(get_client_capabilities,
  113. set_client_capabilities)
  114. def handle(self):
  115. progress = lambda x: self.proto.write_sideband(2, x)
  116. write = lambda x: self.proto.write_sideband(1, x)
  117. graph_walker = ProtocolGraphWalker(self)
  118. objects_iter = self.backend.fetch_objects(
  119. graph_walker.determine_wants, graph_walker, progress)
  120. # Do they want any objects?
  121. if len(objects_iter) == 0:
  122. return
  123. progress("dul-daemon says what\n")
  124. progress("counting objects: %d, done.\n" % len(objects_iter))
  125. write_pack_data(ProtocolFile(None, write), objects_iter,
  126. len(objects_iter))
  127. progress("how was that, then?\n")
  128. # we are done
  129. self.proto.write("0000")
  130. class ProtocolGraphWalker(object):
  131. """A graph walker that knows the git protocol.
  132. As a graph walker, this class implements ack(), next(), and reset(). It also
  133. contains some base methods for interacting with the wire and walking the
  134. commit tree.
  135. The work of determining which acks to send is passed on to the
  136. implementation instance stored in _impl. The reason for this is that we do
  137. not know at object creation time what ack level the protocol requires. A
  138. call to set_ack_level() is required to set up the implementation, before any
  139. calls to next() or ack() are made.
  140. """
  141. def __init__(self, handler):
  142. self.handler = handler
  143. self.store = handler.backend.object_store
  144. self.proto = handler.proto
  145. self._wants = []
  146. self._cached = False
  147. self._cache = []
  148. self._cache_index = 0
  149. self._impl = None
  150. def determine_wants(self, heads):
  151. """Determine the wants for a set of heads.
  152. The given heads are advertised to the client, who then specifies which
  153. refs he wants using 'want' lines. This portion of the protocol is the
  154. same regardless of ack type, and in fact is used to set the ack type of
  155. the ProtocolGraphWalker.
  156. :param heads: a dict of refname->SHA1 to advertise
  157. :return: a list of SHA1s requested by the client
  158. """
  159. if not heads:
  160. raise GitProtocolError('No heads found')
  161. values = set(heads.itervalues())
  162. for i, (ref, sha) in enumerate(heads.iteritems()):
  163. line = "%s %s" % (sha, ref)
  164. if not i:
  165. line = "%s\x00%s" % (line, self.handler.capabilities())
  166. self.proto.write_pkt_line("%s\n" % line)
  167. # TODO: include peeled value of any tags
  168. # i'm done..
  169. self.proto.write_pkt_line(None)
  170. # Now client will sending want want want commands
  171. want = self.proto.read_pkt_line()
  172. if not want:
  173. return []
  174. line, caps = extract_want_line_capabilities(want)
  175. self.handler.client_capabilities = caps
  176. self.set_ack_type(ack_type(caps))
  177. command, sha = self._split_proto_line(line)
  178. want_revs = []
  179. while command != None:
  180. if command != 'want':
  181. raise GitProtocolError(
  182. 'Protocol got unexpected command %s' % command)
  183. if sha not in values:
  184. raise GitProtocolError(
  185. 'Client wants invalid object %s' % sha)
  186. want_revs.append(sha)
  187. command, sha = self.read_proto_line()
  188. self.set_wants(want_revs)
  189. return want_revs
  190. def ack(self, have_ref):
  191. return self._impl.ack(have_ref)
  192. def reset(self):
  193. self._cached = True
  194. self._cache_index = 0
  195. def next(self):
  196. if not self._cached:
  197. if not self._impl:
  198. return None
  199. return self._impl.next()
  200. self._cache_index += 1
  201. if self._cache_index > len(self._cache):
  202. return None
  203. return self._cache[self._cache_index]
  204. def _split_proto_line(self, line):
  205. fields = line.rstrip('\n').split(' ', 1)
  206. if len(fields) == 1 and fields[0] == 'done':
  207. return ('done', None)
  208. elif len(fields) == 2 and fields[0] in ('want', 'have'):
  209. try:
  210. hex_to_sha(fields[1])
  211. return tuple(fields)
  212. except (TypeError, AssertionError), e:
  213. raise GitProtocolError(e)
  214. raise GitProtocolError('Received invalid line from client:\n%s' % line)
  215. def read_proto_line(self):
  216. """Read a line from the wire.
  217. :return: a tuple having one of the following forms:
  218. ('want', obj_id)
  219. ('have', obj_id)
  220. ('done', None)
  221. (None, None) (for a flush-pkt)
  222. """
  223. line = self.proto.read_pkt_line()
  224. if not line:
  225. return (None, None)
  226. return self._split_proto_line(line)
  227. def send_ack(self, sha, ack_type=''):
  228. if ack_type:
  229. ack_type = ' %s' % ack_type
  230. self.proto.write_pkt_line('ACK %s%s\n' % (sha, ack_type))
  231. def send_nak(self):
  232. self.proto.write_pkt_line('NAK\n')
  233. def set_wants(self, wants):
  234. self._wants = wants
  235. def _is_satisfied(self, haves, want, earliest):
  236. """Check whether a want is satisfied by a set of haves.
  237. A want, typically a branch tip, is "satisfied" only if there exists a
  238. path back from that want to one of the haves.
  239. :param haves: A set of commits we know the client has.
  240. :param want: The want to check satisfaction for.
  241. :param earliest: A timestamp beyond which the search for haves will be
  242. terminated, presumably because we're searching too far down the
  243. wrong branch.
  244. """
  245. o = self.store[want]
  246. pending = collections.deque([o])
  247. while pending:
  248. commit = pending.popleft()
  249. if commit.id in haves:
  250. return True
  251. if not getattr(commit, 'get_parents', None):
  252. # non-commit wants are assumed to be satisfied
  253. continue
  254. for parent in commit.get_parents():
  255. parent_obj = self.store[parent]
  256. # TODO: handle parents with later commit times than children
  257. if parent_obj.commit_time >= earliest:
  258. pending.append(parent_obj)
  259. return False
  260. def all_wants_satisfied(self, haves):
  261. """Check whether all the current wants are satisfied by a set of haves.
  262. :param haves: A set of commits we know the client has.
  263. :note: Wants are specified with set_wants rather than passed in since
  264. in the current interface they are determined outside this class.
  265. """
  266. haves = set(haves)
  267. earliest = min([self.store[h].commit_time for h in haves])
  268. for want in self._wants:
  269. if not self._is_satisfied(haves, want, earliest):
  270. return False
  271. return True
  272. def set_ack_type(self, ack_type):
  273. impl_classes = {
  274. MULTI_ACK: MultiAckGraphWalkerImpl,
  275. SINGLE_ACK: SingleAckGraphWalkerImpl,
  276. }
  277. self._impl = impl_classes[ack_type](self)
  278. class SingleAckGraphWalkerImpl(object):
  279. """Graph walker implementation that speaks the single-ack protocol."""
  280. def __init__(self, walker):
  281. self.walker = walker
  282. self._sent_ack = False
  283. def ack(self, have_ref):
  284. if not self._sent_ack:
  285. self.walker.send_ack(have_ref)
  286. self._sent_ack = True
  287. def next(self):
  288. command, sha = self.walker.read_proto_line()
  289. if command in (None, 'done'):
  290. if not self._sent_ack:
  291. self.walker.send_nak()
  292. return None
  293. elif command == 'have':
  294. return sha
  295. class MultiAckGraphWalkerImpl(object):
  296. """Graph walker implementation that speaks the multi-ack protocol."""
  297. def __init__(self, walker):
  298. self.walker = walker
  299. self._found_base = False
  300. self._common = []
  301. def ack(self, have_ref):
  302. self._common.append(have_ref)
  303. if not self._found_base:
  304. self.walker.send_ack(have_ref, 'continue')
  305. if self.walker.all_wants_satisfied(self._common):
  306. self._found_base = True
  307. # else we blind ack within next
  308. def next(self):
  309. while True:
  310. command, sha = self.walker.read_proto_line()
  311. if command is None:
  312. self.walker.send_nak()
  313. # in multi-ack mode, a flush-pkt indicates the client wants to
  314. # flush but more have lines are still coming
  315. continue
  316. elif command == 'done':
  317. # don't nak unless no common commits were found, even if not
  318. # everything is satisfied
  319. if self._common:
  320. self.walker.send_ack(self._common[-1])
  321. else:
  322. self.walker.send_nak()
  323. return None
  324. elif command == 'have':
  325. if self._found_base:
  326. # blind ack
  327. self.walker.send_ack(sha, 'continue')
  328. return sha
  329. class ReceivePackHandler(Handler):
  330. """Protocol handler for downloading a pack to the client."""
  331. def default_capabilities(self):
  332. return ("report-status", "delete-refs")
  333. def handle(self):
  334. refs = self.backend.get_refs().items()
  335. if refs:
  336. self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
  337. for i in range(1, len(refs)):
  338. ref = refs[i]
  339. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  340. else:
  341. self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
  342. self.proto.write("0000")
  343. client_refs = []
  344. ref = self.proto.read_pkt_line()
  345. # if ref is none then client doesnt want to send us anything..
  346. if ref is None:
  347. return
  348. ref, client_capabilities = extract_capabilities(ref)
  349. # client will now send us a list of (oldsha, newsha, ref)
  350. while ref:
  351. client_refs.append(ref.split())
  352. ref = self.proto.read_pkt_line()
  353. # backend can now deal with this refs and read a pack using self.read
  354. self.backend.apply_pack(client_refs, self.proto.read)
  355. # when we have read all the pack from the client, it assumes
  356. # everything worked OK.
  357. # there is NO ack from the server before it reports victory.
  358. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  359. def handle(self):
  360. proto = Protocol(self.rfile.read, self.wfile.write)
  361. command, args = proto.read_cmd()
  362. # switch case to handle the specific git command
  363. if command == 'git-upload-pack':
  364. cls = UploadPackHandler
  365. elif command == 'git-receive-pack':
  366. cls = ReceivePackHandler
  367. else:
  368. return
  369. h = cls(self.server.backend, self.rfile.read, self.wfile.write)
  370. h.handle()
  371. class TCPGitServer(SocketServer.TCPServer):
  372. allow_reuse_address = True
  373. serve = SocketServer.TCPServer.serve_forever
  374. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  375. self.backend = backend
  376. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)