statistics groups renamed
[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.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Future;
21 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
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.DeviceFlowRegistry;
27 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
28 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowHash;
29 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
30 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
31 import org.opendaylight.openflowplugin.impl.registry.flow.FlowHashFactory;
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.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
51 import org.opendaylight.yangtools.yang.common.RpcError;
52 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
53 import org.opendaylight.yangtools.yang.common.RpcResult;
54 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
55 import org.slf4j.Logger;
56
57 public class SalFlowServiceImpl extends CommonService implements SalFlowService {
58
59     private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalFlowServiceImpl.class);
60
61     public SalFlowServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
62         super(requestContextStack, deviceContext);
63     }
64
65     @Override
66     public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
67         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_ENTERED);
68
69         final List<FlowModInputBuilder> ofFlowModInputs = FlowConvertor.toFlowModInputs(input, getVersion(), getDatapathId());
70         final ListenableFuture<RpcResult<AddFlowOutput>> future = processFlowModInputBuilders(ofFlowModInputs);
71
72         Futures.addCallback(future, new FutureCallback<RpcResult<AddFlowOutput>>() {
73
74             final DeviceContext deviceContext = getDeviceContext();
75             final FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
76             FlowId flowId = null;
77             @Override
78             public void onSuccess(final RpcResult<AddFlowOutput> rpcResult) {
79                 if (rpcResult.isSuccessful()) {
80                     getMessageSpy().spyMessage(FlowModInput.class, MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
81                     LOG.debug("flow add finished without error, id={}", flowId.getValue());
82                 } else {
83                     getMessageSpy().spyMessage(FlowModInput.class, MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
84                     LOG.debug("flow add failed with error, id={}", flowId.getValue());
85                 }
86             }
87
88             @Override
89             public void onFailure(final Throwable throwable) {
90                 deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
91                 getMessageSpy().spyMessage(FlowModInput.class, MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
92                 LOG.trace("Service call for adding flows failed, id={}.", flowId.getValue(), throwable);
93             }
94         });
95
96         return future;
97     }
98
99     @Override
100     public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
101         LOG.trace("Calling remove flow for flow with ID ={}.", input.getFlowRef());
102         return this.<RemoveFlowOutput, Void>handleServiceCall(new Function<DataCrate<RemoveFlowOutput>, ListenableFuture<RpcResult<Void>>>() {
103             @Override
104             public ListenableFuture<RpcResult<Void>> apply(final DataCrate<RemoveFlowOutput> data) {
105                 final FlowModInputBuilder ofFlowModInput = FlowConvertor.toFlowModInput(input, getVersion(),
106                         getDatapathId());
107                 final ListenableFuture<RpcResult<Void>> future = createResultForFlowMod(data, ofFlowModInput);
108                 Futures.addCallback(future, new FutureCallback() {
109                     @Override
110                     public void onSuccess(final Object o) {
111                         final DeviceContext deviceContext = getDeviceContext();
112                         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
113                         FlowHash flowHash = FlowHashFactory.create(input, deviceContext.getPrimaryConnectionContext().getFeatures().getVersion());
114                         deviceContext.getDeviceFlowRegistry().markToBeremoved(flowHash);
115                     }
116
117                     @Override
118                     public void onFailure(final Throwable throwable) {
119                         getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
120                         LOG.trace("Flow modification failed..", throwable);
121                         StringBuffer errors = new StringBuffer();
122                         try {
123                             RpcResult<Void> result = future.get();
124                             Collection<RpcError> rpcErrors = result.getErrors();
125                             if (null != rpcErrors && rpcErrors.size() > 0) {
126                                 for (RpcError rpcError : rpcErrors) {
127                                     errors.append(rpcError.getMessage());
128                                 }
129                             }
130                         } catch (InterruptedException | ExecutionException e) {
131                             LOG.trace("Flow modification failed. Can't read errors from RpcResult.");
132                         } finally {
133                             LOG.trace("Flow modification failed. Errors : {}", errors.toString());
134                         }
135                     }
136                 });
137                 return future;
138             }
139         });
140     }
141
142     @Override
143     public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
144         final UpdateFlowInput in = input;
145         final UpdatedFlow updated = in.getUpdatedFlow();
146         final OriginalFlow original = in.getOriginalFlow();
147
148         final List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
149         List<FlowModInputBuilder> ofFlowModInputs;
150
151         if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) {
152             // We would need to remove original and add updated.
153
154             // remove flow
155             final RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
156             final List<FlowModInputBuilder> ofFlowRemoveInput = FlowConvertor.toFlowModInputs(removeflow.build(),
157                     getVersion(), getDatapathId());
158             // remove flow should be the first
159             allFlowMods.addAll(ofFlowRemoveInput);
160             final AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
161             ofFlowModInputs = FlowConvertor.toFlowModInputs(addFlowInputBuilder.build(), getVersion(), getDatapathId());
162         } else {
163             ofFlowModInputs = FlowConvertor.toFlowModInputs(updated, getVersion(), getDatapathId());
164         }
165
166         allFlowMods.addAll(ofFlowModInputs);
167         ListenableFuture future = processFlowModInputBuilders(allFlowMods);
168         Futures.addCallback(future, new FutureCallback() {
169             @Override
170             public void onSuccess(final Object o) {
171                 final DeviceContext deviceContext = getDeviceContext();
172                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
173                 final short version = deviceContext.getPrimaryConnectionContext().getFeatures().getVersion();
174                 FlowHash flowHash = FlowHashFactory.create(original, version);
175
176                 FlowHash updatedflowHash = FlowHashFactory.create(updated, version);
177                 FlowId flowId = input.getFlowRef().getValue().firstKeyOf(Flow.class, FlowKey.class).getId();
178                 FlowDescriptor flowDescriptor = FlowDescriptorFactory.create(updated.getTableId(), flowId);
179                 final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
180                 deviceFlowRegistry.markToBeremoved(flowHash);
181                 deviceFlowRegistry.store(updatedflowHash, flowDescriptor);
182             }
183
184             @Override
185             public void onFailure(final Throwable throwable) {
186                 getMessageSpy().spyMessage(input.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
187             }
188         });
189         return future;
190     }
191
192     private <T> ListenableFuture<RpcResult<T>> processFlowModInputBuilders(final List<FlowModInputBuilder> ofFlowModInputs) {
193
194         final List<ListenableFuture<RpcResult<T>>> partialFutures = new ArrayList<>();
195
196         for (FlowModInputBuilder flowModInputBuilder : ofFlowModInputs) {
197             DataCrateBuilder<T> dataCrateBuilder = DataCrateBuilder.<T>builder().setFlowModInputBuilder(flowModInputBuilder);
198             ListenableFuture<RpcResult<T>> partialFuture = handleServiceCall(
199                     new Function<DataCrate<T>, ListenableFuture<RpcResult<Void>>>() {
200                         @Override
201                         public ListenableFuture<RpcResult<Void>> apply(final DataCrate<T> data) {
202                             return createResultForFlowMod(data);
203                         }
204                     },
205                     dataCrateBuilder
206             );
207             partialFutures.add(partialFuture);
208         }
209
210         // processing of final (optionally composite future)
211         final ListenableFuture<List<RpcResult<T>>> allFutures = Futures.successfulAsList(partialFutures);
212         final SettableFuture<RpcResult<T>> finalFuture = SettableFuture.create();
213         Futures.addCallback(allFutures, new FutureCallback<List<RpcResult<T>>>() {
214             @Override
215             public void onSuccess(List<RpcResult<T>> results) {
216                 List<RpcError> rpcErrorLot = new ArrayList<>();
217                 RpcResultBuilder<T> resultBuilder;
218
219                 Iterator<FlowModInputBuilder> flowModInputBldIterator = ofFlowModInputs.iterator();
220                 Iterator<RpcResult<T>> resultIterator = results.iterator();
221
222                 for (ListenableFuture<RpcResult<T>> partFutureFromRqCtx : partialFutures) {
223                     FlowModInputBuilder flowModInputBld = flowModInputBldIterator.next();
224                     RpcResult<T> result = resultIterator.next();
225                     Long xid = flowModInputBld.getXid();
226
227
228                     LOG.trace("flowMod future processing [{}], result={}", xid, result);
229                     if (partFutureFromRqCtx.isCancelled()) { // one and only positive case
230                         if (LOG.isTraceEnabled()) {
231                             LOG.trace("flow future result was cancelled [{}] = barrier passed it without error", xid);
232                         }
233                     } else { // all negative cases
234                         if (result == null) { // there is exception or null value set
235                             try {
236                                 partFutureFromRqCtx.get();
237                             } catch (Exception e) {
238                                 rpcErrorLot.add(RpcResultBuilder.newError(ErrorType.APPLICATION, "",
239                                         "flow future result [" + xid + "] failed with exception",
240                                         OFConstants.APPLICATION_TAG, e.getMessage(), e));
241
242                                 // xid might be not available in case requestContext not even stored
243                                 if (xid != null) {
244                                     final DeviceContext deviceContext = getDeviceContext();
245                                     deviceContext.unhookRequestCtx(new Xid(xid));
246                                 }
247                             }
248                         } else {
249                             if (result.isSuccessful()) {  // positive confirmation - never happens
250                                 LOG.warn("Positive confirmation of flow push is not supported by OF-spec");
251                                 LOG.warn("flow future result was successful [{}] = this should have never happen",
252                                         xid);
253                                 rpcErrorLot.add(RpcResultBuilder.newError(ErrorType.APPLICATION, "",
254                                         "flow future result was successful [" + xid + "] = this should have never happen"));
255                             } else { // standard error occurred
256                                 LOG.trace("passing original rpcErrors [{}]", xid);
257                                 if (LOG.isTraceEnabled()) {
258                                     for (RpcError rpcError : result.getErrors()) {
259                                         LOG.trace("passed rpcError [{}]: {}", xid, rpcError);
260                                     }
261                                 }
262                                 rpcErrorLot.addAll(result.getErrors());
263                             }
264                         }
265                     }
266                 }
267
268                 if (rpcErrorLot.isEmpty()) {
269                     resultBuilder = RpcResultBuilder.<T>success();
270                 } else {
271                     resultBuilder = RpcResultBuilder.<T>failed().withRpcErrors(rpcErrorLot);
272                 }
273
274                 finalFuture.set(resultBuilder.build());
275             }
276
277             @Override
278             public void onFailure(Throwable t) {
279                 LOG.trace("Flow mods chained future failed.");
280                 RpcResultBuilder<T> resultBuilder = RpcResultBuilder.<T>failed()
281                         .withError(ErrorType.APPLICATION, "", t.getMessage());
282                 finalFuture.set(resultBuilder.build());
283             }
284         });
285
286         return finalFuture;
287     }
288
289     protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data) {
290         return createResultForFlowMod(data, data.getFlowModInputBuilder());
291     }
292
293     protected <T> ListenableFuture<RpcResult<Void>> createResultForFlowMod(final DataCrate<T> data, final FlowModInputBuilder flowModInputBuilder) {
294         final OutboundQueue outboundQueue = getDeviceContext().getPrimaryConnectionContext().getOutboundQueueProvider().getOutboundQueue();
295         long xid = data.getRequestContext().getXid().getValue();
296         flowModInputBuilder.setXid(xid);
297         final FlowModInput flowModInput = flowModInputBuilder.build();
298
299         final SettableFuture<RpcResult<Void>> settableFuture = SettableFuture.create();
300         outboundQueue.commitEntry(xid, flowModInput, new FutureCallback<OfHeader>() {
301             @Override
302             public void onSuccess(final OfHeader ofHeader) {
303                 settableFuture.set(RpcResultBuilder.<Void>success().build());
304             }
305
306             @Override
307             public void onFailure(final Throwable throwable) {
308                 RpcResultBuilder rpcResultBuilder = RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, throwable.getMessage());
309                 settableFuture.set(rpcResultBuilder.build());
310             }
311         });
312         return settableFuture;
313     }
314
315 }