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.

Proposal.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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.Proposal.State.ABORTED;
  45. import static org.eclipse.jgit.internal.ketch.Proposal.State.EXECUTED;
  46. import static org.eclipse.jgit.internal.ketch.Proposal.State.NEW;
  47. import static org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED;
  48. import static org.eclipse.jgit.transport.ReceiveCommand.Result.OK;
  49. import java.io.IOException;
  50. import java.util.ArrayList;
  51. import java.util.Collection;
  52. import java.util.Collections;
  53. import java.util.List;
  54. import java.util.concurrent.CopyOnWriteArrayList;
  55. import java.util.concurrent.TimeUnit;
  56. import java.util.concurrent.atomic.AtomicReference;
  57. import org.eclipse.jgit.annotations.Nullable;
  58. import org.eclipse.jgit.errors.MissingObjectException;
  59. import org.eclipse.jgit.internal.storage.reftree.Command;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.PersonIdent;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.revwalk.RevWalk;
  64. import org.eclipse.jgit.transport.PushCertificate;
  65. import org.eclipse.jgit.transport.ReceiveCommand;
  66. import org.eclipse.jgit.util.time.ProposedTimestamp;
  67. /**
  68. * A proposal to be applied in a Ketch system.
  69. * <p>
  70. * Pushing to a Ketch leader results in the leader making a proposal. The
  71. * proposal includes the list of reference updates. The leader attempts to send
  72. * the proposal to a quorum of replicas by pushing the proposal to a "staging"
  73. * area under the {@code refs/txn/stage/} namespace. If the proposal succeeds
  74. * then the changes are durable and the leader can commit the proposal.
  75. * <p>
  76. * Proposals are executed by {@link KetchLeader#queueProposal(Proposal)}, which
  77. * runs them asynchronously in the background. Proposals are thread-safe futures
  78. * allowing callers to {@link #await()} for results or be notified by callback
  79. * using {@link #addListener(Runnable)}.
  80. */
  81. public class Proposal {
  82. /** Current state of the proposal. */
  83. public enum State {
  84. /** Proposal has not yet been given to a {@link KetchLeader}. */
  85. NEW(false),
  86. /**
  87. * Proposal was validated and has entered the queue, but a round
  88. * containing this proposal has not started yet.
  89. */
  90. QUEUED(false),
  91. /** Round containing the proposal has begun and is in progress. */
  92. RUNNING(false),
  93. /**
  94. * Proposal was executed through a round. Individual results from
  95. * {@link Proposal#getCommands()}, {@link Command#getResult()} explain
  96. * the success or failure outcome.
  97. */
  98. EXECUTED(true),
  99. /** Proposal was aborted and did not reach consensus. */
  100. ABORTED(true);
  101. private final boolean done;
  102. private State(boolean done) {
  103. this.done = done;
  104. }
  105. /** @return true if this is a terminal state. */
  106. public boolean isDone() {
  107. return done;
  108. }
  109. }
  110. private final List<Command> commands;
  111. private PersonIdent author;
  112. private String message;
  113. private PushCertificate pushCert;
  114. private List<ProposedTimestamp> timestamps;
  115. private final List<Runnable> listeners = new CopyOnWriteArrayList<>();
  116. private final AtomicReference<State> state = new AtomicReference<>(NEW);
  117. /**
  118. * Create a proposal from a list of Ketch commands.
  119. *
  120. * @param cmds
  121. * prepared list of commands.
  122. */
  123. public Proposal(List<Command> cmds) {
  124. commands = Collections.unmodifiableList(new ArrayList<>(cmds));
  125. }
  126. /**
  127. * Create a proposal from a collection of received commands.
  128. *
  129. * @param rw
  130. * walker to assist in preparing commands.
  131. * @param cmds
  132. * list of pending commands.
  133. * @throws MissingObjectException
  134. * newId of a command is not found locally.
  135. * @throws IOException
  136. * local objects cannot be accessed.
  137. */
  138. public Proposal(RevWalk rw, Collection<ReceiveCommand> cmds)
  139. throws MissingObjectException, IOException {
  140. commands = asCommandList(rw, cmds);
  141. }
  142. private static List<Command> asCommandList(RevWalk rw,
  143. Collection<ReceiveCommand> cmds)
  144. throws MissingObjectException, IOException {
  145. List<Command> commands = new ArrayList<>(cmds.size());
  146. for (ReceiveCommand cmd : cmds) {
  147. commands.add(new Command(rw, cmd));
  148. }
  149. return Collections.unmodifiableList(commands);
  150. }
  151. /** @return commands from this proposal. */
  152. public Collection<Command> getCommands() {
  153. return commands;
  154. }
  155. /** @return optional author of the proposal. */
  156. @Nullable
  157. public PersonIdent getAuthor() {
  158. return author;
  159. }
  160. /**
  161. * Set the author for the proposal.
  162. *
  163. * @param who
  164. * optional identity of the author of the proposal.
  165. * @return {@code this}
  166. */
  167. public Proposal setAuthor(@Nullable PersonIdent who) {
  168. author = who;
  169. return this;
  170. }
  171. /** @return optional message for the commit log of the RefTree. */
  172. @Nullable
  173. public String getMessage() {
  174. return message;
  175. }
  176. /**
  177. * Set the message to appear in the commit log of the RefTree.
  178. *
  179. * @param msg
  180. * message text for the commit.
  181. * @return {@code this}
  182. */
  183. public Proposal setMessage(@Nullable String msg) {
  184. message = msg != null && !msg.isEmpty() ? msg : null;
  185. return this;
  186. }
  187. /** @return optional certificate signing the references. */
  188. @Nullable
  189. public PushCertificate getPushCertificate() {
  190. return pushCert;
  191. }
  192. /**
  193. * Set the push certificate signing the references.
  194. *
  195. * @param cert
  196. * certificate, may be null.
  197. * @return {@code this}
  198. */
  199. public Proposal setPushCertificate(@Nullable PushCertificate cert) {
  200. pushCert = cert;
  201. return this;
  202. }
  203. /**
  204. * @return timestamps that Ketch must block for. These may have been used as
  205. * commit times inside the objects involved in the proposal.
  206. */
  207. public List<ProposedTimestamp> getProposedTimestamps() {
  208. if (timestamps != null) {
  209. return timestamps;
  210. }
  211. return Collections.emptyList();
  212. }
  213. /**
  214. * Request the proposal to wait for the affected timestamps to resolve.
  215. *
  216. * @param ts
  217. * @return {@code this}.
  218. */
  219. public Proposal addProposedTimestamp(ProposedTimestamp ts) {
  220. if (timestamps == null) {
  221. timestamps = new ArrayList<>(4);
  222. }
  223. timestamps.add(ts);
  224. return this;
  225. }
  226. /**
  227. * Add a callback to be invoked when the proposal is done.
  228. * <p>
  229. * A proposal is done when it has entered either {@link State#EXECUTED} or
  230. * {@link State#ABORTED} state. If the proposal is already done
  231. * {@code callback.run()} is immediately invoked on the caller's thread.
  232. *
  233. * @param callback
  234. * method to run after the proposal is done. The callback may be
  235. * run on a Ketch system thread and should be completed quickly.
  236. */
  237. public void addListener(Runnable callback) {
  238. boolean runNow = false;
  239. synchronized (state) {
  240. if (state.get().isDone()) {
  241. runNow = true;
  242. } else {
  243. listeners.add(callback);
  244. }
  245. }
  246. if (runNow) {
  247. callback.run();
  248. }
  249. }
  250. /** Set command result as OK. */
  251. void success() {
  252. for (Command c : commands) {
  253. if (c.getResult() == NOT_ATTEMPTED) {
  254. c.setResult(OK);
  255. }
  256. }
  257. notifyState(EXECUTED);
  258. }
  259. /** Mark commands as "transaction aborted". */
  260. void abort() {
  261. Command.abort(commands, null);
  262. notifyState(ABORTED);
  263. }
  264. /** @return read the current state of the proposal. */
  265. public State getState() {
  266. return state.get();
  267. }
  268. /**
  269. * @return {@code true} if the proposal was attempted. A true value does not
  270. * mean consensus was reached, only that the proposal was considered
  271. * and will not be making any more progress beyond its current
  272. * state.
  273. */
  274. public boolean isDone() {
  275. return state.get().isDone();
  276. }
  277. /**
  278. * Wait for the proposal to be attempted and {@link #isDone()} to be true.
  279. *
  280. * @throws InterruptedException
  281. * caller was interrupted before proposal executed.
  282. */
  283. public void await() throws InterruptedException {
  284. synchronized (state) {
  285. while (!state.get().isDone()) {
  286. state.wait();
  287. }
  288. }
  289. }
  290. /**
  291. * Wait for the proposal to be attempted and {@link #isDone()} to be true.
  292. *
  293. * @param wait
  294. * how long to wait.
  295. * @param unit
  296. * unit describing the wait time.
  297. * @return true if the proposal is done; false if the method timed out.
  298. * @throws InterruptedException
  299. * caller was interrupted before proposal executed.
  300. */
  301. public boolean await(long wait, TimeUnit unit) throws InterruptedException {
  302. synchronized (state) {
  303. if (state.get().isDone()) {
  304. return true;
  305. }
  306. state.wait(unit.toMillis(wait));
  307. return state.get().isDone();
  308. }
  309. }
  310. /**
  311. * Wait for the proposal to exit a state.
  312. *
  313. * @param notIn
  314. * state the proposal should not be in to return.
  315. * @param wait
  316. * how long to wait.
  317. * @param unit
  318. * unit describing the wait time.
  319. * @return true if the proposal exited the state; false on time out.
  320. * @throws InterruptedException
  321. * caller was interrupted before proposal executed.
  322. */
  323. public boolean awaitStateChange(State notIn, long wait, TimeUnit unit)
  324. throws InterruptedException {
  325. synchronized (state) {
  326. if (state.get() != notIn) {
  327. return true;
  328. }
  329. state.wait(unit.toMillis(wait));
  330. return state.get() != notIn;
  331. }
  332. }
  333. void notifyState(State s) {
  334. synchronized (state) {
  335. state.set(s);
  336. state.notifyAll();
  337. }
  338. if (s.isDone()) {
  339. for (Runnable callback : listeners) {
  340. callback.run();
  341. }
  342. listeners.clear();
  343. }
  344. }
  345. @Override
  346. public String toString() {
  347. StringBuilder s = new StringBuilder();
  348. s.append("Ketch Proposal {\n"); //$NON-NLS-1$
  349. s.append(" ").append(state.get()).append('\n'); //$NON-NLS-1$
  350. if (author != null) {
  351. s.append(" author ").append(author).append('\n'); //$NON-NLS-1$
  352. }
  353. if (message != null) {
  354. s.append(" message ").append(message).append('\n'); //$NON-NLS-1$
  355. }
  356. for (Command c : commands) {
  357. s.append(" "); //$NON-NLS-1$
  358. format(s, c.getOldRef(), "CREATE"); //$NON-NLS-1$
  359. s.append(' ');
  360. format(s, c.getNewRef(), "DELETE"); //$NON-NLS-1$
  361. s.append(' ').append(c.getRefName());
  362. if (c.getResult() != ReceiveCommand.Result.NOT_ATTEMPTED) {
  363. s.append(' ').append(c.getResult()); // $NON-NLS-1$
  364. }
  365. s.append('\n');
  366. }
  367. s.append('}');
  368. return s.toString();
  369. }
  370. private static void format(StringBuilder s, @Nullable Ref r, String n) {
  371. if (r == null) {
  372. s.append(n);
  373. } else if (r.isSymbolic()) {
  374. s.append(r.getTarget().getName());
  375. } else {
  376. ObjectId id = r.getObjectId();
  377. if (id != null) {
  378. s.append(id.abbreviate(8).name());
  379. }
  380. }
  381. }
  382. }