Merge "BUG 1595 - Clustering : NPE on startup"
[controller.git] / opendaylight / md-sal / sal-remoterpc-connector / src / main / java / org / opendaylight / controller / remote / rpc / RpcBroker.java
1 /*
2  * Copyright (c) 2014 Cisco 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
9 package org.opendaylight.controller.remote.rpc;
10
11 import static akka.pattern.Patterns.ask;
12 import akka.actor.ActorRef;
13 import akka.actor.Props;
14 import akka.dispatch.OnComplete;
15 import akka.japi.Creator;
16 import akka.japi.Pair;
17 import akka.util.Timeout;
18
19 import org.opendaylight.controller.remote.rpc.messages.ExecuteRpc;
20 import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
21 import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
22 import org.opendaylight.controller.remote.rpc.utils.LatestEntryRoutingLogic;
23 import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
24 import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
25 import org.opendaylight.controller.remote.rpc.utils.RoutingLogic;
26 import org.opendaylight.controller.xml.codec.XmlUtils;
27 import org.opendaylight.controller.sal.connector.api.RpcRouter;
28 import org.opendaylight.controller.sal.core.api.Broker;
29 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
30 import org.opendaylight.yangtools.yang.common.RpcError;
31 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
32 import org.opendaylight.yangtools.yang.common.RpcResult;
33 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
34 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.common.util.concurrent.FutureCallback;
40 import com.google.common.util.concurrent.Futures;
41 import com.google.common.util.concurrent.JdkFutureAdapters;
42 import com.google.common.util.concurrent.ListenableFuture;
43
44 import java.util.Arrays;
45 import java.util.Collection;
46 import java.util.List;
47 import java.util.concurrent.Future;
48
49 /**
50  * Actor to initiate execution of remote RPC on other nodes of the cluster.
51  */
52
53 public class RpcBroker extends AbstractUntypedActor {
54
55     private static final Logger LOG = LoggerFactory.getLogger(RpcBroker.class);
56     private final Broker.ProviderSession brokerSession;
57     private final ActorRef rpcRegistry;
58     private final SchemaContext schemaContext;
59
60     private RpcBroker(Broker.ProviderSession brokerSession, ActorRef rpcRegistry,
61             SchemaContext schemaContext) {
62         this.brokerSession = brokerSession;
63         this.rpcRegistry = rpcRegistry;
64         this.schemaContext = schemaContext;
65     }
66
67     public static Props props(Broker.ProviderSession brokerSession, ActorRef rpcRegistry,
68             SchemaContext schemaContext) {
69         return Props.create(new RpcBrokerCreator(brokerSession, rpcRegistry, schemaContext));
70     }
71
72     @Override
73     protected void handleReceive(Object message) throws Exception {
74         if(message instanceof InvokeRpc) {
75             invokeRemoteRpc((InvokeRpc) message);
76         } else if(message instanceof ExecuteRpc) {
77             executeRpc((ExecuteRpc) message);
78         }
79     }
80
81     private void invokeRemoteRpc(final InvokeRpc msg) {
82         LOG.debug("Looking up the remote actor for rpc {}", msg.getRpc());
83
84         RpcRouter.RouteIdentifier<?,?,?> routeId = new RouteIdentifierImpl(
85                 null, msg.getRpc(), msg.getIdentifier());
86         RpcRegistry.Messages.FindRouters findMsg = new RpcRegistry.Messages.FindRouters(routeId);
87
88         scala.concurrent.Future<Object> future = ask(rpcRegistry, findMsg,
89                 new Timeout(ActorUtil.LOCAL_ASK_DURATION));
90
91         final ActorRef sender = getSender();
92         final ActorRef self = self();
93
94         OnComplete<Object> onComplete = new OnComplete<Object>() {
95             @Override
96             public void onComplete(Throwable failure, Object reply) throws Throwable {
97                 if(failure != null) {
98                     LOG.error("FindRouters failed", failure);
99                     sender.tell(new akka.actor.Status.Failure(failure), self);
100                     return;
101                 }
102
103                 RpcRegistry.Messages.FindRoutersReply findReply =
104                                                 (RpcRegistry.Messages.FindRoutersReply)reply;
105
106                 List<Pair<ActorRef, Long>> actorRefList = findReply.getRouterWithUpdateTime();
107
108                 if(actorRefList == null || actorRefList.isEmpty()) {
109                     String message = String.format(
110                             "No remote implementation found for rpc %s",  msg.getRpc());
111                     sender.tell(new akka.actor.Status.Failure(new RpcErrorsException(
112                             message, Arrays.asList(RpcResultBuilder.newError(ErrorType.RPC,
113                                     "operation-not-supported", message)))), self);
114                     return;
115                 }
116
117                 finishInvokeRpc(actorRefList, msg, sender, self);
118             }
119         };
120
121         future.onComplete(onComplete, getContext().dispatcher());
122     }
123
124     protected void finishInvokeRpc(final List<Pair<ActorRef, Long>> actorRefList,
125             final InvokeRpc msg, final ActorRef sender, final ActorRef self) {
126
127         RoutingLogic logic = new LatestEntryRoutingLogic(actorRefList);
128
129         ExecuteRpc executeMsg = new ExecuteRpc(XmlUtils.inputCompositeNodeToXml(msg.getInput(),
130                 schemaContext), msg.getRpc());
131
132         scala.concurrent.Future<Object> future = ask(logic.select(), executeMsg,
133                 new Timeout(ActorUtil.REMOTE_ASK_DURATION));
134
135         OnComplete<Object> onComplete = new OnComplete<Object>() {
136             @Override
137             public void onComplete(Throwable failure, Object reply) throws Throwable {
138                 if(failure != null) {
139                     LOG.error("ExecuteRpc failed", failure);
140                     sender.tell(new akka.actor.Status.Failure(failure), self);
141                     return;
142                 }
143
144                 sender.tell(reply, self);
145             }
146         };
147
148         future.onComplete(onComplete, getContext().dispatcher());
149     }
150
151     private void executeRpc(final ExecuteRpc msg) {
152         LOG.debug("Executing rpc {}", msg.getRpc());
153
154         Future<RpcResult<CompositeNode>> future = brokerSession.rpc(msg.getRpc(),
155                 XmlUtils.inputXmlToCompositeNode(msg.getRpc(), msg.getInputCompositeNode(),
156                         schemaContext));
157
158         ListenableFuture<RpcResult<CompositeNode>> listenableFuture =
159                 JdkFutureAdapters.listenInPoolThread(future);
160
161         final ActorRef sender = getSender();
162         final ActorRef self = self();
163
164         Futures.addCallback(listenableFuture, new FutureCallback<RpcResult<CompositeNode>>() {
165             @Override
166             public void onSuccess(RpcResult<CompositeNode> result) {
167                 if(result.isSuccessful()) {
168                     sender.tell(new RpcResponse(XmlUtils.outputCompositeNodeToXml(result.getResult(),
169                             schemaContext)), self);
170                 } else {
171                     String message = String.format("Execution of RPC %s failed",  msg.getRpc());
172                     Collection<RpcError> errors = result.getErrors();
173                     if(errors == null || errors.size() == 0) {
174                         errors = Arrays.asList(RpcResultBuilder.newError(ErrorType.RPC,
175                                 null, message));
176                     }
177
178                     sender.tell(new akka.actor.Status.Failure(new RpcErrorsException(
179                             message, errors)), self);
180                 }
181             }
182
183             @Override
184             public void onFailure(Throwable t) {
185                 LOG.error("executeRpc for {} failed: {}", msg.getRpc(), t);
186                 sender.tell(new akka.actor.Status.Failure(t), self);
187             }
188         });
189     }
190
191     private static class RpcBrokerCreator implements Creator<RpcBroker> {
192         private static final long serialVersionUID = 1L;
193
194         final Broker.ProviderSession brokerSession;
195         final ActorRef rpcRegistry;
196         final SchemaContext schemaContext;
197
198         RpcBrokerCreator(ProviderSession brokerSession, ActorRef rpcRegistry,
199                 SchemaContext schemaContext) {
200             this.brokerSession = brokerSession;
201             this.rpcRegistry = rpcRegistry;
202             this.schemaContext = schemaContext;
203         }
204
205         @Override
206         public RpcBroker create() throws Exception {
207             return new RpcBroker(brokerSession, rpcRegistry, schemaContext);
208         }
209     }
210 }