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.

RepositoryManager.java 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. /*
  2. * Copyright 2013 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.manager;
  17. import java.io.File;
  18. import java.io.FileFilter;
  19. import java.io.IOException;
  20. import java.lang.reflect.Field;
  21. import java.net.URI;
  22. import java.net.URISyntaxException;
  23. import java.text.MessageFormat;
  24. import java.text.SimpleDateFormat;
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import java.util.Calendar;
  28. import java.util.Collection;
  29. import java.util.Collections;
  30. import java.util.Date;
  31. import java.util.HashSet;
  32. import java.util.LinkedHashMap;
  33. import java.util.LinkedHashSet;
  34. import java.util.List;
  35. import java.util.Map;
  36. import java.util.Map.Entry;
  37. import java.util.Set;
  38. import java.util.TreeSet;
  39. import java.util.concurrent.ConcurrentHashMap;
  40. import java.util.concurrent.Executors;
  41. import java.util.concurrent.ScheduledExecutorService;
  42. import java.util.concurrent.TimeUnit;
  43. import java.util.concurrent.atomic.AtomicInteger;
  44. import java.util.concurrent.atomic.AtomicReference;
  45. import org.eclipse.jgit.lib.Repository;
  46. import org.eclipse.jgit.lib.RepositoryCache;
  47. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  48. import org.eclipse.jgit.lib.StoredConfig;
  49. import org.eclipse.jgit.storage.file.FileBasedConfig;
  50. import org.eclipse.jgit.storage.file.WindowCacheConfig;
  51. import org.eclipse.jgit.util.FS;
  52. import org.eclipse.jgit.util.FileUtils;
  53. import org.slf4j.Logger;
  54. import org.slf4j.LoggerFactory;
  55. import com.gitblit.Constants;
  56. import com.gitblit.Constants.AccessPermission;
  57. import com.gitblit.Constants.AccessRestrictionType;
  58. import com.gitblit.Constants.AuthorizationControl;
  59. import com.gitblit.Constants.CommitMessageRenderer;
  60. import com.gitblit.Constants.FederationStrategy;
  61. import com.gitblit.Constants.PermissionType;
  62. import com.gitblit.Constants.RegistrantType;
  63. import com.gitblit.GitBlitException;
  64. import com.gitblit.IStoredSettings;
  65. import com.gitblit.Keys;
  66. import com.gitblit.models.ForkModel;
  67. import com.gitblit.models.Metric;
  68. import com.gitblit.models.RefModel;
  69. import com.gitblit.models.RegistrantAccessPermission;
  70. import com.gitblit.models.RepositoryModel;
  71. import com.gitblit.models.SearchResult;
  72. import com.gitblit.models.TeamModel;
  73. import com.gitblit.models.UserModel;
  74. import com.gitblit.service.GarbageCollectorService;
  75. import com.gitblit.service.LuceneService;
  76. import com.gitblit.service.MirrorService;
  77. import com.gitblit.utils.ArrayUtils;
  78. import com.gitblit.utils.ByteFormat;
  79. import com.gitblit.utils.CommitCache;
  80. import com.gitblit.utils.DeepCopier;
  81. import com.gitblit.utils.JGitUtils;
  82. import com.gitblit.utils.JGitUtils.LastChange;
  83. import com.gitblit.utils.MetricUtils;
  84. import com.gitblit.utils.ModelUtils;
  85. import com.gitblit.utils.ObjectCache;
  86. import com.gitblit.utils.StringUtils;
  87. import com.gitblit.utils.TimeUtils;
  88. /**
  89. * Repository manager creates, updates, deletes and caches git repositories. It
  90. * also starts services to mirror, index, and cleanup repositories.
  91. *
  92. * @author James Moger
  93. *
  94. */
  95. public class RepositoryManager implements IRepositoryManager {
  96. private final Logger logger = LoggerFactory.getLogger(getClass());
  97. private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
  98. private final ObjectCache<Long> repositorySizeCache = new ObjectCache<Long>();
  99. private final ObjectCache<List<Metric>> repositoryMetricsCache = new ObjectCache<List<Metric>>();
  100. private final Map<String, RepositoryModel> repositoryListCache = new ConcurrentHashMap<String, RepositoryModel>();
  101. private final AtomicReference<String> repositoryListSettingsChecksum = new AtomicReference<String>("");
  102. private final IStoredSettings settings;
  103. private final IRuntimeManager runtimeManager;
  104. private final IUserManager userManager;
  105. private final File repositoriesFolder;
  106. private LuceneService luceneExecutor;
  107. private GarbageCollectorService gcExecutor;
  108. private MirrorService mirrorExecutor;
  109. public RepositoryManager(
  110. IRuntimeManager runtimeManager,
  111. IUserManager userManager) {
  112. this.settings = runtimeManager.getSettings();
  113. this.runtimeManager = runtimeManager;
  114. this.userManager = userManager;
  115. this.repositoriesFolder = runtimeManager.getFileOrFolder(Keys.git.repositoriesFolder, "${baseFolder}/git");
  116. }
  117. @Override
  118. public RepositoryManager start() {
  119. logger.info("Repositories folder : {}", repositoriesFolder.getAbsolutePath());
  120. // initialize utilities
  121. String prefix = settings.getString(Keys.git.userRepositoryPrefix, "~");
  122. ModelUtils.setUserRepoPrefix(prefix);
  123. // calculate repository list settings checksum for future config changes
  124. repositoryListSettingsChecksum.set(getRepositoryListSettingsChecksum());
  125. // build initial repository list
  126. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  127. logger.info("Identifying repositories...");
  128. getRepositoryList();
  129. }
  130. configureLuceneIndexing();
  131. configureGarbageCollector();
  132. configureMirrorExecutor();
  133. configureJGit();
  134. configureCommitCache();
  135. confirmWriteAccess();
  136. return this;
  137. }
  138. @Override
  139. public RepositoryManager stop() {
  140. scheduledExecutor.shutdownNow();
  141. luceneExecutor.close();
  142. gcExecutor.close();
  143. mirrorExecutor.close();
  144. return this;
  145. }
  146. /**
  147. * Returns the most recent change date of any repository served by Gitblit.
  148. *
  149. * @return a date
  150. */
  151. @Override
  152. public Date getLastActivityDate() {
  153. Date date = null;
  154. for (String name : getRepositoryList()) {
  155. Repository r = getRepository(name);
  156. Date lastChange = JGitUtils.getLastChange(r).when;
  157. r.close();
  158. if (lastChange != null && (date == null || lastChange.after(date))) {
  159. date = lastChange;
  160. }
  161. }
  162. return date;
  163. }
  164. /**
  165. * Returns the path of the repositories folder. This method checks to see if
  166. * Gitblit is running on a cloud service and may return an adjusted path.
  167. *
  168. * @return the repositories folder path
  169. */
  170. @Override
  171. public File getRepositoriesFolder() {
  172. return repositoriesFolder;
  173. }
  174. /**
  175. * Returns the path of the Groovy folder. This method checks to see if
  176. * Gitblit is running on a cloud service and may return an adjusted path.
  177. *
  178. * @return the Groovy scripts folder path
  179. */
  180. @Override
  181. public File getHooksFolder() {
  182. return runtimeManager.getFileOrFolder(Keys.groovy.scriptsFolder, "${baseFolder}/groovy");
  183. }
  184. /**
  185. * Returns the path of the Groovy Grape folder. This method checks to see if
  186. * Gitblit is running on a cloud service and may return an adjusted path.
  187. *
  188. * @return the Groovy Grape folder path
  189. */
  190. @Override
  191. public File getGrapesFolder() {
  192. return runtimeManager.getFileOrFolder(Keys.groovy.grapeFolder, "${baseFolder}/groovy/grape");
  193. }
  194. /**
  195. *
  196. * @return true if we are running the gc executor
  197. */
  198. @Override
  199. public boolean isCollectingGarbage() {
  200. return gcExecutor != null && gcExecutor.isRunning();
  201. }
  202. /**
  203. * Returns true if Gitblit is actively collecting garbage in this repository.
  204. *
  205. * @param repositoryName
  206. * @return true if actively collecting garbage
  207. */
  208. @Override
  209. public boolean isCollectingGarbage(String repositoryName) {
  210. return gcExecutor != null && gcExecutor.isCollectingGarbage(repositoryName);
  211. }
  212. /**
  213. * Returns the effective list of permissions for this user, taking into account
  214. * team memberships, ownerships.
  215. *
  216. * @param user
  217. * @return the effective list of permissions for the user
  218. */
  219. @Override
  220. public List<RegistrantAccessPermission> getUserAccessPermissions(UserModel user) {
  221. if (StringUtils.isEmpty(user.username)) {
  222. // new user
  223. return new ArrayList<RegistrantAccessPermission>();
  224. }
  225. Set<RegistrantAccessPermission> set = new LinkedHashSet<RegistrantAccessPermission>();
  226. set.addAll(user.getRepositoryPermissions());
  227. // Flag missing repositories
  228. for (RegistrantAccessPermission permission : set) {
  229. if (permission.mutable && PermissionType.EXPLICIT.equals(permission.permissionType)) {
  230. RepositoryModel rm = getRepositoryModel(permission.registrant);
  231. if (rm == null) {
  232. permission.permissionType = PermissionType.MISSING;
  233. permission.mutable = false;
  234. continue;
  235. }
  236. }
  237. }
  238. // TODO reconsider ownership as a user property
  239. // manually specify personal repository ownerships
  240. for (RepositoryModel rm : repositoryListCache.values()) {
  241. if (rm.isUsersPersonalRepository(user.username) || rm.isOwner(user.username)) {
  242. RegistrantAccessPermission rp = new RegistrantAccessPermission(rm.name, AccessPermission.REWIND,
  243. PermissionType.OWNER, RegistrantType.REPOSITORY, null, false);
  244. // user may be owner of a repository to which they've inherited
  245. // a team permission, replace any existing perm with owner perm
  246. set.remove(rp);
  247. set.add(rp);
  248. }
  249. }
  250. List<RegistrantAccessPermission> list = new ArrayList<RegistrantAccessPermission>(set);
  251. Collections.sort(list);
  252. return list;
  253. }
  254. /**
  255. * Returns the list of users and their access permissions for the specified
  256. * repository including permission source information such as the team or
  257. * regular expression which sets the permission.
  258. *
  259. * @param repository
  260. * @return a list of RegistrantAccessPermissions
  261. */
  262. @Override
  263. public List<RegistrantAccessPermission> getUserAccessPermissions(RepositoryModel repository) {
  264. List<RegistrantAccessPermission> list = new ArrayList<RegistrantAccessPermission>();
  265. if (AccessRestrictionType.NONE.equals(repository.accessRestriction)) {
  266. // no permissions needed, REWIND for everyone!
  267. return list;
  268. }
  269. if (AuthorizationControl.AUTHENTICATED.equals(repository.authorizationControl)) {
  270. // no permissions needed, REWIND for authenticated!
  271. return list;
  272. }
  273. // NAMED users and teams
  274. for (UserModel user : userManager.getAllUsers()) {
  275. RegistrantAccessPermission ap = user.getRepositoryPermission(repository);
  276. if (ap.permission.exceeds(AccessPermission.NONE)) {
  277. list.add(ap);
  278. }
  279. }
  280. return list;
  281. }
  282. /**
  283. * Sets the access permissions to the specified repository for the specified users.
  284. *
  285. * @param repository
  286. * @param permissions
  287. * @return true if the user models have been updated
  288. */
  289. @Override
  290. public boolean setUserAccessPermissions(RepositoryModel repository, Collection<RegistrantAccessPermission> permissions) {
  291. List<UserModel> users = new ArrayList<UserModel>();
  292. for (RegistrantAccessPermission up : permissions) {
  293. if (up.mutable) {
  294. // only set editable defined permissions
  295. UserModel user = userManager.getUserModel(up.registrant);
  296. user.setRepositoryPermission(repository.name, up.permission);
  297. users.add(user);
  298. }
  299. }
  300. return userManager.updateUserModels(users);
  301. }
  302. /**
  303. * Returns the list of all users who have an explicit access permission
  304. * for the specified repository.
  305. *
  306. * @see IUserService.getUsernamesForRepositoryRole(String)
  307. * @param repository
  308. * @return list of all usernames that have an access permission for the repository
  309. */
  310. @Override
  311. public List<String> getRepositoryUsers(RepositoryModel repository) {
  312. return userManager.getUsernamesForRepositoryRole(repository.name);
  313. }
  314. /**
  315. * Returns the list of teams and their access permissions for the specified
  316. * repository including the source of the permission such as the admin flag
  317. * or a regular expression.
  318. *
  319. * @param repository
  320. * @return a list of RegistrantAccessPermissions
  321. */
  322. @Override
  323. public List<RegistrantAccessPermission> getTeamAccessPermissions(RepositoryModel repository) {
  324. List<RegistrantAccessPermission> list = new ArrayList<RegistrantAccessPermission>();
  325. for (TeamModel team : userManager.getAllTeams()) {
  326. RegistrantAccessPermission ap = team.getRepositoryPermission(repository);
  327. if (ap.permission.exceeds(AccessPermission.NONE)) {
  328. list.add(ap);
  329. }
  330. }
  331. Collections.sort(list);
  332. return list;
  333. }
  334. /**
  335. * Sets the access permissions to the specified repository for the specified teams.
  336. *
  337. * @param repository
  338. * @param permissions
  339. * @return true if the team models have been updated
  340. */
  341. @Override
  342. public boolean setTeamAccessPermissions(RepositoryModel repository, Collection<RegistrantAccessPermission> permissions) {
  343. List<TeamModel> teams = new ArrayList<TeamModel>();
  344. for (RegistrantAccessPermission tp : permissions) {
  345. if (tp.mutable) {
  346. // only set explicitly defined access permissions
  347. TeamModel team = userManager.getTeamModel(tp.registrant);
  348. team.setRepositoryPermission(repository.name, tp.permission);
  349. teams.add(team);
  350. }
  351. }
  352. return userManager.updateTeamModels(teams);
  353. }
  354. /**
  355. * Returns the list of all teams who have an explicit access permission for
  356. * the specified repository.
  357. *
  358. * @see IUserService.getTeamnamesForRepositoryRole(String)
  359. * @param repository
  360. * @return list of all teamnames with explicit access permissions to the repository
  361. */
  362. @Override
  363. public List<String> getRepositoryTeams(RepositoryModel repository) {
  364. return userManager.getTeamNamesForRepositoryRole(repository.name);
  365. }
  366. /**
  367. * Adds the repository to the list of cached repositories if Gitblit is
  368. * configured to cache the repository list.
  369. *
  370. * @param model
  371. */
  372. @Override
  373. public void addToCachedRepositoryList(RepositoryModel model) {
  374. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  375. repositoryListCache.put(model.name.toLowerCase(), model);
  376. // update the fork origin repository with this repository clone
  377. if (!StringUtils.isEmpty(model.originRepository)) {
  378. if (repositoryListCache.containsKey(model.originRepository)) {
  379. RepositoryModel origin = repositoryListCache.get(model.originRepository);
  380. origin.addFork(model.name);
  381. }
  382. }
  383. }
  384. }
  385. /**
  386. * Removes the repository from the list of cached repositories.
  387. *
  388. * @param name
  389. * @return the model being removed
  390. */
  391. private RepositoryModel removeFromCachedRepositoryList(String name) {
  392. if (StringUtils.isEmpty(name)) {
  393. return null;
  394. }
  395. return repositoryListCache.remove(name.toLowerCase());
  396. }
  397. /**
  398. * Clears all the cached metadata for the specified repository.
  399. *
  400. * @param repositoryName
  401. */
  402. private void clearRepositoryMetadataCache(String repositoryName) {
  403. repositorySizeCache.remove(repositoryName);
  404. repositoryMetricsCache.remove(repositoryName);
  405. }
  406. /**
  407. * Resets the repository list cache.
  408. *
  409. */
  410. @Override
  411. public void resetRepositoryListCache() {
  412. logger.info("Repository cache manually reset");
  413. repositoryListCache.clear();
  414. repositorySizeCache.clear();
  415. repositoryMetricsCache.clear();
  416. }
  417. /**
  418. * Calculate the checksum of settings that affect the repository list cache.
  419. * @return a checksum
  420. */
  421. private String getRepositoryListSettingsChecksum() {
  422. StringBuilder ns = new StringBuilder();
  423. ns.append(settings.getString(Keys.git.cacheRepositoryList, "")).append('\n');
  424. ns.append(settings.getString(Keys.git.onlyAccessBareRepositories, "")).append('\n');
  425. ns.append(settings.getString(Keys.git.searchRepositoriesSubfolders, "")).append('\n');
  426. ns.append(settings.getString(Keys.git.searchRecursionDepth, "")).append('\n');
  427. ns.append(settings.getString(Keys.git.searchExclusions, "")).append('\n');
  428. String checksum = StringUtils.getSHA1(ns.toString());
  429. return checksum;
  430. }
  431. /**
  432. * Compare the last repository list setting checksum to the current checksum.
  433. * If different then clear the cache so that it may be rebuilt.
  434. *
  435. * @return true if the cached repository list is valid since the last check
  436. */
  437. private boolean isValidRepositoryList() {
  438. String newChecksum = getRepositoryListSettingsChecksum();
  439. boolean valid = newChecksum.equals(repositoryListSettingsChecksum.get());
  440. repositoryListSettingsChecksum.set(newChecksum);
  441. if (!valid && settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  442. logger.info("Repository list settings have changed. Clearing repository list cache.");
  443. repositoryListCache.clear();
  444. }
  445. return valid;
  446. }
  447. /**
  448. * Returns the list of all repositories available to Gitblit. This method
  449. * does not consider user access permissions.
  450. *
  451. * @return list of all repositories
  452. */
  453. @Override
  454. public List<String> getRepositoryList() {
  455. if (repositoryListCache.size() == 0 || !isValidRepositoryList()) {
  456. // we are not caching OR we have not yet cached OR the cached list is invalid
  457. long startTime = System.currentTimeMillis();
  458. List<String> repositories = JGitUtils.getRepositoryList(repositoriesFolder,
  459. settings.getBoolean(Keys.git.onlyAccessBareRepositories, false),
  460. settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true),
  461. settings.getInteger(Keys.git.searchRecursionDepth, -1),
  462. settings.getStrings(Keys.git.searchExclusions));
  463. if (!settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  464. // we are not caching
  465. StringUtils.sortRepositorynames(repositories);
  466. return repositories;
  467. } else {
  468. // we are caching this list
  469. String msg = "{0} repositories identified in {1} msecs";
  470. if (settings.getBoolean(Keys.web.showRepositorySizes, true)) {
  471. // optionally (re)calculate repository sizes
  472. msg = "{0} repositories identified with calculated folder sizes in {1} msecs";
  473. }
  474. for (String repository : repositories) {
  475. getRepositoryModel(repository);
  476. }
  477. // rebuild fork networks
  478. for (RepositoryModel model : repositoryListCache.values()) {
  479. if (!StringUtils.isEmpty(model.originRepository)) {
  480. if (repositoryListCache.containsKey(model.originRepository)) {
  481. RepositoryModel origin = repositoryListCache.get(model.originRepository);
  482. origin.addFork(model.name);
  483. }
  484. }
  485. }
  486. long duration = System.currentTimeMillis() - startTime;
  487. logger.info(MessageFormat.format(msg, repositoryListCache.size(), duration));
  488. }
  489. }
  490. // return sorted copy of cached list
  491. List<String> list = new ArrayList<String>();
  492. for (RepositoryModel model : repositoryListCache.values()) {
  493. list.add(model.name);
  494. }
  495. StringUtils.sortRepositorynames(list);
  496. return list;
  497. }
  498. /**
  499. * Returns the JGit repository for the specified name.
  500. *
  501. * @param repositoryName
  502. * @return repository or null
  503. */
  504. @Override
  505. public Repository getRepository(String repositoryName) {
  506. return getRepository(repositoryName, true);
  507. }
  508. /**
  509. * Returns the JGit repository for the specified name.
  510. *
  511. * @param repositoryName
  512. * @param logError
  513. * @return repository or null
  514. */
  515. @Override
  516. public Repository getRepository(String repositoryName, boolean logError) {
  517. // Decode url-encoded repository name (issue-278)
  518. // http://stackoverflow.com/questions/17183110
  519. repositoryName = repositoryName.replace("%7E", "~").replace("%7e", "~");
  520. if (isCollectingGarbage(repositoryName)) {
  521. logger.warn(MessageFormat.format("Rejecting request for {0}, busy collecting garbage!", repositoryName));
  522. return null;
  523. }
  524. File dir = FileKey.resolve(new File(repositoriesFolder, repositoryName), FS.DETECTED);
  525. if (dir == null)
  526. return null;
  527. Repository r = null;
  528. try {
  529. FileKey key = FileKey.exact(dir, FS.DETECTED);
  530. r = RepositoryCache.open(key, true);
  531. } catch (IOException e) {
  532. if (logError) {
  533. logger.error("GitBlit.getRepository(String) failed to find "
  534. + new File(repositoriesFolder, repositoryName).getAbsolutePath());
  535. }
  536. }
  537. return r;
  538. }
  539. /**
  540. * Returns the list of repository models that are accessible to the user.
  541. *
  542. * @param user
  543. * @return list of repository models accessible to user
  544. */
  545. @Override
  546. public List<RepositoryModel> getRepositoryModels(UserModel user) {
  547. long methodStart = System.currentTimeMillis();
  548. List<String> list = getRepositoryList();
  549. List<RepositoryModel> repositories = new ArrayList<RepositoryModel>();
  550. for (String repo : list) {
  551. RepositoryModel model = getRepositoryModel(user, repo);
  552. if (model != null) {
  553. if (!model.hasCommits) {
  554. // only add empty repositories that user can push to
  555. if (UserModel.ANONYMOUS.canPush(model)
  556. || user != null && user.canPush(model)) {
  557. repositories.add(model);
  558. }
  559. } else {
  560. repositories.add(model);
  561. }
  562. }
  563. }
  564. long duration = System.currentTimeMillis() - methodStart;
  565. logger.info(MessageFormat.format("{0} repository models loaded for {1} in {2} msecs",
  566. repositories.size(), user == null ? "anonymous" : user.username, duration));
  567. return repositories;
  568. }
  569. /**
  570. * Returns a repository model if the repository exists and the user may
  571. * access the repository.
  572. *
  573. * @param user
  574. * @param repositoryName
  575. * @return repository model or null
  576. */
  577. @Override
  578. public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
  579. RepositoryModel model = getRepositoryModel(repositoryName);
  580. if (model == null) {
  581. return null;
  582. }
  583. if (user == null) {
  584. user = UserModel.ANONYMOUS;
  585. }
  586. if (user.canView(model)) {
  587. return model;
  588. }
  589. return null;
  590. }
  591. /**
  592. * Returns the repository model for the specified repository. This method
  593. * does not consider user access permissions.
  594. *
  595. * @param repositoryName
  596. * @return repository model or null
  597. */
  598. @Override
  599. public RepositoryModel getRepositoryModel(String repositoryName) {
  600. // Decode url-encoded repository name (issue-278)
  601. // http://stackoverflow.com/questions/17183110
  602. repositoryName = repositoryName.replace("%7E", "~").replace("%7e", "~");
  603. if (!repositoryListCache.containsKey(repositoryName)) {
  604. RepositoryModel model = loadRepositoryModel(repositoryName);
  605. if (model == null) {
  606. return null;
  607. }
  608. addToCachedRepositoryList(model);
  609. return DeepCopier.copy(model);
  610. }
  611. // cached model
  612. RepositoryModel model = repositoryListCache.get(repositoryName.toLowerCase());
  613. if (gcExecutor.isCollectingGarbage(model.name)) {
  614. // Gitblit is busy collecting garbage, use our cached model
  615. RepositoryModel rm = DeepCopier.copy(model);
  616. rm.isCollectingGarbage = true;
  617. return rm;
  618. }
  619. // check for updates
  620. Repository r = getRepository(model.name);
  621. if (r == null) {
  622. // repository is missing
  623. removeFromCachedRepositoryList(repositoryName);
  624. logger.error(MessageFormat.format("Repository \"{0}\" is missing! Removing from cache.", repositoryName));
  625. return null;
  626. }
  627. FileBasedConfig config = (FileBasedConfig) getRepositoryConfig(r);
  628. if (config.isOutdated()) {
  629. // reload model
  630. logger.debug(MessageFormat.format("Config for \"{0}\" has changed. Reloading model and updating cache.", repositoryName));
  631. model = loadRepositoryModel(model.name);
  632. removeFromCachedRepositoryList(model.name);
  633. addToCachedRepositoryList(model);
  634. } else {
  635. // update a few repository parameters
  636. if (!model.hasCommits) {
  637. // update hasCommits, assume a repository only gains commits :)
  638. model.hasCommits = JGitUtils.hasCommits(r);
  639. }
  640. updateLastChangeFields(r, model);
  641. }
  642. r.close();
  643. // return a copy of the cached model
  644. return DeepCopier.copy(model);
  645. }
  646. /**
  647. * Returns the star count of the repository.
  648. *
  649. * @param repository
  650. * @return the star count
  651. */
  652. @Override
  653. public long getStarCount(RepositoryModel repository) {
  654. long count = 0;
  655. for (UserModel user : userManager.getAllUsers()) {
  656. if (user.getPreferences().isStarredRepository(repository.name)) {
  657. count++;
  658. }
  659. }
  660. return count;
  661. }
  662. /**
  663. * Workaround JGit. I need to access the raw config object directly in order
  664. * to see if the config is dirty so that I can reload a repository model.
  665. * If I use the stock JGit method to get the config it already reloads the
  666. * config. If the config changes are made within Gitblit this is fine as
  667. * the returned config will still be flagged as dirty. BUT... if the config
  668. * is manipulated outside Gitblit then it fails to recognize this as dirty.
  669. *
  670. * @param r
  671. * @return a config
  672. */
  673. private StoredConfig getRepositoryConfig(Repository r) {
  674. try {
  675. Field f = r.getClass().getDeclaredField("repoConfig");
  676. f.setAccessible(true);
  677. StoredConfig config = (StoredConfig) f.get(r);
  678. return config;
  679. } catch (Exception e) {
  680. logger.error("Failed to retrieve \"repoConfig\" via reflection", e);
  681. }
  682. return r.getConfig();
  683. }
  684. /**
  685. * Create a repository model from the configuration and repository data.
  686. *
  687. * @param repositoryName
  688. * @return a repositoryModel or null if the repository does not exist
  689. */
  690. private RepositoryModel loadRepositoryModel(String repositoryName) {
  691. Repository r = getRepository(repositoryName);
  692. if (r == null) {
  693. return null;
  694. }
  695. RepositoryModel model = new RepositoryModel();
  696. model.isBare = r.isBare();
  697. File basePath = getRepositoriesFolder();
  698. if (model.isBare) {
  699. model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory());
  700. } else {
  701. model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory().getParentFile());
  702. }
  703. if (StringUtils.isEmpty(model.name)) {
  704. // Repository is NOT located relative to the base folder because it
  705. // is symlinked. Use the provided repository name.
  706. model.name = repositoryName;
  707. }
  708. model.projectPath = StringUtils.getFirstPathElement(repositoryName);
  709. StoredConfig config = r.getConfig();
  710. boolean hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));
  711. if (config != null) {
  712. // Initialize description from description file
  713. if (getConfig(config,"description", null) == null) {
  714. File descFile = new File(r.getDirectory(), "description");
  715. if (descFile.exists()) {
  716. String desc = com.gitblit.utils.FileUtils.readContent(descFile, System.getProperty("line.separator"));
  717. if (!desc.toLowerCase().startsWith("unnamed repository")) {
  718. config.setString(Constants.CONFIG_GITBLIT, null, "description", desc);
  719. }
  720. }
  721. }
  722. model.description = getConfig(config, "description", "");
  723. model.originRepository = getConfig(config, "originRepository", null);
  724. model.addOwners(ArrayUtils.fromString(getConfig(config, "owner", "")));
  725. model.useIncrementalPushTags = getConfig(config, "useIncrementalPushTags", false);
  726. model.incrementalPushTagPrefix = getConfig(config, "incrementalPushTagPrefix", null);
  727. model.allowForks = getConfig(config, "allowForks", true);
  728. model.accessRestriction = AccessRestrictionType.fromName(getConfig(config,
  729. "accessRestriction", settings.getString(Keys.git.defaultAccessRestriction, "PUSH")));
  730. model.authorizationControl = AuthorizationControl.fromName(getConfig(config,
  731. "authorizationControl", settings.getString(Keys.git.defaultAuthorizationControl, null)));
  732. model.verifyCommitter = getConfig(config, "verifyCommitter", false);
  733. model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
  734. model.isFrozen = getConfig(config, "isFrozen", false);
  735. model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
  736. model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
  737. model.commitMessageRenderer = CommitMessageRenderer.fromName(getConfig(config, "commitMessageRenderer",
  738. settings.getString(Keys.web.commitMessageRenderer, null)));
  739. model.federationStrategy = FederationStrategy.fromName(getConfig(config,
  740. "federationStrategy", null));
  741. model.federationSets = new ArrayList<String>(Arrays.asList(config.getStringList(
  742. Constants.CONFIG_GITBLIT, null, "federationSets")));
  743. model.isFederated = getConfig(config, "isFederated", false);
  744. model.gcThreshold = getConfig(config, "gcThreshold", settings.getString(Keys.git.defaultGarbageCollectionThreshold, "500KB"));
  745. model.gcPeriod = getConfig(config, "gcPeriod", settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7));
  746. try {
  747. model.lastGC = new SimpleDateFormat(Constants.ISO8601).parse(getConfig(config, "lastGC", "1970-01-01'T'00:00:00Z"));
  748. } catch (Exception e) {
  749. model.lastGC = new Date(0);
  750. }
  751. model.maxActivityCommits = getConfig(config, "maxActivityCommits", settings.getInteger(Keys.web.maxActivityCommits, 0));
  752. model.origin = config.getString("remote", "origin", "url");
  753. if (model.origin != null) {
  754. model.origin = model.origin.replace('\\', '/');
  755. model.isMirror = config.getBoolean("remote", "origin", "mirror", false);
  756. }
  757. model.preReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
  758. Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
  759. model.postReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
  760. Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
  761. model.mailingLists = new ArrayList<String>(Arrays.asList(config.getStringList(
  762. Constants.CONFIG_GITBLIT, null, "mailingList")));
  763. model.indexedBranches = new ArrayList<String>(Arrays.asList(config.getStringList(
  764. Constants.CONFIG_GITBLIT, null, "indexBranch")));
  765. model.metricAuthorExclusions = new ArrayList<String>(Arrays.asList(config.getStringList(
  766. Constants.CONFIG_GITBLIT, null, "metricAuthorExclusions")));
  767. // Custom defined properties
  768. model.customFields = new LinkedHashMap<String, String>();
  769. for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
  770. model.customFields.put(aProperty, config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
  771. }
  772. }
  773. model.HEAD = JGitUtils.getHEADRef(r);
  774. model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
  775. model.sparkleshareId = JGitUtils.getSparkleshareId(r);
  776. model.hasCommits = JGitUtils.hasCommits(r);
  777. updateLastChangeFields(r, model);
  778. r.close();
  779. if (StringUtils.isEmpty(model.originRepository) && model.origin != null && model.origin.startsWith("file://")) {
  780. // repository was cloned locally... perhaps as a fork
  781. try {
  782. File folder = new File(new URI(model.origin));
  783. String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
  784. if (!StringUtils.isEmpty(originRepo)) {
  785. // ensure origin still exists
  786. File repoFolder = new File(getRepositoriesFolder(), originRepo);
  787. if (repoFolder.exists()) {
  788. model.originRepository = originRepo.toLowerCase();
  789. // persist the fork origin
  790. updateConfiguration(r, model);
  791. }
  792. }
  793. } catch (URISyntaxException e) {
  794. logger.error("Failed to determine fork for " + model, e);
  795. }
  796. }
  797. return model;
  798. }
  799. /**
  800. * Determines if this server has the requested repository.
  801. *
  802. * @param n
  803. * @return true if the repository exists
  804. */
  805. @Override
  806. public boolean hasRepository(String repositoryName) {
  807. return hasRepository(repositoryName, false);
  808. }
  809. /**
  810. * Determines if this server has the requested repository.
  811. *
  812. * @param n
  813. * @param caseInsensitive
  814. * @return true if the repository exists
  815. */
  816. @Override
  817. public boolean hasRepository(String repositoryName, boolean caseSensitiveCheck) {
  818. if (!caseSensitiveCheck && settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  819. // if we are caching use the cache to determine availability
  820. // otherwise we end up adding a phantom repository to the cache
  821. return repositoryListCache.containsKey(repositoryName.toLowerCase());
  822. }
  823. Repository r = getRepository(repositoryName, false);
  824. if (r == null) {
  825. return false;
  826. }
  827. r.close();
  828. return true;
  829. }
  830. /**
  831. * Determines if the specified user has a fork of the specified origin
  832. * repository.
  833. *
  834. * @param username
  835. * @param origin
  836. * @return true the if the user has a fork
  837. */
  838. @Override
  839. public boolean hasFork(String username, String origin) {
  840. return getFork(username, origin) != null;
  841. }
  842. /**
  843. * Gets the name of a user's fork of the specified origin
  844. * repository.
  845. *
  846. * @param username
  847. * @param origin
  848. * @return the name of the user's fork, null otherwise
  849. */
  850. @Override
  851. public String getFork(String username, String origin) {
  852. String userProject = ModelUtils.getPersonalPath(username);
  853. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  854. String userPath = userProject + "/";
  855. // collect all origin nodes in fork network
  856. Set<String> roots = new HashSet<String>();
  857. roots.add(origin);
  858. RepositoryModel originModel = repositoryListCache.get(origin);
  859. while (originModel != null) {
  860. if (!ArrayUtils.isEmpty(originModel.forks)) {
  861. for (String fork : originModel.forks) {
  862. if (!fork.startsWith(userPath)) {
  863. roots.add(fork);
  864. }
  865. }
  866. }
  867. if (originModel.originRepository != null) {
  868. roots.add(originModel.originRepository);
  869. originModel = repositoryListCache.get(originModel.originRepository);
  870. } else {
  871. // break
  872. originModel = null;
  873. }
  874. }
  875. for (String repository : repositoryListCache.keySet()) {
  876. if (repository.startsWith(userPath)) {
  877. RepositoryModel model = repositoryListCache.get(repository);
  878. if (!StringUtils.isEmpty(model.originRepository)) {
  879. if (roots.contains(model.originRepository)) {
  880. // user has a fork in this graph
  881. return model.name;
  882. }
  883. }
  884. }
  885. }
  886. } else {
  887. // not caching
  888. File subfolder = new File(getRepositoriesFolder(), userProject);
  889. List<String> repositories = JGitUtils.getRepositoryList(subfolder,
  890. settings.getBoolean(Keys.git.onlyAccessBareRepositories, false),
  891. settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true),
  892. settings.getInteger(Keys.git.searchRecursionDepth, -1),
  893. settings.getStrings(Keys.git.searchExclusions));
  894. for (String repository : repositories) {
  895. RepositoryModel model = getRepositoryModel(userProject + "/" + repository);
  896. if (model.originRepository.equalsIgnoreCase(origin)) {
  897. // user has a fork
  898. return model.name;
  899. }
  900. }
  901. }
  902. // user does not have a fork
  903. return null;
  904. }
  905. /**
  906. * Returns the fork network for a repository by traversing up the fork graph
  907. * to discover the root and then down through all children of the root node.
  908. *
  909. * @param repository
  910. * @return a ForkModel
  911. */
  912. @Override
  913. public ForkModel getForkNetwork(String repository) {
  914. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  915. // find the root, cached
  916. RepositoryModel model = repositoryListCache.get(repository.toLowerCase());
  917. while (model.originRepository != null) {
  918. model = repositoryListCache.get(model.originRepository);
  919. }
  920. ForkModel root = getForkModelFromCache(model.name);
  921. return root;
  922. } else {
  923. // find the root, non-cached
  924. RepositoryModel model = getRepositoryModel(repository.toLowerCase());
  925. while (model.originRepository != null) {
  926. model = getRepositoryModel(model.originRepository);
  927. }
  928. ForkModel root = getForkModel(model.name);
  929. return root;
  930. }
  931. }
  932. private ForkModel getForkModelFromCache(String repository) {
  933. RepositoryModel model = repositoryListCache.get(repository.toLowerCase());
  934. if (model == null) {
  935. return null;
  936. }
  937. ForkModel fork = new ForkModel(model);
  938. if (!ArrayUtils.isEmpty(model.forks)) {
  939. for (String aFork : model.forks) {
  940. ForkModel fm = getForkModelFromCache(aFork);
  941. if (fm != null) {
  942. fork.forks.add(fm);
  943. }
  944. }
  945. }
  946. return fork;
  947. }
  948. private ForkModel getForkModel(String repository) {
  949. RepositoryModel model = getRepositoryModel(repository.toLowerCase());
  950. if (model == null) {
  951. return null;
  952. }
  953. ForkModel fork = new ForkModel(model);
  954. if (!ArrayUtils.isEmpty(model.forks)) {
  955. for (String aFork : model.forks) {
  956. ForkModel fm = getForkModel(aFork);
  957. if (fm != null) {
  958. fork.forks.add(fm);
  959. }
  960. }
  961. }
  962. return fork;
  963. }
  964. /**
  965. * Updates the last changed fields and optionally calculates the size of the
  966. * repository. Gitblit caches the repository sizes to reduce the performance
  967. * penalty of recursive calculation. The cache is updated if the repository
  968. * has been changed since the last calculation.
  969. *
  970. * @param model
  971. * @return size in bytes of the repository
  972. */
  973. @Override
  974. public long updateLastChangeFields(Repository r, RepositoryModel model) {
  975. LastChange lc = JGitUtils.getLastChange(r);
  976. model.lastChange = lc.when;
  977. model.lastChangeAuthor = lc.who;
  978. if (!settings.getBoolean(Keys.web.showRepositorySizes, true) || model.skipSizeCalculation) {
  979. model.size = null;
  980. return 0L;
  981. }
  982. if (!repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
  983. File gitDir = r.getDirectory();
  984. long sz = com.gitblit.utils.FileUtils.folderSize(gitDir);
  985. repositorySizeCache.updateObject(model.name, model.lastChange, sz);
  986. }
  987. long size = repositorySizeCache.getObject(model.name);
  988. ByteFormat byteFormat = new ByteFormat();
  989. model.size = byteFormat.format(size);
  990. return size;
  991. }
  992. /**
  993. * Ensure that a cached repository is completely closed and its resources
  994. * are properly released.
  995. *
  996. * @param repositoryName
  997. */
  998. private void closeRepository(String repositoryName) {
  999. Repository repository = getRepository(repositoryName);
  1000. if (repository == null) {
  1001. return;
  1002. }
  1003. RepositoryCache.close(repository);
  1004. // assume 2 uses in case reflection fails
  1005. int uses = 2;
  1006. try {
  1007. // The FileResolver caches repositories which is very useful
  1008. // for performance until you want to delete a repository.
  1009. // I have to use reflection to call close() the correct
  1010. // number of times to ensure that the object and ref databases
  1011. // are properly closed before I can delete the repository from
  1012. // the filesystem.
  1013. Field useCnt = Repository.class.getDeclaredField("useCnt");
  1014. useCnt.setAccessible(true);
  1015. uses = ((AtomicInteger) useCnt.get(repository)).get();
  1016. } catch (Exception e) {
  1017. logger.warn(MessageFormat
  1018. .format("Failed to reflectively determine use count for repository {0}",
  1019. repositoryName), e);
  1020. }
  1021. if (uses > 0) {
  1022. logger.info(MessageFormat
  1023. .format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases",
  1024. repositoryName, uses, uses));
  1025. for (int i = 0; i < uses; i++) {
  1026. repository.close();
  1027. }
  1028. }
  1029. // close any open index writer/searcher in the Lucene executor
  1030. luceneExecutor.close(repositoryName);
  1031. }
  1032. /**
  1033. * Returns the metrics for the default branch of the specified repository.
  1034. * This method builds a metrics cache. The cache is updated if the
  1035. * repository is updated. A new copy of the metrics list is returned on each
  1036. * call so that modifications to the list are non-destructive.
  1037. *
  1038. * @param model
  1039. * @param repository
  1040. * @return a new array list of metrics
  1041. */
  1042. @Override
  1043. public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
  1044. if (repositoryMetricsCache.hasCurrent(model.name, model.lastChange)) {
  1045. return new ArrayList<Metric>(repositoryMetricsCache.getObject(model.name));
  1046. }
  1047. List<Metric> metrics = MetricUtils.getDateMetrics(repository, null, true, null, runtimeManager.getTimezone());
  1048. repositoryMetricsCache.updateObject(model.name, model.lastChange, metrics);
  1049. return new ArrayList<Metric>(metrics);
  1050. }
  1051. /**
  1052. * Returns the gitblit string value for the specified key. If key is not
  1053. * set, returns defaultValue.
  1054. *
  1055. * @param config
  1056. * @param field
  1057. * @param defaultValue
  1058. * @return field value or defaultValue
  1059. */
  1060. private String getConfig(StoredConfig config, String field, String defaultValue) {
  1061. String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
  1062. if (StringUtils.isEmpty(value)) {
  1063. return defaultValue;
  1064. }
  1065. return value;
  1066. }
  1067. /**
  1068. * Returns the gitblit boolean value for the specified key. If key is not
  1069. * set, returns defaultValue.
  1070. *
  1071. * @param config
  1072. * @param field
  1073. * @param defaultValue
  1074. * @return field value or defaultValue
  1075. */
  1076. private boolean getConfig(StoredConfig config, String field, boolean defaultValue) {
  1077. return config.getBoolean(Constants.CONFIG_GITBLIT, field, defaultValue);
  1078. }
  1079. /**
  1080. * Returns the gitblit string value for the specified key. If key is not
  1081. * set, returns defaultValue.
  1082. *
  1083. * @param config
  1084. * @param field
  1085. * @param defaultValue
  1086. * @return field value or defaultValue
  1087. */
  1088. private int getConfig(StoredConfig config, String field, int defaultValue) {
  1089. String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
  1090. if (StringUtils.isEmpty(value)) {
  1091. return defaultValue;
  1092. }
  1093. try {
  1094. return Integer.parseInt(value);
  1095. } catch (Exception e) {
  1096. }
  1097. return defaultValue;
  1098. }
  1099. /**
  1100. * Creates/updates the repository model keyed by reopsitoryName. Saves all
  1101. * repository settings in .git/config. This method allows for renaming
  1102. * repositories and will update user access permissions accordingly.
  1103. *
  1104. * All repositories created by this method are bare and automatically have
  1105. * .git appended to their names, which is the standard convention for bare
  1106. * repositories.
  1107. *
  1108. * @param repositoryName
  1109. * @param repository
  1110. * @param isCreate
  1111. * @throws GitBlitException
  1112. */
  1113. @Override
  1114. public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
  1115. boolean isCreate) throws GitBlitException {
  1116. if (gcExecutor.isCollectingGarbage(repositoryName)) {
  1117. throw new GitBlitException(MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}",
  1118. repositoryName));
  1119. }
  1120. Repository r = null;
  1121. String projectPath = StringUtils.getFirstPathElement(repository.name);
  1122. if (!StringUtils.isEmpty(projectPath)) {
  1123. if (projectPath.equalsIgnoreCase(settings.getString(Keys.web.repositoryRootGroupName, "main"))) {
  1124. // strip leading group name
  1125. repository.name = repository.name.substring(projectPath.length() + 1);
  1126. }
  1127. }
  1128. if (isCreate) {
  1129. // ensure created repository name ends with .git
  1130. if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
  1131. repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
  1132. }
  1133. if (hasRepository(repository.name)) {
  1134. throw new GitBlitException(MessageFormat.format(
  1135. "Can not create repository ''{0}'' because it already exists.",
  1136. repository.name));
  1137. }
  1138. // create repository
  1139. logger.info("create repository " + repository.name);
  1140. String shared = settings.getString(Keys.git.createRepositoriesShared, "FALSE");
  1141. r = JGitUtils.createRepository(repositoriesFolder, repository.name, shared);
  1142. } else {
  1143. // rename repository
  1144. if (!repositoryName.equalsIgnoreCase(repository.name)) {
  1145. if (!repository.name.toLowerCase().endsWith(
  1146. org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
  1147. repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
  1148. }
  1149. if (new File(repositoriesFolder, repository.name).exists()) {
  1150. throw new GitBlitException(MessageFormat.format(
  1151. "Failed to rename ''{0}'' because ''{1}'' already exists.",
  1152. repositoryName, repository.name));
  1153. }
  1154. closeRepository(repositoryName);
  1155. File folder = new File(repositoriesFolder, repositoryName);
  1156. File destFolder = new File(repositoriesFolder, repository.name);
  1157. if (destFolder.exists()) {
  1158. throw new GitBlitException(
  1159. MessageFormat
  1160. .format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
  1161. repositoryName, repository.name));
  1162. }
  1163. File parentFile = destFolder.getParentFile();
  1164. if (!parentFile.exists() && !parentFile.mkdirs()) {
  1165. throw new GitBlitException(MessageFormat.format(
  1166. "Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
  1167. }
  1168. if (!folder.renameTo(destFolder)) {
  1169. throw new GitBlitException(MessageFormat.format(
  1170. "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
  1171. repository.name));
  1172. }
  1173. // rename the roles
  1174. if (!userManager.renameRepositoryRole(repositoryName, repository.name)) {
  1175. throw new GitBlitException(MessageFormat.format(
  1176. "Failed to rename repository permissions ''{0}'' to ''{1}''.",
  1177. repositoryName, repository.name));
  1178. }
  1179. // rename fork origins in their configs
  1180. if (!ArrayUtils.isEmpty(repository.forks)) {
  1181. for (String fork : repository.forks) {
  1182. Repository rf = getRepository(fork);
  1183. try {
  1184. StoredConfig config = rf.getConfig();
  1185. String origin = config.getString("remote", "origin", "url");
  1186. origin = origin.replace(repositoryName, repository.name);
  1187. config.setString("remote", "origin", "url", origin);
  1188. config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.name);
  1189. config.save();
  1190. } catch (Exception e) {
  1191. logger.error("Failed to update repository fork config for " + fork, e);
  1192. }
  1193. rf.close();
  1194. }
  1195. }
  1196. // update this repository's origin's fork list
  1197. if (!StringUtils.isEmpty(repository.originRepository)) {
  1198. RepositoryModel origin = repositoryListCache.get(repository.originRepository);
  1199. if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
  1200. origin.forks.remove(repositoryName);
  1201. origin.forks.add(repository.name);
  1202. }
  1203. }
  1204. // clear the cache
  1205. clearRepositoryMetadataCache(repositoryName);
  1206. repository.resetDisplayName();
  1207. }
  1208. // load repository
  1209. logger.info("edit repository " + repository.name);
  1210. r = getRepository(repository.name);
  1211. }
  1212. // update settings
  1213. if (r != null) {
  1214. updateConfiguration(r, repository);
  1215. // Update the description file
  1216. File descFile = new File(r.getDirectory(), "description");
  1217. if (repository.description != null)
  1218. {
  1219. com.gitblit.utils.FileUtils.writeContent(descFile, repository.description);
  1220. }
  1221. else if (descFile.exists() && !descFile.isDirectory()) {
  1222. descFile.delete();
  1223. }
  1224. // only update symbolic head if it changes
  1225. String currentRef = JGitUtils.getHEADRef(r);
  1226. if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
  1227. logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}",
  1228. repository.name, currentRef, repository.HEAD));
  1229. if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
  1230. // clear the cache
  1231. clearRepositoryMetadataCache(repository.name);
  1232. }
  1233. }
  1234. // Adjust permissions in case we updated the config files
  1235. JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "config"),
  1236. settings.getString(Keys.git.createRepositoriesShared, "FALSE"));
  1237. JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "HEAD"),
  1238. settings.getString(Keys.git.createRepositoriesShared, "FALSE"));
  1239. // close the repository object
  1240. r.close();
  1241. }
  1242. // update repository cache
  1243. removeFromCachedRepositoryList(repositoryName);
  1244. // model will actually be replaced on next load because config is stale
  1245. addToCachedRepositoryList(repository);
  1246. }
  1247. /**
  1248. * Updates the Gitblit configuration for the specified repository.
  1249. *
  1250. * @param r
  1251. * the Git repository
  1252. * @param repository
  1253. * the Gitblit repository model
  1254. */
  1255. @Override
  1256. public void updateConfiguration(Repository r, RepositoryModel repository) {
  1257. StoredConfig config = r.getConfig();
  1258. config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
  1259. config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.originRepository);
  1260. config.setString(Constants.CONFIG_GITBLIT, null, "owner", ArrayUtils.toString(repository.owners));
  1261. config.setBoolean(Constants.CONFIG_GITBLIT, null, "useIncrementalPushTags", repository.useIncrementalPushTags);
  1262. if (StringUtils.isEmpty(repository.incrementalPushTagPrefix) ||
  1263. repository.incrementalPushTagPrefix.equals(settings.getString(Keys.git.defaultIncrementalPushTagPrefix, "r"))) {
  1264. config.unset(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix");
  1265. } else {
  1266. config.setString(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix", repository.incrementalPushTagPrefix);
  1267. }
  1268. config.setBoolean(Constants.CONFIG_GITBLIT, null, "allowForks", repository.allowForks);
  1269. config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
  1270. config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl", repository.authorizationControl.name());
  1271. config.setBoolean(Constants.CONFIG_GITBLIT, null, "verifyCommitter", repository.verifyCommitter);
  1272. config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
  1273. config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
  1274. config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
  1275. config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
  1276. config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
  1277. repository.federationStrategy.name());
  1278. config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);
  1279. config.setString(Constants.CONFIG_GITBLIT, null, "gcThreshold", repository.gcThreshold);
  1280. if (repository.gcPeriod == settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7)) {
  1281. // use default from config
  1282. config.unset(Constants.CONFIG_GITBLIT, null, "gcPeriod");
  1283. } else {
  1284. config.setInt(Constants.CONFIG_GITBLIT, null, "gcPeriod", repository.gcPeriod);
  1285. }
  1286. if (repository.lastGC != null) {
  1287. config.setString(Constants.CONFIG_GITBLIT, null, "lastGC", new SimpleDateFormat(Constants.ISO8601).format(repository.lastGC));
  1288. }
  1289. if (repository.maxActivityCommits == settings.getInteger(Keys.web.maxActivityCommits, 0)) {
  1290. // use default from config
  1291. config.unset(Constants.CONFIG_GITBLIT, null, "maxActivityCommits");
  1292. } else {
  1293. config.setInt(Constants.CONFIG_GITBLIT, null, "maxActivityCommits", repository.maxActivityCommits);
  1294. }
  1295. CommitMessageRenderer defaultRenderer = CommitMessageRenderer.fromName(settings.getString(Keys.web.commitMessageRenderer, null));
  1296. if (repository.commitMessageRenderer == null || repository.commitMessageRenderer == defaultRenderer) {
  1297. // use default from config
  1298. config.unset(Constants.CONFIG_GITBLIT, null, "commitMessageRenderer");
  1299. } else {
  1300. // repository overrides default
  1301. config.setString(Constants.CONFIG_GITBLIT, null, "commitMessageRenderer",
  1302. repository.commitMessageRenderer.name());
  1303. }
  1304. updateList(config, "federationSets", repository.federationSets);
  1305. updateList(config, "preReceiveScript", repository.preReceiveScripts);
  1306. updateList(config, "postReceiveScript", repository.postReceiveScripts);
  1307. updateList(config, "mailingList", repository.mailingLists);
  1308. updateList(config, "indexBranch", repository.indexedBranches);
  1309. updateList(config, "metricAuthorExclusions", repository.metricAuthorExclusions);
  1310. // User Defined Properties
  1311. if (repository.customFields != null) {
  1312. if (repository.customFields.size() == 0) {
  1313. // clear section
  1314. config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
  1315. } else {
  1316. for (Entry<String, String> property : repository.customFields.entrySet()) {
  1317. // set field
  1318. String key = property.getKey();
  1319. String value = property.getValue();
  1320. config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
  1321. }
  1322. }
  1323. }
  1324. try {
  1325. config.save();
  1326. } catch (IOException e) {
  1327. logger.error("Failed to save repository config!", e);
  1328. }
  1329. }
  1330. private void updateList(StoredConfig config, String field, List<String> list) {
  1331. // a null list is skipped, not cleared
  1332. // this is for RPC administration where an older manager might be used
  1333. if (list == null) {
  1334. return;
  1335. }
  1336. if (ArrayUtils.isEmpty(list)) {
  1337. config.unset(Constants.CONFIG_GITBLIT, null, field);
  1338. } else {
  1339. config.setStringList(Constants.CONFIG_GITBLIT, null, field, list);
  1340. }
  1341. }
  1342. /**
  1343. * Deletes the repository from the file system and removes the repository
  1344. * permission from all repository users.
  1345. *
  1346. * @param model
  1347. * @return true if successful
  1348. */
  1349. @Override
  1350. public boolean deleteRepositoryModel(RepositoryModel model) {
  1351. return deleteRepository(model.name);
  1352. }
  1353. /**
  1354. * Deletes the repository from the file system and removes the repository
  1355. * permission from all repository users.
  1356. *
  1357. * @param repositoryName
  1358. * @return true if successful
  1359. */
  1360. @Override
  1361. public boolean deleteRepository(String repositoryName) {
  1362. try {
  1363. closeRepository(repositoryName);
  1364. // clear the repository cache
  1365. clearRepositoryMetadataCache(repositoryName);
  1366. RepositoryModel model = removeFromCachedRepositoryList(repositoryName);
  1367. if (model != null && !ArrayUtils.isEmpty(model.forks)) {
  1368. resetRepositoryListCache();
  1369. }
  1370. File folder = new File(repositoriesFolder, repositoryName);
  1371. if (folder.exists() && folder.isDirectory()) {
  1372. FileUtils.delete(folder, FileUtils.RECURSIVE | FileUtils.RETRY);
  1373. if (userManager.deleteRepositoryRole(repositoryName)) {
  1374. logger.info(MessageFormat.format("Repository \"{0}\" deleted", repositoryName));
  1375. return true;
  1376. }
  1377. }
  1378. } catch (Throwable t) {
  1379. logger.error(MessageFormat.format("Failed to delete repository {0}", repositoryName), t);
  1380. }
  1381. return false;
  1382. }
  1383. /**
  1384. * Returns the list of all Groovy push hook scripts. Script files must have
  1385. * .groovy extension
  1386. *
  1387. * @return list of available hook scripts
  1388. */
  1389. @Override
  1390. public List<String> getAllScripts() {
  1391. File groovyFolder = getHooksFolder();
  1392. File[] files = groovyFolder.listFiles(new FileFilter() {
  1393. @Override
  1394. public boolean accept(File pathname) {
  1395. return pathname.isFile() && pathname.getName().endsWith(".groovy");
  1396. }
  1397. });
  1398. List<String> scripts = new ArrayList<String>();
  1399. if (files != null) {
  1400. for (File file : files) {
  1401. String script = file.getName().substring(0, file.getName().lastIndexOf('.'));
  1402. scripts.add(script);
  1403. }
  1404. }
  1405. return scripts;
  1406. }
  1407. /**
  1408. * Returns the list of pre-receive scripts the repository inherited from the
  1409. * global settings and team affiliations.
  1410. *
  1411. * @param repository
  1412. * if null only the globally specified scripts are returned
  1413. * @return a list of scripts
  1414. */
  1415. @Override
  1416. public List<String> getPreReceiveScriptsInherited(RepositoryModel repository) {
  1417. Set<String> scripts = new LinkedHashSet<String>();
  1418. // Globals
  1419. for (String script : settings.getStrings(Keys.groovy.preReceiveScripts)) {
  1420. if (script.endsWith(".groovy")) {
  1421. scripts.add(script.substring(0, script.lastIndexOf('.')));
  1422. } else {
  1423. scripts.add(script);
  1424. }
  1425. }
  1426. // Team Scripts
  1427. if (repository != null) {
  1428. for (String teamname : userManager.getTeamNamesForRepositoryRole(repository.name)) {
  1429. TeamModel team = userManager.getTeamModel(teamname);
  1430. if (!ArrayUtils.isEmpty(team.preReceiveScripts)) {
  1431. scripts.addAll(team.preReceiveScripts);
  1432. }
  1433. }
  1434. }
  1435. return new ArrayList<String>(scripts);
  1436. }
  1437. /**
  1438. * Returns the list of all available Groovy pre-receive push hook scripts
  1439. * that are not already inherited by the repository. Script files must have
  1440. * .groovy extension
  1441. *
  1442. * @param repository
  1443. * optional parameter
  1444. * @return list of available hook scripts
  1445. */
  1446. @Override
  1447. public List<String> getPreReceiveScriptsUnused(RepositoryModel repository) {
  1448. Set<String> inherited = new TreeSet<String>(getPreReceiveScriptsInherited(repository));
  1449. // create list of available scripts by excluding inherited scripts
  1450. List<String> scripts = new ArrayList<String>();
  1451. for (String script : getAllScripts()) {
  1452. if (!inherited.contains(script)) {
  1453. scripts.add(script);
  1454. }
  1455. }
  1456. return scripts;
  1457. }
  1458. /**
  1459. * Returns the list of post-receive scripts the repository inherited from
  1460. * the global settings and team affiliations.
  1461. *
  1462. * @param repository
  1463. * if null only the globally specified scripts are returned
  1464. * @return a list of scripts
  1465. */
  1466. @Override
  1467. public List<String> getPostReceiveScriptsInherited(RepositoryModel repository) {
  1468. Set<String> scripts = new LinkedHashSet<String>();
  1469. // Global Scripts
  1470. for (String script : settings.getStrings(Keys.groovy.postReceiveScripts)) {
  1471. if (script.endsWith(".groovy")) {
  1472. scripts.add(script.substring(0, script.lastIndexOf('.')));
  1473. } else {
  1474. scripts.add(script);
  1475. }
  1476. }
  1477. // Team Scripts
  1478. if (repository != null) {
  1479. for (String teamname : userManager.getTeamNamesForRepositoryRole(repository.name)) {
  1480. TeamModel team = userManager.getTeamModel(teamname);
  1481. if (!ArrayUtils.isEmpty(team.postReceiveScripts)) {
  1482. scripts.addAll(team.postReceiveScripts);
  1483. }
  1484. }
  1485. }
  1486. return new ArrayList<String>(scripts);
  1487. }
  1488. /**
  1489. * Returns the list of unused Groovy post-receive push hook scripts that are
  1490. * not already inherited by the repository. Script files must have .groovy
  1491. * extension
  1492. *
  1493. * @param repository
  1494. * optional parameter
  1495. * @return list of available hook scripts
  1496. */
  1497. @Override
  1498. public List<String> getPostReceiveScriptsUnused(RepositoryModel repository) {
  1499. Set<String> inherited = new TreeSet<String>(getPostReceiveScriptsInherited(repository));
  1500. // create list of available scripts by excluding inherited scripts
  1501. List<String> scripts = new ArrayList<String>();
  1502. for (String script : getAllScripts()) {
  1503. if (!inherited.contains(script)) {
  1504. scripts.add(script);
  1505. }
  1506. }
  1507. return scripts;
  1508. }
  1509. /**
  1510. * Search the specified repositories using the Lucene query.
  1511. *
  1512. * @param query
  1513. * @param page
  1514. * @param pageSize
  1515. * @param repositories
  1516. * @return
  1517. */
  1518. @Override
  1519. public List<SearchResult> search(String query, int page, int pageSize, List<String> repositories) {
  1520. List<SearchResult> srs = luceneExecutor.search(query, page, pageSize, repositories);
  1521. return srs;
  1522. }
  1523. protected void configureLuceneIndexing() {
  1524. luceneExecutor = new LuceneService(settings, this);
  1525. int period = 2;
  1526. scheduledExecutor.scheduleAtFixedRate(luceneExecutor, 1, period, TimeUnit.MINUTES);
  1527. logger.info("Lucene will process indexed branches every {} minutes.", period);
  1528. }
  1529. protected void configureGarbageCollector() {
  1530. // schedule gc engine
  1531. gcExecutor = new GarbageCollectorService(settings, this);
  1532. if (gcExecutor.isReady()) {
  1533. logger.info("Garbage Collector (GC) will scan repositories every 24 hours.");
  1534. Calendar c = Calendar.getInstance();
  1535. c.set(Calendar.HOUR_OF_DAY, settings.getInteger(Keys.git.garbageCollectionHour, 0));
  1536. c.set(Calendar.MINUTE, 0);
  1537. c.set(Calendar.SECOND, 0);
  1538. c.set(Calendar.MILLISECOND, 0);
  1539. Date cd = c.getTime();
  1540. Date now = new Date();
  1541. int delay = 0;
  1542. if (cd.before(now)) {
  1543. c.add(Calendar.DATE, 1);
  1544. cd = c.getTime();
  1545. }
  1546. delay = (int) ((cd.getTime() - now.getTime())/TimeUtils.MIN);
  1547. String when = delay + " mins";
  1548. if (delay > 60) {
  1549. when = MessageFormat.format("{0,number,0.0} hours", delay / 60f);
  1550. }
  1551. logger.info(MessageFormat.format("Next scheculed GC scan is in {0}", when));
  1552. scheduledExecutor.scheduleAtFixedRate(gcExecutor, delay, 60 * 24, TimeUnit.MINUTES);
  1553. } else {
  1554. logger.info("Garbage Collector (GC) is disabled.");
  1555. }
  1556. }
  1557. protected void configureMirrorExecutor() {
  1558. mirrorExecutor = new MirrorService(settings, this);
  1559. if (mirrorExecutor.isReady()) {
  1560. int mins = TimeUtils.convertFrequencyToMinutes(settings.getString(Keys.git.mirrorPeriod, "30 mins"));
  1561. if (mins < 5) {
  1562. mins = 5;
  1563. }
  1564. int delay = 1;
  1565. scheduledExecutor.scheduleAtFixedRate(mirrorExecutor, delay, mins, TimeUnit.MINUTES);
  1566. logger.info("Mirror service will fetch updates every {} minutes.", mins);
  1567. logger.info("Next scheduled mirror fetch is in {} minutes", delay);
  1568. } else {
  1569. logger.info("Mirror service is disabled.");
  1570. }
  1571. }
  1572. protected void configureJGit() {
  1573. // Configure JGit
  1574. WindowCacheConfig cfg = new WindowCacheConfig();
  1575. cfg.setPackedGitWindowSize(settings.getFilesize(Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
  1576. cfg.setPackedGitLimit(settings.getFilesize(Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
  1577. cfg.setDeltaBaseCacheLimit(settings.getFilesize(Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
  1578. cfg.setPackedGitOpenFiles(settings.getFilesize(Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
  1579. cfg.setStreamFileThreshold(settings.getFilesize(Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
  1580. cfg.setPackedGitMMAP(settings.getBoolean(Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
  1581. try {
  1582. cfg.install();
  1583. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
  1584. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
  1585. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
  1586. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
  1587. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
  1588. logger.debug(MessageFormat.format("{0} = {1}", Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
  1589. } catch (IllegalArgumentException e) {
  1590. logger.error("Failed to configure JGit parameters!", e);
  1591. }
  1592. }
  1593. protected void configureCommitCache() {
  1594. int daysToCache = settings.getInteger(Keys.web.activityCacheDays, 14);
  1595. if (daysToCache <= 0) {
  1596. logger.info("Commit cache is disabled");
  1597. } else {
  1598. long start = System.nanoTime();
  1599. long repoCount = 0;
  1600. long commitCount = 0;
  1601. logger.info(MessageFormat.format("Preparing {0} day commit cache. please wait...", daysToCache));
  1602. CommitCache.instance().setCacheDays(daysToCache);
  1603. Date cutoff = CommitCache.instance().getCutoffDate();
  1604. for (String repositoryName : getRepositoryList()) {
  1605. RepositoryModel model = getRepositoryModel(repositoryName);
  1606. if (model != null && model.hasCommits && model.lastChange.after(cutoff)) {
  1607. repoCount++;
  1608. Repository repository = getRepository(repositoryName);
  1609. for (RefModel ref : JGitUtils.getLocalBranches(repository, true, -1)) {
  1610. if (!ref.getDate().after(cutoff)) {
  1611. // branch not recently updated
  1612. continue;
  1613. }
  1614. List<?> commits = CommitCache.instance().getCommits(repositoryName, repository, ref.getName());
  1615. if (commits.size() > 0) {
  1616. logger.info(MessageFormat.format(" cached {0} commits for {1}:{2}",
  1617. commits.size(), repositoryName, ref.getName()));
  1618. commitCount += commits.size();
  1619. }
  1620. }
  1621. repository.close();
  1622. }
  1623. }
  1624. logger.info(MessageFormat.format("built {0} day commit cache of {1} commits across {2} repositories in {3} msecs",
  1625. daysToCache, commitCount, repoCount, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
  1626. }
  1627. }
  1628. protected void confirmWriteAccess() {
  1629. if (runtimeManager.isServingRepositories()) {
  1630. try {
  1631. File file = File.createTempFile(".test-", ".txt", getRepositoriesFolder());
  1632. file.delete();
  1633. } catch (Exception e) {
  1634. logger.error("");
  1635. logger.error(Constants.BORDER2);
  1636. logger.error("Please check filesystem permissions!");
  1637. logger.error("FAILED TO WRITE TO REPOSITORIES FOLDER!!", e);
  1638. logger.error(Constants.BORDER2);
  1639. logger.error("");
  1640. }
  1641. }
  1642. }
  1643. }