ba842961408ce84745f8f59a866098b378deede0
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / admin / ClusterAdminRpcService.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.admin;
9
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.Strings;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import java.io.FileOutputStream;
21 import java.util.List;
22 import java.util.concurrent.Future;
23 import java.util.concurrent.TimeUnit;
24 import org.apache.commons.lang3.SerializationUtils;
25 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
26 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
27 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
28 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshotList;
29 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
31 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ConvertMembersToNonvotingForAllShardsInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ConvertMembersToVotingForAllShardsInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaInput;
38 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
39 import org.opendaylight.yangtools.yang.common.RpcResult;
40 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Implements the yang RPCs defined in the generated ClusterAdminService interface.
46  *
47  * @author Thomas Pantelis
48  */
49 public class ClusterAdminRpcService implements ClusterAdminService, AutoCloseable {
50     private static final Logger LOG = LoggerFactory.getLogger(ClusterAdminRpcService.class);
51
52     private final DistributedDataStore configDataStore;
53     private final DistributedDataStore operDataStore;
54     private RpcRegistration<ClusterAdminService> rpcRegistration;
55
56     public ClusterAdminRpcService(DistributedDataStore configDataStore, DistributedDataStore operDataStore) {
57         this.configDataStore = configDataStore;
58         this.operDataStore = operDataStore;
59     }
60
61     public void start(RpcProviderRegistry rpcProviderRegistry) {
62         LOG.debug("ClusterAdminRpcService starting");
63
64         rpcRegistration = rpcProviderRegistry.addRpcImplementation(ClusterAdminService.class, this);
65     }
66
67     @Override
68     public void close() {
69         if(rpcRegistration != null) {
70             rpcRegistration.close();
71         }
72     }
73
74     @Override
75     public Future<RpcResult<Void>> addShardReplica(final AddShardReplicaInput input) {
76         final String shardName = input.getShardName();
77         if(Strings.isNullOrEmpty(shardName)) {
78             return newFailedRpcResultBuilder("A valid shard name must be specified").buildFuture();
79         }
80
81         LOG.info("Adding replica for shard {}", shardName);
82
83         final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create();
84         ListenableFuture<List<Success>> future = sendMessageToShardManagers(new AddShardReplica(shardName));
85         Futures.addCallback(future, new FutureCallback<List<Success>>() {
86             @Override
87             public void onSuccess(List<Success> snapshots) {
88                 LOG.info("Successfully added replica for shard {}", shardName);
89                 returnFuture.set(newSuccessfulResult());
90             }
91
92             @Override
93             public void onFailure(Throwable failure) {
94                 onMessageFailure(String.format("Failed to add replica for shard %s", shardName),
95                         returnFuture, failure);
96             }
97         });
98
99         return returnFuture;
100     }
101
102     @Override
103     public Future<RpcResult<Void>> removeShardReplica(RemoveShardReplicaInput input) {
104         // TODO implement
105         return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, "operation-not-supported",
106                 "Not implemented yet").buildFuture();
107     }
108
109     @Override
110     public Future<RpcResult<Void>> addReplicasForAllShards() {
111         // TODO implement
112         return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, "operation-not-supported",
113                 "Not implemented yet").buildFuture();
114     }
115
116     @Override
117     public Future<RpcResult<Void>> removeAllShardReplicas() {
118         // TODO implement
119         return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, "operation-not-supported",
120                 "Not implemented yet").buildFuture();
121     }
122
123     @Override
124     public Future<RpcResult<Void>> convertMembersToVotingForAllShards(ConvertMembersToVotingForAllShardsInput input) {
125         // TODO implement
126         return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, "operation-not-supported",
127                 "Not implemented yet").buildFuture();
128     }
129
130     @Override
131     public Future<RpcResult<Void>> convertMembersToNonvotingForAllShards(
132             ConvertMembersToNonvotingForAllShardsInput input) {
133         // TODO implement
134         return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, "operation-not-supported",
135                 "Not implemented yet").buildFuture();
136     }
137
138     @Override
139     public Future<RpcResult<Void>> backupDatastore(final BackupDatastoreInput input) {
140         LOG.debug("backupDatastore: {}", input);
141
142         if(Strings.isNullOrEmpty(input.getFilePath())) {
143             return newFailedRpcResultBuilder("A valid file path must be specified").buildFuture();
144         }
145
146         final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create();
147         ListenableFuture<List<DatastoreSnapshot>> future = sendMessageToShardManagers(GetSnapshot.INSTANCE);
148         Futures.addCallback(future, new FutureCallback<List<DatastoreSnapshot>>() {
149             @Override
150             public void onSuccess(List<DatastoreSnapshot> snapshots) {
151                 saveSnapshotsToFile(new DatastoreSnapshotList(snapshots), input.getFilePath(), returnFuture);
152             }
153
154             @Override
155             public void onFailure(Throwable failure) {
156                 onDatastoreBackupFailure(input.getFilePath(), returnFuture, failure);
157             }
158         });
159
160         return returnFuture;
161     }
162
163     @SuppressWarnings("unchecked")
164     private <T> ListenableFuture<List<T>> sendMessageToShardManagers(Object message) {
165         Timeout timeout = new Timeout(1, TimeUnit.MINUTES);
166         ListenableFuture<T> configFuture = ask(configDataStore.getActorContext().getShardManager(), message, timeout);
167         ListenableFuture<T> operFuture = ask(operDataStore.getActorContext().getShardManager(), message, timeout);
168
169         return Futures.allAsList(configFuture, operFuture);
170     }
171
172     private static void saveSnapshotsToFile(DatastoreSnapshotList snapshots, String fileName,
173             SettableFuture<RpcResult<Void>> returnFuture) {
174         try(FileOutputStream fos = new FileOutputStream(fileName)) {
175             SerializationUtils.serialize(snapshots, fos);
176
177             returnFuture.set(newSuccessfulResult());
178             LOG.info("Successfully backed up datastore to file {}", fileName);
179         } catch(Exception e) {
180             onDatastoreBackupFailure(fileName, returnFuture, e);
181         }
182     }
183
184     private static void onDatastoreBackupFailure(String fileName, SettableFuture<RpcResult<Void>> returnFuture,
185             Throwable failure) {
186         onMessageFailure(String.format("Failed to back up datastore to file %s", fileName), returnFuture, failure);
187     }
188
189     private static void onMessageFailure(String msg, final SettableFuture<RpcResult<Void>> returnFuture,
190             Throwable failure) {
191         LOG.error(msg, failure);
192         returnFuture.set(newFailedRpcResultBuilder(String.format("%s: %s", msg, failure.getMessage())).build());
193     }
194
195     private <T> ListenableFuture<T> ask(ActorRef actor, Object message, Timeout timeout) {
196         final SettableFuture<T> returnFuture = SettableFuture.create();
197
198         @SuppressWarnings("unchecked")
199         scala.concurrent.Future<T> askFuture = (scala.concurrent.Future<T>) Patterns.ask(actor, message, timeout);
200         askFuture.onComplete(new OnComplete<T>() {
201             @Override
202             public void onComplete(Throwable failure, T resp) {
203                 if(failure != null) {
204                     returnFuture.setException(failure);
205                 } else {
206                     returnFuture.set(resp);
207                 }
208             }
209         }, configDataStore.getActorContext().getClientDispatcher());
210
211         return returnFuture;
212     }
213
214     private static RpcResultBuilder<Void> newFailedRpcResultBuilder(String message) {
215         return newFailedRpcResultBuilder(message, null);
216     }
217
218     private static RpcResultBuilder<Void> newFailedRpcResultBuilder(String message, Throwable cause) {
219         return RpcResultBuilder.<Void>failed().withError(ErrorType.RPC, message, cause);
220     }
221
222     private static RpcResult<Void> newSuccessfulResult() {
223         return RpcResultBuilder.<Void>success().build();
224     }
225 }