Bug 1254 - added basic functionality test for OFRpcTaskUtil
[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 task of rpc
108      * @param originalResult
109      * @param notificationProviderService
110      * @param notificationComposer lazy notification composer
111      */
112     public static <R extends RpcResult<? extends TransactionAware>, N extends Notification, INPUT extends DataContainer>
113     void hookFutureNotification(
114             final OFRpcTask<INPUT, R> task,
115             ListenableFuture<R> originalResult,
116             final NotificationProviderService notificationProviderService,
117             final NotificationComposer<N> notificationComposer) {
118         Futures.addCallback(originalResult, new FutureCallback<R>() {
119             @Override
120             public void onSuccess(R result) {
121                 if(null == notificationProviderService) {
122                     LOG.warn("onSuccess(): notificationServiceProvider is null, could not publish result {}",result);
123                 } else if (notificationComposer == null) {
124                     LOG.warn("onSuccess(): notificationComposer is null, could not publish result {}",result);
125                 } else if(result == null) {
126                     LOG.warn("onSuccess(): result is null, could not publish result {}",result);
127                 } else if (result.getResult() == null) {
128                     LOG.warn("onSuccess(): result.getResult() is null, could not publish result {}",result);
129                 } else if (result.getResult().getTransactionId() == null) {
130                     LOG.warn("onSuccess(): result.getResult().getTransactionId() is null, could not publish result {}",result);
131                 } else {
132                     notificationProviderService.publish(notificationComposer.compose(result.getResult().getTransactionId()));
133                     task.getTaskContext().getMessageSpy().spyMessage(
134                             task.getInput(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_SUCCESS);
135                 }
136             }
137
138             @Override
139             public void onFailure(Throwable t) {
140                 //TODO: good place to notify MD-SAL about errors
141                 task.getTaskContext().getMessageSpy().spyMessage(
142                         task.getInput(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
143             }
144         });
145     }
146
147     /**
148      * @param task of rpcl
149      * @param originalResult
150      * @param notificationProviderService
151      * @param notificationComposer lazy notification composer
152      * @return chained result with barrier
153      */
154     public static <TX extends TransactionAware, INPUT extends DataContainer>
155     ListenableFuture<RpcResult<TX>> chainFutureBarrier(
156             final OFRpcTask<INPUT, RpcResult<TX>> task,
157             final ListenableFuture<RpcResult<TX>> originalResult) {
158
159         ListenableFuture<RpcResult<TX>> chainResult = originalResult;
160         if (Objects.firstNonNull(task.isBarrier(), Boolean.FALSE)) {
161
162             chainResult = Futures.transform(originalResult, new AsyncFunction<RpcResult<TX>, RpcResult<TX>>() {
163
164                 @Override
165                 public ListenableFuture<RpcResult<TX>> apply(final RpcResult<TX> input) throws Exception {
166                     if (input.isSuccessful()) {
167                         RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc = sendBarrier(
168                                 task.getSession(), task.getCookie(), task.getMessageService());
169                         ListenableFuture<RpcResult<TX>> barrierTxResult = Futures.transform(
170                                 sendBarrierRpc.getOutput(),
171                                 transformBarrierToTransactionAware(input, sendBarrierRpc.getInput()));
172                         return barrierTxResult;
173                     } else {
174                         return Futures.immediateFuture(input);
175                     }
176                 }
177
178             });
179         }
180
181         return chainResult;
182     }
183
184     /**
185      * @param originalInput
186      * @return
187      */
188     protected static <TX extends TransactionAware> Function<RpcResult<BarrierOutput>, RpcResult<TX>> transformBarrierToTransactionAware(
189             final RpcResult<TX> originalInput, final BarrierInput barrierInput) {
190         return new Function<RpcResult<BarrierOutput>, RpcResult<TX>>() {
191
192             @Override
193             public RpcResult<TX> apply(final RpcResult<BarrierOutput> barrierResult) {
194                 RpcResultBuilder<TX> rpcBuilder = null;
195                 if (barrierResult.isSuccessful()) {
196                     rpcBuilder = RpcResultBuilder.<TX>success();
197                 } else {
198                     rpcBuilder = RpcResultBuilder.<TX>failed();
199                     RpcError rpcError = RpcResultBuilder.newWarning(
200                             ErrorType.RPC,
201                             OFConstants.ERROR_TAG_TIMEOUT,
202                             "barrier sending failed",
203                             OFConstants.APPLICATION_TAG,
204                             "switch failed to respond on barrier request, barrier.xid = "+barrierInput.getXid(),
205                             null);
206                     List<RpcError> chainedErrors = new ArrayList<>();
207                     chainedErrors.add(rpcError);
208                     chainedErrors.addAll(barrierResult.getErrors());
209                     rpcBuilder.withRpcErrors(chainedErrors);
210                 }
211
212                 rpcBuilder.withResult(originalInput.getResult());
213
214                 return rpcBuilder.build();
215             }
216
217         };
218     }
219 }