Bug 4149: Implement per-shard DatastoreContext settings
[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 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;
30 import java.util.Map;
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;
69
70 /**
71  * Unit tests for DistributedEntityOwnershipService.
72  *
73  * @author Thomas Pantelis
74  */
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");
80
81     private final String dataStoreType = "config" + ID_COUNTER++;
82     private DistributedDataStore dataStore;
83
84     @Before
85     public void setUp() {
86         DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
87                 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
88
89         Configuration configuration = new ConfigurationImpl(new ModuleShardConfigProvider() {
90             @Override
91             public Map<String, ModuleConfig> retrieveModuleConfigs(Configuration configuration) {
92                 return Collections.emptyMap();
93             }
94         });
95
96         DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
97         Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
98         Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
99
100         dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, mockContextFactory);
101
102         dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
103     }
104
105     @After
106     public void tearDown() {
107         dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
108     }
109
110     @Test
111     public void testEntityOwnershipShardCreated() throws Exception {
112         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
113         service.start();
114
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);
119
120         service.close();
121     }
122
123     @Test
124     public void testRegisterCandidate() throws Exception {
125         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
126         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
127             @Override
128             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
129                 return shardPropsCreator;
130             }
131         };
132
133         service.start();
134
135         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
136
137         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
138         Entity entity = new Entity(ENTITY_TYPE, entityId);
139
140         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
141
142         verifyEntityOwnershipCandidateRegistration(entity, reg);
143         verifyRegisterCandidateLocal(shardPropsCreator, entity);
144         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE, entityId,
145                 dataStore.getActorContext().getCurrentMemberName());
146
147         // Register the same entity - should throw exception
148
149         try {
150             service.registerCandidate(entity);
151             fail("Expected CandidateAlreadyRegisteredException");
152         } catch(CandidateAlreadyRegisteredException e) {
153             // expected
154             assertEquals("getEntity", entity, e.getEntity());
155         }
156
157         // Register a different entity - should succeed
158
159         Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
160         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
161
162         EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
163
164         verifyEntityOwnershipCandidateRegistration(entity2, reg2);
165         verifyRegisterCandidateLocal(shardPropsCreator, entity2);
166         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
167                 dataStore.getActorContext().getCurrentMemberName());
168
169         service.close();
170     }
171
172     @Test
173     public void testCloseCandidateRegistration() throws Exception {
174         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
175         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
176             @Override
177             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
178                 return shardPropsCreator;
179             }
180         };
181
182         service.start();
183
184         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
185
186         Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
187
188         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
189
190         verifyEntityOwnershipCandidateRegistration(entity, reg);
191         verifyRegisterCandidateLocal(shardPropsCreator, entity);
192
193         shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
194
195         reg.close();
196
197         UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
198         assertEquals("getEntity", entity, unregCandidate.getEntity());
199
200         // Re-register - should succeed.
201
202         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
203
204         service.registerCandidate(entity);
205
206         verifyRegisterCandidateLocal(shardPropsCreator, entity);
207
208         service.close();
209     }
210
211     @Test
212     public void testListenerRegistration() {
213         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
214         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
215             @Override
216             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
217                 return shardPropsCreator;
218             }
219         };
220
221         service.start();
222
223         shardPropsCreator.expectShardMessage(RegisterListenerLocal.class);
224
225         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
226         Entity entity = new Entity(ENTITY_TYPE, entityId);
227         EntityOwnershipListener listener = mock(EntityOwnershipListener.class);
228
229         EntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
230
231         assertNotNull("EntityOwnershipListenerRegistration null", reg);
232         assertEquals("getEntityType", entity.getType(), reg.getEntityType());
233         assertEquals("getInstance", listener, reg.getInstance());
234
235         RegisterListenerLocal regListener = shardPropsCreator.waitForShardMessage();
236         assertSame("getListener", listener, regListener.getListener());
237         assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
238
239         shardPropsCreator.expectShardMessage(UnregisterListenerLocal.class);
240
241         reg.close();
242
243         UnregisterListenerLocal unregListener = shardPropsCreator.waitForShardMessage();
244         assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
245         assertSame("getListener", listener, unregListener.getListener());
246
247         service.close();
248     }
249
250     @Test
251     public void testGetOwnershipState() throws Exception {
252         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
253         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
254             @Override
255             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
256                 return shardPropsCreator;
257             }
258         };
259
260         service.start();
261
262         ShardDataTree shardDataTree = new ShardDataTree(SchemaContextHelper.entityOwners());
263         shardPropsCreator.setDataTree(shardDataTree.getDataTree());
264
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);
269
270         writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), "member-2"),
271                 shardDataTree);
272         verifyGetOwnershipState(service, entity1, false, true);
273
274         writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), ""),
275                 shardDataTree);
276         verifyGetOwnershipState(service, entity1, false, false);
277
278         Entity entity2 = new Entity(ENTITY_TYPE, "two");
279         Optional<EntityOwnershipState> state = service.getOwnershipState(entity2);
280         assertEquals("getOwnershipState present", false, state.isPresent());
281
282         writeNode(entityPath(entity2.getType(), entity2.getId()), ImmutableNodes.mapEntry(ENTITY_QNAME,
283                 ENTITY_ID_QNAME, entity2.getId()), shardDataTree);
284         verifyGetOwnershipState(service, entity2, false, false);
285
286         service.close();
287     }
288
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());
295     }
296
297     private void verifyEntityCandidate(ActorRef entityOwnershipShard, String entityType,
298             YangInstanceIdentifier entityId, String candidateName) {
299         verifyEntityCandidate(entityType, entityId, candidateName,
300                 new Function<YangInstanceIdentifier, NormalizedNode<?,?>>() {
301                     @Override
302                     public NormalizedNode<?, ?> apply(YangInstanceIdentifier path) {
303                         try {
304                             return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
305                         } catch (Exception e) {
306                             return null;
307                         }
308                     }
309                 });
310     }
311
312     private static void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity) {
313         RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
314         assertEquals("getEntity", entity, regCandidate.getEntity());
315     }
316
317     private static void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
318         assertNotNull("EntityOwnershipCandidateRegistration null", reg);
319         assertEquals("getInstance", entity, reg.getInstance());
320     }
321
322     static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
323         TestShardPropsCreator() {
324             super("member-1");
325         }
326
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<>();
331
332         @Override
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);
337         }
338
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();
345         }
346
347         void expectShardMessage(Class<?> ofType) {
348             messageReceived.set(new CountDownLatch(1));
349             receivedMessage.set(null);
350             messageClass.set(ofType);
351         }
352
353         void setDataTree(DataTree tree) {
354             this.dataTree.set(tree);
355         }
356     }
357
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;
363
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;
373         }
374
375         @Override
376         public void onReceiveCommand(final Object message) throws Exception {
377             try {
378                 if(dataTree.get() != null && message instanceof GetShardDataTree) {
379                     sender().tell(dataTree.get(), self());
380                 } else {
381                     super.onReceiveCommand(message);
382                 }
383             } finally {
384                 Class<?> expMsgClass = messageClass.get();
385                 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
386                     receivedMessage.set(message);
387                     messageReceived.get().countDown();
388                 }
389             }
390         }
391     }
392 }