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
9 package org.opendaylight.openflowplugin.applications.frm.impl;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.JdkFutureAdapters;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.ListIterator;
28 import java.util.concurrent.Callable;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.Future;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.TimeoutException;
35 import java.util.concurrent.atomic.AtomicLong;
36 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
37 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
38 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.openflowplugin.api.OFConstants;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
43 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
44 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddFlowCaseBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddGroupCaseBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.flow._case.AddFlowCaseDataBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.group._case.AddGroupCaseDataBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.flow._case.RemoveFlowCaseDataBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.group._case.RemoveGroupCaseDataBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
98 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
99 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
100 import org.opendaylight.yangtools.yang.common.RpcResult;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
105 * Default implementation of {@link ForwardingRulesManager}.
107 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
109 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
111 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
113 // The number of nanoseconds to wait for a single group to be added.
114 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
116 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
117 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
118 private static final String SEPARATOR = ":";
119 private static final int THREAD_POOL_SIZE = 4;
121 private final DataBroker dataBroker;
122 private final ForwardingRulesManager provider;
123 private final String serviceName;
124 private final int priority;
125 private final ResultState resultState;
126 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
128 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
130 private final SalBundleService salBundleService;
132 private static final AtomicLong BUNDLE_ID = new AtomicLong();
133 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
135 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
136 final String serviceName, final int priority, final ResultState resultState) {
137 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
138 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
139 this.serviceName = serviceName;
140 this.priority = priority;
141 this.resultState = resultState;
142 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
143 "salBundleService can not be null!");
147 public void close() {
148 if (executor != null) {
149 executor.shutdownNow();
153 private ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
154 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
155 if (provider.isStaleMarkingEnabled()) {
156 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
157 connectedNode.toString());
158 reconciliationPreProcess(connectedNode);
160 LOG.debug("Bundle based reconciliation status : {}",
161 provider.isBundleBasedReconciliationEnabled() ? "Enable" : "Disable");
162 if (provider.isBundleBasedReconciliationEnabled()) {
163 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
164 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
166 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
167 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
171 private class BundleBasedReconciliationTask implements Callable<Boolean> {
172 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
174 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
175 nodeIdentity = nodeIdent;
179 public Boolean call() {
180 String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
181 Optional<FlowCapableNode> flowNode = Optional.absent();
182 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
183 BigInteger dpnId = getDpnIdFromNodeName(node);
184 LOG.debug("Triggering bundle based reconciliation for device :{}", dpnId);
185 ReadOnlyTransaction trans = provider.getReadTranaction();
187 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
188 } catch (ExecutionException | InterruptedException e) {
189 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
192 if (flowNode.isPresent()) {
193 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
194 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
196 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
197 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
200 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
201 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
202 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
204 final AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
205 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
206 .setMessages(createMessages(nodeRef, flowNode)).build();
208 Future<RpcResult<Void>> openBundle = salBundleService.controlBundle(openBundleInput);
210 ListenableFuture<RpcResult<Void>> addBundleMessagesFuture = Futures
211 .transformAsync(JdkFutureAdapters.listenInPoolThread(openBundle), rpcResult -> {
212 if (rpcResult.isSuccessful()) {
213 return JdkFutureAdapters
214 .listenInPoolThread(salBundleService.addBundleMessages(addBundleMessagesInput));
216 return Futures.immediateFuture(null);
217 }, MoreExecutors.directExecutor());
218 ListenableFuture<RpcResult<Void>> commitBundleFuture = Futures.transformAsync(addBundleMessagesFuture,
220 if (rpcResult.isSuccessful()) {
221 return JdkFutureAdapters
222 .listenInPoolThread(salBundleService.controlBundle(commitBundleInput));
224 return Futures.immediateFuture(null);
225 }, MoreExecutors.directExecutor());
227 /* Bundles not supported for meters */
228 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
229 : Collections.emptyList();
230 Futures.transformAsync(commitBundleFuture,
232 if (rpcResult.isSuccessful()) {
233 for (Meter meter : meters) {
234 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
235 .child(Meter.class, meter.getKey());
236 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
239 return Futures.immediateFuture(null);
240 }, MoreExecutors.directExecutor());
244 if (commitBundleFuture.get().isSuccessful()) {
245 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
250 } catch (InterruptedException | ExecutionException e) {
251 LOG.error("Error while doing bundle based reconciliation for device ID:{}", nodeIdentity);
255 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
261 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
262 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
263 .augmentation(FlowCapableNode.class);
264 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
268 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
269 futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
270 futureMap.remove(node);
271 return Futures.immediateFuture(true);
275 public int getPriority() {
280 public String getName() {
285 public ResultState getResultState() {
289 private class ReconciliationTask implements Callable<Boolean> {
291 InstanceIdentifier<FlowCapableNode> nodeIdentity;
293 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
294 nodeIdentity = nodeIdent;
298 public Boolean call() {
299 String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
300 BigInteger dpnId = getDpnIdFromNodeName(node);
302 ReadOnlyTransaction trans = provider.getReadTranaction();
303 Optional<FlowCapableNode> flowNode;
304 // initialize the counter
307 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
308 } catch (ExecutionException | InterruptedException e) {
309 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
313 if (flowNode.isPresent()) {
314 /* Tables - have to be pushed before groups */
315 // CHECK if while pushing the update, updateTableInput can be null to emulate a
317 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
318 ? flowNode.get().getTableFeatures()
319 : Collections.<TableFeatures>emptyList();
320 for (TableFeatures tableFeaturesItem : tableList) {
321 TableFeaturesKey tableKey = tableFeaturesItem.getKey();
322 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
323 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
324 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
327 /* Groups - have to be first */
328 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
329 : Collections.<Group>emptyList();
330 List<Group> toBeInstalledGroups = new ArrayList<>();
331 toBeInstalledGroups.addAll(groups);
332 // new list for suspected groups pointing to ports .. when the ports come up
334 List<Group> suspectedGroups = new ArrayList<>();
335 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
337 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
338 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
339 // crossed the threshold
341 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
342 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
343 suspectedGroups.toString());
344 toBeInstalledGroups.addAll(suspectedGroups);
348 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
349 while (iterator.hasNext()) {
350 Group group = iterator.next();
351 boolean okToInstall = true;
352 Buckets buckets = group.getBuckets();
353 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
354 if (bucketList == null) {
355 bucketList = Collections.<Bucket>emptyList();
357 for (Bucket bucket : bucketList) {
358 List<Action> actions = bucket.getAction();
359 if (actions == null) {
360 actions = Collections.<Action>emptyList();
362 for (Action action : actions) {
364 if (action.getAction().getImplementedInterface().getName()
365 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
366 + ".action.types.rev131112.action.action.OutputActionCase")) {
367 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
368 .getOutputNodeConnector().getValue();
370 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
372 // check if the nodeconnector is there in the multimap
373 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
374 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
375 // if yes set okToInstall = true
380 // else put it in a different list and still set okToInstall = true
381 suspectedGroups.add(group);
383 "Not yet received the node-connector updated for {} "
384 + "for the group with id {}",
385 nodeConnectorUri, group.getGroupId().toString());
388 } else if (action.getAction().getImplementedInterface().getName()
389 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
390 + ".action.types.rev131112.action.action.GroupActionCase")) {
392 Long groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
393 ListenableFuture<?> future = groupFutures.get(groupId);
394 if (future == null) {
398 // Need to ensure that the group specified
399 // by group-action is already installed.
400 awaitGroup(node, future);
404 // increment retry counter value
410 addGroup(groupFutures, group);
412 // resetting the counter to zero
418 /* installation of suspected groups */
419 if (!toBeInstalledGroups.isEmpty()) {
420 for (Group group : toBeInstalledGroups) {
422 "Installing the group {} finally although "
423 + "the port is not up after checking for {} times ",
424 group.getGroupId().toString(), provider.getReconciliationRetryCount());
425 addGroup(groupFutures, group);
429 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
430 : Collections.<Meter>emptyList();
431 for (Meter meter : meters) {
432 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
434 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
437 // Need to wait for all groups to be installed before adding
439 awaitGroups(node, groupFutures.values());
442 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
443 : Collections.<Table>emptyList();
444 for (Table table : tables) {
445 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
447 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
448 for (Flow flow : flows) {
449 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
451 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
455 /* clean transaction */
461 * Invoke add-group RPC, and put listenable future associated with the RPC into
465 * The map to store listenable futures associated with add-group RPC.
469 private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
470 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.getKey());
471 final Long groupId = group.getGroupId().getValue();
472 ListenableFuture<?> future = JdkFutureAdapters
473 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
475 Futures.addCallback(future, new FutureCallback<Object>() {
477 public void onSuccess(Object result) {
478 if (LOG.isTraceEnabled()) {
479 LOG.trace("add-group RPC completed: node={}, id={}",
480 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
485 public void onFailure(Throwable cause) {
486 String msg = "add-group RPC failed: node=" + nodeIdentity.firstKeyOf(Node.class).getId().getValue()
488 LOG.debug(msg, cause);
490 }, MoreExecutors.directExecutor());
492 map.put(groupId, future);
496 * Wait for completion of add-group RPC.
499 * The identifier for the target node.
501 * Future associated with add-group RPC that installs the target
504 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
505 awaitGroups(nodeId, Collections.singleton(future));
509 * Wait for completion of add-group RPCs.
512 * The identifier for the target node.
514 * A collection of futures associated with add-group RPCs.
516 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
517 if (!futures.isEmpty()) {
518 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
520 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
521 LOG.trace("awaitGroups() completed: node={}", nodeId);
522 } catch (TimeoutException | InterruptedException | ExecutionException e) {
523 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
529 private BigInteger getDpnIdFromNodeName(String nodeName) {
531 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
532 return new BigInteger(dpId);
535 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
536 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
537 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
538 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
540 ReadOnlyTransaction trans = provider.getReadTranaction();
541 Optional<FlowCapableNode> flowNode = Optional.absent();
544 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
545 } catch (ExecutionException | InterruptedException e) {
546 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
549 if (flowNode.isPresent()) {
551 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
552 nodeIdent.toString());
553 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
554 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
555 : Collections.<Table>emptyList();
556 for (Table table : tables) {
557 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
559 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
560 : Collections.<StaleFlow>emptyList();
561 for (StaleFlow staleFlow : staleFlows) {
563 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
564 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
566 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
567 toBeDeletedFlow.getKey());
569 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
571 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
575 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
576 nodeIdent.toString());
578 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
579 // Flows are fully deleted
580 // before attempting to delete groups - just in case there are references
582 /* Stale-marked Groups - Can be deleted after flows */
583 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
584 : Collections.<StaleGroup>emptyList();
585 for (StaleGroup staleGroup : staleGroups) {
587 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
588 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
590 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
591 toBeDeletedGroup.getKey());
593 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
595 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
598 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
599 nodeIdent.toString());
600 /* Stale-marked Meters - can be deleted anytime - so least priority */
601 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
602 : Collections.<StaleMeter>emptyList();
604 for (StaleMeter staleMeter : staleMeters) {
606 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
607 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
609 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
610 toBeDeletedMeter.getKey());
612 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
614 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
618 /* clean transaction */
621 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
622 nodeIdent.toString());
623 // Now, do the bulk deletions
624 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
625 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
626 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
629 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
630 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
632 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
633 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
636 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
637 handleStaleEntityDeletionResultFuture(submitFuture);
640 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
641 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
643 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
644 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
647 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
648 handleStaleEntityDeletionResultFuture(submitFuture);
651 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
652 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
654 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
655 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
658 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
659 handleStaleEntityDeletionResultFuture(submitFuture);
662 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
663 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
664 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
665 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
666 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
667 new StaleFlowKey(new FlowId(staleFlow.getId())));
670 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
671 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
672 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
673 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
676 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
677 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
678 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
679 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
682 private void handleStaleEntityDeletionResultFuture(
683 CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
684 Futures.addCallback(submitFuture, new FutureCallback<Void>() {
686 public void onSuccess(Void result) {
687 LOG.debug("Stale entity removal success");
691 public void onFailure(Throwable throwable) {
692 LOG.debug("Stale entity removal failed {}", throwable);
694 }, MoreExecutors.directExecutor());
697 private Flow getDeleteAllFlow() {
698 final FlowBuilder flowBuilder = new FlowBuilder();
699 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
700 return flowBuilder.build();
703 private Group getDeleteAllGroup() {
704 final GroupBuilder groupBuilder = new GroupBuilder();
705 groupBuilder.setGroupType(GroupTypes.GroupAll);
706 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
707 return groupBuilder.build();
710 private Messages createMessages(final NodeRef nodeRef, final Optional<FlowCapableNode> flowNode) {
711 final List<Message> messages = new ArrayList<>();
712 messages.add(new MessageBuilder().setNode(nodeRef)
713 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
714 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
717 messages.add(new MessageBuilder().setNode(nodeRef)
718 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
719 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
722 if (flowNode.get().getGroup() != null) {
723 for (Group gr : flowNode.get().getGroup()) {
724 messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddGroupCaseBuilder()
725 .setAddGroupCaseData(new AddGroupCaseDataBuilder(gr).build()).build()).build());
729 if (flowNode.get().getTable() != null) {
730 for (Table table : flowNode.get().getTable()) {
731 for (Flow flow : table.getFlow()) {
733 new MessageBuilder().setNode(nodeRef)
734 .setBundleInnerMessage(new BundleAddFlowCaseBuilder()
735 .setAddFlowCaseData(new AddFlowCaseDataBuilder(flow).build()).build())
741 LOG.debug("The size of the flows and group messages created in createMessage() {}", messages.size());
742 return new MessagesBuilder().setMessage(messages).build();