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

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