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