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