Bug 2068: Fix NPE in OFRPCUtil$1.onSuccess, improve logging.
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / sal / OFRpcTaskUtil.java
1 /**
2  * Copyright (c) 2013 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 package org.opendaylight.openflowplugin.openflow.md.core.sal;
9
10 import java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.concurrent.Future;
15
16 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
17 import org.opendaylight.openflowplugin.api.OFConstants;
18 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
19 import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer;
20 import org.opendaylight.openflowplugin.api.statistics.MessageSpy;
21 import org.opendaylight.openflowplugin.openflow.md.core.MessageFactory;
22 import org.opendaylight.openflowplugin.openflow.md.core.session.IMessageDispatchService;
23 import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContext;
24 import org.opendaylight.openflowplugin.openflow.md.util.RpcInputOutputTuple;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
28 import org.opendaylight.yangtools.yang.binding.DataContainer;
29 import org.opendaylight.yangtools.yang.binding.Notification;
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.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import com.google.common.base.Function;
38 import com.google.common.base.Objects;
39 import com.google.common.collect.Lists;
40 import com.google.common.util.concurrent.AsyncFunction;
41 import com.google.common.util.concurrent.FutureCallback;
42 import com.google.common.util.concurrent.Futures;
43 import com.google.common.util.concurrent.JdkFutureAdapters;
44 import com.google.common.util.concurrent.ListenableFuture;
45 import com.google.common.util.concurrent.SettableFuture;
46
47 /**
48  *
49  */
50 public abstract class OFRpcTaskUtil {
51     protected static final Logger LOG = LoggerFactory.getLogger(OFRpcTaskUtil.class);
52     /**
53      * @param taskContext
54      * @param isBarrier
55      * @param cookie
56      * @return rpcResult of given type, containing wrapped errors of barrier sending (if any) or success
57      */
58     public static Collection<RpcError> manageBarrier(OFRpcTaskContext taskContext, Boolean isBarrier,
59             SwitchConnectionDistinguisher cookie) {
60         Collection<RpcError> errors = null;
61         if (Objects.firstNonNull(isBarrier, Boolean.FALSE)) {
62             RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc =
63                     sendBarrier(taskContext.getSession(), cookie, taskContext.getMessageService());
64             Future<RpcResult<BarrierOutput>> barrierFuture = sendBarrierRpc.getOutput();
65             try {
66                 RpcResult<BarrierOutput> barrierResult = barrierFuture.get(
67                         taskContext.getMaxTimeout(), taskContext.getMaxTimeoutUnit());
68                 if (!barrierResult.isSuccessful()) {
69                     errors = barrierResult.getErrors();
70                 }
71             } catch (Exception e) {
72                 RpcError rpcError = RpcResultBuilder.newWarning(
73                         ErrorType.RPC,
74                         OFConstants.ERROR_TAG_TIMEOUT,
75                         "barrier sending failed",
76                         OFConstants.APPLICATION_TAG,
77                         "switch failed to respond on barrier request - message ordering is not preserved",
78                         e);
79                 errors = Lists.newArrayList(rpcError);
80             }
81         }
82
83         if (errors == null) {
84             errors = Collections.emptyList();
85         }
86
87         return errors;
88     }
89
90     /**
91      * @param session
92      * @param cookie
93      * @param messageService
94      * @return barrier response
95      */
96     protected static RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrier(SessionContext session,
97             SwitchConnectionDistinguisher cookie, IMessageDispatchService messageService) {
98         BarrierInput barrierInput = MessageFactory.createBarrier(
99                 session.getFeatures().getVersion(), session.getNextXid());
100         Future<RpcResult<BarrierOutput>> barrierResult = messageService.barrier(barrierInput, cookie);
101         ListenableFuture<RpcResult<BarrierOutput>> output = JdkFutureAdapters.listenInPoolThread(barrierResult);
102
103         return new RpcInputOutputTuple<>(barrierInput, output);
104     }
105
106     /**
107      * @param result rpcResult with success = false, errors = given collection
108      * @param barrierErrors
109      */
110     public static <T> void wrapBarrierErrors(SettableFuture<RpcResult<T>> result,
111             Collection<RpcError> barrierErrors) {
112         result.set(RpcResultBuilder.<T>failed().withRpcErrors(barrierErrors).build());
113     }
114
115     /**
116      * @param task of rpc
117      * @param originalResult
118      * @param notificationProviderService
119      * @param notificationComposer lazy notification composer
120      */
121     public static <R extends RpcResult<? extends TransactionAware>, N extends Notification, INPUT extends DataContainer>
122     void hookFutureNotification(
123             final OFRpcTask<INPUT, R> task,
124             ListenableFuture<R> originalResult,
125             final NotificationProviderService notificationProviderService,
126             final NotificationComposer<N> notificationComposer) {
127         Futures.addCallback(originalResult, new FutureCallback<R>() {
128             @Override
129             public void onSuccess(R result) {
130                 if(null == notificationProviderService) {
131                     LOG.warn("onSuccess(): notificationServiceProvider is null, could not publish result {}",result);
132                 } else if (notificationComposer == null) {
133                     LOG.warn("onSuccess(): notificationComposer is null, could not publish result {}",result);
134                 } else if(result == null) {
135                     LOG.warn("onSuccess(): result is null, could not publish result {}",result);
136                 } else if (result.getResult() == null) {
137                     LOG.warn("onSuccess(): result.getResult() is null, could not publish result {}",result);
138                 } else if (result.getResult().getTransactionId() == null) {
139                     LOG.warn("onSuccess(): result.getResult().getTransactionId() is null, could not publish result {}",result);
140                 } else {
141                     notificationProviderService.publish(notificationComposer.compose(result.getResult().getTransactionId()));
142                     task.getTaskContext().getMessageSpy().spyMessage(
143                             task.getInput(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_SUCCESS);
144                 }
145             }
146
147             @Override
148             public void onFailure(Throwable t) {
149                 //TODO: good place to notify MD-SAL about errors
150                 task.getTaskContext().getMessageSpy().spyMessage(
151                         task.getInput(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
152             }
153         });
154     }
155
156     /**
157      * @param task of rpc
158      * @param originalResult
159      * @param notificationProviderService
160      * @param notificationComposer lazy notification composer
161      * @return chained result with barrier
162      */
163     public static <TX extends TransactionAware, INPUT extends DataContainer>
164     ListenableFuture<RpcResult<TX>> chainFutureBarrier(
165             final OFRpcTask<INPUT, RpcResult<TX>> task,
166             final ListenableFuture<RpcResult<TX>> originalResult) {
167
168         ListenableFuture<RpcResult<TX>> chainResult = originalResult;
169         if (Objects.firstNonNull(task.isBarrier(), Boolean.FALSE)) {
170
171             chainResult = Futures.transform(originalResult, new AsyncFunction<RpcResult<TX>, RpcResult<TX>>() {
172
173                 @Override
174                 public ListenableFuture<RpcResult<TX>> apply(final RpcResult<TX> input) throws Exception {
175                     if (input.isSuccessful()) {
176                         RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc = sendBarrier(
177                                 task.getSession(), task.getCookie(), task.getMessageService());
178                         ListenableFuture<RpcResult<TX>> barrierTxResult = Futures.transform(
179                                 sendBarrierRpc.getOutput(),
180                                 transformBarrierToTransactionAware(input, sendBarrierRpc.getInput()));
181                         return barrierTxResult;
182                     } else {
183                         return Futures.immediateFuture(input);
184                     }
185                 }
186
187             });
188         }
189
190         return chainResult;
191     }
192
193     /**
194      * @param originalInput
195      * @return
196      */
197     protected static <TX extends TransactionAware> Function<RpcResult<BarrierOutput>, RpcResult<TX>> transformBarrierToTransactionAware(
198             final RpcResult<TX> originalInput, final BarrierInput barrierInput) {
199         return new Function<RpcResult<BarrierOutput>, RpcResult<TX>>() {
200
201             @Override
202             public RpcResult<TX> apply(final RpcResult<BarrierOutput> barrierResult) {
203                 RpcResultBuilder<TX> rpcBuilder = null;
204                 if (barrierResult.isSuccessful()) {
205                     rpcBuilder = RpcResultBuilder.<TX>success();
206                 } else {
207                     rpcBuilder = RpcResultBuilder.<TX>failed();
208                     RpcError rpcError = RpcResultBuilder.newWarning(
209                             ErrorType.RPC,
210                             OFConstants.ERROR_TAG_TIMEOUT,
211                             "barrier sending failed",
212                             OFConstants.APPLICATION_TAG,
213                             "switch failed to respond on barrier request, barrier.xid = "+barrierInput.getXid(),
214                             null);
215                     List<RpcError> chainedErrors = new ArrayList<>();
216                     chainedErrors.add(rpcError);
217                     chainedErrors.addAll(barrierResult.getErrors());
218                     rpcBuilder.withRpcErrors(chainedErrors);
219                 }
220
221                 rpcBuilder.withResult(originalInput.getResult());
222
223                 return rpcBuilder.build();
224             }
225
226         };
227     }
228 }