Merge "OPNFLWPLUG-983 Group and flow removal stats are not reported in order"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / sal / SalFlowServiceImpl.java
1 /**
2  * Copyright (c) 2015 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.impl.services.sal;
9
10 import com.google.common.util.concurrent.FutureCallback;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.MoreExecutors;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Objects;
18 import java.util.concurrent.Future;
19 import javax.annotation.Nonnull;
20 import org.opendaylight.openflowplugin.api.OFConstants;
21 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
22 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
23 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
24 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
25 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
26 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
27 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
28 import org.opendaylight.openflowplugin.impl.services.multilayer.MultiLayerFlowService;
29 import org.opendaylight.openflowplugin.impl.services.singlelayer.SingleLayerFlowService;
30 import org.opendaylight.openflowplugin.impl.util.ErrorUtil;
31 import org.opendaylight.openflowplugin.impl.util.FlowCreatorUtil;
32 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
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.FlowModInputBuilder;
48 import org.opendaylight.yangtools.yang.common.RpcError;
49 import org.opendaylight.yangtools.yang.common.RpcResult;
50 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class SalFlowServiceImpl implements SalFlowService {
55     private static final Logger LOG = LoggerFactory.getLogger(SalFlowServiceImpl.class);
56     private final MultiLayerFlowService<UpdateFlowOutput> flowUpdate;
57     private final MultiLayerFlowService<AddFlowOutput> flowAdd;
58     private final MultiLayerFlowService<RemoveFlowOutput> flowRemove;
59     private final SingleLayerFlowService<AddFlowOutput> flowAddMessage;
60     private final SingleLayerFlowService<UpdateFlowOutput> flowUpdateMessage;
61     private final SingleLayerFlowService<RemoveFlowOutput> flowRemoveMessage;
62     private final DeviceContext deviceContext;
63
64     public SalFlowServiceImpl(final RequestContextStack requestContextStack,
65                               final DeviceContext deviceContext,
66                               final ConvertorExecutor convertorExecutor) {
67         this.deviceContext = deviceContext;
68         flowRemove = new MultiLayerFlowService<>(requestContextStack,
69                                                  deviceContext,
70                                                  RemoveFlowOutput.class,
71                                                  convertorExecutor);
72         flowAdd = new MultiLayerFlowService<>(requestContextStack,
73                                               deviceContext,
74                                               AddFlowOutput.class,
75                                               convertorExecutor);
76         flowUpdate = new MultiLayerFlowService<>(requestContextStack,
77                                                  deviceContext,
78                                                  UpdateFlowOutput.class,
79                                                  convertorExecutor);
80         flowAddMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, AddFlowOutput.class);
81         flowUpdateMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class);
82         flowRemoveMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, RemoveFlowOutput.class);
83     }
84
85     @Override
86     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
87         final FlowRegistryKey flowRegistryKey =
88                 FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
89         final ListenableFuture<RpcResult<AddFlowOutput>> future;
90
91         if (flowAddMessage.canUseSingleLayerSerialization()) {
92             future = flowAddMessage.handleServiceCall(input);
93             Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey), MoreExecutors.directExecutor());
94         } else {
95             future = flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
96             Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey), MoreExecutors.directExecutor());
97
98         }
99         return future;
100     }
101
102     @Override
103     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
104         final ListenableFuture<RpcResult<RemoveFlowOutput>> future;
105
106         if (flowRemoveMessage.canUseSingleLayerSerialization()) {
107             future = flowRemoveMessage.handleServiceCall(input);
108             Futures.addCallback(future, new RemoveFlowCallback(input), MoreExecutors.directExecutor());
109
110         } else {
111             future = flowRemove.processFlowModInputBuilders(flowRemove.toFlowModInputs(input));
112             Futures.addCallback(future, new RemoveFlowCallback(input), MoreExecutors.directExecutor());
113         }
114
115         return future;
116     }
117
118     @Override
119     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
120         final UpdatedFlow updated = input.getUpdatedFlow();
121         final OriginalFlow original = input.getOriginalFlow();
122
123         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
124         final List<FlowModInputBuilder> ofFlowModInputs;
125
126         ListenableFuture<RpcResult<UpdateFlowOutput>> future;
127         if (flowUpdateMessage.canUseSingleLayerSerialization()) {
128
129             if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdateMessage.getVersion())) {
130                 final SettableFuture<RpcResult<UpdateFlowOutput>> objectSettableFuture = SettableFuture.create();
131
132                 final ListenableFuture<List<RpcResult<UpdateFlowOutput>>> listListenableFuture =
133                         Futures.successfulAsList(flowUpdateMessage.handleServiceCall(input.getOriginalFlow()),
134                                                  flowUpdateMessage.handleServiceCall(input.getUpdatedFlow()));
135
136                 Futures.addCallback(listListenableFuture, new FutureCallback<List<RpcResult<UpdateFlowOutput>>>() {
137                     @Override
138                     public void onSuccess(@Nonnull final List<RpcResult<UpdateFlowOutput>> results) {
139                         final ArrayList<RpcError> errors = new ArrayList();
140                         for (RpcResult<UpdateFlowOutput> flowModResult : results) {
141                             if (flowModResult == null) {
142                                 errors.add(RpcResultBuilder.newError(
143                                         RpcError.ErrorType.PROTOCOL, OFConstants.APPLICATION_TAG,
144                                         "unexpected flowMod result (null) occurred"));
145                             } else if (!flowModResult.isSuccessful()) {
146                                 errors.addAll(flowModResult.getErrors());
147                             }
148                         }
149
150                         final RpcResultBuilder<UpdateFlowOutput> rpcResultBuilder;
151                         if (errors.isEmpty()) {
152                             rpcResultBuilder = RpcResultBuilder.success();
153                         } else {
154                             rpcResultBuilder = RpcResultBuilder.<UpdateFlowOutput>failed().withRpcErrors(errors);
155                         }
156
157                         objectSettableFuture.set(rpcResultBuilder.build());
158                     }
159
160                     @Override
161                     public void onFailure(final Throwable throwable) {
162                         RpcResultBuilder<UpdateFlowOutput> rpcResultBuilder = RpcResultBuilder.failed();
163                         objectSettableFuture.set(rpcResultBuilder.build());
164                     }
165                 }, MoreExecutors.directExecutor());
166
167                 future = objectSettableFuture;
168             } else {
169                 future = flowUpdateMessage.handleServiceCall(input.getUpdatedFlow());
170             }
171         } else {
172             if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdate.getVersion())) {
173                 // We would need to remove original and add updated.
174
175                 // remove flow
176                 final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
177                 final List<FlowModInputBuilder> ofFlowRemoveInput = flowUpdate.toFlowModInputs(removeflow.build());
178                 // remove flow should be the first
179                 allFlowMods.addAll(ofFlowRemoveInput);
180                 final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
181                 ofFlowModInputs = flowUpdate.toFlowModInputs(addFlowInputBuilder.build());
182             } else {
183                 ofFlowModInputs = flowUpdate.toFlowModInputs(updated);
184             }
185
186             allFlowMods.addAll(ofFlowModInputs);
187
188             future = flowUpdate.processFlowModInputBuilders(allFlowMods);
189         }
190
191         Futures.addCallback(future, new UpdateFlowCallback(input), MoreExecutors.directExecutor());
192         return future;
193     }
194
195     private final class AddFlowCallback implements FutureCallback<RpcResult<AddFlowOutput>> {
196         private final AddFlowInput input;
197         private final FlowRegistryKey flowRegistryKey;
198
199         private AddFlowCallback(final AddFlowInput input,
200                                 final FlowRegistryKey flowRegistryKey) {
201             this.input = input;
202             this.flowRegistryKey = flowRegistryKey;
203         }
204
205         @Override
206         public void onSuccess(@Nonnull final RpcResult<AddFlowOutput> rpcResult) {
207             if (rpcResult.isSuccessful()) {
208                 final FlowDescriptor flowDescriptor;
209
210                 if (Objects.nonNull(input.getFlowRef())) {
211                     final FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
212                     flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
213                     deviceContext.getDeviceFlowRegistry().storeDescriptor(flowRegistryKey, flowDescriptor);
214                 } else {
215                     deviceContext.getDeviceFlowRegistry().store(flowRegistryKey);
216                     flowDescriptor = deviceContext.getDeviceFlowRegistry().retrieveDescriptor(flowRegistryKey);
217                 }
218
219                 if (LOG.isDebugEnabled()) {
220                     LOG.debug("Flow add with id={} finished without error", flowDescriptor.getFlowId().getValue());
221                 }
222             } else {
223                 if (LOG.isDebugEnabled()) {
224                     LOG.debug("Flow add failed for flow={}, errors={}", input,
225                             ErrorUtil.errorsToString(rpcResult.getErrors()));
226                 }
227             }
228         }
229
230         @Override
231         public void onFailure(final Throwable throwable) {
232             LOG.warn("Service call for adding flow={} failed, reason: {}", input, throwable);
233         }
234     }
235
236     private final class RemoveFlowCallback implements FutureCallback<RpcResult<RemoveFlowOutput>> {
237         private final RemoveFlowInput input;
238
239         private RemoveFlowCallback(final RemoveFlowInput input) {
240             this.input = input;
241         }
242
243         @Override
244         public void onSuccess(@Nonnull final RpcResult<RemoveFlowOutput> result) {
245             if (result.isSuccessful()) {
246                 if (LOG.isDebugEnabled()) {
247                     LOG.debug("Flow remove finished without error for flow={}", input);
248                 }
249                 FlowRegistryKey flowRegistryKey =
250                         FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
251                 deviceContext.getDeviceFlowRegistry().addMark(flowRegistryKey);
252             } else {
253                 if (LOG.isDebugEnabled()) {
254                     LOG.debug("Flow remove failed for flow={}, errors={}", input,
255                             ErrorUtil.errorsToString(result.getErrors()));
256                 }
257             }
258         }
259
260         @Override
261         public void onFailure(final Throwable throwable) {
262             LOG.warn("Service call for removing flow={} failed, reason: {}", input, throwable);
263         }
264     }
265
266     private final class UpdateFlowCallback implements FutureCallback<RpcResult<UpdateFlowOutput>> {
267         private final UpdateFlowInput input;
268
269         private UpdateFlowCallback(UpdateFlowInput input) {
270             this.input = input;
271         }
272
273         @Override
274         public void onSuccess(@Nonnull final RpcResult<UpdateFlowOutput> updateFlowOutputRpcResult) {
275             final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
276
277             final UpdatedFlow updated = input.getUpdatedFlow();
278             final OriginalFlow original = input.getOriginalFlow();
279             final FlowRegistryKey origFlowRegistryKey =
280                     FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), original);
281             final FlowRegistryKey updatedFlowRegistryKey =
282                     FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), updated);
283             final FlowDescriptor origFlowDescriptor = deviceFlowRegistry.retrieveDescriptor(origFlowRegistryKey);
284
285             final boolean isUpdate = Objects.nonNull(origFlowDescriptor);
286             final FlowDescriptor updatedFlowDescriptor;
287
288             if (Objects.nonNull(input.getFlowRef())) {
289                 updatedFlowDescriptor =
290                         FlowDescriptorFactory.create(updated.getTableId(),
291                                                      input.getFlowRef().getValue().firstKeyOf(Flow.class).getId());
292             } else {
293                 if (isUpdate) {
294                     updatedFlowDescriptor = origFlowDescriptor;
295                 } else {
296                     deviceFlowRegistry.store(updatedFlowRegistryKey);
297                     updatedFlowDescriptor = deviceFlowRegistry.retrieveDescriptor(updatedFlowRegistryKey);
298                 }
299             }
300
301             if (isUpdate) {
302                 deviceFlowRegistry.addMark(origFlowRegistryKey);
303                 deviceFlowRegistry.storeDescriptor(updatedFlowRegistryKey, updatedFlowDescriptor);
304             }
305         }
306
307         @Override
308         public void onFailure(final Throwable throwable) {
309             LOG.warn("Service call for updating flow={} failed, reason: {}", input, throwable);
310         }
311     }
312 }