Merge "Fix deprecation warnings in learning-switch"
[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.collect.EvictingQueue;
11 import com.google.common.collect.Queues;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import com.google.common.util.concurrent.SettableFuture;
17 import java.time.LocalDateTime;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.Queue;
21 import org.opendaylight.openflowplugin.api.OFConstants;
22 import org.opendaylight.openflowplugin.api.openflow.FlowGroupCache;
23 import org.opendaylight.openflowplugin.api.openflow.FlowGroupCacheManager;
24 import org.opendaylight.openflowplugin.api.openflow.FlowGroupStatus;
25 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
26 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
27 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
28 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
29 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
30 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
31 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
32 import org.opendaylight.openflowplugin.impl.services.multilayer.MultiLayerFlowService;
33 import org.opendaylight.openflowplugin.impl.services.singlelayer.SingleLayerFlowService;
34 import org.opendaylight.openflowplugin.impl.util.ErrorUtil;
35 import org.opendaylight.openflowplugin.impl.util.FlowCreatorUtil;
36 import org.opendaylight.openflowplugin.impl.util.PathUtil;
37 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
56 import org.opendaylight.yangtools.yang.common.Uint8;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 public class SalFlowServiceImpl implements SalFlowService {
61     private static final Logger LOG = LoggerFactory.getLogger(SalFlowServiceImpl.class);
62     private final MultiLayerFlowService<UpdateFlowOutput> flowUpdate;
63     private final MultiLayerFlowService<AddFlowOutput> flowAdd;
64     private final MultiLayerFlowService<RemoveFlowOutput> flowRemove;
65     private final SingleLayerFlowService<AddFlowOutput> flowAddMessage;
66     private final SingleLayerFlowService<UpdateFlowOutput> flowUpdateMessage;
67     private final SingleLayerFlowService<RemoveFlowOutput> flowRemoveMessage;
68     private final DeviceContext deviceContext;
69     private static final Uint8 OFPTT_ALL = Uint8.MAX_VALUE;
70     private final FlowGroupCacheManager provider;
71     public static final int FLOWGROUP_CACHE_SIZE = 10000;
72
73
74     public SalFlowServiceImpl(final RequestContextStack requestContextStack,
75                               final DeviceContext deviceContext,
76                               final ConvertorExecutor convertorExecutor,
77                               final FlowGroupCacheManager provider) {
78         this.deviceContext = deviceContext;
79         this.provider = provider;
80         flowRemove = new MultiLayerFlowService<>(requestContextStack,
81                                                  deviceContext,
82                                                  RemoveFlowOutput.class,
83                                                  convertorExecutor);
84         flowAdd = new MultiLayerFlowService<>(requestContextStack,
85                                               deviceContext,
86                                               AddFlowOutput.class,
87                                               convertorExecutor);
88         flowUpdate = new MultiLayerFlowService<>(requestContextStack,
89                                                  deviceContext,
90                                                  UpdateFlowOutput.class,
91                                                  convertorExecutor);
92         flowAddMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, AddFlowOutput.class);
93         flowUpdateMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class);
94         flowRemoveMessage = new SingleLayerFlowService<>(requestContextStack, deviceContext, RemoveFlowOutput.class);
95     }
96
97     @Override
98     public ListenableFuture<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
99         final FlowRegistryKey flowRegistryKey =
100                 FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
101         final ListenableFuture<RpcResult<AddFlowOutput>> future;
102         NodeId nodeId = PathUtil.extractNodeId(input.getNode());
103         if (flowAddMessage.canUseSingleLayerSerialization()) {
104             future = flowAddMessage.handleServiceCall(input);
105             Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey, nodeId),
106                     MoreExecutors.directExecutor());
107         } else {
108             future = flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
109             Futures.addCallback(future, new AddFlowCallback(input, flowRegistryKey, nodeId),
110                     MoreExecutors.directExecutor());
111
112         }
113         return future;
114     }
115
116     @Override
117     public ListenableFuture<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
118         final ListenableFuture<RpcResult<RemoveFlowOutput>> future;
119         NodeId nodeId = PathUtil.extractNodeId(input.getNode());
120         if (flowRemoveMessage.canUseSingleLayerSerialization()) {
121             future = flowRemoveMessage.handleServiceCall(input);
122             Futures.addCallback(future, new RemoveFlowCallback(input, nodeId), MoreExecutors.directExecutor());
123
124         } else {
125             future = flowRemove.processFlowModInputBuilders(flowRemove.toFlowModInputs(input));
126             Futures.addCallback(future, new RemoveFlowCallback(input, nodeId), MoreExecutors.directExecutor());
127         }
128
129         return future;
130     }
131
132     @Override
133     public ListenableFuture<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
134         final UpdatedFlow updated = input.getUpdatedFlow();
135         final OriginalFlow original = input.getOriginalFlow();
136         String nodeId =  PathUtil.extractNodeId(input.getNode()).getValue();
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                 }, MoreExecutors.directExecutor());
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, nodeId), MoreExecutors.directExecutor());
206         return future;
207     }
208
209     private final class AddFlowCallback implements FutureCallback<RpcResult<AddFlowOutput>> {
210         private final AddFlowInput input;
211         private final FlowRegistryKey flowRegistryKey;
212         private final NodeId nodeId;
213
214         private AddFlowCallback(final AddFlowInput input,
215                                 final FlowRegistryKey flowRegistryKey,
216                                 final NodeId nodeId) {
217             this.input = input;
218             this.flowRegistryKey = flowRegistryKey;
219             this.nodeId = nodeId;
220         }
221
222         @Override
223         public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
224             if (rpcResult.isSuccessful()) {
225                 final FlowDescriptor flowDescriptor;
226                 final FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class).getId();
227                 FlowGroupCache cache = new FlowGroupCache(flowId.getValue(), input.getTableId().toString(),
228                         FlowGroupStatus.ADDED, LocalDateTime.now());
229                 if (provider.getAllNodesFlowGroupCache().containsKey(nodeId.getValue())) {
230                     provider.getAllNodesFlowGroupCache().get(nodeId.getValue()).add(cache);
231                 } else {
232                     Queue<FlowGroupCache> flowGroupCacheList =
233                             Queues.synchronizedQueue(EvictingQueue.create(FLOWGROUP_CACHE_SIZE));
234                     flowGroupCacheList.add(cache);
235                     provider.getAllNodesFlowGroupCache().put(nodeId.getValue(), flowGroupCacheList);
236                 }
237                 if (input.getFlowRef() != null) {
238                     flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
239                     deviceContext.getDeviceFlowRegistry().storeDescriptor(flowRegistryKey, flowDescriptor);
240                 } else {
241                     deviceContext.getDeviceFlowRegistry().store(flowRegistryKey);
242                     flowDescriptor = deviceContext.getDeviceFlowRegistry().retrieveDescriptor(flowRegistryKey);
243                 }
244
245                 if (LOG.isDebugEnabled()) {
246                     LOG.debug("Flow add with id={} finished without error", flowDescriptor.getFlowId().getValue());
247                 }
248             } else {
249                 if (LOG.isDebugEnabled()) {
250                     LOG.debug("Flow add failed for flow={}, errors={}", input,
251                             ErrorUtil.errorsToString(rpcResult.getErrors()));
252                 }
253             }
254         }
255
256         @Override
257         public void onFailure(final Throwable throwable) {
258             LOG.warn("Service call for adding flow={} failed", input, throwable);
259         }
260     }
261
262     private final class RemoveFlowCallback implements FutureCallback<RpcResult<RemoveFlowOutput>> {
263         private final RemoveFlowInput input;
264         private final NodeId nodeId;
265
266         private RemoveFlowCallback(final RemoveFlowInput input, final NodeId nodeId) {
267             this.input = input;
268             this.nodeId = nodeId;
269         }
270
271         @Override
272         public void onSuccess(final RpcResult<RemoveFlowOutput> result) {
273             if (result.isSuccessful()) {
274                 if (LOG.isDebugEnabled()) {
275                     LOG.debug("Flow remove finished without error for flow={}", input);
276                 }
277                 if (input.getTableId() != null && !input.getTableId().equals(OFPTT_ALL)) {
278                     FlowRegistryKey flowRegistryKey =
279                             FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), input);
280                     deviceContext.getDeviceFlowRegistry().addMark(flowRegistryKey);
281                     final FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class).getId();
282                     FlowGroupCache cache = new FlowGroupCache(flowId.getValue(),
283                             input.getTableId().toString(), FlowGroupStatus.REMOVED,
284                             LocalDateTime.now());
285                     if (provider.getAllNodesFlowGroupCache().containsKey(nodeId.getValue())) {
286                         provider.getAllNodesFlowGroupCache().get(nodeId.getValue()).add(cache);
287                     } else {
288                         Queue<FlowGroupCache> flowGroupCacheList =
289                                 Queues.synchronizedQueue(EvictingQueue.create(FLOWGROUP_CACHE_SIZE));
290                         flowGroupCacheList.add(cache);
291                         provider.getAllNodesFlowGroupCache().put(nodeId.getValue(), flowGroupCacheList);
292                     }
293                 } else {
294                     deviceContext.getDeviceFlowRegistry().clearFlowRegistry();
295                 }
296             } else {
297                 if (LOG.isDebugEnabled()) {
298                     LOG.debug("Flow remove failed for flow={}, errors={}", input,
299                             ErrorUtil.errorsToString(result.getErrors()));
300                 }
301             }
302         }
303
304         @Override
305         public void onFailure(final Throwable throwable) {
306             LOG.warn("Service call for removing flow={} failed", input, throwable);
307         }
308     }
309
310     private final class UpdateFlowCallback implements FutureCallback<RpcResult<UpdateFlowOutput>> {
311         private final UpdateFlowInput input;
312         private final String nodeId;
313
314         private UpdateFlowCallback(UpdateFlowInput input,  String nodeId) {
315             this.input = input;
316             this.nodeId = nodeId;
317         }
318
319         @Override
320         public void onSuccess(final RpcResult<UpdateFlowOutput> updateFlowOutputRpcResult) {
321             final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
322             final FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class).getId();
323             final UpdatedFlow updated = input.getUpdatedFlow();
324             final OriginalFlow original = input.getOriginalFlow();
325             final FlowRegistryKey origFlowRegistryKey =
326                     FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), original);
327             final FlowRegistryKey updatedFlowRegistryKey =
328                     FlowRegistryKeyFactory.create(deviceContext.getDeviceInfo().getVersion(), updated);
329             final FlowDescriptor origFlowDescriptor = deviceFlowRegistry.retrieveDescriptor(origFlowRegistryKey);
330
331             final boolean isUpdate = origFlowDescriptor != null;
332             final FlowDescriptor updatedFlowDescriptor;
333             FlowGroupCache cache = new FlowGroupCache(flowId.getValue(), updated.getTableId().toString(),
334                     FlowGroupStatus.MODIFIED,
335                     LocalDateTime.now());
336             if (provider.getAllNodesFlowGroupCache().containsKey(nodeId)) {
337                 provider.getAllNodesFlowGroupCache().get(nodeId).add(cache);
338             } else {
339                 Queue<FlowGroupCache> flowGroupCacheList =
340                         Queues.synchronizedQueue(EvictingQueue.create(FLOWGROUP_CACHE_SIZE));
341                 flowGroupCacheList.add(cache);
342                 provider.getAllNodesFlowGroupCache().put(nodeId, flowGroupCacheList);
343             }
344
345             if (input.getFlowRef() != null) {
346                 updatedFlowDescriptor =
347                         FlowDescriptorFactory.create(updated.getTableId(),
348                                                      input.getFlowRef().getValue().firstKeyOf(Flow.class).getId());
349             } else {
350                 if (isUpdate) {
351                     updatedFlowDescriptor = origFlowDescriptor;
352                 } else {
353                     deviceFlowRegistry.store(updatedFlowRegistryKey);
354                     updatedFlowDescriptor = deviceFlowRegistry.retrieveDescriptor(updatedFlowRegistryKey);
355                 }
356             }
357
358             if (isUpdate) {
359                 deviceFlowRegistry.addMark(origFlowRegistryKey);
360                 deviceFlowRegistry.storeDescriptor(updatedFlowRegistryKey, updatedFlowDescriptor);
361             }
362         }
363
364         @Override
365         public void onFailure(final Throwable throwable) {
366             LOG.warn("Service call for updating flow={} failed", input, throwable);
367         }
368     }
369 }