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