SalFlowServiceImpl - implementing methods
[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.util.concurrent.AsyncFunction;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.JdkFutureAdapters;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.math.BigInteger;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Future;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
23 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
24 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
25 import org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory;
26 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.FlowConvertor;
27 import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
40 import org.opendaylight.yangtools.yang.binding.DataObject;
41 import org.opendaylight.yangtools.yang.common.RpcError;
42 import org.opendaylight.yangtools.yang.common.RpcResult;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.slf4j.Logger;
45
46 public class SalFlowServiceImpl extends CommonService implements SalFlowService {
47
48     private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
49
50     // TODO set cookie somehow from - DeviceContext probably (temporary set to 0 - primary connection)
51     private final BigInteger connectionID = PRIMARY_CONNECTION;
52
53     private interface Function {
54         Future<RpcResult<Void>> apply(final BigInteger IDConnection);
55     }
56
57     public SalFlowServiceImpl(final RpcContext rpcContext) {
58         super(rpcContext);
59     }
60
61     @Override
62     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
63         return processFlow(new Function() {
64             @Override
65             public ListenableFuture<RpcResult<Void>> apply(final BigInteger IDConnection) {
66                 final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, version,
67                         datapathId);
68                 return chainFlowMods(ofFlowModInputs, 0, IDConnection);
69             }
70         });
71     }
72
73     @Override
74     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
75         return processFlow(new Function() {
76             @Override
77             public Future<RpcResult<Void>> apply(final BigInteger IDConnection) {
78                 final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, version,
79                         datapathId);
80                 return provideConnectionAdapter(IDConnection).flowMod(ofFlowModInputs.get(0).build());
81             }
82         });
83     }
84
85     @Override
86     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
87         final UpdateFlowInput in = input;
88         final UpdatedFlow updated = in.getUpdatedFlow();
89         final OriginalFlow original = in.getOriginalFlow();
90
91         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
92         List<FlowModInputBuilder> ofFlowModInputs;
93
94         if (!FlowCreatorUtil.canModifyFlow(original, updated, version)) {
95             // We would need to remove original and add updated.
96
97             // remove flow
98             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
99             final List<FlowModInputBuilder> ofFlowRemoveInput = FlowConvertor.toFlowModInputs(removeflow.build(),
100                     version, datapathId);
101             // remove flow should be the first
102             allFlowMods.addAll(ofFlowRemoveInput);
103             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
104             ofFlowModInputs = FlowConvertor.toFlowModInputs(addFlowInputBuilder.build(), version, datapathId);
105         } else {
106             ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, version, datapathId);
107         }
108
109         allFlowMods.addAll(ofFlowModInputs);
110         LOG.debug("Number of flows to push to switch: {}", allFlowMods.size());
111         Collections.<String> emptyList();
112         return this.<UpdateFlowOutput> processFlow(new Function() {
113             @Override
114             public Future<RpcResult<Void>> apply(final BigInteger cookie) {
115                 return chainFlowMods(allFlowMods, 0, cookie);
116             }
117         });
118     }
119
120     private <T extends DataObject> Future<RpcResult<T>> processFlow(final Function function) {
121         LOG.debug("Calling the FlowMod RPC method on MessageDispatchService");
122         // use primary connection
123
124         final RequestContext requestContext = rpcContext.createRequestContext();
125         final SettableFuture<RpcResult<T>> result = rpcContext.storeOrFail(requestContext);
126
127         if (!result.isDone()) {
128             try {
129                 final Future<RpcResult<Void>> resultFromOFLib = function.apply(connectionID);
130                 final RpcResult<Void> rpcResult = resultFromOFLib.get(getWaitTime(), TimeUnit.MILLISECONDS);
131                 if (!rpcResult.isSuccessful()) {
132                     result.set(RpcResultBuilder.<T> failed().withRpcErrors(rpcResult.getErrors()).build());
133                     requestContext.close();
134                 }
135             } catch (InterruptedException | ExecutionException | TimeoutException e) {
136                 result.set(RpcResultBuilder
137                         .<T> failed()
138                         .withError(RpcError.ErrorType.APPLICATION, "",
139                                 "Flow modification on device wasn't successfull.").build());
140                 requestContext.close();
141             } catch (final Exception e) {
142                 result.set(RpcResultBuilder.<T> failed()
143                         .withError(RpcError.ErrorType.APPLICATION, "", "Flow translation to OF JAVA failed.").build());
144                 requestContext.close();
145             }
146
147         } else {
148             requestContext.close();
149         }
150         return result;
151     }
152
153     /**
154      * Recursive helper method for
155      * {@link OFRpcTaskFactory#chainFlowMods(java.util.List, int, org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext, org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher)}
156      * {@link OFRpcTaskFactory#createUpdateFlowTask()} to chain results of multiple flowmods. The next flowmod gets
157      * executed if the earlier one is successful. All the flowmods should have the same xid, in-order to cross-reference
158      * the notification
159      */
160     protected ListenableFuture<RpcResult<Void>> chainFlowMods(final List<FlowModInputBuilder> ofFlowModInputs,
161             final int index, final BigInteger cookie) {
162
163         final Future<RpcResult<Void>> resultFromOFLib = createResultForFlowMod(ofFlowModInputs.get(index), cookie);
164
165         final ListenableFuture<RpcResult<Void>> result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
166
167         if (ofFlowModInputs.size() > index + 1) {
168             // there are more flowmods to chain
169             return Futures.transform(result, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
170                 @Override
171                 public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
172                     if (input.isSuccessful()) {
173                         return chainFlowMods(ofFlowModInputs, index + 1, cookie);
174                     } else {
175                         LOG.warn("Flowmod failed. Any chained flowmods are ignored. xid:{}", ofFlowModInputs.get(index)
176                                 .getXid());
177                         return Futures.immediateFuture(input);
178                     }
179                 }
180             });
181         } else {
182             return result;
183         }
184     }
185
186     protected Future<RpcResult<Void>> createResultForFlowMod(final FlowModInputBuilder flowModInput,
187             final BigInteger cookie) {
188         flowModInput.setXid(deviceContext.getNextXid().getValue());
189         return provideConnectionAdapter(cookie).flowMod(flowModInput.build());
190     }
191
192 }