Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

RepositoryManager.java 65KB

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