2 * Copyright (c) 2014, 2017 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.applications.frm.impl;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.buildGroupInstanceIdentifier;
12 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getActiveBundle;
13 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getFlowId;
14 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getNodeIdValueFromNodeIdentifier;
15 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.isFlowDependentOnGroup;
16 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.isGroupExistsOnDevice;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import com.google.common.util.concurrent.SettableFuture;
24 import java.util.Optional;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.Future;
27 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
28 import org.opendaylight.mdsal.binding.api.DataBroker;
29 import org.opendaylight.mdsal.binding.api.ReadTransaction;
30 import org.opendaylight.mdsal.binding.api.WriteTransaction;
31 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
32 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowTableRef;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInputBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlowBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlowBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupRef;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
63 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
64 import org.opendaylight.yangtools.yang.common.ErrorType;
65 import org.opendaylight.yangtools.yang.common.RpcResult;
66 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
67 import org.opendaylight.yangtools.yang.common.Uint32;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * FlowForwarder It implements
73 * {@link org.opendaylight.mdsal.binding.api.DataTreeChangeListener}
74 * for WildCardedPath to {@link Flow} and ForwardingRulesCommiter interface for
75 * methods: add, update and remove {@link Flow} processing for
76 * {@link org.opendaylight.mdsal.binding.api.DataTreeModification}.
78 public class FlowForwarder extends AbstractListeningCommiter<Flow> {
79 private static final Logger LOG = LoggerFactory.getLogger(FlowForwarder.class);
80 private static final String GROUP_EXISTS_IN_DEVICE_ERROR = "GROUPEXISTS";
82 public FlowForwarder(final ForwardingRulesManager manager, final DataBroker db,
83 final ListenerRegistrationHelper registrationHelper) {
84 super(manager, db, registrationHelper);
88 public void remove(final InstanceIdentifier<Flow> identifier, final Flow removeDataObj,
89 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
91 final TableKey tableKey = identifier.firstKeyOf(Table.class);
92 if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
93 BundleId bundleId = getActiveBundle(nodeIdent, provider);
94 if (bundleId != null) {
95 provider.getBundleFlowListener().remove(identifier, removeDataObj, nodeIdent, bundleId);
97 final String nodeId = getNodeIdValueFromNodeIdentifier(nodeIdent);
98 nodeConfigurator.enqueueJob(nodeId, () -> {
99 final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
100 builder.setFlowRef(new FlowRef(identifier));
101 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
102 builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
104 // This method is called only when a given flow object has been
105 // removed from datastore. So FRM always needs to set strict flag
106 // into remove-flow input so that only a flow entry associated with
107 // a given flow object is removed.
108 builder.setTransactionUri(new Uri(provider.getNewTransactionId())).setStrict(Boolean.TRUE);
109 final ListenableFuture<RpcResult<RemoveFlowOutput>> resultFuture =
110 provider.getSalFlowService().removeFlow(builder.build());
111 LoggingFutures.addErrorLogging(resultFuture, LOG, "removeFlow");
118 // TODO: Pull this into ForwardingRulesCommiter and override it here
121 public ListenableFuture<RpcResult<RemoveFlowOutput>> removeWithResult(final InstanceIdentifier<Flow> identifier,
122 final Flow removeDataObj, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
124 ListenableFuture<RpcResult<RemoveFlowOutput>> resultFuture = SettableFuture.create();
125 final TableKey tableKey = identifier.firstKeyOf(Table.class);
126 if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
127 final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
128 builder.setFlowRef(new FlowRef(identifier));
129 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
130 builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
132 // This method is called only when a given flow object has been
133 // removed from datastore. So FRM always needs to set strict flag
134 // into remove-flow input so that only a flow entry associated with
135 // a given flow object is removed.
136 builder.setTransactionUri(new Uri(provider.getNewTransactionId())).setStrict(Boolean.TRUE);
137 resultFuture = provider.getSalFlowService().removeFlow(builder.build());
144 public void update(final InstanceIdentifier<Flow> identifier, final Flow original, final Flow update,
145 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
147 final TableKey tableKey = identifier.firstKeyOf(Table.class);
148 if (tableIdValidationPrecondition(tableKey, update)) {
149 BundleId bundleId = getActiveBundle(nodeIdent, provider);
150 if (bundleId != null) {
151 provider.getBundleFlowListener().update(identifier, original, update, nodeIdent, bundleId);
153 final String nodeId = getNodeIdValueFromNodeIdentifier(nodeIdent);
154 nodeConfigurator.enqueueJob(nodeId, () -> {
155 final UpdateFlowInputBuilder builder = new UpdateFlowInputBuilder();
156 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
157 builder.setFlowRef(new FlowRef(identifier));
158 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
160 // This method is called only when a given flow object in datastore
161 // has been updated. So FRM always needs to set strict flag into
162 // update-flow input so that only a flow entry associated with
163 // a given flow object is updated.
164 builder.setUpdatedFlow(new UpdatedFlowBuilder(update).setStrict(Boolean.TRUE).build());
165 builder.setOriginalFlow(new OriginalFlowBuilder(original).setStrict(Boolean.TRUE).build());
167 Uint32 groupId = isFlowDependentOnGroup(update);
168 if (groupId != null) {
169 LOG.trace("The flow {} is dependent on group {}. Checking if the group is already present",
170 getFlowId(identifier), groupId);
171 if (isGroupExistsOnDevice(nodeIdent, groupId, provider)) {
172 LOG.trace("The dependent group {} is already programmed. Updating the flow {}", groupId,
173 getFlowId(identifier));
174 return provider.getSalFlowService().updateFlow(builder.build());
176 LOG.trace("The dependent group {} isn't programmed yet. Pushing the group", groupId);
177 ListenableFuture<RpcResult<AddGroupOutput>> groupFuture = pushDependentGroup(nodeIdent,
179 SettableFuture<RpcResult<UpdateFlowOutput>> resultFuture = SettableFuture.create();
180 Futures.addCallback(groupFuture,
181 new UpdateFlowCallBack(builder.build(), nodeId, resultFuture, groupId),
182 MoreExecutors.directExecutor());
187 LOG.trace("The flow {} is not dependent on any group. Updating the flow",
188 getFlowId(identifier));
189 return provider.getSalFlowService().updateFlow(builder.build());
196 public Future<? extends RpcResult<?>> add(final InstanceIdentifier<Flow> identifier, final Flow addDataObj,
197 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
199 final TableKey tableKey = identifier.firstKeyOf(Table.class);
200 if (tableIdValidationPrecondition(tableKey, addDataObj)) {
201 BundleId bundleId = getActiveBundle(nodeIdent, provider);
202 if (bundleId != null) {
203 return provider.getBundleFlowListener().add(identifier, addDataObj, nodeIdent, bundleId);
205 final String nodeId = getNodeIdValueFromNodeIdentifier(nodeIdent);
206 nodeConfigurator.enqueueJob(nodeId, () -> {
207 final AddFlowInputBuilder builder = new AddFlowInputBuilder(addDataObj);
209 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
210 builder.setFlowRef(new FlowRef(identifier));
211 builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
212 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
213 Uint32 groupId = isFlowDependentOnGroup(addDataObj);
214 if (groupId != null) {
215 LOG.trace("The flow {} is dependent on group {}. Checking if the group is already present",
216 getFlowId(new FlowRef(identifier)), groupId);
217 if (isGroupExistsOnDevice(nodeIdent, groupId, provider)) {
218 LOG.trace("The dependent group {} is already programmed. Adding the flow {}", groupId,
219 getFlowId(new FlowRef(identifier)));
220 return provider.getSalFlowService().addFlow(builder.build());
222 LOG.trace("The dependent group {} isn't programmed yet. Pushing the group", groupId);
223 ListenableFuture<RpcResult<AddGroupOutput>> groupFuture = pushDependentGroup(nodeIdent,
225 SettableFuture<RpcResult<AddFlowOutput>> resultFuture = SettableFuture.create();
226 Futures.addCallback(groupFuture, new AddFlowCallBack(builder.build(), nodeId, groupId,
227 resultFuture), MoreExecutors.directExecutor());
232 LOG.trace("The flow {} is not dependent on any group. Adding the flow",
233 getFlowId(new FlowRef(identifier)));
234 return provider.getSalFlowService().addFlow(builder.build());
238 return Futures.immediateFuture(null);
242 public void createStaleMarkEntity(final InstanceIdentifier<Flow> identifier, final Flow del,
243 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
244 LOG.debug("Creating Stale-Mark entry for the switch {} for flow {} ", nodeIdent, del);
245 StaleFlow staleFlow = makeStaleFlow(identifier, del, nodeIdent);
246 persistStaleFlow(staleFlow, nodeIdent);
250 protected InstanceIdentifier<Flow> getWildCardPath() {
251 return InstanceIdentifier.create(Nodes.class).child(Node.class).augmentation(FlowCapableNode.class)
252 .child(Table.class).child(Flow.class);
255 private static boolean tableIdValidationPrecondition(final TableKey tableKey, final Flow flow) {
256 requireNonNull(tableKey, "TableKey can not be null or empty!");
257 requireNonNull(flow, "Flow can not be null or empty!");
258 if (!tableKey.getId().equals(flow.getTableId())) {
259 LOG.warn("TableID in URI tableId={} and in palyload tableId={} is not same.", flow.getTableId(),
266 private static StaleFlow makeStaleFlow(final InstanceIdentifier<Flow> identifier, final Flow del,
267 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
268 StaleFlowBuilder staleFlowBuilder = new StaleFlowBuilder(del);
269 return staleFlowBuilder.setId(del.getId()).build();
272 private void persistStaleFlow(final StaleFlow staleFlow, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
273 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
274 writeTransaction.put(LogicalDatastoreType.CONFIGURATION, getStaleFlowInstanceIdentifier(staleFlow, nodeIdent),
277 FluentFuture<?> submitFuture = writeTransaction.commit();
278 handleStaleFlowResultFuture(submitFuture);
281 private static void handleStaleFlowResultFuture(final FluentFuture<?> submitFuture) {
282 submitFuture.addCallback(new FutureCallback<Object>() {
284 public void onSuccess(final Object result) {
285 LOG.debug("Stale Flow creation success");
289 public void onFailure(final Throwable throwable) {
290 LOG.error("Stale Flow creation failed", throwable);
292 }, MoreExecutors.directExecutor());
296 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
297 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
298 final StaleFlow staleFlow, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
299 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
300 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
301 new StaleFlowKey(new FlowId(staleFlow.getId())));
304 private ListenableFuture<RpcResult<AddGroupOutput>> pushDependentGroup(
305 final InstanceIdentifier<FlowCapableNode> nodeIdent, final Uint32 groupId) {
307 //TODO This read to the DS might have a performance impact.
308 //if the dependent group is not installed than we should just cache the parent group,
309 //till we receive the dependent group DTCN and then push it.
311 InstanceIdentifier<Group> groupIdent = buildGroupInstanceIdentifier(nodeIdent, groupId);
312 ListenableFuture<RpcResult<AddGroupOutput>> resultFuture;
313 LOG.info("Reading the group from config inventory: {}", groupId);
314 try (ReadTransaction readTransaction = provider.getReadTransaction()) {
315 Optional<Group> group = readTransaction.read(LogicalDatastoreType.CONFIGURATION, groupIdent).get();
316 if (group.isPresent()) {
317 final AddGroupInputBuilder builder = new AddGroupInputBuilder(group.orElseThrow());
318 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
319 builder.setGroupRef(new GroupRef(nodeIdent));
320 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
321 AddGroupInput addGroupInput = builder.build();
322 resultFuture = provider.getSalGroupService().addGroup(addGroupInput);
324 resultFuture = RpcResultBuilder.<AddGroupOutput>failed()
325 .withError(ErrorType.APPLICATION,
326 "Group " + groupId + " not present in the config inventory").buildFuture();
328 } catch (InterruptedException | ExecutionException e) {
329 LOG.error("Error while reading group from config datastore for the group ID {}", groupId, e);
330 resultFuture = RpcResultBuilder.<AddGroupOutput>failed()
331 .withError(ErrorType.APPLICATION,
332 "Error while reading group " + groupId + " from inventory").buildFuture();
337 private final class AddFlowCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
338 private final AddFlowInput addFlowInput;
339 private final String nodeId;
340 private final Uint32 groupId;
341 private final SettableFuture<RpcResult<AddFlowOutput>> resultFuture;
343 private AddFlowCallBack(final AddFlowInput addFlowInput, final String nodeId, final Uint32 groupId,
344 final SettableFuture<RpcResult<AddFlowOutput>> resultFuture) {
345 this.addFlowInput = addFlowInput;
346 this.nodeId = nodeId;
347 this.groupId = groupId;
348 this.resultFuture = resultFuture;
352 public void onSuccess(final RpcResult<AddGroupOutput> rpcResult) {
353 if (rpcResult.isSuccessful() || rpcResult.getErrors().size() == 1
354 && rpcResult.getErrors().iterator().next().getMessage().contains(GROUP_EXISTS_IN_DEVICE_ERROR)) {
355 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
356 Futures.addCallback(provider.getSalFlowService().addFlow(addFlowInput),
357 new FutureCallback<RpcResult<AddFlowOutput>>() {
359 public void onSuccess(final RpcResult<AddFlowOutput> result) {
360 resultFuture.set(result);
364 public void onFailure(final Throwable failure) {
365 resultFuture.setException(failure);
367 }, MoreExecutors.directExecutor());
369 LOG.debug("Flow add with id {} finished without error for node {}",
370 getFlowId(addFlowInput.getFlowRef()), nodeId);
372 LOG.error("Flow add with id {} failed for node {} with error {}", getFlowId(addFlowInput.getFlowRef()),
373 nodeId, rpcResult.getErrors());
374 resultFuture.set(RpcResultBuilder.<AddFlowOutput>failed()
375 .withRpcErrors(rpcResult.getErrors()).build());
380 public void onFailure(final Throwable throwable) {
381 LOG.error("Service call for adding flow with id {} failed for node {}",
382 getFlowId(addFlowInput.getFlowRef()), nodeId, throwable);
383 resultFuture.setException(throwable);
387 private final class UpdateFlowCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
388 private final UpdateFlowInput updateFlowInput;
389 private final String nodeId;
390 private final Uint32 groupId;
391 private final SettableFuture<RpcResult<UpdateFlowOutput>> resultFuture;
393 private UpdateFlowCallBack(final UpdateFlowInput updateFlowInput, final String nodeId,
394 final SettableFuture<RpcResult<UpdateFlowOutput>> resultFuture, final Uint32 groupId) {
395 this.updateFlowInput = updateFlowInput;
396 this.nodeId = nodeId;
397 this.groupId = groupId;
398 this.resultFuture = resultFuture;
402 public void onSuccess(final RpcResult<AddGroupOutput> rpcResult) {
403 if (rpcResult.isSuccessful() || rpcResult.getErrors().size() == 1
404 && rpcResult.getErrors().iterator().next().getMessage().contains(GROUP_EXISTS_IN_DEVICE_ERROR)) {
405 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
406 Futures.addCallback(provider.getSalFlowService().updateFlow(updateFlowInput),
407 new FutureCallback<RpcResult<UpdateFlowOutput>>() {
409 public void onSuccess(final RpcResult<UpdateFlowOutput> result) {
410 resultFuture.set(result);
414 public void onFailure(final Throwable failure) {
415 resultFuture.setException(failure);
417 }, MoreExecutors.directExecutor());
419 LOG.debug("Flow update with id {} finished without error for node {}",
420 getFlowId(updateFlowInput.getFlowRef()), nodeId);
422 LOG.error("Flow update with id {} failed for node {} with error {}",
423 getFlowId(updateFlowInput.getFlowRef()), nodeId, rpcResult.getErrors());
424 resultFuture.set(RpcResultBuilder.<UpdateFlowOutput>failed()
425 .withRpcErrors(rpcResult.getErrors()).build());
430 public void onFailure(final Throwable throwable) {
431 LOG.error("Service call for updating flow with id {} failed for node {}",
432 getFlowId(updateFlowInput.getFlowRef()), nodeId, throwable);
433 resultFuture.setException(throwable);