Pass in EntityOwnerSelectionStrategyConfig when constructing EntityOwnershipShard
[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.opendaylight.controller.cluster.datastore.DatastoreContext;
38 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
39 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
40 import org.opendaylight.controller.cluster.datastore.config.Configuration;
41 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
42 import org.opendaylight.controller.cluster.datastore.config.ModuleConfig;
43 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfigProvider;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
48 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
49 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
50 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
51 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
52 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
53 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
54 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
55 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
56 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
57 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
58 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import scala.concurrent.Await;
66 import scala.concurrent.Future;
67 import scala.concurrent.duration.Duration;
68
69 /**
70  * Unit tests for DistributedEntityOwnershipService.
71  *
72  * @author Thomas Pantelis
73  */
74 public class DistributedEntityOwnershipServiceTest extends AbstractEntityOwnershipTest {
75     static String ENTITY_TYPE = "test";
76     static String ENTITY_TYPE2 = "test2";
77     static int ID_COUNTER = 1;
78     static final QName QNAME = QName.create("test", "2015-08-11", "foo");
79
80     private final String dataStoreType = "config" + ID_COUNTER++;
81     private DistributedDataStore dataStore;
82
83     @Before
84     public void setUp() {
85         DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
86                 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
87
88         Configuration configuration = new ConfigurationImpl(new ModuleShardConfigProvider() {
89             @Override
90             public Map<String, ModuleConfig> retrieveModuleConfigs(Configuration configuration) {
91                 return Collections.emptyMap();
92             }
93         });
94
95         dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, datastoreContext );
96
97         dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
98     }
99
100     @After
101     public void tearDown() {
102         dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
103     }
104
105     @Test
106     public void testEntityOwnershipShardCreated() throws Exception {
107         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
108         service.start();
109
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);
114
115         service.close();
116     }
117
118     @Test
119     public void testRegisterCandidate() throws Exception {
120         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
121         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
122             @Override
123             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
124                 return shardPropsCreator;
125             }
126         };
127
128         service.start();
129
130         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
131
132         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
133         Entity entity = new Entity(ENTITY_TYPE, entityId);
134
135         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
136
137         verifyEntityOwnershipCandidateRegistration(entity, reg);
138         verifyRegisterCandidateLocal(shardPropsCreator, entity);
139         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE, entityId,
140                 dataStore.getActorContext().getCurrentMemberName());
141
142         // Register the same entity - should throw exception
143
144         try {
145             service.registerCandidate(entity);
146             fail("Expected CandidateAlreadyRegisteredException");
147         } catch(CandidateAlreadyRegisteredException e) {
148             // expected
149             assertEquals("getEntity", entity, e.getEntity());
150         }
151
152         // Register a different entity - should succeed
153
154         Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
155         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
156
157         EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
158
159         verifyEntityOwnershipCandidateRegistration(entity2, reg2);
160         verifyRegisterCandidateLocal(shardPropsCreator, entity2);
161         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
162                 dataStore.getActorContext().getCurrentMemberName());
163
164         service.close();
165     }
166
167     @Test
168     public void testCloseCandidateRegistration() throws Exception {
169         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
170         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
171             @Override
172             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
173                 return shardPropsCreator;
174             }
175         };
176
177         service.start();
178
179         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
180
181         Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
182
183         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
184
185         verifyEntityOwnershipCandidateRegistration(entity, reg);
186         verifyRegisterCandidateLocal(shardPropsCreator, entity);
187
188         shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
189
190         reg.close();
191
192         UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
193         assertEquals("getEntity", entity, unregCandidate.getEntity());
194
195         // Re-register - should succeed.
196
197         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
198
199         service.registerCandidate(entity);
200
201         verifyRegisterCandidateLocal(shardPropsCreator, entity);
202
203         service.close();
204     }
205
206     @Test
207     public void testListenerRegistration() {
208         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
209         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
210             @Override
211             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
212                 return shardPropsCreator;
213             }
214         };
215
216         service.start();
217
218         shardPropsCreator.expectShardMessage(RegisterListenerLocal.class);
219
220         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
221         Entity entity = new Entity(ENTITY_TYPE, entityId);
222         EntityOwnershipListener listener = mock(EntityOwnershipListener.class);
223
224         EntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
225
226         assertNotNull("EntityOwnershipListenerRegistration null", reg);
227         assertEquals("getEntityType", entity.getType(), reg.getEntityType());
228         assertEquals("getInstance", listener, reg.getInstance());
229
230         RegisterListenerLocal regListener = shardPropsCreator.waitForShardMessage();
231         assertSame("getListener", listener, regListener.getListener());
232         assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
233
234         shardPropsCreator.expectShardMessage(UnregisterListenerLocal.class);
235
236         reg.close();
237
238         UnregisterListenerLocal unregListener = shardPropsCreator.waitForShardMessage();
239         assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
240         assertSame("getListener", listener, unregListener.getListener());
241
242         service.close();
243     }
244
245     @Test
246     public void testGetOwnershipState() throws Exception {
247         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
248         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
249             @Override
250             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
251                 return shardPropsCreator;
252             }
253         };
254
255         service.start();
256
257         ShardDataTree shardDataTree = new ShardDataTree(SchemaContextHelper.entityOwners());
258         shardPropsCreator.setDataTree(shardDataTree.getDataTree());
259
260         Entity entity1 = new Entity(ENTITY_TYPE, "one");
261         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithEntityTypeEntry(entityTypeEntryWithEntityEntry(entity1.getType(),
262                 entityEntryWithOwner(entity1.getId(), "member-1"))), shardDataTree);
263         verifyGetOwnershipState(service, entity1, true, true);
264
265         writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), "member-2"),
266                 shardDataTree);
267         verifyGetOwnershipState(service, entity1, false, true);
268
269         writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), ""),
270                 shardDataTree);
271         verifyGetOwnershipState(service, entity1, false, false);
272
273         Entity entity2 = new Entity(ENTITY_TYPE, "two");
274         Optional<EntityOwnershipState> state = service.getOwnershipState(entity2);
275         assertEquals("getOwnershipState present", false, state.isPresent());
276
277         writeNode(entityPath(entity2.getType(), entity2.getId()), ImmutableNodes.mapEntry(ENTITY_QNAME,
278                 ENTITY_ID_QNAME, entity2.getId()), shardDataTree);
279         verifyGetOwnershipState(service, entity2, false, false);
280
281         service.close();
282     }
283
284     private void verifyGetOwnershipState(DistributedEntityOwnershipService service, Entity entity,
285             boolean isOwner, boolean hasOwner) {
286         Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
287         assertEquals("getOwnershipState present", true, state.isPresent());
288         assertEquals("isOwner", isOwner, state.get().isOwner());
289         assertEquals("hasOwner", hasOwner, state.get().hasOwner());
290     }
291
292     private void verifyEntityCandidate(ActorRef entityOwnershipShard, String entityType,
293             YangInstanceIdentifier entityId, String candidateName) {
294         verifyEntityCandidate(entityType, entityId, candidateName,
295                 new Function<YangInstanceIdentifier, NormalizedNode<?,?>>() {
296                     @Override
297                     public NormalizedNode<?, ?> apply(YangInstanceIdentifier path) {
298                         try {
299                             return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
300                         } catch (Exception e) {
301                             return null;
302                         }
303                     }
304                 });
305     }
306
307     private void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity) {
308         RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
309         assertEquals("getEntity", entity, regCandidate.getEntity());
310     }
311
312     private void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
313         assertNotNull("EntityOwnershipCandidateRegistration null", reg);
314         assertEquals("getInstance", entity, reg.getInstance());
315     }
316
317     static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
318         TestShardPropsCreator() {
319             super("member-1", EntityOwnerSelectionStrategyConfig.newBuilder().build());
320         }
321
322         private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
323         private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
324         private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
325         private final AtomicReference<DataTree> dataTree = new AtomicReference<>();
326
327         @Override
328         public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
329                 DatastoreContext datastoreContext, SchemaContext schemaContext) {
330             return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
331                     schemaContext, "member-1", messageClass, messageReceived, receivedMessage, dataTree);
332         }
333
334         @SuppressWarnings("unchecked")
335         <T> T waitForShardMessage() {
336             assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
337                     Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
338             assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
339             return (T) receivedMessage.get();
340         }
341
342         void expectShardMessage(Class<?> ofType) {
343             messageReceived.set(new CountDownLatch(1));
344             receivedMessage.set(null);
345             messageClass.set(ofType);
346         }
347
348         void setDataTree(DataTree tree) {
349             this.dataTree.set(tree);
350         }
351     }
352
353     static class TestEntityOwnershipShard extends EntityOwnershipShard {
354         private final AtomicReference<CountDownLatch> messageReceived;
355         private final AtomicReference<Object> receivedMessage;
356         private final AtomicReference<Class<?>> messageClass;
357         private final AtomicReference<DataTree> dataTree;
358
359         protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
360                 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
361                 AtomicReference<Class<?>> messageClass, AtomicReference<CountDownLatch> messageReceived,
362                 AtomicReference<Object> receivedMessage, AtomicReference<DataTree> dataTree) {
363             super(name, peerAddresses, datastoreContext, schemaContext, localMemberName, EntityOwnerSelectionStrategyConfig.newBuilder().build());
364             this.messageClass = messageClass;
365             this.messageReceived = messageReceived;
366             this.receivedMessage = receivedMessage;
367             this.dataTree = dataTree;
368         }
369
370         @Override
371         public void onReceiveCommand(final Object message) throws Exception {
372             try {
373                 if(dataTree.get() != null && message instanceof GetShardDataTree) {
374                     sender().tell(dataTree.get(), self());
375                 } else {
376                     super.onReceiveCommand(message);
377                 }
378             } finally {
379                 Class<?> expMsgClass = messageClass.get();
380                 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
381                     receivedMessage.set(message);
382                     messageReceived.get().countDown();
383                 }
384             }
385         }
386     }
387 }