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_OWNERS_PATH;
17 import akka.actor.ActorRef;
18 import akka.actor.PoisonPill;
19 import akka.actor.Props;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Stopwatch;
22 import com.google.common.collect.ImmutableMap;
23 import com.google.common.util.concurrent.Uninterruptibles;
24 import java.util.Collections;
25 import java.util.List;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicReference;
30 import org.junit.After;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
34 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
35 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
36 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
37 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
38 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
39 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
40 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
41 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
42 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
43 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
44 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
45 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidate;
46 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
47 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import scala.concurrent.Await;
53 import scala.concurrent.Future;
54 import scala.concurrent.duration.Duration;
57 * Unit tests for DistributedEntityOwnershipService.
59 * @author Thomas Pantelis
61 public class DistributedEntityOwnershipServiceTest extends AbstractEntityOwnershipTest {
62 static String ENTITY_TYPE = "test";
63 static String ENTITY_TYPE2 = "test2";
64 static int ID_COUNTER = 1;
65 static final QName QNAME = QName.create("test", "2015-08-11", "foo");
67 private final String dataStoreType = "config" + ID_COUNTER++;
68 private DistributedDataStore dataStore;
72 DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
73 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
75 // FIXME - remove this MockConfiguration and use the production ConfigurationImpl class when the
76 // DistributedEntityOwnershipService is changed to setup the ShardStrategy for the entity-owners module.
77 MockConfiguration configuration = new MockConfiguration(Collections.<String, List<String>>emptyMap()) {
79 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
80 return Optional.of("entity-owners");
84 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
85 return ImmutableMap.<String, ShardStrategy>builder().put("entity-owners", new ShardStrategy() {
87 public String findShard(YangInstanceIdentifier path) {
88 return DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME;
94 dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, datastoreContext );
96 dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
98 ShardStrategyFactory.setConfiguration(configuration);
102 public void tearDown() {
103 dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
107 public void testEntityOwnershipShardCreated() throws Exception {
108 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
111 Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
112 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
113 ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
114 assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
120 public void testRegisterCandidate() throws Exception {
121 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
122 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
124 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
125 return shardPropsCreator;
131 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
133 YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
134 Entity entity = new Entity(ENTITY_TYPE, entityId);
135 EntityOwnershipCandidate candidate = mock(EntityOwnershipCandidate.class);
137 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity, candidate);
139 verifyEntityOwnershipCandidateRegistration(entity, reg);
140 verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
141 verifyEntityCandidate(readEntityOwners(service.getLocalEntityOwnershipShard()), ENTITY_TYPE, entityId,
142 dataStore.getActorContext().getCurrentMemberName());
144 // Register the same entity - should throw exception
146 EntityOwnershipCandidate candidate2 = mock(EntityOwnershipCandidate.class);
148 service.registerCandidate(entity, candidate2);
149 fail("Expected CandidateAlreadyRegisteredException");
150 } catch(CandidateAlreadyRegisteredException e) {
152 assertSame("getCandidate", candidate, e.getRegisteredCandidate());
153 assertEquals("getEntity", entity, e.getEntity());
156 // Register a different entity - should succeed
158 Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
159 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
161 EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2, candidate);
163 verifyEntityOwnershipCandidateRegistration(entity2, reg2);
164 verifyRegisterCandidateLocal(shardPropsCreator, entity2, candidate);
165 verifyEntityCandidate(readEntityOwners(service.getLocalEntityOwnershipShard()), ENTITY_TYPE2, entityId,
166 dataStore.getActorContext().getCurrentMemberName());
172 public void testCloseCandidateRegistration() throws Exception {
173 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
174 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
176 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
177 return shardPropsCreator;
183 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
185 Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
186 EntityOwnershipCandidate candidate = mock(EntityOwnershipCandidate.class);
188 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity, candidate);
190 verifyEntityOwnershipCandidateRegistration(entity, reg);
191 verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
193 shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
197 UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
198 assertEquals("getEntity", entity, unregCandidate.getEntity());
200 // Re-register - should succeed.
202 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
204 service.registerCandidate(entity, candidate);
206 verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
212 public void testRegisterListener() {
215 private NormalizedNode<?, ?> readEntityOwners(ActorRef shard) throws Exception {
216 Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
217 Stopwatch sw = Stopwatch.createStarted();
218 while(sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
219 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
220 Optional<NormalizedNode<?, ?>> optional = readTx.read(ENTITY_OWNERS_PATH).
221 checkedGet(5, TimeUnit.SECONDS);
222 if(optional.isPresent()) {
223 return optional.get();
226 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
232 private void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity,
233 EntityOwnershipCandidate candidate) {
234 RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
235 assertSame("getCandidate", candidate, regCandidate.getCandidate());
236 assertEquals("getEntity", entity, regCandidate.getEntity());
239 private void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
240 assertNotNull("EntityOwnershipCandidateRegistration null", reg);
241 assertEquals("getEntity", entity, reg.getEntity());
244 static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
245 TestShardPropsCreator() {
249 private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
250 private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
251 private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
254 public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
255 DatastoreContext datastoreContext, SchemaContext schemaContext) {
256 return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
257 schemaContext, "member-1", messageClass, messageReceived, receivedMessage);
260 @SuppressWarnings("unchecked")
261 <T> T waitForShardMessage() {
262 assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
263 Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
264 assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
265 return (T) receivedMessage.get();
268 void expectShardMessage(Class<?> ofType) {
269 messageReceived.set(new CountDownLatch(1));
270 receivedMessage.set(null);
271 messageClass.set(ofType);
275 static class TestEntityOwnershipShard extends EntityOwnershipShard {
276 private final AtomicReference<CountDownLatch> messageReceived;
277 private final AtomicReference<Object> receivedMessage;
278 private final AtomicReference<Class<?>> messageClass;
280 protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
281 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
282 AtomicReference<Class<?>> messageClass, AtomicReference<CountDownLatch> messageReceived,
283 AtomicReference<Object> receivedMessage) {
284 super(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
285 this.messageClass = messageClass;
286 this.messageReceived = messageReceived;
287 this.receivedMessage = receivedMessage;
291 public void onReceiveCommand(final Object message) throws Exception {
293 super.onReceiveCommand(message);
295 Class<?> expMsgClass = messageClass.get();
296 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
297 receivedMessage.set(message);
298 messageReceived.get().countDown();