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