2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft.utils;
10 import akka.dispatch.Futures;
11 import akka.japi.Procedure;
12 import akka.persistence.PersistentConfirmation;
13 import akka.persistence.PersistentId;
14 import akka.persistence.PersistentImpl;
15 import akka.persistence.PersistentRepr;
16 import akka.persistence.journal.japi.AsyncWriteJournal;
17 import com.google.common.collect.Maps;
18 import com.google.common.util.concurrent.Uninterruptibles;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.CountDownLatch;
27 import java.util.concurrent.TimeUnit;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import scala.concurrent.Future;
33 * An akka AsyncWriteJournal implementation that stores data in memory. This is intended for testing.
35 * @author Thomas Pantelis
37 public class InMemoryJournal extends AsyncWriteJournal {
39 private static class WriteMessagesComplete {
40 final CountDownLatch latch;
41 final Class<?> ofType;
43 public WriteMessagesComplete(int count, Class<?> ofType) {
44 this.latch = new CountDownLatch(count);
49 static final Logger LOG = LoggerFactory.getLogger(InMemoryJournal.class);
51 private static final Map<String, Map<Long, Object>> journals = new ConcurrentHashMap<>();
53 private static final Map<String, CountDownLatch> deleteMessagesCompleteLatches = new ConcurrentHashMap<>();
55 private static final Map<String, WriteMessagesComplete> writeMessagesComplete = new ConcurrentHashMap<>();
57 private static final Map<String, CountDownLatch> blockReadMessagesLatches = new ConcurrentHashMap<>();
59 public static void addEntry(String persistenceId, long sequenceNr, Object data) {
60 Map<Long, Object> journal = journals.get(persistenceId);
62 journal = Maps.newLinkedHashMap();
63 journals.put(persistenceId, journal);
66 synchronized (journal) {
67 journal.put(sequenceNr, data);
71 public static void clear() {
75 @SuppressWarnings("unchecked")
76 public static <T> List<T> get(String persistenceId, Class<T> type) {
77 Map<Long, Object> journalMap = journals.get(persistenceId);
78 if(journalMap == null) {
79 return Collections.<T>emptyList();
82 synchronized (journalMap) {
83 List<T> journal = new ArrayList<>(journalMap.size());
84 for(Object entry: journalMap.values()) {
85 if(type.isInstance(entry)) {
86 journal.add((T) entry);
94 public static Map<Long, Object> get(String persistenceId) {
95 Map<Long, Object> journalMap = journals.get(persistenceId);
96 return journalMap != null ? journalMap : Collections.<Long, Object>emptyMap();
99 public static void dumpJournal(String persistenceId) {
100 StringBuilder builder = new StringBuilder(String.format("Journal log for %s:", persistenceId));
101 Map<Long, Object> journalMap = journals.get(persistenceId);
102 if(journalMap != null) {
103 synchronized (journalMap) {
104 for(Map.Entry<Long, Object> e: journalMap.entrySet()) {
105 builder.append("\n ").append(e.getKey()).append(" = ").append(e.getValue());
110 LOG.info(builder.toString());
113 public static void waitForDeleteMessagesComplete(String persistenceId) {
114 if(!Uninterruptibles.awaitUninterruptibly(deleteMessagesCompleteLatches.get(persistenceId), 5, TimeUnit.SECONDS)) {
115 throw new AssertionError("Delete messages did not complete");
119 public static void waitForWriteMessagesComplete(String persistenceId) {
120 if(!Uninterruptibles.awaitUninterruptibly(writeMessagesComplete.get(persistenceId).latch, 5, TimeUnit.SECONDS)) {
121 throw new AssertionError("Journal write messages did not complete");
125 public static void addDeleteMessagesCompleteLatch(String persistenceId) {
126 deleteMessagesCompleteLatches.put(persistenceId, new CountDownLatch(1));
129 public static void addWriteMessagesCompleteLatch(String persistenceId, int count) {
130 writeMessagesComplete.put(persistenceId, new WriteMessagesComplete(count, null));
133 public static void addWriteMessagesCompleteLatch(String persistenceId, int count, Class<?> ofType) {
134 writeMessagesComplete.put(persistenceId, new WriteMessagesComplete(count, ofType));
137 public static void addBlockReadMessagesLatch(String persistenceId, CountDownLatch latch) {
138 blockReadMessagesLatches.put(persistenceId, latch);
142 public Future<Void> doAsyncReplayMessages(final String persistenceId, final long fromSequenceNr,
143 final long toSequenceNr, long max, final Procedure<PersistentRepr> replayCallback) {
144 return Futures.future(new Callable<Void>() {
146 public Void call() throws Exception {
147 CountDownLatch blockLatch = blockReadMessagesLatches.remove(persistenceId);
148 if(blockLatch != null) {
149 Uninterruptibles.awaitUninterruptibly(blockLatch);
152 Map<Long, Object> journal = journals.get(persistenceId);
153 if (journal == null) {
157 synchronized (journal) {
158 for (Map.Entry<Long,Object> entry : journal.entrySet()) {
159 if (entry.getKey() >= fromSequenceNr && entry.getKey() <= toSequenceNr) {
160 PersistentRepr persistentMessage =
161 new PersistentImpl(entry.getValue(), entry.getKey(), persistenceId,
163 replayCallback.apply(persistentMessage);
170 }, context().dispatcher());
174 public Future<Long> doAsyncReadHighestSequenceNr(String persistenceId, long fromSequenceNr) {
175 // Akka calls this during recovery.
177 Map<Long, Object> journal = journals.get(persistenceId);
178 if(journal == null) {
179 return Futures.successful(-1L);
182 synchronized (journal) {
184 for (Long seqNr : journal.keySet()) {
185 if(seqNr.longValue() >= fromSequenceNr && seqNr.longValue() > highest) {
186 highest = seqNr.longValue();
190 return Futures.successful(highest);
195 public Future<Void> doAsyncWriteMessages(final Iterable<PersistentRepr> messages) {
196 return Futures.future(new Callable<Void>() {
198 public Void call() throws Exception {
199 for (PersistentRepr repr : messages) {
200 Map<Long, Object> journal = journals.get(repr.persistenceId());
201 if(journal == null) {
202 journal = Maps.newLinkedHashMap();
203 journals.put(repr.persistenceId(), journal);
206 synchronized (journal) {
207 LOG.trace("doAsyncWriteMessages: id: {}: seqNr: {}, payload: {}", repr.persistenceId(),
208 repr.sequenceNr(), repr.payload());
209 journal.put(repr.sequenceNr(), repr.payload());
212 WriteMessagesComplete complete = writeMessagesComplete.get(repr.persistenceId());
213 if(complete != null) {
214 if(complete.ofType == null || complete.ofType.equals(repr.payload().getClass())) {
215 complete.latch.countDown();
222 }, context().dispatcher());
226 public Future<Void> doAsyncWriteConfirmations(Iterable<PersistentConfirmation> confirmations) {
227 return Futures.successful(null);
231 public Future<Void> doAsyncDeleteMessages(Iterable<PersistentId> messageIds, boolean permanent) {
232 return Futures.successful(null);
236 public Future<Void> doAsyncDeleteMessagesTo(String persistenceId, long toSequenceNr, boolean permanent) {
237 LOG.trace("doAsyncDeleteMessagesTo: {}", toSequenceNr);
238 Map<Long, Object> journal = journals.get(persistenceId);
239 if(journal != null) {
240 synchronized (journal) {
241 Iterator<Long> iter = journal.keySet().iterator();
242 while(iter.hasNext()) {
243 Long n = iter.next();
244 if(n <= toSequenceNr) {
251 CountDownLatch latch = deleteMessagesCompleteLatches.get(persistenceId);
256 return Futures.successful(null);