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.

GC.java 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. /*
  2. * Copyright (C) 2012, Christian Halstrick <christian.halstrick@sap.com>
  3. * Copyright (C) 2011, Shawn O. Pearce <spearce@spearce.org>
  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.internal.storage.file;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
  46. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  47. import java.io.File;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.OutputStream;
  51. import java.nio.channels.Channels;
  52. import java.nio.channels.FileChannel;
  53. import java.nio.file.StandardCopyOption;
  54. import java.text.MessageFormat;
  55. import java.text.ParseException;
  56. import java.util.ArrayList;
  57. import java.util.Collection;
  58. import java.util.Collections;
  59. import java.util.Comparator;
  60. import java.util.Date;
  61. import java.util.HashMap;
  62. import java.util.HashSet;
  63. import java.util.LinkedList;
  64. import java.util.List;
  65. import java.util.Map;
  66. import java.util.Objects;
  67. import java.util.Set;
  68. import java.util.TreeMap;
  69. import org.eclipse.jgit.annotations.NonNull;
  70. import org.eclipse.jgit.dircache.DirCacheIterator;
  71. import org.eclipse.jgit.errors.CorruptObjectException;
  72. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.errors.NoWorkTreeException;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.internal.storage.pack.PackExt;
  77. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  78. import org.eclipse.jgit.internal.storage.reftree.RefTreeNames;
  79. import org.eclipse.jgit.lib.ConfigConstants;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.FileMode;
  82. import org.eclipse.jgit.lib.NullProgressMonitor;
  83. import org.eclipse.jgit.lib.ObjectId;
  84. import org.eclipse.jgit.lib.ObjectIdSet;
  85. import org.eclipse.jgit.lib.ProgressMonitor;
  86. import org.eclipse.jgit.lib.Ref;
  87. import org.eclipse.jgit.lib.Ref.Storage;
  88. import org.eclipse.jgit.lib.RefDatabase;
  89. import org.eclipse.jgit.lib.ReflogEntry;
  90. import org.eclipse.jgit.lib.ReflogReader;
  91. import org.eclipse.jgit.revwalk.ObjectWalk;
  92. import org.eclipse.jgit.revwalk.RevObject;
  93. import org.eclipse.jgit.revwalk.RevWalk;
  94. import org.eclipse.jgit.storage.pack.PackConfig;
  95. import org.eclipse.jgit.treewalk.TreeWalk;
  96. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  97. import org.eclipse.jgit.util.FileUtils;
  98. import org.eclipse.jgit.util.GitDateParser;
  99. import org.eclipse.jgit.util.SystemReader;
  100. /**
  101. * A garbage collector for git {@link FileRepository}. Instances of this class
  102. * are not thread-safe. Don't use the same instance from multiple threads.
  103. *
  104. * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
  105. * adapted to FileRepositories.
  106. */
  107. public class GC {
  108. private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
  109. private final FileRepository repo;
  110. private ProgressMonitor pm;
  111. private long expireAgeMillis = -1;
  112. private Date expire;
  113. private PackConfig pconfig = null;
  114. /**
  115. * the refs which existed during the last call to {@link #repack()}. This is
  116. * needed during {@link #prune(Set)} where we can optimize by looking at the
  117. * difference between the current refs and the refs which existed during
  118. * last {@link #repack()}.
  119. */
  120. private Collection<Ref> lastPackedRefs;
  121. /**
  122. * Holds the starting time of the last repack() execution. This is needed in
  123. * prune() to inspect only those reflog entries which have been added since
  124. * last repack().
  125. */
  126. private long lastRepackTime;
  127. /**
  128. * Creates a new garbage collector with default values. An expirationTime of
  129. * two weeks and <code>null</code> as progress monitor will be used.
  130. *
  131. * @param repo
  132. * the repo to work on
  133. */
  134. public GC(FileRepository repo) {
  135. this.repo = repo;
  136. this.pm = NullProgressMonitor.INSTANCE;
  137. }
  138. /**
  139. * Runs a garbage collector on a {@link FileRepository}. It will
  140. * <ul>
  141. * <li>pack loose references into packed-refs</li>
  142. * <li>repack all reachable objects into new pack files and delete the old
  143. * pack files</li>
  144. * <li>prune all loose objects which are now reachable by packs</li>
  145. * </ul>
  146. *
  147. * @return the collection of {@link PackFile}'s which are newly created
  148. * @throws IOException
  149. * @throws ParseException
  150. * If the configuration parameter "gc.pruneexpire" couldn't be
  151. * parsed
  152. */
  153. public Collection<PackFile> gc() throws IOException, ParseException {
  154. pm.start(6 /* tasks */);
  155. packRefs();
  156. // TODO: implement reflog_expire(pm, repo);
  157. Collection<PackFile> newPacks = repack();
  158. prune(Collections.<ObjectId> emptySet());
  159. // TODO: implement rerere_gc(pm);
  160. return newPacks;
  161. }
  162. /**
  163. * Delete old pack files. What is 'old' is defined by specifying a set of
  164. * old pack files and a set of new pack files. Each pack file contained in
  165. * old pack files but not contained in new pack files will be deleted. If an
  166. * expirationDate is set then pack files which are younger than the
  167. * expirationDate will not be deleted.
  168. *
  169. * @param oldPacks
  170. * @param newPacks
  171. * @throws ParseException
  172. */
  173. private void deleteOldPacks(Collection<PackFile> oldPacks,
  174. Collection<PackFile> newPacks) throws ParseException {
  175. long expireDate = getExpireDate();
  176. oldPackLoop: for (PackFile oldPack : oldPacks) {
  177. String oldName = oldPack.getPackName();
  178. // check whether an old pack file is also among the list of new
  179. // pack files. Then we must not delete it.
  180. for (PackFile newPack : newPacks)
  181. if (oldName.equals(newPack.getPackName()))
  182. continue oldPackLoop;
  183. if (!oldPack.shouldBeKept()
  184. && oldPack.getPackFile().lastModified() < expireDate) {
  185. oldPack.close();
  186. prunePack(oldName);
  187. }
  188. }
  189. // close the complete object database. Thats my only chance to force
  190. // rescanning and to detect that certain pack files are now deleted.
  191. repo.getObjectDatabase().close();
  192. }
  193. /**
  194. * Delete files associated with a single pack file. First try to delete the
  195. * ".pack" file because on some platforms the ".pack" file may be locked and
  196. * can't be deleted. In such a case it is better to detect this early and
  197. * give up on deleting files for this packfile. Otherwise we may delete the
  198. * ".index" file and when failing to delete the ".pack" file we are left
  199. * with a ".pack" file without a ".index" file.
  200. *
  201. * @param packName
  202. */
  203. private void prunePack(String packName) {
  204. PackExt[] extensions = PackExt.values();
  205. try {
  206. // Delete the .pack file first and if this fails give up on deleting
  207. // the other files
  208. int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  209. for (PackExt ext : extensions)
  210. if (PackExt.PACK.equals(ext)) {
  211. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  212. FileUtils.delete(f, deleteOptions);
  213. break;
  214. }
  215. // The .pack file has been deleted. Delete as many as the other
  216. // files as you can.
  217. deleteOptions |= FileUtils.IGNORE_ERRORS;
  218. for (PackExt ext : extensions) {
  219. if (!PackExt.PACK.equals(ext)) {
  220. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  221. FileUtils.delete(f, deleteOptions);
  222. }
  223. }
  224. } catch (IOException e) {
  225. // Deletion of the .pack file failed. Silently return.
  226. }
  227. }
  228. /**
  229. * Like "git prune-packed" this method tries to prune all loose objects
  230. * which can be found in packs. If certain objects can't be pruned (e.g.
  231. * because the filesystem delete operation fails) this is silently ignored.
  232. *
  233. * @throws IOException
  234. */
  235. public void prunePacked() throws IOException {
  236. ObjectDirectory objdb = repo.getObjectDatabase();
  237. Collection<PackFile> packs = objdb.getPacks();
  238. File objects = repo.getObjectsDirectory();
  239. String[] fanout = objects.list();
  240. if (fanout != null && fanout.length > 0) {
  241. pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
  242. try {
  243. for (String d : fanout) {
  244. pm.update(1);
  245. if (d.length() != 2)
  246. continue;
  247. String[] entries = new File(objects, d).list();
  248. if (entries == null)
  249. continue;
  250. for (String e : entries) {
  251. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  252. continue;
  253. ObjectId id;
  254. try {
  255. id = ObjectId.fromString(d + e);
  256. } catch (IllegalArgumentException notAnObject) {
  257. // ignoring the file that does not represent loose
  258. // object
  259. continue;
  260. }
  261. boolean found = false;
  262. for (PackFile p : packs)
  263. if (p.hasObject(id)) {
  264. found = true;
  265. break;
  266. }
  267. if (found)
  268. FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
  269. | FileUtils.SKIP_MISSING
  270. | FileUtils.IGNORE_ERRORS);
  271. }
  272. }
  273. } finally {
  274. pm.endTask();
  275. }
  276. }
  277. }
  278. /**
  279. * Like "git prune" this method tries to prune all loose objects which are
  280. * unreferenced. If certain objects can't be pruned (e.g. because the
  281. * filesystem delete operation fails) this is silently ignored.
  282. *
  283. * @param objectsToKeep
  284. * a set of objects which should explicitly not be pruned
  285. *
  286. * @throws IOException
  287. * @throws ParseException
  288. * If the configuration parameter "gc.pruneexpire" couldn't be
  289. * parsed
  290. */
  291. public void prune(Set<ObjectId> objectsToKeep) throws IOException,
  292. ParseException {
  293. long expireDate = getExpireDate();
  294. // Collect all loose objects which are old enough, not referenced from
  295. // the index and not in objectsToKeep
  296. Map<ObjectId, File> deletionCandidates = new HashMap<ObjectId, File>();
  297. Set<ObjectId> indexObjects = null;
  298. File objects = repo.getObjectsDirectory();
  299. String[] fanout = objects.list();
  300. if (fanout != null && fanout.length > 0) {
  301. pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
  302. fanout.length);
  303. try {
  304. for (String d : fanout) {
  305. pm.update(1);
  306. if (d.length() != 2)
  307. continue;
  308. File[] entries = new File(objects, d).listFiles();
  309. if (entries == null)
  310. continue;
  311. for (File f : entries) {
  312. String fName = f.getName();
  313. if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  314. continue;
  315. if (f.lastModified() >= expireDate)
  316. continue;
  317. try {
  318. ObjectId id = ObjectId.fromString(d + fName);
  319. if (objectsToKeep.contains(id))
  320. continue;
  321. if (indexObjects == null)
  322. indexObjects = listNonHEADIndexObjects();
  323. if (indexObjects.contains(id))
  324. continue;
  325. deletionCandidates.put(id, f);
  326. } catch (IllegalArgumentException notAnObject) {
  327. // ignoring the file that does not represent loose
  328. // object
  329. continue;
  330. }
  331. }
  332. }
  333. } finally {
  334. pm.endTask();
  335. }
  336. }
  337. if (deletionCandidates.isEmpty())
  338. return;
  339. // From the set of current refs remove all those which have been handled
  340. // during last repack(). Only those refs will survive which have been
  341. // added or modified since the last repack. Only these can save existing
  342. // loose refs from being pruned.
  343. Collection<Ref> newRefs;
  344. if (lastPackedRefs == null || lastPackedRefs.isEmpty())
  345. newRefs = getAllRefs();
  346. else {
  347. Map<String, Ref> last = new HashMap<>();
  348. for (Ref r : lastPackedRefs) {
  349. last.put(r.getName(), r);
  350. }
  351. newRefs = new ArrayList<>();
  352. for (Ref r : getAllRefs()) {
  353. Ref old = last.get(r.getName());
  354. if (!equals(r, old)) {
  355. newRefs.add(r);
  356. }
  357. }
  358. }
  359. if (!newRefs.isEmpty()) {
  360. // There are new/modified refs! Check which loose objects are now
  361. // referenced by these modified refs (or their reflogentries).
  362. // Remove these loose objects
  363. // from the deletionCandidates. When the last candidate is removed
  364. // leave this method.
  365. ObjectWalk w = new ObjectWalk(repo);
  366. try {
  367. for (Ref cr : newRefs)
  368. w.markStart(w.parseAny(cr.getObjectId()));
  369. if (lastPackedRefs != null)
  370. for (Ref lpr : lastPackedRefs)
  371. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  372. removeReferenced(deletionCandidates, w);
  373. } finally {
  374. w.dispose();
  375. }
  376. }
  377. if (deletionCandidates.isEmpty())
  378. return;
  379. // Since we have not left the method yet there are still
  380. // deletionCandidates. Last chance for these objects not to be pruned is
  381. // that they are referenced by reflog entries. Even refs which currently
  382. // point to the same object as during last repack() may have
  383. // additional reflog entries not handled during last repack()
  384. ObjectWalk w = new ObjectWalk(repo);
  385. try {
  386. for (Ref ar : getAllRefs())
  387. for (ObjectId id : listRefLogObjects(ar, lastRepackTime))
  388. w.markStart(w.parseAny(id));
  389. if (lastPackedRefs != null)
  390. for (Ref lpr : lastPackedRefs)
  391. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  392. removeReferenced(deletionCandidates, w);
  393. } finally {
  394. w.dispose();
  395. }
  396. if (deletionCandidates.isEmpty())
  397. return;
  398. // delete all candidates which have survived: these are unreferenced
  399. // loose objects
  400. for (File f : deletionCandidates.values())
  401. f.delete();
  402. repo.getObjectDatabase().close();
  403. }
  404. private long getExpireDate() throws ParseException {
  405. long expireDate = Long.MAX_VALUE;
  406. if (expire == null && expireAgeMillis == -1) {
  407. String pruneExpireStr = repo.getConfig().getString(
  408. ConfigConstants.CONFIG_GC_SECTION, null,
  409. ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
  410. if (pruneExpireStr == null)
  411. pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
  412. expire = GitDateParser.parse(pruneExpireStr, null, SystemReader
  413. .getInstance().getLocale());
  414. expireAgeMillis = -1;
  415. }
  416. if (expire != null)
  417. expireDate = expire.getTime();
  418. if (expireAgeMillis != -1)
  419. expireDate = System.currentTimeMillis() - expireAgeMillis;
  420. return expireDate;
  421. }
  422. /**
  423. * Remove all entries from a map which key is the id of an object referenced
  424. * by the given ObjectWalk
  425. *
  426. * @param id2File
  427. * @param w
  428. * @throws MissingObjectException
  429. * @throws IncorrectObjectTypeException
  430. * @throws IOException
  431. */
  432. private void removeReferenced(Map<ObjectId, File> id2File,
  433. ObjectWalk w) throws MissingObjectException,
  434. IncorrectObjectTypeException, IOException {
  435. RevObject ro = w.next();
  436. while (ro != null) {
  437. if (id2File.remove(ro.getId()) != null)
  438. if (id2File.isEmpty())
  439. return;
  440. ro = w.next();
  441. }
  442. ro = w.nextObject();
  443. while (ro != null) {
  444. if (id2File.remove(ro.getId()) != null)
  445. if (id2File.isEmpty())
  446. return;
  447. ro = w.nextObject();
  448. }
  449. }
  450. private static boolean equals(Ref r1, Ref r2) {
  451. if (r1 == null || r2 == null)
  452. return false;
  453. if (r1.isSymbolic()) {
  454. if (!r2.isSymbolic())
  455. return false;
  456. return r1.getTarget().getName().equals(r2.getTarget().getName());
  457. } else {
  458. if (r2.isSymbolic()) {
  459. return false;
  460. }
  461. return Objects.equals(r1.getObjectId(), r2.getObjectId());
  462. }
  463. }
  464. /**
  465. * Packs all non-symbolic, loose refs into packed-refs.
  466. *
  467. * @throws IOException
  468. */
  469. public void packRefs() throws IOException {
  470. Collection<Ref> refs = repo.getRefDatabase().getRefs(Constants.R_REFS).values();
  471. List<String> refsToBePacked = new ArrayList<String>(refs.size());
  472. pm.beginTask(JGitText.get().packRefs, refs.size());
  473. try {
  474. for (Ref ref : refs) {
  475. if (!ref.isSymbolic() && ref.getStorage().isLoose())
  476. refsToBePacked.add(ref.getName());
  477. pm.update(1);
  478. }
  479. ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
  480. } finally {
  481. pm.endTask();
  482. }
  483. }
  484. /**
  485. * Packs all objects which reachable from any of the heads into one pack
  486. * file. Additionally all objects which are not reachable from any head but
  487. * which are reachable from any of the other refs (e.g. tags), special refs
  488. * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
  489. * included in pack files which have a .keep file associated are never
  490. * repacked. All old pack files which existed before are deleted.
  491. *
  492. * @return a collection of the newly created pack files
  493. * @throws IOException
  494. * when during reading of refs, index, packfiles, objects,
  495. * reflog-entries or during writing to the packfiles
  496. * {@link IOException} occurs
  497. */
  498. public Collection<PackFile> repack() throws IOException {
  499. Collection<PackFile> toBeDeleted = repo.getObjectDatabase().getPacks();
  500. long time = System.currentTimeMillis();
  501. Collection<Ref> refsBefore = getAllRefs();
  502. Set<ObjectId> allHeads = new HashSet<ObjectId>();
  503. Set<ObjectId> nonHeads = new HashSet<ObjectId>();
  504. Set<ObjectId> txnHeads = new HashSet<ObjectId>();
  505. Set<ObjectId> tagTargets = new HashSet<ObjectId>();
  506. Set<ObjectId> indexObjects = listNonHEADIndexObjects();
  507. RefDatabase refdb = repo.getRefDatabase();
  508. for (Ref ref : refsBefore) {
  509. nonHeads.addAll(listRefLogObjects(ref, 0));
  510. if (ref.isSymbolic() || ref.getObjectId() == null)
  511. continue;
  512. if (ref.getName().startsWith(Constants.R_HEADS))
  513. allHeads.add(ref.getObjectId());
  514. else if (RefTreeNames.isRefTree(refdb, ref.getName()))
  515. txnHeads.add(ref.getObjectId());
  516. else
  517. nonHeads.add(ref.getObjectId());
  518. if (ref.getPeeledObjectId() != null)
  519. tagTargets.add(ref.getPeeledObjectId());
  520. }
  521. List<ObjectIdSet> excluded = new LinkedList<ObjectIdSet>();
  522. for (final PackFile f : repo.getObjectDatabase().getPacks())
  523. if (f.shouldBeKept())
  524. excluded.add(f.getIndex());
  525. tagTargets.addAll(allHeads);
  526. nonHeads.addAll(indexObjects);
  527. List<PackFile> ret = new ArrayList<PackFile>(2);
  528. PackFile heads = null;
  529. if (!allHeads.isEmpty()) {
  530. heads = writePack(allHeads, Collections.<ObjectId> emptySet(),
  531. tagTargets, excluded);
  532. if (heads != null) {
  533. ret.add(heads);
  534. excluded.add(0, heads.getIndex());
  535. }
  536. }
  537. if (!nonHeads.isEmpty()) {
  538. PackFile rest = writePack(nonHeads, allHeads, tagTargets, excluded);
  539. if (rest != null)
  540. ret.add(rest);
  541. }
  542. if (!txnHeads.isEmpty()) {
  543. PackFile txn = writePack(txnHeads, PackWriter.NONE, null, excluded);
  544. if (txn != null)
  545. ret.add(txn);
  546. }
  547. try {
  548. deleteOldPacks(toBeDeleted, ret);
  549. } catch (ParseException e) {
  550. // TODO: the exception has to be wrapped into an IOException because
  551. // throwing the ParseException directly would break the API, instead
  552. // we should throw a ConfigInvalidException
  553. throw new IOException(e);
  554. }
  555. prunePacked();
  556. lastPackedRefs = refsBefore;
  557. lastRepackTime = time;
  558. return ret;
  559. }
  560. /**
  561. * @param ref
  562. * the ref which log should be inspected
  563. * @param minTime only reflog entries not older then this time are processed
  564. * @return the {@link ObjectId}s contained in the reflog
  565. * @throws IOException
  566. */
  567. private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
  568. ReflogReader reflogReader = repo.getReflogReader(ref.getName());
  569. if (reflogReader == null) {
  570. return Collections.emptySet();
  571. }
  572. List<ReflogEntry> rlEntries = reflogReader
  573. .getReverseEntries();
  574. if (rlEntries == null || rlEntries.isEmpty())
  575. return Collections.<ObjectId> emptySet();
  576. Set<ObjectId> ret = new HashSet<ObjectId>();
  577. for (ReflogEntry e : rlEntries) {
  578. if (e.getWho().getWhen().getTime() < minTime)
  579. break;
  580. ObjectId newId = e.getNewId();
  581. if (newId != null && !ObjectId.zeroId().equals(newId))
  582. ret.add(newId);
  583. ObjectId oldId = e.getOldId();
  584. if (oldId != null && !ObjectId.zeroId().equals(oldId))
  585. ret.add(oldId);
  586. }
  587. return ret;
  588. }
  589. /**
  590. * Returns a map of all refs and additional refs (e.g. FETCH_HEAD,
  591. * MERGE_HEAD, ...)
  592. *
  593. * @return a map where names of refs point to ref objects
  594. * @throws IOException
  595. */
  596. private Collection<Ref> getAllRefs() throws IOException {
  597. Collection<Ref> refs = RefTreeNames.allRefs(repo.getRefDatabase());
  598. List<Ref> addl = repo.getRefDatabase().getAdditionalRefs();
  599. if (!addl.isEmpty()) {
  600. List<Ref> all = new ArrayList<>(refs.size() + addl.size());
  601. all.addAll(refs);
  602. all.addAll(addl);
  603. return all;
  604. }
  605. return refs;
  606. }
  607. /**
  608. * Return a list of those objects in the index which differ from whats in
  609. * HEAD
  610. *
  611. * @return a set of ObjectIds of changed objects in the index
  612. * @throws IOException
  613. * @throws CorruptObjectException
  614. * @throws NoWorkTreeException
  615. */
  616. private Set<ObjectId> listNonHEADIndexObjects()
  617. throws CorruptObjectException, IOException {
  618. if (repo.isBare()) {
  619. return Collections.emptySet();
  620. }
  621. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  622. treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
  623. ObjectId headID = repo.resolve(Constants.HEAD);
  624. if (headID != null) {
  625. try (RevWalk revWalk = new RevWalk(repo)) {
  626. treeWalk.addTree(revWalk.parseTree(headID));
  627. }
  628. }
  629. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  630. treeWalk.setRecursive(true);
  631. Set<ObjectId> ret = new HashSet<ObjectId>();
  632. while (treeWalk.next()) {
  633. ObjectId objectId = treeWalk.getObjectId(0);
  634. switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
  635. case FileMode.TYPE_MISSING:
  636. case FileMode.TYPE_GITLINK:
  637. continue;
  638. case FileMode.TYPE_TREE:
  639. case FileMode.TYPE_FILE:
  640. case FileMode.TYPE_SYMLINK:
  641. ret.add(objectId);
  642. continue;
  643. default:
  644. throw new IOException(MessageFormat.format(
  645. JGitText.get().corruptObjectInvalidMode3,
  646. String.format("%o", //$NON-NLS-1$
  647. Integer.valueOf(treeWalk.getRawMode(0))),
  648. (objectId == null) ? "null" : objectId.name(), //$NON-NLS-1$
  649. treeWalk.getPathString(), //
  650. repo.getIndexFile()));
  651. }
  652. }
  653. return ret;
  654. }
  655. }
  656. private PackFile writePack(@NonNull Set<? extends ObjectId> want,
  657. @NonNull Set<? extends ObjectId> have, Set<ObjectId> tagTargets,
  658. List<ObjectIdSet> excludeObjects) throws IOException {
  659. File tmpPack = null;
  660. Map<PackExt, File> tmpExts = new TreeMap<PackExt, File>(
  661. new Comparator<PackExt>() {
  662. public int compare(PackExt o1, PackExt o2) {
  663. // INDEX entries must be returned last, so the pack
  664. // scanner does pick up the new pack until all the
  665. // PackExt entries have been written.
  666. if (o1 == o2)
  667. return 0;
  668. if (o1 == PackExt.INDEX)
  669. return 1;
  670. if (o2 == PackExt.INDEX)
  671. return -1;
  672. return Integer.signum(o1.hashCode() - o2.hashCode());
  673. }
  674. });
  675. try (PackWriter pw = new PackWriter(
  676. (pconfig == null) ? new PackConfig(repo) : pconfig,
  677. repo.newObjectReader())) {
  678. // prepare the PackWriter
  679. pw.setDeltaBaseAsOffset(true);
  680. pw.setReuseDeltaCommits(false);
  681. if (tagTargets != null)
  682. pw.setTagTargets(tagTargets);
  683. if (excludeObjects != null)
  684. for (ObjectIdSet idx : excludeObjects)
  685. pw.excludeObjects(idx);
  686. pw.preparePack(pm, want, have);
  687. if (pw.getObjectCount() == 0)
  688. return null;
  689. // create temporary files
  690. String id = pw.computeName().getName();
  691. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  692. tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
  693. final String tmpBase = tmpPack.getName()
  694. .substring(0, tmpPack.getName().lastIndexOf('.'));
  695. File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
  696. tmpExts.put(INDEX, tmpIdx);
  697. if (!tmpIdx.createNewFile())
  698. throw new IOException(MessageFormat.format(
  699. JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
  700. // write the packfile
  701. FileOutputStream fos = new FileOutputStream(tmpPack);
  702. FileChannel channel = fos.getChannel();
  703. OutputStream channelStream = Channels.newOutputStream(channel);
  704. try {
  705. pw.writePack(pm, pm, channelStream);
  706. } finally {
  707. channel.force(true);
  708. channelStream.close();
  709. fos.close();
  710. }
  711. // write the packindex
  712. fos = new FileOutputStream(tmpIdx);
  713. FileChannel idxChannel = fos.getChannel();
  714. OutputStream idxStream = Channels.newOutputStream(idxChannel);
  715. try {
  716. pw.writeIndex(idxStream);
  717. } finally {
  718. idxChannel.force(true);
  719. idxStream.close();
  720. fos.close();
  721. }
  722. if (pw.prepareBitmapIndex(pm)) {
  723. File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
  724. tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
  725. if (!tmpBitmapIdx.createNewFile())
  726. throw new IOException(MessageFormat.format(
  727. JGitText.get().cannotCreateIndexfile,
  728. tmpBitmapIdx.getPath()));
  729. fos = new FileOutputStream(tmpBitmapIdx);
  730. idxChannel = fos.getChannel();
  731. idxStream = Channels.newOutputStream(idxChannel);
  732. try {
  733. pw.writeBitmapIndex(idxStream);
  734. } finally {
  735. idxChannel.force(true);
  736. idxStream.close();
  737. fos.close();
  738. }
  739. }
  740. // rename the temporary files to real files
  741. File realPack = nameFor(id, ".pack"); //$NON-NLS-1$
  742. // if the packfile already exists (because we are rewriting a
  743. // packfile for the same set of objects maybe with different
  744. // PackConfig) then make sure we get rid of all handles on the file.
  745. // Windows will not allow for rename otherwise.
  746. if (realPack.exists())
  747. for (PackFile p : repo.getObjectDatabase().getPacks())
  748. if (realPack.getPath().equals(p.getPackFile().getPath())) {
  749. p.close();
  750. break;
  751. }
  752. tmpPack.setReadOnly();
  753. FileUtils.rename(tmpPack, realPack, StandardCopyOption.ATOMIC_MOVE);
  754. for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
  755. File tmpExt = tmpEntry.getValue();
  756. tmpExt.setReadOnly();
  757. File realExt = nameFor(id,
  758. "." + tmpEntry.getKey().getExtension()); //$NON-NLS-1$
  759. try {
  760. FileUtils.rename(tmpExt, realExt,
  761. StandardCopyOption.ATOMIC_MOVE);
  762. } catch (IOException e) {
  763. File newExt = new File(realExt.getParentFile(),
  764. realExt.getName() + ".new"); //$NON-NLS-1$
  765. try {
  766. FileUtils.rename(tmpExt, newExt,
  767. StandardCopyOption.ATOMIC_MOVE);
  768. } catch (IOException e2) {
  769. newExt = tmpExt;
  770. e = e2;
  771. }
  772. throw new IOException(MessageFormat.format(
  773. JGitText.get().panicCantRenameIndexFile, newExt,
  774. realExt), e);
  775. }
  776. }
  777. return repo.getObjectDatabase().openPack(realPack);
  778. } finally {
  779. if (tmpPack != null && tmpPack.exists())
  780. tmpPack.delete();
  781. for (File tmpExt : tmpExts.values()) {
  782. if (tmpExt.exists())
  783. tmpExt.delete();
  784. }
  785. }
  786. }
  787. private File nameFor(String name, String ext) {
  788. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  789. return new File(packdir, "pack-" + name + ext); //$NON-NLS-1$
  790. }
  791. /**
  792. * A class holding statistical data for a FileRepository regarding how many
  793. * objects are stored as loose or packed objects
  794. */
  795. public class RepoStatistics {
  796. /**
  797. * The number of objects stored in pack files. If the same object is
  798. * stored in multiple pack files then it is counted as often as it
  799. * occurs in pack files.
  800. */
  801. public long numberOfPackedObjects;
  802. /**
  803. * The number of pack files
  804. */
  805. public long numberOfPackFiles;
  806. /**
  807. * The number of objects stored as loose objects.
  808. */
  809. public long numberOfLooseObjects;
  810. /**
  811. * The sum of the sizes of all files used to persist loose objects.
  812. */
  813. public long sizeOfLooseObjects;
  814. /**
  815. * The sum of the sizes of all pack files.
  816. */
  817. public long sizeOfPackedObjects;
  818. /**
  819. * The number of loose refs.
  820. */
  821. public long numberOfLooseRefs;
  822. /**
  823. * The number of refs stored in pack files.
  824. */
  825. public long numberOfPackedRefs;
  826. /**
  827. * The number of bitmaps in the bitmap indices.
  828. */
  829. public long numberOfBitmaps;
  830. public String toString() {
  831. final StringBuilder b = new StringBuilder();
  832. b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
  833. b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
  834. b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
  835. b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
  836. b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
  837. b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
  838. b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
  839. b.append(", numberOfBitmaps=").append(numberOfBitmaps); //$NON-NLS-1$
  840. return b.toString();
  841. }
  842. }
  843. /**
  844. * Returns information about objects and pack files for a FileRepository.
  845. *
  846. * @return information about objects and pack files for a FileRepository
  847. * @throws IOException
  848. */
  849. public RepoStatistics getStatistics() throws IOException {
  850. RepoStatistics ret = new RepoStatistics();
  851. Collection<PackFile> packs = repo.getObjectDatabase().getPacks();
  852. for (PackFile f : packs) {
  853. ret.numberOfPackedObjects += f.getIndex().getObjectCount();
  854. ret.numberOfPackFiles++;
  855. ret.sizeOfPackedObjects += f.getPackFile().length();
  856. if (f.getBitmapIndex() != null)
  857. ret.numberOfBitmaps += f.getBitmapIndex().getBitmapCount();
  858. }
  859. File objDir = repo.getObjectsDirectory();
  860. String[] fanout = objDir.list();
  861. if (fanout != null && fanout.length > 0) {
  862. for (String d : fanout) {
  863. if (d.length() != 2)
  864. continue;
  865. File[] entries = new File(objDir, d).listFiles();
  866. if (entries == null)
  867. continue;
  868. for (File f : entries) {
  869. if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  870. continue;
  871. ret.numberOfLooseObjects++;
  872. ret.sizeOfLooseObjects += f.length();
  873. }
  874. }
  875. }
  876. RefDatabase refDb = repo.getRefDatabase();
  877. for (Ref r : refDb.getRefs(RefDatabase.ALL).values()) {
  878. Storage storage = r.getStorage();
  879. if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
  880. ret.numberOfLooseRefs++;
  881. if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
  882. ret.numberOfPackedRefs++;
  883. }
  884. return ret;
  885. }
  886. /**
  887. * Set the progress monitor used for garbage collection methods.
  888. *
  889. * @param pm
  890. * @return this
  891. */
  892. public GC setProgressMonitor(ProgressMonitor pm) {
  893. this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
  894. return this;
  895. }
  896. /**
  897. * During gc() or prune() each unreferenced, loose object which has been
  898. * created or modified in the last <code>expireAgeMillis</code> milliseconds
  899. * will not be pruned. Only older objects may be pruned. If set to 0 then
  900. * every object is a candidate for pruning.
  901. *
  902. * @param expireAgeMillis
  903. * minimal age of objects to be pruned in milliseconds.
  904. */
  905. public void setExpireAgeMillis(long expireAgeMillis) {
  906. this.expireAgeMillis = expireAgeMillis;
  907. expire = null;
  908. }
  909. /**
  910. * Set the PackConfig used when (re-)writing packfiles. This allows to
  911. * influence how packs are written and to implement something similar to
  912. * "git gc --aggressive"
  913. *
  914. * @since 3.6
  915. * @param pconfig
  916. * the {@link PackConfig} used when writing packs
  917. */
  918. public void setPackConfig(PackConfig pconfig) {
  919. this.pconfig = pconfig;
  920. }
  921. /**
  922. * During gc() or prune() each unreferenced, loose object which has been
  923. * created or modified after or at <code>expire</code> will not be pruned.
  924. * Only older objects may be pruned. If set to null then every object is a
  925. * candidate for pruning.
  926. *
  927. * @param expire
  928. * instant in time which defines object expiration
  929. * objects with modification time before this instant are expired
  930. * objects with modification time newer or equal to this instant
  931. * are not expired
  932. */
  933. public void setExpire(Date expire) {
  934. this.expire = expire;
  935. expireAgeMillis = -1;
  936. }
  937. }