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 org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.buildGroupInstanceIdentifier;
11 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getActiveBundle;
12 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getFlowId;
13 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getNodeIdFromNodeIdentifier;
14 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.isFlowDependentOnGroup;
15 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.isGroupExistsOnDevice;
17 import com.google.common.base.Preconditions;
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.JdkFutures;
28 import org.opendaylight.mdsal.binding.api.DataBroker;
29 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
30 import org.opendaylight.mdsal.binding.api.ReadTransaction;
31 import org.opendaylight.mdsal.binding.api.WriteTransaction;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowTableRef;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInputBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlowBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlowBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupRef;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
65 import org.opendaylight.yangtools.concepts.ListenerRegistration;
66 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
67 import org.opendaylight.yangtools.yang.common.RpcError;
68 import org.opendaylight.yangtools.yang.common.RpcResult;
69 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
74 * FlowForwarder It implements
75 * {@link org.opendaylight.mdsal.binding.api.DataTreeChangeListener}
76 * for WildCardedPath to {@link Flow} and ForwardingRulesCommiter interface for
77 * methods: add, update and remove {@link Flow} processing for
78 * {@link org.opendaylight.mdsal.binding.api.DataTreeModification}.
80 public class FlowForwarder extends AbstractListeningCommiter<Flow> {
82 private static final Logger LOG = LoggerFactory.getLogger(FlowForwarder.class);
84 private static final String GROUP_EXISTS_IN_DEVICE_ERROR = "GROUPEXISTS";
86 private ListenerRegistration<FlowForwarder> listenerRegistration;
87 private final BundleFlowForwarder bundleFlowForwarder;
89 public FlowForwarder(final ForwardingRulesManager manager, final DataBroker db) {
91 bundleFlowForwarder = new BundleFlowForwarder(manager);
95 @SuppressWarnings("IllegalCatch")
96 public void registerListener() {
97 final DataTreeIdentifier<Flow> treeId = DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION,
100 listenerRegistration = dataBroker.registerDataTreeChangeListener(treeId, FlowForwarder.this);
101 } catch (final Exception e) {
102 LOG.warn("FRM Flow DataTreeChange listener registration fail!");
103 LOG.debug("FRM Flow DataTreeChange listener registration fail ..", e);
104 throw new IllegalStateException("FlowForwarder startup fail! System needs restart.", e);
110 public void deregisterListener() {
115 public void close() {
116 if (listenerRegistration != null) {
117 listenerRegistration.close();
118 listenerRegistration = null;
123 public void remove(final InstanceIdentifier<Flow> identifier, final Flow removeDataObj,
124 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
126 final TableKey tableKey = identifier.firstKeyOf(Table.class);
127 if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
128 BundleId bundleId = getActiveBundle(nodeIdent, provider);
129 if (bundleId != null) {
130 bundleFlowForwarder.remove(identifier, removeDataObj, nodeIdent, bundleId);
132 final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
133 builder.setFlowRef(new FlowRef(identifier));
134 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
135 builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
137 // This method is called only when a given flow object has been
138 // removed from datastore. So FRM always needs to set strict flag
139 // into remove-flow input so that only a flow entry associated with
140 // a given flow object is removed.
141 builder.setTransactionUri(new Uri(provider.getNewTransactionId())).setStrict(Boolean.TRUE);
142 final Future<RpcResult<RemoveFlowOutput>> resultFuture =
143 provider.getSalFlowService().removeFlow(builder.build());
144 JdkFutures.addErrorLogging(resultFuture, LOG, "removeFlow");
149 // TODO: Pull this into ForwardingRulesCommiter and override it here
152 public Future<RpcResult<RemoveFlowOutput>> removeWithResult(final InstanceIdentifier<Flow> identifier,
153 final Flow removeDataObj, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
155 Future<RpcResult<RemoveFlowOutput>> resultFuture = SettableFuture.create();
156 final TableKey tableKey = identifier.firstKeyOf(Table.class);
157 if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
158 final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
159 builder.setFlowRef(new FlowRef(identifier));
160 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
161 builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
163 // This method is called only when a given flow object has been
164 // removed from datastore. So FRM always needs to set strict flag
165 // into remove-flow input so that only a flow entry associated with
166 // a given flow object is removed.
167 builder.setTransactionUri(new Uri(provider.getNewTransactionId())).setStrict(Boolean.TRUE);
168 resultFuture = provider.getSalFlowService().removeFlow(builder.build());
175 public void update(final InstanceIdentifier<Flow> identifier, final Flow original, final Flow update,
176 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
178 final TableKey tableKey = identifier.firstKeyOf(Table.class);
179 if (tableIdValidationPrecondition(tableKey, update)) {
180 BundleId bundleId = getActiveBundle(nodeIdent, provider);
181 if (bundleId != null) {
182 bundleFlowForwarder.update(identifier, original, update, nodeIdent, bundleId);
184 final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
185 nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
186 final UpdateFlowInputBuilder builder = new UpdateFlowInputBuilder();
187 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
188 builder.setFlowRef(new FlowRef(identifier));
189 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
191 // This method is called only when a given flow object in datastore
192 // has been updated. So FRM always needs to set strict flag into
193 // update-flow input so that only a flow entry associated with
194 // a given flow object is updated.
195 builder.setUpdatedFlow(new UpdatedFlowBuilder(update).setStrict(Boolean.TRUE).build());
196 builder.setOriginalFlow(new OriginalFlowBuilder(original).setStrict(Boolean.TRUE).build());
198 Long groupId = isFlowDependentOnGroup(update);
199 if (groupId != null) {
200 LOG.trace("The flow {} is dependent on group {}. Checking if the group is already present",
201 getFlowId(new FlowRef(identifier)), groupId);
202 if (isGroupExistsOnDevice(nodeIdent, groupId, provider)) {
203 LOG.trace("The dependent group {} is already programmed. Updating the flow {}", groupId,
204 getFlowId(new FlowRef(identifier)));
205 return provider.getSalFlowService().updateFlow(builder.build());
207 LOG.trace("The dependent group {} isn't programmed yet. Pushing the group", groupId);
208 ListenableFuture<RpcResult<AddGroupOutput>> groupFuture = pushDependentGroup(nodeIdent,
210 SettableFuture<RpcResult<UpdateFlowOutput>> resultFuture = SettableFuture.create();
211 Futures.addCallback(groupFuture,
212 new UpdateFlowCallBack(builder.build(), nodeId, resultFuture, groupId),
213 MoreExecutors.directExecutor());
218 LOG.trace("The flow {} is not dependent on any group. Updating the flow",
219 getFlowId(new FlowRef(identifier)));
220 return provider.getSalFlowService().updateFlow(builder.build());
227 public Future<? extends RpcResult<?>> add(final InstanceIdentifier<Flow> identifier, final Flow addDataObj,
228 final InstanceIdentifier<FlowCapableNode> nodeIdent) {
230 final TableKey tableKey = identifier.firstKeyOf(Table.class);
231 if (tableIdValidationPrecondition(tableKey, addDataObj)) {
232 BundleId bundleId = getActiveBundle(nodeIdent, provider);
233 if (bundleId != null) {
234 return bundleFlowForwarder.add(identifier, addDataObj, nodeIdent, bundleId);
236 final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
237 nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
238 final AddFlowInputBuilder builder = new AddFlowInputBuilder(addDataObj);
240 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
241 builder.setFlowRef(new FlowRef(identifier));
242 builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
243 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
244 Long groupId = isFlowDependentOnGroup(addDataObj);
245 if (groupId != null) {
246 LOG.trace("The flow {} is dependent on group {}. Checking if the group is already present",
247 getFlowId(new FlowRef(identifier)), groupId);
248 if (isGroupExistsOnDevice(nodeIdent, groupId, provider)) {
249 LOG.trace("The dependent group {} is already programmed. Adding the flow {}", groupId,
250 getFlowId(new FlowRef(identifier)));
251 return provider.getSalFlowService().addFlow(builder.build());
253 LOG.trace("The dependent group {} isn't programmed yet. Pushing the group", groupId);
254 ListenableFuture<RpcResult<AddGroupOutput>> groupFuture = pushDependentGroup(nodeIdent,
256 SettableFuture<RpcResult<AddFlowOutput>> resultFuture = SettableFuture.create();
257 Futures.addCallback(groupFuture, new AddFlowCallBack(builder.build(), nodeId, groupId,
258 resultFuture), MoreExecutors.directExecutor());
263 LOG.trace("The flow {} is not dependent on any group. Adding the flow",
264 getFlowId(new FlowRef(identifier)));
265 return provider.getSalFlowService().addFlow(builder.build());
269 return Futures.immediateFuture(null);
273 public void createStaleMarkEntity(InstanceIdentifier<Flow> identifier, Flow del,
274 InstanceIdentifier<FlowCapableNode> nodeIdent) {
275 LOG.debug("Creating Stale-Mark entry for the switch {} for flow {} ", nodeIdent.toString(), del.toString());
276 StaleFlow staleFlow = makeStaleFlow(identifier, del, nodeIdent);
277 persistStaleFlow(staleFlow, nodeIdent);
281 protected InstanceIdentifier<Flow> getWildCardPath() {
282 return InstanceIdentifier.create(Nodes.class).child(Node.class).augmentation(FlowCapableNode.class)
283 .child(Table.class).child(Flow.class);
286 private static boolean tableIdValidationPrecondition(final TableKey tableKey, final Flow flow) {
287 Preconditions.checkNotNull(tableKey, "TableKey can not be null or empty!");
288 Preconditions.checkNotNull(flow, "Flow can not be null or empty!");
289 if (!tableKey.getId().equals(flow.getTableId())) {
290 LOG.warn("TableID in URI tableId={} and in palyload tableId={} is not same.", flow.getTableId(),
297 private StaleFlow makeStaleFlow(InstanceIdentifier<Flow> identifier, Flow del,
298 InstanceIdentifier<FlowCapableNode> nodeIdent) {
299 StaleFlowBuilder staleFlowBuilder = new StaleFlowBuilder(del);
300 return staleFlowBuilder.setId(del.getId()).build();
303 private void persistStaleFlow(StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
304 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
305 writeTransaction.put(LogicalDatastoreType.CONFIGURATION, getStaleFlowInstanceIdentifier(staleFlow, nodeIdent),
308 FluentFuture<?> submitFuture = writeTransaction.commit();
309 handleStaleFlowResultFuture(submitFuture);
312 private void handleStaleFlowResultFuture(FluentFuture<?> submitFuture) {
313 submitFuture.addCallback(new FutureCallback<Object>() {
315 public void onSuccess(Object result) {
316 LOG.debug("Stale Flow creation success");
320 public void onFailure(Throwable throwable) {
321 LOG.error("Stale Flow creation failed {}", throwable);
323 }, MoreExecutors.directExecutor());
327 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
328 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
329 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
330 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
331 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
332 new StaleFlowKey(new FlowId(staleFlow.getId())));
335 private ListenableFuture<RpcResult<AddGroupOutput>> pushDependentGroup(
336 final InstanceIdentifier<FlowCapableNode> nodeIdent, final Long groupId) {
338 //TODO This read to the DS might have a performance impact.
339 //if the dependent group is not installed than we should just cache the parent group,
340 //till we receive the dependent group DTCN and then push it.
342 InstanceIdentifier<Group> groupIdent = buildGroupInstanceIdentifier(nodeIdent, groupId);
343 ListenableFuture<RpcResult<AddGroupOutput>> resultFuture;
344 LOG.info("Reading the group from config inventory: {}", groupId);
345 try (ReadTransaction readTransaction = provider.getReadTransaction()) {
346 Optional<Group> group = readTransaction.read(LogicalDatastoreType.CONFIGURATION, groupIdent).get();
347 if (group.isPresent()) {
348 final AddGroupInputBuilder builder = new AddGroupInputBuilder(group.get());
349 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
350 builder.setGroupRef(new GroupRef(nodeIdent));
351 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
352 AddGroupInput addGroupInput = builder.build();
353 resultFuture = this.provider.getSalGroupService().addGroup(addGroupInput);
355 resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddGroupOutput>failed()
356 .withError(RpcError.ErrorType.APPLICATION,
357 "Group " + groupId + " not present in the config inventory").build());
359 } catch (InterruptedException | ExecutionException e) {
360 LOG.error("Error while reading group from config datastore for the group ID {}", groupId, e);
361 resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddGroupOutput>failed()
362 .withError(RpcError.ErrorType.APPLICATION,
363 "Error while reading group " + groupId + " from inventory").build());
368 private final class AddFlowCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
369 private final AddFlowInput addFlowInput;
370 private final NodeId nodeId;
371 private final Long groupId;
372 private final SettableFuture<RpcResult<AddFlowOutput>> resultFuture;
374 private AddFlowCallBack(final AddFlowInput addFlowInput, final NodeId nodeId, Long groupId,
375 SettableFuture<RpcResult<AddFlowOutput>> resultFuture) {
376 this.addFlowInput = addFlowInput;
377 this.nodeId = nodeId;
378 this.groupId = groupId;
379 this.resultFuture = resultFuture;
383 public void onSuccess(RpcResult<AddGroupOutput> rpcResult) {
384 if (rpcResult.isSuccessful() || rpcResult.getErrors().size() == 1
385 && rpcResult.getErrors().iterator().next().getMessage().contains(GROUP_EXISTS_IN_DEVICE_ERROR)) {
386 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
387 Futures.addCallback(provider.getSalFlowService().addFlow(addFlowInput),
388 new FutureCallback<RpcResult<AddFlowOutput>>() {
390 public void onSuccess(RpcResult<AddFlowOutput> result) {
391 resultFuture.set(result);
395 public void onFailure(Throwable failure) {
396 resultFuture.setException(failure);
398 }, MoreExecutors.directExecutor());
400 LOG.debug("Flow add with id {} finished without error for node {}",
401 getFlowId(addFlowInput.getFlowRef()), nodeId);
403 LOG.error("Flow add with id {} failed for node {} with error {}", getFlowId(addFlowInput.getFlowRef()),
404 nodeId, rpcResult.getErrors().toString());
405 resultFuture.set(RpcResultBuilder.<AddFlowOutput>failed()
406 .withRpcErrors(rpcResult.getErrors()).build());
411 public void onFailure(Throwable throwable) {
412 LOG.error("Service call for adding flow with id {} failed for node {}",
413 getFlowId(addFlowInput.getFlowRef()), nodeId, throwable);
414 resultFuture.setException(throwable);
418 private final class UpdateFlowCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
419 private final UpdateFlowInput updateFlowInput;
420 private final NodeId nodeId;
421 private final Long groupId;
422 private final SettableFuture<RpcResult<UpdateFlowOutput>> resultFuture;
424 private UpdateFlowCallBack(final UpdateFlowInput updateFlowInput, final NodeId nodeId,
425 SettableFuture<RpcResult<UpdateFlowOutput>> resultFuture, Long groupId) {
426 this.updateFlowInput = updateFlowInput;
427 this.nodeId = nodeId;
428 this.groupId = groupId;
429 this.resultFuture = resultFuture;
433 public void onSuccess(RpcResult<AddGroupOutput> rpcResult) {
434 if (rpcResult.isSuccessful() || rpcResult.getErrors().size() == 1
435 && rpcResult.getErrors().iterator().next().getMessage().contains(GROUP_EXISTS_IN_DEVICE_ERROR)) {
436 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
437 Futures.addCallback(provider.getSalFlowService().updateFlow(updateFlowInput),
438 new FutureCallback<RpcResult<UpdateFlowOutput>>() {
440 public void onSuccess(RpcResult<UpdateFlowOutput> result) {
441 resultFuture.set(result);
445 public void onFailure(Throwable failure) {
446 resultFuture.setException(failure);
448 }, MoreExecutors.directExecutor());
450 LOG.debug("Flow update with id {} finished without error for node {}",
451 getFlowId(updateFlowInput.getFlowRef()), nodeId);
453 LOG.error("Flow update with id {} failed for node {} with error {}",
454 getFlowId(updateFlowInput.getFlowRef()), nodeId, rpcResult.getErrors().toString());
455 resultFuture.set(RpcResultBuilder.<UpdateFlowOutput>failed()
456 .withRpcErrors(rpcResult.getErrors()).build());
461 public void onFailure(Throwable throwable) {
462 LOG.error("Service call for updating flow with id {} failed for node {}",
463 getFlowId(updateFlowInput.getFlowRef()), nodeId, throwable);
464 resultFuture.setException(throwable);