Bug 4105: Implement candidate registration close
[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 akka.actor.ActorRef;
17 import akka.actor.PoisonPill;
18 import akka.actor.Props;
19 import com.google.common.util.concurrent.Uninterruptibles;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.concurrent.CountDownLatch;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.atomic.AtomicReference;
26 import org.junit.After;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
30 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
31 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
32 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
33 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
35 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
36 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
37 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
38 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
39 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
40 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidate;
41 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import scala.concurrent.Await;
46 import scala.concurrent.Future;
47 import scala.concurrent.duration.Duration;
48
49 /**
50  * Unit tests for DistributedEntityOwnershipService.
51  *
52  * @author Thomas Pantelis
53  */
54 public class DistributedEntityOwnershipServiceTest extends AbstractActorTest {
55     static String ENTITY_TYPE = "test";
56     static String ENTITY_TYPE2 = "test2";
57     static int ID_COUNTER = 1;
58     static final QName QNAME = QName.create("test", "2015-08-11", "foo");
59
60     private final String dataStoreType = "config" + ID_COUNTER++;
61     private DistributedDataStore dataStore;
62
63     @Before
64     public void setUp() {
65         DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreType(dataStoreType).
66                 shardInitializationTimeout(10, TimeUnit.SECONDS).build();
67         dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(),
68                 new MockConfiguration(Collections.<String, List<String>>emptyMap()), datastoreContext );
69
70         dataStore.onGlobalContextUpdated(TestModel.createTestContext());
71     }
72
73     @After
74     public void tearDown() {
75         dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), ActorRef.noSender());
76     }
77
78     @Test
79     public void testEntityOwnershipShardCreated() throws Exception {
80         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore);
81         service.start();
82
83         Future<ActorRef> future = dataStore.getActorContext().findLocalShardAsync(
84                 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
85         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
86         assertNotNull(DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME + " not found", shardActor);
87
88         service.close();
89     }
90
91     @Test
92     public void testRegisterCandidate() throws Exception {
93         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
94         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
95             @Override
96             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
97                 return shardPropsCreator;
98             }
99         };
100
101         service.start();
102
103         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
104
105         Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
106         EntityOwnershipCandidate candidate = mock(EntityOwnershipCandidate.class);
107
108         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity, candidate);
109
110         verifyEntityOwnershipCandidateRegistration(entity, reg);
111         verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
112
113         // Register the same entity - should throw exception
114
115         EntityOwnershipCandidate candidate2 = mock(EntityOwnershipCandidate.class);
116         try {
117             service.registerCandidate(entity, candidate2);
118             fail("Expected CandidateAlreadyRegisteredException");
119         } catch(CandidateAlreadyRegisteredException e) {
120             // expected
121             assertSame("getCandidate", candidate, e.getRegisteredCandidate());
122             assertEquals("getEntity", entity, e.getEntity());
123         }
124
125         // Register a different entity - should succeed
126
127         Entity entity2 = new Entity(ENTITY_TYPE2, YangInstanceIdentifier.of(QNAME));
128         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
129
130         EntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2, candidate);
131
132         verifyEntityOwnershipCandidateRegistration(entity2, reg2);
133         verifyRegisterCandidateLocal(shardPropsCreator, entity2, candidate);
134
135         service.close();
136     }
137
138     @Test
139     public void testCloseCandidateRegistration() throws Exception {
140         final TestShardPropsCreator shardPropsCreator = new TestShardPropsCreator();
141         DistributedEntityOwnershipService service = new DistributedEntityOwnershipService(dataStore) {
142             @Override
143             protected EntityOwnershipShardPropsCreator newShardPropsCreator() {
144                 return shardPropsCreator;
145             }
146         };
147
148         service.start();
149
150         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
151
152         Entity entity = new Entity(ENTITY_TYPE, YangInstanceIdentifier.of(QNAME));
153         EntityOwnershipCandidate candidate = mock(EntityOwnershipCandidate.class);
154
155         EntityOwnershipCandidateRegistration reg = service.registerCandidate(entity, candidate);
156
157         verifyEntityOwnershipCandidateRegistration(entity, reg);
158         verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
159
160         shardPropsCreator.expectShardMessage(UnregisterCandidateLocal.class);
161
162         reg.close();
163
164         UnregisterCandidateLocal unregCandidate = shardPropsCreator.waitForShardMessage();
165         assertEquals("getEntity", entity, unregCandidate.getEntity());
166
167         // Re-register - should succeed.
168
169         shardPropsCreator.expectShardMessage(RegisterCandidateLocal.class);
170
171         service.registerCandidate(entity, candidate);
172
173         verifyRegisterCandidateLocal(shardPropsCreator, entity, candidate);
174
175         service.close();
176     }
177
178     @Test
179     public void testRegisterListener() {
180     }
181
182     private void verifyRegisterCandidateLocal(final TestShardPropsCreator shardPropsCreator, Entity entity,
183             EntityOwnershipCandidate candidate) {
184         RegisterCandidateLocal regCandidate = shardPropsCreator.waitForShardMessage();
185         assertSame("getCandidate", candidate, regCandidate.getCandidate());
186         assertEquals("getEntity", entity, regCandidate.getEntity());
187     }
188
189     private void verifyEntityOwnershipCandidateRegistration(Entity entity, EntityOwnershipCandidateRegistration reg) {
190         assertNotNull("EntityOwnershipCandidateRegistration null", reg);
191         assertEquals("getEntity", entity, reg.getEntity());
192     }
193
194     static class TestShardPropsCreator extends EntityOwnershipShardPropsCreator {
195         private final AtomicReference<CountDownLatch> messageReceived = new AtomicReference<>();
196         private final AtomicReference<Object> receivedMessage = new AtomicReference<>();
197         private final AtomicReference<Class<?>> messageClass = new AtomicReference<>();
198
199         @Override
200         public Props newProps(ShardIdentifier shardId, Map<String, String> peerAddresses,
201                 DatastoreContext datastoreContext, SchemaContext schemaContext) {
202             return Props.create(TestEntityOwnershipShard.class, shardId, peerAddresses, datastoreContext,
203                     schemaContext, messageClass, messageReceived, receivedMessage);
204         }
205
206         @SuppressWarnings("unchecked")
207         <T> T waitForShardMessage() {
208             assertTrue("Message " + messageClass.get().getSimpleName() + " was not received",
209                     Uninterruptibles.awaitUninterruptibly(messageReceived.get(), 5, TimeUnit.SECONDS));
210             assertEquals("Message type", messageClass.get(), receivedMessage.get().getClass());
211             return (T) receivedMessage.get();
212         }
213
214         void expectShardMessage(Class<?> ofType) {
215             messageReceived.set(new CountDownLatch(1));
216             receivedMessage.set(null);
217             messageClass.set(ofType);
218         }
219     }
220
221     static class TestEntityOwnershipShard extends EntityOwnershipShard {
222         private final AtomicReference<CountDownLatch> messageReceived;
223         private final AtomicReference<Object> receivedMessage;
224         private final AtomicReference<Class<?>> messageClass;
225
226         protected TestEntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
227                 DatastoreContext datastoreContext, SchemaContext schemaContext, AtomicReference<Class<?>> messageClass,
228                 AtomicReference<CountDownLatch> messageReceived, AtomicReference<Object> receivedMessage) {
229             super(name, peerAddresses, datastoreContext, schemaContext);
230             this.messageClass = messageClass;
231             this.messageReceived = messageReceived;
232             this.receivedMessage = receivedMessage;
233         }
234
235         @Override
236         public void onReceiveCommand(final Object message) throws Exception {
237             try {
238                 super.onReceiveCommand(message);
239             } finally {
240                 Class<?> expMsgClass = messageClass.get();
241                 if(expMsgClass != null && expMsgClass.equals(message.getClass())) {
242                     receivedMessage.set(message);
243                     messageReceived.get().countDown();
244                 }
245             }
246         }
247     }
248 }