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.

ProposalRound.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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.RUNNING;
  45. import java.io.IOException;
  46. import java.time.Duration;
  47. import java.util.ArrayList;
  48. import java.util.Collections;
  49. import java.util.HashMap;
  50. import java.util.HashSet;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.Set;
  54. import java.util.concurrent.TimeoutException;
  55. import java.util.stream.Collectors;
  56. import org.eclipse.jgit.annotations.Nullable;
  57. import org.eclipse.jgit.internal.storage.reftree.Command;
  58. import org.eclipse.jgit.internal.storage.reftree.RefTree;
  59. import org.eclipse.jgit.lib.CommitBuilder;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ObjectInserter;
  62. import org.eclipse.jgit.lib.PersonIdent;
  63. import org.eclipse.jgit.lib.Ref;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.revwalk.RevCommit;
  66. import org.eclipse.jgit.revwalk.RevWalk;
  67. import org.eclipse.jgit.transport.ReceiveCommand;
  68. import org.eclipse.jgit.util.time.ProposedTimestamp;
  69. /** A {@link Round} that aggregates and sends user {@link Proposal}s. */
  70. class ProposalRound extends Round {
  71. private final List<Proposal> todo;
  72. private RefTree queuedTree;
  73. ProposalRound(KetchLeader leader, LogIndex head, List<Proposal> todo,
  74. @Nullable RefTree tree) {
  75. super(leader, head);
  76. this.todo = todo;
  77. if (tree != null && canCombine(todo)) {
  78. this.queuedTree = tree;
  79. } else {
  80. leader.roundHoldsReferenceToRefTree = false;
  81. }
  82. }
  83. private static boolean canCombine(List<Proposal> todo) {
  84. Proposal first = todo.get(0);
  85. for (int i = 1; i < todo.size(); i++) {
  86. if (!canCombine(first, todo.get(i))) {
  87. return false;
  88. }
  89. }
  90. return true;
  91. }
  92. private static boolean canCombine(Proposal a, Proposal b) {
  93. String aMsg = nullToEmpty(a.getMessage());
  94. String bMsg = nullToEmpty(b.getMessage());
  95. return aMsg.equals(bMsg) && canCombine(a.getAuthor(), b.getAuthor());
  96. }
  97. private static String nullToEmpty(@Nullable String str) {
  98. return str != null ? str : ""; //$NON-NLS-1$
  99. }
  100. private static boolean canCombine(@Nullable PersonIdent a,
  101. @Nullable PersonIdent b) {
  102. if (a != null && b != null) {
  103. // Same name and email address. Combine timestamp as the two
  104. // proposals are running concurrently and appear together or
  105. // not at all from the point of view of an outside reader.
  106. return a.getName().equals(b.getName())
  107. && a.getEmailAddress().equals(b.getEmailAddress());
  108. }
  109. // If a and b are null, both will be the system identity.
  110. return a == null && b == null;
  111. }
  112. void start() throws IOException {
  113. for (Proposal p : todo) {
  114. p.notifyState(RUNNING);
  115. }
  116. try {
  117. ObjectId id;
  118. try (Repository git = leader.openRepository();
  119. ProposedTimestamp ts = getSystem().getClock().propose()) {
  120. id = insertProposals(git, ts);
  121. blockUntil(ts);
  122. }
  123. runAsync(id);
  124. } catch (NoOp e) {
  125. for (Proposal p : todo) {
  126. p.success();
  127. }
  128. leader.lock.lock();
  129. try {
  130. leader.nextRound();
  131. } finally {
  132. leader.lock.unlock();
  133. }
  134. } catch (IOException e) {
  135. abort();
  136. throw e;
  137. }
  138. }
  139. private ObjectId insertProposals(Repository git, ProposedTimestamp ts)
  140. throws IOException, NoOp {
  141. ObjectId id;
  142. try (ObjectInserter inserter = git.newObjectInserter()) {
  143. // TODO(sop) Process signed push certificates.
  144. if (queuedTree != null) {
  145. id = insertSingleProposal(git, ts, inserter);
  146. } else {
  147. id = insertMultiProposal(git, ts, inserter);
  148. }
  149. stageCommands = makeStageList(git, inserter);
  150. inserter.flush();
  151. }
  152. return id;
  153. }
  154. private ObjectId insertSingleProposal(Repository git, ProposedTimestamp ts,
  155. ObjectInserter inserter) throws IOException, NoOp {
  156. // Fast path: tree is passed in with all proposals applied.
  157. ObjectId treeId = queuedTree.writeTree(inserter);
  158. queuedTree = null;
  159. leader.roundHoldsReferenceToRefTree = false;
  160. if (!ObjectId.zeroId().equals(acceptedOldIndex)) {
  161. try (RevWalk rw = new RevWalk(git)) {
  162. RevCommit c = rw.parseCommit(acceptedOldIndex);
  163. if (treeId.equals(c.getTree())) {
  164. throw new NoOp();
  165. }
  166. }
  167. }
  168. Proposal p = todo.get(0);
  169. CommitBuilder b = new CommitBuilder();
  170. b.setTreeId(treeId);
  171. if (!ObjectId.zeroId().equals(acceptedOldIndex)) {
  172. b.setParentId(acceptedOldIndex);
  173. }
  174. b.setCommitter(leader.getSystem().newCommitter(ts));
  175. b.setAuthor(p.getAuthor() != null ? p.getAuthor() : b.getCommitter());
  176. b.setMessage(message(p));
  177. return inserter.insert(b);
  178. }
  179. private ObjectId insertMultiProposal(Repository git, ProposedTimestamp ts,
  180. ObjectInserter inserter) throws IOException, NoOp {
  181. // The tree was not passed in, or there are multiple proposals
  182. // each needing their own commit. Reset the tree and replay each
  183. // proposal in order as individual commits.
  184. ObjectId lastIndex = acceptedOldIndex;
  185. ObjectId oldTreeId;
  186. RefTree tree;
  187. if (ObjectId.zeroId().equals(lastIndex)) {
  188. oldTreeId = ObjectId.zeroId();
  189. tree = RefTree.newEmptyTree();
  190. } else {
  191. try (RevWalk rw = new RevWalk(git)) {
  192. RevCommit c = rw.parseCommit(lastIndex);
  193. oldTreeId = c.getTree();
  194. tree = RefTree.read(rw.getObjectReader(), c.getTree());
  195. }
  196. }
  197. PersonIdent committer = leader.getSystem().newCommitter(ts);
  198. for (Proposal p : todo) {
  199. if (!tree.apply(p.getCommands())) {
  200. // This should not occur, previously during queuing the
  201. // commands were successfully applied to the pending tree.
  202. // Abort the entire round.
  203. throw new IOException(
  204. KetchText.get().queuedProposalFailedToApply);
  205. }
  206. ObjectId treeId = tree.writeTree(inserter);
  207. if (treeId.equals(oldTreeId)) {
  208. continue;
  209. }
  210. CommitBuilder b = new CommitBuilder();
  211. b.setTreeId(treeId);
  212. if (!ObjectId.zeroId().equals(lastIndex)) {
  213. b.setParentId(lastIndex);
  214. }
  215. b.setAuthor(p.getAuthor() != null ? p.getAuthor() : committer);
  216. b.setCommitter(committer);
  217. b.setMessage(message(p));
  218. lastIndex = inserter.insert(b);
  219. }
  220. if (lastIndex.equals(acceptedOldIndex)) {
  221. throw new NoOp();
  222. }
  223. return lastIndex;
  224. }
  225. private String message(Proposal p) {
  226. StringBuilder m = new StringBuilder();
  227. String msg = p.getMessage();
  228. if (msg != null && !msg.isEmpty()) {
  229. m.append(msg);
  230. while (m.length() < 2 || m.charAt(m.length() - 2) != '\n'
  231. || m.charAt(m.length() - 1) != '\n') {
  232. m.append('\n');
  233. }
  234. }
  235. m.append(KetchConstants.TERM.getName())
  236. .append(": ") //$NON-NLS-1$
  237. .append(leader.getTerm());
  238. return m.toString();
  239. }
  240. void abort() {
  241. for (Proposal p : todo) {
  242. p.abort();
  243. }
  244. }
  245. void success() {
  246. for (Proposal p : todo) {
  247. p.success();
  248. }
  249. }
  250. private List<ReceiveCommand> makeStageList(Repository git,
  251. ObjectInserter inserter) throws IOException {
  252. // For each branch, collapse consecutive updates to only most recent,
  253. // avoiding sending multiple objects in a rapid fast-forward chain, or
  254. // rewritten content.
  255. Map<String, ObjectId> byRef = new HashMap<>();
  256. for (Proposal p : todo) {
  257. for (Command c : p.getCommands()) {
  258. Ref n = c.getNewRef();
  259. if (n != null && !n.isSymbolic()) {
  260. byRef.put(n.getName(), n.getObjectId());
  261. }
  262. }
  263. }
  264. if (byRef.isEmpty()) {
  265. return Collections.emptyList();
  266. }
  267. Set<ObjectId> newObjs = new HashSet<>(byRef.values());
  268. StageBuilder b = new StageBuilder(
  269. leader.getSystem().getTxnStage(),
  270. acceptedNewIndex);
  271. return b.makeStageList(newObjs, git, inserter);
  272. }
  273. private void blockUntil(ProposedTimestamp ts)
  274. throws TimeIsUncertainException {
  275. List<ProposedTimestamp> times = todo.stream()
  276. .flatMap(p -> p.getProposedTimestamps().stream())
  277. .collect(Collectors.toCollection(ArrayList::new));
  278. times.add(ts);
  279. try {
  280. Duration maxWait = getSystem().getMaxWaitForMonotonicClock();
  281. ProposedTimestamp.blockUntil(times, maxWait);
  282. } catch (InterruptedException | TimeoutException e) {
  283. throw new TimeIsUncertainException(e);
  284. }
  285. }
  286. private static class NoOp extends Exception {
  287. private static final long serialVersionUID = 1L;
  288. }
  289. }