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.datastore.entityownership;
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;
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;
71 * Abstract base class providing utility methods.
73 * @author Thomas Pantelis
75 public class AbstractEntityOwnershipTest extends AbstractActorTest {
76 protected final Logger testLog = LoggerFactory.getLogger(getClass());
78 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
80 protected void verifyEntityCandidate(NormalizedNode<?, ?> node, String entityType,
81 YangInstanceIdentifier entityId, String candidateName, boolean expectPresent) {
83 assertNotNull("Missing " + EntityOwners.QNAME.toString(), node);
84 assertTrue(node instanceof ContainerNode);
86 ContainerNode entityOwnersNode = (ContainerNode) node;
88 MapEntryNode entityTypeEntry = getMapEntryNodeChild(entityOwnersNode, EntityType.QNAME,
89 ENTITY_TYPE_QNAME, entityType, true);
91 MapEntryNode entityEntry = getMapEntryNodeChild(entityTypeEntry, ENTITY_QNAME, ENTITY_ID_QNAME,
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);
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);
107 verifyEntityCandidate(node, entityType, entityId, candidateName, expectPresent);
109 } catch (AssertionError e) {
111 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
118 protected void verifyEntityCandidate(String entityType, YangInstanceIdentifier entityId, String candidateName,
119 Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader) {
120 verifyEntityCandidate(entityType, entityId, candidateName, reader, true);
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());
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);
138 return entityTypeEntry.isPresent() ? entityTypeEntry.get() : null;
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) {
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());
152 } catch (AssertionError e) {
154 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
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 -> {
166 return AbstractShardTest.readStore(shard, path);
167 } catch (Exception e) {
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) {
179 NormalizedNode<?, ?> node = reader.apply(path);
180 Assert.assertNull("Node was not removed at path: " + path, node);
182 } catch (AssertionError e) {
184 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
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);
198 static void deleteNode(YangInstanceIdentifier path, ShardDataTree shardDataTree)
199 throws DataValidationFailedException {
200 DataTreeModification modification = shardDataTree.newModification();
201 modification.delete(path);
202 commit(shardDataTree, modification);
205 static void commit(ShardDataTree shardDataTree, DataTreeModification modification)
206 throws DataValidationFailedException {
207 shardDataTree.notifyListeners(shardDataTree.commit(modification));
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);
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>() {
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();
227 public void describeTo(Description description) {
228 description.appendValue(new DOMEntityOwnershipChange(expEntity, EntityOwnershipChangeState.from(
229 expWasOwner, expIsOwner, expHasOwner), expInJeopardy));
234 static DOMEntityOwnershipChange ownershipChange(final DOMEntity expEntity) {
235 return Matchers.argThat(new ArgumentMatcher<DOMEntityOwnershipChange>() {
237 public boolean matches(Object argument) {
238 DOMEntityOwnershipChange change = (DOMEntityOwnershipChange) argument;
239 return expEntity.equals(change.getEntity());
243 public void describeTo(Description description) {
244 description.appendValue(new DOMEntityOwnershipChange(expEntity, EntityOwnershipChangeState.from(
245 false, false, false)));
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);
255 NormalizedNode<?, ?> node = AbstractShardTest.readStore(shard, entityPath);
257 Assert.fail("Owner " + node.getValue() + " was set for " + entityPath);
260 } catch (Exception e) {
261 throw new AssertionError("read failed", e);
265 static void verifyRaftState(final TestActorRef<? extends EntityOwnershipShard> shard,
266 Consumer<OnDemandRaftState> verifier)
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);
275 verifier.accept(raftState);
277 } catch (AssertionError e) {
279 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
286 static ShardIdentifier newShardId(String memberName) {
287 return ShardIdentifier.create("entity-ownership", MemberName.forName(memberName),
288 "operational" + NEXT_SHARD_NUM.getAndIncrement());
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 -> {
296 return AbstractShardTest.readStore(shard, path);
297 } catch (Exception e) {
298 throw new AssertionError("Failed to read " + path, e);
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 -> {
308 return AbstractShardTest.readStore(shard, path);
309 } catch (Exception e) {
310 throw new AssertionError("Failed to read " + path, e);
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 -> {
320 return AbstractShardTest.readStore(shard, path);
321 } catch (Exception e) {
322 throw new AssertionError("Failed to read " + path, e);