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

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