aad0a21d747ec255534403a667da8ceda9365b06
[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 import akka.actor.ActorRef;
31 import akka.actor.PoisonPill;
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.datastore.DatastoreContext;
42 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
43 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
44 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
45 import org.opendaylight.controller.cluster.datastore.config.Configuration;
46 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
47 import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
49 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
50 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
51 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
52 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
53 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
54 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
55 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
56 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
57 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
58 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
59 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
60 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
64 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
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 final String ENTITY_TYPE = "test";
76     static final String ENTITY_TYPE2 = "test2";
77     static final QName QNAME = QName.create("test", "2015-08-11", "foo");
78     static int ID_COUNTER = 1;
79
80     private final String dataStoreName = "config" + ID_COUNTER++;
81     private DistributedDataStore dataStore;
82
83     @Before
84     public void setUp() {
85         DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreName(dataStoreName).
86                 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
87
88         Configuration configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider()) {
89             @Override
90             public Collection<String> getUniqueMemberNamesForAllShards() {
91                 return Sets.newHashSet("member-1");
92             }
93         };
94
95         DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
96         Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
97         Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
98
99         dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, mockContextFactory, null);
100
101         dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
102     }
103
104     @After
105     public void tearDown() {
106         dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
107     }
108
109     private static <T> T verifyMessage(final DistributedEntityOwnershipService mock, final Class<T> type) {
110         final ArgumentCaptor<T> message = ArgumentCaptor.forClass(type);
111         verify(mock).executeLocalEntityOwnershipShardOperation(message.capture());
112         return message.getValue();
113     }
114
115     @Test
116     public void testEntityOwnershipShardCreated() throws Exception {
117         DistributedEntityOwnershipService service = DistributedEntityOwnershipService.start(dataStore.getActorContext(),
118                 EntityOwnerSelectionStrategyConfig.newBuilder().build());
119
120         Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
121                 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
122         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
123         assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
124
125         service.close();
126     }
127
128     @Test
129     public void testRegisterCandidate() throws Exception {
130         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
131             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
132
133         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
134         Entity entity = new Entity(ENTITY_TYPE, entityId);
135
136         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
137         verifyRegisterCandidateLocal(service, entity);
138         verifyEntityOwnershipCandidateRegistration(entity, reg);
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         reset(service);
154
155         Entity entity2 = new Entity(ENTITY_TYPE2, entityId);
156         EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
157         verifyRegisterCandidateLocal(service, entity2);
158         verifyEntityOwnershipCandidateRegistration(entity2, reg2);
159         verifyEntityCandidate(service.getLocalEntityOwnershipShard(), ENTITY_TYPE2, entityId,
160                 dataStore.getActorContext().getCurrentMemberName());
161
162         service.close();
163     }
164
165     @Test
166     public void testCloseCandidateRegistration() throws Exception {
167         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
168             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
169
170         Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
171         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
172
173         verifyEntityOwnershipCandidateRegistration(entity, reg);
174         verifyRegisterCandidateLocal(service, entity);
175
176         reset(service);
177         reg.close();
178         UnregisterCandidateLocal unregCandidate = verifyMessage(service, UnregisterCandidateLocal.class);
179         assertEquals("getEntity", entity, unregCandidate.getEntity());
180
181         // Re-register - should succeed.
182         reset(service);
183         service.registerCandidate(entity);
184         verifyRegisterCandidateLocal(service, entity);
185
186         service.close();
187     }
188
189     @Test
190     public void testListenerRegistration() {
191         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
192             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
193
194         YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
195         Entity entity = new Entity(ENTITY_TYPE, entityId);
196         EntityOwnershipListener listener = mock(EntityOwnershipListener.class);
197
198         EntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
199
200         assertNotNull("EntityOwnershipListenerRegistration null", reg);
201         assertEquals("getEntityType", entity.getType(), reg.getEntityType());
202         assertEquals("getInstance", listener, reg.getInstance());
203
204         RegisterListenerLocal regListener = verifyMessage(service, RegisterListenerLocal.class);
205         assertSame("getListener", listener, regListener.getListener());
206         assertEquals("getEntityType", entity.getType(), regListener.getEntityType());
207
208         reset(service);
209         reg.close();
210         UnregisterListenerLocal unregListener = verifyMessage(service, UnregisterListenerLocal.class);
211         assertEquals("getEntityType", entity.getType(), unregListener.getEntityType());
212         assertSame("getListener", listener, unregListener.getListener());
213
214         service.close();
215     }
216
217     @Test
218     public void testGetOwnershipState() throws Exception {
219         DistributedEntityOwnershipService service = spy(DistributedEntityOwnershipService.start(
220             dataStore.getActorContext(), EntityOwnerSelectionStrategyConfig.newBuilder().build()));
221
222         ShardDataTree shardDataTree = new ShardDataTree(SchemaContextHelper.entityOwners(), TreeType.OPERATIONAL);
223
224         when(service.getLocalEntityOwnershipShardDataTree()).thenReturn(shardDataTree.getDataTree());
225
226         Entity entity1 = new Entity(ENTITY_TYPE, "one");
227         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity1.getId(), "member-1"), shardDataTree);
228         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithEntityTypeEntry(entityTypeEntryWithEntityEntry(entity1.getType(),
229                 entityEntryWithOwner(entity1.getId(), "member-1"))), shardDataTree);
230         verifyGetOwnershipState(service, entity1, true, true);
231
232         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity1.getId(), "member-2"), shardDataTree);
233         writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), "member-2"),
234                 shardDataTree);
235         verifyGetOwnershipState(service, entity1, false, true);
236
237         writeNode(entityPath(entity1.getType(), entity1.getId()), entityEntryWithOwner(entity1.getId(), ""),
238                 shardDataTree);
239         verifyGetOwnershipState(service, entity1, false, false);
240
241         Entity entity2 = new Entity(ENTITY_TYPE, "two");
242         Optional<EntityOwnershipState> state = service.getOwnershipState(entity2);
243         assertEquals("getOwnershipState present", false, state.isPresent());
244
245         writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity2.getId(), "member-1"), shardDataTree);
246         writeNode(entityPath(entity2.getType(), entity2.getId()), ImmutableNodes.mapEntry(ENTITY_QNAME,
247                 ENTITY_ID_QNAME, entity2.getId()), shardDataTree);
248         verifyGetOwnershipState(service, entity2, false, false);
249
250         deleteNode(candidatePath(entityPath(entity2.getType(), entity2.getId()), "member-1"), shardDataTree);
251         Optional<EntityOwnershipState> state2 = service.getOwnershipState(entity2);
252         assertEquals("getOwnershipState present", false, state2.isPresent());
253         service.close();
254     }
255
256     @Test
257     public void testIsCandidateRegistered() throws CandidateAlreadyRegisteredException {
258         DistributedEntityOwnershipService service = DistributedEntityOwnershipService.start(dataStore.getActorContext(),
259                 EntityOwnerSelectionStrategyConfig.newBuilder().build());
260
261         final Entity test = new Entity("test-type", "test");
262
263         assertFalse(service.isCandidateRegistered(test));
264
265         service.registerCandidate(test);
266
267         assertTrue(service.isCandidateRegistered(test));
268
269         service.close();
270     }
271
272     private static void verifyGetOwnershipState(final DistributedEntityOwnershipService service, final Entity entity,
273             final boolean isOwner, final boolean hasOwner) {
274         Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
275         assertEquals("getOwnershipState present", true, state.isPresent());
276         assertEquals("isOwner", isOwner, state.get().isOwner());
277         assertEquals("hasOwner", hasOwner, state.get().hasOwner());
278     }
279
280     private void verifyEntityCandidate(final ActorRef entityOwnershipShard, final String entityType,
281             final YangInstanceIdentifier entityId, final String candidateName) {
282         verifyEntityCandidate(entityType, entityId, candidateName,
283                 path -> {
284                     try {
285                         return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
286                     } catch (Exception e) {
287                         return null;
288                     }
289                 });
290     }
291
292     private static void verifyRegisterCandidateLocal(final DistributedEntityOwnershipService service, final Entity entity) {
293         RegisterCandidateLocal regCandidate = verifyMessage(service, RegisterCandidateLocal.class);
294         assertEquals("getEntity", entity, regCandidate.getEntity());
295     }
296
297     private static void verifyEntityOwnershipCandidateRegistration(final Entity entity, final EntityOwnershipCandidateRegistration reg) {
298         assertNotNull("EntityOwnershipCandidateRegistration null", reg);
299         assertEquals("getInstance", entity, reg.getInstance());
300     }
301 }