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

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