You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RepositoryManager.java 69KB

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