bf130897354d12b9a89d75730f7353ba9135526c
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / utils / InMemorySnapshotStore.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
9 package org.opendaylight.controller.cluster.raft.utils;
10
11 import akka.dispatch.Futures;
12 import akka.japi.Option;
13 import akka.persistence.SelectedSnapshot;
14 import akka.persistence.SnapshotMetadata;
15 import akka.persistence.SnapshotSelectionCriteria;
16 import akka.persistence.snapshot.japi.SnapshotStore;
17 import com.google.common.collect.Lists;
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;
23 import java.util.Map;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.CountDownLatch;
26 import java.util.concurrent.TimeUnit;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import scala.concurrent.Future;
30
31 /**
32  * An akka SnapshotStore implementation that stores data in memory. This is intended for testing.
33  *
34  * @author Thomas Pantelis
35  */
36 public class InMemorySnapshotStore extends SnapshotStore {
37
38     static final Logger LOG = LoggerFactory.getLogger(InMemorySnapshotStore.class);
39
40     private static Map<String, List<StoredSnapshot>> snapshots = new ConcurrentHashMap<>();
41     private static final Map<String, CountDownLatch> snapshotSavedLatches = new ConcurrentHashMap<>();
42     private static final Map<String, CountDownLatch> snapshotDeletedLatches = new ConcurrentHashMap<>();
43
44     public static void addSnapshot(String persistentId, Object snapshot) {
45         List<StoredSnapshot> snapshotList = snapshots.get(persistentId);
46
47         if(snapshotList == null) {
48             snapshotList = new ArrayList<>();
49             snapshots.put(persistentId, snapshotList);
50         }
51
52         synchronized (snapshotList) {
53             snapshotList.add(new StoredSnapshot(new SnapshotMetadata(persistentId, snapshotList.size(),
54                     System.currentTimeMillis()), snapshot));
55         }
56     }
57
58     @SuppressWarnings("unchecked")
59     public static <T> List<T> getSnapshots(String persistentId, Class<T> type) {
60         List<StoredSnapshot> stored = snapshots.get(persistentId);
61         if(stored == null) {
62             return Collections.emptyList();
63         }
64
65         List<T> retList;
66         synchronized (stored) {
67             retList = Lists.newArrayListWithCapacity(stored.size());
68             for(StoredSnapshot s: stored) {
69                 if(type.isInstance(s.data)) {
70                     retList.add((T) s.data);
71                 }
72             }
73         }
74
75         return retList;
76     }
77
78     public static void clear() {
79         snapshots.clear();
80     }
81
82     public static void addSnapshotSavedLatch(String persistenceId) {
83         snapshotSavedLatches.put(persistenceId, new CountDownLatch(1));
84     }
85
86     public static void addSnapshotDeletedLatch(String persistenceId) {
87         snapshotDeletedLatches.put(persistenceId, new CountDownLatch(1));
88     }
89
90     public static <T> T waitForSavedSnapshot(String persistenceId, Class<T> type) {
91         if(!Uninterruptibles.awaitUninterruptibly(snapshotSavedLatches.get(persistenceId), 5, TimeUnit.SECONDS)) {
92             throw new AssertionError("Snapshot was not saved");
93         }
94
95         return getSnapshots(persistenceId, type).get(0);
96     }
97
98     public static void waitForDeletedSnapshot(String persistenceId) {
99         if(!Uninterruptibles.awaitUninterruptibly(snapshotDeletedLatches.get(persistenceId), 5, TimeUnit.SECONDS)) {
100             throw new AssertionError("Snapshot was not deleted");
101         }
102     }
103
104     @Override
105     public Future<Option<SelectedSnapshot>> doLoadAsync(String persistenceId,
106             SnapshotSelectionCriteria snapshotSelectionCriteria) {
107         List<StoredSnapshot> snapshotList = snapshots.get(persistenceId);
108         if(snapshotList == null){
109             return Futures.successful(Option.<SelectedSnapshot>none());
110         }
111
112         synchronized(snapshotList) {
113             for(int i = snapshotList.size() - 1; i >= 0; i--) {
114                 StoredSnapshot snapshot = snapshotList.get(i);
115                 if(matches(snapshot, snapshotSelectionCriteria)) {
116                     return Futures.successful(Option.some(new SelectedSnapshot(snapshot.metadata,
117                             snapshot.data)));
118                 }
119             }
120         }
121
122         return Futures.successful(Option.<SelectedSnapshot>none());
123     }
124
125     private static boolean matches(StoredSnapshot snapshot, SnapshotSelectionCriteria criteria) {
126         return snapshot.metadata.sequenceNr() <= criteria.maxSequenceNr() &&
127                 snapshot.metadata.timestamp() <= criteria.maxTimestamp();
128     }
129
130     @Override
131     public Future<Void> doSaveAsync(SnapshotMetadata snapshotMetadata, Object o) {
132         List<StoredSnapshot> snapshotList = snapshots.get(snapshotMetadata.persistenceId());
133
134         LOG.trace("doSaveAsync: persistentId {}: sequenceNr: {}: timestamp {}: {}", snapshotMetadata.persistenceId(),
135                 snapshotMetadata.sequenceNr(), snapshotMetadata.timestamp(), o);
136
137         if(snapshotList == null){
138             snapshotList = new ArrayList<>();
139             snapshots.put(snapshotMetadata.persistenceId(), snapshotList);
140         }
141         synchronized (snapshotList) {
142             snapshotList.add(new StoredSnapshot(snapshotMetadata, o));
143         }
144
145         CountDownLatch latch = snapshotSavedLatches.get(snapshotMetadata.persistenceId());
146         if(latch != null) {
147             latch.countDown();
148         }
149
150         return Futures.successful(null);
151     }
152
153     @Override
154     public void onSaved(SnapshotMetadata snapshotMetadata) throws Exception {
155     }
156
157     @Override
158     public void doDelete(SnapshotMetadata snapshotMetadata) throws Exception {
159         List<StoredSnapshot> snapshotList = snapshots.get(snapshotMetadata.persistenceId());
160
161         if(snapshotList == null){
162             return;
163         }
164
165         synchronized (snapshotList) {
166             for(int i=0;i<snapshotList.size(); i++){
167                 StoredSnapshot snapshot = snapshotList.get(i);
168                 if(snapshotMetadata.equals(snapshot.metadata)){
169                     snapshotList.remove(i);
170                     break;
171                 }
172             }
173         }
174     }
175
176     @Override
177     public void doDelete(String persistentId, SnapshotSelectionCriteria snapshotSelectionCriteria)
178             throws Exception {
179         LOG.trace("doDelete: persistentId {}: maxSequenceNr: {}: maxTimestamp {}", persistentId,
180                 snapshotSelectionCriteria.maxSequenceNr(), snapshotSelectionCriteria.maxTimestamp());
181
182         List<StoredSnapshot> snapshotList = snapshots.get(persistentId);
183         if(snapshotList != null){
184             synchronized (snapshotList) {
185                 Iterator<StoredSnapshot> iter = snapshotList.iterator();
186                 while(iter.hasNext()) {
187                     StoredSnapshot s = iter.next();
188                     if(matches(s, snapshotSelectionCriteria)) {
189                         LOG.trace("Deleting snapshot for sequenceNr: {}, timestamp: {}: {}",
190                                 s.metadata.sequenceNr(), s.metadata.timestamp(), s.data);
191
192                         iter.remove();
193                     }
194                 }
195             }
196         }
197
198         CountDownLatch latch = snapshotDeletedLatches.get(persistentId);
199         if(latch != null) {
200             latch.countDown();
201         }
202     }
203
204     private static class StoredSnapshot {
205         private final SnapshotMetadata metadata;
206         private final Object data;
207
208         private StoredSnapshot(SnapshotMetadata metadata, Object data) {
209             this.metadata = metadata;
210             this.data = data;
211         }
212     }
213 }