Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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