2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore.admin;
10 import akka.actor.ActorRef;
11 import akka.actor.Status.Success;
12 import akka.dispatch.OnComplete;
13 import akka.pattern.Patterns;
14 import akka.util.Timeout;
15 import com.google.common.base.Function;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.util.AbstractMap.SimpleEntry;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import java.util.concurrent.TimeUnit;
34 import org.apache.commons.lang3.SerializationUtils;
35 import org.opendaylight.controller.cluster.access.concepts.MemberName;
36 import org.opendaylight.controller.cluster.datastore.DistributedDataStoreInterface;
37 import org.opendaylight.controller.cluster.datastore.messages.AddPrefixShardReplica;
38 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
39 import org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus;
40 import org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus;
41 import org.opendaylight.controller.cluster.datastore.messages.GetShardRole;
42 import org.opendaylight.controller.cluster.datastore.messages.GetShardRoleReply;
43 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
44 import org.opendaylight.controller.cluster.datastore.messages.RemovePrefixShardReplica;
45 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
46 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
47 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshotList;
48 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
49 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
50 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
51 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddPrefixShardReplicaInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddPrefixShardReplicaOutput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddPrefixShardReplicaOutputBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsOutputBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaOutput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaOutputBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreOutputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsOutput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsOutputBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardInput;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardOutput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardOutputBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsInput;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsOutput;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsOutputBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetPrefixShardRoleInput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetPrefixShardRoleOutput;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetPrefixShardRoleOutputBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleInput;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleOutput;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleOutputBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalInput;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalOutput;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalOutputBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasInput;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasOutput;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasOutputBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemovePrefixShardReplicaInput;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemovePrefixShardReplicaOutput;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemovePrefixShardReplicaOutputBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaInput;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaOutput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaOutputBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.member.voting.states.input.MemberVotingState;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResult;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResultBuilder;
96 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
97 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
98 import org.opendaylight.yangtools.yang.common.RpcResult;
99 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
100 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
105 * Implements the yang RPCs defined in the generated ClusterAdminService interface.
107 * @author Thomas Pantelis
109 public class ClusterAdminRpcService implements ClusterAdminService {
110 private static final Timeout SHARD_MGR_TIMEOUT = new Timeout(1, TimeUnit.MINUTES);
112 private static final Logger LOG = LoggerFactory.getLogger(ClusterAdminRpcService.class);
114 private final DistributedDataStoreInterface configDataStore;
115 private final DistributedDataStoreInterface operDataStore;
116 private final BindingNormalizedNodeSerializer serializer;
117 private final Timeout makeLeaderLocalTimeout;
119 public ClusterAdminRpcService(final DistributedDataStoreInterface configDataStore,
120 final DistributedDataStoreInterface operDataStore,
121 final BindingNormalizedNodeSerializer serializer) {
122 this.configDataStore = configDataStore;
123 this.operDataStore = operDataStore;
124 this.serializer = serializer;
126 this.makeLeaderLocalTimeout =
127 new Timeout(configDataStore.getActorUtils().getDatastoreContext()
128 .getShardLeaderElectionTimeout().duration().$times(2));
132 public ListenableFuture<RpcResult<AddShardReplicaOutput>> addShardReplica(final AddShardReplicaInput input) {
133 final String shardName = input.getShardName();
134 if (Strings.isNullOrEmpty(shardName)) {
135 return newFailedRpcResultFuture("A valid shard name must be specified");
138 DataStoreType dataStoreType = input.getDataStoreType();
139 if (dataStoreType == null) {
140 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
143 LOG.info("Adding replica for shard {}", shardName);
145 final SettableFuture<RpcResult<AddShardReplicaOutput>> returnFuture = SettableFuture.create();
146 ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, new AddShardReplica(shardName));
147 Futures.addCallback(future, new FutureCallback<Success>() {
149 public void onSuccess(final Success success) {
150 LOG.info("Successfully added replica for shard {}", shardName);
151 returnFuture.set(newSuccessfulResult(new AddShardReplicaOutputBuilder().build()));
155 public void onFailure(final Throwable failure) {
156 onMessageFailure(String.format("Failed to add replica for shard %s", shardName),
157 returnFuture, failure);
159 }, MoreExecutors.directExecutor());
165 public ListenableFuture<RpcResult<RemoveShardReplicaOutput>> removeShardReplica(
166 final RemoveShardReplicaInput input) {
167 final String shardName = input.getShardName();
168 if (Strings.isNullOrEmpty(shardName)) {
169 return newFailedRpcResultFuture("A valid shard name must be specified");
172 DataStoreType dataStoreType = input.getDataStoreType();
173 if (dataStoreType == null) {
174 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
177 final String memberName = input.getMemberName();
178 if (Strings.isNullOrEmpty(memberName)) {
179 return newFailedRpcResultFuture("A valid member name must be specified");
182 LOG.info("Removing replica for shard {} memberName {}, datastoreType {}", shardName, memberName, dataStoreType);
184 final SettableFuture<RpcResult<RemoveShardReplicaOutput>> returnFuture = SettableFuture.create();
185 ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType,
186 new RemoveShardReplica(shardName, MemberName.forName(memberName)));
187 Futures.addCallback(future, new FutureCallback<Success>() {
189 public void onSuccess(final Success success) {
190 LOG.info("Successfully removed replica for shard {}", shardName);
191 returnFuture.set(newSuccessfulResult(new RemoveShardReplicaOutputBuilder().build()));
195 public void onFailure(final Throwable failure) {
196 onMessageFailure(String.format("Failed to remove replica for shard %s", shardName),
197 returnFuture, failure);
199 }, MoreExecutors.directExecutor());
205 public ListenableFuture<RpcResult<MakeLeaderLocalOutput>> makeLeaderLocal(final MakeLeaderLocalInput input) {
206 final String shardName = input.getShardName();
207 if (Strings.isNullOrEmpty(shardName)) {
208 return newFailedRpcResultFuture("A valid shard name must be specified");
211 DataStoreType dataStoreType = input.getDataStoreType();
212 if (dataStoreType == null) {
213 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
216 ActorUtils actorUtils = dataStoreType == DataStoreType.Config
217 ? configDataStore.getActorUtils() : operDataStore.getActorUtils();
219 LOG.info("Moving leader to local node {} for shard {}, datastoreType {}",
220 actorUtils.getCurrentMemberName().getName(), shardName, dataStoreType);
222 final scala.concurrent.Future<ActorRef> localShardReply =
223 actorUtils.findLocalShardAsync(shardName);
225 final scala.concurrent.Promise<Object> makeLeaderLocalAsk = akka.dispatch.Futures.promise();
226 localShardReply.onComplete(new OnComplete<ActorRef>() {
228 public void onComplete(final Throwable failure, final ActorRef actorRef) {
229 if (failure != null) {
230 LOG.warn("No local shard found for {} datastoreType {} - Cannot request leadership transfer to"
231 + " local shard.", shardName, dataStoreType, failure);
232 makeLeaderLocalAsk.failure(failure);
235 .completeWith(actorUtils
236 .executeOperationAsync(actorRef, MakeLeaderLocal.INSTANCE, makeLeaderLocalTimeout));
239 }, actorUtils.getClientDispatcher());
241 final SettableFuture<RpcResult<MakeLeaderLocalOutput>> future = SettableFuture.create();
242 makeLeaderLocalAsk.future().onComplete(new OnComplete<Object>() {
244 public void onComplete(final Throwable failure, final Object success) {
245 if (failure != null) {
246 LOG.error("Leadership transfer failed for shard {}.", shardName, failure);
247 future.set(RpcResultBuilder.<MakeLeaderLocalOutput>failed().withError(ErrorType.APPLICATION,
248 "leadership transfer failed", failure).build());
252 LOG.debug("Leadership transfer complete");
253 future.set(RpcResultBuilder.success(new MakeLeaderLocalOutputBuilder().build()).build());
255 }, actorUtils.getClientDispatcher());
261 public ListenableFuture<RpcResult<AddPrefixShardReplicaOutput>> addPrefixShardReplica(
262 final AddPrefixShardReplicaInput input) {
264 final InstanceIdentifier<?> identifier = input.getShardPrefix();
265 if (identifier == null) {
266 return newFailedRpcResultFuture("A valid shard identifier must be specified");
269 final DataStoreType dataStoreType = input.getDataStoreType();
270 if (dataStoreType == null) {
271 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
274 LOG.info("Adding replica for shard {}, datastore type {}", identifier, dataStoreType);
276 final YangInstanceIdentifier prefix = serializer.toYangInstanceIdentifier(identifier);
277 final SettableFuture<RpcResult<AddPrefixShardReplicaOutput>> returnFuture = SettableFuture.create();
278 ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, new AddPrefixShardReplica(prefix));
279 Futures.addCallback(future, new FutureCallback<Success>() {
281 public void onSuccess(final Success success) {
282 LOG.info("Successfully added replica for shard {}", prefix);
283 returnFuture.set(newSuccessfulResult(new AddPrefixShardReplicaOutputBuilder().build()));
287 public void onFailure(final Throwable failure) {
288 onMessageFailure(String.format("Failed to add replica for shard %s", prefix),
289 returnFuture, failure);
291 }, MoreExecutors.directExecutor());
297 public ListenableFuture<RpcResult<RemovePrefixShardReplicaOutput>> removePrefixShardReplica(
298 final RemovePrefixShardReplicaInput input) {
300 final InstanceIdentifier<?> identifier = input.getShardPrefix();
301 if (identifier == null) {
302 return newFailedRpcResultFuture("A valid shard identifier must be specified");
305 final DataStoreType dataStoreType = input.getDataStoreType();
306 if (dataStoreType == null) {
307 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
310 final String memberName = input.getMemberName();
311 if (Strings.isNullOrEmpty(memberName)) {
312 return newFailedRpcResultFuture("A valid member name must be specified");
315 LOG.info("Removing replica for shard {} memberName {}, datastoreType {}",
316 identifier, memberName, dataStoreType);
317 final YangInstanceIdentifier prefix = serializer.toYangInstanceIdentifier(identifier);
319 final SettableFuture<RpcResult<RemovePrefixShardReplicaOutput>> returnFuture = SettableFuture.create();
320 final ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType,
321 new RemovePrefixShardReplica(prefix, MemberName.forName(memberName)));
322 Futures.addCallback(future, new FutureCallback<Success>() {
324 public void onSuccess(final Success success) {
325 LOG.info("Successfully removed replica for shard {}", prefix);
326 returnFuture.set(newSuccessfulResult(new RemovePrefixShardReplicaOutputBuilder().build()));
330 public void onFailure(final Throwable failure) {
331 onMessageFailure(String.format("Failed to remove replica for shard %s", prefix),
332 returnFuture, failure);
334 }, MoreExecutors.directExecutor());
340 public ListenableFuture<RpcResult<AddReplicasForAllShardsOutput>> addReplicasForAllShards(
341 final AddReplicasForAllShardsInput input) {
342 LOG.info("Adding replicas for all shards");
344 final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData = new ArrayList<>();
345 Function<String, Object> messageSupplier = AddShardReplica::new;
347 sendMessageToManagerForConfiguredShards(DataStoreType.Config, shardResultData, messageSupplier);
348 sendMessageToManagerForConfiguredShards(DataStoreType.Operational, shardResultData, messageSupplier);
350 return waitForShardResults(shardResultData, shardResults ->
351 new AddReplicasForAllShardsOutputBuilder().setShardResult(shardResults).build(),
352 "Failed to add replica");
357 public ListenableFuture<RpcResult<RemoveAllShardReplicasOutput>> removeAllShardReplicas(
358 final RemoveAllShardReplicasInput input) {
359 LOG.info("Removing replicas for all shards");
361 final String memberName = input.getMemberName();
362 if (Strings.isNullOrEmpty(memberName)) {
363 return newFailedRpcResultFuture("A valid member name must be specified");
366 final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData = new ArrayList<>();
367 Function<String, Object> messageSupplier = shardName ->
368 new RemoveShardReplica(shardName, MemberName.forName(memberName));
370 sendMessageToManagerForConfiguredShards(DataStoreType.Config, shardResultData, messageSupplier);
371 sendMessageToManagerForConfiguredShards(DataStoreType.Operational, shardResultData, messageSupplier);
373 return waitForShardResults(shardResultData, shardResults ->
374 new RemoveAllShardReplicasOutputBuilder().setShardResult(shardResults).build(),
375 " Failed to remove replica");
379 public ListenableFuture<RpcResult<ChangeMemberVotingStatesForShardOutput>> changeMemberVotingStatesForShard(
380 final ChangeMemberVotingStatesForShardInput input) {
381 final String shardName = input.getShardName();
382 if (Strings.isNullOrEmpty(shardName)) {
383 return newFailedRpcResultFuture("A valid shard name must be specified");
386 DataStoreType dataStoreType = input.getDataStoreType();
387 if (dataStoreType == null) {
388 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
391 List<MemberVotingState> memberVotingStates = input.getMemberVotingState();
392 if (memberVotingStates == null || memberVotingStates.isEmpty()) {
393 return newFailedRpcResultFuture("No member voting state input was specified");
396 ChangeShardMembersVotingStatus changeVotingStatus = toChangeShardMembersVotingStatus(shardName,
399 LOG.info("Change member voting states for shard {}: {}", shardName,
400 changeVotingStatus.getMeberVotingStatusMap());
402 final SettableFuture<RpcResult<ChangeMemberVotingStatesForShardOutput>> returnFuture = SettableFuture.create();
403 ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, changeVotingStatus);
404 Futures.addCallback(future, new FutureCallback<Success>() {
406 public void onSuccess(final Success success) {
407 LOG.info("Successfully changed member voting states for shard {}", shardName);
408 returnFuture.set(newSuccessfulResult(new ChangeMemberVotingStatesForShardOutputBuilder().build()));
412 public void onFailure(final Throwable failure) {
413 onMessageFailure(String.format("Failed to change member voting states for shard %s", shardName),
414 returnFuture, failure);
416 }, MoreExecutors.directExecutor());
422 public ListenableFuture<RpcResult<ChangeMemberVotingStatesForAllShardsOutput>> changeMemberVotingStatesForAllShards(
423 final ChangeMemberVotingStatesForAllShardsInput input) {
424 List<MemberVotingState> memberVotingStates = input.getMemberVotingState();
425 if (memberVotingStates == null || memberVotingStates.isEmpty()) {
426 return newFailedRpcResultFuture("No member voting state input was specified");
429 final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData = new ArrayList<>();
430 Function<String, Object> messageSupplier = shardName ->
431 toChangeShardMembersVotingStatus(shardName, memberVotingStates);
433 LOG.info("Change member voting states for all shards");
435 sendMessageToManagerForConfiguredShards(DataStoreType.Config, shardResultData, messageSupplier);
436 sendMessageToManagerForConfiguredShards(DataStoreType.Operational, shardResultData, messageSupplier);
438 return waitForShardResults(shardResultData, shardResults ->
439 new ChangeMemberVotingStatesForAllShardsOutputBuilder().setShardResult(shardResults).build(),
440 "Failed to change member voting states");
444 public ListenableFuture<RpcResult<FlipMemberVotingStatesForAllShardsOutput>> flipMemberVotingStatesForAllShards(
445 final FlipMemberVotingStatesForAllShardsInput input) {
446 final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData = new ArrayList<>();
447 Function<String, Object> messageSupplier = FlipShardMembersVotingStatus::new;
449 LOG.info("Flip member voting states for all shards");
451 sendMessageToManagerForConfiguredShards(DataStoreType.Config, shardResultData, messageSupplier);
452 sendMessageToManagerForConfiguredShards(DataStoreType.Operational, shardResultData, messageSupplier);
454 return waitForShardResults(shardResultData, shardResults ->
455 new FlipMemberVotingStatesForAllShardsOutputBuilder().setShardResult(shardResults).build(),
456 "Failed to change member voting states");
460 public ListenableFuture<RpcResult<GetShardRoleOutput>> getShardRole(final GetShardRoleInput input) {
461 final String shardName = input.getShardName();
462 if (Strings.isNullOrEmpty(shardName)) {
463 return newFailedRpcResultFuture("A valid shard name must be specified");
466 DataStoreType dataStoreType = input.getDataStoreType();
467 if (dataStoreType == null) {
468 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
471 LOG.info("Getting role for shard {}, datastore type {}", shardName, dataStoreType);
473 final SettableFuture<RpcResult<GetShardRoleOutput>> returnFuture = SettableFuture.create();
474 ListenableFuture<GetShardRoleReply> future = sendMessageToShardManager(dataStoreType,
475 new GetShardRole(shardName));
476 Futures.addCallback(future, new FutureCallback<GetShardRoleReply>() {
478 public void onSuccess(final GetShardRoleReply reply) {
480 returnFuture.set(ClusterAdminRpcService.<GetShardRoleOutput>newFailedRpcResultBuilder(
481 "No Shard role present. Please retry..").build());
484 LOG.info("Successfully received role:{} for shard {}", reply.getRole(), shardName);
485 final GetShardRoleOutputBuilder builder = new GetShardRoleOutputBuilder();
486 if (reply.getRole() != null) {
487 builder.setRole(reply.getRole());
489 returnFuture.set(newSuccessfulResult(builder.build()));
493 public void onFailure(final Throwable failure) {
494 returnFuture.set(ClusterAdminRpcService.<GetShardRoleOutput>newFailedRpcResultBuilder(
495 "Failed to get shard role.", failure).build());
497 }, MoreExecutors.directExecutor());
503 public ListenableFuture<RpcResult<GetPrefixShardRoleOutput>> getPrefixShardRole(
504 final GetPrefixShardRoleInput input) {
505 final InstanceIdentifier<?> identifier = input.getShardPrefix();
506 if (identifier == null) {
507 return newFailedRpcResultFuture("A valid shard identifier must be specified");
510 final DataStoreType dataStoreType = input.getDataStoreType();
511 if (dataStoreType == null) {
512 return newFailedRpcResultFuture("A valid DataStoreType must be specified");
515 LOG.info("Getting prefix shard role for shard: {}, datastore type {}", identifier, dataStoreType);
517 final YangInstanceIdentifier prefix = serializer.toYangInstanceIdentifier(identifier);
518 final String shardName = ClusterUtils.getCleanShardName(prefix);
519 final SettableFuture<RpcResult<GetPrefixShardRoleOutput>> returnFuture = SettableFuture.create();
520 ListenableFuture<GetShardRoleReply> future = sendMessageToShardManager(dataStoreType,
521 new GetShardRole(shardName));
522 Futures.addCallback(future, new FutureCallback<GetShardRoleReply>() {
524 public void onSuccess(final GetShardRoleReply reply) {
526 returnFuture.set(ClusterAdminRpcService.<GetPrefixShardRoleOutput>newFailedRpcResultBuilder(
527 "No Shard role present. Please retry..").build());
531 LOG.info("Successfully received role:{} for shard {}", reply.getRole(), shardName);
532 final GetPrefixShardRoleOutputBuilder builder = new GetPrefixShardRoleOutputBuilder();
533 if (reply.getRole() != null) {
534 builder.setRole(reply.getRole());
536 returnFuture.set(newSuccessfulResult(builder.build()));
540 public void onFailure(final Throwable failure) {
541 returnFuture.set(ClusterAdminRpcService.<GetPrefixShardRoleOutput>newFailedRpcResultBuilder(
542 "Failed to get shard role.", failure).build());
544 }, MoreExecutors.directExecutor());
550 public ListenableFuture<RpcResult<BackupDatastoreOutput>> backupDatastore(final BackupDatastoreInput input) {
551 LOG.debug("backupDatastore: {}", input);
553 if (Strings.isNullOrEmpty(input.getFilePath())) {
554 return newFailedRpcResultFuture("A valid file path must be specified");
557 final SettableFuture<RpcResult<BackupDatastoreOutput>> returnFuture = SettableFuture.create();
558 ListenableFuture<List<DatastoreSnapshot>> future = sendMessageToShardManagers(GetSnapshot.INSTANCE);
559 Futures.addCallback(future, new FutureCallback<List<DatastoreSnapshot>>() {
561 public void onSuccess(final List<DatastoreSnapshot> snapshots) {
562 saveSnapshotsToFile(new DatastoreSnapshotList(snapshots), input.getFilePath(), returnFuture);
566 public void onFailure(final Throwable failure) {
567 onDatastoreBackupFailure(input.getFilePath(), returnFuture, failure);
569 }, MoreExecutors.directExecutor());
574 private static ChangeShardMembersVotingStatus toChangeShardMembersVotingStatus(final String shardName,
575 final List<MemberVotingState> memberVotingStatus) {
576 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
577 for (MemberVotingState memberStatus: memberVotingStatus) {
578 serverVotingStatusMap.put(memberStatus.getMemberName(), memberStatus.isVoting());
580 return new ChangeShardMembersVotingStatus(shardName, serverVotingStatusMap);
583 private static <T> SettableFuture<RpcResult<T>> waitForShardResults(
584 final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData,
585 final Function<List<ShardResult>, T> resultDataSupplier,
586 final String failureLogMsgPrefix) {
587 final SettableFuture<RpcResult<T>> returnFuture = SettableFuture.create();
588 final List<ShardResult> shardResults = new ArrayList<>();
589 for (final Entry<ListenableFuture<Success>, ShardResultBuilder> entry : shardResultData) {
590 Futures.addCallback(entry.getKey(), new FutureCallback<Success>() {
592 public void onSuccess(final Success result) {
593 synchronized (shardResults) {
594 ShardResultBuilder shardResult = entry.getValue();
595 LOG.debug("onSuccess for shard {}, type {}", shardResult.getShardName(),
596 shardResult.getDataStoreType());
597 shardResults.add(shardResult.setSucceeded(true).build());
603 public void onFailure(final Throwable failure) {
604 synchronized (shardResults) {
605 ShardResultBuilder shardResult = entry.getValue();
606 LOG.warn("{} for shard {}, type {}", failureLogMsgPrefix, shardResult.getShardName(),
607 shardResult.getDataStoreType(), failure);
608 shardResults.add(shardResult.setSucceeded(false).setErrorMessage(
609 Throwables.getRootCause(failure).getMessage()).build());
614 void checkIfComplete() {
615 LOG.debug("checkIfComplete: expected {}, actual {}", shardResultData.size(), shardResults.size());
616 if (shardResults.size() == shardResultData.size()) {
617 returnFuture.set(newSuccessfulResult(resultDataSupplier.apply(shardResults)));
620 }, MoreExecutors.directExecutor());
625 private <T> void sendMessageToManagerForConfiguredShards(final DataStoreType dataStoreType,
626 final List<Entry<ListenableFuture<T>, ShardResultBuilder>> shardResultData,
627 final Function<String, Object> messageSupplier) {
628 ActorUtils actorUtils = dataStoreType == DataStoreType.Config ? configDataStore.getActorUtils()
629 : operDataStore.getActorUtils();
630 Set<String> allShardNames = actorUtils.getConfiguration().getAllShardNames();
632 LOG.debug("Sending message to all shards {} for data store {}", allShardNames, actorUtils.getDataStoreName());
634 for (String shardName: allShardNames) {
635 ListenableFuture<T> future = this.ask(actorUtils.getShardManager(), messageSupplier.apply(shardName),
637 shardResultData.add(new SimpleEntry<>(future,
638 new ShardResultBuilder().setShardName(shardName).setDataStoreType(dataStoreType)));
642 private <T> ListenableFuture<List<T>> sendMessageToShardManagers(final Object message) {
643 Timeout timeout = SHARD_MGR_TIMEOUT;
644 ListenableFuture<T> configFuture = ask(configDataStore.getActorUtils().getShardManager(), message, timeout);
645 ListenableFuture<T> operFuture = ask(operDataStore.getActorUtils().getShardManager(), message, timeout);
647 return Futures.allAsList(configFuture, operFuture);
650 private <T> ListenableFuture<T> sendMessageToShardManager(final DataStoreType dataStoreType, final Object message) {
651 ActorRef shardManager = dataStoreType == DataStoreType.Config
652 ? configDataStore.getActorUtils().getShardManager()
653 : operDataStore.getActorUtils().getShardManager();
654 return ask(shardManager, message, SHARD_MGR_TIMEOUT);
657 @SuppressWarnings("checkstyle:IllegalCatch")
658 private static void saveSnapshotsToFile(final DatastoreSnapshotList snapshots, final String fileName,
659 final SettableFuture<RpcResult<BackupDatastoreOutput>> returnFuture) {
660 try (FileOutputStream fos = new FileOutputStream(fileName)) {
661 SerializationUtils.serialize(snapshots, fos);
663 returnFuture.set(newSuccessfulResult(new BackupDatastoreOutputBuilder().build()));
664 LOG.info("Successfully backed up datastore to file {}", fileName);
665 } catch (IOException | RuntimeException e) {
666 onDatastoreBackupFailure(fileName, returnFuture, e);
670 private static <T> void onDatastoreBackupFailure(final String fileName,
671 final SettableFuture<RpcResult<T>> returnFuture, final Throwable failure) {
672 onMessageFailure(String.format("Failed to back up datastore to file %s", fileName), returnFuture, failure);
675 @SuppressFBWarnings("SLF4J_SIGN_ONLY_FORMAT")
676 private static <T> void onMessageFailure(final String msg, final SettableFuture<RpcResult<T>> returnFuture,
677 final Throwable failure) {
678 LOG.error("{}", msg, failure);
679 returnFuture.set(ClusterAdminRpcService.<T>newFailedRpcResultBuilder(String.format("%s: %s", msg,
680 failure.getMessage())).build());
683 private <T> ListenableFuture<T> ask(final ActorRef actor, final Object message, final Timeout timeout) {
684 final SettableFuture<T> returnFuture = SettableFuture.create();
686 @SuppressWarnings("unchecked")
687 scala.concurrent.Future<T> askFuture = (scala.concurrent.Future<T>) Patterns.ask(actor, message, timeout);
688 askFuture.onComplete(new OnComplete<T>() {
690 public void onComplete(final Throwable failure, final T resp) {
691 if (failure != null) {
692 returnFuture.setException(failure);
694 returnFuture.set(resp);
697 }, configDataStore.getActorUtils().getClientDispatcher());
702 private static <T> ListenableFuture<RpcResult<T>> newFailedRpcResultFuture(final String message) {
703 return ClusterAdminRpcService.<T>newFailedRpcResultBuilder(message).buildFuture();
706 private static <T> RpcResultBuilder<T> newFailedRpcResultBuilder(final String message) {
707 return newFailedRpcResultBuilder(message, null);
710 private static <T> RpcResultBuilder<T> newFailedRpcResultBuilder(final String message, final Throwable cause) {
711 return RpcResultBuilder.<T>failed().withError(ErrorType.RPC, message, cause);
714 private static <T> RpcResult<T> newSuccessfulResult(final T data) {
715 return RpcResultBuilder.success(data).build();