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 akka.actor.ActorRef;
17 import akka.actor.PoisonPill;
18 import akka.actor.Props;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Stopwatch;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.util.concurrent.Uninterruptibles;
23 import java.util.Collections;
24 import java.util.List;
26 import java.util.concurrent.CountDownLatch;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.atomic.AtomicReference;
29 import org.junit.After;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
33 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
34 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
35 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
36 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
37 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
38 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
39 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
40 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
41 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
42 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
43 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
44 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidate;
45 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
46 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import scala.concurrent.Await;
52 import scala.concurrent.Future;
53 import scala.concurrent.duration.Duration;
56 * Unit tests for DistributedEntityOwnershipService.
58 * @author Thomas Pantelis
60 public class DistributedEntityOwnershipServiceTest extends AbstractEntityOwnershipTest {
61 static String ENTITY_TYPE = "test";
62 static String ENTITY_TYPE2 = "test2";
63 static int ID_COUNTER = 1;
64 static final QName QNAME = QName.create("test", "2015-08-11", "foo");
66 private final String dataStoreType = "config" + ID_COUNTER++;
67 private DistributedDataStore dataStore;
71 DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
72 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
74 // FIXME - remove this MockConfiguration and use the production ConfigurationImpl class when the
75 // DistributedEntityOwnershipService is changed to setup the ShardStrategy for the entity-owners module.
76 MockConfiguration configuration = new MockConfiguration(Collections.<String, List<String>>emptyMap()) {
78 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
79 return Optional.of("entity-owners");
83 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
84 return ImmutableMap.<String, ShardStrategy>builder().put("entity-owners", new ShardStrategy() {
86 public String findShard(YangInstanceIdentifier path) {
87 return DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME;
93 dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, datastoreContext );
95 dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
97 ShardStrategyFactory.setConfiguration(configuration);
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);
134 EntityOwnershipCandidate candidate = mock(EntityOwnershipCandidate.class);
136 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity, candidate);
138 verifyEntityOwnershipCandidateRegistration(entity, reg);
139 verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
140 verifyEntityCandidate(readEntityOwners(service.getLocalEntityOwnershipShard()), ENTITY_TYPE, entityId,
141 dataStore.getActorContext().getCurrentMemberName());
143 // Register the same entity - should throw exception
145 EntityOwnershipCandidate candidate2 = mock(EntityOwnershipCandidate.class);
147 service.registerCandidate(entity, candidate2);
148 fail("Expected CandidateAlreadyRegisteredException");
149 } catch(CandidateAlreadyRegisteredException e) {
151 assertSame("getCandidate", candidate, e.getRegisteredCandidate());
152 assertEquals("getEntity", entity, e.getEntity());
155 // Register a different entity - should succeed
157 Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
158 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
160 EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2, candidate);
162 verifyEntityOwnershipCandidateRegistration(entity2, reg2);
163 verifyRegisterCandidateLocal(shardPropsCreator, entity2, candidate);
164 verifyEntityCandidate(readEntityOwners(service.getLocalEntityOwnershipShard()), ENTITY_TYPE2, entityId,
165 dataStore.getActorContext().getCurrentMemberName());
171 public void testCloseCandidateRegistration() throws Exception {
172 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
173 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
175 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
176 return shardPropsCreator;
182 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
184 Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
185 EntityOwnershipCandidate candidate = mock(EntityOwnershipCandidate.class);
187 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity, candidate);
189 verifyEntityOwnershipCandidateRegistration(entity, reg);
190 verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
192 shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
196 UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
197 assertEquals("getEntity", entity, unregCandidate.getEntity());
199 // Re-register - should succeed.
201 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
203 service.registerCandidate(entity, candidate);
205 verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
211 public void testRegisterListener() {
214 private NormalizedNode<?, ?> readEntityOwners(ActorRef shard) throws Exception {
215 Stopwatch sw = Stopwatch.createStarted();
216 while(sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
217 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
218 Optional<NormalizedNode<?, ?>> optional = readTx.read(EntityOwnershipShard.ENTITY_OWNERS_PATH).
219 checkedGet(5, TimeUnit.SECONDS);
220 if(optional.isPresent()) {
221 return optional.get();
224 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
230 private void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity,
231 EntityOwnershipCandidate candidate) {
232 RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
233 assertSame("getCandidate", candidate, regCandidate.getCandidate());
234 assertEquals("getEntity", entity, regCandidate.getEntity());
237 private void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
238 assertNotNull("EntityOwnershipCandidateRegistration null", reg);
239 assertEquals("getEntity", entity, reg.getEntity());
242 static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
243 TestShardPropsCreator() {
247 private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
248 private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
249 private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
252 public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
253 DatastoreContext datastoreContext, SchemaContext schemaContext) {
254 return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
255 schemaContext, "member-1", messageClass, messageReceived, receivedMessage);
258 @SuppressWarnings("unchecked")
259 <T> T waitForShardMessage() {
260 assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
261 Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
262 assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
263 return (T) receivedMessage.get();
266 void expectShardMessage(Class<?> ofType) {
267 messageReceived.set(new CountDownLatch(1));
268 receivedMessage.set(null);
269 messageClass.set(ofType);
273 static class TestEntityOwnershipShard extends EntityOwnershipShard {
274 private final AtomicReference<CountDownLatch> messageReceived;
275 private final AtomicReference<Object> receivedMessage;
276 private final AtomicReference<Class<?>> messageClass;
278 protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
279 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
280 AtomicReference<Class<?>> messageClass, AtomicReference<CountDownLatch> messageReceived,
281 AtomicReference<Object> receivedMessage) {
282 super(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
283 this.messageClass = messageClass;
284 this.messageReceived = messageReceived;
285 this.receivedMessage = receivedMessage;
289 public void onReceiveCommand(final Object message) throws Exception {
291 super.onReceiveCommand(message);
293 Class<?> expMsgClass = messageClass.get();
294 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
295 receivedMessage.set(message);
296 messageReceived.get().countDown();