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

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