BUG-2138: Create DistributedShardFrontend
[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.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.reset;
18 import static org.mockito.Mockito.spy;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.Mockito.when;
21 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_QNAME;
22 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
23 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_QNAME;
24 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
25 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityEntryWithOwner;
26 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
27 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithEntityTypeEntry;
28 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
29 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityTypeEntryWithEntityEntry;
30
31 import akka.actor.ActorRef;
32 import com.google.common.base.Optional;
33 import com.google.common.collect.Sets;
34 import java.util.Collection;
35 import java.util.concurrent.TimeUnit;
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.ArgumentCaptor;
40 import org.mockito.Mockito;
41 import org.opendaylight.controller.cluster.access.concepts.MemberName;
42 import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
43 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
44 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
45 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
46 import org.opendaylight.controller.cluster.datastore.Shard;
47 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
48 import org.opendaylight.controller.cluster.datastore.config.Configuration;
49 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
50 import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
51 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
52 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
53 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
54 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
55 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
56 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
57 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
58 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
59 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
60 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
61 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
62 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
63 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
64 import org.opendaylight.yangtools.yang.common.QName;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
68 import scala.concurrent.Await;
69 import scala.concurrent.Future;
70 import scala.concurrent.duration.Duration;
71
72 /**
73  * Unit tests for DistributedEntityOwnershipService.
74  *
75  * @author Thomas Pantelis
76  */
77 public class DistributedEntityOwnershipServiceTest extends AbstractClusterRefEntityOwnershipTest {
78     static final String ENTITY_TYPE = "test";
79     static final String ENTITY_TYPE2 = "test2";
80     static final QName QNAME = QName.create("test", "2015-08-11", "foo");
81     static int ID_COUNTER = 1;
82
83     private final String dataStoreName = "config" + ID_COUNTER++;
84     private AbstractDataStore dataStore;
85
86     @Before
87     public void setUp() {
88         DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreName(dataStoreName)
89                 .shardInitializationTimeout(10, TimeUnit.SECONDS).build();
90
91         Configuration configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider()) {
92             @Override
93             public Collection<MemberName> getUniqueMemberNamesForAllShards() {
94                 return Sets.newHashSet(MemberName.forName("member-1"));
95             }
96         };
97
98         DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
99         Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
100         Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
101
102         dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration,
103                 mockContextFactory, null);
104
105         dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
106     }
107
108     @After
109     public void tearDown() {
110         dataStore.close();
111     }
112
113     private static <T> T verifyMessage(final DistributedEntityOwnershipService mock, final Class<T> type) {
114         final ArgumentCaptor<T> message = ArgumentCaptor.forClass(type);
115         verify(mock).executeLocalEntityOwnershipShardOperation(message.capture());
116         return message.getValue();
117     }
118
119     @Test
120     public void testEntityOwnershipShardCreated() throws Exception {
121         DistributedEntityOwnershipService service = DistributedEntityOwnershipService.start(dataStore.getActorContext(),
122                 EntityOwnerSelectionStrategyConfig.newBuilder().build());
123
124         Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
125                 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
126         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
127         assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
128
129         service.close();
130     }
131
132     @Test
133     public void testRegisterCandidate() throws Exception {
134         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
135             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
136
137         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
138         DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
139
140         DOMEntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
141         verifyRegisterCandidateLocal(service, entity);
142         verifyEntityOwnershipCandidateRegistration(entity, reg);
143         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE, entityId,
144                 dataStore.getActorContext().getCurrentMemberName().getName());
145
146         // Register the same entity - should throw exception
147
148         try {
149             service.registerCandidate(entity);
150             fail("Expected CandidateAlreadyRegisteredException");
151         } catch (CandidateAlreadyRegisteredException e) {
152             // expected
153             assertEquals("getEntity", entity, e.getEntity());
154         }
155
156         // Register a different entity - should succeed
157         reset(service);
158
159         DOMEntity entity2 = new DOMEntity(ENTITY_TYPE2, entityId);
160         DOMEntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
161
162         verifyEntityOwnershipCandidateRegistration(entity2, reg2);
163         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
164                 dataStore.getActorContext().getCurrentMemberName().getName());
165
166         service.close();
167     }
168
169     @Test
170     public void testCloseCandidateRegistration() throws Exception {
171         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
172             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
173
174         DOMEntity entity = new DOMEntity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
175
176         DOMEntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
177
178         verifyEntityOwnershipCandidateRegistration(entity, reg);
179         verifyRegisterCandidateLocal(service, entity);
180
181         reset(service);
182         reg.close();
183         UnregisterCandidateLocal unregCandidate = verifyMessage(service, UnregisterCandidateLocal.class);
184         assertEquals("getEntity", entity, unregCandidate.getEntity());
185
186         // Re-register - should succeed.
187         reset(service);
188         service.registerCandidate(entity);
189         verifyRegisterCandidateLocal(service, entity);
190
191         service.close();
192     }
193
194     @Test
195     public void testListenerRegistration() {
196         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
197             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
198
199         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
200         DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
201         DOMEntityOwnershipListener listener = mock(DOMEntityOwnershipListener.class);
202
203         DOMEntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
204
205         assertNotNull("EntityOwnershipListenerRegistration null", reg);
206         assertEquals("getEntityType", entity.getType(), reg.getEntityType());
207         assertEquals("getInstance", listener, reg.getInstance());
208
209         RegisterListenerLocal regListener = verifyMessage(service, RegisterListenerLocal.class);
210         assertSame("getListener", listener, regListener.getListener());
211         assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
212
213         reset(service);
214         reg.close();
215         UnregisterListenerLocal unregListener = verifyMessage(service, UnregisterListenerLocal.class);
216         assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
217         assertSame("getListener", listener, unregListener.getListener());
218
219         service.close();
220     }
221
222     @Test
223     public void testGetOwnershipState() throws Exception {
224         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
225             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
226
227         final Shard mockShard = Mockito.mock(Shard.class);
228         ShardDataTree shardDataTree = new ShardDataTree(mockShard, SchemaContextHelper.entityOwners(),
229             TreeType.OPERATIONAL);
230
231         when(service.getLocalEntityOwnershipShardDataTree()).thenReturn(shardDataTree.getDataTree());
232
233         DOMEntity entity1 = new DOMEntity(ENTITY_TYPE, "one");
234         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity1.getIdentifier(), "member-1"),
235                 shardDataTree);
236         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithEntityTypeEntry(entityTypeEntryWithEntityEntry(entity1.getType(),
237                 entityEntryWithOwner(entity1.getIdentifier(), "member-1"))), shardDataTree);
238         verifyGetOwnershipState(service, entity1, EntityOwnershipState.IS_OWNER);
239
240         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE,
241                 entity1.getIdentifier(), "member-2"), shardDataTree);
242         writeNode(entityPath(entity1.getType(), entity1.getIdentifier()),
243                 entityEntryWithOwner(entity1.getIdentifier(), "member-2"), shardDataTree);
244         verifyGetOwnershipState(service, entity1, EntityOwnershipState.OWNED_BY_OTHER);
245
246         writeNode(entityPath(entity1.getType(), entity1.getIdentifier()), entityEntryWithOwner(entity1.getIdentifier(),
247                 ""), shardDataTree);
248         verifyGetOwnershipState(service, entity1, EntityOwnershipState.NO_OWNER);
249
250         DOMEntity entity2 = new DOMEntity(ENTITY_TYPE, "two");
251         Optional<EntityOwnershipState> state = service.getOwnershipState(entity2);
252         assertEquals("getOwnershipState present", false, state.isPresent());
253
254         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity2.getIdentifier(), "member-1"),
255                 shardDataTree);
256         writeNode(entityPath(entity2.getType(), entity2.getIdentifier()), ImmutableNodes.mapEntry(ENTITY_QNAME,
257                 ENTITY_ID_QNAME, entity2.getIdentifier()), shardDataTree);
258         verifyGetOwnershipState(service, entity2, EntityOwnershipState.NO_OWNER);
259
260         deleteNode(candidatePath(entityPath(entity2.getType(), entity2.getIdentifier()), "member-1"), shardDataTree);
261         Optional<EntityOwnershipState> state2 = service.getOwnershipState(entity2);
262         assertEquals("getOwnershipState present", false, state2.isPresent());
263         service.close();
264     }
265
266     @Test
267     public void testIsCandidateRegistered() throws CandidateAlreadyRegisteredException {
268         DistributedEntityOwnershipService service = DistributedEntityOwnershipService.start(dataStore.getActorContext(),
269                 EntityOwnerSelectionStrategyConfig.newBuilder().build());
270
271         final DOMEntity test = new DOMEntity("test-type", "test");
272
273         assertFalse(service.isCandidateRegistered(test));
274
275         service.registerCandidate(test);
276
277         assertTrue(service.isCandidateRegistered(test));
278
279         service.close();
280     }
281
282     private static void verifyGetOwnershipState(final DistributedEntityOwnershipService service, final DOMEntity entity,
283             final EntityOwnershipState expState) {
284         Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
285         assertEquals("getOwnershipState present", true, state.isPresent());
286         assertEquals("EntityOwnershipState", expState, state.get());
287     }
288
289     @SuppressWarnings("checkstyle:IllegalCatch")
290     private void verifyEntityCandidate(final ActorRef entityOwnershipShard, final String entityType,
291             final YangInstanceIdentifier entityId, final String candidateName) {
292         verifyEntityCandidate(entityType, entityId, candidateName, path -> {
293             try {
294                 return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
295             } catch (Exception e) {
296                 return null;
297             }
298         });
299     }
300
301     private static void verifyRegisterCandidateLocal(final DistributedEntityOwnershipService service,
302             final DOMEntity entity) {
303         RegisterCandidateLocal regCandidate = verifyMessage(service, RegisterCandidateLocal.class);
304         assertEquals("getEntity", entity, regCandidate.getEntity());
305     }
306
307     private static void verifyEntityOwnershipCandidateRegistration(final DOMEntity entity,
308             final DOMEntityOwnershipCandidateRegistration reg) {
309         assertNotNull("EntityOwnershipCandidateRegistration null", reg);
310         assertEquals("getInstance", entity, reg.getInstance());
311     }
312 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.