Merge "Bug 5974: He plugin: Don't invalidate session context that is not valid."
[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.concurrent.Future;
18 import javax.annotation.Nullable;
19 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
20 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
21 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
22 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
23 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
24 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
25 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
26 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
27 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
28 import org.opendaylight.openflowplugin.impl.util.FlowUtil;
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 FlowId flowId;
80         if (null != input.getFlowRef()) {
81             flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
82         } else {
83             flowId = FlowUtil.createAlienFlowId(input.getTableId());
84         }
85         LOG.trace("Calling add flow for flow with ID ={}.", flowId);
86         final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(input);
87         final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
88         deviceContext.getDeviceFlowRegistry().store(flowRegistryKey, flowDescriptor);
89         final ListenableFuture<RpcResult<AddFlowOutput>> future =
90                 flowAdd.processFlowModInputBuilders(flowAdd.toFlowModInputs(input));
91         Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
92             @Override
93             public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
94                 if (rpcResult.isSuccessful()) {
95                     if(LOG.isDebugEnabled()) {
96                         LOG.debug("flow add with id={},finished without error,", flowId.getValue());
97                     }
98                     if (itemLifecycleListener != null) {
99                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
100                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
101                         final FlowBuilder flowBuilder = new FlowBuilder(input).setId(flowDescriptor.getFlowId());
102                         itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
103                     }
104                 } else {
105                 LOG.error("flow add failed for id={}, errors={}", flowId.getValue(), errorsToString(rpcResult.getErrors()));
106             }
107             }
108
109             @Override
110             public void onFailure(final Throwable throwable) {
111                 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowRegistryKey);
112                 LOG.error("Service call for adding flow with  id={} failed, reason {} .", flowId.getValue(), throwable);
113             }
114         });
115
116         return future;
117     }
118
119     @Override
120     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
121         LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
122
123         final ListenableFuture<RpcResult<RemoveFlowOutput>> future =
124                 flowRemove.processFlowModInputBuilders(flowRemove.toFlowModInputs(input));
125         Futures.addCallback(future, new FutureCallback<RpcResult<RemoveFlowOutput>>() {
126             @Override
127             public void onSuccess(final RpcResult<RemoveFlowOutput> result) {
128                 if (result.isSuccessful()) {
129                     if(LOG.isDebugEnabled()) {
130                         LOG.debug("flow removed finished without error,");
131                     }
132                     FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(input);
133                     deviceContext.getDeviceFlowRegistry().markToBeremoved(flowRegistryKey);
134                     if (itemLifecycleListener != null) {
135                         final FlowDescriptor flowDescriptor =
136                                 deviceContext.getDeviceFlowRegistry().retrieveIdForFlow(flowRegistryKey);
137                         if (flowDescriptor != null) {
138                             KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
139                                     deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
140                             itemLifecycleListener.onRemoved(flowPath);
141                         }
142                     }
143                 } else {
144                     LOG.error("Flow remove failed with errors : {}",errorsToString(result.getErrors()));
145                 }
146             }
147
148             @Override
149             public void onFailure(final Throwable throwable) {
150                 LOG.error("Service call for removing flow with id {} failed ,reason {}",input.getFlowRef().getValue(), throwable);
151             }
152         });
153
154         return future;
155     }
156
157     private final String errorsToString(final Collection<RpcError> rpcErrors) {
158         final StringBuilder errors = new StringBuilder();
159         if ((null != rpcErrors) && (rpcErrors.size() > 0)) {
160             for (final RpcError rpcError : rpcErrors) {
161                 errors.append(rpcError.getMessage());
162             }
163         }
164         return errors.toString();
165     }
166
167     @Override
168     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
169         final UpdateFlowInput in = input;
170         final UpdatedFlow updated = in.getUpdatedFlow();
171         final OriginalFlow original = in.getOriginalFlow();
172
173         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
174         final List<FlowModInputBuilder> ofFlowModInputs;
175
176         if (!FlowCreatorUtil.canModifyFlow(original, updated, flowUpdate.getVersion())) {
177             // We would need to remove original and add updated.
178
179             // remove flow
180             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
181             final List<FlowModInputBuilder> ofFlowRemoveInput = flowUpdate.toFlowModInputs(removeflow.build());
182             // remove flow should be the first
183             allFlowMods.addAll(ofFlowRemoveInput);
184             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
185             ofFlowModInputs = flowUpdate.toFlowModInputs(addFlowInputBuilder.build());
186         } else {
187             ofFlowModInputs = flowUpdate.toFlowModInputs(updated);
188         }
189
190         allFlowMods.addAll(ofFlowModInputs);
191         ListenableFuture<RpcResult<UpdateFlowOutput>> future = flowUpdate.processFlowModInputBuilders(allFlowMods);
192         Futures.addCallback(future, new FutureCallback<RpcResult<UpdateFlowOutput>>() {
193             @Override
194             public void onSuccess(final RpcResult<UpdateFlowOutput> o) {
195                 FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(original);
196
197                 FlowRegistryKey updatedflowRegistryKey = FlowRegistryKeyFactory.create(updated);
198                 final FlowRef flowRef = input.getFlowRef();
199                 final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
200                 deviceFlowRegistry.markToBeremoved(flowRegistryKey);
201
202                 if (itemLifecycleListener != null) {
203                     final FlowDescriptor flowDescriptor = deviceContext.getDeviceFlowRegistry().retrieveIdForFlow(flowRegistryKey);
204                     if (flowDescriptor != null) {
205                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
206                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
207                         itemLifecycleListener.onRemoved(flowPath);
208                     }
209                 }
210                 //if provided, store flow id to flow registry
211                 if (flowRef != null) {
212                     final FlowId flowId = flowRef.getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
213                     final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
214                     deviceFlowRegistry.store(updatedflowRegistryKey, flowDescriptor);
215
216                     if (itemLifecycleListener != null) {
217                         KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
218                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
219                         final FlowBuilder flowBuilder = new FlowBuilder(input.getUpdatedFlow()).setId(flowDescriptor.getFlowId());
220                         itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
221                     }
222                 }
223             }
224
225             @Override
226             public void onFailure(final Throwable throwable) {
227                 LOG.error("Service call for updating flow failed, reason{}", throwable);
228             }
229         });
230         return future;
231     }
232
233     @VisibleForTesting
234     static KeyedInstanceIdentifier<Flow, FlowKey> createFlowPath(FlowDescriptor flowDescriptor,
235                                                                  KeyedInstanceIdentifier<Node, NodeKey> nodePath) {
236         return nodePath.augmentation(FlowCapableNode.class)
237                 .child(Table.class, flowDescriptor.getTableKey())
238                 .child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
239     }
240 }