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