f3d4bc6b2ae8822ced64b247d4ac0eb92346690c
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / utils / InMemoryJournal.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.raft.utils;
9
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.util.concurrent.Uninterruptibles;
16 import java.io.Serializable;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.LinkedHashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Optional;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26 import java.util.function.Consumer;
27 import org.apache.commons.lang.SerializationUtils;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import scala.concurrent.Future;
31 import scala.jdk.javaapi.CollectionConverters;
32
33 /**
34  * An akka AsyncWriteJournal implementation that stores data in memory. This is intended for testing.
35  *
36  * @author Thomas Pantelis
37  */
38 public class InMemoryJournal extends AsyncWriteJournal {
39
40     private static class WriteMessagesComplete {
41         final CountDownLatch latch;
42         final Class<?> ofType;
43
44         WriteMessagesComplete(final int count, final Class<?> ofType) {
45             this.latch = new CountDownLatch(count);
46             this.ofType = ofType;
47         }
48     }
49
50     static final Logger LOG = LoggerFactory.getLogger(InMemoryJournal.class);
51
52     private static final Map<String, Map<Long, Object>> JOURNALS = new ConcurrentHashMap<>();
53
54     private static final Map<String, CountDownLatch> DELETE_MESSAGES_COMPLETE_LATCHES = new ConcurrentHashMap<>();
55
56     private static final Map<String, WriteMessagesComplete> WRITE_MESSAGES_COMPLETE = new ConcurrentHashMap<>();
57
58     private static final Map<String, CountDownLatch> BLOCK_READ_MESSAGES_LATCHES = new ConcurrentHashMap<>();
59
60     private static Object deserialize(final Object data) {
61         return data instanceof byte[] ? SerializationUtils.deserialize((byte[])data) : data;
62     }
63
64     public static void addEntry(final String persistenceId, final long sequenceNr, final Object data) {
65         Map<Long, Object> journal = JOURNALS.computeIfAbsent(persistenceId, k -> new LinkedHashMap<>());
66
67         synchronized (journal) {
68             journal.put(sequenceNr, data instanceof Serializable
69                     ? SerializationUtils.serialize((Serializable) data) : data);
70         }
71     }
72
73     public static void clear() {
74         JOURNALS.clear();
75         DELETE_MESSAGES_COMPLETE_LATCHES.clear();
76         WRITE_MESSAGES_COMPLETE.clear();
77         BLOCK_READ_MESSAGES_LATCHES.clear();
78     }
79
80     @SuppressWarnings("unchecked")
81     public static <T> List<T> get(final String persistenceId, final Class<T> type) {
82         Map<Long, Object> journalMap = JOURNALS.get(persistenceId);
83         if (journalMap == null) {
84             return Collections.<T>emptyList();
85         }
86
87         synchronized (journalMap) {
88             List<T> journal = new ArrayList<>(journalMap.size());
89             for (Object entry: journalMap.values()) {
90                 Object data = deserialize(entry);
91                 if (type.isInstance(data)) {
92                     journal.add((T) data);
93                 }
94             }
95
96             return journal;
97         }
98     }
99
100     public static Map<Long, Object> get(final String persistenceId) {
101         Map<Long, Object> journalMap = JOURNALS.get(persistenceId);
102         return journalMap != null ? journalMap : Collections.<Long, Object>emptyMap();
103     }
104
105     public static void dumpJournal(final String persistenceId) {
106         StringBuilder builder = new StringBuilder(String.format("Journal log for %s:", persistenceId));
107         Map<Long, Object> journalMap = JOURNALS.get(persistenceId);
108         if (journalMap != null) {
109             synchronized (journalMap) {
110                 for (Map.Entry<Long, Object> e: journalMap.entrySet()) {
111                     builder.append("\n    ").append(e.getKey()).append(" = ").append(deserialize(e.getValue()));
112                 }
113             }
114         }
115
116         LOG.info(builder.toString());
117     }
118
119     public static void waitForDeleteMessagesComplete(final String persistenceId) {
120         if (!Uninterruptibles.awaitUninterruptibly(DELETE_MESSAGES_COMPLETE_LATCHES.get(persistenceId),
121                 5, TimeUnit.SECONDS)) {
122             throw new AssertionError("Delete messages did not complete");
123         }
124     }
125
126     public static void waitForWriteMessagesComplete(final String persistenceId) {
127         if (!Uninterruptibles.awaitUninterruptibly(WRITE_MESSAGES_COMPLETE.get(persistenceId).latch,
128                 5, TimeUnit.SECONDS)) {
129             throw new AssertionError("Journal write messages did not complete");
130         }
131     }
132
133     public static void addDeleteMessagesCompleteLatch(final String persistenceId) {
134         DELETE_MESSAGES_COMPLETE_LATCHES.put(persistenceId, new CountDownLatch(1));
135     }
136
137     public static void addWriteMessagesCompleteLatch(final String persistenceId, final int count) {
138         WRITE_MESSAGES_COMPLETE.put(persistenceId, new WriteMessagesComplete(count, null));
139     }
140
141     public static void addWriteMessagesCompleteLatch(final String persistenceId, final int count,
142             final Class<?> ofType) {
143         WRITE_MESSAGES_COMPLETE.put(persistenceId, new WriteMessagesComplete(count, ofType));
144     }
145
146     public static void addBlockReadMessagesLatch(final String persistenceId, final CountDownLatch latch) {
147         BLOCK_READ_MESSAGES_LATCHES.put(persistenceId, latch);
148     }
149
150     @Override
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);
159             }
160
161             Map<Long, Object> journal = JOURNALS.get(persistenceId);
162             if (journal == null) {
163                 return null;
164             }
165
166             synchronized (journal) {
167                 int count = 0;
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, 0);
173                         replayCallback.accept(persistentMessage);
174                     }
175                 }
176             }
177
178             return null;
179         }, context().dispatcher());
180     }
181
182     @Override
183     public Future<Long> doAsyncReadHighestSequenceNr(final String persistenceId, final long fromSequenceNr) {
184         LOG.trace("doAsyncReadHighestSequenceNr for {}: fromSequenceNr: {}", persistenceId, fromSequenceNr);
185
186         // Akka calls this during recovery.
187         Map<Long, Object> journal = JOURNALS.get(persistenceId);
188         if (journal == null) {
189             return Futures.successful(fromSequenceNr);
190         }
191
192         synchronized (journal) {
193             long highest = -1;
194             for (Long seqNr : journal.keySet()) {
195                 if (seqNr.longValue() >= fromSequenceNr && seqNr.longValue() > highest) {
196                     highest = seqNr.longValue();
197                 }
198             }
199
200             return Futures.successful(highest);
201         }
202     }
203
204     @Override
205     public Future<Iterable<Optional<Exception>>> doAsyncWriteMessages(final Iterable<AtomicWrite> messages) {
206         return Futures.future(() -> {
207             for (AtomicWrite write : messages) {
208                 for (PersistentRepr repr : CollectionConverters.asJava(write.payload())) {
209                     LOG.trace("doAsyncWriteMessages: id: {}: seqNr: {}, payload: {}", repr.persistenceId(),
210                         repr.sequenceNr(), repr.payload());
211
212                     addEntry(repr.persistenceId(), repr.sequenceNr(), repr.payload());
213
214                     WriteMessagesComplete complete = WRITE_MESSAGES_COMPLETE.get(repr.persistenceId());
215                     if (complete != null) {
216                         if (complete.ofType == null || complete.ofType.equals(repr.payload().getClass())) {
217                             complete.latch.countDown();
218                         }
219                     }
220                 }
221             }
222
223             return Collections.emptyList();
224         }, context().dispatcher());
225     }
226
227     @Override
228     public Future<Void> doAsyncDeleteMessagesTo(final String persistenceId, final long toSequenceNr) {
229         LOG.trace("doAsyncDeleteMessagesTo: {}", toSequenceNr);
230         Map<Long, Object> journal = JOURNALS.get(persistenceId);
231         if (journal != null) {
232             synchronized (journal) {
233                 journal.keySet().removeIf(num -> num <= toSequenceNr);
234             }
235         }
236
237         CountDownLatch latch = DELETE_MESSAGES_COMPLETE_LATCHES.get(persistenceId);
238         if (latch != null) {
239             latch.countDown();
240         }
241
242         return Futures.successful(null);
243     }
244 }