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 49KB

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