Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RedisTicketService.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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.tickets;
  17. import java.net.URI;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.List;
  21. import java.util.Set;
  22. import javax.inject.Inject;
  23. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  24. import redis.clients.jedis.Client;
  25. import redis.clients.jedis.Jedis;
  26. import redis.clients.jedis.JedisPool;
  27. import redis.clients.jedis.Protocol;
  28. import redis.clients.jedis.Transaction;
  29. import redis.clients.jedis.exceptions.JedisException;
  30. import com.gitblit.Keys;
  31. import com.gitblit.manager.INotificationManager;
  32. import com.gitblit.manager.IRepositoryManager;
  33. import com.gitblit.manager.IRuntimeManager;
  34. import com.gitblit.manager.IUserManager;
  35. import com.gitblit.models.RepositoryModel;
  36. import com.gitblit.models.TicketModel;
  37. import com.gitblit.models.TicketModel.Attachment;
  38. import com.gitblit.models.TicketModel.Change;
  39. import com.gitblit.utils.ArrayUtils;
  40. import com.gitblit.utils.StringUtils;
  41. /**
  42. * Implementation of a ticket service based on a Redis key-value store. All
  43. * tickets are persisted in the Redis store so it must be configured for
  44. * durability otherwise tickets are lost on a flush or restart. Tickets are
  45. * indexed with Lucene and all queries are executed against the Lucene index.
  46. *
  47. * @author James Moger
  48. *
  49. */
  50. public class RedisTicketService extends ITicketService {
  51. private final JedisPool pool;
  52. private enum KeyType {
  53. journal, ticket, counter
  54. }
  55. @Inject
  56. public RedisTicketService(
  57. IRuntimeManager runtimeManager,
  58. INotificationManager notificationManager,
  59. IUserManager userManager,
  60. IRepositoryManager repositoryManager) {
  61. super(runtimeManager,
  62. notificationManager,
  63. userManager,
  64. repositoryManager);
  65. String redisUrl = settings.getString(Keys.tickets.redis.url, "");
  66. this.pool = createPool(redisUrl);
  67. }
  68. @Override
  69. public RedisTicketService start() {
  70. return this;
  71. }
  72. @Override
  73. protected void resetCachesImpl() {
  74. }
  75. @Override
  76. protected void resetCachesImpl(RepositoryModel repository) {
  77. }
  78. @Override
  79. protected void close() {
  80. pool.destroy();
  81. }
  82. @Override
  83. public boolean isReady() {
  84. return pool != null;
  85. }
  86. /**
  87. * Constructs a key for use with a key-value data store.
  88. *
  89. * @param key
  90. * @param repository
  91. * @param id
  92. * @return a key
  93. */
  94. private String key(RepositoryModel repository, KeyType key, String id) {
  95. StringBuilder sb = new StringBuilder();
  96. sb.append(repository.name).append(':');
  97. sb.append(key.name());
  98. if (!StringUtils.isEmpty(id)) {
  99. sb.append(':');
  100. sb.append(id);
  101. }
  102. return sb.toString();
  103. }
  104. /**
  105. * Constructs a key for use with a key-value data store.
  106. *
  107. * @param key
  108. * @param repository
  109. * @param id
  110. * @return a key
  111. */
  112. private String key(RepositoryModel repository, KeyType key, long id) {
  113. return key(repository, key, "" + id);
  114. }
  115. private boolean isNull(String value) {
  116. return value == null || "nil".equals(value);
  117. }
  118. private String getUrl() {
  119. Jedis jedis = pool.getResource();
  120. try {
  121. if (jedis != null) {
  122. Client client = jedis.getClient();
  123. return client.getHost() + ":" + client.getPort() + "/" + client.getDB();
  124. }
  125. } catch (JedisException e) {
  126. pool.returnBrokenResource(jedis);
  127. jedis = null;
  128. } finally {
  129. if (jedis != null) {
  130. pool.returnResource(jedis);
  131. }
  132. }
  133. return null;
  134. }
  135. /**
  136. * Ensures that we have a ticket for this ticket id.
  137. *
  138. * @param repository
  139. * @param ticketId
  140. * @return true if the ticket exists
  141. */
  142. @Override
  143. public boolean hasTicket(RepositoryModel repository, long ticketId) {
  144. if (ticketId <= 0L) {
  145. return false;
  146. }
  147. Jedis jedis = pool.getResource();
  148. if (jedis == null) {
  149. return false;
  150. }
  151. try {
  152. Boolean exists = jedis.exists(key(repository, KeyType.journal, ticketId));
  153. return exists != null && !exists;
  154. } catch (JedisException e) {
  155. log.error("failed to check hasTicket from Redis @ " + getUrl(), e);
  156. pool.returnBrokenResource(jedis);
  157. jedis = null;
  158. } finally {
  159. if (jedis != null) {
  160. pool.returnResource(jedis);
  161. }
  162. }
  163. return false;
  164. }
  165. /**
  166. * Assigns a new ticket id.
  167. *
  168. * @param repository
  169. * @return a new long ticket id
  170. */
  171. @Override
  172. public synchronized long assignNewId(RepositoryModel repository) {
  173. Jedis jedis = pool.getResource();
  174. try {
  175. String key = key(repository, KeyType.counter, null);
  176. String val = jedis.get(key);
  177. if (isNull(val)) {
  178. jedis.set(key, "0");
  179. }
  180. long ticketNumber = jedis.incr(key);
  181. return ticketNumber;
  182. } catch (JedisException e) {
  183. log.error("failed to assign new ticket id in Redis @ " + getUrl(), e);
  184. pool.returnBrokenResource(jedis);
  185. jedis = null;
  186. } finally {
  187. if (jedis != null) {
  188. pool.returnResource(jedis);
  189. }
  190. }
  191. return 0L;
  192. }
  193. /**
  194. * Returns all the tickets in the repository. Querying tickets from the
  195. * repository requires deserializing all tickets. This is an expensive
  196. * process and not recommended. Tickets should be indexed by Lucene and
  197. * queries should be executed against that index.
  198. *
  199. * @param repository
  200. * @param filter
  201. * optional filter to only return matching results
  202. * @return a list of tickets
  203. */
  204. @Override
  205. public List<TicketModel> getTickets(RepositoryModel repository, TicketFilter filter) {
  206. Jedis jedis = pool.getResource();
  207. List<TicketModel> list = new ArrayList<TicketModel>();
  208. if (jedis == null) {
  209. return list;
  210. }
  211. try {
  212. // Deserialize each journal, build the ticket, and optionally filter
  213. Set<String> keys = jedis.keys(key(repository, KeyType.journal, "*"));
  214. for (String key : keys) {
  215. // {repo}:journal:{id}
  216. String id = key.split(":")[2];
  217. long ticketId = Long.parseLong(id);
  218. List<Change> changes = getJournal(jedis, repository, ticketId);
  219. if (ArrayUtils.isEmpty(changes)) {
  220. log.warn("Empty journal for {}:{}", repository, ticketId);
  221. continue;
  222. }
  223. TicketModel ticket = TicketModel.buildTicket(changes);
  224. ticket.project = repository.projectPath;
  225. ticket.repository = repository.name;
  226. ticket.number = ticketId;
  227. // add the ticket, conditionally, to the list
  228. if (filter == null) {
  229. list.add(ticket);
  230. } else {
  231. if (filter.accept(ticket)) {
  232. list.add(ticket);
  233. }
  234. }
  235. }
  236. // sort the tickets by creation
  237. Collections.sort(list);
  238. } catch (JedisException e) {
  239. log.error("failed to retrieve tickets from Redis @ " + getUrl(), e);
  240. pool.returnBrokenResource(jedis);
  241. jedis = null;
  242. } finally {
  243. if (jedis != null) {
  244. pool.returnResource(jedis);
  245. }
  246. }
  247. return list;
  248. }
  249. /**
  250. * Retrieves the ticket from the repository by first looking-up the changeId
  251. * associated with the ticketId.
  252. *
  253. * @param repository
  254. * @param ticketId
  255. * @return a ticket, if it exists, otherwise null
  256. */
  257. @Override
  258. protected TicketModel getTicketImpl(RepositoryModel repository, long ticketId) {
  259. Jedis jedis = pool.getResource();
  260. if (jedis == null) {
  261. return null;
  262. }
  263. try {
  264. List<Change> changes = getJournal(jedis, repository, ticketId);
  265. if (ArrayUtils.isEmpty(changes)) {
  266. log.warn("Empty journal for {}:{}", repository, ticketId);
  267. return null;
  268. }
  269. TicketModel ticket = TicketModel.buildTicket(changes);
  270. ticket.project = repository.projectPath;
  271. ticket.repository = repository.name;
  272. ticket.number = ticketId;
  273. log.debug("rebuilt ticket {} from Redis @ {}", ticketId, getUrl());
  274. return ticket;
  275. } catch (JedisException e) {
  276. log.error("failed to retrieve ticket from Redis @ " + getUrl(), e);
  277. pool.returnBrokenResource(jedis);
  278. jedis = null;
  279. } finally {
  280. if (jedis != null) {
  281. pool.returnResource(jedis);
  282. }
  283. }
  284. return null;
  285. }
  286. /**
  287. * Returns the journal for the specified ticket.
  288. *
  289. * @param repository
  290. * @param ticketId
  291. * @return a list of changes
  292. */
  293. private List<Change> getJournal(Jedis jedis, RepositoryModel repository, long ticketId) throws JedisException {
  294. if (ticketId <= 0L) {
  295. return new ArrayList<Change>();
  296. }
  297. List<String> entries = jedis.lrange(key(repository, KeyType.journal, ticketId), 0, -1);
  298. if (entries.size() > 0) {
  299. // build a json array from the individual entries
  300. StringBuilder sb = new StringBuilder();
  301. sb.append("[");
  302. for (String entry : entries) {
  303. sb.append(entry).append(',');
  304. }
  305. sb.setLength(sb.length() - 1);
  306. sb.append(']');
  307. String journal = sb.toString();
  308. return TicketSerializer.deserializeJournal(journal);
  309. }
  310. return new ArrayList<Change>();
  311. }
  312. @Override
  313. public boolean supportsAttachments() {
  314. return false;
  315. }
  316. /**
  317. * Retrieves the specified attachment from a ticket.
  318. *
  319. * @param repository
  320. * @param ticketId
  321. * @param filename
  322. * @return an attachment, if found, null otherwise
  323. */
  324. @Override
  325. public Attachment getAttachment(RepositoryModel repository, long ticketId, String filename) {
  326. return null;
  327. }
  328. /**
  329. * Deletes a ticket.
  330. *
  331. * @param ticket
  332. * @return true if successful
  333. */
  334. @Override
  335. protected boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket, String deletedBy) {
  336. boolean success = false;
  337. if (ticket == null) {
  338. throw new RuntimeException("must specify a ticket!");
  339. }
  340. Jedis jedis = pool.getResource();
  341. if (jedis == null) {
  342. return false;
  343. }
  344. try {
  345. // atomically remove ticket
  346. Transaction t = jedis.multi();
  347. t.del(key(repository, KeyType.ticket, ticket.number));
  348. t.del(key(repository, KeyType.journal, ticket.number));
  349. t.exec();
  350. success = true;
  351. log.debug("deleted ticket {} from Redis @ {}", "" + ticket.number, getUrl());
  352. } catch (JedisException e) {
  353. log.error("failed to delete ticket from Redis @ " + getUrl(), e);
  354. pool.returnBrokenResource(jedis);
  355. jedis = null;
  356. } finally {
  357. if (jedis != null) {
  358. pool.returnResource(jedis);
  359. }
  360. }
  361. return success;
  362. }
  363. /**
  364. * Commit a ticket change to the repository.
  365. *
  366. * @param repository
  367. * @param ticketId
  368. * @param change
  369. * @return true, if the change was committed
  370. */
  371. @Override
  372. protected boolean commitChangeImpl(RepositoryModel repository, long ticketId, Change change) {
  373. Jedis jedis = pool.getResource();
  374. if (jedis == null) {
  375. return false;
  376. }
  377. try {
  378. List<Change> changes = getJournal(jedis, repository, ticketId);
  379. changes.add(change);
  380. // build a new effective ticket from the changes
  381. TicketModel ticket = TicketModel.buildTicket(changes);
  382. String object = TicketSerializer.serialize(ticket);
  383. String journal = TicketSerializer.serialize(change);
  384. // atomically store ticket
  385. Transaction t = jedis.multi();
  386. t.set(key(repository, KeyType.ticket, ticketId), object);
  387. t.rpush(key(repository, KeyType.journal, ticketId), journal);
  388. t.exec();
  389. log.debug("updated ticket {} in Redis @ {}", "" + ticketId, getUrl());
  390. return true;
  391. } catch (JedisException e) {
  392. log.error("failed to update ticket cache in Redis @ " + getUrl(), e);
  393. pool.returnBrokenResource(jedis);
  394. jedis = null;
  395. } finally {
  396. if (jedis != null) {
  397. pool.returnResource(jedis);
  398. }
  399. }
  400. return false;
  401. }
  402. /**
  403. * Deletes all Tickets for the rpeository from the Redis key-value store.
  404. *
  405. */
  406. @Override
  407. protected boolean deleteAllImpl(RepositoryModel repository) {
  408. Jedis jedis = pool.getResource();
  409. if (jedis == null) {
  410. return false;
  411. }
  412. boolean success = false;
  413. try {
  414. Set<String> keys = jedis.keys(repository.name + ":*");
  415. if (keys.size() > 0) {
  416. Transaction t = jedis.multi();
  417. t.del(keys.toArray(new String[keys.size()]));
  418. t.exec();
  419. }
  420. success = true;
  421. } catch (JedisException e) {
  422. log.error("failed to delete all tickets in Redis @ " + getUrl(), e);
  423. pool.returnBrokenResource(jedis);
  424. jedis = null;
  425. } finally {
  426. if (jedis != null) {
  427. pool.returnResource(jedis);
  428. }
  429. }
  430. return success;
  431. }
  432. @Override
  433. protected boolean renameImpl(RepositoryModel oldRepository, RepositoryModel newRepository) {
  434. Jedis jedis = pool.getResource();
  435. if (jedis == null) {
  436. return false;
  437. }
  438. boolean success = false;
  439. try {
  440. Set<String> oldKeys = jedis.keys(oldRepository.name + ":*");
  441. Transaction t = jedis.multi();
  442. for (String oldKey : oldKeys) {
  443. String newKey = newRepository.name + oldKey.substring(oldKey.indexOf(':'));
  444. t.rename(oldKey, newKey);
  445. }
  446. t.exec();
  447. success = true;
  448. } catch (JedisException e) {
  449. log.error("failed to rename tickets in Redis @ " + getUrl(), e);
  450. pool.returnBrokenResource(jedis);
  451. jedis = null;
  452. } finally {
  453. if (jedis != null) {
  454. pool.returnResource(jedis);
  455. }
  456. }
  457. return success;
  458. }
  459. private JedisPool createPool(String url) {
  460. JedisPool pool = null;
  461. if (!StringUtils.isEmpty(url)) {
  462. try {
  463. URI uri = URI.create(url);
  464. if (uri.getScheme() != null && uri.getScheme().equalsIgnoreCase("redis")) {
  465. int database = Protocol.DEFAULT_DATABASE;
  466. String password = null;
  467. if (uri.getUserInfo() != null) {
  468. password = uri.getUserInfo().split(":", 2)[1];
  469. }
  470. if (uri.getPath().indexOf('/') > -1) {
  471. database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
  472. }
  473. pool = new JedisPool(new GenericObjectPoolConfig(), uri.getHost(), uri.getPort(), Protocol.DEFAULT_TIMEOUT, password, database);
  474. } else {
  475. pool = new JedisPool(url);
  476. }
  477. } catch (JedisException e) {
  478. log.error("failed to create a Redis pool!", e);
  479. }
  480. }
  481. return pool;
  482. }
  483. @Override
  484. public String toString() {
  485. String url = getUrl();
  486. return getClass().getSimpleName() + " (" + (url == null ? "DISABLED" : url) + ")";
  487. }
  488. }