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.

PackWriter.java 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.storage.pack;
  45. import static org.eclipse.jgit.storage.pack.StoredObjectRepresentation.PACK_DELTA;
  46. import static org.eclipse.jgit.storage.pack.StoredObjectRepresentation.PACK_WHOLE;
  47. import java.io.IOException;
  48. import java.io.OutputStream;
  49. import java.security.MessageDigest;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Collection;
  54. import java.util.Collections;
  55. import java.util.Comparator;
  56. import java.util.HashMap;
  57. import java.util.HashSet;
  58. import java.util.Iterator;
  59. import java.util.LinkedList;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.Set;
  63. import java.util.concurrent.ExecutionException;
  64. import java.util.concurrent.Executor;
  65. import java.util.concurrent.ExecutorService;
  66. import java.util.concurrent.Executors;
  67. import java.util.concurrent.Future;
  68. import java.util.concurrent.TimeUnit;
  69. import java.util.zip.Deflater;
  70. import java.util.zip.DeflaterOutputStream;
  71. import org.eclipse.jgit.JGitText;
  72. import org.eclipse.jgit.errors.CorruptObjectException;
  73. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  74. import org.eclipse.jgit.errors.LargeObjectException;
  75. import org.eclipse.jgit.errors.MissingObjectException;
  76. import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
  77. import org.eclipse.jgit.lib.AnyObjectId;
  78. import org.eclipse.jgit.lib.AsyncObjectSizeQueue;
  79. import org.eclipse.jgit.lib.Constants;
  80. import org.eclipse.jgit.lib.NullProgressMonitor;
  81. import org.eclipse.jgit.lib.ObjectId;
  82. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  83. import org.eclipse.jgit.lib.ObjectLoader;
  84. import org.eclipse.jgit.lib.ObjectReader;
  85. import org.eclipse.jgit.lib.ProgressMonitor;
  86. import org.eclipse.jgit.lib.Repository;
  87. import org.eclipse.jgit.lib.ThreadSafeProgressMonitor;
  88. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  89. import org.eclipse.jgit.revwalk.ObjectWalk;
  90. import org.eclipse.jgit.revwalk.RevCommit;
  91. import org.eclipse.jgit.revwalk.RevFlag;
  92. import org.eclipse.jgit.revwalk.RevFlagSet;
  93. import org.eclipse.jgit.revwalk.RevObject;
  94. import org.eclipse.jgit.revwalk.RevSort;
  95. import org.eclipse.jgit.revwalk.RevTag;
  96. import org.eclipse.jgit.revwalk.RevTree;
  97. import org.eclipse.jgit.storage.file.PackIndexWriter;
  98. import org.eclipse.jgit.util.TemporaryBuffer;
  99. /**
  100. * <p>
  101. * PackWriter class is responsible for generating pack files from specified set
  102. * of objects from repository. This implementation produce pack files in format
  103. * version 2.
  104. * </p>
  105. * <p>
  106. * Source of objects may be specified in two ways:
  107. * <ul>
  108. * <li>(usually) by providing sets of interesting and uninteresting objects in
  109. * repository - all interesting objects and their ancestors except uninteresting
  110. * objects and their ancestors will be included in pack, or</li>
  111. * <li>by providing iterator of {@link RevObject} specifying exact list and
  112. * order of objects in pack</li>
  113. * </ul>
  114. * Typical usage consists of creating instance intended for some pack,
  115. * configuring options, preparing the list of objects by calling
  116. * {@link #preparePack(Iterator)} or
  117. * {@link #preparePack(ProgressMonitor, Collection, Collection)}, and finally
  118. * producing the stream with {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}.
  119. * </p>
  120. * <p>
  121. * Class provide set of configurable options and {@link ProgressMonitor}
  122. * support, as operations may take a long time for big repositories. Deltas
  123. * searching algorithm is <b>NOT IMPLEMENTED</b> yet - this implementation
  124. * relies only on deltas and objects reuse.
  125. * </p>
  126. * <p>
  127. * This class is not thread safe, it is intended to be used in one thread, with
  128. * one instance per created pack. Subsequent calls to writePack result in
  129. * undefined behavior.
  130. * </p>
  131. */
  132. public class PackWriter {
  133. private static final int PACK_VERSION_GENERATED = 2;
  134. @SuppressWarnings("unchecked")
  135. private final List<ObjectToPack> objectsLists[] = new List[Constants.OBJ_TAG + 1];
  136. {
  137. objectsLists[0] = Collections.<ObjectToPack> emptyList();
  138. objectsLists[Constants.OBJ_COMMIT] = new ArrayList<ObjectToPack>();
  139. objectsLists[Constants.OBJ_TREE] = new ArrayList<ObjectToPack>();
  140. objectsLists[Constants.OBJ_BLOB] = new ArrayList<ObjectToPack>();
  141. objectsLists[Constants.OBJ_TAG] = new ArrayList<ObjectToPack>();
  142. }
  143. private final ObjectIdSubclassMap<ObjectToPack> objectsMap = new ObjectIdSubclassMap<ObjectToPack>();
  144. // edge objects for thin packs
  145. private List<ObjectToPack> edgeObjects = new ArrayList<ObjectToPack>();
  146. private List<CachedPack> cachedPacks = new ArrayList<CachedPack>(2);
  147. private Set<ObjectId> tagTargets = Collections.emptySet();
  148. private Deflater myDeflater;
  149. private final ObjectReader reader;
  150. /** {@link #reader} recast to the reuse interface, if it supports it. */
  151. private final ObjectReuseAsIs reuseSupport;
  152. private final PackConfig config;
  153. private final Statistics stats;
  154. private List<ObjectToPack> sortedByName;
  155. private byte packcsum[];
  156. private boolean deltaBaseAsOffset;
  157. private boolean reuseDeltas;
  158. private boolean reuseDeltaCommits;
  159. private boolean reuseValidate;
  160. private boolean thin;
  161. private boolean useCachedPacks;
  162. private boolean ignoreMissingUninteresting = true;
  163. /**
  164. * Create writer for specified repository.
  165. * <p>
  166. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  167. * {@link #preparePack(ProgressMonitor, Collection, Collection)}.
  168. *
  169. * @param repo
  170. * repository where objects are stored.
  171. */
  172. public PackWriter(final Repository repo) {
  173. this(repo, repo.newObjectReader());
  174. }
  175. /**
  176. * Create a writer to load objects from the specified reader.
  177. * <p>
  178. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  179. * {@link #preparePack(ProgressMonitor, Collection, Collection)}.
  180. *
  181. * @param reader
  182. * reader to read from the repository with.
  183. */
  184. public PackWriter(final ObjectReader reader) {
  185. this(new PackConfig(), reader);
  186. }
  187. /**
  188. * Create writer for specified repository.
  189. * <p>
  190. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  191. * {@link #preparePack(ProgressMonitor, Collection, Collection)}.
  192. *
  193. * @param repo
  194. * repository where objects are stored.
  195. * @param reader
  196. * reader to read from the repository with.
  197. */
  198. public PackWriter(final Repository repo, final ObjectReader reader) {
  199. this(new PackConfig(repo), reader);
  200. }
  201. /**
  202. * Create writer with a specified configuration.
  203. * <p>
  204. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  205. * {@link #preparePack(ProgressMonitor, Collection, Collection)}.
  206. *
  207. * @param config
  208. * configuration for the pack writer.
  209. * @param reader
  210. * reader to read from the repository with.
  211. */
  212. public PackWriter(final PackConfig config, final ObjectReader reader) {
  213. this.config = config;
  214. this.reader = reader;
  215. if (reader instanceof ObjectReuseAsIs)
  216. reuseSupport = ((ObjectReuseAsIs) reader);
  217. else
  218. reuseSupport = null;
  219. deltaBaseAsOffset = config.isDeltaBaseAsOffset();
  220. reuseDeltas = config.isReuseDeltas();
  221. reuseValidate = true; // be paranoid by default
  222. stats = new Statistics();
  223. }
  224. /**
  225. * Check whether writer can store delta base as an offset (new style
  226. * reducing pack size) or should store it as an object id (legacy style,
  227. * compatible with old readers).
  228. *
  229. * Default setting: {@value PackConfig#DEFAULT_DELTA_BASE_AS_OFFSET}
  230. *
  231. * @return true if delta base is stored as an offset; false if it is stored
  232. * as an object id.
  233. */
  234. public boolean isDeltaBaseAsOffset() {
  235. return deltaBaseAsOffset;
  236. }
  237. /**
  238. * Set writer delta base format. Delta base can be written as an offset in a
  239. * pack file (new approach reducing file size) or as an object id (legacy
  240. * approach, compatible with old readers).
  241. *
  242. * Default setting: {@value PackConfig#DEFAULT_DELTA_BASE_AS_OFFSET}
  243. *
  244. * @param deltaBaseAsOffset
  245. * boolean indicating whether delta base can be stored as an
  246. * offset.
  247. */
  248. public void setDeltaBaseAsOffset(boolean deltaBaseAsOffset) {
  249. this.deltaBaseAsOffset = deltaBaseAsOffset;
  250. }
  251. /**
  252. * Check if the writer will reuse commits that are already stored as deltas.
  253. *
  254. * @return true if the writer would reuse commits stored as deltas, assuming
  255. * delta reuse is already enabled.
  256. */
  257. public boolean isReuseDeltaCommits() {
  258. return reuseDeltaCommits;
  259. }
  260. /**
  261. * Set the writer to reuse existing delta versions of commits.
  262. *
  263. * @param reuse
  264. * if true, the writer will reuse any commits stored as deltas.
  265. * By default the writer does not reuse delta commits.
  266. */
  267. public void setReuseDeltaCommits(boolean reuse) {
  268. reuseDeltaCommits = reuse;
  269. }
  270. /**
  271. * Check if the writer validates objects before copying them.
  272. *
  273. * @return true if validation is enabled; false if the reader will handle
  274. * object validation as a side-effect of it consuming the output.
  275. */
  276. public boolean isReuseValidatingObjects() {
  277. return reuseValidate;
  278. }
  279. /**
  280. * Enable (or disable) object validation during packing.
  281. *
  282. * @param validate
  283. * if true the pack writer will validate an object before it is
  284. * put into the output. This additional validation work may be
  285. * necessary to avoid propagating corruption from one local pack
  286. * file to another local pack file.
  287. */
  288. public void setReuseValidatingObjects(boolean validate) {
  289. reuseValidate = validate;
  290. }
  291. /** @return true if this writer is producing a thin pack. */
  292. public boolean isThin() {
  293. return thin;
  294. }
  295. /**
  296. * @param packthin
  297. * a boolean indicating whether writer may pack objects with
  298. * delta base object not within set of objects to pack, but
  299. * belonging to party repository (uninteresting/boundary) as
  300. * determined by set; this kind of pack is used only for
  301. * transport; true - to produce thin pack, false - otherwise.
  302. */
  303. public void setThin(final boolean packthin) {
  304. thin = packthin;
  305. }
  306. /** @return true to reuse cached packs. If true index creation isn't available. */
  307. public boolean isUseCachedPacks() {
  308. return useCachedPacks;
  309. }
  310. /**
  311. * @param useCached
  312. * if set to true and a cached pack is present, it will be
  313. * appended onto the end of a thin-pack, reducing the amount of
  314. * working set space and CPU used by PackWriter. Enabling this
  315. * feature prevents PackWriter from creating an index for the
  316. * newly created pack, so its only suitable for writing to a
  317. * network client, where the client will make the index.
  318. */
  319. public void setUseCachedPacks(boolean useCached) {
  320. useCachedPacks = useCached;
  321. }
  322. /**
  323. * @return true to ignore objects that are uninteresting and also not found
  324. * on local disk; false to throw a {@link MissingObjectException}
  325. * out of {@link #preparePack(ProgressMonitor, Collection, Collection)} if an
  326. * uninteresting object is not in the source repository. By default,
  327. * true, permitting gracefully ignoring of uninteresting objects.
  328. */
  329. public boolean isIgnoreMissingUninteresting() {
  330. return ignoreMissingUninteresting;
  331. }
  332. /**
  333. * @param ignore
  334. * true if writer should ignore non existing uninteresting
  335. * objects during construction set of objects to pack; false
  336. * otherwise - non existing uninteresting objects may cause
  337. * {@link MissingObjectException}
  338. */
  339. public void setIgnoreMissingUninteresting(final boolean ignore) {
  340. ignoreMissingUninteresting = ignore;
  341. }
  342. /**
  343. * Set the tag targets that should be hoisted earlier during packing.
  344. * <p>
  345. * Callers may put objects into this set before invoking any of the
  346. * preparePack methods to influence where an annotated tag's target is
  347. * stored within the resulting pack. Typically these will be clustered
  348. * together, and hoisted earlier in the file even if they are ancient
  349. * revisions, allowing readers to find tag targets with better locality.
  350. *
  351. * @param objects
  352. * objects that annotated tags point at.
  353. */
  354. public void setTagTargets(Set<ObjectId> objects) {
  355. tagTargets = objects;
  356. }
  357. /**
  358. * Returns objects number in a pack file that was created by this writer.
  359. *
  360. * @return number of objects in pack.
  361. */
  362. public long getObjectsNumber() {
  363. return stats.totalObjects;
  364. }
  365. /**
  366. * Prepare the list of objects to be written to the pack stream.
  367. * <p>
  368. * Iterator <b>exactly</b> determines which objects are included in a pack
  369. * and order they appear in pack (except that objects order by type is not
  370. * needed at input). This order should conform general rules of ordering
  371. * objects in git - by recency and path (type and delta-base first is
  372. * internally secured) and responsibility for guaranteeing this order is on
  373. * a caller side. Iterator must return each id of object to write exactly
  374. * once.
  375. * </p>
  376. *
  377. * @param objectsSource
  378. * iterator of object to store in a pack; order of objects within
  379. * each type is important, ordering by type is not needed;
  380. * allowed types for objects are {@link Constants#OBJ_COMMIT},
  381. * {@link Constants#OBJ_TREE}, {@link Constants#OBJ_BLOB} and
  382. * {@link Constants#OBJ_TAG}; objects returned by iterator may be
  383. * later reused by caller as object id and type are internally
  384. * copied in each iteration.
  385. * @throws IOException
  386. * when some I/O problem occur during reading objects.
  387. */
  388. public void preparePack(final Iterator<RevObject> objectsSource)
  389. throws IOException {
  390. while (objectsSource.hasNext()) {
  391. addObject(objectsSource.next());
  392. }
  393. }
  394. /**
  395. * Prepare the list of objects to be written to the pack stream.
  396. * <p>
  397. * Basing on these 2 sets, another set of objects to put in a pack file is
  398. * created: this set consists of all objects reachable (ancestors) from
  399. * interesting objects, except uninteresting objects and their ancestors.
  400. * This method uses class {@link ObjectWalk} extensively to find out that
  401. * appropriate set of output objects and their optimal order in output pack.
  402. * Order is consistent with general git in-pack rules: sort by object type,
  403. * recency, path and delta-base first.
  404. * </p>
  405. *
  406. * @param countingMonitor
  407. * progress during object enumeration.
  408. * @param want
  409. * collection of objects to be marked as interesting (start
  410. * points of graph traversal).
  411. * @param have
  412. * collection of objects to be marked as uninteresting (end
  413. * points of graph traversal).
  414. * @throws IOException
  415. * when some I/O problem occur during reading objects.
  416. */
  417. public void preparePack(ProgressMonitor countingMonitor,
  418. final Collection<? extends ObjectId> want,
  419. final Collection<? extends ObjectId> have) throws IOException {
  420. ObjectWalk ow = new ObjectWalk(reader);
  421. preparePack(countingMonitor, ow, want, have);
  422. }
  423. /**
  424. * Prepare the list of objects to be written to the pack stream.
  425. * <p>
  426. * Basing on these 2 sets, another set of objects to put in a pack file is
  427. * created: this set consists of all objects reachable (ancestors) from
  428. * interesting objects, except uninteresting objects and their ancestors.
  429. * This method uses class {@link ObjectWalk} extensively to find out that
  430. * appropriate set of output objects and their optimal order in output pack.
  431. * Order is consistent with general git in-pack rules: sort by object type,
  432. * recency, path and delta-base first.
  433. * </p>
  434. *
  435. * @param countingMonitor
  436. * progress during object enumeration.
  437. * @param walk
  438. * ObjectWalk to perform enumeration.
  439. * @param interestingObjects
  440. * collection of objects to be marked as interesting (start
  441. * points of graph traversal).
  442. * @param uninterestingObjects
  443. * collection of objects to be marked as uninteresting (end
  444. * points of graph traversal).
  445. * @throws IOException
  446. * when some I/O problem occur during reading objects.
  447. */
  448. public void preparePack(ProgressMonitor countingMonitor,
  449. final ObjectWalk walk,
  450. final Collection<? extends ObjectId> interestingObjects,
  451. final Collection<? extends ObjectId> uninterestingObjects)
  452. throws IOException {
  453. if (countingMonitor == null)
  454. countingMonitor = NullProgressMonitor.INSTANCE;
  455. findObjectsToPack(countingMonitor, walk, interestingObjects,
  456. uninterestingObjects);
  457. }
  458. /**
  459. * Determine if the pack file will contain the requested object.
  460. *
  461. * @param id
  462. * the object to test the existence of.
  463. * @return true if the object will appear in the output pack file.
  464. * @throws IOException
  465. * a cached pack cannot be examined.
  466. */
  467. public boolean willInclude(final AnyObjectId id) throws IOException {
  468. ObjectToPack obj = objectsMap.get(id);
  469. if (obj != null && !obj.isEdge())
  470. return true;
  471. Set<ObjectId> toFind = Collections.singleton(id.toObjectId());
  472. for (CachedPack pack : cachedPacks) {
  473. if (pack.hasObject(toFind).contains(id))
  474. return true;
  475. }
  476. return false;
  477. }
  478. /**
  479. * Lookup the ObjectToPack object for a given ObjectId.
  480. *
  481. * @param id
  482. * the object to find in the pack.
  483. * @return the object we are packing, or null.
  484. */
  485. public ObjectToPack get(AnyObjectId id) {
  486. ObjectToPack obj = objectsMap.get(id);
  487. return obj != null && !obj.isEdge() ? obj : null;
  488. }
  489. /**
  490. * Computes SHA-1 of lexicographically sorted objects ids written in this
  491. * pack, as used to name a pack file in repository.
  492. *
  493. * @return ObjectId representing SHA-1 name of a pack that was created.
  494. */
  495. public ObjectId computeName() {
  496. final byte[] buf = new byte[Constants.OBJECT_ID_LENGTH];
  497. final MessageDigest md = Constants.newMessageDigest();
  498. for (ObjectToPack otp : sortByName()) {
  499. otp.copyRawTo(buf, 0);
  500. md.update(buf, 0, Constants.OBJECT_ID_LENGTH);
  501. }
  502. return ObjectId.fromRaw(md.digest());
  503. }
  504. /**
  505. * Create an index file to match the pack file just written.
  506. * <p>
  507. * This method can only be invoked after {@link #preparePack(Iterator)} or
  508. * {@link #preparePack(ProgressMonitor, Collection, Collection)} has been
  509. * invoked and completed successfully. Writing a corresponding index is an
  510. * optional feature that not all pack users may require.
  511. *
  512. * @param indexStream
  513. * output for the index data. Caller is responsible for closing
  514. * this stream.
  515. * @throws IOException
  516. * the index data could not be written to the supplied stream.
  517. */
  518. public void writeIndex(final OutputStream indexStream) throws IOException {
  519. if (!cachedPacks.isEmpty())
  520. throw new IOException(JGitText.get().cachedPacksPreventsIndexCreation);
  521. final List<ObjectToPack> list = sortByName();
  522. final PackIndexWriter iw;
  523. int indexVersion = config.getIndexVersion();
  524. if (indexVersion <= 0)
  525. iw = PackIndexWriter.createOldestPossible(indexStream, list);
  526. else
  527. iw = PackIndexWriter.createVersion(indexStream, indexVersion);
  528. iw.write(list, packcsum);
  529. }
  530. private List<ObjectToPack> sortByName() {
  531. if (sortedByName == null) {
  532. int cnt = 0;
  533. for (List<ObjectToPack> list : objectsLists)
  534. cnt += list.size();
  535. sortedByName = new ArrayList<ObjectToPack>(cnt);
  536. for (List<ObjectToPack> list : objectsLists) {
  537. for (ObjectToPack otp : list)
  538. sortedByName.add(otp);
  539. }
  540. Collections.sort(sortedByName);
  541. }
  542. return sortedByName;
  543. }
  544. /**
  545. * Write the prepared pack to the supplied stream.
  546. * <p>
  547. * At first, this method collects and sorts objects to pack, then deltas
  548. * search is performed if set up accordingly, finally pack stream is
  549. * written.
  550. * </p>
  551. * <p>
  552. * All reused objects data checksum (Adler32/CRC32) is computed and
  553. * validated against existing checksum.
  554. * </p>
  555. *
  556. * @param compressMonitor
  557. * progress monitor to report object compression work.
  558. * @param writeMonitor
  559. * progress monitor to report the number of objects written.
  560. * @param packStream
  561. * output stream of pack data. The stream should be buffered by
  562. * the caller. The caller is responsible for closing the stream.
  563. * @throws IOException
  564. * an error occurred reading a local object's data to include in
  565. * the pack, or writing compressed object data to the output
  566. * stream.
  567. */
  568. public void writePack(ProgressMonitor compressMonitor,
  569. ProgressMonitor writeMonitor, OutputStream packStream)
  570. throws IOException {
  571. if (compressMonitor == null)
  572. compressMonitor = NullProgressMonitor.INSTANCE;
  573. if (writeMonitor == null)
  574. writeMonitor = NullProgressMonitor.INSTANCE;
  575. if ((reuseDeltas || config.isReuseObjects()) && reuseSupport != null)
  576. searchForReuse(compressMonitor);
  577. if (config.isDeltaCompress())
  578. searchForDeltas(compressMonitor);
  579. final PackOutputStream out = new PackOutputStream(writeMonitor,
  580. packStream, this);
  581. long objCnt = 0;
  582. for (List<ObjectToPack> list : objectsLists)
  583. objCnt += list.size();
  584. for (CachedPack pack : cachedPacks)
  585. objCnt += pack.getObjectCount();
  586. stats.totalObjects = objCnt;
  587. writeMonitor.beginTask(JGitText.get().writingObjects, (int) objCnt);
  588. long writeStart = System.currentTimeMillis();
  589. long headerStart = out.length();
  590. out.writeFileHeader(PACK_VERSION_GENERATED, objCnt);
  591. out.flush();
  592. long headerEnd = out.length();
  593. writeObjects(out);
  594. if (!edgeObjects.isEmpty() || !cachedPacks.isEmpty())
  595. stats.thinPackBytes = out.length() - (headerEnd - headerStart);
  596. for (CachedPack pack : cachedPacks) {
  597. long deltaCnt = pack.getDeltaCount();
  598. stats.reusedObjects += pack.getObjectCount();
  599. stats.reusedDeltas += deltaCnt;
  600. stats.totalDeltas += deltaCnt;
  601. reuseSupport.copyPackAsIs(out, pack);
  602. }
  603. writeChecksum(out);
  604. out.flush();
  605. stats.timeWriting = System.currentTimeMillis() - writeStart;
  606. stats.totalBytes = out.length();
  607. stats.reusedPacks = Collections.unmodifiableList(cachedPacks);
  608. reader.release();
  609. writeMonitor.endTask();
  610. }
  611. /**
  612. * @return description of what this PackWriter did in order to create the
  613. * final pack stream. The object is only available to callers after
  614. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}
  615. */
  616. public Statistics getStatistics() {
  617. return stats;
  618. }
  619. /** Release all resources used by this writer. */
  620. public void release() {
  621. reader.release();
  622. if (myDeflater != null) {
  623. myDeflater.end();
  624. myDeflater = null;
  625. }
  626. }
  627. private void searchForReuse(ProgressMonitor monitor) throws IOException {
  628. int cnt = 0;
  629. for (List<ObjectToPack> list : objectsLists)
  630. cnt += list.size();
  631. long start = System.currentTimeMillis();
  632. monitor.beginTask(JGitText.get().searchForReuse, cnt);
  633. for (List<ObjectToPack> list : objectsLists)
  634. reuseSupport.selectObjectRepresentation(this, monitor, list);
  635. monitor.endTask();
  636. stats.timeSearchingForReuse = System.currentTimeMillis() - start;
  637. }
  638. private void searchForDeltas(ProgressMonitor monitor)
  639. throws MissingObjectException, IncorrectObjectTypeException,
  640. IOException {
  641. // Commits and annotated tags tend to have too many differences to
  642. // really benefit from delta compression. Consequently just don't
  643. // bother examining those types here.
  644. //
  645. ObjectToPack[] list = new ObjectToPack[
  646. objectsLists[Constants.OBJ_TREE].size()
  647. + objectsLists[Constants.OBJ_BLOB].size()
  648. + edgeObjects.size()];
  649. int cnt = 0;
  650. cnt = findObjectsNeedingDelta(list, cnt, Constants.OBJ_TREE);
  651. cnt = findObjectsNeedingDelta(list, cnt, Constants.OBJ_BLOB);
  652. if (cnt == 0)
  653. return;
  654. int nonEdgeCnt = cnt;
  655. // Queue up any edge objects that we might delta against. We won't
  656. // be sending these as we assume the other side has them, but we need
  657. // them in the search phase below.
  658. //
  659. for (ObjectToPack eo : edgeObjects) {
  660. eo.setWeight(0);
  661. list[cnt++] = eo;
  662. }
  663. // Compute the sizes of the objects so we can do a proper sort.
  664. // We let the reader skip missing objects if it chooses. For
  665. // some readers this can be a huge win. We detect missing objects
  666. // by having set the weights above to 0 and allowing the delta
  667. // search code to discover the missing object and skip over it, or
  668. // abort with an exception if we actually had to have it.
  669. //
  670. final long sizingStart = System.currentTimeMillis();
  671. monitor.beginTask(JGitText.get().searchForSizes, cnt);
  672. AsyncObjectSizeQueue<ObjectToPack> sizeQueue = reader.getObjectSize(
  673. Arrays.<ObjectToPack> asList(list).subList(0, cnt), false);
  674. try {
  675. final long limit = config.getBigFileThreshold();
  676. for (;;) {
  677. monitor.update(1);
  678. try {
  679. if (!sizeQueue.next())
  680. break;
  681. } catch (MissingObjectException notFound) {
  682. if (ignoreMissingUninteresting) {
  683. ObjectToPack otp = sizeQueue.getCurrent();
  684. if (otp != null && otp.isEdge()) {
  685. otp.setDoNotDelta(true);
  686. continue;
  687. }
  688. otp = objectsMap.get(notFound.getObjectId());
  689. if (otp != null && otp.isEdge()) {
  690. otp.setDoNotDelta(true);
  691. continue;
  692. }
  693. }
  694. throw notFound;
  695. }
  696. ObjectToPack otp = sizeQueue.getCurrent();
  697. if (otp == null)
  698. otp = objectsMap.get(sizeQueue.getObjectId());
  699. long sz = sizeQueue.getSize();
  700. if (limit <= sz || Integer.MAX_VALUE <= sz)
  701. otp.setDoNotDelta(true); // too big, avoid costly files
  702. else if (sz <= DeltaIndex.BLKSZ)
  703. otp.setDoNotDelta(true); // too small, won't work
  704. else
  705. otp.setWeight((int) sz);
  706. }
  707. } finally {
  708. sizeQueue.release();
  709. }
  710. monitor.endTask();
  711. stats.timeSearchingForSizes = System.currentTimeMillis() - sizingStart;
  712. // Sort the objects by path hash so like files are near each other,
  713. // and then by size descending so that bigger files are first. This
  714. // applies "Linus' Law" which states that newer files tend to be the
  715. // bigger ones, because source files grow and hardly ever shrink.
  716. //
  717. Arrays.sort(list, 0, cnt, new Comparator<ObjectToPack>() {
  718. public int compare(ObjectToPack a, ObjectToPack b) {
  719. int cmp = (a.isDoNotDelta() ? 1 : 0)
  720. - (b.isDoNotDelta() ? 1 : 0);
  721. if (cmp != 0)
  722. return cmp;
  723. cmp = a.getType() - b.getType();
  724. if (cmp != 0)
  725. return cmp;
  726. cmp = (a.getPathHash() >>> 1) - (b.getPathHash() >>> 1);
  727. if (cmp != 0)
  728. return cmp;
  729. cmp = (a.getPathHash() & 1) - (b.getPathHash() & 1);
  730. if (cmp != 0)
  731. return cmp;
  732. cmp = (a.isEdge() ? 0 : 1) - (b.isEdge() ? 0 : 1);
  733. if (cmp != 0)
  734. return cmp;
  735. return b.getWeight() - a.getWeight();
  736. }
  737. });
  738. // Above we stored the objects we cannot delta onto the end.
  739. // Remove them from the list so we don't waste time on them.
  740. while (0 < cnt && list[cnt - 1].isDoNotDelta()) {
  741. if (!list[cnt - 1].isEdge())
  742. nonEdgeCnt--;
  743. cnt--;
  744. }
  745. if (cnt == 0)
  746. return;
  747. final long searchStart = System.currentTimeMillis();
  748. monitor.beginTask(JGitText.get().compressingObjects, nonEdgeCnt);
  749. searchForDeltas(monitor, list, cnt);
  750. monitor.endTask();
  751. stats.deltaSearchNonEdgeObjects = nonEdgeCnt;
  752. stats.timeCompressing = System.currentTimeMillis() - searchStart;
  753. for (int i = 0; i < cnt; i++)
  754. if (!list[i].isEdge() && list[i].isDeltaRepresentation())
  755. stats.deltasFound++;
  756. }
  757. private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) {
  758. for (ObjectToPack otp : objectsLists[type]) {
  759. if (otp.isReuseAsIs()) // already reusing a representation
  760. continue;
  761. if (otp.isDoNotDelta()) // delta is disabled for this path
  762. continue;
  763. otp.setWeight(0);
  764. list[cnt++] = otp;
  765. }
  766. return cnt;
  767. }
  768. private void searchForDeltas(final ProgressMonitor monitor,
  769. final ObjectToPack[] list, final int cnt)
  770. throws MissingObjectException, IncorrectObjectTypeException,
  771. LargeObjectException, IOException {
  772. int threads = config.getThreads();
  773. if (threads == 0)
  774. threads = Runtime.getRuntime().availableProcessors();
  775. if (threads <= 1 || cnt <= 2 * config.getDeltaSearchWindowSize()) {
  776. DeltaCache dc = new DeltaCache(config);
  777. DeltaWindow dw = new DeltaWindow(config, dc, reader);
  778. dw.search(monitor, list, 0, cnt);
  779. return;
  780. }
  781. final DeltaCache dc = new ThreadSafeDeltaCache(config);
  782. final ThreadSafeProgressMonitor pm = new ThreadSafeProgressMonitor(monitor);
  783. // Guess at the size of batch we want. Because we don't really
  784. // have a way for a thread to steal work from another thread if
  785. // it ends early, we over partition slightly so the work units
  786. // are a bit smaller.
  787. //
  788. int estSize = cnt / (threads * 2);
  789. if (estSize < 2 * config.getDeltaSearchWindowSize())
  790. estSize = 2 * config.getDeltaSearchWindowSize();
  791. final List<DeltaTask> myTasks = new ArrayList<DeltaTask>(threads * 2);
  792. for (int i = 0; i < cnt;) {
  793. final int start = i;
  794. final int batchSize;
  795. if (cnt - i < estSize) {
  796. // If we don't have enough to fill the remaining block,
  797. // schedule what is left over as a single block.
  798. //
  799. batchSize = cnt - i;
  800. } else {
  801. // Try to split the block at the end of a path.
  802. //
  803. int end = start + estSize;
  804. while (end < cnt) {
  805. ObjectToPack a = list[end - 1];
  806. ObjectToPack b = list[end];
  807. if (a.getPathHash() == b.getPathHash())
  808. end++;
  809. else
  810. break;
  811. }
  812. batchSize = end - start;
  813. }
  814. i += batchSize;
  815. myTasks.add(new DeltaTask(config, reader, dc, pm, batchSize, start, list));
  816. }
  817. pm.startWorkers(myTasks.size());
  818. final Executor executor = config.getExecutor();
  819. final List<Throwable> errors = Collections
  820. .synchronizedList(new ArrayList<Throwable>());
  821. if (executor instanceof ExecutorService) {
  822. // Caller supplied us a service, use it directly.
  823. //
  824. runTasks((ExecutorService) executor, pm, myTasks, errors);
  825. } else if (executor == null) {
  826. // Caller didn't give us a way to run the tasks, spawn up a
  827. // temporary thread pool and make sure it tears down cleanly.
  828. //
  829. ExecutorService pool = Executors.newFixedThreadPool(threads);
  830. try {
  831. runTasks(pool, pm, myTasks, errors);
  832. } finally {
  833. pool.shutdown();
  834. for (;;) {
  835. try {
  836. if (pool.awaitTermination(60, TimeUnit.SECONDS))
  837. break;
  838. } catch (InterruptedException e) {
  839. throw new IOException(
  840. JGitText.get().packingCancelledDuringObjectsWriting);
  841. }
  842. }
  843. }
  844. } else {
  845. // The caller gave us an executor, but it might not do
  846. // asynchronous execution. Wrap everything and hope it
  847. // can schedule these for us.
  848. //
  849. for (final DeltaTask task : myTasks) {
  850. executor.execute(new Runnable() {
  851. public void run() {
  852. try {
  853. task.call();
  854. } catch (Throwable failure) {
  855. errors.add(failure);
  856. }
  857. }
  858. });
  859. }
  860. try {
  861. pm.waitForCompletion();
  862. } catch (InterruptedException ie) {
  863. // We can't abort the other tasks as we have no handle.
  864. // Cross our fingers and just break out anyway.
  865. //
  866. throw new IOException(
  867. JGitText.get().packingCancelledDuringObjectsWriting);
  868. }
  869. }
  870. // If any task threw an error, try to report it back as
  871. // though we weren't using a threaded search algorithm.
  872. //
  873. if (!errors.isEmpty()) {
  874. Throwable err = errors.get(0);
  875. if (err instanceof Error)
  876. throw (Error) err;
  877. if (err instanceof RuntimeException)
  878. throw (RuntimeException) err;
  879. if (err instanceof IOException)
  880. throw (IOException) err;
  881. IOException fail = new IOException(err.getMessage());
  882. fail.initCause(err);
  883. throw fail;
  884. }
  885. }
  886. private void runTasks(ExecutorService pool, ThreadSafeProgressMonitor pm,
  887. List<DeltaTask> tasks, List<Throwable> errors) throws IOException {
  888. List<Future<?>> futures = new ArrayList<Future<?>>(tasks.size());
  889. for (DeltaTask task : tasks)
  890. futures.add(pool.submit(task));
  891. try {
  892. pm.waitForCompletion();
  893. for (Future<?> f : futures) {
  894. try {
  895. f.get();
  896. } catch (ExecutionException failed) {
  897. errors.add(failed.getCause());
  898. }
  899. }
  900. } catch (InterruptedException ie) {
  901. for (Future<?> f : futures)
  902. f.cancel(true);
  903. throw new IOException(
  904. JGitText.get().packingCancelledDuringObjectsWriting);
  905. }
  906. }
  907. private void writeObjects(PackOutputStream out) throws IOException {
  908. writeObjects(out, objectsLists[Constants.OBJ_COMMIT]);
  909. writeObjects(out, objectsLists[Constants.OBJ_TAG]);
  910. writeObjects(out, objectsLists[Constants.OBJ_TREE]);
  911. writeObjects(out, objectsLists[Constants.OBJ_BLOB]);
  912. }
  913. private void writeObjects(PackOutputStream out, List<ObjectToPack> list)
  914. throws IOException {
  915. if (reuseSupport != null) {
  916. reuseSupport.writeObjects(out, list);
  917. } else {
  918. for (ObjectToPack otp : list)
  919. out.writeObject(otp);
  920. }
  921. }
  922. void writeObject(PackOutputStream out, ObjectToPack otp) throws IOException {
  923. if (otp.isWritten())
  924. return; // We shouldn't be here.
  925. otp.markWantWrite();
  926. if (otp.isDeltaRepresentation())
  927. writeBaseFirst(out, otp);
  928. out.resetCRC32();
  929. otp.setOffset(out.length());
  930. while (otp.isReuseAsIs()) {
  931. try {
  932. reuseSupport.copyObjectAsIs(out, otp, reuseValidate);
  933. out.endObject();
  934. otp.setCRC(out.getCRC32());
  935. stats.reusedObjects++;
  936. if (otp.isDeltaRepresentation()) {
  937. stats.totalDeltas++;
  938. stats.reusedDeltas++;
  939. }
  940. return;
  941. } catch (StoredObjectRepresentationNotAvailableException gone) {
  942. if (otp.getOffset() == out.length()) {
  943. redoSearchForReuse(otp);
  944. continue;
  945. } else {
  946. // Object writing already started, we cannot recover.
  947. //
  948. CorruptObjectException coe;
  949. coe = new CorruptObjectException(otp, "");
  950. coe.initCause(gone);
  951. throw coe;
  952. }
  953. }
  954. }
  955. // If we reached here, reuse wasn't possible.
  956. //
  957. if (otp.isDeltaRepresentation())
  958. writeDeltaObjectDeflate(out, otp);
  959. else
  960. writeWholeObjectDeflate(out, otp);
  961. out.endObject();
  962. otp.setCRC(out.getCRC32());
  963. }
  964. private void writeBaseFirst(PackOutputStream out, final ObjectToPack otp)
  965. throws IOException {
  966. ObjectToPack baseInPack = otp.getDeltaBase();
  967. if (baseInPack != null) {
  968. if (!baseInPack.isWritten()) {
  969. if (baseInPack.wantWrite()) {
  970. // There is a cycle. Our caller is trying to write the
  971. // object we want as a base, and called us. Turn off
  972. // delta reuse so we can find another form.
  973. //
  974. reuseDeltas = false;
  975. redoSearchForReuse(otp);
  976. reuseDeltas = true;
  977. } else {
  978. writeObject(out, baseInPack);
  979. }
  980. }
  981. } else if (!thin) {
  982. // This should never occur, the base isn't in the pack and
  983. // the pack isn't allowed to reference base outside objects.
  984. // Write the object as a whole form, even if that is slow.
  985. //
  986. otp.clearDeltaBase();
  987. otp.clearReuseAsIs();
  988. }
  989. }
  990. private void redoSearchForReuse(final ObjectToPack otp) throws IOException,
  991. MissingObjectException {
  992. otp.clearDeltaBase();
  993. otp.clearReuseAsIs();
  994. reuseSupport.selectObjectRepresentation(this,
  995. NullProgressMonitor.INSTANCE, Collections.singleton(otp));
  996. }
  997. private void writeWholeObjectDeflate(PackOutputStream out,
  998. final ObjectToPack otp) throws IOException {
  999. final Deflater deflater = deflater();
  1000. final ObjectLoader ldr = reader.open(otp, otp.getType());
  1001. out.writeHeader(otp, ldr.getSize());
  1002. deflater.reset();
  1003. DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
  1004. ldr.copyTo(dst);
  1005. dst.finish();
  1006. }
  1007. private void writeDeltaObjectDeflate(PackOutputStream out,
  1008. final ObjectToPack otp) throws IOException {
  1009. DeltaCache.Ref ref = otp.popCachedDelta();
  1010. if (ref != null) {
  1011. byte[] zbuf = ref.get();
  1012. if (zbuf != null) {
  1013. out.writeHeader(otp, otp.getCachedSize());
  1014. out.write(zbuf);
  1015. return;
  1016. }
  1017. }
  1018. TemporaryBuffer.Heap delta = delta(otp);
  1019. out.writeHeader(otp, delta.length());
  1020. Deflater deflater = deflater();
  1021. deflater.reset();
  1022. DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
  1023. delta.writeTo(dst, null);
  1024. dst.finish();
  1025. stats.totalDeltas++;
  1026. }
  1027. private TemporaryBuffer.Heap delta(final ObjectToPack otp)
  1028. throws IOException {
  1029. DeltaIndex index = new DeltaIndex(buffer(otp.getDeltaBaseId()));
  1030. byte[] res = buffer(otp);
  1031. // We never would have proposed this pair if the delta would be
  1032. // larger than the unpacked version of the object. So using it
  1033. // as our buffer limit is valid: we will never reach it.
  1034. //
  1035. TemporaryBuffer.Heap delta = new TemporaryBuffer.Heap(res.length);
  1036. index.encode(delta, res);
  1037. return delta;
  1038. }
  1039. private byte[] buffer(AnyObjectId objId) throws IOException {
  1040. return buffer(config, reader, objId);
  1041. }
  1042. static byte[] buffer(PackConfig config, ObjectReader or, AnyObjectId objId)
  1043. throws IOException {
  1044. // PackWriter should have already pruned objects that
  1045. // are above the big file threshold, so our chances of
  1046. // the object being below it are very good. We really
  1047. // shouldn't be here, unless the implementation is odd.
  1048. return or.open(objId).getCachedBytes(config.getBigFileThreshold());
  1049. }
  1050. private Deflater deflater() {
  1051. if (myDeflater == null)
  1052. myDeflater = new Deflater(config.getCompressionLevel());
  1053. return myDeflater;
  1054. }
  1055. private void writeChecksum(PackOutputStream out) throws IOException {
  1056. packcsum = out.getDigest();
  1057. out.write(packcsum);
  1058. }
  1059. private void findObjectsToPack(final ProgressMonitor countingMonitor,
  1060. final ObjectWalk walker, final Collection<? extends ObjectId> want,
  1061. Collection<? extends ObjectId> have)
  1062. throws MissingObjectException, IOException,
  1063. IncorrectObjectTypeException {
  1064. final long countingStart = System.currentTimeMillis();
  1065. countingMonitor.beginTask(JGitText.get().countingObjects,
  1066. ProgressMonitor.UNKNOWN);
  1067. if (have == null)
  1068. have = Collections.emptySet();
  1069. stats.interestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(want));
  1070. stats.uninterestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(have));
  1071. List<ObjectId> all = new ArrayList<ObjectId>(want.size() + have.size());
  1072. all.addAll(want);
  1073. all.addAll(have);
  1074. final Map<ObjectId, CachedPack> tipToPack = new HashMap<ObjectId, CachedPack>();
  1075. final RevFlag inCachedPack = walker.newFlag("inCachedPack");
  1076. final RevFlag include = walker.newFlag("include");
  1077. final RevFlag added = walker.newFlag("added");
  1078. final RevFlagSet keepOnRestart = new RevFlagSet();
  1079. keepOnRestart.add(inCachedPack);
  1080. walker.setRetainBody(false);
  1081. walker.carry(include);
  1082. int haveEst = have.size();
  1083. if (have.isEmpty()) {
  1084. walker.sort(RevSort.COMMIT_TIME_DESC);
  1085. if (useCachedPacks && reuseSupport != null) {
  1086. Set<ObjectId> need = new HashSet<ObjectId>(want);
  1087. List<CachedPack> shortCircuit = new LinkedList<CachedPack>();
  1088. for (CachedPack pack : reuseSupport.getCachedPacks()) {
  1089. if (need.containsAll(pack.getTips())) {
  1090. need.removeAll(pack.getTips());
  1091. shortCircuit.add(pack);
  1092. }
  1093. for (ObjectId id : pack.getTips()) {
  1094. tipToPack.put(id, pack);
  1095. all.add(id);
  1096. }
  1097. }
  1098. if (need.isEmpty() && !shortCircuit.isEmpty()) {
  1099. cachedPacks.addAll(shortCircuit);
  1100. for (CachedPack pack : shortCircuit)
  1101. countingMonitor.update((int) pack.getObjectCount());
  1102. countingMonitor.endTask();
  1103. stats.timeCounting = System.currentTimeMillis() - countingStart;
  1104. return;
  1105. }
  1106. haveEst += tipToPack.size();
  1107. }
  1108. } else {
  1109. walker.sort(RevSort.TOPO);
  1110. if (thin)
  1111. walker.sort(RevSort.BOUNDARY, true);
  1112. }
  1113. List<RevObject> wantObjs = new ArrayList<RevObject>(want.size());
  1114. List<RevObject> haveObjs = new ArrayList<RevObject>(haveEst);
  1115. List<RevTag> wantTags = new ArrayList<RevTag>(want.size());
  1116. AsyncRevObjectQueue q = walker.parseAny(all, true);
  1117. try {
  1118. for (;;) {
  1119. try {
  1120. RevObject o = q.next();
  1121. if (o == null)
  1122. break;
  1123. if (tipToPack.containsKey(o))
  1124. o.add(inCachedPack);
  1125. if (have.contains(o)) {
  1126. haveObjs.add(o);
  1127. } else if (want.contains(o)) {
  1128. o.add(include);
  1129. wantObjs.add(o);
  1130. if (o instanceof RevTag)
  1131. wantTags.add((RevTag) o);
  1132. }
  1133. } catch (MissingObjectException e) {
  1134. if (ignoreMissingUninteresting
  1135. && have.contains(e.getObjectId()))
  1136. continue;
  1137. throw e;
  1138. }
  1139. }
  1140. } finally {
  1141. q.release();
  1142. }
  1143. if (!wantTags.isEmpty()) {
  1144. all = new ArrayList<ObjectId>(wantTags.size());
  1145. for (RevTag tag : wantTags)
  1146. all.add(tag.getObject());
  1147. q = walker.parseAny(all, true);
  1148. try {
  1149. while (q.next() != null) {
  1150. // Just need to pop the queue item to parse the object.
  1151. }
  1152. } finally {
  1153. q.release();
  1154. }
  1155. }
  1156. for (RevObject obj : wantObjs)
  1157. walker.markStart(obj);
  1158. for (RevObject obj : haveObjs)
  1159. walker.markUninteresting(obj);
  1160. int typesToPrune = 0;
  1161. final int maxBases = config.getDeltaSearchWindowSize();
  1162. Set<RevTree> baseTrees = new HashSet<RevTree>();
  1163. List<RevCommit> commits = new ArrayList<RevCommit>();
  1164. RevCommit c;
  1165. while ((c = walker.next()) != null) {
  1166. if (c.has(inCachedPack)) {
  1167. CachedPack pack = tipToPack.get(c);
  1168. if (includesAllTips(pack, include, walker)) {
  1169. useCachedPack(walker, keepOnRestart, //
  1170. wantObjs, haveObjs, pack);
  1171. commits = new ArrayList<RevCommit>();
  1172. countingMonitor.endTask();
  1173. countingMonitor.beginTask(JGitText.get().countingObjects,
  1174. ProgressMonitor.UNKNOWN);
  1175. continue;
  1176. }
  1177. }
  1178. if (c.has(RevFlag.UNINTERESTING)) {
  1179. if (baseTrees.size() <= maxBases)
  1180. baseTrees.add(c.getTree());
  1181. continue;
  1182. }
  1183. commits.add(c);
  1184. countingMonitor.update(1);
  1185. }
  1186. if (objectsLists[Constants.OBJ_COMMIT] instanceof ArrayList) {
  1187. ArrayList<ObjectToPack> list = (ArrayList<ObjectToPack>) objectsLists[Constants.OBJ_COMMIT];
  1188. list.ensureCapacity(list.size() + commits.size());
  1189. }
  1190. int commitCnt = 0;
  1191. boolean putTagTargets = false;
  1192. for (RevCommit cmit : commits) {
  1193. if (!cmit.has(added)) {
  1194. cmit.add(added);
  1195. addObject(cmit, 0);
  1196. commitCnt++;
  1197. }
  1198. for (int i = 0; i < cmit.getParentCount(); i++) {
  1199. RevCommit p = cmit.getParent(i);
  1200. if (!p.has(added) && !p.has(RevFlag.UNINTERESTING)) {
  1201. p.add(added);
  1202. addObject(p, 0);
  1203. commitCnt++;
  1204. }
  1205. }
  1206. if (!putTagTargets && 4096 < commitCnt) {
  1207. for (ObjectId id : tagTargets) {
  1208. RevObject obj = walker.lookupOrNull(id);
  1209. if (obj instanceof RevCommit
  1210. && obj.has(include)
  1211. && !obj.has(RevFlag.UNINTERESTING)
  1212. && !obj.has(added)) {
  1213. obj.add(added);
  1214. addObject(obj, 0);
  1215. }
  1216. }
  1217. putTagTargets = true;
  1218. }
  1219. }
  1220. commits = null;
  1221. for (CachedPack p : cachedPacks) {
  1222. for (ObjectId d : p.hasObject(objectsLists[Constants.OBJ_COMMIT])) {
  1223. if (baseTrees.size() <= maxBases)
  1224. baseTrees.add(walker.lookupCommit(d).getTree());
  1225. objectsMap.get(d).setEdge();
  1226. typesToPrune |= 1 << Constants.OBJ_COMMIT;
  1227. }
  1228. }
  1229. BaseSearch bases = new BaseSearch(countingMonitor, baseTrees, //
  1230. objectsMap, edgeObjects, reader);
  1231. RevObject o;
  1232. while ((o = walker.nextObject()) != null) {
  1233. if (o.has(RevFlag.UNINTERESTING))
  1234. continue;
  1235. int pathHash = walker.getPathHashCode();
  1236. byte[] pathBuf = walker.getPathBuffer();
  1237. int pathLen = walker.getPathLength();
  1238. bases.addBase(o.getType(), pathBuf, pathLen, pathHash);
  1239. addObject(o, pathHash);
  1240. countingMonitor.update(1);
  1241. }
  1242. for (CachedPack p : cachedPacks) {
  1243. for (ObjectId d : p.hasObject(objectsLists[Constants.OBJ_TREE])) {
  1244. objectsMap.get(d).setEdge();
  1245. typesToPrune |= 1 << Constants.OBJ_TREE;
  1246. }
  1247. for (ObjectId d : p.hasObject(objectsLists[Constants.OBJ_BLOB])) {
  1248. objectsMap.get(d).setEdge();
  1249. typesToPrune |= 1 << Constants.OBJ_BLOB;
  1250. }
  1251. for (ObjectId d : p.hasObject(objectsLists[Constants.OBJ_TAG])) {
  1252. objectsMap.get(d).setEdge();
  1253. typesToPrune |= 1 << Constants.OBJ_TAG;
  1254. }
  1255. }
  1256. if (typesToPrune != 0) {
  1257. pruneObjectList(typesToPrune, Constants.OBJ_COMMIT);
  1258. pruneObjectList(typesToPrune, Constants.OBJ_TREE);
  1259. pruneObjectList(typesToPrune, Constants.OBJ_BLOB);
  1260. pruneObjectList(typesToPrune, Constants.OBJ_TAG);
  1261. }
  1262. for (CachedPack pack : cachedPacks)
  1263. countingMonitor.update((int) pack.getObjectCount());
  1264. countingMonitor.endTask();
  1265. stats.timeCounting = System.currentTimeMillis() - countingStart;
  1266. }
  1267. private void pruneObjectList(int typesToPrune, int typeCode) {
  1268. if ((typesToPrune & (1 << typeCode)) == 0)
  1269. return;
  1270. final List<ObjectToPack> list = objectsLists[typeCode];
  1271. final int size = list.size();
  1272. int src = 0;
  1273. int dst = 0;
  1274. for (; src < size; src++) {
  1275. ObjectToPack obj = list.get(src);
  1276. if (obj.isEdge())
  1277. continue;
  1278. if (dst != src)
  1279. list.set(dst, obj);
  1280. dst++;
  1281. }
  1282. while (dst < list.size())
  1283. list.remove(dst);
  1284. }
  1285. private void useCachedPack(ObjectWalk walker, RevFlagSet keepOnRestart,
  1286. List<RevObject> wantObj, List<RevObject> baseObj, CachedPack pack)
  1287. throws MissingObjectException, IncorrectObjectTypeException,
  1288. IOException {
  1289. cachedPacks.add(pack);
  1290. for (ObjectId id : pack.getTips())
  1291. baseObj.add(walker.lookupOrNull(id));
  1292. setThin(true);
  1293. walker.resetRetain(keepOnRestart);
  1294. walker.sort(RevSort.TOPO);
  1295. walker.sort(RevSort.BOUNDARY, true);
  1296. for (RevObject id : wantObj)
  1297. walker.markStart(id);
  1298. for (RevObject id : baseObj)
  1299. walker.markUninteresting(id);
  1300. }
  1301. private static boolean includesAllTips(CachedPack pack, RevFlag include,
  1302. ObjectWalk walker) {
  1303. for (ObjectId id : pack.getTips()) {
  1304. if (!walker.lookupOrNull(id).has(include))
  1305. return false;
  1306. }
  1307. return true;
  1308. }
  1309. /**
  1310. * Include one object to the output file.
  1311. * <p>
  1312. * Objects are written in the order they are added. If the same object is
  1313. * added twice, it may be written twice, creating a larger than necessary
  1314. * file.
  1315. *
  1316. * @param object
  1317. * the object to add.
  1318. * @throws IncorrectObjectTypeException
  1319. * the object is an unsupported type.
  1320. */
  1321. public void addObject(final RevObject object)
  1322. throws IncorrectObjectTypeException {
  1323. addObject(object, 0);
  1324. }
  1325. private void addObject(final RevObject object, final int pathHashCode)
  1326. throws IncorrectObjectTypeException {
  1327. final ObjectToPack otp;
  1328. if (reuseSupport != null)
  1329. otp = reuseSupport.newObjectToPack(object);
  1330. else
  1331. otp = new ObjectToPack(object);
  1332. otp.setPathHash(pathHashCode);
  1333. try {
  1334. objectsLists[object.getType()].add(otp);
  1335. } catch (ArrayIndexOutOfBoundsException x) {
  1336. throw new IncorrectObjectTypeException(object,
  1337. JGitText.get().incorrectObjectType_COMMITnorTREEnorBLOBnorTAG);
  1338. } catch (UnsupportedOperationException x) {
  1339. // index pointing to "dummy" empty list
  1340. throw new IncorrectObjectTypeException(object,
  1341. JGitText.get().incorrectObjectType_COMMITnorTREEnorBLOBnorTAG);
  1342. }
  1343. objectsMap.add(otp);
  1344. }
  1345. /**
  1346. * Select an object representation for this writer.
  1347. * <p>
  1348. * An {@link ObjectReader} implementation should invoke this method once for
  1349. * each representation available for an object, to allow the writer to find
  1350. * the most suitable one for the output.
  1351. *
  1352. * @param otp
  1353. * the object being packed.
  1354. * @param next
  1355. * the next available representation from the repository.
  1356. */
  1357. public void select(ObjectToPack otp, StoredObjectRepresentation next) {
  1358. int nFmt = next.getFormat();
  1359. int nWeight;
  1360. if (otp.isReuseAsIs()) {
  1361. // We've already chosen to reuse a packed form, if next
  1362. // cannot beat that break out early.
  1363. //
  1364. if (PACK_WHOLE < nFmt)
  1365. return; // next isn't packed
  1366. else if (PACK_DELTA < nFmt && otp.isDeltaRepresentation())
  1367. return; // next isn't a delta, but we are
  1368. nWeight = next.getWeight();
  1369. if (otp.getWeight() <= nWeight)
  1370. return; // next would be bigger
  1371. } else
  1372. nWeight = next.getWeight();
  1373. if (nFmt == PACK_DELTA && reuseDeltas && reuseDeltaFor(otp)) {
  1374. ObjectId baseId = next.getDeltaBase();
  1375. ObjectToPack ptr = objectsMap.get(baseId);
  1376. if (ptr != null && !ptr.isEdge()) {
  1377. otp.setDeltaBase(ptr);
  1378. otp.setReuseAsIs();
  1379. otp.setWeight(nWeight);
  1380. } else if (thin && ptr != null && ptr.isEdge()) {
  1381. otp.setDeltaBase(baseId);
  1382. otp.setReuseAsIs();
  1383. otp.setWeight(nWeight);
  1384. } else {
  1385. otp.clearDeltaBase();
  1386. otp.clearReuseAsIs();
  1387. }
  1388. } else if (nFmt == PACK_WHOLE && config.isReuseObjects()) {
  1389. otp.clearDeltaBase();
  1390. otp.setReuseAsIs();
  1391. otp.setWeight(nWeight);
  1392. } else {
  1393. otp.clearDeltaBase();
  1394. otp.clearReuseAsIs();
  1395. }
  1396. otp.select(next);
  1397. }
  1398. private boolean reuseDeltaFor(ObjectToPack otp) {
  1399. switch (otp.getType()) {
  1400. case Constants.OBJ_COMMIT:
  1401. return reuseDeltaCommits;
  1402. case Constants.OBJ_TREE:
  1403. return true;
  1404. case Constants.OBJ_BLOB:
  1405. return true;
  1406. case Constants.OBJ_TAG:
  1407. return false;
  1408. default:
  1409. return true;
  1410. }
  1411. }
  1412. /** Summary of how PackWriter created the pack. */
  1413. public static class Statistics {
  1414. Set<ObjectId> interestingObjects;
  1415. Set<ObjectId> uninterestingObjects;
  1416. Collection<CachedPack> reusedPacks;
  1417. int deltaSearchNonEdgeObjects;
  1418. int deltasFound;
  1419. long totalObjects;
  1420. long totalDeltas;
  1421. long reusedObjects;
  1422. long reusedDeltas;
  1423. long totalBytes;
  1424. long thinPackBytes;
  1425. long timeCounting;
  1426. long timeSearchingForReuse;
  1427. long timeSearchingForSizes;
  1428. long timeCompressing;
  1429. long timeWriting;
  1430. /**
  1431. * @return unmodifiable collection of objects to be included in the
  1432. * pack. May be null if the pack was hand-crafted in a unit
  1433. * test.
  1434. */
  1435. public Set<ObjectId> getInterestingObjects() {
  1436. return interestingObjects;
  1437. }
  1438. /**
  1439. * @return unmodifiable collection of objects that should be excluded
  1440. * from the pack, as the peer that will receive the pack already
  1441. * has these objects.
  1442. */
  1443. public Set<ObjectId> getUninterestingObjects() {
  1444. return uninterestingObjects;
  1445. }
  1446. /**
  1447. * @return unmodifiable collection of the cached packs that were reused
  1448. * in the output, if any were selected for reuse.
  1449. */
  1450. public Collection<CachedPack> getReusedPacks() {
  1451. return reusedPacks;
  1452. }
  1453. /**
  1454. * @return number of objects in the output pack that went through the
  1455. * delta search process in order to find a potential delta base.
  1456. */
  1457. public int getDeltaSearchNonEdgeObjects() {
  1458. return deltaSearchNonEdgeObjects;
  1459. }
  1460. /**
  1461. * @return number of objects in the output pack that went through delta
  1462. * base search and found a suitable base. This is a subset of
  1463. * {@link #getDeltaSearchNonEdgeObjects()}.
  1464. */
  1465. public int getDeltasFound() {
  1466. return deltasFound;
  1467. }
  1468. /**
  1469. * @return total number of objects output. This total includes the value
  1470. * of {@link #getTotalDeltas()}.
  1471. */
  1472. public long getTotalObjects() {
  1473. return totalObjects;
  1474. }
  1475. /**
  1476. * @return total number of deltas output. This may be lower than the
  1477. * actual number of deltas if a cached pack was reused.
  1478. */
  1479. public long getTotalDeltas() {
  1480. return totalDeltas;
  1481. }
  1482. /**
  1483. * @return number of objects whose existing representation was reused in
  1484. * the output. This count includes {@link #getReusedDeltas()}.
  1485. */
  1486. public long getReusedObjects() {
  1487. return reusedObjects;
  1488. }
  1489. /**
  1490. * @return number of deltas whose existing representation was reused in
  1491. * the output, as their base object was also output or was
  1492. * assumed present for a thin pack. This may be lower than the
  1493. * actual number of reused deltas if a cached pack was reused.
  1494. */
  1495. public long getReusedDeltas() {
  1496. return reusedDeltas;
  1497. }
  1498. /**
  1499. * @return total number of bytes written. This size includes the pack
  1500. * header, trailer, thin pack, and reused cached pack(s).
  1501. */
  1502. public long getTotalBytes() {
  1503. return totalBytes;
  1504. }
  1505. /**
  1506. * @return size of the thin pack in bytes, if a thin pack was generated.
  1507. * A thin pack is created when the client already has objects
  1508. * and some deltas are created against those objects, or if a
  1509. * cached pack is being used and some deltas will reference
  1510. * objects in the cached pack. This size does not include the
  1511. * pack header or trailer.
  1512. */
  1513. public long getThinPackBytes() {
  1514. return thinPackBytes;
  1515. }
  1516. /**
  1517. * @return time in milliseconds spent enumerating the objects that need
  1518. * to be included in the output. This time includes any restarts
  1519. * that occur when a cached pack is selected for reuse.
  1520. */
  1521. public long getTimeCounting() {
  1522. return timeCounting;
  1523. }
  1524. /**
  1525. * @return time in milliseconds spent matching existing representations
  1526. * against objects that will be transmitted, or that the client
  1527. * can be assumed to already have.
  1528. */
  1529. public long getTimeSearchingForReuse() {
  1530. return timeSearchingForReuse;
  1531. }
  1532. /**
  1533. * @return time in milliseconds spent finding the sizes of all objects
  1534. * that will enter the delta compression search window. The
  1535. * sizes need to be known to better match similar objects
  1536. * together and improve delta compression ratios.
  1537. */
  1538. public long getTimeSearchingForSizes() {
  1539. return timeSearchingForSizes;
  1540. }
  1541. /**
  1542. * @return time in milliseconds spent on delta compression. This is
  1543. * observed wall-clock time and does not accurately track CPU
  1544. * time used when multiple threads were used to perform the
  1545. * delta compression.
  1546. */
  1547. public long getTimeCompressing() {
  1548. return timeCompressing;
  1549. }
  1550. /**
  1551. * @return time in milliseconds spent writing the pack output, from
  1552. * start of header until end of trailer. The transfer speed can
  1553. * be approximated by dividing {@link #getTotalBytes()} by this
  1554. * value.
  1555. */
  1556. public long getTimeWriting() {
  1557. return timeWriting;
  1558. }
  1559. /**
  1560. * @return get the average output speed in terms of bytes-per-second.
  1561. * {@code getTotalBytes() / (getTimeWriting() / 1000.0)}.
  1562. */
  1563. public double getTransferRate() {
  1564. return getTotalBytes() / (getTimeWriting() / 1000.0);
  1565. }
  1566. /** @return formatted message string for display to clients. */
  1567. public String getMessage() {
  1568. return MessageFormat.format(JGitText.get().packWriterStatistics, //
  1569. totalObjects, totalDeltas, //
  1570. reusedObjects, reusedDeltas);
  1571. }
  1572. }
  1573. }