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

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