8609c1192f2656d4c29651e4369fcfdedce2c29d
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / 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;
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 java.util.ArrayList;
15 import java.util.Collection;
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.openflow.device.DeviceContext;
21 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
22 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
23 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
24 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
25 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
26 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
27 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
28 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
29 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
30 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
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.FlowBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
52 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 public class SalFlowServiceImpl implements SalFlowService, ItemLifeCycleSource {
59     private static final Logger LOG = LoggerFactory.getLogger(SalFlowServiceImpl.class);
60     private final FlowService<UpdateFlowOutput> flowUpdate;
61     private final FlowService<AddFlowOutput> flowAdd;
62     private final FlowService<RemoveFlowOutput> flowRemove;
63     private final DeviceContext deviceContext;
64     private ItemLifecycleListener itemLifecycleListener;
65
66     public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext, final ConvertorExecutor convertorExecutor) {
67         this.deviceContext = deviceContext;
68         flowRemove = new FlowService<>(requestContextStack, deviceContext, RemoveFlowOutput.class, convertorExecutor);
69         flowAdd = new FlowService<>(requestContextStack, deviceContext, AddFlowOutput.class, convertorExecutor);
70         flowUpdate = new FlowService<>(requestContextStack, deviceContext, UpdateFlowOutput.class, convertorExecutor);
71     }
72
73     @Override
74     public void setItemLifecycleListener(@Nullable ItemLifecycleListener itemLifecycleListener) {
75         this.itemLifecycleListener = itemLifecycleListener;
76     }
77
78     @Override
79     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
80         final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(input);
81         final FlowId flowId;
82         final FlowDescriptor flowDescriptor;
83
84         if (Objects.nonNull(input.getFlowRef())) {
85             flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
86             flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
87             deviceContext.getDeviceFlowRegistry().store(flowRegistryKey, flowDescriptor);
88         } else {
89             flowId = deviceContext.getDeviceFlowRegistry().storeIfNecessary(flowRegistryKey);
90             flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
91         }
92
93         LOG.trace("Calling add flow for flow with ID ={}.", flowId);
94         final ListenableFuture<RpcResult<AddFlowOutput>> future =
95                 flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
96         Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
97             @Override
98             public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
99                 if (rpcResult.isSuccessful()) {
100                     if(LOG.isDebugEnabled()) {
101                         LOG.debug("flow add with id={},finished without error,", flowId.getValue());
102                     }
103                     if (itemLifecycleListener != null) {
104                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
105                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
106                         final FlowBuilder flowBuilder = new FlowBuilder(input).setId(flowDescriptor.getFlowId());
107                         itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
108                     }
109                 } else {
110                 LOG.error("flow add failed for id={}, errors={}", flowId.getValue(), errorsToString(rpcResult.getErrors()));
111             }
112             }
113
114             @Override
115             public void onFailure(final Throwable throwable) {
116                 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowRegistryKey);
117                 LOG.error("Service call for adding flow with  id={} failed, reason {} .", flowId.getValue(), throwable);
118             }
119         });
120
121         return future;
122     }
123
124     @Override
125     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
126         LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
127
128         final ListenableFuture<RpcResult<RemoveFlowOutput>> future =
129                 flowRemove.processFlowModInputBuilders(flowRemove.toFlowModInputs(input));
130         Futures.addCallback(future, new FutureCallback<RpcResult<RemoveFlowOutput>>() {
131             @Override
132             public void onSuccess(final RpcResult<RemoveFlowOutput> result) {
133                 if (result.isSuccessful()) {
134                     if(LOG.isDebugEnabled()) {
135                         LOG.debug("flow removed finished without error,");
136                     }
137                     FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(input);
138                     deviceContext.getDeviceFlowRegistry().markToBeremoved(flowRegistryKey);
139                     if (itemLifecycleListener != null) {
140                         final FlowDescriptor flowDescriptor =
141                                 deviceContext.getDeviceFlowRegistry().retrieveIdForFlow(flowRegistryKey);
142                         if (flowDescriptor != null) {
143                             KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
144                                     deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
145                             itemLifecycleListener.onRemoved(flowPath);
146                         }
147                     }
148                 } else {
149                     LOG.error("Flow remove failed with errors : {}",errorsToString(result.getErrors()));
150                 }
151             }
152
153             @Override
154             public void onFailure(final Throwable throwable) {
155                 LOG.error("Service call for removing flow with id {} failed ,reason {}",input.getFlowRef().getValue(), throwable);
156             }
157         });
158
159         return future;
160     }
161
162     private final String errorsToString(final Collection<RpcError> rpcErrors) {
163         final StringBuilder errors = new StringBuilder();
164         if ((null != rpcErrors) && (rpcErrors.size() > 0)) {
165             for (final RpcError rpcError : rpcErrors) {
166                 errors.append(rpcError.getMessage());
167             }
168         }
169         return errors.toString();
170     }
171
172     @Override
173     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
174         final UpdateFlowInput in = input;
175         final UpdatedFlow updated = in.getUpdatedFlow();
176         final OriginalFlow original = in.getOriginalFlow();
177
178         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
179         final List<FlowModInputBuilder> ofFlowModInputs;
180
181         if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdate.getVersion())) {
182             // We would need to remove original and add updated.
183
184             // remove flow
185             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
186             final List<FlowModInputBuilder> ofFlowRemoveInput = flowUpdate.toFlowModInputs(removeflow.build());
187             // remove flow should be the first
188             allFlowMods.addAll(ofFlowRemoveInput);
189             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
190             ofFlowModInputs = flowUpdate.toFlowModInputs(addFlowInputBuilder.build());
191         } else {
192             ofFlowModInputs = flowUpdate.toFlowModInputs(updated);
193         }
194
195         allFlowMods.addAll(ofFlowModInputs);
196         ListenableFuture<RpcResult<UpdateFlowOutput>> future = flowUpdate.processFlowModInputBuilders(allFlowMods);
197         Futures.addCallback(future, new FutureCallback<RpcResult<UpdateFlowOutput>>() {
198             @Override
199             public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
200                 FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(original);
201
202                 FlowRegistryKey updatedflowRegistryKey = FlowRegistryKeyFactory.create(updated);
203                 final FlowRef flowRef = input.getFlowRef();
204                 final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
205
206                 if (flowRef == null) { //then this is equivalent to a delete
207                     deviceFlowRegistry.markToBeremoved(flowRegistryKey);
208
209                     if (itemLifecycleListener != null) {
210                         final FlowDescriptor flowDescriptor =
211                                 deviceContext.getDeviceFlowRegistry().retrieveIdForFlow( flowRegistryKey);
212                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
213                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
214                         itemLifecycleListener.onRemoved(flowPath);
215                     }
216                 } else { //this is either an add or an update
217                     final FlowId flowId = flowRef.getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
218                     final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
219                     deviceFlowRegistry.store(updatedflowRegistryKey, flowDescriptor);
220
221                     if (itemLifecycleListener != null) {
222                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
223                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
224                         final FlowBuilder flowBuilder = new FlowBuilder(
225                                                     input.getUpdatedFlow()).setId(flowDescriptor.getFlowId());
226
227                         boolean isUpdate = null !=
228                                             deviceFlowRegistry.retrieveIdForFlow(flowRegistryKey);
229                         if (isUpdate) {
230                             itemLifecycleListener.onUpdated(flowPath, flowBuilder.build());
231                         } else {
232                             itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
233                         }
234                     }
235
236
237                 }
238             }
239
240             @Override
241             public void onFailure(final Throwable throwable) {
242                 LOG.error("Service call for updating flow failed, reason{}", throwable);
243             }
244         });
245         return future;
246     }
247
248     @VisibleForTesting
249     static KeyedInstanceIdentifier<Flow, FlowKey> createFlowPath(FlowDescriptor flowDescriptor,
250                                                                  KeyedInstanceIdentifier<Node, NodeKey> nodePath) {
251         return nodePath.augmentation(FlowCapableNode.class)
252                 .child(Table.class, flowDescriptor.getTableKey())
253                 .child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
254     }
255 }