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

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