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.mockito.Mockito;
38 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
39 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
40 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
41 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
42 import org.opendaylight.controller.cluster.datastore.config.Configuration;
43 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
44 import org.opendaylight.controller.cluster.datastore.config.ModuleConfig;
45 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfigProvider;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
49 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
50 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
51 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
52 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
53 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
54 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
55 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
56 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
57 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
58 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
59 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
64 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import scala.concurrent.Await;
67 import scala.concurrent.Future;
68 import scala.concurrent.duration.Duration;
71 * Unit tests for DistributedEntityOwnershipService.
73 * @author Thomas Pantelis
75 public class DistributedEntityOwnershipServiceTest extends AbstractEntityOwnershipTest {
76 static String ENTITY_TYPE = "test";
77 static String ENTITY_TYPE2 = "test2";
78 static int ID_COUNTER = 1;
79 static final QName QNAME = QName.create("test", "2015-08-11", "foo");
81 private final String dataStoreType = "config" + ID_COUNTER++;
82 private DistributedDataStore dataStore;
86 DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
87 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
89 Configuration configuration = new ConfigurationImpl(new ModuleShardConfigProvider() {
91 public Map<String, ModuleConfig> retrieveModuleConfigs(Configuration configuration) {
92 return Collections.emptyMap();
96 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
97 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
98 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
100 dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, mockContextFactory);
102 dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
106 public void tearDown() {
107 dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
111 public void testEntityOwnershipShardCreated() throws Exception {
112 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
115 Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
116 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
117 ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
118 assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
124 public void testRegisterCandidate() throws Exception {
125 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
126 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
128 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
129 return shardPropsCreator;
135 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
137 YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
138 Entity entity = new Entity(ENTITY_TYPE, entityId);
140 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
142 verifyEntityOwnershipCandidateRegistration(entity, reg);
143 verifyRegisterCandidateLocal(shardPropsCreator, entity);
144 verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE, entityId,
145 dataStore.getActorContext().getCurrentMemberName());
147 // Register the same entity - should throw exception
150 service.registerCandidate(entity);
151 fail("Expected CandidateAlreadyRegisteredException");
152 } catch(CandidateAlreadyRegisteredException e) {
154 assertEquals("getEntity", entity, e.getEntity());
157 // Register a different entity - should succeed
159 Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
160 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
162 EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
164 verifyEntityOwnershipCandidateRegistration(entity2, reg2);
165 verifyRegisterCandidateLocal(shardPropsCreator, entity2);
166 verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
167 dataStore.getActorContext().getCurrentMemberName());
173 public void testCloseCandidateRegistration() throws Exception {
174 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
175 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
177 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
178 return shardPropsCreator;
184 shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
186 Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
188 EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
190 verifyEntityOwnershipCandidateRegistration(entity, reg);
191 verifyRegisterCandidateLocal(shardPropsCreator, entity);
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);
206 verifyRegisterCandidateLocal(shardPropsCreator, entity);
212 public void testListenerRegistration() {
213 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
214 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
216 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
217 return shardPropsCreator;
223 shardPropsCreator.expectShardMessage(RegisterListenerLocal.class);
225 YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
226 Entity entity = new Entity(ENTITY_TYPE, entityId);
227 EntityOwnershipListener listener = mock(EntityOwnershipListener.class);
229 EntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
231 assertNotNull("EntityOwnershipListenerRegistration null", reg);
232 assertEquals("getEntityType", entity.getType(), reg.getEntityType());
233 assertEquals("getInstance", listener, reg.getInstance());
235 RegisterListenerLocal regListener = shardPropsCreator.waitForShardMessage();
236 assertSame("getListener", listener, regListener.getListener());
237 assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
239 shardPropsCreator.expectShardMessage(UnregisterListenerLocal.class);
243 UnregisterListenerLocal unregListener = shardPropsCreator.waitForShardMessage();
244 assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
245 assertSame("getListener", listener, unregListener.getListener());
251 public void testGetOwnershipState() throws Exception {
252 final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
253 DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
255 protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
256 return shardPropsCreator;
262 ShardDataTree shardDataTree = new ShardDataTree(SchemaContextHelper.entityOwners());
263 shardPropsCreator.setDataTree(shardDataTree.getDataTree());
265 Entity entity1 = new Entity(ENTITY_TYPE, "one");
266 writeNode(ENTITY_OWNERS_PATH, entityOwnersWithEntityTypeEntry(entityTypeEntryWithEntityEntry(entity1.getType(),
267 entityEntryWithOwner(entity1.getId(), "member-1"))), shardDataTree);
268 verifyGetOwnershipState(service, entity1, true, true);
270 writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), "member-2"),
272 verifyGetOwnershipState(service, entity1, false, true);
274 writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), ""),
276 verifyGetOwnershipState(service, entity1, false, false);
278 Entity entity2 = new Entity(ENTITY_TYPE, "two");
279 Optional<EntityOwnershipState> state = service.getOwnershipState(entity2);
280 assertEquals("getOwnershipState present", false, state.isPresent());
282 writeNode(entityPath(entity2.getType(), entity2.getId()), ImmutableNodes.mapEntry(ENTITY_QNAME,
283 ENTITY_ID_QNAME, entity2.getId()), shardDataTree);
284 verifyGetOwnershipState(service, entity2, false, false);
289 private static void verifyGetOwnershipState(DistributedEntityOwnershipService service, Entity entity,
290 boolean isOwner, boolean hasOwner) {
291 Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
292 assertEquals("getOwnershipState present", true, state.isPresent());
293 assertEquals("isOwner", isOwner, state.get().isOwner());
294 assertEquals("hasOwner", hasOwner, state.get().hasOwner());
297 private void verifyEntityCandidate(ActorRef entityOwnershipShard, String entityType,
298 YangInstanceIdentifier entityId, String candidateName) {
299 verifyEntityCandidate(entityType, entityId, candidateName,
300 new Function<YangInstanceIdentifier, NormalizedNode<?,?>>() {
302 public NormalizedNode<?, ?> apply(YangInstanceIdentifier path) {
304 return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
305 } catch (Exception e) {
312 private static void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity) {
313 RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
314 assertEquals("getEntity", entity, regCandidate.getEntity());
317 private static void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
318 assertNotNull("EntityOwnershipCandidateRegistration null", reg);
319 assertEquals("getInstance", entity, reg.getInstance());
322 static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
323 TestShardPropsCreator() {
327 private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
328 private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
329 private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
330 private final AtomicReference<DataTree> dataTree = new AtomicReference<>();
333 public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
334 DatastoreContext datastoreContext, SchemaContext schemaContext) {
335 return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
336 schemaContext, "member-1", messageClass, messageReceived, receivedMessage, dataTree);
339 @SuppressWarnings("unchecked")
340 <T> T waitForShardMessage() {
341 assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
342 Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
343 assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
344 return (T) receivedMessage.get();
347 void expectShardMessage(Class<?> ofType) {
348 messageReceived.set(new CountDownLatch(1));
349 receivedMessage.set(null);
350 messageClass.set(ofType);
353 void setDataTree(DataTree tree) {
354 this.dataTree.set(tree);
358 static class TestEntityOwnershipShard extends EntityOwnershipShard {
359 private final AtomicReference<CountDownLatch> messageReceived;
360 private final AtomicReference<Object> receivedMessage;
361 private final AtomicReference<Class<?>> messageClass;
362 private final AtomicReference<DataTree> dataTree;
364 protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
365 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
366 AtomicReference<Class<?>> messageClass, AtomicReference<CountDownLatch> messageReceived,
367 AtomicReference<Object> receivedMessage, AtomicReference<DataTree> dataTree) {
368 super(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
369 this.messageClass = messageClass;
370 this.messageReceived = messageReceived;
371 this.receivedMessage = receivedMessage;
372 this.dataTree = dataTree;
376 public void onReceiveCommand(final Object message) throws Exception {
378 if(dataTree.get() != null && message instanceof GetShardDataTree) {
379 sender().tell(dataTree.get(), self());
381 super.onReceiveCommand(message);
384 Class<?> expMsgClass = messageClass.get();
385 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
386 receivedMessage.set(message);
387 messageReceived.get().countDown();