Fix unit test CS warnings in sal-distributed-datastore
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / entityownership / AbstractEntityOwnershipTest.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.datastore.entityownership;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NAME_QNAME;
15 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_QNAME;
16 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
17 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_QNAME;
18 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_QNAME;
19 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPE_QNAME;
20 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
21 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
22
23 import akka.pattern.Patterns;
24 import akka.testkit.TestActorRef;
25 import akka.util.Timeout;
26 import com.google.common.base.Function;
27 import com.google.common.base.Optional;
28 import com.google.common.base.Stopwatch;
29 import com.google.common.util.concurrent.Uninterruptibles;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicInteger;
32 import java.util.function.Consumer;
33 import org.hamcrest.Description;
34 import org.junit.Assert;
35 import org.mockito.ArgumentMatcher;
36 import org.mockito.Matchers;
37 import org.opendaylight.controller.cluster.access.concepts.MemberName;
38 import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
39 import org.opendaylight.controller.cluster.datastore.AbstractShardTest;
40 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
41 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
42 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
43 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
44 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipChangeState;
45 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
46 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipChange;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.EntityOwners;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.entity.owners.EntityType;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.entity.owners.entity.type.entity.Candidate;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import scala.concurrent.Await;
66 import scala.concurrent.Future;
67 import scala.concurrent.duration.Duration;
68 import scala.concurrent.duration.FiniteDuration;
69
70 /**
71  * Abstract base class providing utility methods.
72  *
73  * @author Thomas Pantelis
74  */
75 public class AbstractEntityOwnershipTest extends AbstractActorTest {
76     protected final Logger testLog = LoggerFactory.getLogger(getClass());
77
78     private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
79
80     protected void verifyEntityCandidate(NormalizedNode<?, ?> node, String entityType,
81             YangInstanceIdentifier entityId, String candidateName, boolean expectPresent) {
82         try {
83             assertNotNull("Missing " + EntityOwners.QNAME.toString(), node);
84             assertTrue(node instanceof ContainerNode);
85
86             ContainerNode entityOwnersNode = (ContainerNode) node;
87
88             MapEntryNode entityTypeEntry = getMapEntryNodeChild(entityOwnersNode, EntityType.QNAME,
89                     ENTITY_TYPE_QNAME, entityType, true);
90
91             MapEntryNode entityEntry = getMapEntryNodeChild(entityTypeEntry, ENTITY_QNAME, ENTITY_ID_QNAME,
92                     entityId, true);
93
94             getMapEntryNodeChild(entityEntry, Candidate.QNAME, CANDIDATE_NAME_QNAME, candidateName, expectPresent);
95         } catch (AssertionError e) {
96             throw new AssertionError("Verification of entity candidate failed - returned data was: " + node, e);
97         }
98     }
99
100     protected void verifyEntityCandidate(String entityType, YangInstanceIdentifier entityId, String candidateName,
101             Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader, boolean expectPresent) {
102         AssertionError lastError = null;
103         Stopwatch sw = Stopwatch.createStarted();
104         while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
105             NormalizedNode<?, ?> node = reader.apply(ENTITY_OWNERS_PATH);
106             try {
107                 verifyEntityCandidate(node, entityType, entityId, candidateName, expectPresent);
108                 return;
109             } catch (AssertionError e) {
110                 lastError = e;
111                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
112             }
113         }
114
115         throw lastError;
116     }
117
118     protected void verifyEntityCandidate(String entityType, YangInstanceIdentifier entityId, String candidateName,
119             Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader) {
120         verifyEntityCandidate(entityType, entityId, candidateName, reader, true);
121     }
122
123     protected MapEntryNode getMapEntryNodeChild(DataContainerNode<? extends PathArgument> parent, QName childMap,
124             QName child, Object key, boolean expectPresent) {
125         Optional<DataContainerChild<? extends PathArgument, ?>> childNode =
126                 parent.getChild(new NodeIdentifier(childMap));
127         assertEquals("Missing " + childMap.toString(), true, childNode.isPresent());
128
129         MapNode entityTypeMapNode = (MapNode) childNode.get();
130         Optional<MapEntryNode> entityTypeEntry = entityTypeMapNode.getChild(new NodeIdentifierWithPredicates(
131                 childMap, child, key));
132         if (expectPresent && !entityTypeEntry.isPresent()) {
133             fail("Missing " + childMap.toString() + " entry for " + key + ". Actual: " + entityTypeMapNode.getValue());
134         } else if (!expectPresent && entityTypeEntry.isPresent()) {
135             fail("Found unexpected " + childMap.toString() + " entry for " + key);
136         }
137
138         return entityTypeEntry.isPresent() ? entityTypeEntry.get() : null;
139     }
140
141     static void verifyOwner(String expected, String entityType, YangInstanceIdentifier entityId,
142             Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader) {
143         AssertionError lastError = null;
144         YangInstanceIdentifier entityPath = entityPath(entityType, entityId).node(ENTITY_OWNER_QNAME);
145         Stopwatch sw = Stopwatch.createStarted();
146         while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
147             try {
148                 NormalizedNode<?, ?> node = reader.apply(entityPath);
149                 Assert.assertNotNull("Owner was not set for entityId: " + entityId, node);
150                 Assert.assertEquals("Entity owner", expected, node.getValue().toString());
151                 return;
152             } catch (AssertionError e) {
153                 lastError = e;
154                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
155             }
156         }
157
158         throw lastError;
159     }
160
161     @SuppressWarnings("checkstyle:IllegalCatch")
162     static void verifyOwner(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
163             YangInstanceIdentifier entityId, String localMemberName) {
164         verifyOwner(localMemberName, entityType, entityId, path -> {
165             try {
166                 return AbstractShardTest.readStore(shard, path);
167             } catch (Exception e) {
168                 return null;
169             }
170         });
171     }
172
173     protected void verifyNodeRemoved(YangInstanceIdentifier path,
174             Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader) {
175         AssertionError lastError = null;
176         Stopwatch sw = Stopwatch.createStarted();
177         while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
178             try {
179                 NormalizedNode<?, ?> node = reader.apply(path);
180                 Assert.assertNull("Node was not removed at path: " + path, node);
181                 return;
182             } catch (AssertionError e) {
183                 lastError = e;
184                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
185             }
186         }
187
188         throw lastError;
189     }
190
191     static void writeNode(YangInstanceIdentifier path, NormalizedNode<?, ?> node, ShardDataTree shardDataTree)
192             throws DataValidationFailedException {
193         DataTreeModification modification = shardDataTree.newModification();
194         modification.merge(path, node);
195         commit(shardDataTree, modification);
196     }
197
198     static void deleteNode(YangInstanceIdentifier path, ShardDataTree shardDataTree)
199             throws DataValidationFailedException {
200         DataTreeModification modification = shardDataTree.newModification();
201         modification.delete(path);
202         commit(shardDataTree, modification);
203     }
204
205     static void commit(ShardDataTree shardDataTree, DataTreeModification modification)
206             throws DataValidationFailedException {
207         shardDataTree.notifyListeners(shardDataTree.commit(modification));
208     }
209
210     static DOMEntityOwnershipChange ownershipChange(final DOMEntity expEntity, final boolean expWasOwner,
211             final boolean expIsOwner, final boolean expHasOwner) {
212         return ownershipChange(expEntity, expWasOwner, expIsOwner, expHasOwner, false);
213     }
214
215     static DOMEntityOwnershipChange ownershipChange(final DOMEntity expEntity, final boolean expWasOwner,
216             final boolean expIsOwner, final boolean expHasOwner, final boolean expInJeopardy) {
217         return Matchers.argThat(new ArgumentMatcher<DOMEntityOwnershipChange>() {
218             @Override
219             public boolean matches(Object argument) {
220                 DOMEntityOwnershipChange change = (DOMEntityOwnershipChange) argument;
221                 return expEntity.equals(change.getEntity()) && expWasOwner == change.getState().wasOwner()
222                         && expIsOwner == change.getState().isOwner() && expHasOwner == change.getState().hasOwner()
223                         && expInJeopardy == change.inJeopardy();
224             }
225
226             @Override
227             public void describeTo(Description description) {
228                 description.appendValue(new DOMEntityOwnershipChange(expEntity, EntityOwnershipChangeState.from(
229                         expWasOwner, expIsOwner, expHasOwner), expInJeopardy));
230             }
231         });
232     }
233
234     static DOMEntityOwnershipChange ownershipChange(final DOMEntity expEntity) {
235         return Matchers.argThat(new ArgumentMatcher<DOMEntityOwnershipChange>() {
236             @Override
237             public boolean matches(Object argument) {
238                 DOMEntityOwnershipChange change = (DOMEntityOwnershipChange) argument;
239                 return expEntity.equals(change.getEntity());
240             }
241
242             @Override
243             public void describeTo(Description description) {
244                 description.appendValue(new DOMEntityOwnershipChange(expEntity, EntityOwnershipChangeState.from(
245                         false, false, false)));
246             }
247         });
248     }
249
250     @SuppressWarnings("checkstyle:IllegalCatch")
251     static void verifyNoOwnerSet(TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
252             YangInstanceIdentifier entityId) {
253         YangInstanceIdentifier entityPath = entityPath(entityType, entityId).node(ENTITY_OWNER_QNAME);
254         try {
255             NormalizedNode<?, ?> node = AbstractShardTest.readStore(shard, entityPath);
256             if (node != null) {
257                 Assert.fail("Owner " + node.getValue() + " was set for " + entityPath);
258             }
259
260         } catch (Exception e) {
261             throw new AssertionError("read failed", e);
262         }
263     }
264
265     static void verifyRaftState(final TestActorRef<? extends EntityOwnershipShard> shard,
266             Consumer<OnDemandRaftState> verifier)
267             throws Exception {
268         AssertionError lastError = null;
269         Stopwatch sw = Stopwatch.createStarted();
270         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
271             FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
272             Future<Object> future = Patterns.ask(shard, GetOnDemandRaftState.INSTANCE, new Timeout(operationDuration));
273             OnDemandRaftState raftState = (OnDemandRaftState)Await.result(future, operationDuration);
274             try {
275                 verifier.accept(raftState);
276                 return;
277             } catch (AssertionError e) {
278                 lastError = e;
279                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
280             }
281         }
282
283         throw lastError;
284     }
285
286     static ShardIdentifier newShardId(String memberName) {
287         return ShardIdentifier.create("entity-ownership", MemberName.forName(memberName),
288             "operational" + NEXT_SHARD_NUM.getAndIncrement());
289     }
290
291     @SuppressWarnings("checkstyle:IllegalCatch")
292     void verifyEntityCandidateRemoved(final TestActorRef<EntityOwnershipShard> shard, String entityType,
293             YangInstanceIdentifier entityId, String candidateName) {
294         verifyNodeRemoved(candidatePath(entityType, entityId, candidateName), path -> {
295             try {
296                 return AbstractShardTest.readStore(shard, path);
297             } catch (Exception e) {
298                 throw new AssertionError("Failed to read " + path, e);
299             }
300         });
301     }
302
303     @SuppressWarnings("checkstyle:IllegalCatch")
304     void verifyCommittedEntityCandidate(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
305             YangInstanceIdentifier entityId, String candidateName) {
306         verifyEntityCandidate(entityType, entityId, candidateName, path -> {
307             try {
308                 return AbstractShardTest.readStore(shard, path);
309             } catch (Exception e) {
310                 throw new AssertionError("Failed to read " + path, e);
311             }
312         });
313     }
314
315     @SuppressWarnings("checkstyle:IllegalCatch")
316     void verifyNoEntityCandidate(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
317             YangInstanceIdentifier entityId, String candidateName) {
318         verifyEntityCandidate(entityType, entityId, candidateName, path -> {
319             try {
320                 return AbstractShardTest.readStore(shard, path);
321             } catch (Exception e) {
322                 throw new AssertionError("Failed to read " + path, e);
323             }
324         }, false);
325     }
326 }