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

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