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