flow descriptors should be always stored when addFlow is called
[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         final DeviceContext deviceContext = getDeviceContext();
78         final FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
79         final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
80         deviceContext.getDeviceFlowRegistry().store(flowHash, flowDescriptor);
81         Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
82
83
84             @Override
85             public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
86                 if (rpcResult.isSuccessful()) {
87                     LOG.debug("flow add finished without error, id={}", flowId.getValue());
88                 } else {
89                     LOG.debug("flow add failed with error, id={}", flowId.getValue());
90                 }
91             }
92
93             @Override
94             public void onFailure(final Throwable throwable) {
95                 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
96                 LOG.trace("Service call for adding flows failed, id={}.", flowId.getValue(), throwable);
97             }
98         });
99
100         return future;
101     }
102
103     @Override
104     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
105         LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
106         return this.<RemoveFlowOutput, Void>handleServiceCall(new Function<RequestContext<RemoveFlowOutput>, ListenableFuture<RpcResult<Void>>>() {
107             @Override
108             public ListenableFuture<RpcResult<Void>> apply(final RequestContext<RemoveFlowOutput> requestContext) {
109                 final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, getVersion(),
110                         getDatapathId());
111                 final ListenableFuture<RpcResult<Void>> future = createResultForFlowMod(requestContext, ofFlowModInput);
112                 Futures.addCallback(future, new FutureCallback<RpcResult<Void>>() {
113                     @Override
114                     public void onSuccess(final RpcResult<Void> o) {
115                         final DeviceContext deviceContext = getDeviceContext();
116                         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
117                         FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
118                         deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
119                     }
120
121                     @Override
122                     public void onFailure(final Throwable throwable) {
123                         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
124                         LOG.trace("Flow modification failed..", throwable);
125                         StringBuilder errors = new StringBuilder();
126                         try {
127                             RpcResult<Void> result = future.get();
128                             Collection<RpcError> rpcErrors = result.getErrors();
129                             if (null != rpcErrors && rpcErrors.size() > 0) {
130                                 for (RpcError rpcError : rpcErrors) {
131                                     errors.append(rpcError.getMessage());
132                                 }
133                             }
134                         } catch (InterruptedException | ExecutionException e) {
135                             LOG.trace("Flow modification failed. Can't read errors from RpcResult.");
136                         } finally {
137                             LOG.trace("Flow modification failed. Errors : {}", errors.toString());
138                         }
139                     }
140                 });
141                 return future;
142             }
143         });
144     }
145
146     @Override
147     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
148         final UpdateFlowInput in = input;
149         final UpdatedFlow updated = in.getUpdatedFlow();
150         final OriginalFlow original = in.getOriginalFlow();
151
152         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
153         List<FlowModInputBuilder> ofFlowModInputs;
154
155         if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) {
156             // We would need to remove original and add updated.
157
158             // remove flow
159             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
160             final List<FlowModInputBuilder> ofFlowRemoveInput = FlowConvertor.toFlowModInputs(removeflow.build(),
161                     getVersion(), getDatapathId());
162             // remove flow should be the first
163             allFlowMods.addAll(ofFlowRemoveInput);
164             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
165             ofFlowModInputs = FlowConvertor.toFlowModInputs(addFlowInputBuilder.build(), getVersion(), getDatapathId());
166         } else {
167             ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, getVersion(), getDatapathId());
168         }
169
170         allFlowMods.addAll(ofFlowModInputs);
171         ListenableFuture<RpcResult<UpdateFlowOutput>> future = processFlowModInputBuilders(allFlowMods);
172         Futures.addCallback(future, new FutureCallback<RpcResult<UpdateFlowOutput>>() {
173             @Override
174             public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
175                 final DeviceContext deviceContext = getDeviceContext();
176                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
177                 final short version = deviceContext.getPrimaryConnectionContext().getFeatures().getVersion();
178                 FlowHash flowHash = FlowHashFactory.create(original, version);
179
180                 FlowHash updatedflowHash = FlowHashFactory.create(updated, version);
181                 FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
182                 FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
183                 final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
184                 deviceFlowRegistry.markToBeremoved(flowHash);
185                 deviceFlowRegistry.store(updatedflowHash, flowDescriptor);
186             }
187
188             @Override
189             public void onFailure(final Throwable throwable) {
190                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
191             }
192         });
193         return future;
194     }
195
196     private <T> ListenableFuture<RpcResult<T>> processFlowModInputBuilders(final List<FlowModInputBuilder> ofFlowModInputs) {
197
198         final List<ListenableFuture<RpcResult<T>>> partialFutures = new ArrayList<>();
199
200         for (final FlowModInputBuilder flowModInputBuilder : ofFlowModInputs) {
201             ListenableFuture<RpcResult<T>> partialFuture = handleServiceCall(
202                     new Function<RequestContext<T>, ListenableFuture<RpcResult<Void>>>() {
203                         @Override
204                         public ListenableFuture<RpcResult<Void>> apply(final RequestContext<T> requestContext) {
205                             return createResultForFlowMod(requestContext, flowModInputBuilder);
206                         }
207                     });
208             partialFutures.add(partialFuture);
209         }
210
211         final ListenableFuture<List<RpcResult<T>>> allFutures = Futures.successfulAsList(partialFutures);
212         final SettableFuture<RpcResult<T>> finalFuture = SettableFuture.create();
213         Futures.addCallback(allFutures, new FutureCallback<List<RpcResult<T>>>() {
214             @Override
215             public void onSuccess(final List<RpcResult<T>> results) {
216                 RpcResultBuilder<T> rpcResultBuilder = RpcResultBuilder.success();
217                 finalFuture.set(rpcResultBuilder.build());
218             }
219
220             @Override
221             public void onFailure(final Throwable t) {
222                 RpcResultBuilder<T> rpcResultBuilder = RpcResultBuilder.failed();
223                 finalFuture.set(rpcResultBuilder.build());
224             }
225         });
226
227         return finalFuture;
228     }
229
230     protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final RequestContext<T> requestContext, final FlowModInputBuilder flowModInputBuilder) {
231         final OutboundQueue outboundQueue = getDeviceContext().getPrimaryConnectionContext().getOutboundQueueProvider();
232         final long xid = requestContext.getXid().getValue();
233         flowModInputBuilder.setXid(xid);
234         final FlowModInput flowModInput = flowModInputBuilder.build();
235
236         final SettableFuture<RpcResult<Void>> settableFuture = SettableFuture.create();
237         outboundQueue.commitEntry(xid, flowModInput, new FutureCallback<OfHeader>() {
238             @Override
239             public void onSuccess(final OfHeader ofHeader) {
240                 RequestContextUtil.closeRequstContext(requestContext);
241                 getMessageSpy().spyMessage(FlowModInput.class, MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
242
243                 settableFuture.set(SUCCESSFUL_RPCRESULT);
244             }
245
246             @Override
247             public void onFailure(final Throwable throwable) {
248                 RpcResultBuilder<Void> rpcResultBuilder = RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, throwable.getMessage(), throwable);
249                 RequestContextUtil.closeRequstContext(requestContext);
250                 settableFuture.set(rpcResultBuilder.build());
251             }
252         });
253         return settableFuture;
254     }
255
256 }