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

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