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.

ReftableBatchRefUpdate.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /*
  2. * Copyright (C) 2017, 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.storage.dfs;
  44. import static org.eclipse.jgit.internal.storage.pack.PackExt.REFTABLE;
  45. import static org.eclipse.jgit.lib.Ref.Storage.NEW;
  46. import static org.eclipse.jgit.lib.Ref.Storage.PACKED;
  47. import static org.eclipse.jgit.transport.ReceiveCommand.Result.LOCK_FAILURE;
  48. import static org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED;
  49. import static org.eclipse.jgit.transport.ReceiveCommand.Result.OK;
  50. import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_MISSING_OBJECT;
  51. import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_NONFASTFORWARD;
  52. import static org.eclipse.jgit.transport.ReceiveCommand.Type.UPDATE_NONFASTFORWARD;
  53. import java.io.ByteArrayOutputStream;
  54. import java.io.IOException;
  55. import java.io.OutputStream;
  56. import java.util.ArrayList;
  57. import java.util.Collections;
  58. import java.util.HashMap;
  59. import java.util.HashSet;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.Set;
  63. import java.util.concurrent.locks.ReentrantLock;
  64. import org.eclipse.jgit.annotations.Nullable;
  65. import org.eclipse.jgit.errors.MissingObjectException;
  66. import org.eclipse.jgit.internal.storage.dfs.DfsObjDatabase.PackSource;
  67. import org.eclipse.jgit.internal.storage.io.BlockSource;
  68. import org.eclipse.jgit.internal.storage.pack.PackExt;
  69. import org.eclipse.jgit.internal.storage.reftable.RefCursor;
  70. import org.eclipse.jgit.internal.storage.reftable.Reftable;
  71. import org.eclipse.jgit.internal.storage.reftable.ReftableCompactor;
  72. import org.eclipse.jgit.internal.storage.reftable.ReftableConfig;
  73. import org.eclipse.jgit.internal.storage.reftable.ReftableReader;
  74. import org.eclipse.jgit.internal.storage.reftable.ReftableWriter;
  75. import org.eclipse.jgit.lib.AnyObjectId;
  76. import org.eclipse.jgit.lib.BatchRefUpdate;
  77. import org.eclipse.jgit.lib.ObjectId;
  78. import org.eclipse.jgit.lib.ObjectIdRef;
  79. import org.eclipse.jgit.lib.PersonIdent;
  80. import org.eclipse.jgit.lib.ProgressMonitor;
  81. import org.eclipse.jgit.lib.Ref;
  82. import org.eclipse.jgit.lib.ReflogEntry;
  83. import org.eclipse.jgit.lib.SymbolicRef;
  84. import org.eclipse.jgit.revwalk.RevObject;
  85. import org.eclipse.jgit.revwalk.RevTag;
  86. import org.eclipse.jgit.revwalk.RevWalk;
  87. import org.eclipse.jgit.transport.ReceiveCommand;
  88. /** {@link BatchRefUpdate} for {@link DfsReftableDatabase}. */
  89. public class ReftableBatchRefUpdate extends BatchRefUpdate {
  90. private static final int AVG_BYTES = 36;
  91. private final DfsReftableDatabase refdb;
  92. private final DfsObjDatabase odb;
  93. private final ReentrantLock lock;
  94. private final ReftableConfig reftableConfig;
  95. /**
  96. * Initialize batch update.
  97. *
  98. * @param refdb
  99. * database the update will modify.
  100. * @param odb
  101. * object database to store the reftable.
  102. */
  103. protected ReftableBatchRefUpdate(DfsReftableDatabase refdb,
  104. DfsObjDatabase odb) {
  105. super(refdb);
  106. this.refdb = refdb;
  107. this.odb = odb;
  108. lock = refdb.getLock();
  109. reftableConfig = refdb.getReftableConfig();
  110. }
  111. @Override
  112. public void execute(RevWalk rw, ProgressMonitor pm, List<String> options) {
  113. List<ReceiveCommand> pending = getPending();
  114. if (pending.isEmpty()) {
  115. return;
  116. }
  117. if (options != null) {
  118. setPushOptions(options);
  119. }
  120. try {
  121. if (!checkObjectExistence(rw, pending)) {
  122. return;
  123. }
  124. if (!checkNonFastForwards(rw, pending)) {
  125. return;
  126. }
  127. lock.lock();
  128. try {
  129. Reftable table = refdb.reader();
  130. if (!checkExpected(table, pending)) {
  131. return;
  132. }
  133. if (!checkConflicting(pending)) {
  134. return;
  135. }
  136. if (!blockUntilTimestamps(MAX_WAIT)) {
  137. return;
  138. }
  139. applyUpdates(rw, pending);
  140. for (ReceiveCommand cmd : pending) {
  141. cmd.setResult(OK);
  142. }
  143. } finally {
  144. lock.unlock();
  145. }
  146. } catch (IOException e) {
  147. pending.get(0).setResult(LOCK_FAILURE, "io error"); //$NON-NLS-1$
  148. ReceiveCommand.abort(pending);
  149. }
  150. }
  151. private List<ReceiveCommand> getPending() {
  152. return ReceiveCommand.filter(getCommands(), NOT_ATTEMPTED);
  153. }
  154. private boolean checkObjectExistence(RevWalk rw,
  155. List<ReceiveCommand> pending) throws IOException {
  156. for (ReceiveCommand cmd : pending) {
  157. try {
  158. if (!cmd.getNewId().equals(ObjectId.zeroId())) {
  159. rw.parseAny(cmd.getNewId());
  160. }
  161. } catch (MissingObjectException e) {
  162. // ReceiveCommand#setResult(Result) converts REJECTED to
  163. // REJECTED_NONFASTFORWARD, even though that result is also
  164. // used for a missing object. Eagerly handle this case so we
  165. // can set the right result.
  166. cmd.setResult(REJECTED_MISSING_OBJECT);
  167. ReceiveCommand.abort(pending);
  168. return false;
  169. }
  170. }
  171. return true;
  172. }
  173. private boolean checkNonFastForwards(RevWalk rw,
  174. List<ReceiveCommand> pending) throws IOException {
  175. if (isAllowNonFastForwards()) {
  176. return true;
  177. }
  178. for (ReceiveCommand cmd : pending) {
  179. cmd.updateType(rw);
  180. if (cmd.getType() == UPDATE_NONFASTFORWARD) {
  181. cmd.setResult(REJECTED_NONFASTFORWARD);
  182. ReceiveCommand.abort(pending);
  183. return false;
  184. }
  185. }
  186. return true;
  187. }
  188. private boolean checkConflicting(List<ReceiveCommand> pending)
  189. throws IOException {
  190. Set<String> names = new HashSet<>();
  191. for (ReceiveCommand cmd : pending) {
  192. names.add(cmd.getRefName());
  193. }
  194. boolean ok = true;
  195. for (ReceiveCommand cmd : pending) {
  196. String name = cmd.getRefName();
  197. if (refdb.isNameConflicting(name)) {
  198. cmd.setResult(LOCK_FAILURE);
  199. ok = false;
  200. } else {
  201. int s = name.lastIndexOf('/');
  202. while (0 < s) {
  203. if (names.contains(name.substring(0, s))) {
  204. cmd.setResult(LOCK_FAILURE);
  205. ok = false;
  206. break;
  207. }
  208. s = name.lastIndexOf('/', s - 1);
  209. }
  210. }
  211. }
  212. if (!ok && isAtomic()) {
  213. ReceiveCommand.abort(pending);
  214. return false;
  215. }
  216. return ok;
  217. }
  218. private boolean checkExpected(Reftable table, List<ReceiveCommand> pending)
  219. throws IOException {
  220. for (ReceiveCommand cmd : pending) {
  221. Ref ref;
  222. try (RefCursor rc = table.seekRef(cmd.getRefName())) {
  223. ref = rc.next() ? rc.getRef() : null;
  224. }
  225. if (!matchOld(cmd, ref)) {
  226. cmd.setResult(LOCK_FAILURE);
  227. if (isAtomic()) {
  228. ReceiveCommand.abort(pending);
  229. return false;
  230. }
  231. }
  232. }
  233. return true;
  234. }
  235. private static boolean matchOld(ReceiveCommand cmd, @Nullable Ref ref) {
  236. if (ref == null) {
  237. return AnyObjectId.equals(ObjectId.zeroId(), cmd.getOldId())
  238. && cmd.getOldSymref() == null;
  239. } else if (ref.isSymbolic()) {
  240. return ref.getTarget().getName().equals(cmd.getOldSymref());
  241. }
  242. ObjectId id = ref.getObjectId();
  243. if (id == null) {
  244. id = ObjectId.zeroId();
  245. }
  246. return cmd.getOldId().equals(id);
  247. }
  248. private void applyUpdates(RevWalk rw, List<ReceiveCommand> pending)
  249. throws IOException {
  250. List<Ref> newRefs = toNewRefs(rw, pending);
  251. long updateIndex = nextUpdateIndex();
  252. Set<DfsPackDescription> prune = Collections.emptySet();
  253. DfsPackDescription pack = odb.newPack(PackSource.INSERT);
  254. try (DfsOutputStream out = odb.writeFile(pack, REFTABLE)) {
  255. ReftableConfig cfg = DfsPackCompactor
  256. .configureReftable(reftableConfig, out);
  257. ReftableWriter.Stats stats;
  258. if (refdb.compactDuringCommit()
  259. && newRefs.size() * AVG_BYTES <= cfg.getRefBlockSize()
  260. && canCompactTopOfStack(cfg)) {
  261. ByteArrayOutputStream tmp = new ByteArrayOutputStream();
  262. write(tmp, cfg, updateIndex, newRefs, pending);
  263. stats = compactTopOfStack(out, cfg, tmp.toByteArray());
  264. prune = toPruneTopOfStack();
  265. } else {
  266. stats = write(out, cfg, updateIndex, newRefs, pending);
  267. }
  268. pack.addFileExt(REFTABLE);
  269. pack.setReftableStats(stats);
  270. }
  271. odb.commitPack(Collections.singleton(pack), prune);
  272. odb.addReftable(pack, prune);
  273. refdb.clearCache();
  274. }
  275. private ReftableWriter.Stats write(OutputStream os, ReftableConfig cfg,
  276. long updateIndex, List<Ref> newRefs, List<ReceiveCommand> pending)
  277. throws IOException {
  278. ReftableWriter writer = new ReftableWriter(cfg)
  279. .setMinUpdateIndex(updateIndex).setMaxUpdateIndex(updateIndex)
  280. .begin(os).sortAndWriteRefs(newRefs);
  281. if (!isRefLogDisabled()) {
  282. writeLog(writer, updateIndex, pending);
  283. }
  284. writer.finish();
  285. return writer.getStats();
  286. }
  287. private void writeLog(ReftableWriter writer, long updateIndex,
  288. List<ReceiveCommand> pending) throws IOException {
  289. Map<String, ReceiveCommand> cmds = new HashMap<>();
  290. List<String> byName = new ArrayList<>(pending.size());
  291. for (ReceiveCommand cmd : pending) {
  292. cmds.put(cmd.getRefName(), cmd);
  293. byName.add(cmd.getRefName());
  294. }
  295. Collections.sort(byName);
  296. PersonIdent ident = getRefLogIdent();
  297. if (ident == null) {
  298. ident = new PersonIdent(refdb.getRepository());
  299. }
  300. for (String name : byName) {
  301. ReceiveCommand cmd = cmds.get(name);
  302. if (isRefLogDisabled(cmd)) {
  303. continue;
  304. }
  305. String msg = getRefLogMessage(cmd);
  306. if (isRefLogIncludingResult(cmd)) {
  307. String strResult = toResultString(cmd);
  308. if (strResult != null) {
  309. msg = msg.isEmpty() ? strResult : msg + ": " + strResult; //$NON-NLS-1$
  310. }
  311. }
  312. writer.writeLog(name, updateIndex, ident, cmd.getOldId(),
  313. cmd.getNewId(), msg);
  314. }
  315. }
  316. private String toResultString(ReceiveCommand cmd) {
  317. switch (cmd.getType()) {
  318. case CREATE:
  319. return ReflogEntry.PREFIX_CREATED;
  320. case UPDATE:
  321. // Match the behavior of a single RefUpdate. In that case, setting
  322. // the force bit completely bypasses the potentially expensive
  323. // isMergedInto check, by design, so the reflog message may be
  324. // inaccurate.
  325. //
  326. // Similarly, this class bypasses the isMergedInto checks when the
  327. // force bit is set, meaning we can't actually distinguish between
  328. // UPDATE and UPDATE_NONFASTFORWARD when isAllowNonFastForwards()
  329. // returns true.
  330. return isAllowNonFastForwards() ? ReflogEntry.PREFIX_FORCED_UPDATE
  331. : ReflogEntry.PREFIX_FAST_FORWARD;
  332. case UPDATE_NONFASTFORWARD:
  333. return ReflogEntry.PREFIX_FORCED_UPDATE;
  334. default:
  335. return null;
  336. }
  337. }
  338. private static List<Ref> toNewRefs(RevWalk rw, List<ReceiveCommand> pending)
  339. throws IOException {
  340. List<Ref> refs = new ArrayList<>(pending.size());
  341. for (ReceiveCommand cmd : pending) {
  342. String name = cmd.getRefName();
  343. ObjectId newId = cmd.getNewId();
  344. String newSymref = cmd.getNewSymref();
  345. if (AnyObjectId.equals(ObjectId.zeroId(), newId)
  346. && newSymref == null) {
  347. refs.add(new ObjectIdRef.Unpeeled(NEW, name, null));
  348. continue;
  349. } else if (newSymref != null) {
  350. refs.add(new SymbolicRef(name,
  351. new ObjectIdRef.Unpeeled(NEW, newSymref, null)));
  352. continue;
  353. }
  354. RevObject obj = rw.parseAny(newId);
  355. RevObject peel = null;
  356. if (obj instanceof RevTag) {
  357. peel = rw.peel(obj);
  358. }
  359. if (peel != null) {
  360. refs.add(new ObjectIdRef.PeeledTag(PACKED, name, newId,
  361. peel.copy()));
  362. } else {
  363. refs.add(new ObjectIdRef.PeeledNonTag(PACKED, name, newId));
  364. }
  365. }
  366. return refs;
  367. }
  368. private long nextUpdateIndex() throws IOException {
  369. long updateIndex = 0;
  370. for (Reftable r : refdb.stack().readers()) {
  371. if (r instanceof ReftableReader) {
  372. updateIndex = Math.max(updateIndex,
  373. ((ReftableReader) r).maxUpdateIndex());
  374. }
  375. }
  376. return updateIndex + 1;
  377. }
  378. private boolean canCompactTopOfStack(ReftableConfig cfg)
  379. throws IOException {
  380. ReftableStack stack = refdb.stack();
  381. List<Reftable> readers = stack.readers();
  382. if (readers.isEmpty()) {
  383. return false;
  384. }
  385. int lastIdx = readers.size() - 1;
  386. DfsReftable last = stack.files().get(lastIdx);
  387. DfsPackDescription desc = last.getPackDescription();
  388. if (desc.getPackSource() != PackSource.INSERT
  389. || !packOnlyContainsReftable(desc)) {
  390. return false;
  391. }
  392. Reftable table = readers.get(lastIdx);
  393. int bs = cfg.getRefBlockSize();
  394. return table instanceof ReftableReader
  395. && ((ReftableReader) table).size() <= 3 * bs;
  396. }
  397. private ReftableWriter.Stats compactTopOfStack(OutputStream out,
  398. ReftableConfig cfg, byte[] newTable) throws IOException {
  399. List<Reftable> stack = refdb.stack().readers();
  400. Reftable last = stack.get(stack.size() - 1);
  401. List<Reftable> tables = new ArrayList<>(2);
  402. tables.add(last);
  403. tables.add(new ReftableReader(BlockSource.from(newTable)));
  404. ReftableCompactor compactor = new ReftableCompactor();
  405. compactor.setConfig(cfg);
  406. compactor.addAll(tables);
  407. compactor.compact(out);
  408. return compactor.getStats();
  409. }
  410. private Set<DfsPackDescription> toPruneTopOfStack() throws IOException {
  411. List<DfsReftable> stack = refdb.stack().files();
  412. DfsReftable last = stack.get(stack.size() - 1);
  413. return Collections.singleton(last.getPackDescription());
  414. }
  415. private boolean packOnlyContainsReftable(DfsPackDescription desc) {
  416. for (PackExt ext : PackExt.values()) {
  417. if (ext != REFTABLE && desc.hasFileExt(ext)) {
  418. return false;
  419. }
  420. }
  421. return true;
  422. }
  423. }