Introduce a shared successful RpcResult
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / SalFlowServiceImpl.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  * <p/>
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.impl.services;
9
10 import com.google.common.base.Function;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Future;
20 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
21 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
22 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
24 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
25 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
26 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowHash;
27 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
28 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
29 import org.opendaylight.openflowplugin.impl.registry.flow.FlowHashFactory;
30 import org.opendaylight.openflowplugin.impl.util.FlowUtil;
31 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.FlowConvertor;
32 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
50 import org.opendaylight.yangtools.yang.common.RpcError;
51 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
52 import org.opendaylight.yangtools.yang.common.RpcResult;
53 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
54 import org.slf4j.Logger;
55
56 public class SalFlowServiceImpl extends CommonService implements SalFlowService {
57
58     private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
59
60     public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
61         super(requestContextStack, deviceContext);
62     }
63
64     @Override
65     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
66         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_ENTERED);
67
68         final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, getVersion(), getDatapathId());
69         final ListenableFuture<RpcResult<AddFlowOutput>> future = processFlowModInputBuilders(ofFlowModInputs);
70         final FlowId flowId;
71         if (null != input.getFlowRef()) {
72             flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
73         } else {
74             flowId = FlowUtil.createAlienFlowId(input.getTableId());
75         }
76
77         Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
78
79             final DeviceContext deviceContext = getDeviceContext();
80             final FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
81
82             @Override
83             public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
84                 if (rpcResult.isSuccessful()) {
85                     LOG.debug("flow add finished without error, id={}", flowId.getValue());
86                 } else {
87                     LOG.debug("flow add failed with error, id={}", flowId.getValue());
88                 }
89             }
90
91             @Override
92             public void onFailure(final Throwable throwable) {
93                 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
94                 LOG.trace("Service call for adding flows failed, id={}.", flowId.getValue(), throwable);
95             }
96         });
97
98         return future;
99     }
100
101     @Override
102     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
103         LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
104         return this.<RemoveFlowOutput, Void>handleServiceCall(new Function<RequestContext<RemoveFlowOutput>, ListenableFuture<RpcResult<Void>>>() {
105             @Override
106             public ListenableFuture<RpcResult<Void>> apply(final RequestContext<RemoveFlowOutput> requestContext) {
107                 final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, getVersion(),
108                         getDatapathId());
109                 final ListenableFuture<RpcResult<Void>> future = createResultForFlowMod(requestContext, ofFlowModInput);
110                 Futures.addCallback(future, new FutureCallback<RpcResult<Void>>() {
111                     @Override
112                     public void onSuccess(final RpcResult<Void> o) {
113                         final DeviceContext deviceContext = getDeviceContext();
114                         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
115                         FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
116                         deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
117                     }
118
119                     @Override
120                     public void onFailure(final Throwable throwable) {
121                         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
122                         LOG.trace("Flow modification failed..", throwable);
123                         StringBuilder errors = new StringBuilder();
124                         try {
125                             RpcResult<Void> result = future.get();
126                             Collection<RpcError> rpcErrors = result.getErrors();
127                             if (null != rpcErrors && rpcErrors.size() > 0) {
128                                 for (RpcError rpcError : rpcErrors) {
129                                     errors.append(rpcError.getMessage());
130                                 }
131                             }
132                         } catch (InterruptedException | ExecutionException e) {
133                             LOG.trace("Flow modification failed. Can't read errors from RpcResult.");
134                         } finally {
135                             LOG.trace("Flow modification failed. Errors : {}", errors.toString());
136                         }
137                     }
138                 });
139                 return future;
140             }
141         });
142     }
143
144     @Override
145     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
146         final UpdateFlowInput in = input;
147         final UpdatedFlow updated = in.getUpdatedFlow();
148         final OriginalFlow original = in.getOriginalFlow();
149
150         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
151         List<FlowModInputBuilder> ofFlowModInputs;
152
153         if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) {
154             // We would need to remove original and add updated.
155
156             // remove flow
157             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
158             final List<FlowModInputBuilder> ofFlowRemoveInput = FlowConvertor.toFlowModInputs(removeflow.build(),
159                     getVersion(), getDatapathId());
160             // remove flow should be the first
161             allFlowMods.addAll(ofFlowRemoveInput);
162             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
163             ofFlowModInputs = FlowConvertor.toFlowModInputs(addFlowInputBuilder.build(), getVersion(), getDatapathId());
164         } else {
165             ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, getVersion(), getDatapathId());
166         }
167
168         allFlowMods.addAll(ofFlowModInputs);
169         ListenableFuture<RpcResult<UpdateFlowOutput>> future = processFlowModInputBuilders(allFlowMods);
170         Futures.addCallback(future, new FutureCallback<RpcResult<UpdateFlowOutput>>() {
171             @Override
172             public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
173                 final DeviceContext deviceContext = getDeviceContext();
174                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
175                 final short version = deviceContext.getPrimaryConnectionContext().getFeatures().getVersion();
176                 FlowHash flowHash = FlowHashFactory.create(original, version);
177
178                 FlowHash updatedflowHash = FlowHashFactory.create(updated, version);
179                 FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
180                 FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
181                 final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
182                 deviceFlowRegistry.markToBeremoved(flowHash);
183                 deviceFlowRegistry.store(updatedflowHash, flowDescriptor);
184             }
185
186             @Override
187             public void onFailure(final Throwable throwable) {
188                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
189             }
190         });
191         return future;
192     }
193
194     private <T> ListenableFuture<RpcResult<T>> processFlowModInputBuilders(final List<FlowModInputBuilder> ofFlowModInputs) {
195
196         final List<ListenableFuture<RpcResult<T>>> partialFutures = new ArrayList<>();
197
198         for (final FlowModInputBuilder flowModInputBuilder : ofFlowModInputs) {
199             ListenableFuture<RpcResult<T>> partialFuture = handleServiceCall(
200                     new Function<RequestContext<T>, ListenableFuture<RpcResult<Void>>>() {
201                         @Override
202                         public ListenableFuture<RpcResult<Void>> apply(final RequestContext<T> requestContext) {
203                             return createResultForFlowMod(requestContext, flowModInputBuilder);
204                         }
205                     });
206             partialFutures.add(partialFuture);
207         }
208
209         final ListenableFuture<List<RpcResult<T>>> allFutures = Futures.successfulAsList(partialFutures);
210         final SettableFuture<RpcResult<T>> finalFuture = SettableFuture.create();
211         Futures.addCallback(allFutures, new FutureCallback<List<RpcResult<T>>>() {
212             @Override
213             public void onSuccess(final List<RpcResult<T>> results) {
214                 RpcResultBuilder<T> rpcResultBuilder = RpcResultBuilder.success();
215                 finalFuture.set(rpcResultBuilder.build());
216             }
217
218             @Override
219             public void onFailure(final Throwable t) {
220                 RpcResultBuilder<T> rpcResultBuilder = RpcResultBuilder.failed();
221                 finalFuture.set(rpcResultBuilder.build());
222             }
223         });
224
225         return finalFuture;
226     }
227
228     protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final RequestContext<T> requestContext, final FlowModInputBuilder flowModInputBuilder) {
229         final OutboundQueue outboundQueue = getDeviceContext().getPrimaryConnectionContext().getOutboundQueueProvider();
230         final long xid = requestContext.getXid().getValue();
231         flowModInputBuilder.setXid(xid);
232         final FlowModInput flowModInput = flowModInputBuilder.build();
233
234         final SettableFuture<RpcResult<Void>> settableFuture = SettableFuture.create();
235         outboundQueue.commitEntry(xid, flowModInput, new FutureCallback<OfHeader>() {
236             @Override
237             public void onSuccess(final OfHeader ofHeader) {
238                 RequestContextUtil.closeRequstContext(requestContext);
239                 getMessageSpy().spyMessage(FlowModInput.class, MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
240
241                 settableFuture.set(SUCCESSFUL_RPCRESULT);
242             }
243
244             @Override
245             public void onFailure(final Throwable throwable) {
246                 RpcResultBuilder<Void> rpcResultBuilder = RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, throwable.getMessage(), throwable);
247                 RequestContextUtil.closeRequstContext(requestContext);
248                 settableFuture.set(rpcResultBuilder.build());
249             }
250         });
251         return settableFuture;
252     }
253
254 }