73171cbfb508ffb15ebfa76dd077b26133785185
[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.util.RpcInputOutputTuple;
22 import org.opendaylight.openflowplugin.openflow.md.util.TaskUtil;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
26 import org.opendaylight.yangtools.yang.binding.DataContainer;
27 import org.opendaylight.yangtools.yang.binding.Notification;
28 import org.opendaylight.yangtools.yang.common.RpcError;
29 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
30 import org.opendaylight.yangtools.yang.common.RpcResult;
31 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
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.ListenableFuture;
42
43 /**
44  *
45  */
46 public abstract class OFRpcTaskUtil {
47     protected static final Logger LOG = LoggerFactory.getLogger(OFRpcTaskUtil.class);
48     /**
49      * @param taskContext
50      * @param isBarrier
51      * @param cookie
52      * @return rpcResult of given type, containing wrapped errors of barrier sending (if any) or success
53      */
54     private OFRpcTaskUtil() {
55         //hiding implicit constructor
56     }
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                     TaskUtil.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 task of rpc
92      * @param originalResult
93      * @param notificationProviderService
94      * @param notificationComposer lazy notification composer
95      */
96     public static <R extends RpcResult<? extends TransactionAware>, N extends Notification, I extends DataContainer>
97     void hookFutureNotification(
98             final OFRpcTask<I, R> task,
99             ListenableFuture<R> originalResult,
100             final NotificationProviderService notificationProviderService,
101             final NotificationComposer<N> notificationComposer) {
102
103         class FutureCallbackImpl implements FutureCallback<R> {
104             @Override
105             public void onSuccess(R result) {
106                 if(null == notificationProviderService) {
107                     LOG.warn("onSuccess(): notificationServiceProvider is null, could not publish result {}",result);
108                 } else if (notificationComposer == null) {
109                     LOG.warn("onSuccess(): notificationComposer is null, could not publish result {}",result);
110                 } else if(result == null) {
111                     LOG.warn("onSuccess(): result is null, could not publish result {}",result);
112                 } else if (result.getResult() == null) {
113                     LOG.warn("onSuccess(): result.getResult() is null, could not publish result {}",result);
114                 } else if (result.getResult().getTransactionId() == null) {
115                     LOG.warn("onSuccess(): result.getResult().getTransactionId() is null, could not publish result {}",result);
116                 } else {
117                     notificationProviderService.publish(notificationComposer.compose(result.getResult().getTransactionId()));
118                     task.getTaskContext().getMessageSpy().spyMessage(
119                             task.getInput(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_SUCCESS);
120                 }
121             }
122
123             @Override
124             public void onFailure(Throwable t) {
125                 //TODO: good place to notify MD-SAL about errors
126                 task.getTaskContext().getMessageSpy().spyMessage(
127                         task.getInput(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
128             }
129         }
130
131         Futures.addCallback(originalResult, new FutureCallbackImpl());
132     }
133
134     /**
135      * @param task of rpcl
136      * @param originalResult
137      * @param notificationProviderService
138      * @param notificationComposer lazy notification composer
139      * @return chained result with barrier
140      */
141     public static <T extends TransactionAware, I extends DataContainer>
142     ListenableFuture<RpcResult<T>> chainFutureBarrier(
143             final OFRpcTask<I, RpcResult<T>> task,
144             final ListenableFuture<RpcResult<T>> originalResult) {
145
146         ListenableFuture<RpcResult<T>> chainResult = originalResult;
147         if (Objects.firstNonNull(task.isBarrier(), Boolean.FALSE)) {
148
149             chainResult = Futures.transform(originalResult, new AsyncFunction<RpcResult<T>, RpcResult<T>>() {
150
151                 @Override
152                 public ListenableFuture<RpcResult<T>> apply(final RpcResult<T> input) throws Exception {
153                     if (input.isSuccessful()) {
154                         RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc = TaskUtil.sendBarrier(
155                                 task.getSession(), task.getCookie(), task.getMessageService());
156                         ListenableFuture<RpcResult<T>> barrierTxResult = Futures.transform(
157                                 sendBarrierRpc.getOutput(),
158                                 transformBarrierToTransactionAware(input, sendBarrierRpc.getInput()));
159                         return barrierTxResult;
160                     } else {
161                         return Futures.immediateFuture(input);
162                     }
163                 }
164
165             });
166         }
167
168         return chainResult;
169     }
170
171     /**
172      * @param originalInput
173      * @return
174      */
175     protected static <T extends TransactionAware> Function<RpcResult<BarrierOutput>, RpcResult<T>> transformBarrierToTransactionAware(
176             final RpcResult<T> originalInput, final BarrierInput barrierInput) {
177
178         class FunctionImpl implements Function<RpcResult<BarrierOutput>, RpcResult<T>> {
179
180             @Override
181             public RpcResult<T> apply(final RpcResult<BarrierOutput> barrierResult) {
182                 RpcResultBuilder<T> rpcBuilder = null;
183                 if (barrierResult.isSuccessful()) {
184                     rpcBuilder = RpcResultBuilder.<T>success();
185                 } else {
186                     rpcBuilder = RpcResultBuilder.<T>failed();
187                     RpcError rpcError = RpcResultBuilder.newWarning(
188                             ErrorType.RPC,
189                             OFConstants.ERROR_TAG_TIMEOUT,
190                             "barrier sending failed",
191                             OFConstants.APPLICATION_TAG,
192                             "switch failed to respond on barrier request, barrier.xid = "+barrierInput.getXid(),
193                             null);
194                     List<RpcError> chainedErrors = new ArrayList<>();
195                     chainedErrors.add(rpcError);
196                     chainedErrors.addAll(barrierResult.getErrors());
197                     rpcBuilder.withRpcErrors(chainedErrors);
198                 }
199
200                 rpcBuilder.withResult(originalInput.getResult());
201
202                 return rpcBuilder.build();
203             }
204         }
205
206         return new FunctionImpl();
207     }
208 }