2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.openflowplugin.impl.services;
10 import com.google.common.base.Function;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.JdkFutureAdapters;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.SettableFuture;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Future;
22 import org.opendaylight.openflowplugin.api.OFConstants;
23 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
24 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
25 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
26 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
27 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowHash;
28 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
29 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
30 import org.opendaylight.openflowplugin.impl.registry.flow.FlowHashFactory;
31 import org.opendaylight.openflowplugin.impl.util.FlowUtil;
32 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.FlowConvertor;
33 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
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.openflow.protocol.rev130731.FlowModInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
50 import org.opendaylight.yangtools.yang.common.RpcError;
51 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
52 import org.opendaylight.yangtools.yang.common.RpcResult;
53 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
54 import org.slf4j.Logger;
56 public class SalFlowServiceImpl extends CommonService implements SalFlowService {
58 private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
60 public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
61 super(requestContextStack, deviceContext);
65 public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
67 if (null != input.getFlowRef()) {
68 flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
70 flowId = FlowUtil.createAlienFlowId(input.getTableId());
74 final DeviceContext deviceContext = getDeviceContext();
75 final FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
76 final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(input.getTableId(), flowId);
78 final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, getVersion(), getDatapathId());
79 final ListenableFuture<RpcResult<AddFlowOutput>> future = processFlowModInputBuilders(ofFlowModInputs);
81 Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
83 public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
84 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_SUCCESS);
85 synchronized (deviceContext) {
86 deviceContext.getDeviceFlowRegistry().store(flowHash, flowDescriptor);
88 if (rpcResult.isSuccessful()) {
89 LOG.debug("flow add finished without error, id={}", flowId.getValue());
91 LOG.debug("flow add failed with error, id={}", flowId.getValue());
96 public void onFailure(final Throwable throwable) {
97 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
98 synchronized (deviceContext) {
99 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
101 LOG.trace("Service call for adding flows failed, id={}.", flowId.getValue(), throwable);
109 public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
110 LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
111 return this.<RemoveFlowOutput, Void>handleServiceCall(new Function<DataCrate<RemoveFlowOutput>, ListenableFuture<RpcResult<Void>>>() {
113 public ListenableFuture<RpcResult<Void>> apply(final DataCrate<RemoveFlowOutput> data) {
114 final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, getVersion(),
116 final ListenableFuture<RpcResult<Void>> future = createResultForFlowMod(data, ofFlowModInput);
117 Futures.addCallback(future, new FutureCallback() {
119 public void onSuccess(final Object o) {
120 final DeviceContext deviceContext = getDeviceContext();
121 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_SUCCESS);
122 FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
123 synchronized (deviceContext) {
124 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
129 public void onFailure(final Throwable throwable) {
130 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
131 StringBuffer errors = new StringBuffer();
133 RpcResult<Void> result = future.get();
134 Collection<RpcError> rpcErrors = result.getErrors();
135 if (null != rpcErrors && rpcErrors.size() > 0) {
136 for (RpcError rpcError : rpcErrors) {
137 errors.append(rpcError.getMessage());
140 } catch (InterruptedException | ExecutionException e) {
141 LOG.trace("Flow modification failed. Can't read errors from RpcResult.");
143 LOG.trace("Flow modification failed. Errors : {}", errors.toString());
152 public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
153 final UpdateFlowInput in = input;
154 final UpdatedFlow updated = in.getUpdatedFlow();
155 final OriginalFlow original = in.getOriginalFlow();
157 final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
158 List<FlowModInputBuilder> ofFlowModInputs;
160 if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) {
161 // We would need to remove original and add updated.
164 final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
165 final List<FlowModInputBuilder> ofFlowRemoveInput = FlowConvertor.toFlowModInputs(removeflow.build(),
166 getVersion(), getDatapathId());
167 // remove flow should be the first
168 allFlowMods.addAll(ofFlowRemoveInput);
169 final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
170 ofFlowModInputs = FlowConvertor.toFlowModInputs(addFlowInputBuilder.build(), getVersion(), getDatapathId());
172 ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, getVersion(), getDatapathId());
175 allFlowMods.addAll(ofFlowModInputs);
176 ListenableFuture future = processFlowModInputBuilders(allFlowMods);
177 Futures.addCallback(future, new FutureCallback() {
179 public void onSuccess(final Object o) {
180 final DeviceContext deviceContext = getDeviceContext();
181 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_SUCCESS);
182 final short version = deviceContext.getPrimaryConnectionContext().getFeatures().getVersion();
183 FlowHash flowHash = FlowHashFactory.create(original, version);
185 FlowHash updatedflowHash = FlowHashFactory.create(updated, version);
186 FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
187 FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
188 synchronized (deviceContext) {
189 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
190 deviceContext.getDeviceFlowRegistry().store(updatedflowHash, flowDescriptor);
195 public void onFailure(final Throwable throwable) {
196 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
202 private <T> ListenableFuture<RpcResult<T>> processFlowModInputBuilders(
203 final List<FlowModInputBuilder> ofFlowModInputs) {
204 final List<ListenableFuture<RpcResult<T>>> partialFutures = new ArrayList<>();
206 for (FlowModInputBuilder flowModInputBuilder : ofFlowModInputs) {
207 DataCrateBuilder<T> dataCrateBuilder = DataCrateBuilder.<T>builder().setFlowModInputBuilder(flowModInputBuilder);
208 ListenableFuture<RpcResult<T>> partialFuture = handleServiceCall(
209 getPrimaryConnection(),
210 new Function<DataCrate<T>, ListenableFuture<RpcResult<Void>>>() {
212 public ListenableFuture<RpcResult<Void>> apply(final DataCrate<T> data) {
213 return createResultForFlowMod(data);
218 partialFutures.add(partialFuture);
221 // processing of final (optionally composite future)
222 final ListenableFuture<List<RpcResult<T>>> allFutures = Futures.successfulAsList(partialFutures);
223 final SettableFuture<RpcResult<T>> finalFuture = SettableFuture.create();
224 Futures.addCallback(allFutures, new FutureCallback<List<RpcResult<T>>>() {
226 public void onSuccess(List<RpcResult<T>> results) {
227 List<RpcError> rpcErrorLot = new ArrayList<>();
228 RpcResultBuilder<T> resultBuilder;
230 Iterator<FlowModInputBuilder> flowModInputBldIterator = ofFlowModInputs.iterator();
231 Iterator<RpcResult<T>> resultIterator = results.iterator();
233 for (ListenableFuture<RpcResult<T>> partFutureFromRqCtx : partialFutures) {
234 FlowModInputBuilder flowModInputBld = flowModInputBldIterator.next();
235 RpcResult<T> result = resultIterator.next();
236 Long xid = flowModInputBld.getXid();
239 LOG.trace("flowMod future processing [{}], result={}", xid, result);
240 if (partFutureFromRqCtx.isCancelled()) { // one and only positive case
241 if (LOG.isTraceEnabled()) {
242 LOG.trace("flow future result was cancelled [{}] = barrier passed it without error", xid);
244 } else { // all negative cases
245 if (result == null) { // there is exception or null value set
247 partFutureFromRqCtx.get();
248 } catch (Exception e) {
249 rpcErrorLot.add(RpcResultBuilder.newError(ErrorType.APPLICATION, "",
250 "flow future result [" + xid + "] failed with exception",
251 OFConstants.APPLICATION_TAG, e.getMessage(), e));
253 // xid might be not available in case requestContext not even stored
255 final DeviceContext deviceContext = getDeviceContext();
256 synchronized (deviceContext) {
257 deviceContext.unhookRequestCtx(new Xid(xid));
262 if (result.isSuccessful()) { // positive confirmation - never happens
263 LOG.warn("Positive confirmation of flow push is not supported by OF-spec");
264 LOG.warn("flow future result was successful [{}] = this should have never happen",
266 rpcErrorLot.add(RpcResultBuilder.newError(ErrorType.APPLICATION, "",
267 "flow future result was successful [" + xid + "] = this should have never happen"));
268 } else { // standard error occurred
269 LOG.trace("passing original rpcErrors [{}]", xid);
270 if (LOG.isTraceEnabled()) {
271 for (RpcError rpcError : result.getErrors()) {
272 LOG.trace("passed rpcError [{}]: {}", xid, rpcError);
275 rpcErrorLot.addAll(result.getErrors());
281 if (rpcErrorLot.isEmpty()) {
282 resultBuilder = RpcResultBuilder.<T>success();
284 resultBuilder = RpcResultBuilder.<T>failed().withRpcErrors(rpcErrorLot);
287 finalFuture.set(resultBuilder.build());
291 public void onFailure(Throwable t) {
292 LOG.trace("Flow mods chained future failed.");
293 RpcResultBuilder<T> resultBuilder = RpcResultBuilder.<T>failed()
294 .withError(ErrorType.APPLICATION, "", t.getMessage());
295 finalFuture.set(resultBuilder.build());
302 protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data) {
303 return createResultForFlowMod(data, data.getFlowModInputBuilder());
306 protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data, final FlowModInputBuilder flowModInputBuilder) {
307 final Xid xid = data.getRequestContext().getXid();
308 flowModInputBuilder.setXid(xid.getValue());
309 final FlowModInput flowModInput = flowModInputBuilder.build();
310 Future<RpcResult<Void>> flowModResult = provideConnectionAdapter(data.getiDConnection()).flowMod(
313 final ListenableFuture<RpcResult<Void>> result = JdkFutureAdapters.listenInPoolThread(flowModResult);