c1c16a98b9b8bac2a965c1038ce0a59f8199b15f
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / entityownership / DistributedEntityOwnershipServiceTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.entityownership;
9
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.Function;
20 import com.google.common.util.concurrent.Uninterruptibles;
21 import java.util.Collections;
22 import java.util.Map;
23 import java.util.concurrent.CountDownLatch;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.atomic.AtomicReference;
26 import org.junit.After;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
30 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
31 import org.opendaylight.controller.cluster.datastore.config.Configuration;
32 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
33 import org.opendaylight.controller.cluster.datastore.config.ModuleConfig;
34 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfigProvider;
35 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
36 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
37 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
38 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
39 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
40 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
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.EntityOwnershipCandidateRegistration;
45 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
46 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
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;
54
55 /**
56  * Unit tests for DistributedEntityOwnershipService.
57  *
58  * @author Thomas Pantelis
59  */
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");
65
66     private final String dataStoreType = "config" + ID_COUNTER++;
67     private DistributedDataStore dataStore;
68
69     @Before
70     public void setUp() {
71         DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
72                 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
73
74         Configuration configuration = new ConfigurationImpl(new ModuleShardConfigProvider() {
75             @Override
76             public Map<String, ModuleConfig> retrieveModuleConfigs(Configuration configuration) {
77                 return Collections.emptyMap();
78             }
79         });
80
81         dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, datastoreContext );
82
83         dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
84     }
85
86     @After
87     public void tearDown() {
88         dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
89     }
90
91     @Test
92     public void testEntityOwnershipShardCreated() throws Exception {
93         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
94         service.start();
95
96         Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
97                 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
98         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
99         assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
100
101         service.close();
102     }
103
104     @Test
105     public void testRegisterCandidate() throws Exception {
106         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
107         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
108             @Override
109             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
110                 return shardPropsCreator;
111             }
112         };
113
114         service.start();
115
116         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
117
118         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
119         Entity entity = new Entity(ENTITY_TYPE, entityId);
120
121         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
122
123         verifyEntityOwnershipCandidateRegistration(entity, reg);
124         verifyRegisterCandidateLocal(shardPropsCreator, entity);
125         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE, entityId,
126                 dataStore.getActorContext().getCurrentMemberName());
127
128         // Register the same entity - should throw exception
129
130         try {
131             service.registerCandidate(entity);
132             fail("Expected CandidateAlreadyRegisteredException");
133         } catch(CandidateAlreadyRegisteredException e) {
134             // expected
135             assertEquals("getEntity", entity, e.getEntity());
136         }
137
138         // Register a different entity - should succeed
139
140         Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
141         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
142
143         EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
144
145         verifyEntityOwnershipCandidateRegistration(entity2, reg2);
146         verifyRegisterCandidateLocal(shardPropsCreator, entity2);
147         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
148                 dataStore.getActorContext().getCurrentMemberName());
149
150         service.close();
151     }
152
153     @Test
154     public void testCloseCandidateRegistration() throws Exception {
155         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
156         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
157             @Override
158             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
159                 return shardPropsCreator;
160             }
161         };
162
163         service.start();
164
165         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
166
167         Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
168
169         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
170
171         verifyEntityOwnershipCandidateRegistration(entity, reg);
172         verifyRegisterCandidateLocal(shardPropsCreator, entity);
173
174         shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
175
176         reg.close();
177
178         UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
179         assertEquals("getEntity", entity, unregCandidate.getEntity());
180
181         // Re-register - should succeed.
182
183         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
184
185         service.registerCandidate(entity);
186
187         verifyRegisterCandidateLocal(shardPropsCreator, entity);
188
189         service.close();
190     }
191
192     @Test
193     public void testListenerRegistration() {
194         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
195         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
196             @Override
197             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
198                 return shardPropsCreator;
199             }
200         };
201
202         service.start();
203
204         shardPropsCreator.expectShardMessage(RegisterListenerLocal.class);
205
206         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
207         Entity entity = new Entity(ENTITY_TYPE, entityId);
208         EntityOwnershipListener listener = mock(EntityOwnershipListener.class);
209
210         EntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
211
212         assertNotNull("EntityOwnershipListenerRegistration null", reg);
213         assertEquals("getEntityType", entity.getType(), reg.getEntityType());
214         assertEquals("getInstance", listener, reg.getInstance());
215
216         RegisterListenerLocal regListener = shardPropsCreator.waitForShardMessage();
217         assertSame("getListener", listener, regListener.getListener());
218         assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
219
220         shardPropsCreator.expectShardMessage(UnregisterListenerLocal.class);
221
222         reg.close();
223
224         UnregisterListenerLocal unregListener = shardPropsCreator.waitForShardMessage();
225         assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
226         assertSame("getListener", listener, unregListener.getListener());
227
228         service.close();
229     }
230
231     private void verifyEntityCandidate(ActorRef entityOwnershipShard, String entityType,
232             YangInstanceIdentifier entityId, String candidateName) {
233         verifyEntityCandidate(entityType, entityId, candidateName,
234                 new Function<YangInstanceIdentifier, NormalizedNode<?,?>>() {
235                     @Override
236                     public NormalizedNode<?, ?> apply(YangInstanceIdentifier path) {
237                         try {
238                             return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
239                         } catch (Exception e) {
240                             return null;
241                         }
242                     }
243                 });
244     }
245
246     private void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity) {
247         RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
248         assertEquals("getEntity", entity, regCandidate.getEntity());
249     }
250
251     private void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
252         assertNotNull("EntityOwnershipCandidateRegistration null", reg);
253         assertEquals("getInstance", entity, reg.getInstance());
254     }
255
256     static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
257         TestShardPropsCreator() {
258             super("member-1");
259         }
260
261         private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
262         private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
263         private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
264
265         @Override
266         public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
267                 DatastoreContext datastoreContext, SchemaContext schemaContext) {
268             return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
269                     schemaContext, "member-1", messageClass, messageReceived, receivedMessage);
270         }
271
272         @SuppressWarnings("unchecked")
273         <T> T waitForShardMessage() {
274             assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
275                     Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
276             assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
277             return (T) receivedMessage.get();
278         }
279
280         void expectShardMessage(Class<?> ofType) {
281             messageReceived.set(new CountDownLatch(1));
282             receivedMessage.set(null);
283             messageClass.set(ofType);
284         }
285     }
286
287     static class TestEntityOwnershipShard extends EntityOwnershipShard {
288         private final AtomicReference<CountDownLatch> messageReceived;
289         private final AtomicReference<Object> receivedMessage;
290         private final AtomicReference<Class<?>> messageClass;
291
292         protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
293                 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
294                 AtomicReference<Class<?>> messageClass, AtomicReference<CountDownLatch> messageReceived,
295                 AtomicReference<Object> receivedMessage) {
296             super(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
297             this.messageClass = messageClass;
298             this.messageReceived = messageReceived;
299             this.receivedMessage = receivedMessage;
300         }
301
302         @Override
303         public void onReceiveCommand(final Object message) throws Exception {
304             try {
305                 super.onReceiveCommand(message);
306             } finally {
307                 Class<?> expMsgClass = messageClass.get();
308                 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
309                     receivedMessage.set(message);
310                     messageReceived.get().countDown();
311                 }
312             }
313         }
314     }
315 }