You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

KetchLeader.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /*
  2. * Copyright (C) 2016, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.ketch;
  44. import static org.eclipse.jgit.internal.ketch.KetchLeader.State.CANDIDATE;
  45. import static org.eclipse.jgit.internal.ketch.KetchLeader.State.LEADER;
  46. import static org.eclipse.jgit.internal.ketch.KetchLeader.State.SHUTDOWN;
  47. import static org.eclipse.jgit.internal.ketch.KetchReplica.Participation.FOLLOWER_ONLY;
  48. import static org.eclipse.jgit.internal.ketch.Proposal.State.QUEUED;
  49. import java.io.IOException;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Collection;
  54. import java.util.List;
  55. import java.util.concurrent.locks.Lock;
  56. import java.util.concurrent.locks.ReentrantLock;
  57. import org.eclipse.jgit.internal.storage.reftree.RefTree;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.Repository;
  60. import org.eclipse.jgit.revwalk.RevCommit;
  61. import org.eclipse.jgit.revwalk.RevWalk;
  62. import org.slf4j.Logger;
  63. import org.slf4j.LoggerFactory;
  64. /**
  65. * A leader managing consensus across remote followers.
  66. * <p>
  67. * A leader instance starts up in {@link State#CANDIDATE} and tries to begin a
  68. * new term by sending an {@link ElectionRound} to all replicas. Its term starts
  69. * if a majority of replicas have accepted this leader instance for the term.
  70. * <p>
  71. * Once elected by a majority the instance enters {@link State#LEADER} and runs
  72. * proposals offered to {@link #queueProposal(Proposal)}. This continues until
  73. * the leader is timed out for inactivity, or is deposed by a competing leader
  74. * gaining its own majority.
  75. * <p>
  76. * Once timed out or deposed this {@code KetchLeader} instance should be
  77. * discarded, and a new instance takes over.
  78. * <p>
  79. * Each leader instance coordinates a group of {@link KetchReplica}s. Replica
  80. * instances are owned by the leader instance and must be discarded when the
  81. * leader is discarded.
  82. * <p>
  83. * In Ketch all push requests are issued through the leader. The steps are as
  84. * follows (see {@link KetchPreReceive} for an example):
  85. * <ul>
  86. * <li>Create a {@link Proposal} with the
  87. * {@link org.eclipse.jgit.transport.ReceiveCommand}s that represent the push.
  88. * <li>Invoke {@link #queueProposal(Proposal)} on the leader instance.
  89. * <li>Wait for consensus with {@link Proposal#await()}.
  90. * <li>To examine the status of the push, check {@link Proposal#getCommands()},
  91. * looking at
  92. * {@link org.eclipse.jgit.internal.storage.reftree.Command#getResult()}.
  93. * </ul>
  94. * <p>
  95. * The leader gains consensus by first pushing the needed objects and a
  96. * {@link RefTree} representing the desired target repository state to the
  97. * {@code refs/txn/accepted} branch on each of the replicas. Once a majority has
  98. * succeeded, the leader commits the state by either pushing the
  99. * {@code refs/txn/accepted} value to {@code refs/txn/committed} (for
  100. * Ketch-aware replicas) or by pushing updates to {@code refs/heads/master},
  101. * etc. for stock Git replicas.
  102. * <p>
  103. * Internally, the actual transport to replicas is performed on background
  104. * threads via the {@link KetchSystem}'s executor service. For performance, the
  105. * {@link KetchLeader}, {@link KetchReplica} and {@link Proposal} objects share
  106. * some state, and may invoke each other's methods on different threads. This
  107. * access is protected by the leader's {@link #lock} object. Care must be taken
  108. * to prevent concurrent access by correctly obtaining the leader's lock.
  109. */
  110. public abstract class KetchLeader {
  111. private static final Logger log = LoggerFactory.getLogger(KetchLeader.class);
  112. /** Current state of the leader instance. */
  113. public static enum State {
  114. /** Newly created instance trying to elect itself leader. */
  115. CANDIDATE,
  116. /** Leader instance elected by a majority. */
  117. LEADER,
  118. /** Instance has been deposed by another with a more recent term. */
  119. DEPOSED,
  120. /** Leader has been gracefully shutdown, e.g. due to inactivity. */
  121. SHUTDOWN;
  122. }
  123. private final KetchSystem system;
  124. /** Leader's knowledge of replicas for this repository. */
  125. private KetchReplica[] voters;
  126. private KetchReplica[] followers;
  127. private LocalReplica self;
  128. /**
  129. * Lock protecting all data within this leader instance.
  130. * <p>
  131. * This lock extends into the {@link KetchReplica} instances used by the
  132. * leader. They share the same lock instance to simplify concurrency.
  133. */
  134. final Lock lock;
  135. private State state = CANDIDATE;
  136. /** Term of this leader, once elected. */
  137. private long term;
  138. /**
  139. * Pending proposals accepted into the queue in FIFO order.
  140. * <p>
  141. * These proposals were preflighted and do not contain any conflicts with
  142. * each other and their expectations matched the leader's local view of the
  143. * agreed upon {@code refs/txn/accepted} tree.
  144. */
  145. private final List<Proposal> queued;
  146. /**
  147. * State of the repository's RefTree after applying all entries in
  148. * {@link #queued}. New proposals must be consistent with this tree to be
  149. * appended to the end of {@link #queued}.
  150. * <p>
  151. * Must be deep-copied with {@link RefTree#copy()} if
  152. * {@link #roundHoldsReferenceToRefTree} is {@code true}.
  153. */
  154. private RefTree refTree;
  155. /**
  156. * If {@code true} {@link #refTree} must be duplicated before queuing the
  157. * next proposal. The {@link #refTree} was passed into the constructor of a
  158. * {@link ProposalRound}, and that external reference to the {@link RefTree}
  159. * object is held by the proposal until it materializes the tree object in
  160. * the object store. This field is set {@code true} when the proposal begins
  161. * execution and set {@code false} once tree objects are persisted in the
  162. * local repository's object store or {@link #refTree} is replaced with a
  163. * copy to isolate it from any running rounds.
  164. * <p>
  165. * If proposals arrive less frequently than the {@code RefTree} is written
  166. * out to the repository the {@link #roundHoldsReferenceToRefTree} behavior
  167. * avoids duplicating {@link #refTree}, reducing both time and memory used.
  168. * However if proposals arrive more frequently {@link #refTree} must be
  169. * duplicated to prevent newly queued proposals from corrupting the
  170. * {@link #runningRound}.
  171. */
  172. volatile boolean roundHoldsReferenceToRefTree;
  173. /** End of the leader's log. */
  174. private LogIndex headIndex;
  175. /** Leader knows this (and all prior) states are committed. */
  176. private LogIndex committedIndex;
  177. /**
  178. * Is the leader idle with no work pending? If {@code true} there is no work
  179. * for the leader (normal state). This field is {@code false} when the
  180. * leader thread is scheduled for execution, or while {@link #runningRound}
  181. * defines a round in progress.
  182. */
  183. private boolean idle;
  184. /** Current round the leader is preparing and waiting for a vote on. */
  185. private Round runningRound;
  186. /**
  187. * Construct a leader for a Ketch instance.
  188. *
  189. * @param system
  190. * Ketch system configuration the leader must adhere to.
  191. */
  192. protected KetchLeader(KetchSystem system) {
  193. this.system = system;
  194. this.lock = new ReentrantLock(true /* fair */);
  195. this.queued = new ArrayList<>(4);
  196. this.idle = true;
  197. }
  198. /** @return system configuration. */
  199. KetchSystem getSystem() {
  200. return system;
  201. }
  202. /**
  203. * Configure the replicas used by this Ketch instance.
  204. * <p>
  205. * Replicas should be configured once at creation before any proposals are
  206. * executed. Once elections happen, <b>reconfiguration is a complicated
  207. * concept that is not currently supported</b>.
  208. *
  209. * @param replicas
  210. * members participating with the same repository.
  211. */
  212. public void setReplicas(Collection<KetchReplica> replicas) {
  213. List<KetchReplica> v = new ArrayList<>(5);
  214. List<KetchReplica> f = new ArrayList<>(5);
  215. for (KetchReplica r : replicas) {
  216. switch (r.getParticipation()) {
  217. case FULL:
  218. v.add(r);
  219. break;
  220. case FOLLOWER_ONLY:
  221. f.add(r);
  222. break;
  223. }
  224. }
  225. Collection<Integer> validVoters = validVoterCounts();
  226. if (!validVoters.contains(Integer.valueOf(v.size()))) {
  227. throw new IllegalArgumentException(MessageFormat.format(
  228. KetchText.get().unsupportedVoterCount,
  229. Integer.valueOf(v.size()),
  230. validVoters));
  231. }
  232. LocalReplica me = findLocal(v);
  233. if (me == null) {
  234. throw new IllegalArgumentException(
  235. KetchText.get().localReplicaRequired);
  236. }
  237. lock.lock();
  238. try {
  239. voters = v.toArray(new KetchReplica[v.size()]);
  240. followers = f.toArray(new KetchReplica[f.size()]);
  241. self = me;
  242. } finally {
  243. lock.unlock();
  244. }
  245. }
  246. private static Collection<Integer> validVoterCounts() {
  247. @SuppressWarnings("boxing")
  248. Integer[] valid = {
  249. // An odd number of voting replicas is required.
  250. 1, 3, 5, 7, 9 };
  251. return Arrays.asList(valid);
  252. }
  253. private static LocalReplica findLocal(Collection<KetchReplica> voters) {
  254. for (KetchReplica r : voters) {
  255. if (r instanceof LocalReplica) {
  256. return (LocalReplica) r;
  257. }
  258. }
  259. return null;
  260. }
  261. /**
  262. * Get an instance of the repository for use by a leader thread.
  263. * <p>
  264. * The caller will close the repository.
  265. *
  266. * @return opened repository for use by the leader thread.
  267. * @throws IOException
  268. * cannot reopen the repository for the leader.
  269. */
  270. protected abstract Repository openRepository() throws IOException;
  271. /**
  272. * Queue a reference update proposal for consensus.
  273. * <p>
  274. * This method does not wait for consensus to be reached. The proposal is
  275. * checked to look for risks of conflicts, and then submitted into the queue
  276. * for distribution as soon as possible.
  277. * <p>
  278. * Callers must use {@link Proposal#await()} to see if the proposal is done.
  279. *
  280. * @param proposal
  281. * the proposed reference updates to queue for consideration.
  282. * Once execution is complete the individual reference result
  283. * fields will be populated with the outcome.
  284. * @throws InterruptedException
  285. * current thread was interrupted. The proposal may have been
  286. * aborted if it was not yet queued for execution.
  287. * @throws IOException
  288. * unrecoverable error preventing proposals from being attempted
  289. * by this leader.
  290. */
  291. public void queueProposal(Proposal proposal)
  292. throws InterruptedException, IOException {
  293. try {
  294. lock.lockInterruptibly();
  295. } catch (InterruptedException e) {
  296. proposal.abort();
  297. throw e;
  298. }
  299. try {
  300. if (refTree == null) {
  301. initialize();
  302. for (Proposal p : queued) {
  303. refTree.apply(p.getCommands());
  304. }
  305. } else if (roundHoldsReferenceToRefTree) {
  306. refTree = refTree.copy();
  307. roundHoldsReferenceToRefTree = false;
  308. }
  309. if (!refTree.apply(proposal.getCommands())) {
  310. // A conflict exists so abort the proposal.
  311. proposal.abort();
  312. return;
  313. }
  314. queued.add(proposal);
  315. proposal.notifyState(QUEUED);
  316. if (idle) {
  317. scheduleLeader();
  318. }
  319. } finally {
  320. lock.unlock();
  321. }
  322. }
  323. private void initialize() throws IOException {
  324. try (Repository git = openRepository(); RevWalk rw = new RevWalk(git)) {
  325. self.initialize(git);
  326. ObjectId accepted = self.getTxnAccepted();
  327. if (!ObjectId.zeroId().equals(accepted)) {
  328. RevCommit c = rw.parseCommit(accepted);
  329. headIndex = LogIndex.unknown(accepted);
  330. refTree = RefTree.read(rw.getObjectReader(), c.getTree());
  331. } else {
  332. headIndex = LogIndex.unknown(ObjectId.zeroId());
  333. refTree = RefTree.newEmptyTree();
  334. }
  335. }
  336. }
  337. private void scheduleLeader() {
  338. idle = false;
  339. system.getExecutor().execute(new Runnable() {
  340. @Override
  341. public void run() {
  342. runLeader();
  343. }
  344. });
  345. }
  346. private void runLeader() {
  347. Round round;
  348. lock.lock();
  349. try {
  350. switch (state) {
  351. case CANDIDATE:
  352. round = new ElectionRound(this, headIndex);
  353. break;
  354. case LEADER:
  355. round = newProposalRound();
  356. break;
  357. case DEPOSED:
  358. case SHUTDOWN:
  359. default:
  360. log.warn("Leader cannot run {}", state); //$NON-NLS-1$
  361. // TODO(sop): Redirect proposals.
  362. return;
  363. }
  364. } finally {
  365. lock.unlock();
  366. }
  367. try {
  368. round.start();
  369. } catch (IOException e) {
  370. // TODO(sop) Depose leader if it cannot use its repository.
  371. log.error(KetchText.get().leaderFailedToStore, e);
  372. lock.lock();
  373. try {
  374. nextRound();
  375. } finally {
  376. lock.unlock();
  377. }
  378. }
  379. }
  380. private ProposalRound newProposalRound() {
  381. List<Proposal> todo = new ArrayList<>(queued);
  382. queued.clear();
  383. roundHoldsReferenceToRefTree = true;
  384. return new ProposalRound(this, headIndex, todo, refTree);
  385. }
  386. /** @return term of this leader's reign. */
  387. long getTerm() {
  388. return term;
  389. }
  390. /** @return end of the leader's log. */
  391. LogIndex getHead() {
  392. return headIndex;
  393. }
  394. /**
  395. * @return state leader knows it has committed across a quorum of replicas.
  396. */
  397. LogIndex getCommitted() {
  398. return committedIndex;
  399. }
  400. boolean isIdle() {
  401. return idle;
  402. }
  403. void runAsync(Round round) {
  404. lock.lock();
  405. try {
  406. // End of the log is this round. Once transport begins it is
  407. // reasonable to assume at least one replica will eventually get
  408. // this, and there is reasonable probability it commits.
  409. headIndex = round.acceptedNewIndex;
  410. runningRound = round;
  411. for (KetchReplica replica : voters) {
  412. replica.pushTxnAcceptedAsync(round);
  413. }
  414. for (KetchReplica replica : followers) {
  415. replica.pushTxnAcceptedAsync(round);
  416. }
  417. } finally {
  418. lock.unlock();
  419. }
  420. }
  421. /**
  422. * Asynchronous signal from a replica after completion.
  423. * <p>
  424. * Must be called while {@link #lock} is held by the replica.
  425. *
  426. * @param replica
  427. * replica posting a completion event.
  428. */
  429. void onReplicaUpdate(KetchReplica replica) {
  430. if (log.isDebugEnabled()) {
  431. log.debug("Replica {} finished:\n{}", //$NON-NLS-1$
  432. replica.describeForLog(), snapshot());
  433. }
  434. if (replica.getParticipation() == FOLLOWER_ONLY) {
  435. // Followers cannot vote, so votes haven't changed.
  436. return;
  437. } else if (runningRound == null) {
  438. // No round running, no need to tally votes.
  439. return;
  440. }
  441. assert headIndex.equals(runningRound.acceptedNewIndex);
  442. int matching = 0;
  443. for (KetchReplica r : voters) {
  444. if (r.hasAccepted(headIndex)) {
  445. matching++;
  446. }
  447. }
  448. int quorum = voters.length / 2 + 1;
  449. boolean success = matching >= quorum;
  450. if (!success) {
  451. return;
  452. }
  453. switch (state) {
  454. case CANDIDATE:
  455. term = ((ElectionRound) runningRound).getTerm();
  456. state = LEADER;
  457. if (log.isDebugEnabled()) {
  458. log.debug("Won election, running term " + term); //$NON-NLS-1$
  459. }
  460. //$FALL-THROUGH$
  461. case LEADER:
  462. committedIndex = headIndex;
  463. if (log.isDebugEnabled()) {
  464. log.debug("Committed {} in term {}", //$NON-NLS-1$
  465. committedIndex.describeForLog(),
  466. Long.valueOf(term));
  467. }
  468. nextRound();
  469. commitAsync(replica);
  470. notifySuccess(runningRound);
  471. if (log.isDebugEnabled()) {
  472. log.debug("Leader state:\n{}", snapshot()); //$NON-NLS-1$
  473. }
  474. break;
  475. default:
  476. log.debug("Leader ignoring replica while in {}", state); //$NON-NLS-1$
  477. break;
  478. }
  479. }
  480. private void notifySuccess(Round round) {
  481. // Drop the leader lock while notifying Proposal listeners.
  482. lock.unlock();
  483. try {
  484. round.success();
  485. } finally {
  486. lock.lock();
  487. }
  488. }
  489. private void commitAsync(KetchReplica caller) {
  490. for (KetchReplica r : voters) {
  491. if (r == caller) {
  492. continue;
  493. }
  494. if (r.shouldPushUnbatchedCommit(committedIndex, isIdle())) {
  495. r.pushCommitAsync(committedIndex);
  496. }
  497. }
  498. for (KetchReplica r : followers) {
  499. if (r == caller) {
  500. continue;
  501. }
  502. if (r.shouldPushUnbatchedCommit(committedIndex, isIdle())) {
  503. r.pushCommitAsync(committedIndex);
  504. }
  505. }
  506. }
  507. /** Schedule the next round; invoked while {@link #lock} is held. */
  508. void nextRound() {
  509. runningRound = null;
  510. if (queued.isEmpty()) {
  511. idle = true;
  512. } else {
  513. // Caller holds lock. Reschedule leader on a new thread so
  514. // the call stack can unwind and lock is not held unexpectedly
  515. // during prepare for the next round.
  516. scheduleLeader();
  517. }
  518. }
  519. /** @return snapshot this leader. */
  520. public LeaderSnapshot snapshot() {
  521. lock.lock();
  522. try {
  523. LeaderSnapshot s = new LeaderSnapshot();
  524. s.state = state;
  525. s.term = term;
  526. s.headIndex = headIndex;
  527. s.committedIndex = committedIndex;
  528. s.idle = isIdle();
  529. for (KetchReplica r : voters) {
  530. s.replicas.add(r.snapshot());
  531. }
  532. for (KetchReplica r : followers) {
  533. s.replicas.add(r.snapshot());
  534. }
  535. return s;
  536. } finally {
  537. lock.unlock();
  538. }
  539. }
  540. /** Gracefully shutdown this leader and cancel outstanding operations. */
  541. public void shutdown() {
  542. lock.lock();
  543. try {
  544. if (state != SHUTDOWN) {
  545. state = SHUTDOWN;
  546. for (KetchReplica r : voters) {
  547. r.shutdown();
  548. }
  549. for (KetchReplica r : followers) {
  550. r.shutdown();
  551. }
  552. }
  553. } finally {
  554. lock.unlock();
  555. }
  556. }
  557. @Override
  558. public String toString() {
  559. return snapshot().toString();
  560. }
  561. }