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.persistence.AtomicWrite;
12 import akka.persistence.PersistentImpl;
13 import akka.persistence.PersistentRepr;
14 import akka.persistence.journal.japi.AsyncWriteJournal;
15 import com.google.common.collect.Maps;
16 import com.google.common.util.concurrent.Uninterruptibles;
17 import java.io.Serializable;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Iterator;
21 import java.util.List;
23 import java.util.Optional;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.CountDownLatch;
26 import java.util.concurrent.TimeUnit;
27 import java.util.function.Consumer;
28 import org.apache.commons.lang.SerializationUtils;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import scala.concurrent.Future;
34 * An akka AsyncWriteJournal implementation that stores data in memory. This is intended for testing.
36 * @author Thomas Pantelis
38 public class InMemoryJournal extends AsyncWriteJournal {
40 private static class WriteMessagesComplete {
41 final CountDownLatch latch;
42 final Class<?> ofType;
44 WriteMessagesComplete(int count, Class<?> ofType) {
45 this.latch = new CountDownLatch(count);
50 static final Logger LOG = LoggerFactory.getLogger(InMemoryJournal.class);
52 private static final Map<String, Map<Long, Object>> JOURNALS = new ConcurrentHashMap<>();
54 private static final Map<String, CountDownLatch> DELETE_MESSAGES_COMPLETE_LATCHES = new ConcurrentHashMap<>();
56 private static final Map<String, WriteMessagesComplete> WRITE_MESSAGES_COMPLETE = new ConcurrentHashMap<>();
58 private static final Map<String, CountDownLatch> BLOCK_READ_MESSAGES_LATCHES = new ConcurrentHashMap<>();
60 private static Object deserialize(Object data) {
61 return data instanceof byte[] ? SerializationUtils.deserialize((byte[])data) : data;
64 public static void addEntry(String persistenceId, long sequenceNr, Object data) {
65 Map<Long, Object> journal = JOURNALS.get(persistenceId);
66 if (journal == null) {
67 journal = Maps.newLinkedHashMap();
68 JOURNALS.put(persistenceId, journal);
71 synchronized (journal) {
72 journal.put(sequenceNr, data instanceof Serializable
73 ? SerializationUtils.serialize((Serializable) data) : data);
77 public static void clear() {
81 @SuppressWarnings("unchecked")
82 public static <T> List<T> get(String persistenceId, Class<T> type) {
83 Map<Long, Object> journalMap = JOURNALS.get(persistenceId);
84 if (journalMap == null) {
85 return Collections.<T>emptyList();
88 synchronized (journalMap) {
89 List<T> journal = new ArrayList<>(journalMap.size());
90 for (Object entry: journalMap.values()) {
91 Object data = deserialize(entry);
92 if (type.isInstance(data)) {
93 journal.add((T) data);
101 public static Map<Long, Object> get(String persistenceId) {
102 Map<Long, Object> journalMap = JOURNALS.get(persistenceId);
103 return journalMap != null ? journalMap : Collections.<Long, Object>emptyMap();
106 public static void dumpJournal(String persistenceId) {
107 StringBuilder builder = new StringBuilder(String.format("Journal log for %s:", persistenceId));
108 Map<Long, Object> journalMap = JOURNALS.get(persistenceId);
109 if (journalMap != null) {
110 synchronized (journalMap) {
111 for (Map.Entry<Long, Object> e: journalMap.entrySet()) {
112 builder.append("\n ").append(e.getKey()).append(" = ").append(e.getValue());
117 LOG.info(builder.toString());
120 public static void waitForDeleteMessagesComplete(String persistenceId) {
121 if (!Uninterruptibles.awaitUninterruptibly(DELETE_MESSAGES_COMPLETE_LATCHES.get(persistenceId),
122 5, TimeUnit.SECONDS)) {
123 throw new AssertionError("Delete messages did not complete");
127 public static void waitForWriteMessagesComplete(String persistenceId) {
128 if (!Uninterruptibles.awaitUninterruptibly(WRITE_MESSAGES_COMPLETE.get(persistenceId).latch,
129 5, TimeUnit.SECONDS)) {
130 throw new AssertionError("Journal write messages did not complete");
134 public static void addDeleteMessagesCompleteLatch(String persistenceId) {
135 DELETE_MESSAGES_COMPLETE_LATCHES.put(persistenceId, new CountDownLatch(1));
138 public static void addWriteMessagesCompleteLatch(String persistenceId, int count) {
139 WRITE_MESSAGES_COMPLETE.put(persistenceId, new WriteMessagesComplete(count, null));
142 public static void addWriteMessagesCompleteLatch(String persistenceId, int count, Class<?> ofType) {
143 WRITE_MESSAGES_COMPLETE.put(persistenceId, new WriteMessagesComplete(count, ofType));
146 public static void addBlockReadMessagesLatch(String persistenceId, CountDownLatch latch) {
147 BLOCK_READ_MESSAGES_LATCHES.put(persistenceId, latch);
151 public Future<Void> doAsyncReplayMessages(final String persistenceId, final long fromSequenceNr,
152 final long toSequenceNr, final long max, final Consumer<PersistentRepr> replayCallback) {
153 LOG.trace("doAsyncReplayMessages for {}: fromSequenceNr: {}, toSequenceNr: {}", persistenceId,
154 fromSequenceNr,toSequenceNr);
155 return Futures.future(() -> {
156 CountDownLatch blockLatch = BLOCK_READ_MESSAGES_LATCHES.remove(persistenceId);
157 if (blockLatch != null) {
158 Uninterruptibles.awaitUninterruptibly(blockLatch);
161 Map<Long, Object> journal = JOURNALS.get(persistenceId);
162 if (journal == null) {
166 synchronized (journal) {
168 for (Map.Entry<Long,Object> entry : journal.entrySet()) {
169 if (++count <= max && entry.getKey() >= fromSequenceNr && entry.getKey() <= toSequenceNr) {
170 PersistentRepr persistentMessage =
171 new PersistentImpl(deserialize(entry.getValue()), entry.getKey(), persistenceId,
172 null, false, null, null);
173 replayCallback.accept(persistentMessage);
179 }, context().dispatcher());
183 public Future<Long> doAsyncReadHighestSequenceNr(String persistenceId, long fromSequenceNr) {
184 LOG.trace("doAsyncReadHighestSequenceNr for {}: fromSequenceNr: {}", persistenceId, fromSequenceNr);
186 // Akka calls this during recovery.
187 Map<Long, Object> journal = JOURNALS.get(persistenceId);
188 if (journal == null) {
189 return Futures.successful(fromSequenceNr);
192 synchronized (journal) {
194 for (Long seqNr : journal.keySet()) {
195 if (seqNr.longValue() >= fromSequenceNr && seqNr.longValue() > highest) {
196 highest = seqNr.longValue();
200 return Futures.successful(highest);
205 public Future<Iterable<Optional<Exception>>> doAsyncWriteMessages(final Iterable<AtomicWrite> messages) {
206 return Futures.future(() -> {
207 for (AtomicWrite write : messages) {
208 // Copy to array - workaround for eclipse "ambiguous method" errors for toIterator, toIterable etc
209 PersistentRepr[] array = new PersistentRepr[write.payload().size()];
210 write.payload().copyToArray(array);
211 for (PersistentRepr repr: array) {
212 LOG.trace("doAsyncWriteMessages: id: {}: seqNr: {}, payload: {}", repr.persistenceId(),
213 repr.sequenceNr(), repr.payload());
215 addEntry(repr.persistenceId(), repr.sequenceNr(), repr.payload());
217 WriteMessagesComplete complete = WRITE_MESSAGES_COMPLETE.get(repr.persistenceId());
218 if (complete != null) {
219 if (complete.ofType == null || complete.ofType.equals(repr.payload().getClass())) {
220 complete.latch.countDown();
226 return Collections.emptyList();
227 }, context().dispatcher());
231 public Future<Void> doAsyncDeleteMessagesTo(String persistenceId, long toSequenceNr) {
232 LOG.trace("doAsyncDeleteMessagesTo: {}", toSequenceNr);
233 Map<Long, Object> journal = JOURNALS.get(persistenceId);
234 if (journal != null) {
235 synchronized (journal) {
236 Iterator<Long> iter = journal.keySet().iterator();
237 while (iter.hasNext()) {
238 Long num = iter.next();
239 if (num <= toSequenceNr) {
246 CountDownLatch latch = DELETE_MESSAGES_COMPLETE_LATCHES.get(persistenceId);
251 return Futures.successful(null);