Merge "Bug 1904: Handle null ThreadExecutorStatsMXBeanImpl in ShardStats"
[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 akka.actor.ActorRef;
12 import akka.actor.Props;
13 import akka.dispatch.OnComplete;
14 import akka.japi.Creator;
15 import akka.japi.Pair;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.JdkFutureAdapters;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor;
21 import org.opendaylight.controller.remote.rpc.messages.ExecuteRpc;
22 import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
23 import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
24 import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
25 import org.opendaylight.controller.remote.rpc.utils.LatestEntryRoutingLogic;
26 import org.opendaylight.controller.remote.rpc.utils.RoutingLogic;
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.controller.xml.codec.XmlUtils;
31 import org.opendaylight.yangtools.yang.common.RpcError;
32 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
33 import org.opendaylight.yangtools.yang.common.RpcResult;
34 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
35 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import java.util.Arrays;
41 import java.util.Collection;
42 import java.util.List;
43 import java.util.concurrent.Future;
44
45 import static akka.pattern.Patterns.ask;
46
47 /**
48  * Actor to initiate execution of remote RPC on other nodes of the cluster.
49  */
50
51 public class RpcBroker extends AbstractUntypedActor {
52
53     private static final Logger LOG = LoggerFactory.getLogger(RpcBroker.class);
54     private final Broker.ProviderSession brokerSession;
55     private final ActorRef rpcRegistry;
56     private final SchemaContext schemaContext;
57     private final RemoteRpcProviderConfig config;
58
59     private RpcBroker(Broker.ProviderSession brokerSession, ActorRef rpcRegistry,
60             SchemaContext schemaContext) {
61         this.brokerSession = brokerSession;
62         this.rpcRegistry = rpcRegistry;
63         this.schemaContext = schemaContext;
64         config = new RemoteRpcProviderConfig(getContext().system().settings().config());
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         if(LOG.isDebugEnabled()) {
83             LOG.debug("Looking up the remote actor for rpc {}", msg.getRpc());
84         }
85         RpcRouter.RouteIdentifier<?,?,?> routeId = new RouteIdentifierImpl(
86                 null, msg.getRpc(), msg.getIdentifier());
87         RpcRegistry.Messages.FindRouters findMsg = new RpcRegistry.Messages.FindRouters(routeId);
88
89         scala.concurrent.Future<Object> future = ask(rpcRegistry, findMsg, config.getAskDuration());
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, config.getAskDuration());
133
134         OnComplete<Object> onComplete = new OnComplete<Object>() {
135             @Override
136             public void onComplete(Throwable failure, Object reply) throws Throwable {
137                 if(failure != null) {
138                     LOG.error("ExecuteRpc failed", failure);
139                     sender.tell(new akka.actor.Status.Failure(failure), self);
140                     return;
141                 }
142
143                 sender.tell(reply, self);
144             }
145         };
146
147         future.onComplete(onComplete, getContext().dispatcher());
148     }
149
150     private void executeRpc(final ExecuteRpc msg) {
151         if(LOG.isDebugEnabled()) {
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 }