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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. /*
  2. * Copyright (C) 2012, Christian Halstrick <christian.halstrick@sap.com>
  3. * Copyright (C) 2011, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.internal.storage.file;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
  46. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  47. import java.io.File;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.OutputStream;
  51. import java.nio.channels.Channels;
  52. import java.nio.channels.FileChannel;
  53. import java.nio.file.StandardCopyOption;
  54. import java.text.MessageFormat;
  55. import java.text.ParseException;
  56. import java.util.ArrayList;
  57. import java.util.Collection;
  58. import java.util.Collections;
  59. import java.util.Comparator;
  60. import java.util.Date;
  61. import java.util.HashMap;
  62. import java.util.HashSet;
  63. import java.util.LinkedList;
  64. import java.util.List;
  65. import java.util.Map;
  66. import java.util.Objects;
  67. import java.util.Set;
  68. import java.util.TreeMap;
  69. import org.eclipse.jgit.annotations.NonNull;
  70. import org.eclipse.jgit.dircache.DirCacheIterator;
  71. import org.eclipse.jgit.errors.CorruptObjectException;
  72. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.errors.NoWorkTreeException;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.internal.storage.pack.PackExt;
  77. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  78. import org.eclipse.jgit.internal.storage.reftree.RefTreeNames;
  79. import org.eclipse.jgit.lib.ConfigConstants;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.FileMode;
  82. import org.eclipse.jgit.lib.NullProgressMonitor;
  83. import org.eclipse.jgit.lib.ObjectId;
  84. import org.eclipse.jgit.lib.ObjectIdSet;
  85. import org.eclipse.jgit.lib.ProgressMonitor;
  86. import org.eclipse.jgit.lib.Ref;
  87. import org.eclipse.jgit.lib.Ref.Storage;
  88. import org.eclipse.jgit.lib.RefDatabase;
  89. import org.eclipse.jgit.lib.ReflogEntry;
  90. import org.eclipse.jgit.lib.ReflogReader;
  91. import org.eclipse.jgit.revwalk.ObjectWalk;
  92. import org.eclipse.jgit.revwalk.RevObject;
  93. import org.eclipse.jgit.revwalk.RevWalk;
  94. import org.eclipse.jgit.storage.pack.PackConfig;
  95. import org.eclipse.jgit.treewalk.TreeWalk;
  96. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  97. import org.eclipse.jgit.util.FileUtils;
  98. import org.eclipse.jgit.util.GitDateParser;
  99. import org.eclipse.jgit.util.SystemReader;
  100. /**
  101. * A garbage collector for git {@link FileRepository}. Instances of this class
  102. * are not thread-safe. Don't use the same instance from multiple threads.
  103. *
  104. * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
  105. * adapted to FileRepositories.
  106. */
  107. public class GC {
  108. private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
  109. private static final String PRUNE_PACK_EXPIRE_DEFAULT = "1.hour.ago"; //$NON-NLS-1$
  110. private final FileRepository repo;
  111. private ProgressMonitor pm;
  112. private long expireAgeMillis = -1;
  113. private Date expire;
  114. private long packExpireAgeMillis = -1;
  115. private Date packExpire;
  116. private PackConfig pconfig = null;
  117. /**
  118. * the refs which existed during the last call to {@link #repack()}. This is
  119. * needed during {@link #prune(Set)} where we can optimize by looking at the
  120. * difference between the current refs and the refs which existed during
  121. * last {@link #repack()}.
  122. */
  123. private Collection<Ref> lastPackedRefs;
  124. /**
  125. * Holds the starting time of the last repack() execution. This is needed in
  126. * prune() to inspect only those reflog entries which have been added since
  127. * last repack().
  128. */
  129. private long lastRepackTime;
  130. /**
  131. * Creates a new garbage collector with default values. An expirationTime of
  132. * two weeks and <code>null</code> as progress monitor will be used.
  133. *
  134. * @param repo
  135. * the repo to work on
  136. */
  137. public GC(FileRepository repo) {
  138. this.repo = repo;
  139. this.pm = NullProgressMonitor.INSTANCE;
  140. }
  141. /**
  142. * Runs a garbage collector on a {@link FileRepository}. It will
  143. * <ul>
  144. * <li>pack loose references into packed-refs</li>
  145. * <li>repack all reachable objects into new pack files and delete the old
  146. * pack files</li>
  147. * <li>prune all loose objects which are now reachable by packs</li>
  148. * </ul>
  149. *
  150. * @return the collection of {@link PackFile}'s which are newly created
  151. * @throws IOException
  152. * @throws ParseException
  153. * If the configuration parameter "gc.pruneexpire" couldn't be
  154. * parsed
  155. */
  156. public Collection<PackFile> gc() throws IOException, ParseException {
  157. pm.start(6 /* tasks */);
  158. packRefs();
  159. // TODO: implement reflog_expire(pm, repo);
  160. Collection<PackFile> newPacks = repack();
  161. prune(Collections.<ObjectId> emptySet());
  162. // TODO: implement rerere_gc(pm);
  163. return newPacks;
  164. }
  165. /**
  166. * Delete old pack files. What is 'old' is defined by specifying a set of
  167. * old pack files and a set of new pack files. Each pack file contained in
  168. * old pack files but not contained in new pack files will be deleted. If an
  169. * expirationDate is set then pack files which are younger than the
  170. * expirationDate will not be deleted.
  171. *
  172. * @param oldPacks
  173. * @param newPacks
  174. * @throws ParseException
  175. * @throws IOException
  176. */
  177. private void deleteOldPacks(Collection<PackFile> oldPacks,
  178. Collection<PackFile> newPacks) throws ParseException, IOException {
  179. long packExpireDate = getPackExpireDate();
  180. oldPackLoop: for (PackFile oldPack : oldPacks) {
  181. String oldName = oldPack.getPackName();
  182. // check whether an old pack file is also among the list of new
  183. // pack files. Then we must not delete it.
  184. for (PackFile newPack : newPacks)
  185. if (oldName.equals(newPack.getPackName()))
  186. continue oldPackLoop;
  187. if (!oldPack.shouldBeKept()
  188. && repo.getFS().lastModified(
  189. oldPack.getPackFile()) < packExpireDate) {
  190. oldPack.close();
  191. prunePack(oldName);
  192. }
  193. }
  194. // close the complete object database. Thats my only chance to force
  195. // rescanning and to detect that certain pack files are now deleted.
  196. repo.getObjectDatabase().close();
  197. }
  198. /**
  199. * Delete files associated with a single pack file. First try to delete the
  200. * ".pack" file because on some platforms the ".pack" file may be locked and
  201. * can't be deleted. In such a case it is better to detect this early and
  202. * give up on deleting files for this packfile. Otherwise we may delete the
  203. * ".index" file and when failing to delete the ".pack" file we are left
  204. * with a ".pack" file without a ".index" file.
  205. *
  206. * @param packName
  207. */
  208. private void prunePack(String packName) {
  209. PackExt[] extensions = PackExt.values();
  210. try {
  211. // Delete the .pack file first and if this fails give up on deleting
  212. // the other files
  213. int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  214. for (PackExt ext : extensions)
  215. if (PackExt.PACK.equals(ext)) {
  216. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  217. FileUtils.delete(f, deleteOptions);
  218. break;
  219. }
  220. // The .pack file has been deleted. Delete as many as the other
  221. // files as you can.
  222. deleteOptions |= FileUtils.IGNORE_ERRORS;
  223. for (PackExt ext : extensions) {
  224. if (!PackExt.PACK.equals(ext)) {
  225. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  226. FileUtils.delete(f, deleteOptions);
  227. }
  228. }
  229. } catch (IOException e) {
  230. // Deletion of the .pack file failed. Silently return.
  231. }
  232. }
  233. /**
  234. * Like "git prune-packed" this method tries to prune all loose objects
  235. * which can be found in packs. If certain objects can't be pruned (e.g.
  236. * because the filesystem delete operation fails) this is silently ignored.
  237. *
  238. * @throws IOException
  239. */
  240. public void prunePacked() throws IOException {
  241. ObjectDirectory objdb = repo.getObjectDatabase();
  242. Collection<PackFile> packs = objdb.getPacks();
  243. File objects = repo.getObjectsDirectory();
  244. String[] fanout = objects.list();
  245. if (fanout != null && fanout.length > 0) {
  246. pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
  247. try {
  248. for (String d : fanout) {
  249. pm.update(1);
  250. if (d.length() != 2)
  251. continue;
  252. String[] entries = new File(objects, d).list();
  253. if (entries == null)
  254. continue;
  255. for (String e : entries) {
  256. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  257. continue;
  258. ObjectId id;
  259. try {
  260. id = ObjectId.fromString(d + e);
  261. } catch (IllegalArgumentException notAnObject) {
  262. // ignoring the file that does not represent loose
  263. // object
  264. continue;
  265. }
  266. boolean found = false;
  267. for (PackFile p : packs)
  268. if (p.hasObject(id)) {
  269. found = true;
  270. break;
  271. }
  272. if (found)
  273. FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
  274. | FileUtils.SKIP_MISSING
  275. | FileUtils.IGNORE_ERRORS);
  276. }
  277. }
  278. } finally {
  279. pm.endTask();
  280. }
  281. }
  282. }
  283. /**
  284. * Like "git prune" this method tries to prune all loose objects which are
  285. * unreferenced. If certain objects can't be pruned (e.g. because the
  286. * filesystem delete operation fails) this is silently ignored.
  287. *
  288. * @param objectsToKeep
  289. * a set of objects which should explicitly not be pruned
  290. *
  291. * @throws IOException
  292. * @throws ParseException
  293. * If the configuration parameter "gc.pruneexpire" couldn't be
  294. * parsed
  295. */
  296. public void prune(Set<ObjectId> objectsToKeep) throws IOException,
  297. ParseException {
  298. long expireDate = getExpireDate();
  299. // Collect all loose objects which are old enough, not referenced from
  300. // the index and not in objectsToKeep
  301. Map<ObjectId, File> deletionCandidates = new HashMap<ObjectId, File>();
  302. Set<ObjectId> indexObjects = null;
  303. File objects = repo.getObjectsDirectory();
  304. String[] fanout = objects.list();
  305. if (fanout != null && fanout.length > 0) {
  306. pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
  307. fanout.length);
  308. try {
  309. for (String d : fanout) {
  310. pm.update(1);
  311. if (d.length() != 2)
  312. continue;
  313. File[] entries = new File(objects, d).listFiles();
  314. if (entries == null)
  315. continue;
  316. for (File f : entries) {
  317. String fName = f.getName();
  318. if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  319. continue;
  320. if (repo.getFS().lastModified(f) >= expireDate)
  321. continue;
  322. try {
  323. ObjectId id = ObjectId.fromString(d + fName);
  324. if (objectsToKeep.contains(id))
  325. continue;
  326. if (indexObjects == null)
  327. indexObjects = listNonHEADIndexObjects();
  328. if (indexObjects.contains(id))
  329. continue;
  330. deletionCandidates.put(id, f);
  331. } catch (IllegalArgumentException notAnObject) {
  332. // ignoring the file that does not represent loose
  333. // object
  334. continue;
  335. }
  336. }
  337. }
  338. } finally {
  339. pm.endTask();
  340. }
  341. }
  342. if (deletionCandidates.isEmpty())
  343. return;
  344. // From the set of current refs remove all those which have been handled
  345. // during last repack(). Only those refs will survive which have been
  346. // added or modified since the last repack. Only these can save existing
  347. // loose refs from being pruned.
  348. Collection<Ref> newRefs;
  349. if (lastPackedRefs == null || lastPackedRefs.isEmpty())
  350. newRefs = getAllRefs();
  351. else {
  352. Map<String, Ref> last = new HashMap<>();
  353. for (Ref r : lastPackedRefs) {
  354. last.put(r.getName(), r);
  355. }
  356. newRefs = new ArrayList<>();
  357. for (Ref r : getAllRefs()) {
  358. Ref old = last.get(r.getName());
  359. if (!equals(r, old)) {
  360. newRefs.add(r);
  361. }
  362. }
  363. }
  364. if (!newRefs.isEmpty()) {
  365. // There are new/modified refs! Check which loose objects are now
  366. // referenced by these modified refs (or their reflogentries).
  367. // Remove these loose objects
  368. // from the deletionCandidates. When the last candidate is removed
  369. // leave this method.
  370. ObjectWalk w = new ObjectWalk(repo);
  371. try {
  372. for (Ref cr : newRefs)
  373. w.markStart(w.parseAny(cr.getObjectId()));
  374. if (lastPackedRefs != null)
  375. for (Ref lpr : lastPackedRefs)
  376. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  377. removeReferenced(deletionCandidates, w);
  378. } finally {
  379. w.dispose();
  380. }
  381. }
  382. if (deletionCandidates.isEmpty())
  383. return;
  384. // Since we have not left the method yet there are still
  385. // deletionCandidates. Last chance for these objects not to be pruned is
  386. // that they are referenced by reflog entries. Even refs which currently
  387. // point to the same object as during last repack() may have
  388. // additional reflog entries not handled during last repack()
  389. ObjectWalk w = new ObjectWalk(repo);
  390. try {
  391. for (Ref ar : getAllRefs())
  392. for (ObjectId id : listRefLogObjects(ar, lastRepackTime))
  393. w.markStart(w.parseAny(id));
  394. if (lastPackedRefs != null)
  395. for (Ref lpr : lastPackedRefs)
  396. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  397. removeReferenced(deletionCandidates, w);
  398. } finally {
  399. w.dispose();
  400. }
  401. if (deletionCandidates.isEmpty())
  402. return;
  403. // delete all candidates which have survived: these are unreferenced
  404. // loose objects. Make a last check, though, to avoid deleting objects
  405. // that could have been referenced while the candidates list was being
  406. // built (by an incoming push, for example).
  407. for (File f : deletionCandidates.values()) {
  408. if (f.lastModified() < expireDate) {
  409. f.delete();
  410. }
  411. }
  412. repo.getObjectDatabase().close();
  413. }
  414. private long getExpireDate() throws ParseException {
  415. long expireDate = Long.MAX_VALUE;
  416. if (expire == null && expireAgeMillis == -1) {
  417. String pruneExpireStr = repo.getConfig().getString(
  418. ConfigConstants.CONFIG_GC_SECTION, null,
  419. ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
  420. if (pruneExpireStr == null)
  421. pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
  422. expire = GitDateParser.parse(pruneExpireStr, null, SystemReader
  423. .getInstance().getLocale());
  424. expireAgeMillis = -1;
  425. }
  426. if (expire != null)
  427. expireDate = expire.getTime();
  428. if (expireAgeMillis != -1)
  429. expireDate = System.currentTimeMillis() - expireAgeMillis;
  430. return expireDate;
  431. }
  432. private long getPackExpireDate() throws ParseException {
  433. long packExpireDate = Long.MAX_VALUE;
  434. if (packExpire == null && packExpireAgeMillis == -1) {
  435. String prunePackExpireStr = repo.getConfig().getString(
  436. ConfigConstants.CONFIG_GC_SECTION, null,
  437. ConfigConstants.CONFIG_KEY_PRUNEPACKEXPIRE);
  438. if (prunePackExpireStr == null)
  439. prunePackExpireStr = PRUNE_PACK_EXPIRE_DEFAULT;
  440. packExpire = GitDateParser.parse(prunePackExpireStr, null,
  441. SystemReader.getInstance().getLocale());
  442. packExpireAgeMillis = -1;
  443. }
  444. if (packExpire != null)
  445. packExpireDate = packExpire.getTime();
  446. if (packExpireAgeMillis != -1)
  447. packExpireDate = System.currentTimeMillis() - packExpireAgeMillis;
  448. return packExpireDate;
  449. }
  450. /**
  451. * Remove all entries from a map which key is the id of an object referenced
  452. * by the given ObjectWalk
  453. *
  454. * @param id2File
  455. * @param w
  456. * @throws MissingObjectException
  457. * @throws IncorrectObjectTypeException
  458. * @throws IOException
  459. */
  460. private void removeReferenced(Map<ObjectId, File> id2File,
  461. ObjectWalk w) throws MissingObjectException,
  462. IncorrectObjectTypeException, IOException {
  463. RevObject ro = w.next();
  464. while (ro != null) {
  465. if (id2File.remove(ro.getId()) != null)
  466. if (id2File.isEmpty())
  467. return;
  468. ro = w.next();
  469. }
  470. ro = w.nextObject();
  471. while (ro != null) {
  472. if (id2File.remove(ro.getId()) != null)
  473. if (id2File.isEmpty())
  474. return;
  475. ro = w.nextObject();
  476. }
  477. }
  478. private static boolean equals(Ref r1, Ref r2) {
  479. if (r1 == null || r2 == null)
  480. return false;
  481. if (r1.isSymbolic()) {
  482. if (!r2.isSymbolic())
  483. return false;
  484. return r1.getTarget().getName().equals(r2.getTarget().getName());
  485. } else {
  486. if (r2.isSymbolic()) {
  487. return false;
  488. }
  489. return Objects.equals(r1.getObjectId(), r2.getObjectId());
  490. }
  491. }
  492. /**
  493. * Packs all non-symbolic, loose refs into packed-refs.
  494. *
  495. * @throws IOException
  496. */
  497. public void packRefs() throws IOException {
  498. Collection<Ref> refs = repo.getRefDatabase().getRefs(Constants.R_REFS).values();
  499. List<String> refsToBePacked = new ArrayList<String>(refs.size());
  500. pm.beginTask(JGitText.get().packRefs, refs.size());
  501. try {
  502. for (Ref ref : refs) {
  503. if (!ref.isSymbolic() && ref.getStorage().isLoose())
  504. refsToBePacked.add(ref.getName());
  505. pm.update(1);
  506. }
  507. ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
  508. } finally {
  509. pm.endTask();
  510. }
  511. }
  512. /**
  513. * Packs all objects which reachable from any of the heads into one pack
  514. * file. Additionally all objects which are not reachable from any head but
  515. * which are reachable from any of the other refs (e.g. tags), special refs
  516. * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
  517. * included in pack files which have a .keep file associated are never
  518. * repacked. All old pack files which existed before are deleted.
  519. *
  520. * @return a collection of the newly created pack files
  521. * @throws IOException
  522. * when during reading of refs, index, packfiles, objects,
  523. * reflog-entries or during writing to the packfiles
  524. * {@link IOException} occurs
  525. */
  526. public Collection<PackFile> repack() throws IOException {
  527. Collection<PackFile> toBeDeleted = repo.getObjectDatabase().getPacks();
  528. long time = System.currentTimeMillis();
  529. Collection<Ref> refsBefore = getAllRefs();
  530. Set<ObjectId> allHeads = new HashSet<ObjectId>();
  531. Set<ObjectId> nonHeads = new HashSet<ObjectId>();
  532. Set<ObjectId> txnHeads = new HashSet<ObjectId>();
  533. Set<ObjectId> tagTargets = new HashSet<ObjectId>();
  534. Set<ObjectId> indexObjects = listNonHEADIndexObjects();
  535. RefDatabase refdb = repo.getRefDatabase();
  536. for (Ref ref : refsBefore) {
  537. nonHeads.addAll(listRefLogObjects(ref, 0));
  538. if (ref.isSymbolic() || ref.getObjectId() == null)
  539. continue;
  540. if (ref.getName().startsWith(Constants.R_HEADS))
  541. allHeads.add(ref.getObjectId());
  542. else if (RefTreeNames.isRefTree(refdb, ref.getName()))
  543. txnHeads.add(ref.getObjectId());
  544. else
  545. nonHeads.add(ref.getObjectId());
  546. if (ref.getPeeledObjectId() != null)
  547. tagTargets.add(ref.getPeeledObjectId());
  548. }
  549. List<ObjectIdSet> excluded = new LinkedList<ObjectIdSet>();
  550. for (final PackFile f : repo.getObjectDatabase().getPacks())
  551. if (f.shouldBeKept())
  552. excluded.add(f.getIndex());
  553. tagTargets.addAll(allHeads);
  554. nonHeads.addAll(indexObjects);
  555. List<PackFile> ret = new ArrayList<PackFile>(2);
  556. PackFile heads = null;
  557. if (!allHeads.isEmpty()) {
  558. heads = writePack(allHeads, Collections.<ObjectId> emptySet(),
  559. tagTargets, excluded);
  560. if (heads != null) {
  561. ret.add(heads);
  562. excluded.add(0, heads.getIndex());
  563. }
  564. }
  565. if (!nonHeads.isEmpty()) {
  566. PackFile rest = writePack(nonHeads, allHeads, tagTargets, excluded);
  567. if (rest != null)
  568. ret.add(rest);
  569. }
  570. if (!txnHeads.isEmpty()) {
  571. PackFile txn = writePack(txnHeads, PackWriter.NONE, null, excluded);
  572. if (txn != null)
  573. ret.add(txn);
  574. }
  575. try {
  576. deleteOldPacks(toBeDeleted, ret);
  577. } catch (ParseException e) {
  578. // TODO: the exception has to be wrapped into an IOException because
  579. // throwing the ParseException directly would break the API, instead
  580. // we should throw a ConfigInvalidException
  581. throw new IOException(e);
  582. }
  583. prunePacked();
  584. lastPackedRefs = refsBefore;
  585. lastRepackTime = time;
  586. return ret;
  587. }
  588. /**
  589. * @param ref
  590. * the ref which log should be inspected
  591. * @param minTime only reflog entries not older then this time are processed
  592. * @return the {@link ObjectId}s contained in the reflog
  593. * @throws IOException
  594. */
  595. private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
  596. ReflogReader reflogReader = repo.getReflogReader(ref.getName());
  597. if (reflogReader == null) {
  598. return Collections.emptySet();
  599. }
  600. List<ReflogEntry> rlEntries = reflogReader
  601. .getReverseEntries();
  602. if (rlEntries == null || rlEntries.isEmpty())
  603. return Collections.<ObjectId> emptySet();
  604. Set<ObjectId> ret = new HashSet<ObjectId>();
  605. for (ReflogEntry e : rlEntries) {
  606. if (e.getWho().getWhen().getTime() < minTime)
  607. break;
  608. ObjectId newId = e.getNewId();
  609. if (newId != null && !ObjectId.zeroId().equals(newId))
  610. ret.add(newId);
  611. ObjectId oldId = e.getOldId();
  612. if (oldId != null && !ObjectId.zeroId().equals(oldId))
  613. ret.add(oldId);
  614. }
  615. return ret;
  616. }
  617. /**
  618. * Returns a collection of all refs and additional refs.
  619. *
  620. * Additional refs which don't start with "refs/" are not returned because
  621. * they should not save objects from being garbage collected. Examples for
  622. * such references are ORIG_HEAD, MERGE_HEAD, FETCH_HEAD and
  623. * CHERRY_PICK_HEAD.
  624. *
  625. * @return a collection of refs pointing to live objects.
  626. * @throws IOException
  627. */
  628. private Collection<Ref> getAllRefs() throws IOException {
  629. RefDatabase refdb = repo.getRefDatabase();
  630. Collection<Ref> refs = refdb.getRefs(RefDatabase.ALL).values();
  631. List<Ref> addl = refdb.getAdditionalRefs();
  632. if (!addl.isEmpty()) {
  633. List<Ref> all = new ArrayList<>(refs.size() + addl.size());
  634. all.addAll(refs);
  635. // add additional refs which start with refs/
  636. for (Ref r : addl) {
  637. if (r.getName().startsWith(Constants.R_REFS)) {
  638. all.add(r);
  639. }
  640. }
  641. return all;
  642. }
  643. return refs;
  644. }
  645. /**
  646. * Return a list of those objects in the index which differ from whats in
  647. * HEAD
  648. *
  649. * @return a set of ObjectIds of changed objects in the index
  650. * @throws IOException
  651. * @throws CorruptObjectException
  652. * @throws NoWorkTreeException
  653. */
  654. private Set<ObjectId> listNonHEADIndexObjects()
  655. throws CorruptObjectException, IOException {
  656. if (repo.isBare()) {
  657. return Collections.emptySet();
  658. }
  659. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  660. treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
  661. ObjectId headID = repo.resolve(Constants.HEAD);
  662. if (headID != null) {
  663. try (RevWalk revWalk = new RevWalk(repo)) {
  664. treeWalk.addTree(revWalk.parseTree(headID));
  665. }
  666. }
  667. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  668. treeWalk.setRecursive(true);
  669. Set<ObjectId> ret = new HashSet<ObjectId>();
  670. while (treeWalk.next()) {
  671. ObjectId objectId = treeWalk.getObjectId(0);
  672. switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
  673. case FileMode.TYPE_MISSING:
  674. case FileMode.TYPE_GITLINK:
  675. continue;
  676. case FileMode.TYPE_TREE:
  677. case FileMode.TYPE_FILE:
  678. case FileMode.TYPE_SYMLINK:
  679. ret.add(objectId);
  680. continue;
  681. default:
  682. throw new IOException(MessageFormat.format(
  683. JGitText.get().corruptObjectInvalidMode3,
  684. String.format("%o", //$NON-NLS-1$
  685. Integer.valueOf(treeWalk.getRawMode(0))),
  686. (objectId == null) ? "null" : objectId.name(), //$NON-NLS-1$
  687. treeWalk.getPathString(), //
  688. repo.getIndexFile()));
  689. }
  690. }
  691. return ret;
  692. }
  693. }
  694. private PackFile writePack(@NonNull Set<? extends ObjectId> want,
  695. @NonNull Set<? extends ObjectId> have, Set<ObjectId> tagTargets,
  696. List<ObjectIdSet> excludeObjects) throws IOException {
  697. File tmpPack = null;
  698. Map<PackExt, File> tmpExts = new TreeMap<PackExt, File>(
  699. new Comparator<PackExt>() {
  700. public int compare(PackExt o1, PackExt o2) {
  701. // INDEX entries must be returned last, so the pack
  702. // scanner does pick up the new pack until all the
  703. // PackExt entries have been written.
  704. if (o1 == o2)
  705. return 0;
  706. if (o1 == PackExt.INDEX)
  707. return 1;
  708. if (o2 == PackExt.INDEX)
  709. return -1;
  710. return Integer.signum(o1.hashCode() - o2.hashCode());
  711. }
  712. });
  713. try (PackWriter pw = new PackWriter(
  714. (pconfig == null) ? new PackConfig(repo) : pconfig,
  715. repo.newObjectReader())) {
  716. // prepare the PackWriter
  717. pw.setDeltaBaseAsOffset(true);
  718. pw.setReuseDeltaCommits(false);
  719. if (tagTargets != null)
  720. pw.setTagTargets(tagTargets);
  721. if (excludeObjects != null)
  722. for (ObjectIdSet idx : excludeObjects)
  723. pw.excludeObjects(idx);
  724. pw.preparePack(pm, want, have);
  725. if (pw.getObjectCount() == 0)
  726. return null;
  727. // create temporary files
  728. String id = pw.computeName().getName();
  729. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  730. tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
  731. final String tmpBase = tmpPack.getName()
  732. .substring(0, tmpPack.getName().lastIndexOf('.'));
  733. File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
  734. tmpExts.put(INDEX, tmpIdx);
  735. if (!tmpIdx.createNewFile())
  736. throw new IOException(MessageFormat.format(
  737. JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
  738. // write the packfile
  739. FileOutputStream fos = new FileOutputStream(tmpPack);
  740. FileChannel channel = fos.getChannel();
  741. OutputStream channelStream = Channels.newOutputStream(channel);
  742. try {
  743. pw.writePack(pm, pm, channelStream);
  744. } finally {
  745. channel.force(true);
  746. channelStream.close();
  747. fos.close();
  748. }
  749. // write the packindex
  750. fos = new FileOutputStream(tmpIdx);
  751. FileChannel idxChannel = fos.getChannel();
  752. OutputStream idxStream = Channels.newOutputStream(idxChannel);
  753. try {
  754. pw.writeIndex(idxStream);
  755. } finally {
  756. idxChannel.force(true);
  757. idxStream.close();
  758. fos.close();
  759. }
  760. if (pw.prepareBitmapIndex(pm)) {
  761. File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
  762. tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
  763. if (!tmpBitmapIdx.createNewFile())
  764. throw new IOException(MessageFormat.format(
  765. JGitText.get().cannotCreateIndexfile,
  766. tmpBitmapIdx.getPath()));
  767. fos = new FileOutputStream(tmpBitmapIdx);
  768. idxChannel = fos.getChannel();
  769. idxStream = Channels.newOutputStream(idxChannel);
  770. try {
  771. pw.writeBitmapIndex(idxStream);
  772. } finally {
  773. idxChannel.force(true);
  774. idxStream.close();
  775. fos.close();
  776. }
  777. }
  778. // rename the temporary files to real files
  779. File realPack = nameFor(id, ".pack"); //$NON-NLS-1$
  780. // if the packfile already exists (because we are rewriting a
  781. // packfile for the same set of objects maybe with different
  782. // PackConfig) then make sure we get rid of all handles on the file.
  783. // Windows will not allow for rename otherwise.
  784. if (realPack.exists())
  785. for (PackFile p : repo.getObjectDatabase().getPacks())
  786. if (realPack.getPath().equals(p.getPackFile().getPath())) {
  787. p.close();
  788. break;
  789. }
  790. tmpPack.setReadOnly();
  791. FileUtils.rename(tmpPack, realPack, StandardCopyOption.ATOMIC_MOVE);
  792. for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
  793. File tmpExt = tmpEntry.getValue();
  794. tmpExt.setReadOnly();
  795. File realExt = nameFor(id,
  796. "." + tmpEntry.getKey().getExtension()); //$NON-NLS-1$
  797. try {
  798. FileUtils.rename(tmpExt, realExt,
  799. StandardCopyOption.ATOMIC_MOVE);
  800. } catch (IOException e) {
  801. File newExt = new File(realExt.getParentFile(),
  802. realExt.getName() + ".new"); //$NON-NLS-1$
  803. try {
  804. FileUtils.rename(tmpExt, newExt,
  805. StandardCopyOption.ATOMIC_MOVE);
  806. } catch (IOException e2) {
  807. newExt = tmpExt;
  808. e = e2;
  809. }
  810. throw new IOException(MessageFormat.format(
  811. JGitText.get().panicCantRenameIndexFile, newExt,
  812. realExt), e);
  813. }
  814. }
  815. return repo.getObjectDatabase().openPack(realPack);
  816. } finally {
  817. if (tmpPack != null && tmpPack.exists())
  818. tmpPack.delete();
  819. for (File tmpExt : tmpExts.values()) {
  820. if (tmpExt.exists())
  821. tmpExt.delete();
  822. }
  823. }
  824. }
  825. private File nameFor(String name, String ext) {
  826. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  827. return new File(packdir, "pack-" + name + ext); //$NON-NLS-1$
  828. }
  829. /**
  830. * A class holding statistical data for a FileRepository regarding how many
  831. * objects are stored as loose or packed objects
  832. */
  833. public static class RepoStatistics {
  834. /**
  835. * The number of objects stored in pack files. If the same object is
  836. * stored in multiple pack files then it is counted as often as it
  837. * occurs in pack files.
  838. */
  839. public long numberOfPackedObjects;
  840. /**
  841. * The number of pack files
  842. */
  843. public long numberOfPackFiles;
  844. /**
  845. * The number of objects stored as loose objects.
  846. */
  847. public long numberOfLooseObjects;
  848. /**
  849. * The sum of the sizes of all files used to persist loose objects.
  850. */
  851. public long sizeOfLooseObjects;
  852. /**
  853. * The sum of the sizes of all pack files.
  854. */
  855. public long sizeOfPackedObjects;
  856. /**
  857. * The number of loose refs.
  858. */
  859. public long numberOfLooseRefs;
  860. /**
  861. * The number of refs stored in pack files.
  862. */
  863. public long numberOfPackedRefs;
  864. /**
  865. * The number of bitmaps in the bitmap indices.
  866. */
  867. public long numberOfBitmaps;
  868. public String toString() {
  869. final StringBuilder b = new StringBuilder();
  870. b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
  871. b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
  872. b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
  873. b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
  874. b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
  875. b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
  876. b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
  877. b.append(", numberOfBitmaps=").append(numberOfBitmaps); //$NON-NLS-1$
  878. return b.toString();
  879. }
  880. }
  881. /**
  882. * Returns information about objects and pack files for a FileRepository.
  883. *
  884. * @return information about objects and pack files for a FileRepository
  885. * @throws IOException
  886. */
  887. public RepoStatistics getStatistics() throws IOException {
  888. RepoStatistics ret = new RepoStatistics();
  889. Collection<PackFile> packs = repo.getObjectDatabase().getPacks();
  890. for (PackFile f : packs) {
  891. ret.numberOfPackedObjects += f.getIndex().getObjectCount();
  892. ret.numberOfPackFiles++;
  893. ret.sizeOfPackedObjects += f.getPackFile().length();
  894. if (f.getBitmapIndex() != null)
  895. ret.numberOfBitmaps += f.getBitmapIndex().getBitmapCount();
  896. }
  897. File objDir = repo.getObjectsDirectory();
  898. String[] fanout = objDir.list();
  899. if (fanout != null && fanout.length > 0) {
  900. for (String d : fanout) {
  901. if (d.length() != 2)
  902. continue;
  903. File[] entries = new File(objDir, d).listFiles();
  904. if (entries == null)
  905. continue;
  906. for (File f : entries) {
  907. if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  908. continue;
  909. ret.numberOfLooseObjects++;
  910. ret.sizeOfLooseObjects += f.length();
  911. }
  912. }
  913. }
  914. RefDatabase refDb = repo.getRefDatabase();
  915. for (Ref r : refDb.getRefs(RefDatabase.ALL).values()) {
  916. Storage storage = r.getStorage();
  917. if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
  918. ret.numberOfLooseRefs++;
  919. if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
  920. ret.numberOfPackedRefs++;
  921. }
  922. return ret;
  923. }
  924. /**
  925. * Set the progress monitor used for garbage collection methods.
  926. *
  927. * @param pm
  928. * @return this
  929. */
  930. public GC setProgressMonitor(ProgressMonitor pm) {
  931. this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
  932. return this;
  933. }
  934. /**
  935. * During gc() or prune() each unreferenced, loose object which has been
  936. * created or modified in the last <code>expireAgeMillis</code> milliseconds
  937. * will not be pruned. Only older objects may be pruned. If set to 0 then
  938. * every object is a candidate for pruning.
  939. *
  940. * @param expireAgeMillis
  941. * minimal age of objects to be pruned in milliseconds.
  942. */
  943. public void setExpireAgeMillis(long expireAgeMillis) {
  944. this.expireAgeMillis = expireAgeMillis;
  945. expire = null;
  946. }
  947. /**
  948. * During gc() or prune() packfiles which are created or modified in the
  949. * last <code>packExpireAgeMillis</code> milliseconds will not be deleted.
  950. * Only older packfiles may be deleted. If set to 0 then every packfile is a
  951. * candidate for deletion.
  952. *
  953. * @param packExpireAgeMillis
  954. * minimal age of packfiles to be deleted in milliseconds.
  955. */
  956. public void setPackExpireAgeMillis(long packExpireAgeMillis) {
  957. this.packExpireAgeMillis = packExpireAgeMillis;
  958. expire = null;
  959. }
  960. /**
  961. * Set the PackConfig used when (re-)writing packfiles. This allows to
  962. * influence how packs are written and to implement something similar to
  963. * "git gc --aggressive"
  964. *
  965. * @since 3.6
  966. * @param pconfig
  967. * the {@link PackConfig} used when writing packs
  968. */
  969. public void setPackConfig(PackConfig pconfig) {
  970. this.pconfig = pconfig;
  971. }
  972. /**
  973. * During gc() or prune() each unreferenced, loose object which has been
  974. * created or modified after or at <code>expire</code> will not be pruned.
  975. * Only older objects may be pruned. If set to null then every object is a
  976. * candidate for pruning.
  977. *
  978. * @param expire
  979. * instant in time which defines object expiration
  980. * objects with modification time before this instant are expired
  981. * objects with modification time newer or equal to this instant
  982. * are not expired
  983. */
  984. public void setExpire(Date expire) {
  985. this.expire = expire;
  986. expireAgeMillis = -1;
  987. }
  988. /**
  989. * During gc() or prune() packfiles which are created or modified after or
  990. * at <code>packExpire</code> will not be deleted. Only older packfiles may
  991. * be deleted. If set to null then every packfile is a candidate for
  992. * deletion.
  993. *
  994. * @param packExpire
  995. * instant in time which defines packfile expiration
  996. */
  997. public void setPackExpire(Date packExpire) {
  998. this.packExpire = packExpire;
  999. packExpireAgeMillis = -1;
  1000. }
  1001. }