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