Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

RedisTicketService.java 16KB

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