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.

RedisTicketService.java 16KB

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