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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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 static org.eclipse.jgit.lib.RefDatabase.ALL;
  48. import java.io.File;
  49. import java.io.FileOutputStream;
  50. import java.io.IOException;
  51. import java.io.OutputStream;
  52. import java.nio.channels.Channels;
  53. import java.nio.channels.FileChannel;
  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.Iterator;
  64. import java.util.LinkedList;
  65. import java.util.List;
  66. import java.util.Map;
  67. import java.util.Map.Entry;
  68. import java.util.Set;
  69. import java.util.TreeMap;
  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.pack.PackWriter.ObjectIdSet;
  79. import org.eclipse.jgit.lib.AnyObjectId;
  80. import org.eclipse.jgit.lib.ConfigConstants;
  81. import org.eclipse.jgit.lib.Constants;
  82. import org.eclipse.jgit.lib.FileMode;
  83. import org.eclipse.jgit.lib.NullProgressMonitor;
  84. import org.eclipse.jgit.lib.ObjectId;
  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.revwalk.ObjectWalk;
  91. import org.eclipse.jgit.revwalk.RevObject;
  92. import org.eclipse.jgit.revwalk.RevWalk;
  93. import org.eclipse.jgit.treewalk.TreeWalk;
  94. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  95. import org.eclipse.jgit.util.FileUtils;
  96. import org.eclipse.jgit.util.GitDateParser;
  97. import org.eclipse.jgit.util.SystemReader;
  98. /**
  99. * A garbage collector for git {@link FileRepository}. Instances of this class
  100. * are not thread-safe. Don't use the same instance from multiple threads.
  101. *
  102. * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
  103. * adapted to FileRepositories.
  104. */
  105. public class GC {
  106. private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
  107. private final FileRepository repo;
  108. private ProgressMonitor pm;
  109. private long expireAgeMillis = -1;
  110. private Date expire;
  111. /**
  112. * the refs which existed during the last call to {@link #repack()}. This is
  113. * needed during {@link #prune(Set)} where we can optimize by looking at the
  114. * difference between the current refs and the refs which existed during
  115. * last {@link #repack()}.
  116. */
  117. private Map<String, Ref> lastPackedRefs;
  118. /**
  119. * Holds the starting time of the last repack() execution. This is needed in
  120. * prune() to inspect only those reflog entries which have been added since
  121. * last repack().
  122. */
  123. private long lastRepackTime;
  124. /**
  125. * Creates a new garbage collector with default values. An expirationTime of
  126. * two weeks and <code>null</code> as progress monitor will be used.
  127. *
  128. * @param repo
  129. * the repo to work on
  130. */
  131. public GC(FileRepository repo) {
  132. this.repo = repo;
  133. this.pm = NullProgressMonitor.INSTANCE;
  134. }
  135. /**
  136. * Runs a garbage collector on a {@link FileRepository}. It will
  137. * <ul>
  138. * <li>pack loose references into packed-refs</li>
  139. * <li>repack all reachable objects into new pack files and delete the old
  140. * pack files</li>
  141. * <li>prune all loose objects which are now reachable by packs</li>
  142. * </ul>
  143. *
  144. * @return the collection of {@link PackFile}'s which are newly created
  145. * @throws IOException
  146. * @throws ParseException
  147. * If the configuration parameter "gc.pruneexpire" couldn't be
  148. * parsed
  149. */
  150. public Collection<PackFile> gc() throws IOException, ParseException {
  151. pm.start(6 /* tasks */);
  152. packRefs();
  153. // TODO: implement reflog_expire(pm, repo);
  154. Collection<PackFile> newPacks = repack();
  155. prune(Collections.<ObjectId> emptySet());
  156. // TODO: implement rerere_gc(pm);
  157. return newPacks;
  158. }
  159. /**
  160. * Delete old pack files. What is 'old' is defined by specifying a set of
  161. * old pack files and a set of new pack files. Each pack file contained in
  162. * old pack files but not contained in new pack files will be deleted.
  163. *
  164. * @param oldPacks
  165. * @param newPacks
  166. */
  167. private void deleteOldPacks(Collection<PackFile> oldPacks,
  168. Collection<PackFile> newPacks) {
  169. oldPackLoop: for (PackFile oldPack : oldPacks) {
  170. String oldName = oldPack.getPackName();
  171. // check whether an old pack file is also among the list of new
  172. // pack files. Then we must not delete it.
  173. for (PackFile newPack : newPacks)
  174. if (oldName.equals(newPack.getPackName()))
  175. continue oldPackLoop;
  176. if (!oldPack.shouldBeKept()) {
  177. oldPack.close();
  178. prunePack(oldName);
  179. }
  180. }
  181. // close the complete object database. Thats my only chance to force
  182. // rescanning and to detect that certain pack files are now deleted.
  183. repo.getObjectDatabase().close();
  184. }
  185. /**
  186. * Delete files associated with a single pack file. First try to delete the
  187. * ".pack" file because on some platforms the ".pack" file may be locked and
  188. * can't be deleted. In such a case it is better to detect this early and
  189. * give up on deleting files for this packfile. Otherwise we may delete the
  190. * ".index" file and when failing to delete the ".pack" file we are left
  191. * with a ".pack" file without a ".index" file.
  192. *
  193. * @param packName
  194. */
  195. private void prunePack(String packName) {
  196. PackExt[] extensions = PackExt.values();
  197. try {
  198. // Delete the .pack file first and if this fails give up on deleting
  199. // the other files
  200. int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  201. for (PackExt ext : extensions)
  202. if (PackExt.PACK.equals(ext)) {
  203. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  204. FileUtils.delete(f, deleteOptions);
  205. break;
  206. }
  207. // The .pack file has been deleted. Delete as many as the other
  208. // files as you can.
  209. deleteOptions |= FileUtils.IGNORE_ERRORS;
  210. for (PackExt ext : extensions) {
  211. if (!PackExt.PACK.equals(ext)) {
  212. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  213. FileUtils.delete(f, deleteOptions);
  214. }
  215. }
  216. } catch (IOException e) {
  217. // Deletion of the .pack file failed. Silently return.
  218. }
  219. }
  220. /**
  221. * Like "git prune-packed" this method tries to prune all loose objects
  222. * which can be found in packs. If certain objects can't be pruned (e.g.
  223. * because the filesystem delete operation fails) this is silently ignored.
  224. *
  225. * @throws IOException
  226. */
  227. public void prunePacked() throws IOException {
  228. ObjectDirectory objdb = repo.getObjectDatabase();
  229. Collection<PackFile> packs = objdb.getPacks();
  230. File objects = repo.getObjectsDirectory();
  231. String[] fanout = objects.list();
  232. if (fanout != null && fanout.length > 0) {
  233. pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
  234. try {
  235. for (String d : fanout) {
  236. pm.update(1);
  237. if (d.length() != 2)
  238. continue;
  239. String[] entries = new File(objects, d).list();
  240. if (entries == null)
  241. continue;
  242. for (String e : entries) {
  243. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  244. continue;
  245. ObjectId id;
  246. try {
  247. id = ObjectId.fromString(d + e);
  248. } catch (IllegalArgumentException notAnObject) {
  249. // ignoring the file that does not represent loose
  250. // object
  251. continue;
  252. }
  253. boolean found = false;
  254. for (PackFile p : packs)
  255. if (p.hasObject(id)) {
  256. found = true;
  257. break;
  258. }
  259. if (found)
  260. FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
  261. | FileUtils.SKIP_MISSING
  262. | FileUtils.IGNORE_ERRORS);
  263. }
  264. }
  265. } finally {
  266. pm.endTask();
  267. }
  268. }
  269. }
  270. /**
  271. * Like "git prune" this method tries to prune all loose objects which are
  272. * unreferenced. If certain objects can't be pruned (e.g. because the
  273. * filesystem delete operation fails) this is silently ignored.
  274. *
  275. * @param objectsToKeep
  276. * a set of objects which should explicitly not be pruned
  277. *
  278. * @throws IOException
  279. * @throws ParseException
  280. * If the configuration parameter "gc.pruneexpire" couldn't be
  281. * parsed
  282. */
  283. public void prune(Set<ObjectId> objectsToKeep) throws IOException,
  284. ParseException {
  285. long expireDate = Long.MAX_VALUE;
  286. if (expire == null && expireAgeMillis == -1) {
  287. String pruneExpireStr = repo.getConfig().getString(
  288. ConfigConstants.CONFIG_GC_SECTION, null,
  289. ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
  290. if (pruneExpireStr == null)
  291. pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
  292. expire = GitDateParser.parse(pruneExpireStr, null, SystemReader
  293. .getInstance().getLocale());
  294. expireAgeMillis = -1;
  295. }
  296. if (expire != null)
  297. expireDate = expire.getTime();
  298. if (expireAgeMillis != -1)
  299. expireDate = System.currentTimeMillis() - expireAgeMillis;
  300. // Collect all loose objects which are old enough, not referenced from
  301. // the index and not in objectsToKeep
  302. Map<ObjectId, File> deletionCandidates = new HashMap<ObjectId, File>();
  303. Set<ObjectId> indexObjects = null;
  304. File objects = repo.getObjectsDirectory();
  305. String[] fanout = objects.list();
  306. if (fanout != null && fanout.length > 0) {
  307. pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
  308. fanout.length);
  309. try {
  310. for (String d : fanout) {
  311. pm.update(1);
  312. if (d.length() != 2)
  313. continue;
  314. File[] entries = new File(objects, d).listFiles();
  315. if (entries == null)
  316. continue;
  317. for (File f : entries) {
  318. String fName = f.getName();
  319. if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  320. continue;
  321. if (f.lastModified() >= expireDate)
  322. continue;
  323. try {
  324. ObjectId id = ObjectId.fromString(d + fName);
  325. if (objectsToKeep.contains(id))
  326. continue;
  327. if (indexObjects == null)
  328. indexObjects = listNonHEADIndexObjects();
  329. if (indexObjects.contains(id))
  330. continue;
  331. deletionCandidates.put(id, f);
  332. } catch (IllegalArgumentException notAnObject) {
  333. // ignoring the file that does not represent loose
  334. // object
  335. continue;
  336. }
  337. }
  338. }
  339. } finally {
  340. pm.endTask();
  341. }
  342. }
  343. if (deletionCandidates.isEmpty())
  344. return;
  345. // From the set of current refs remove all those which have been handled
  346. // during last repack(). Only those refs will survive which have been
  347. // added or modified since the last repack. Only these can save existing
  348. // loose refs from being pruned.
  349. Map<String, Ref> newRefs;
  350. if (lastPackedRefs == null || lastPackedRefs.isEmpty())
  351. newRefs = getAllRefs();
  352. else {
  353. newRefs = new HashMap<String, Ref>();
  354. for (Iterator<Map.Entry<String, Ref>> i = getAllRefs().entrySet()
  355. .iterator(); i.hasNext();) {
  356. Entry<String, Ref> newEntry = i.next();
  357. Ref old = lastPackedRefs.get(newEntry.getKey());
  358. if (!equals(newEntry.getValue(), old))
  359. newRefs.put(newEntry.getKey(), newEntry.getValue());
  360. }
  361. }
  362. if (!newRefs.isEmpty()) {
  363. // There are new/modified refs! Check which loose objects are now
  364. // referenced by these modified refs (or their reflogentries).
  365. // Remove these loose objects
  366. // from the deletionCandidates. When the last candidate is removed
  367. // leave this method.
  368. ObjectWalk w = new ObjectWalk(repo);
  369. try {
  370. for (Ref cr : newRefs.values())
  371. w.markStart(w.parseAny(cr.getObjectId()));
  372. if (lastPackedRefs != null)
  373. for (Ref lpr : lastPackedRefs.values())
  374. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  375. removeReferenced(deletionCandidates, w);
  376. } finally {
  377. w.dispose();
  378. }
  379. }
  380. if (deletionCandidates.isEmpty())
  381. return;
  382. // Since we have not left the method yet there are still
  383. // deletionCandidates. Last chance for these objects not to be pruned is
  384. // that they are referenced by reflog entries. Even refs which currently
  385. // point to the same object as during last repack() may have
  386. // additional reflog entries not handled during last repack()
  387. ObjectWalk w = new ObjectWalk(repo);
  388. try {
  389. for (Ref ar : getAllRefs().values())
  390. for (ObjectId id : listRefLogObjects(ar, lastRepackTime))
  391. w.markStart(w.parseAny(id));
  392. if (lastPackedRefs != null)
  393. for (Ref lpr : lastPackedRefs.values())
  394. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  395. removeReferenced(deletionCandidates, w);
  396. } finally {
  397. w.dispose();
  398. }
  399. if (deletionCandidates.isEmpty())
  400. return;
  401. // delete all candidates which have survived: these are unreferenced
  402. // loose objects
  403. for (File f : deletionCandidates.values())
  404. f.delete();
  405. repo.getObjectDatabase().close();
  406. }
  407. /**
  408. * Remove all entries from a map which key is the id of an object referenced
  409. * by the given ObjectWalk
  410. *
  411. * @param id2File
  412. * @param w
  413. * @throws MissingObjectException
  414. * @throws IncorrectObjectTypeException
  415. * @throws IOException
  416. */
  417. private void removeReferenced(Map<ObjectId, File> id2File,
  418. ObjectWalk w) throws MissingObjectException,
  419. IncorrectObjectTypeException, IOException {
  420. RevObject ro = w.next();
  421. while (ro != null) {
  422. if (id2File.remove(ro.getId()) != null)
  423. if (id2File.isEmpty())
  424. return;
  425. ro = w.next();
  426. }
  427. ro = w.nextObject();
  428. while (ro != null) {
  429. if (id2File.remove(ro.getId()) != null)
  430. if (id2File.isEmpty())
  431. return;
  432. ro = w.nextObject();
  433. }
  434. }
  435. private static boolean equals(Ref r1, Ref r2) {
  436. if (r1 == null || r2 == null)
  437. return false;
  438. if (r1.isSymbolic()) {
  439. if (!r2.isSymbolic())
  440. return false;
  441. return r1.getTarget().getName().equals(r2.getTarget().getName());
  442. } else {
  443. if (r2.isSymbolic())
  444. return false;
  445. return r1.getObjectId().equals(r2.getObjectId());
  446. }
  447. }
  448. /**
  449. * Packs all non-symbolic, loose refs into packed-refs.
  450. *
  451. * @throws IOException
  452. */
  453. public void packRefs() throws IOException {
  454. Collection<Ref> refs = repo.getRefDatabase().getRefs(ALL).values();
  455. List<String> refsToBePacked = new ArrayList<String>(refs.size());
  456. pm.beginTask(JGitText.get().packRefs, refs.size());
  457. try {
  458. for (Ref ref : refs) {
  459. if (!ref.isSymbolic() && ref.getStorage().isLoose())
  460. refsToBePacked.add(ref.getName());
  461. pm.update(1);
  462. }
  463. ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
  464. } finally {
  465. pm.endTask();
  466. }
  467. }
  468. /**
  469. * Packs all objects which reachable from any of the heads into one pack
  470. * file. Additionally all objects which are not reachable from any head but
  471. * which are reachable from any of the other refs (e.g. tags), special refs
  472. * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
  473. * included in pack files which have a .keep file associated are never
  474. * repacked. All old pack files which existed before are deleted.
  475. *
  476. * @return a collection of the newly created pack files
  477. * @throws IOException
  478. * when during reading of refs, index, packfiles, objects,
  479. * reflog-entries or during writing to the packfiles
  480. * {@link IOException} occurs
  481. */
  482. public Collection<PackFile> repack() throws IOException {
  483. Collection<PackFile> toBeDeleted = repo.getObjectDatabase().getPacks();
  484. long time = System.currentTimeMillis();
  485. Map<String, Ref> refsBefore = getAllRefs();
  486. Set<ObjectId> allHeads = new HashSet<ObjectId>();
  487. Set<ObjectId> nonHeads = new HashSet<ObjectId>();
  488. Set<ObjectId> tagTargets = new HashSet<ObjectId>();
  489. Set<ObjectId> indexObjects = listNonHEADIndexObjects();
  490. for (Ref ref : refsBefore.values()) {
  491. nonHeads.addAll(listRefLogObjects(ref, 0));
  492. if (ref.isSymbolic() || ref.getObjectId() == null)
  493. continue;
  494. if (ref.getName().startsWith(Constants.R_HEADS))
  495. allHeads.add(ref.getObjectId());
  496. else
  497. nonHeads.add(ref.getObjectId());
  498. if (ref.getPeeledObjectId() != null)
  499. tagTargets.add(ref.getPeeledObjectId());
  500. }
  501. List<ObjectIdSet> excluded = new LinkedList<ObjectIdSet>();
  502. for (final PackFile f : repo.getObjectDatabase().getPacks())
  503. if (f.shouldBeKept())
  504. excluded.add(objectIdSet(f.getIndex()));
  505. tagTargets.addAll(allHeads);
  506. nonHeads.addAll(indexObjects);
  507. List<PackFile> ret = new ArrayList<PackFile>(2);
  508. PackFile heads = null;
  509. if (!allHeads.isEmpty()) {
  510. heads = writePack(allHeads, Collections.<ObjectId> emptySet(),
  511. tagTargets, excluded);
  512. if (heads != null) {
  513. ret.add(heads);
  514. excluded.add(0, objectIdSet(heads.getIndex()));
  515. }
  516. }
  517. if (!nonHeads.isEmpty()) {
  518. PackFile rest = writePack(nonHeads, allHeads, tagTargets, excluded);
  519. if (rest != null)
  520. ret.add(rest);
  521. }
  522. deleteOldPacks(toBeDeleted, ret);
  523. prunePacked();
  524. lastPackedRefs = refsBefore;
  525. lastRepackTime = time;
  526. return ret;
  527. }
  528. /**
  529. * @param ref
  530. * the ref which log should be inspected
  531. * @param minTime only reflog entries not older then this time are processed
  532. * @return the {@link ObjectId}s contained in the reflog
  533. * @throws IOException
  534. */
  535. private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
  536. List<ReflogEntry> rlEntries = repo.getReflogReader(ref.getName())
  537. .getReverseEntries();
  538. if (rlEntries == null || rlEntries.isEmpty())
  539. return Collections.<ObjectId> emptySet();
  540. Set<ObjectId> ret = new HashSet<ObjectId>();
  541. for (ReflogEntry e : rlEntries) {
  542. if (e.getWho().getWhen().getTime() < minTime)
  543. break;
  544. ObjectId newId = e.getNewId();
  545. if (newId != null && !ObjectId.zeroId().equals(newId))
  546. ret.add(newId);
  547. ObjectId oldId = e.getOldId();
  548. if (oldId != null && !ObjectId.zeroId().equals(oldId))
  549. ret.add(oldId);
  550. }
  551. return ret;
  552. }
  553. /**
  554. * Returns a map of all refs and additional refs (e.g. FETCH_HEAD,
  555. * MERGE_HEAD, ...)
  556. *
  557. * @return a map where names of refs point to ref objects
  558. * @throws IOException
  559. */
  560. private Map<String, Ref> getAllRefs() throws IOException {
  561. Map<String, Ref> ret = repo.getRefDatabase().getRefs(ALL);
  562. for (Ref ref : repo.getRefDatabase().getAdditionalRefs())
  563. ret.put(ref.getName(), ref);
  564. return ret;
  565. }
  566. /**
  567. * Return a list of those objects in the index which differ from whats in
  568. * HEAD
  569. *
  570. * @return a set of ObjectIds of changed objects in the index
  571. * @throws IOException
  572. * @throws CorruptObjectException
  573. * @throws NoWorkTreeException
  574. */
  575. private Set<ObjectId> listNonHEADIndexObjects()
  576. throws CorruptObjectException, IOException {
  577. RevWalk revWalk = null;
  578. try {
  579. if (repo.getIndexFile() == null)
  580. return Collections.emptySet();
  581. } catch (NoWorkTreeException e) {
  582. return Collections.emptySet();
  583. }
  584. TreeWalk treeWalk = new TreeWalk(repo);
  585. try {
  586. treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
  587. ObjectId headID = repo.resolve(Constants.HEAD);
  588. if (headID != null) {
  589. revWalk = new RevWalk(repo);
  590. treeWalk.addTree(revWalk.parseTree(headID));
  591. revWalk.dispose();
  592. revWalk = null;
  593. }
  594. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  595. treeWalk.setRecursive(true);
  596. Set<ObjectId> ret = new HashSet<ObjectId>();
  597. while (treeWalk.next()) {
  598. ObjectId objectId = treeWalk.getObjectId(0);
  599. switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
  600. case FileMode.TYPE_MISSING:
  601. case FileMode.TYPE_GITLINK:
  602. continue;
  603. case FileMode.TYPE_TREE:
  604. case FileMode.TYPE_FILE:
  605. case FileMode.TYPE_SYMLINK:
  606. ret.add(objectId);
  607. continue;
  608. default:
  609. throw new IOException(MessageFormat.format(
  610. JGitText.get().corruptObjectInvalidMode3,
  611. String.format("%o", //$NON-NLS-1$
  612. Integer.valueOf(treeWalk.getRawMode(0))),
  613. (objectId == null) ? "null" : objectId.name(), //$NON-NLS-1$
  614. treeWalk.getPathString(), //
  615. repo.getIndexFile()));
  616. }
  617. }
  618. return ret;
  619. } finally {
  620. if (revWalk != null)
  621. revWalk.dispose();
  622. treeWalk.release();
  623. }
  624. }
  625. private PackFile writePack(Set<? extends ObjectId> want,
  626. Set<? extends ObjectId> have, Set<ObjectId> tagTargets,
  627. List<ObjectIdSet> excludeObjects) throws IOException {
  628. File tmpPack = null;
  629. Map<PackExt, File> tmpExts = new TreeMap<PackExt, File>(
  630. new Comparator<PackExt>() {
  631. public int compare(PackExt o1, PackExt o2) {
  632. // INDEX entries must be returned last, so the pack
  633. // scanner does pick up the new pack until all the
  634. // PackExt entries have been written.
  635. if (o1 == o2)
  636. return 0;
  637. if (o1 == PackExt.INDEX)
  638. return 1;
  639. if (o2 == PackExt.INDEX)
  640. return -1;
  641. return Integer.signum(o1.hashCode() - o2.hashCode());
  642. }
  643. });
  644. PackWriter pw = new PackWriter(repo);
  645. try {
  646. // prepare the PackWriter
  647. pw.setDeltaBaseAsOffset(true);
  648. pw.setReuseDeltaCommits(false);
  649. if (tagTargets != null)
  650. pw.setTagTargets(tagTargets);
  651. if (excludeObjects != null)
  652. for (ObjectIdSet idx : excludeObjects)
  653. pw.excludeObjects(idx);
  654. pw.preparePack(pm, want, have);
  655. if (pw.getObjectCount() == 0)
  656. return null;
  657. // create temporary files
  658. String id = pw.computeName().getName();
  659. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  660. tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
  661. final String tmpBase = tmpPack.getName()
  662. .substring(0, tmpPack.getName().lastIndexOf('.'));
  663. File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
  664. tmpExts.put(INDEX, tmpIdx);
  665. if (!tmpIdx.createNewFile())
  666. throw new IOException(MessageFormat.format(
  667. JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
  668. // write the packfile
  669. @SuppressWarnings("resource" /* java 7 */)
  670. FileChannel channel = new FileOutputStream(tmpPack).getChannel();
  671. OutputStream channelStream = Channels.newOutputStream(channel);
  672. try {
  673. pw.writePack(pm, pm, channelStream);
  674. } finally {
  675. channel.force(true);
  676. channelStream.close();
  677. channel.close();
  678. }
  679. // write the packindex
  680. FileChannel idxChannel = new FileOutputStream(tmpIdx).getChannel();
  681. OutputStream idxStream = Channels.newOutputStream(idxChannel);
  682. try {
  683. pw.writeIndex(idxStream);
  684. } finally {
  685. idxChannel.force(true);
  686. idxStream.close();
  687. idxChannel.close();
  688. }
  689. if (pw.prepareBitmapIndex(pm)) {
  690. File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
  691. tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
  692. if (!tmpBitmapIdx.createNewFile())
  693. throw new IOException(MessageFormat.format(
  694. JGitText.get().cannotCreateIndexfile,
  695. tmpBitmapIdx.getPath()));
  696. idxChannel = new FileOutputStream(tmpBitmapIdx).getChannel();
  697. idxStream = Channels.newOutputStream(idxChannel);
  698. try {
  699. pw.writeBitmapIndex(idxStream);
  700. } finally {
  701. idxChannel.force(true);
  702. idxStream.close();
  703. idxChannel.close();
  704. }
  705. }
  706. // rename the temporary files to real files
  707. File realPack = nameFor(id, ".pack"); //$NON-NLS-1$
  708. // if the packfile already exists (because we are rewriting a
  709. // packfile for the same set of objects maybe with different
  710. // PackConfig) then make sure we get rid of all handles on the file.
  711. // Windows will not allow for rename otherwise.
  712. if (realPack.exists())
  713. for (PackFile p : repo.getObjectDatabase().getPacks())
  714. if (realPack.getPath().equals(p.getPackFile().getPath())) {
  715. p.close();
  716. break;
  717. }
  718. tmpPack.setReadOnly();
  719. boolean delete = true;
  720. try {
  721. FileUtils.rename(tmpPack, realPack);
  722. delete = false;
  723. for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
  724. File tmpExt = tmpEntry.getValue();
  725. tmpExt.setReadOnly();
  726. File realExt = nameFor(
  727. id, "." + tmpEntry.getKey().getExtension()); //$NON-NLS-1$
  728. try {
  729. FileUtils.rename(tmpExt, realExt);
  730. } catch (IOException e) {
  731. File newExt = new File(realExt.getParentFile(),
  732. realExt.getName() + ".new"); //$NON-NLS-1$
  733. if (!tmpExt.renameTo(newExt))
  734. newExt = tmpExt;
  735. throw new IOException(MessageFormat.format(
  736. JGitText.get().panicCantRenameIndexFile, newExt,
  737. realExt));
  738. }
  739. }
  740. } finally {
  741. if (delete) {
  742. if (tmpPack.exists())
  743. tmpPack.delete();
  744. for (File tmpExt : tmpExts.values()) {
  745. if (tmpExt.exists())
  746. tmpExt.delete();
  747. }
  748. }
  749. }
  750. return repo.getObjectDatabase().openPack(realPack);
  751. } finally {
  752. pw.release();
  753. if (tmpPack != null && tmpPack.exists())
  754. tmpPack.delete();
  755. for (File tmpExt : tmpExts.values()) {
  756. if (tmpExt.exists())
  757. tmpExt.delete();
  758. }
  759. }
  760. }
  761. private File nameFor(String name, String ext) {
  762. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  763. return new File(packdir, "pack-" + name + ext); //$NON-NLS-1$
  764. }
  765. /**
  766. * A class holding statistical data for a FileRepository regarding how many
  767. * objects are stored as loose or packed objects
  768. */
  769. public class RepoStatistics {
  770. /**
  771. * The number of objects stored in pack files. If the same object is
  772. * stored in multiple pack files then it is counted as often as it
  773. * occurs in pack files.
  774. */
  775. public long numberOfPackedObjects;
  776. /**
  777. * The number of pack files
  778. */
  779. public long numberOfPackFiles;
  780. /**
  781. * The number of objects stored as loose objects.
  782. */
  783. public long numberOfLooseObjects;
  784. /**
  785. * The sum of the sizes of all files used to persist loose objects.
  786. */
  787. public long sizeOfLooseObjects;
  788. /**
  789. * The sum of the sizes of all pack files.
  790. */
  791. public long sizeOfPackedObjects;
  792. /**
  793. * The number of loose refs.
  794. */
  795. public long numberOfLooseRefs;
  796. /**
  797. * The number of refs stored in pack files.
  798. */
  799. public long numberOfPackedRefs;
  800. public String toString() {
  801. final StringBuilder b = new StringBuilder();
  802. b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
  803. b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
  804. b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
  805. b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
  806. b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
  807. b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
  808. b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
  809. return b.toString();
  810. }
  811. }
  812. /**
  813. * Returns the number of objects stored in pack files. If an object is
  814. * contained in multiple pack files it is counted as often as it occurs.
  815. *
  816. * @return the number of objects stored in pack files
  817. * @throws IOException
  818. */
  819. public RepoStatistics getStatistics() throws IOException {
  820. RepoStatistics ret = new RepoStatistics();
  821. Collection<PackFile> packs = repo.getObjectDatabase().getPacks();
  822. for (PackFile f : packs) {
  823. ret.numberOfPackedObjects += f.getIndex().getObjectCount();
  824. ret.numberOfPackFiles++;
  825. ret.sizeOfPackedObjects += f.getPackFile().length();
  826. }
  827. File objDir = repo.getObjectsDirectory();
  828. String[] fanout = objDir.list();
  829. if (fanout != null && fanout.length > 0) {
  830. for (String d : fanout) {
  831. if (d.length() != 2)
  832. continue;
  833. File[] entries = new File(objDir, d).listFiles();
  834. if (entries == null)
  835. continue;
  836. for (File f : entries) {
  837. if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  838. continue;
  839. ret.numberOfLooseObjects++;
  840. ret.sizeOfLooseObjects += f.length();
  841. }
  842. }
  843. }
  844. RefDatabase refDb = repo.getRefDatabase();
  845. for (Ref r : refDb.getRefs(RefDatabase.ALL).values()) {
  846. Storage storage = r.getStorage();
  847. if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
  848. ret.numberOfLooseRefs++;
  849. if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
  850. ret.numberOfPackedRefs++;
  851. }
  852. return ret;
  853. }
  854. /**
  855. * Set the progress monitor used for garbage collection methods.
  856. *
  857. * @param pm
  858. * @return this
  859. */
  860. public GC setProgressMonitor(ProgressMonitor pm) {
  861. this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
  862. return this;
  863. }
  864. /**
  865. * During gc() or prune() each unreferenced, loose object which has been
  866. * created or modified in the last <code>expireAgeMillis</code> milliseconds
  867. * will not be pruned. Only older objects may be pruned. If set to 0 then
  868. * every object is a candidate for pruning.
  869. *
  870. * @param expireAgeMillis
  871. * minimal age of objects to be pruned in milliseconds.
  872. */
  873. public void setExpireAgeMillis(long expireAgeMillis) {
  874. this.expireAgeMillis = expireAgeMillis;
  875. expire = null;
  876. }
  877. /**
  878. * During gc() or prune() each unreferenced, loose object which has been
  879. * created or modified after or at <code>expire</code> will not be pruned.
  880. * Only older objects may be pruned. If set to null then every object is a
  881. * candidate for pruning.
  882. *
  883. * @param expire
  884. * instant in time which defines object expiration
  885. * objects with modification time before this instant are expired
  886. * objects with modification time newer or equal to this instant
  887. * are not expired
  888. */
  889. public void setExpire(Date expire) {
  890. this.expire = expire;
  891. expireAgeMillis = -1;
  892. }
  893. private static ObjectIdSet objectIdSet(final PackIndex idx) {
  894. return new ObjectIdSet() {
  895. public boolean contains(AnyObjectId objectId) {
  896. return idx.hasObject(objectId);
  897. }
  898. };
  899. }
  900. }