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

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