Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

GC.java 49KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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.io.PrintWriter;
  52. import java.io.StringWriter;
  53. import java.nio.channels.Channels;
  54. import java.nio.channels.FileChannel;
  55. import java.nio.file.DirectoryNotEmptyException;
  56. import java.nio.file.DirectoryStream;
  57. import java.nio.file.Files;
  58. import java.nio.file.Path;
  59. import java.nio.file.StandardCopyOption;
  60. import java.text.MessageFormat;
  61. import java.text.ParseException;
  62. import java.time.Instant;
  63. import java.time.temporal.ChronoUnit;
  64. import java.util.ArrayList;
  65. import java.util.Collection;
  66. import java.util.Collections;
  67. import java.util.Comparator;
  68. import java.util.Date;
  69. import java.util.HashMap;
  70. import java.util.HashSet;
  71. import java.util.Iterator;
  72. import java.util.LinkedList;
  73. import java.util.List;
  74. import java.util.Map;
  75. import java.util.Objects;
  76. import java.util.Set;
  77. import java.util.TreeMap;
  78. import java.util.concurrent.Callable;
  79. import java.util.concurrent.ExecutorService;
  80. import java.util.regex.Pattern;
  81. import java.util.stream.Collectors;
  82. import java.util.stream.Stream;
  83. import org.eclipse.jgit.annotations.NonNull;
  84. import org.eclipse.jgit.dircache.DirCacheIterator;
  85. import org.eclipse.jgit.errors.CancelledException;
  86. import org.eclipse.jgit.errors.CorruptObjectException;
  87. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  88. import org.eclipse.jgit.errors.MissingObjectException;
  89. import org.eclipse.jgit.errors.NoWorkTreeException;
  90. import org.eclipse.jgit.internal.JGitText;
  91. import org.eclipse.jgit.internal.storage.pack.PackExt;
  92. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  93. import org.eclipse.jgit.internal.storage.reftree.RefTreeNames;
  94. import org.eclipse.jgit.lib.ConfigConstants;
  95. import org.eclipse.jgit.lib.Constants;
  96. import org.eclipse.jgit.lib.FileMode;
  97. import org.eclipse.jgit.lib.NullProgressMonitor;
  98. import org.eclipse.jgit.lib.ObjectId;
  99. import org.eclipse.jgit.lib.ObjectIdSet;
  100. import org.eclipse.jgit.lib.ObjectLoader;
  101. import org.eclipse.jgit.lib.ObjectReader;
  102. import org.eclipse.jgit.lib.ProgressMonitor;
  103. import org.eclipse.jgit.lib.Ref;
  104. import org.eclipse.jgit.lib.Ref.Storage;
  105. import org.eclipse.jgit.lib.RefDatabase;
  106. import org.eclipse.jgit.lib.ReflogEntry;
  107. import org.eclipse.jgit.lib.ReflogReader;
  108. import org.eclipse.jgit.lib.internal.WorkQueue;
  109. import org.eclipse.jgit.revwalk.ObjectWalk;
  110. import org.eclipse.jgit.revwalk.RevObject;
  111. import org.eclipse.jgit.revwalk.RevWalk;
  112. import org.eclipse.jgit.storage.pack.PackConfig;
  113. import org.eclipse.jgit.treewalk.TreeWalk;
  114. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  115. import org.eclipse.jgit.util.FileUtils;
  116. import org.eclipse.jgit.util.GitDateParser;
  117. import org.eclipse.jgit.util.SystemReader;
  118. import org.slf4j.Logger;
  119. import org.slf4j.LoggerFactory;
  120. /**
  121. * A garbage collector for git
  122. * {@link org.eclipse.jgit.internal.storage.file.FileRepository}. Instances of
  123. * this class are not thread-safe. Don't use the same instance from multiple
  124. * threads.
  125. *
  126. * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
  127. * adapted to FileRepositories.
  128. */
  129. public class GC {
  130. private final static Logger LOG = LoggerFactory
  131. .getLogger(GC.class);
  132. private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
  133. private static final String PRUNE_PACK_EXPIRE_DEFAULT = "1.hour.ago"; //$NON-NLS-1$
  134. private static final Pattern PATTERN_LOOSE_OBJECT = Pattern
  135. .compile("[0-9a-fA-F]{38}"); //$NON-NLS-1$
  136. private static final String PACK_EXT = "." + PackExt.PACK.getExtension();//$NON-NLS-1$
  137. private static final String BITMAP_EXT = "." //$NON-NLS-1$
  138. + PackExt.BITMAP_INDEX.getExtension();
  139. private static final String INDEX_EXT = "." + PackExt.INDEX.getExtension(); //$NON-NLS-1$
  140. private static final int DEFAULT_AUTOPACKLIMIT = 50;
  141. private static final int DEFAULT_AUTOLIMIT = 6700;
  142. private static volatile ExecutorService executor;
  143. /**
  144. * Set the executor for running auto-gc in the background. If no executor is
  145. * set JGit's own WorkQueue will be used.
  146. *
  147. * @param e
  148. * the executor to be used for running auto-gc
  149. * @since 4.8
  150. */
  151. public static void setExecutor(ExecutorService e) {
  152. executor = e;
  153. }
  154. private final FileRepository repo;
  155. private ProgressMonitor pm;
  156. private long expireAgeMillis = -1;
  157. private Date expire;
  158. private long packExpireAgeMillis = -1;
  159. private Date packExpire;
  160. private PackConfig pconfig = null;
  161. /**
  162. * the refs which existed during the last call to {@link #repack()}. This is
  163. * needed during {@link #prune(Set)} where we can optimize by looking at the
  164. * difference between the current refs and the refs which existed during
  165. * last {@link #repack()}.
  166. */
  167. private Collection<Ref> lastPackedRefs;
  168. /**
  169. * Holds the starting time of the last repack() execution. This is needed in
  170. * prune() to inspect only those reflog entries which have been added since
  171. * last repack().
  172. */
  173. private long lastRepackTime;
  174. /**
  175. * Whether gc should do automatic housekeeping
  176. */
  177. private boolean automatic;
  178. /**
  179. * Whether to run gc in a background thread
  180. */
  181. private boolean background;
  182. /**
  183. * Creates a new garbage collector with default values. An expirationTime of
  184. * two weeks and <code>null</code> as progress monitor will be used.
  185. *
  186. * @param repo
  187. * the repo to work on
  188. */
  189. public GC(FileRepository repo) {
  190. this.repo = repo;
  191. this.pm = NullProgressMonitor.INSTANCE;
  192. }
  193. /**
  194. * Runs a garbage collector on a
  195. * {@link org.eclipse.jgit.internal.storage.file.FileRepository}. It will
  196. * <ul>
  197. * <li>pack loose references into packed-refs</li>
  198. * <li>repack all reachable objects into new pack files and delete the old
  199. * pack files</li>
  200. * <li>prune all loose objects which are now reachable by packs</li>
  201. * </ul>
  202. *
  203. * If {@link #setAuto(boolean)} was set to {@code true} {@code gc} will
  204. * first check whether any housekeeping is required; if not, it exits
  205. * without performing any work.
  206. *
  207. * If {@link #setBackground(boolean)} was set to {@code true}
  208. * {@code collectGarbage} will start the gc in the background, and then
  209. * return immediately. In this case, errors will not be reported except in
  210. * gc.log.
  211. *
  212. * @return the collection of
  213. * {@link org.eclipse.jgit.internal.storage.file.PackFile}'s which
  214. * are newly created
  215. * @throws java.io.IOException
  216. * @throws java.text.ParseException
  217. * If the configuration parameter "gc.pruneexpire" couldn't be
  218. * parsed
  219. */
  220. // TODO(ms): in 5.0 change signature and return Future<Collection<PackFile>>
  221. @SuppressWarnings("FutureReturnValueIgnored")
  222. public Collection<PackFile> gc() throws IOException, ParseException {
  223. if (!background) {
  224. return doGc();
  225. }
  226. final GcLog gcLog = new GcLog(repo);
  227. if (!gcLog.lock()) {
  228. // there is already a background gc running
  229. return Collections.emptyList();
  230. }
  231. Callable<Collection<PackFile>> gcTask = () -> {
  232. try {
  233. Collection<PackFile> newPacks = doGc();
  234. if (automatic && tooManyLooseObjects()) {
  235. String message = JGitText.get().gcTooManyUnpruned;
  236. gcLog.write(message);
  237. gcLog.commit();
  238. }
  239. return newPacks;
  240. } catch (IOException | ParseException e) {
  241. try {
  242. gcLog.write(e.getMessage());
  243. StringWriter sw = new StringWriter();
  244. e.printStackTrace(new PrintWriter(sw));
  245. gcLog.write(sw.toString());
  246. gcLog.commit();
  247. } catch (IOException e2) {
  248. e2.addSuppressed(e);
  249. LOG.error(e2.getMessage(), e2);
  250. }
  251. } finally {
  252. gcLog.unlock();
  253. }
  254. return Collections.emptyList();
  255. };
  256. // TODO(ms): in 5.0 change signature and return the Future
  257. executor().submit(gcTask);
  258. return Collections.emptyList();
  259. }
  260. private ExecutorService executor() {
  261. return (executor != null) ? executor : WorkQueue.getExecutor();
  262. }
  263. private Collection<PackFile> doGc() throws IOException, ParseException {
  264. if (automatic && !needGc()) {
  265. return Collections.emptyList();
  266. }
  267. pm.start(6 /* tasks */);
  268. packRefs();
  269. // TODO: implement reflog_expire(pm, repo);
  270. Collection<PackFile> newPacks = repack();
  271. prune(Collections.emptySet());
  272. // TODO: implement rerere_gc(pm);
  273. return newPacks;
  274. }
  275. /**
  276. * Loosen objects in a pack file which are not also in the newly-created
  277. * pack files.
  278. *
  279. * @param inserter
  280. * @param reader
  281. * @param pack
  282. * @param existing
  283. * @throws IOException
  284. */
  285. private void loosen(ObjectDirectoryInserter inserter, ObjectReader reader, PackFile pack, HashSet<ObjectId> existing)
  286. throws IOException {
  287. for (PackIndex.MutableEntry entry : pack) {
  288. ObjectId oid = entry.toObjectId();
  289. if (existing.contains(oid)) {
  290. continue;
  291. }
  292. existing.add(oid);
  293. ObjectLoader loader = reader.open(oid);
  294. inserter.insert(loader.getType(),
  295. loader.getSize(),
  296. loader.openStream(),
  297. true /* create this object even though it's a duplicate */);
  298. }
  299. }
  300. /**
  301. * Delete old pack files. What is 'old' is defined by specifying a set of
  302. * old pack files and a set of new pack files. Each pack file contained in
  303. * old pack files but not contained in new pack files will be deleted. If
  304. * preserveOldPacks is set, keep a copy of the pack file in the preserve
  305. * directory. If an expirationDate is set then pack files which are younger
  306. * than the expirationDate will not be deleted nor preserved.
  307. * <p>
  308. * If we're not immediately expiring loose objects, loosen any objects
  309. * in the old pack files which aren't in the new pack files.
  310. *
  311. * @param oldPacks
  312. * @param newPacks
  313. * @throws ParseException
  314. * @throws IOException
  315. */
  316. private void deleteOldPacks(Collection<PackFile> oldPacks,
  317. Collection<PackFile> newPacks) throws ParseException, IOException {
  318. HashSet<ObjectId> ids = new HashSet<>();
  319. for (PackFile pack : newPacks) {
  320. for (PackIndex.MutableEntry entry : pack) {
  321. ids.add(entry.toObjectId());
  322. }
  323. }
  324. ObjectReader reader = repo.newObjectReader();
  325. ObjectDirectory dir = repo.getObjectDatabase();
  326. ObjectDirectoryInserter inserter = dir.newInserter();
  327. boolean shouldLoosen = !"now".equals(getPruneExpireStr()) && //$NON-NLS-1$
  328. getExpireDate() < Long.MAX_VALUE;
  329. prunePreserved();
  330. long packExpireDate = getPackExpireDate();
  331. oldPackLoop: for (PackFile oldPack : oldPacks) {
  332. checkCancelled();
  333. String oldName = oldPack.getPackName();
  334. // check whether an old pack file is also among the list of new
  335. // pack files. Then we must not delete it.
  336. for (PackFile newPack : newPacks)
  337. if (oldName.equals(newPack.getPackName()))
  338. continue oldPackLoop;
  339. if (!oldPack.shouldBeKept()
  340. && repo.getFS().lastModified(
  341. oldPack.getPackFile()) < packExpireDate) {
  342. oldPack.close();
  343. if (shouldLoosen) {
  344. loosen(inserter, reader, oldPack, ids);
  345. }
  346. prunePack(oldName);
  347. }
  348. }
  349. // close the complete object database. That's my only chance to force
  350. // rescanning and to detect that certain pack files are now deleted.
  351. repo.getObjectDatabase().close();
  352. }
  353. /**
  354. * Deletes old pack file, unless 'preserve-oldpacks' is set, in which case it
  355. * moves the pack file to the preserved directory
  356. *
  357. * @param packFile
  358. * @param packName
  359. * @param ext
  360. * @param deleteOptions
  361. * @throws IOException
  362. */
  363. private void removeOldPack(File packFile, String packName, PackExt ext,
  364. int deleteOptions) throws IOException {
  365. if (pconfig != null && pconfig.isPreserveOldPacks()) {
  366. File oldPackDir = repo.getObjectDatabase().getPreservedDirectory();
  367. FileUtils.mkdir(oldPackDir, true);
  368. String oldPackName = "pack-" + packName + ".old-" + ext.getExtension(); //$NON-NLS-1$ //$NON-NLS-2$
  369. File oldPackFile = new File(oldPackDir, oldPackName);
  370. FileUtils.rename(packFile, oldPackFile);
  371. } else {
  372. FileUtils.delete(packFile, deleteOptions);
  373. }
  374. }
  375. /**
  376. * Delete the preserved directory including all pack files within
  377. */
  378. private void prunePreserved() {
  379. if (pconfig != null && pconfig.isPrunePreserved()) {
  380. try {
  381. FileUtils.delete(repo.getObjectDatabase().getPreservedDirectory(),
  382. FileUtils.RECURSIVE | FileUtils.RETRY | FileUtils.SKIP_MISSING);
  383. } catch (IOException e) {
  384. // Deletion of the preserved pack files failed. Silently return.
  385. }
  386. }
  387. }
  388. /**
  389. * Delete files associated with a single pack file. First try to delete the
  390. * ".pack" file because on some platforms the ".pack" file may be locked and
  391. * can't be deleted. In such a case it is better to detect this early and
  392. * give up on deleting files for this packfile. Otherwise we may delete the
  393. * ".index" file and when failing to delete the ".pack" file we are left
  394. * with a ".pack" file without a ".index" file.
  395. *
  396. * @param packName
  397. */
  398. private void prunePack(String packName) {
  399. PackExt[] extensions = PackExt.values();
  400. try {
  401. // Delete the .pack file first and if this fails give up on deleting
  402. // the other files
  403. int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  404. for (PackExt ext : extensions)
  405. if (PackExt.PACK.equals(ext)) {
  406. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  407. removeOldPack(f, packName, ext, deleteOptions);
  408. break;
  409. }
  410. // The .pack file has been deleted. Delete as many as the other
  411. // files as you can.
  412. deleteOptions |= FileUtils.IGNORE_ERRORS;
  413. for (PackExt ext : extensions) {
  414. if (!PackExt.PACK.equals(ext)) {
  415. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  416. removeOldPack(f, packName, ext, deleteOptions);
  417. }
  418. }
  419. } catch (IOException e) {
  420. // Deletion of the .pack file failed. Silently return.
  421. }
  422. }
  423. /**
  424. * Like "git prune-packed" this method tries to prune all loose objects
  425. * which can be found in packs. If certain objects can't be pruned (e.g.
  426. * because the filesystem delete operation fails) this is silently ignored.
  427. *
  428. * @throws java.io.IOException
  429. */
  430. public void prunePacked() throws IOException {
  431. ObjectDirectory objdb = repo.getObjectDatabase();
  432. Collection<PackFile> packs = objdb.getPacks();
  433. File objects = repo.getObjectsDirectory();
  434. String[] fanout = objects.list();
  435. if (fanout != null && fanout.length > 0) {
  436. pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
  437. try {
  438. for (String d : fanout) {
  439. checkCancelled();
  440. pm.update(1);
  441. if (d.length() != 2)
  442. continue;
  443. String[] entries = new File(objects, d).list();
  444. if (entries == null)
  445. continue;
  446. for (String e : entries) {
  447. checkCancelled();
  448. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  449. continue;
  450. ObjectId id;
  451. try {
  452. id = ObjectId.fromString(d + e);
  453. } catch (IllegalArgumentException notAnObject) {
  454. // ignoring the file that does not represent loose
  455. // object
  456. continue;
  457. }
  458. boolean found = false;
  459. for (PackFile p : packs) {
  460. checkCancelled();
  461. if (p.hasObject(id)) {
  462. found = true;
  463. break;
  464. }
  465. }
  466. if (found)
  467. FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
  468. | FileUtils.SKIP_MISSING
  469. | FileUtils.IGNORE_ERRORS);
  470. }
  471. }
  472. } finally {
  473. pm.endTask();
  474. }
  475. }
  476. }
  477. /**
  478. * Like "git prune" this method tries to prune all loose objects which are
  479. * unreferenced. If certain objects can't be pruned (e.g. because the
  480. * filesystem delete operation fails) this is silently ignored.
  481. *
  482. * @param objectsToKeep
  483. * a set of objects which should explicitly not be pruned
  484. * @throws java.io.IOException
  485. * @throws java.text.ParseException
  486. * If the configuration parameter "gc.pruneexpire" couldn't be
  487. * parsed
  488. */
  489. public void prune(Set<ObjectId> objectsToKeep) throws IOException,
  490. ParseException {
  491. long expireDate = getExpireDate();
  492. // Collect all loose objects which are old enough, not referenced from
  493. // the index and not in objectsToKeep
  494. Map<ObjectId, File> deletionCandidates = new HashMap<>();
  495. Set<ObjectId> indexObjects = null;
  496. File objects = repo.getObjectsDirectory();
  497. String[] fanout = objects.list();
  498. if (fanout == null || fanout.length == 0) {
  499. return;
  500. }
  501. pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
  502. fanout.length);
  503. try {
  504. for (String d : fanout) {
  505. checkCancelled();
  506. pm.update(1);
  507. if (d.length() != 2)
  508. continue;
  509. File[] entries = new File(objects, d).listFiles();
  510. if (entries == null)
  511. continue;
  512. for (File f : entries) {
  513. checkCancelled();
  514. String fName = f.getName();
  515. if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  516. continue;
  517. if (repo.getFS().lastModified(f) >= expireDate)
  518. continue;
  519. try {
  520. ObjectId id = ObjectId.fromString(d + fName);
  521. if (objectsToKeep.contains(id))
  522. continue;
  523. if (indexObjects == null)
  524. indexObjects = listNonHEADIndexObjects();
  525. if (indexObjects.contains(id))
  526. continue;
  527. deletionCandidates.put(id, f);
  528. } catch (IllegalArgumentException notAnObject) {
  529. // ignoring the file that does not represent loose
  530. // object
  531. }
  532. }
  533. }
  534. } finally {
  535. pm.endTask();
  536. }
  537. if (deletionCandidates.isEmpty()) {
  538. return;
  539. }
  540. checkCancelled();
  541. // From the set of current refs remove all those which have been handled
  542. // during last repack(). Only those refs will survive which have been
  543. // added or modified since the last repack. Only these can save existing
  544. // loose refs from being pruned.
  545. Collection<Ref> newRefs;
  546. if (lastPackedRefs == null || lastPackedRefs.isEmpty())
  547. newRefs = getAllRefs();
  548. else {
  549. Map<String, Ref> last = new HashMap<>();
  550. for (Ref r : lastPackedRefs) {
  551. last.put(r.getName(), r);
  552. }
  553. newRefs = new ArrayList<>();
  554. for (Ref r : getAllRefs()) {
  555. Ref old = last.get(r.getName());
  556. if (!equals(r, old)) {
  557. newRefs.add(r);
  558. }
  559. }
  560. }
  561. if (!newRefs.isEmpty()) {
  562. // There are new/modified refs! Check which loose objects are now
  563. // referenced by these modified refs (or their reflogentries).
  564. // Remove these loose objects
  565. // from the deletionCandidates. When the last candidate is removed
  566. // leave this method.
  567. ObjectWalk w = new ObjectWalk(repo);
  568. try {
  569. for (Ref cr : newRefs) {
  570. checkCancelled();
  571. w.markStart(w.parseAny(cr.getObjectId()));
  572. }
  573. if (lastPackedRefs != null)
  574. for (Ref lpr : lastPackedRefs) {
  575. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  576. }
  577. removeReferenced(deletionCandidates, w);
  578. } finally {
  579. w.dispose();
  580. }
  581. }
  582. if (deletionCandidates.isEmpty())
  583. return;
  584. // Since we have not left the method yet there are still
  585. // deletionCandidates. Last chance for these objects not to be pruned is
  586. // that they are referenced by reflog entries. Even refs which currently
  587. // point to the same object as during last repack() may have
  588. // additional reflog entries not handled during last repack()
  589. ObjectWalk w = new ObjectWalk(repo);
  590. try {
  591. for (Ref ar : getAllRefs())
  592. for (ObjectId id : listRefLogObjects(ar, lastRepackTime)) {
  593. checkCancelled();
  594. w.markStart(w.parseAny(id));
  595. }
  596. if (lastPackedRefs != null)
  597. for (Ref lpr : lastPackedRefs) {
  598. checkCancelled();
  599. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  600. }
  601. removeReferenced(deletionCandidates, w);
  602. } finally {
  603. w.dispose();
  604. }
  605. if (deletionCandidates.isEmpty())
  606. return;
  607. checkCancelled();
  608. // delete all candidates which have survived: these are unreferenced
  609. // loose objects. Make a last check, though, to avoid deleting objects
  610. // that could have been referenced while the candidates list was being
  611. // built (by an incoming push, for example).
  612. Set<File> touchedFanout = new HashSet<>();
  613. for (File f : deletionCandidates.values()) {
  614. if (f.lastModified() < expireDate) {
  615. f.delete();
  616. touchedFanout.add(f.getParentFile());
  617. }
  618. }
  619. for (File f : touchedFanout) {
  620. FileUtils.delete(f,
  621. FileUtils.EMPTY_DIRECTORIES_ONLY | FileUtils.IGNORE_ERRORS);
  622. }
  623. repo.getObjectDatabase().close();
  624. }
  625. private long getExpireDate() throws ParseException {
  626. long expireDate = Long.MAX_VALUE;
  627. if (expire == null && expireAgeMillis == -1) {
  628. String pruneExpireStr = getPruneExpireStr();
  629. if (pruneExpireStr == null)
  630. pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
  631. expire = GitDateParser.parse(pruneExpireStr, null, SystemReader
  632. .getInstance().getLocale());
  633. expireAgeMillis = -1;
  634. }
  635. if (expire != null)
  636. expireDate = expire.getTime();
  637. if (expireAgeMillis != -1)
  638. expireDate = System.currentTimeMillis() - expireAgeMillis;
  639. return expireDate;
  640. }
  641. private String getPruneExpireStr() {
  642. return repo.getConfig().getString(
  643. ConfigConstants.CONFIG_GC_SECTION, null,
  644. ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
  645. }
  646. private long getPackExpireDate() throws ParseException {
  647. long packExpireDate = Long.MAX_VALUE;
  648. if (packExpire == null && packExpireAgeMillis == -1) {
  649. String prunePackExpireStr = repo.getConfig().getString(
  650. ConfigConstants.CONFIG_GC_SECTION, null,
  651. ConfigConstants.CONFIG_KEY_PRUNEPACKEXPIRE);
  652. if (prunePackExpireStr == null)
  653. prunePackExpireStr = PRUNE_PACK_EXPIRE_DEFAULT;
  654. packExpire = GitDateParser.parse(prunePackExpireStr, null,
  655. SystemReader.getInstance().getLocale());
  656. packExpireAgeMillis = -1;
  657. }
  658. if (packExpire != null)
  659. packExpireDate = packExpire.getTime();
  660. if (packExpireAgeMillis != -1)
  661. packExpireDate = System.currentTimeMillis() - packExpireAgeMillis;
  662. return packExpireDate;
  663. }
  664. /**
  665. * Remove all entries from a map which key is the id of an object referenced
  666. * by the given ObjectWalk
  667. *
  668. * @param id2File
  669. * @param w
  670. * @throws MissingObjectException
  671. * @throws IncorrectObjectTypeException
  672. * @throws IOException
  673. */
  674. private void removeReferenced(Map<ObjectId, File> id2File,
  675. ObjectWalk w) throws MissingObjectException,
  676. IncorrectObjectTypeException, IOException {
  677. RevObject ro = w.next();
  678. while (ro != null) {
  679. checkCancelled();
  680. if (id2File.remove(ro.getId()) != null && id2File.isEmpty()) {
  681. return;
  682. }
  683. ro = w.next();
  684. }
  685. ro = w.nextObject();
  686. while (ro != null) {
  687. checkCancelled();
  688. if (id2File.remove(ro.getId()) != null && id2File.isEmpty()) {
  689. return;
  690. }
  691. ro = w.nextObject();
  692. }
  693. }
  694. private static boolean equals(Ref r1, Ref r2) {
  695. if (r1 == null || r2 == null) {
  696. return false;
  697. }
  698. if (r1.isSymbolic()) {
  699. return r2.isSymbolic() && r1.getTarget().getName()
  700. .equals(r2.getTarget().getName());
  701. }
  702. return !r2.isSymbolic()
  703. && Objects.equals(r1.getObjectId(), r2.getObjectId());
  704. }
  705. /**
  706. * Packs all non-symbolic, loose refs into packed-refs.
  707. *
  708. * @throws java.io.IOException
  709. */
  710. public void packRefs() throws IOException {
  711. Collection<Ref> refs = repo.getRefDatabase()
  712. .getRefsByPrefix(Constants.R_REFS);
  713. List<String> refsToBePacked = new ArrayList<>(refs.size());
  714. pm.beginTask(JGitText.get().packRefs, refs.size());
  715. try {
  716. for (Ref ref : refs) {
  717. checkCancelled();
  718. if (!ref.isSymbolic() && ref.getStorage().isLoose())
  719. refsToBePacked.add(ref.getName());
  720. pm.update(1);
  721. }
  722. ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
  723. } finally {
  724. pm.endTask();
  725. }
  726. }
  727. /**
  728. * Packs all objects which reachable from any of the heads into one pack
  729. * file. Additionally all objects which are not reachable from any head but
  730. * which are reachable from any of the other refs (e.g. tags), special refs
  731. * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
  732. * included in pack files which have a .keep file associated are never
  733. * repacked. All old pack files which existed before are deleted.
  734. *
  735. * @return a collection of the newly created pack files
  736. * @throws java.io.IOException
  737. * when during reading of refs, index, packfiles, objects,
  738. * reflog-entries or during writing to the packfiles
  739. * {@link java.io.IOException} occurs
  740. */
  741. public Collection<PackFile> repack() throws IOException {
  742. Collection<PackFile> toBeDeleted = repo.getObjectDatabase().getPacks();
  743. long time = System.currentTimeMillis();
  744. Collection<Ref> refsBefore = getAllRefs();
  745. Set<ObjectId> allHeadsAndTags = new HashSet<>();
  746. Set<ObjectId> allHeads = new HashSet<>();
  747. Set<ObjectId> allTags = new HashSet<>();
  748. Set<ObjectId> nonHeads = new HashSet<>();
  749. Set<ObjectId> txnHeads = new HashSet<>();
  750. Set<ObjectId> tagTargets = new HashSet<>();
  751. Set<ObjectId> indexObjects = listNonHEADIndexObjects();
  752. RefDatabase refdb = repo.getRefDatabase();
  753. for (Ref ref : refsBefore) {
  754. checkCancelled();
  755. nonHeads.addAll(listRefLogObjects(ref, 0));
  756. if (ref.isSymbolic() || ref.getObjectId() == null) {
  757. continue;
  758. }
  759. if (isHead(ref)) {
  760. allHeads.add(ref.getObjectId());
  761. } else if (isTag(ref)) {
  762. allTags.add(ref.getObjectId());
  763. } else if (RefTreeNames.isRefTree(refdb, ref.getName())) {
  764. txnHeads.add(ref.getObjectId());
  765. } else {
  766. nonHeads.add(ref.getObjectId());
  767. }
  768. if (ref.getPeeledObjectId() != null) {
  769. tagTargets.add(ref.getPeeledObjectId());
  770. }
  771. }
  772. List<ObjectIdSet> excluded = new LinkedList<>();
  773. for (PackFile f : repo.getObjectDatabase().getPacks()) {
  774. checkCancelled();
  775. if (f.shouldBeKept())
  776. excluded.add(f.getIndex());
  777. }
  778. // Don't exclude tags that are also branch tips
  779. allTags.removeAll(allHeads);
  780. allHeadsAndTags.addAll(allHeads);
  781. allHeadsAndTags.addAll(allTags);
  782. // Hoist all branch tips and tags earlier in the pack file
  783. tagTargets.addAll(allHeadsAndTags);
  784. nonHeads.addAll(indexObjects);
  785. // Combine the GC_REST objects into the GC pack if requested
  786. if (pconfig != null && pconfig.getSinglePack()) {
  787. allHeadsAndTags.addAll(nonHeads);
  788. nonHeads.clear();
  789. }
  790. List<PackFile> ret = new ArrayList<>(2);
  791. PackFile heads = null;
  792. if (!allHeadsAndTags.isEmpty()) {
  793. heads = writePack(allHeadsAndTags, PackWriter.NONE, allTags,
  794. tagTargets, excluded);
  795. if (heads != null) {
  796. ret.add(heads);
  797. excluded.add(0, heads.getIndex());
  798. }
  799. }
  800. if (!nonHeads.isEmpty()) {
  801. PackFile rest = writePack(nonHeads, allHeadsAndTags, PackWriter.NONE,
  802. tagTargets, excluded);
  803. if (rest != null)
  804. ret.add(rest);
  805. }
  806. if (!txnHeads.isEmpty()) {
  807. PackFile txn = writePack(txnHeads, PackWriter.NONE, PackWriter.NONE,
  808. null, excluded);
  809. if (txn != null)
  810. ret.add(txn);
  811. }
  812. try {
  813. deleteOldPacks(toBeDeleted, ret);
  814. } catch (ParseException e) {
  815. // TODO: the exception has to be wrapped into an IOException because
  816. // throwing the ParseException directly would break the API, instead
  817. // we should throw a ConfigInvalidException
  818. throw new IOException(e);
  819. }
  820. prunePacked();
  821. deleteEmptyRefsFolders();
  822. deleteOrphans();
  823. deleteTempPacksIdx();
  824. lastPackedRefs = refsBefore;
  825. lastRepackTime = time;
  826. return ret;
  827. }
  828. private static boolean isHead(Ref ref) {
  829. return ref.getName().startsWith(Constants.R_HEADS);
  830. }
  831. private static boolean isTag(Ref ref) {
  832. return ref.getName().startsWith(Constants.R_TAGS);
  833. }
  834. private void deleteEmptyRefsFolders() throws IOException {
  835. Path refs = repo.getDirectory().toPath().resolve(Constants.R_REFS);
  836. // Avoid deleting a folder that was created after the threshold so that concurrent
  837. // operations trying to create a reference are not impacted
  838. Instant threshold = Instant.now().minus(30, ChronoUnit.SECONDS);
  839. try (Stream<Path> entries = Files.list(refs)) {
  840. Iterator<Path> iterator = entries.iterator();
  841. while (iterator.hasNext()) {
  842. try (Stream<Path> s = Files.list(iterator.next())) {
  843. s.filter(path -> canBeSafelyDeleted(path, threshold)).forEach(this::deleteDir);
  844. }
  845. }
  846. }
  847. }
  848. private boolean canBeSafelyDeleted(Path path, Instant threshold) {
  849. try {
  850. return Files.getLastModifiedTime(path).toInstant().isBefore(threshold);
  851. }
  852. catch (IOException e) {
  853. LOG.warn(MessageFormat.format(
  854. JGitText.get().cannotAccessLastModifiedForSafeDeletion,
  855. path), e);
  856. return false;
  857. }
  858. }
  859. private void deleteDir(Path dir) {
  860. try (Stream<Path> dirs = Files.walk(dir)) {
  861. dirs.filter(this::isDirectory).sorted(Comparator.reverseOrder())
  862. .forEach(this::delete);
  863. } catch (IOException e) {
  864. LOG.error(e.getMessage(), e);
  865. }
  866. }
  867. private boolean isDirectory(Path p) {
  868. return p.toFile().isDirectory();
  869. }
  870. private void delete(Path d) {
  871. try {
  872. Files.delete(d);
  873. } catch (DirectoryNotEmptyException e) {
  874. // Don't log
  875. } catch (IOException e) {
  876. LOG.error(MessageFormat.format(JGitText.get().cannotDeleteFile, d),
  877. e);
  878. }
  879. }
  880. /**
  881. * Deletes orphans
  882. * <p>
  883. * A file is considered an orphan if it is either a "bitmap" or an index
  884. * file, and its corresponding pack file is missing in the list.
  885. * </p>
  886. */
  887. private void deleteOrphans() {
  888. Path packDir = repo.getObjectDatabase().getPackDirectory().toPath();
  889. List<String> fileNames = null;
  890. try (Stream<Path> files = Files.list(packDir)) {
  891. fileNames = files.map(path -> path.getFileName().toString())
  892. .filter(name -> (name.endsWith(PACK_EXT)
  893. || name.endsWith(BITMAP_EXT)
  894. || name.endsWith(INDEX_EXT)))
  895. .sorted(Collections.reverseOrder())
  896. .collect(Collectors.toList());
  897. } catch (IOException e1) {
  898. // ignore
  899. }
  900. if (fileNames == null) {
  901. return;
  902. }
  903. String base = null;
  904. for (String n : fileNames) {
  905. if (n.endsWith(PACK_EXT)) {
  906. base = n.substring(0, n.lastIndexOf('.'));
  907. } else {
  908. if (base == null || !n.startsWith(base)) {
  909. try {
  910. Files.delete(packDir.resolve(n));
  911. } catch (IOException e) {
  912. LOG.error(e.getMessage(), e);
  913. }
  914. }
  915. }
  916. }
  917. }
  918. private void deleteTempPacksIdx() {
  919. Path packDir = repo.getObjectDatabase().getPackDirectory().toPath();
  920. Instant threshold = Instant.now().minus(1, ChronoUnit.DAYS);
  921. if (!Files.exists(packDir)) {
  922. return;
  923. }
  924. try (DirectoryStream<Path> stream =
  925. Files.newDirectoryStream(packDir, "gc_*_tmp")) { //$NON-NLS-1$
  926. stream.forEach(t -> {
  927. try {
  928. Instant lastModified = Files.getLastModifiedTime(t)
  929. .toInstant();
  930. if (lastModified.isBefore(threshold)) {
  931. Files.deleteIfExists(t);
  932. }
  933. } catch (IOException e) {
  934. LOG.error(e.getMessage(), e);
  935. }
  936. });
  937. } catch (IOException e) {
  938. LOG.error(e.getMessage(), e);
  939. }
  940. }
  941. /**
  942. * @param ref
  943. * the ref which log should be inspected
  944. * @param minTime only reflog entries not older then this time are processed
  945. * @return the {@link ObjectId}s contained in the reflog
  946. * @throws IOException
  947. */
  948. private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
  949. ReflogReader reflogReader = repo.getReflogReader(ref.getName());
  950. if (reflogReader == null) {
  951. return Collections.emptySet();
  952. }
  953. List<ReflogEntry> rlEntries = reflogReader
  954. .getReverseEntries();
  955. if (rlEntries == null || rlEntries.isEmpty())
  956. return Collections.emptySet();
  957. Set<ObjectId> ret = new HashSet<>();
  958. for (ReflogEntry e : rlEntries) {
  959. if (e.getWho().getWhen().getTime() < minTime)
  960. break;
  961. ObjectId newId = e.getNewId();
  962. if (newId != null && !ObjectId.zeroId().equals(newId))
  963. ret.add(newId);
  964. ObjectId oldId = e.getOldId();
  965. if (oldId != null && !ObjectId.zeroId().equals(oldId))
  966. ret.add(oldId);
  967. }
  968. return ret;
  969. }
  970. /**
  971. * Returns a collection of all refs and additional refs.
  972. *
  973. * Additional refs which don't start with "refs/" are not returned because
  974. * they should not save objects from being garbage collected. Examples for
  975. * such references are ORIG_HEAD, MERGE_HEAD, FETCH_HEAD and
  976. * CHERRY_PICK_HEAD.
  977. *
  978. * @return a collection of refs pointing to live objects.
  979. * @throws IOException
  980. */
  981. private Collection<Ref> getAllRefs() throws IOException {
  982. RefDatabase refdb = repo.getRefDatabase();
  983. Collection<Ref> refs = refdb.getRefs();
  984. List<Ref> addl = refdb.getAdditionalRefs();
  985. if (!addl.isEmpty()) {
  986. List<Ref> all = new ArrayList<>(refs.size() + addl.size());
  987. all.addAll(refs);
  988. // add additional refs which start with refs/
  989. for (Ref r : addl) {
  990. checkCancelled();
  991. if (r.getName().startsWith(Constants.R_REFS)) {
  992. all.add(r);
  993. }
  994. }
  995. return all;
  996. }
  997. return refs;
  998. }
  999. /**
  1000. * Return a list of those objects in the index which differ from whats in
  1001. * HEAD
  1002. *
  1003. * @return a set of ObjectIds of changed objects in the index
  1004. * @throws IOException
  1005. * @throws CorruptObjectException
  1006. * @throws NoWorkTreeException
  1007. */
  1008. private Set<ObjectId> listNonHEADIndexObjects()
  1009. throws CorruptObjectException, IOException {
  1010. if (repo.isBare()) {
  1011. return Collections.emptySet();
  1012. }
  1013. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  1014. treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
  1015. ObjectId headID = repo.resolve(Constants.HEAD);
  1016. if (headID != null) {
  1017. try (RevWalk revWalk = new RevWalk(repo)) {
  1018. treeWalk.addTree(revWalk.parseTree(headID));
  1019. }
  1020. }
  1021. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  1022. treeWalk.setRecursive(true);
  1023. Set<ObjectId> ret = new HashSet<>();
  1024. while (treeWalk.next()) {
  1025. checkCancelled();
  1026. ObjectId objectId = treeWalk.getObjectId(0);
  1027. switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
  1028. case FileMode.TYPE_MISSING:
  1029. case FileMode.TYPE_GITLINK:
  1030. continue;
  1031. case FileMode.TYPE_TREE:
  1032. case FileMode.TYPE_FILE:
  1033. case FileMode.TYPE_SYMLINK:
  1034. ret.add(objectId);
  1035. continue;
  1036. default:
  1037. throw new IOException(MessageFormat.format(
  1038. JGitText.get().corruptObjectInvalidMode3,
  1039. String.format("%o", //$NON-NLS-1$
  1040. Integer.valueOf(treeWalk.getRawMode(0))),
  1041. (objectId == null) ? "null" : objectId.name(), //$NON-NLS-1$
  1042. treeWalk.getPathString(), //
  1043. repo.getIndexFile()));
  1044. }
  1045. }
  1046. return ret;
  1047. }
  1048. }
  1049. private PackFile writePack(@NonNull Set<? extends ObjectId> want,
  1050. @NonNull Set<? extends ObjectId> have, @NonNull Set<ObjectId> tags,
  1051. Set<ObjectId> tagTargets, List<ObjectIdSet> excludeObjects)
  1052. throws IOException {
  1053. checkCancelled();
  1054. File tmpPack = null;
  1055. Map<PackExt, File> tmpExts = new TreeMap<>((o1, o2) -> {
  1056. // INDEX entries must be returned last, so the pack
  1057. // scanner does pick up the new pack until all the
  1058. // PackExt entries have been written.
  1059. if (o1 == o2) {
  1060. return 0;
  1061. }
  1062. if (o1 == PackExt.INDEX) {
  1063. return 1;
  1064. }
  1065. if (o2 == PackExt.INDEX) {
  1066. return -1;
  1067. }
  1068. return Integer.signum(o1.hashCode() - o2.hashCode());
  1069. });
  1070. try (PackWriter pw = new PackWriter(
  1071. (pconfig == null) ? new PackConfig(repo) : pconfig,
  1072. repo.newObjectReader())) {
  1073. // prepare the PackWriter
  1074. pw.setDeltaBaseAsOffset(true);
  1075. pw.setReuseDeltaCommits(false);
  1076. if (tagTargets != null) {
  1077. pw.setTagTargets(tagTargets);
  1078. }
  1079. if (excludeObjects != null)
  1080. for (ObjectIdSet idx : excludeObjects)
  1081. pw.excludeObjects(idx);
  1082. pw.preparePack(pm, want, have, PackWriter.NONE, tags);
  1083. if (pw.getObjectCount() == 0)
  1084. return null;
  1085. checkCancelled();
  1086. // create temporary files
  1087. String id = pw.computeName().getName();
  1088. File packdir = repo.getObjectDatabase().getPackDirectory();
  1089. tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
  1090. final String tmpBase = tmpPack.getName()
  1091. .substring(0, tmpPack.getName().lastIndexOf('.'));
  1092. File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
  1093. tmpExts.put(INDEX, tmpIdx);
  1094. if (!tmpIdx.createNewFile())
  1095. throw new IOException(MessageFormat.format(
  1096. JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
  1097. // write the packfile
  1098. try (FileOutputStream fos = new FileOutputStream(tmpPack);
  1099. FileChannel channel = fos.getChannel();
  1100. OutputStream channelStream = Channels
  1101. .newOutputStream(channel)) {
  1102. pw.writePack(pm, pm, channelStream);
  1103. channel.force(true);
  1104. }
  1105. // write the packindex
  1106. try (FileOutputStream fos = new FileOutputStream(tmpIdx);
  1107. FileChannel idxChannel = fos.getChannel();
  1108. OutputStream idxStream = Channels
  1109. .newOutputStream(idxChannel)) {
  1110. pw.writeIndex(idxStream);
  1111. idxChannel.force(true);
  1112. }
  1113. if (pw.prepareBitmapIndex(pm)) {
  1114. File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
  1115. tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
  1116. if (!tmpBitmapIdx.createNewFile())
  1117. throw new IOException(MessageFormat.format(
  1118. JGitText.get().cannotCreateIndexfile,
  1119. tmpBitmapIdx.getPath()));
  1120. try (FileOutputStream fos = new FileOutputStream(tmpBitmapIdx);
  1121. FileChannel idxChannel = fos.getChannel();
  1122. OutputStream idxStream = Channels
  1123. .newOutputStream(idxChannel)) {
  1124. pw.writeBitmapIndex(idxStream);
  1125. idxChannel.force(true);
  1126. }
  1127. }
  1128. // rename the temporary files to real files
  1129. File realPack = nameFor(id, ".pack"); //$NON-NLS-1$
  1130. repo.getObjectDatabase().closeAllPackHandles(realPack);
  1131. tmpPack.setReadOnly();
  1132. FileUtils.rename(tmpPack, realPack, StandardCopyOption.ATOMIC_MOVE);
  1133. for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
  1134. File tmpExt = tmpEntry.getValue();
  1135. tmpExt.setReadOnly();
  1136. File realExt = nameFor(id,
  1137. "." + tmpEntry.getKey().getExtension()); //$NON-NLS-1$
  1138. try {
  1139. FileUtils.rename(tmpExt, realExt,
  1140. StandardCopyOption.ATOMIC_MOVE);
  1141. } catch (IOException e) {
  1142. File newExt = new File(realExt.getParentFile(),
  1143. realExt.getName() + ".new"); //$NON-NLS-1$
  1144. try {
  1145. FileUtils.rename(tmpExt, newExt,
  1146. StandardCopyOption.ATOMIC_MOVE);
  1147. } catch (IOException e2) {
  1148. newExt = tmpExt;
  1149. e = e2;
  1150. }
  1151. throw new IOException(MessageFormat.format(
  1152. JGitText.get().panicCantRenameIndexFile, newExt,
  1153. realExt), e);
  1154. }
  1155. }
  1156. return repo.getObjectDatabase().openPack(realPack);
  1157. } finally {
  1158. if (tmpPack != null && tmpPack.exists())
  1159. tmpPack.delete();
  1160. for (File tmpExt : tmpExts.values()) {
  1161. if (tmpExt.exists())
  1162. tmpExt.delete();
  1163. }
  1164. }
  1165. }
  1166. private File nameFor(String name, String ext) {
  1167. File packdir = repo.getObjectDatabase().getPackDirectory();
  1168. return new File(packdir, "pack-" + name + ext); //$NON-NLS-1$
  1169. }
  1170. private void checkCancelled() throws CancelledException {
  1171. if (pm.isCancelled() || Thread.currentThread().isInterrupted()) {
  1172. throw new CancelledException(JGitText.get().operationCanceled);
  1173. }
  1174. }
  1175. /**
  1176. * A class holding statistical data for a FileRepository regarding how many
  1177. * objects are stored as loose or packed objects
  1178. */
  1179. public static class RepoStatistics {
  1180. /**
  1181. * The number of objects stored in pack files. If the same object is
  1182. * stored in multiple pack files then it is counted as often as it
  1183. * occurs in pack files.
  1184. */
  1185. public long numberOfPackedObjects;
  1186. /**
  1187. * The number of pack files
  1188. */
  1189. public long numberOfPackFiles;
  1190. /**
  1191. * The number of objects stored as loose objects.
  1192. */
  1193. public long numberOfLooseObjects;
  1194. /**
  1195. * The sum of the sizes of all files used to persist loose objects.
  1196. */
  1197. public long sizeOfLooseObjects;
  1198. /**
  1199. * The sum of the sizes of all pack files.
  1200. */
  1201. public long sizeOfPackedObjects;
  1202. /**
  1203. * The number of loose refs.
  1204. */
  1205. public long numberOfLooseRefs;
  1206. /**
  1207. * The number of refs stored in pack files.
  1208. */
  1209. public long numberOfPackedRefs;
  1210. /**
  1211. * The number of bitmaps in the bitmap indices.
  1212. */
  1213. public long numberOfBitmaps;
  1214. @Override
  1215. public String toString() {
  1216. final StringBuilder b = new StringBuilder();
  1217. b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
  1218. b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
  1219. b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
  1220. b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
  1221. b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
  1222. b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
  1223. b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
  1224. b.append(", numberOfBitmaps=").append(numberOfBitmaps); //$NON-NLS-1$
  1225. return b.toString();
  1226. }
  1227. }
  1228. /**
  1229. * Returns information about objects and pack files for a FileRepository.
  1230. *
  1231. * @return information about objects and pack files for a FileRepository
  1232. * @throws java.io.IOException
  1233. */
  1234. public RepoStatistics getStatistics() throws IOException {
  1235. RepoStatistics ret = new RepoStatistics();
  1236. Collection<PackFile> packs = repo.getObjectDatabase().getPacks();
  1237. for (PackFile f : packs) {
  1238. ret.numberOfPackedObjects += f.getIndex().getObjectCount();
  1239. ret.numberOfPackFiles++;
  1240. ret.sizeOfPackedObjects += f.getPackFile().length();
  1241. if (f.getBitmapIndex() != null)
  1242. ret.numberOfBitmaps += f.getBitmapIndex().getBitmapCount();
  1243. }
  1244. File objDir = repo.getObjectsDirectory();
  1245. String[] fanout = objDir.list();
  1246. if (fanout != null && fanout.length > 0) {
  1247. for (String d : fanout) {
  1248. if (d.length() != 2)
  1249. continue;
  1250. File[] entries = new File(objDir, d).listFiles();
  1251. if (entries == null)
  1252. continue;
  1253. for (File f : entries) {
  1254. if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  1255. continue;
  1256. ret.numberOfLooseObjects++;
  1257. ret.sizeOfLooseObjects += f.length();
  1258. }
  1259. }
  1260. }
  1261. RefDatabase refDb = repo.getRefDatabase();
  1262. for (Ref r : refDb.getRefs()) {
  1263. Storage storage = r.getStorage();
  1264. if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
  1265. ret.numberOfLooseRefs++;
  1266. if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
  1267. ret.numberOfPackedRefs++;
  1268. }
  1269. return ret;
  1270. }
  1271. /**
  1272. * Set the progress monitor used for garbage collection methods.
  1273. *
  1274. * @param pm a {@link org.eclipse.jgit.lib.ProgressMonitor} object.
  1275. * @return this
  1276. */
  1277. public GC setProgressMonitor(ProgressMonitor pm) {
  1278. this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
  1279. return this;
  1280. }
  1281. /**
  1282. * During gc() or prune() each unreferenced, loose object which has been
  1283. * created or modified in the last <code>expireAgeMillis</code> milliseconds
  1284. * will not be pruned. Only older objects may be pruned. If set to 0 then
  1285. * every object is a candidate for pruning.
  1286. *
  1287. * @param expireAgeMillis
  1288. * minimal age of objects to be pruned in milliseconds.
  1289. */
  1290. public void setExpireAgeMillis(long expireAgeMillis) {
  1291. this.expireAgeMillis = expireAgeMillis;
  1292. expire = null;
  1293. }
  1294. /**
  1295. * During gc() or prune() packfiles which are created or modified in the
  1296. * last <code>packExpireAgeMillis</code> milliseconds will not be deleted.
  1297. * Only older packfiles may be deleted. If set to 0 then every packfile is a
  1298. * candidate for deletion.
  1299. *
  1300. * @param packExpireAgeMillis
  1301. * minimal age of packfiles to be deleted in milliseconds.
  1302. */
  1303. public void setPackExpireAgeMillis(long packExpireAgeMillis) {
  1304. this.packExpireAgeMillis = packExpireAgeMillis;
  1305. expire = null;
  1306. }
  1307. /**
  1308. * Set the PackConfig used when (re-)writing packfiles. This allows to
  1309. * influence how packs are written and to implement something similar to
  1310. * "git gc --aggressive"
  1311. *
  1312. * @param pconfig
  1313. * the {@link org.eclipse.jgit.storage.pack.PackConfig} used when
  1314. * writing packs
  1315. */
  1316. public void setPackConfig(PackConfig pconfig) {
  1317. this.pconfig = pconfig;
  1318. }
  1319. /**
  1320. * During gc() or prune() each unreferenced, loose object which has been
  1321. * created or modified after or at <code>expire</code> will not be pruned.
  1322. * Only older objects may be pruned. If set to null then every object is a
  1323. * candidate for pruning.
  1324. *
  1325. * @param expire
  1326. * instant in time which defines object expiration
  1327. * objects with modification time before this instant are expired
  1328. * objects with modification time newer or equal to this instant
  1329. * are not expired
  1330. */
  1331. public void setExpire(Date expire) {
  1332. this.expire = expire;
  1333. expireAgeMillis = -1;
  1334. }
  1335. /**
  1336. * During gc() or prune() packfiles which are created or modified after or
  1337. * at <code>packExpire</code> will not be deleted. Only older packfiles may
  1338. * be deleted. If set to null then every packfile is a candidate for
  1339. * deletion.
  1340. *
  1341. * @param packExpire
  1342. * instant in time which defines packfile expiration
  1343. */
  1344. public void setPackExpire(Date packExpire) {
  1345. this.packExpire = packExpire;
  1346. packExpireAgeMillis = -1;
  1347. }
  1348. /**
  1349. * Set the {@code gc --auto} option.
  1350. *
  1351. * With this option, gc checks whether any housekeeping is required; if not,
  1352. * it exits without performing any work. Some JGit commands run
  1353. * {@code gc --auto} after performing operations that could create many
  1354. * loose objects.
  1355. * <p>
  1356. * Housekeeping is required if there are too many loose objects or too many
  1357. * packs in the repository. If the number of loose objects exceeds the value
  1358. * of the gc.auto option JGit GC consolidates all existing packs into a
  1359. * single pack (equivalent to {@code -A} option), whereas git-core would
  1360. * combine all loose objects into a single pack using {@code repack -d -l}.
  1361. * Setting the value of {@code gc.auto} to 0 disables automatic packing of
  1362. * loose objects.
  1363. * <p>
  1364. * If the number of packs exceeds the value of {@code gc.autoPackLimit},
  1365. * then existing packs (except those marked with a .keep file) are
  1366. * consolidated into a single pack by using the {@code -A} option of repack.
  1367. * Setting {@code gc.autoPackLimit} to 0 disables automatic consolidation of
  1368. * packs.
  1369. * <p>
  1370. * Like git the following jgit commands run auto gc:
  1371. * <ul>
  1372. * <li>fetch</li>
  1373. * <li>merge</li>
  1374. * <li>rebase</li>
  1375. * <li>receive-pack</li>
  1376. * </ul>
  1377. * The auto gc for receive-pack can be suppressed by setting the config
  1378. * option {@code receive.autogc = false}
  1379. *
  1380. * @param auto
  1381. * defines whether gc should do automatic housekeeping
  1382. */
  1383. public void setAuto(boolean auto) {
  1384. this.automatic = auto;
  1385. }
  1386. /**
  1387. * @param background
  1388. * whether to run the gc in a background thread.
  1389. */
  1390. void setBackground(boolean background) {
  1391. this.background = background;
  1392. }
  1393. private boolean needGc() {
  1394. if (tooManyPacks()) {
  1395. addRepackAllOption();
  1396. } else {
  1397. return tooManyLooseObjects();
  1398. }
  1399. // TODO run pre-auto-gc hook, if it fails return false
  1400. return true;
  1401. }
  1402. private void addRepackAllOption() {
  1403. // TODO: if JGit GC is enhanced to support repack's option -l this
  1404. // method needs to be implemented
  1405. }
  1406. /**
  1407. * @return {@code true} if number of packs > gc.autopacklimit (default 50)
  1408. */
  1409. boolean tooManyPacks() {
  1410. int autopacklimit = repo.getConfig().getInt(
  1411. ConfigConstants.CONFIG_GC_SECTION,
  1412. ConfigConstants.CONFIG_KEY_AUTOPACKLIMIT,
  1413. DEFAULT_AUTOPACKLIMIT);
  1414. if (autopacklimit <= 0) {
  1415. return false;
  1416. }
  1417. // JGit always creates two packfiles, one for the objects reachable from
  1418. // branches, and another one for the rest
  1419. return repo.getObjectDatabase().getPacks().size() > (autopacklimit + 1);
  1420. }
  1421. /**
  1422. * Quickly estimate number of loose objects, SHA1 is distributed evenly so
  1423. * counting objects in one directory (bucket 17) is sufficient
  1424. *
  1425. * @return {@code true} if number of loose objects > gc.auto (default 6700)
  1426. */
  1427. boolean tooManyLooseObjects() {
  1428. int auto = getLooseObjectLimit();
  1429. if (auto <= 0) {
  1430. return false;
  1431. }
  1432. int n = 0;
  1433. int threshold = (auto + 255) / 256;
  1434. Path dir = repo.getObjectsDirectory().toPath().resolve("17"); //$NON-NLS-1$
  1435. if (!dir.toFile().exists()) {
  1436. return false;
  1437. }
  1438. try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, file -> {
  1439. Path fileName = file.getFileName();
  1440. return file.toFile().isFile() && fileName != null
  1441. && PATTERN_LOOSE_OBJECT.matcher(fileName.toString())
  1442. .matches();
  1443. })) {
  1444. for (Iterator<Path> iter = stream.iterator(); iter.hasNext(); iter
  1445. .next()) {
  1446. if (++n > threshold) {
  1447. return true;
  1448. }
  1449. }
  1450. } catch (IOException e) {
  1451. LOG.error(e.getMessage(), e);
  1452. }
  1453. return false;
  1454. }
  1455. private int getLooseObjectLimit() {
  1456. return repo.getConfig().getInt(ConfigConstants.CONFIG_GC_SECTION,
  1457. ConfigConstants.CONFIG_KEY_AUTO, DEFAULT_AUTOLIMIT);
  1458. }
  1459. }