Merge "Improve flow collection"
[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.annotations.VisibleForTesting;
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.List;
17 import java.util.Objects;
18 import java.util.concurrent.Future;
19 import javax.annotation.Nullable;
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.api.openflow.rpc.ItemLifeCycleSource;
27 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
28 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
29 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
30 import org.opendaylight.openflowplugin.impl.services.singlelayer.SingleLayerFlowService;
31 import org.opendaylight.openflowplugin.impl.services.multilayer.MultiLayerFlowService;
32 import org.opendaylight.openflowplugin.impl.util.ErrorUtil;
33 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
34 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
55 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcResult;
58 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public class SalFlowServiceImpl implements SalFlowService, ItemLifeCycleSource {
63     private static final Logger LOG = LoggerFactory.getLogger(SalFlowServiceImpl.class);
64     private final MultiLayerFlowService<UpdateFlowOutput> flowUpdate;
65     private final MultiLayerFlowService<AddFlowOutput> flowAdd;
66     private final MultiLayerFlowService<RemoveFlowOutput> flowRemove;
67     private final SingleLayerFlowService<AddFlowOutput> flowAddMessage;
68     private final SingleLayerFlowService<UpdateFlowOutput> flowUpdateMessage;
69     private final SingleLayerFlowService<RemoveFlowOutput> flowRemoveMessage;
70     private final DeviceContext deviceContext;
71     private ItemLifecycleListener itemLifecycleListener;
72
73     public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext, final ConvertorExecutor convertorExecutor) {
74         this.deviceContext = deviceContext;
75         flowRemove = new MultiLayerFlowService<>(requestContextStack, deviceContext, RemoveFlowOutput.class, convertorExecutor);
76         flowAdd = new MultiLayerFlowService<>(requestContextStack, deviceContext, AddFlowOutput.class, convertorExecutor);
77         flowUpdate = new MultiLayerFlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class, convertorExecutor);
78         flowAddMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, AddFlowOutput.class);
79         flowUpdateMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class);
80         flowRemoveMessage= new SingleLayerFlowService<>(requestContextStack, deviceContext, RemoveFlowOutput.class);
81     }
82
83     @Override
84     public void setItemLifecycleListener(@Nullable ItemLifecycleListener itemLifecycleListener) {
85         this.itemLifecycleListener = itemLifecycleListener;
86     }
87
88     @Override
89     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
90         final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
91         final ListenableFuture<RpcResult<AddFlowOutput>> future;
92
93         if (flowAddMessage.canUseSingleLayerSerialization()) {
94             future = flowAddMessage.handleServiceCall(input);
95             Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey));
96         } else {
97             future = flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
98             Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey));
99
100         }
101         return future;
102     }
103
104     @Override
105     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
106         final ListenableFuture<RpcResult<RemoveFlowOutput>> future;
107
108         if (flowRemoveMessage.canUseSingleLayerSerialization()) {
109             future = flowRemoveMessage.handleServiceCall(input);
110             Futures.addCallback(future, new RemoveFlowCallback(input));
111
112         } else {
113             future = flowRemove.processFlowModInputBuilders(flowRemove.toFlowModInputs(input));
114             Futures.addCallback(future, new RemoveFlowCallback(input));
115         }
116
117         return future;
118     }
119
120     @Override
121     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
122         final UpdatedFlow updated = input.getUpdatedFlow();
123         final OriginalFlow original = input.getOriginalFlow();
124
125         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
126         final List<FlowModInputBuilder> ofFlowModInputs;
127
128         ListenableFuture<RpcResult<UpdateFlowOutput>> future;
129         if (flowUpdateMessage.canUseSingleLayerSerialization()) {
130
131             if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdateMessage.getVersion())) {
132                 final SettableFuture<RpcResult<UpdateFlowOutput>> objectSettableFuture = SettableFuture.create();
133
134                 final ListenableFuture<List<RpcResult<UpdateFlowOutput>>> listListenableFuture = Futures.successfulAsList(
135                         flowUpdateMessage.handleServiceCall(input.getOriginalFlow()),
136                         flowUpdateMessage.handleServiceCall(input.getUpdatedFlow()));
137
138                 Futures.addCallback(listListenableFuture, new FutureCallback<List<RpcResult<UpdateFlowOutput>>>() {
139                     @Override
140                     public void onSuccess(final List<RpcResult<UpdateFlowOutput>> results) {
141                         final ArrayList<RpcError> errors = new ArrayList();
142                         for (RpcResult<UpdateFlowOutput> flowModResult : results) {
143                             if (flowModResult == null) {
144                                 errors.add(RpcResultBuilder.newError(
145                                         RpcError.ErrorType.PROTOCOL, OFConstants.APPLICATION_TAG,
146                                         "unexpected flowMod result (null) occurred"));
147                             } else if (!flowModResult.isSuccessful()) {
148                                 errors.addAll(flowModResult.getErrors());
149                             }
150                         }
151
152                         final RpcResultBuilder<UpdateFlowOutput> rpcResultBuilder;
153                         if (errors.isEmpty()) {
154                             rpcResultBuilder = RpcResultBuilder.success();
155                         } else {
156                             rpcResultBuilder = RpcResultBuilder.<UpdateFlowOutput>failed().withRpcErrors(errors);
157                         }
158
159                         objectSettableFuture.set(rpcResultBuilder.build());
160                     }
161
162                     @Override
163                     public void onFailure(final Throwable t) {
164                         RpcResultBuilder<UpdateFlowOutput> rpcResultBuilder = RpcResultBuilder.failed();
165                         objectSettableFuture.set(rpcResultBuilder.build());
166                     }
167                 });
168
169                 future = objectSettableFuture;
170             } else {
171                 future = flowUpdateMessage.handleServiceCall(input.getUpdatedFlow());
172             }
173         } else {
174             if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdate.getVersion())) {
175                 // We would need to remove original and add updated.
176
177                 // remove flow
178                 final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
179                 final List<FlowModInputBuilder> ofFlowRemoveInput = flowUpdate.toFlowModInputs(removeflow.build());
180                 // remove flow should be the first
181                 allFlowMods.addAll(ofFlowRemoveInput);
182                 final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
183                 ofFlowModInputs = flowUpdate.toFlowModInputs(addFlowInputBuilder.build());
184             } else {
185                 ofFlowModInputs = flowUpdate.toFlowModInputs(updated);
186             }
187
188             allFlowMods.addAll(ofFlowModInputs);
189
190             future = flowUpdate.processFlowModInputBuilders(allFlowMods);
191         }
192
193         Futures.addCallback(future, new UpdateFlowCallback(input));
194         return future;
195     }
196
197     @VisibleForTesting
198     private static KeyedInstanceIdentifier<Flow, FlowKey> createFlowPath(FlowDescriptor flowDescriptor,
199                                                                          KeyedInstanceIdentifier<Node, NodeKey> nodePath) {
200         return nodePath.augmentation(FlowCapableNode.class)
201                 .child(Table.class, flowDescriptor.getTableKey())
202                 .child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
203     }
204
205     private class AddFlowCallback implements FutureCallback<RpcResult<AddFlowOutput>> {
206         private final AddFlowInput input;
207         private final FlowRegistryKey flowRegistryKey;
208
209         private AddFlowCallback(final AddFlowInput input,
210                                 final FlowRegistryKey flowRegistryKey) {
211             this.input = input;
212             this.flowRegistryKey = flowRegistryKey;
213         }
214
215         @Override
216         public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
217             if (rpcResult.isSuccessful()) {
218                 final FlowDescriptor flowDescriptor;
219
220                 if (Objects.nonNull(input.getFlowRef())) {
221                     final FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
222                     flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
223                     deviceContext.getDeviceFlowRegistry().storeDescriptor(flowRegistryKey, flowDescriptor);
224                 } else {
225                     deviceContext.getDeviceFlowRegistry().store(flowRegistryKey);
226                     flowDescriptor = deviceContext.getDeviceFlowRegistry().retrieveDescriptor(flowRegistryKey);
227                 }
228
229                 if (LOG.isDebugEnabled()) {
230                     LOG.debug("Flow add with id={} finished without error", flowDescriptor.getFlowId().getValue());
231                 }
232
233                 if (itemLifecycleListener != null) {
234                     KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
235                             deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
236                     final FlowBuilder flowBuilder = new FlowBuilder(input).setId(flowDescriptor.getFlowId());
237                     itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
238                 }
239             } else {
240                 if (LOG.isDebugEnabled()) {
241                     LOG.debug("Flow add failed for flow={}, errors={}", input,
242                             ErrorUtil.errorsToString(rpcResult.getErrors()));
243                 }
244             }
245         }
246
247         @Override
248         public void onFailure(final Throwable throwable) {
249             LOG.warn("Service call for adding flow={} failed, reason: {}", input, throwable);
250         }
251     }
252
253     private class RemoveFlowCallback implements FutureCallback<RpcResult<RemoveFlowOutput>> {
254         private final RemoveFlowInput input;
255
256         private RemoveFlowCallback(final RemoveFlowInput input) {
257             this.input = input;
258         }
259
260         @Override
261         public void onSuccess(final RpcResult<RemoveFlowOutput> result) {
262             if (result.isSuccessful()) {
263                 if (LOG.isDebugEnabled()) {
264                     LOG.debug("Flow remove finished without error for flow={}", input);
265                 }
266                 FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
267                 deviceContext.getDeviceFlowRegistry().addMark(flowRegistryKey);
268
269                 if (itemLifecycleListener != null) {
270                     final FlowDescriptor flowDescriptor = deviceContext.getDeviceFlowRegistry().retrieveDescriptor(flowRegistryKey);
271
272                     if (flowDescriptor != null) {
273                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
274                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
275                         itemLifecycleListener.onRemoved(flowPath);
276                     }
277                 }
278             } else {
279                 if (LOG.isDebugEnabled()) {
280                     LOG.debug("Flow remove failed for flow={}, errors={}", input,
281                             ErrorUtil.errorsToString(result.getErrors()));
282                 }
283             }
284         }
285
286         @Override
287         public void onFailure(final Throwable throwable) {
288             LOG.warn("Service call for removing flow={} failed, reason: {}", input, throwable);
289         }
290     }
291
292     private class UpdateFlowCallback implements FutureCallback<RpcResult<UpdateFlowOutput>> {
293         private final UpdateFlowInput input;
294
295         private UpdateFlowCallback(UpdateFlowInput input) {
296             this.input = input;
297         }
298
299         @Override
300         public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
301             final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
302
303             final UpdatedFlow updated = input.getUpdatedFlow();
304             final OriginalFlow original = input.getOriginalFlow();
305             final FlowRegistryKey origFlowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), original);
306             final FlowRegistryKey updatedFlowRegistryKey = FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), updated);
307             final FlowDescriptor origFlowDescriptor = deviceFlowRegistry.retrieveDescriptor(origFlowRegistryKey);
308
309             final boolean isUpdate = Objects.nonNull(origFlowDescriptor);
310             final FlowDescriptor updatedFlowDescriptor;
311
312             if (Objects.nonNull(input.getFlowRef())) {
313                 updatedFlowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), input.getFlowRef().getValue().firstKeyOf(Flow.class).getId());
314             } else {
315                 if (isUpdate) {
316                     updatedFlowDescriptor = origFlowDescriptor;
317                 } else {
318                     deviceFlowRegistry.store(updatedFlowRegistryKey);
319                     updatedFlowDescriptor = deviceFlowRegistry.retrieveDescriptor(updatedFlowRegistryKey);
320                 }
321             }
322
323             if (isUpdate) {
324                 deviceFlowRegistry.addMark(origFlowRegistryKey);
325                 deviceFlowRegistry.storeDescriptor(updatedFlowRegistryKey, updatedFlowDescriptor);
326             }
327
328             if (itemLifecycleListener != null) {
329                 final KeyedInstanceIdentifier<Flow, FlowKey> flowPath =
330                         createFlowPath(
331                                 updatedFlowDescriptor,
332                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
333
334                 final Flow flow = new FlowBuilder(updated)
335                         .setId(updatedFlowDescriptor.getFlowId())
336                         .build();
337
338                 if (Objects.nonNull(origFlowDescriptor)) {
339                     itemLifecycleListener.onUpdated(flowPath, flow);
340                 } else {
341                     itemLifecycleListener.onAdded(flowPath, flow);
342                 }
343             }
344         }
345
346         @Override
347         public void onFailure(final Throwable throwable) {
348             LOG.warn("Service call for updating flow={} failed, reason: {}", input, throwable);
349         }
350     }
351 }