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.assertSame;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.mockito.Mockito.mock;
16 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_QNAME;
17 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
18 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_QNAME;
19 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityEntryWithOwner;
20 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithEntityTypeEntry;
21 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
22 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityTypeEntryWithEntityEntry;
23 import akka.actor.ActorRef;
24 import akka.actor.PoisonPill;
25 import akka.actor.Props;
26 import com.google.common.base.Function;
27 import com.google.common.base.Optional;
28 import com.google.common.util.concurrent.Uninterruptibles;
29 import java.util.Collections;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.atomic.AtomicReference;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
38 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
39 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
40 import org.opendaylight.controller.cluster.datastore.config.Configuration;
41 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
42 import org.opendaylight.controller.cluster.datastore.config.ModuleConfig;
43 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfigProvider;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
48 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
49 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
50 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
51 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
52 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
53 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
54 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
55 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
56 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
57 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
58 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import scala.concurrent.Await;
66 import scala.concurrent.Future;
67 import scala.concurrent.duration.Duration;
70 * Unit tests for DistributedEntityOwnershipService.
72 * @author Thomas Pantelis
74 public class DistributedEntityOwnershipServiceTest extends AbstractEntityOwnershipTest {
75 static String ENTITY_TYPE = "test";
76 static String ENTITY_TYPE2 = "test2";
77 static int ID_COUNTER = 1;
78 static final QName QNAME = QName.create("test", "2015-08-11", "foo");
80 private final String dataStoreType = "config" + ID_COUNTER++;
81 private DistributedDataStore dataStore;
85 DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
86 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
88 Configuration configuration = new ConfigurationImpl(new ModuleShardConfigProvider() {
90 public Map<String, ModuleConfig> retrieveModuleConfigs(Configuration configuration) {
91 return Collections.emptyMap();
95 dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, datastoreContext );
97 dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
101 public void tearDown() {
102 dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
106 public void testEntityOwnershipShardCreated() throws Exception {
107 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
110 Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
111 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
112 ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
113 assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
119 public void testRegisterCandidate() throws Exception {
120 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
121 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
123 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
124 return shardPropsCreator;
130 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
132 YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
133 Entity entity = new Entity(ENTITY_TYPE, entityId);
135 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
137 verifyEntityOwnershipCandidateRegistration(entity, reg);
138 verifyRegisterCandidateLocal(shardPropsCreator, entity);
139 verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE, entityId,
140 dataStore.getActorContext().getCurrentMemberName());
142 // Register the same entity - should throw exception
145 service.registerCandidate(entity);
146 fail("Expected CandidateAlreadyRegisteredException");
147 } catch(CandidateAlreadyRegisteredException e) {
149 assertEquals("getEntity", entity, e.getEntity());
152 // Register a different entity - should succeed
154 Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
155 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
157 EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
159 verifyEntityOwnershipCandidateRegistration(entity2, reg2);
160 verifyRegisterCandidateLocal(shardPropsCreator, entity2);
161 verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
162 dataStore.getActorContext().getCurrentMemberName());
168 public void testCloseCandidateRegistration() throws Exception {
169 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
170 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
172 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
173 return shardPropsCreator;
179 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
181 Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
183 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
185 verifyEntityOwnershipCandidateRegistration(entity, reg);
186 verifyRegisterCandidateLocal(shardPropsCreator, entity);
188 shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
192 UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
193 assertEquals("getEntity", entity, unregCandidate.getEntity());
195 // Re-register - should succeed.
197 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
199 service.registerCandidate(entity);
201 verifyRegisterCandidateLocal(shardPropsCreator, entity);
207 public void testListenerRegistration() {
208 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
209 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
211 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
212 return shardPropsCreator;
218 shardPropsCreator.expectShardMessage(RegisterListenerLocal.class);
220 YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
221 Entity entity = new Entity(ENTITY_TYPE, entityId);
222 EntityOwnershipListener listener = mock(EntityOwnershipListener.class);
224 EntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
226 assertNotNull("EntityOwnershipListenerRegistration null", reg);
227 assertEquals("getEntityType", entity.getType(), reg.getEntityType());
228 assertEquals("getInstance", listener, reg.getInstance());
230 RegisterListenerLocal regListener = shardPropsCreator.waitForShardMessage();
231 assertSame("getListener", listener, regListener.getListener());
232 assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
234 shardPropsCreator.expectShardMessage(UnregisterListenerLocal.class);
238 UnregisterListenerLocal unregListener = shardPropsCreator.waitForShardMessage();
239 assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
240 assertSame("getListener", listener, unregListener.getListener());
246 public void testGetOwnershipState() throws Exception {
247 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
248 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
250 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
251 return shardPropsCreator;
257 ShardDataTree shardDataTree = new ShardDataTree(SchemaContextHelper.entityOwners());
258 shardPropsCreator.setDataTree(shardDataTree.getDataTree());
260 Entity entity1 = new Entity(ENTITY_TYPE, "one");
261 writeNode(ENTITY_OWNERS_PATH, entityOwnersWithEntityTypeEntry(entityTypeEntryWithEntityEntry(entity1.getType(),
262 entityEntryWithOwner(entity1.getId(), "member-1"))), shardDataTree);
263 verifyGetOwnershipState(service, entity1, true, true);
265 writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), "member-2"),
267 verifyGetOwnershipState(service, entity1, false, true);
269 writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), ""),
271 verifyGetOwnershipState(service, entity1, false, false);
273 Entity entity2 = new Entity(ENTITY_TYPE, "two");
274 Optional<EntityOwnershipState> state = service.getOwnershipState(entity2);
275 assertEquals("getOwnershipState present", false, state.isPresent());
277 writeNode(entityPath(entity2.getType(), entity2.getId()), ImmutableNodes.mapEntry(ENTITY_QNAME,
278 ENTITY_ID_QNAME, entity2.getId()), shardDataTree);
279 verifyGetOwnershipState(service, entity2, false, false);
284 private void verifyGetOwnershipState(DistributedEntityOwnershipService service, Entity entity,
285 boolean isOwner, boolean hasOwner) {
286 Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
287 assertEquals("getOwnershipState present", true, state.isPresent());
288 assertEquals("isOwner", isOwner, state.get().isOwner());
289 assertEquals("hasOwner", hasOwner, state.get().hasOwner());
292 private void verifyEntityCandidate(ActorRef entityOwnershipShard, String entityType,
293 YangInstanceIdentifier entityId, String candidateName) {
294 verifyEntityCandidate(entityType, entityId, candidateName,
295 new Function<YangInstanceIdentifier, NormalizedNode<?,?>>() {
297 public NormalizedNode<?, ?> apply(YangInstanceIdentifier path) {
299 return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
300 } catch (Exception e) {
307 private void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity) {
308 RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
309 assertEquals("getEntity", entity, regCandidate.getEntity());
312 private void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
313 assertNotNull("EntityOwnershipCandidateRegistration null", reg);
314 assertEquals("getInstance", entity, reg.getInstance());
317 static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
318 TestShardPropsCreator() {
319 super("member-1", EntityOwnerSelectionStrategyConfig.newBuilder().build());
322 private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
323 private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
324 private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
325 private final AtomicReference<DataTree> dataTree = new AtomicReference<>();
328 public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
329 DatastoreContext datastoreContext, SchemaContext schemaContext) {
330 return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
331 schemaContext, "member-1", messageClass, messageReceived, receivedMessage, dataTree);
334 @SuppressWarnings("unchecked")
335 <T> T waitForShardMessage() {
336 assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
337 Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
338 assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
339 return (T) receivedMessage.get();
342 void expectShardMessage(Class<?> ofType) {
343 messageReceived.set(new CountDownLatch(1));
344 receivedMessage.set(null);
345 messageClass.set(ofType);
348 void setDataTree(DataTree tree) {
349 this.dataTree.set(tree);
353 static class TestEntityOwnershipShard extends EntityOwnershipShard {
354 private final AtomicReference<CountDownLatch> messageReceived;
355 private final AtomicReference<Object> receivedMessage;
356 private final AtomicReference<Class<?>> messageClass;
357 private final AtomicReference<DataTree> dataTree;
359 protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
360 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
361 AtomicReference<Class<?>> messageClass, AtomicReference<CountDownLatch> messageReceived,
362 AtomicReference<Object> receivedMessage, AtomicReference<DataTree> dataTree) {
363 super(name, peerAddresses, datastoreContext, schemaContext, localMemberName, EntityOwnerSelectionStrategyConfig.newBuilder().build());
364 this.messageClass = messageClass;
365 this.messageReceived = messageReceived;
366 this.receivedMessage = receivedMessage;
367 this.dataTree = dataTree;
371 public void onReceiveCommand(final Object message) throws Exception {
373 if(dataTree.get() != null && message instanceof GetShardDataTree) {
374 sender().tell(dataTree.get(), self());
376 super.onReceiveCommand(message);
379 Class<?> expMsgClass = messageClass.get();
380 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
381 receivedMessage.set(message);
382 messageReceived.get().countDown();