01683130feaadb7c7ba102ad9c2799489d4af396
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / MemberNode.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;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.fail;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSystem;
14 import akka.actor.Address;
15 import akka.actor.AddressFromURIString;
16 import akka.cluster.Cluster;
17 import akka.cluster.ClusterEvent.CurrentClusterState;
18 import akka.cluster.Member;
19 import akka.cluster.MemberStatus;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Stopwatch;
23 import com.google.common.collect.Sets;
24 import com.google.common.util.concurrent.Uninterruptibles;
25 import com.typesafe.config.ConfigFactory;
26 import java.util.List;
27 import java.util.Set;
28 import java.util.concurrent.TimeUnit;
29 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
30 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
31 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
32 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
33 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import scala.concurrent.Await;
36 import scala.concurrent.Future;
37 import scala.concurrent.duration.Duration;
38
39 /**
40  * Class that represents a cluster member node for unit tests. It encapsulates an actor system with
41  * config and (optional) operational data store instances. The Builder is used to specify the setup
42  * parameters and create the data store instances. The actor system is automatically joined to address
43  * 127.0.0.1:2558 so one member must specify an akka cluster configuration with that address.
44  *
45  * @author Thomas Pantelis
46  */
47 public class MemberNode {
48     static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
49
50     private IntegrationTestKit kit;
51     private DistributedDataStore configDataStore;
52     private DistributedDataStore operDataStore;
53     private DatastoreContext.Builder datastoreContextBuilder;
54     private boolean cleanedUp;
55
56     /**
57      * Constructs a Builder.
58      *
59      * @param members the list to which the resulting MemberNode will be added. This makes it easier for
60      *                callers to cleanup instances on test completion.
61      * @return a Builder instance
62      */
63     public static Builder builder(List<MemberNode> members) {
64         return new Builder(members);
65     }
66
67     public IntegrationTestKit kit() {
68         return kit;
69     }
70
71
72     public DistributedDataStore configDataStore() {
73         return configDataStore;
74     }
75
76
77     public DistributedDataStore operDataStore() {
78         return operDataStore;
79     }
80
81     public DatastoreContext.Builder datastoreContextBuilder() {
82         return datastoreContextBuilder;
83     }
84
85     public void waitForMembersUp(String... otherMembers) {
86         kit.waitForMembersUp(otherMembers);
87     }
88
89     public void waitForMemberDown(String member) {
90         Stopwatch sw = Stopwatch.createStarted();
91         while(sw.elapsed(TimeUnit.SECONDS) <= 10) {
92             CurrentClusterState state = Cluster.get(kit.getSystem()).state();
93             for(Member m: state.getUnreachable()) {
94                 if(member.equals(m.getRoles().iterator().next())) {
95                     return;
96                 }
97             }
98
99             for(Member m: state.getMembers()) {
100                 if(m.status() != MemberStatus.up() && member.equals(m.getRoles().iterator().next())) {
101                     return;
102                 }
103             }
104
105             Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
106         }
107
108         fail("Member " + member + " is now down");
109     }
110
111     public void cleanup() {
112         if(!cleanedUp) {
113             cleanedUp = true;
114             kit.cleanup(configDataStore);
115             kit.cleanup(operDataStore);
116             kit.shutdownActorSystem(kit.getSystem(), Boolean.TRUE);
117         }
118     }
119
120     public static void verifyRaftState(DistributedDataStore datastore, String shardName, RaftStateVerifier verifier)
121             throws Exception {
122         ActorContext actorContext = datastore.getActorContext();
123
124         Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
125         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
126
127         AssertionError lastError = null;
128         Stopwatch sw = Stopwatch.createStarted();
129         while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
130             OnDemandRaftState raftState = (OnDemandRaftState)actorContext.
131                     executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);
132
133             try {
134                 verifier.verify(raftState);
135                 return;
136             } catch (AssertionError e) {
137                 lastError = e;
138                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
139             }
140         }
141
142         throw lastError;
143     }
144
145     public static void verifyRaftPeersPresent(DistributedDataStore datastore, final String shardName,
146             String... peerMemberNames) throws Exception {
147         final Set<String> peerIds = Sets.newHashSet();
148         for(String p: peerMemberNames) {
149             peerIds.add(ShardIdentifier.builder().memberName(p).shardName(shardName).
150                 type(datastore.getActorContext().getDataStoreName()).build().toString());
151         }
152
153         verifyRaftState(datastore, shardName, new RaftStateVerifier() {
154             @Override
155             public void verify(OnDemandRaftState raftState) {
156                 assertEquals("Peers for shard " + shardName, peerIds, raftState.getPeerAddresses().keySet());
157             }
158         });
159     }
160
161     public static void verifyNoShardPresent(DistributedDataStore datastore, String shardName) {
162         Stopwatch sw = Stopwatch.createStarted();
163         while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
164             Optional<ActorRef> shardReply = datastore.getActorContext().findLocalShard(shardName);
165             if(!shardReply.isPresent()) {
166                 return;
167             }
168
169             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
170         }
171
172         fail("Shard " + shardName + " is present");
173     }
174
175     public static class Builder {
176         private final List<MemberNode> members;
177         private String moduleShardsConfig;
178         private String akkaConfig;
179         private String[] waitForshardLeader = new String[0];
180         private String testName;
181         private SchemaContext schemaContext;
182         private boolean createOperDatastore = true;
183         private DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder().
184                 shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(30);
185
186         Builder(List<MemberNode> members) {
187             this.members = members;
188         }
189
190         /**
191          * Specifies the name of the module shards config file. This is required.
192          *
193          * @return this Builder
194          */
195         public Builder moduleShardsConfig(String moduleShardsConfig) {
196             this.moduleShardsConfig = moduleShardsConfig;
197             return this;
198         }
199
200         /**
201          * Specifies the name of the akka configuration. This is required.
202          *
203          * @return this Builder
204          */
205         public Builder akkaConfig(String akkaConfig) {
206             this.akkaConfig = akkaConfig;
207             return this;
208         }
209
210         /**
211          * Specifies the name of the test that is appended to the data store names. This is required.
212          *
213          * @return this Builder
214          */
215         public Builder testName(String testName) {
216             this.testName = testName;
217             return this;
218         }
219
220         /**
221          * Specifies the optional names of the shards to initially wait for a leader to be elected.
222          *
223          * @return this Builder
224          */
225         public Builder waitForShardLeader(String... shardNames) {
226             this.waitForshardLeader = shardNames;
227             return this;
228         }
229
230         /**
231          * Specifies whether or not to create an operational data store. Defaults to true.
232          *
233          * @return this Builder
234          */
235         public Builder createOperDatastore(boolean value) {
236             this.createOperDatastore = value;
237             return this;
238         }
239
240         /**
241          * Specifies the SchemaContext for the data stores. Defaults to SchemaContextHelper.full().
242          *
243          * @return this Builder
244          */
245         public Builder schemaContext(SchemaContext schemaContext) {
246             this.schemaContext = schemaContext;
247             return this;
248         }
249
250         /**
251          * Specifies the DatastoreContext Builder. If not specified, a default instance is used.
252          *
253          * @return this Builder
254          */
255         public Builder datastoreContextBuilder(DatastoreContext.Builder builder) {
256             datastoreContextBuilder = builder;
257             return this;
258         }
259
260         public MemberNode build() {
261             Preconditions.checkNotNull(moduleShardsConfig, "moduleShardsConfig must be specified");
262             Preconditions.checkNotNull(akkaConfig, "akkaConfig must be specified");
263             Preconditions.checkNotNull(testName, "testName must be specified");
264
265             if(schemaContext == null) {
266                 schemaContext = SchemaContextHelper.full();
267             }
268
269             MemberNode node = new MemberNode();
270             node.datastoreContextBuilder = datastoreContextBuilder;
271
272             ActorSystem system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig(akkaConfig));
273             Cluster.get(system).join(MEMBER_1_ADDRESS);
274
275             node.kit = new IntegrationTestKit(system, datastoreContextBuilder);
276
277             String memberName = new ClusterWrapperImpl(system).getCurrentMemberName();
278             node.kit.getDatastoreContextBuilder().shardManagerPersistenceId("shard-manager-config-" + memberName);
279             node.configDataStore = node.kit.setupDistributedDataStore("config_" + testName, moduleShardsConfig,
280                     true, schemaContext, waitForshardLeader);
281
282             if(createOperDatastore) {
283                 node.kit.getDatastoreContextBuilder().shardManagerPersistenceId("shard-manager-oper-" + memberName);
284                 node.operDataStore = node.kit.setupDistributedDataStore("oper_" + testName, moduleShardsConfig,
285                         true, schemaContext, waitForshardLeader);
286             }
287
288             members.add(node);
289             return node;
290         }
291     }
292
293     public static interface RaftStateVerifier {
294         void verify(OnDemandRaftState raftState);
295     }
296 }