CommonService has its fields private
[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  * <p/>
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.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;
55
56 public class SalFlowServiceImpl extends CommonService implements SalFlowService {
57
58     private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
59
60     public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
61         super(requestContextStack, deviceContext);
62     }
63
64     @Override
65     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
66         final FlowId flowId;
67         if (null != input.getFlowRef()) {
68             flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
69         } else {
70             flowId = FlowUtil.createAlienFlowId(input.getTableId());
71         }
72
73
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);
77
78         final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, getVersion(), getDatapathId());
79         final ListenableFuture<RpcResult<AddFlowOutput>> future = processFlowModInputBuilders(ofFlowModInputs);
80
81         Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
82             @Override
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);
87                 }
88                 if (rpcResult.isSuccessful()) {
89                     LOG.debug("flow add finished without error, id={}", flowId.getValue());
90                 } else {
91                     LOG.debug("flow add failed with error, id={}", flowId.getValue());
92                 }
93             }
94
95             @Override
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);
100                 }
101                 LOG.trace("Service call for adding flows failed, id={}.", flowId.getValue(), throwable);
102             }
103         });
104
105         return future;
106     }
107
108     @Override
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>>>() {
112                     @Override
113                     public ListenableFuture<RpcResult<Void>> apply(final DataCrate<RemoveFlowOutput> data) {
114                         final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, getVersion(),
115                                 getDatapathId());
116                         final ListenableFuture<RpcResult<Void>> future = createResultForFlowMod(data, ofFlowModInput);
117                         Futures.addCallback(future, new FutureCallback() {
118                             @Override
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);
125                                 }
126                             }
127
128                             @Override
129                             public void onFailure(final Throwable throwable) {
130                                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
131                                 StringBuffer errors = new StringBuffer();
132                                 try {
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());
138                                         }
139                                     }
140                                 } catch (InterruptedException | ExecutionException e) {
141                                     LOG.trace("Flow modification failed. Can't read errors from RpcResult.");
142                                 }
143                                 LOG.trace("Flow modification failed. Errors : {}", errors.toString());
144                             }
145                         });
146                         return future;
147                     }
148                 });
149     }
150
151     @Override
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();
156
157         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
158         List<FlowModInputBuilder> ofFlowModInputs;
159
160         if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) {
161             // We would need to remove original and add updated.
162
163             // remove flow
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());
171         } else {
172             ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, getVersion(), getDatapathId());
173         }
174
175         allFlowMods.addAll(ofFlowModInputs);
176         ListenableFuture future = processFlowModInputBuilders(allFlowMods);
177         Futures.addCallback(future, new FutureCallback() {
178             @Override
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);
184
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);
191                 }
192             }
193
194             @Override
195             public void onFailure(final Throwable throwable) {
196                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMITTED_FAILURE);
197             }
198         });
199         return future;
200     }
201
202     private <T> ListenableFuture<RpcResult<T>> processFlowModInputBuilders(
203             final List<FlowModInputBuilder> ofFlowModInputs) {
204         final List<ListenableFuture<RpcResult<T>>> partialFutures = new ArrayList<>();
205
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>>>() {
211                         @Override
212                         public ListenableFuture<RpcResult<Void>> apply(final DataCrate<T> data) {
213                             return createResultForFlowMod(data);
214                         }
215                     },
216                     dataCrateBuilder
217             );
218             partialFutures.add(partialFuture);
219         }
220
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>>>() {
225             @Override
226             public void onSuccess(List<RpcResult<T>> results) {
227                 List<RpcError> rpcErrorLot = new ArrayList<>();
228                 RpcResultBuilder<T> resultBuilder;
229
230                 Iterator<FlowModInputBuilder> flowModInputBldIterator = ofFlowModInputs.iterator();
231                 Iterator<RpcResult<T>> resultIterator = results.iterator();
232
233                 for (ListenableFuture<RpcResult<T>> partFutureFromRqCtx : partialFutures) {
234                     FlowModInputBuilder flowModInputBld = flowModInputBldIterator.next();
235                     RpcResult<T> result = resultIterator.next();
236                     Long xid = flowModInputBld.getXid();
237
238
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);
243                         }
244                     } else { // all negative cases
245                         if (result == null) { // there is exception or null value set
246                             try {
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));
252
253                                 // xid might be not available in case requestContext not even stored
254                                 if (xid != null) {
255                                     final DeviceContext deviceContext = getDeviceContext();
256                                     synchronized (deviceContext) {
257                                         deviceContext.unhookRequestCtx(new Xid(xid));
258                                     }
259                                 }
260                             }
261                         } else {
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",
265                                         xid);
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);
273                                     }
274                                 }
275                                 rpcErrorLot.addAll(result.getErrors());
276                             }
277                         }
278                     }
279                 }
280
281                 if (rpcErrorLot.isEmpty()) {
282                     resultBuilder = RpcResultBuilder.<T>success();
283                 } else {
284                     resultBuilder = RpcResultBuilder.<T>failed().withRpcErrors(rpcErrorLot);
285                 }
286
287                 finalFuture.set(resultBuilder.build());
288             }
289
290             @Override
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());
296             }
297         });
298
299         return finalFuture;
300     }
301
302     protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data) {
303         return createResultForFlowMod(data, data.getFlowModInputBuilder());
304     }
305
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(
311                 flowModInput);
312
313         final ListenableFuture<RpcResult<Void>> result = JdkFutureAdapters.listenInPoolThread(flowModResult);
314         return result;
315     }
316
317 }