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