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.api.openflow.ReconciliationState.ReconciliationStatus.COMPLETED;
12 import static org.opendaylight.openflowplugin.api.openflow.ReconciliationState.ReconciliationStatus.FAILED;
13 import static org.opendaylight.openflowplugin.api.openflow.ReconciliationState.ReconciliationStatus.STARTED;
15 import com.google.common.util.concurrent.FluentFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import com.google.common.util.concurrent.ThreadFactoryBuilder;
21 import java.math.BigInteger;
22 import java.time.LocalDateTime;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.ListIterator;
30 import java.util.Optional;
31 import java.util.concurrent.Callable;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentMap;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.ThreadFactory;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.TimeoutException;
40 import java.util.concurrent.atomic.AtomicLong;
41 import org.opendaylight.mdsal.binding.api.DataBroker;
42 import org.opendaylight.mdsal.binding.api.ReadTransaction;
43 import org.opendaylight.mdsal.common.api.CommitInfo;
44 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
45 import org.opendaylight.openflowplugin.api.OFConstants;
46 import org.opendaylight.openflowplugin.api.openflow.FlowGroupCacheManager;
47 import org.opendaylight.openflowplugin.api.openflow.ReconciliationState;
48 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
49 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
50 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
51 import org.opendaylight.openflowplugin.applications.frm.util.FrmUtil;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
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.opendaylight.yangtools.yang.common.Uint32;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
106 * Default implementation of {@link ForwardingRulesManager}.
108 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
110 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
111 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
112 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
114 private static final String SEPARATOR = ":";
115 private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
116 .setNameFormat("BundleResync-%d")
118 .setUncaughtExceptionHandler((thread, ex) -> LOG.error("Uncaught exception {}", thread, ex))
121 // FIXME: these three should be configurable
122 private static final int THREAD_POOL_SIZE = 4;
123 // The number of nanoseconds to wait for a single group to be added.
124 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
125 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
126 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
128 private final ConcurrentMap<DeviceInfo, ListenableFuture<Boolean>> futureMap = new ConcurrentHashMap<>();
129 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
130 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
131 private static final AtomicLong BUNDLE_ID = new AtomicLong();
132 private final Map<String, ReconciliationState> reconciliationStates;
133 private final DataBroker dataBroker;
134 private final ForwardingRulesManager provider;
135 private final String serviceName;
136 private final int priority;
137 private final ResultState resultState;
139 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
140 final String serviceName, final int priority, final ResultState resultState,
141 final FlowGroupCacheManager flowGroupCacheManager) {
142 provider = requireNonNull(manager, "ForwardingRulesManager can not be null!");
143 dataBroker = requireNonNull(db, "DataBroker can not be null!");
144 this.serviceName = serviceName;
145 this.priority = priority;
146 this.resultState = resultState;
147 reconciliationStates = flowGroupCacheManager.getReconciliationStates();
151 public void close() {
152 if (executor != null) {
153 executor.shutdownNow();
158 public ListenableFuture<Boolean> reconcileConfiguration(final InstanceIdentifier<FlowCapableNode> connectedNode) {
159 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
160 // Clearing the group registry cache for the connected node if exists
161 String nodeId = FrmUtil.getNodeIdValueFromNodeIdentifier(connectedNode);
162 provider.getDevicesGroupRegistry().clearNodeGroups(nodeId);
163 if (provider.isStaleMarkingEnabled()) {
164 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
166 reconciliationPreProcess(connectedNode);
169 return Futures.submit(provider.isBundleBasedReconciliationEnabled()
170 ? new BundleBasedReconciliationTask(connectedNode) : new ReconciliationTask(connectedNode), executor);
174 public void flowNodeDisconnected(final InstanceIdentifier<FlowCapableNode> disconnectedNode) {
175 final var node = disconnectedNode.firstKeyOf(Node.class).getId().getValue();
176 // FIXME: BigInteger.toString() called here
177 final var dpnId = getDpnIdFromNodeName(node);
178 reconciliationStates.remove(dpnId.toString());
181 private class BundleBasedReconciliationTask implements Callable<Boolean> {
182 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
184 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
185 nodeIdentity = nodeIdent;
189 public Boolean call() {
190 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
191 Optional<FlowCapableNode> flowNode = Optional.empty();
192 BundleId bundleIdValue = new BundleId(Uint32.valueOf(BUNDLE_ID.getAndIncrement()));
193 BigInteger dpnId = getDpnIdFromNodeName(node);
194 ExecutorService service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
195 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
196 try (ReadTransaction trans = provider.getReadTransaction()) {
197 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
198 } catch (ExecutionException | InterruptedException e) {
199 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
202 if (flowNode.isPresent()) {
203 final var reconciliationState = new ReconciliationState(STARTED, LocalDateTime.now());
204 //put the dpn info into the map
205 reconciliationStates.put(dpnId.toString(), reconciliationState);
206 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
207 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
208 final var nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
210 final var closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
211 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
212 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
214 final var openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
215 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
216 .setType(BundleControlType.ONFBCTOPENREQUEST).build();
218 final var commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
219 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
220 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
222 final var deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
223 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
224 .setMessages(createMessages(nodeRef)).build();
226 LOG.debug("Closing openflow bundle for device {}", dpnId);
227 /* Close previously opened bundle on the openflow switch if any */
228 final var closeBundle = provider.controlBundle().invoke(closeBundleInput);
230 /* Open a new bundle on the switch */
231 final var openBundle = Futures.transformAsync(closeBundle, rpcResult -> {
232 if (rpcResult.isSuccessful()) {
233 LOG.debug("Existing bundle is successfully closed for device {}", dpnId);
235 return provider.controlBundle().invoke(openBundleInput);
238 /* Push groups and flows via bundle add messages */
239 final var deleteAllFlowGroupsFuture = Futures.transformAsync(openBundle, rpcResult -> {
240 if (rpcResult.isSuccessful()) {
241 LOG.debug("Open bundle is successful for device {}", dpnId);
242 return provider.addBundleMessages().invoke(deleteAllFlowGroupsInput);
244 return Futures.immediateFuture(null);
247 /* Push flows and groups via bundle add messages */
248 final var finalFlowNode = flowNode;
249 final var addbundlesFuture = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
250 if (rpcResult.isSuccessful()) {
251 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
252 return Futures.allAsList(addBundleMessages(finalFlowNode.orElseThrow(), bundleIdValue,
255 return Futures.immediateFuture(null);
258 /* Commit the bundle on the openflow switch */
259 final var commitBundleFuture = Futures.transformAsync(addbundlesFuture, rpcResult -> {
260 LOG.debug("Adding bundle messages completed for device {}", dpnId);
261 return provider.controlBundle().invoke(commitBundleInput);
264 /* Bundles not supported for meters */
265 final var meters = finalFlowNode.orElseThrow().nonnullMeter().values();
266 Futures.transformAsync(commitBundleFuture,
268 if (rpcResult.isSuccessful()) {
269 for (var meter : meters) {
270 provider.getMeterCommiter().add(nodeIdentity.child(Meter.class, meter.key()), meter,
274 return Futures.immediateFuture(null);
278 final var bundleFuture = commitBundleFuture.get();
279 if (bundleFuture != null && bundleFuture.isSuccessful()) {
280 reconciliationState.setState(COMPLETED, LocalDateTime.now());
281 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
282 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
285 reconciliationState.setState(FAILED, LocalDateTime.now());
286 LOG.error("commit bundle failed for device {} with error {}", dpnId,
287 commitBundleFuture.get().getErrors());
290 } catch (InterruptedException | ExecutionException e) {
291 reconciliationState.setState(FAILED, LocalDateTime.now());
292 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId, e);
298 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
304 public ListenableFuture<Boolean> startReconciliation(final DeviceInfo node) {
305 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
306 .augmentation(FlowCapableNode.class);
307 // Clearing the group registry cache for the connected node if exists
308 provider.getDevicesGroupRegistry().clearNodeGroups(node.toString());
309 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
313 public ListenableFuture<Boolean> endReconciliation(final DeviceInfo node) {
314 ListenableFuture<Boolean> listenableFuture = futureMap.computeIfPresent(node, (key, future) -> future);
315 if (listenableFuture != null) {
316 listenableFuture.cancel(true);
317 futureMap.remove(node);
319 return Futures.immediateFuture(true);
323 public int getPriority() {
328 public String getName() {
333 public ResultState getResultState() {
337 private class ReconciliationTask implements Callable<Boolean> {
339 InstanceIdentifier<FlowCapableNode> nodeIdentity;
341 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
342 nodeIdentity = nodeIdent;
346 public Boolean call() {
347 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
348 BigInteger dpnId = getDpnIdFromNodeName(node);
349 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
351 Optional<FlowCapableNode> optFlowNode;
352 // initialize the counter
354 try (ReadTransaction trans = provider.getReadTransaction()) {
355 optFlowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
356 } catch (ExecutionException | InterruptedException e) {
357 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
361 if (optFlowNode.isPresent()) {
362 /* Tables - have to be pushed before groups */
363 // CHECK if while pushing the update, updateTableInput can be null to emulate a
365 ReconciliationState reconciliationState = new ReconciliationState(STARTED, LocalDateTime.now());
366 //put the dpn info into the map
367 reconciliationStates.put(dpnId.toString(), reconciliationState);
368 LOG.debug("Triggering reconciliation for node {} with state: {}", dpnId, STARTED);
369 FlowCapableNode flowNode = optFlowNode.orElseThrow();
370 Collection<TableFeatures> tableList = flowNode.nonnullTableFeatures().values();
371 for (TableFeatures tableFeaturesItem : tableList) {
372 TableFeaturesKey tableKey = tableFeaturesItem.key();
373 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
374 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
375 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
378 /* Groups - have to be first */
379 List<Group> toBeInstalledGroups = new ArrayList<>(flowNode.nonnullGroup().values());
380 // new list for suspected groups pointing to ports .. when the ports come up
382 List<Group> suspectedGroups = new ArrayList<>();
383 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
385 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
386 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
387 // crossed the threshold
389 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
390 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
392 toBeInstalledGroups.addAll(suspectedGroups);
396 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
397 while (iterator.hasNext()) {
398 Group group = iterator.next();
399 boolean okToInstall = true;
400 Buckets buckets = group.getBuckets();
401 Collection<Bucket> bucketList = buckets == null ? null : buckets.nonnullBucket().values();
402 if (bucketList == null) {
403 bucketList = Collections.<Bucket>emptyList();
405 for (Bucket bucket : bucketList) {
406 Collection<Action> actions = bucket.nonnullAction().values();
407 if (actions == null) {
408 actions = Collections.<Action>emptyList();
410 for (Action action : actions) {
412 if (action.getAction().implementedInterface().getName()
413 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
414 + ".action.types.rev131112.action.action.OutputActionCase")) {
415 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
416 .getOutputNodeConnector().getValue();
418 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
420 // check if the nodeconnector is there in the multimap
421 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
422 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
423 // if yes set okToInstall = true
428 // else put it in a different list and still set okToInstall = true
429 suspectedGroups.add(group);
431 "Not yet received the node-connector updated for {} "
432 + "for the group with id {}",
433 nodeConnectorUri, group.getGroupId());
436 } else if (action.getAction().implementedInterface().getName()
437 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
438 + ".action.types.rev131112.action.action.GroupActionCase")) {
440 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
442 ListenableFuture<?> future = groupFutures.get(groupId);
443 if (future == null) {
447 // Need to ensure that the group specified
448 // by group-action is already installed.
449 awaitGroup(node, future);
453 // increment retry counter value
459 addGroup(groupFutures, group);
461 // resetting the counter to zero
467 /* installation of suspected groups */
468 if (!toBeInstalledGroups.isEmpty()) {
469 for (Group group : toBeInstalledGroups) {
471 "Installing the group {} finally although the port is not up after checking for {} times ",
472 group.getGroupId(), provider.getReconciliationRetryCount());
473 addGroup(groupFutures, group);
477 Collection<Meter> meters = flowNode.nonnullMeter().values();
478 for (Meter meter : meters) {
479 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
481 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
484 // Need to wait for all groups to be installed before adding
486 awaitGroups(node, groupFutures.values());
490 for (Table table : flowNode.nonnullTable().values()) {
491 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
493 Collection<Flow> flows = table.nonnullFlow().values();
494 flowCount += flows.size();
495 for (Flow flow : flows) {
496 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
498 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
501 reconciliationState.setState(COMPLETED, LocalDateTime.now());
502 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
508 * Invoke add-group RPC, and put listenable future associated with the RPC into
512 * The map to store listenable futures associated with add-group RPC.
516 private void addGroup(final Map<Uint32, ListenableFuture<?>> map, final Group group) {
517 final var groupIdent = nodeIdentity.child(Group.class, group.key());
518 final var groupId = group.getGroupId().getValue();
519 final var future = provider.getGroupCommiter().add(groupIdent, group, nodeIdentity);
521 Futures.addCallback(future, new FutureCallback<RpcResult<?>>() {
523 public void onSuccess(final RpcResult<?> result) {
524 if (LOG.isTraceEnabled()) {
525 LOG.trace("add-group RPC completed: node={}, id={}",
526 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
531 public void onFailure(final Throwable cause) {
532 LOG.debug("add-group RPC failed: node={}, id={}",
533 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
535 }, MoreExecutors.directExecutor());
537 map.put(groupId, future);
541 * Wait for completion of add-group RPC.
544 * The identifier for the target node.
546 * Future associated with add-group RPC that installs the target
549 private void awaitGroup(final String nodeId, final ListenableFuture<?> future) {
550 awaitGroups(nodeId, Collections.singleton(future));
554 * Wait for completion of add-group RPCs.
557 * The identifier for the target node.
559 * A collection of futures associated with add-group RPCs.
561 private void awaitGroups(final String nodeId, final Collection<ListenableFuture<?>> futures) {
562 if (!futures.isEmpty()) {
563 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
565 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
566 LOG.trace("awaitGroups() completed: node={}", nodeId);
567 } catch (TimeoutException | InterruptedException | ExecutionException e) {
568 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
574 private static BigInteger getDpnIdFromNodeName(final String nodeName) {
575 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
576 return new BigInteger(dpId);
579 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
580 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = new ArrayList<>();
581 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = new ArrayList<>();
582 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = new ArrayList<>();
584 Optional<FlowCapableNode> optFlowNode = Optional.empty();
586 try (ReadTransaction trans = provider.getReadTransaction()) {
587 optFlowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
588 } catch (ExecutionException | InterruptedException e) {
589 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
592 if (optFlowNode.isPresent()) {
593 final FlowCapableNode flowNode = optFlowNode.orElseThrow();
594 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
596 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
597 Collection<Table> tables = flowNode.nonnullTable().values();
598 for (Table table : tables) {
599 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
601 Collection<StaleFlow> staleFlows = table.nonnullStaleFlow().values();
602 for (StaleFlow staleFlow : staleFlows) {
604 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
605 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
607 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
608 toBeDeletedFlow.key());
610 provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
612 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
616 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
619 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
620 // Flows are fully deleted
621 // before attempting to delete groups - just in case there are references
623 /* Stale-marked Groups - Can be deleted after flows */
624 for (StaleGroup staleGroup : flowNode.nonnullStaleGroup().values()) {
625 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
626 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
628 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
629 toBeDeletedGroup.key());
631 provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
633 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
636 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
638 /* Stale-marked Meters - can be deleted anytime - so least priority */
639 for (StaleMeter staleMeter : flowNode.nonnullStaleMeter().values()) {
641 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
642 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
644 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
645 toBeDeletedMeter.key());
647 provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
649 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
654 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
656 // Now, do the bulk deletions
657 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
658 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
659 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
662 private void deleteDSStaleFlows(final List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
663 final var writeTransaction = dataBroker.newWriteOnlyTransaction();
664 for (var staleFlowIId : flowsForBulkDelete) {
665 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
667 handleStaleEntityDeletionResultFuture(writeTransaction.commit());
670 private void deleteDSStaleGroups(final List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
671 final var writeTransaction = dataBroker.newWriteOnlyTransaction();
672 for (var staleGroupIId : groupsForBulkDelete) {
673 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
675 handleStaleEntityDeletionResultFuture(writeTransaction.commit());
678 private void deleteDSStaleMeters(final List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
679 final var writeTransaction = dataBroker.newWriteOnlyTransaction();
680 for (var staleMeterIId : metersForBulkDelete) {
681 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
683 handleStaleEntityDeletionResultFuture(writeTransaction.commit());
686 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
687 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
688 final StaleFlow staleFlow, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
689 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
690 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
691 new StaleFlowKey(new FlowId(staleFlow.getId())));
694 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
695 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
696 final StaleGroup staleGroup, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
697 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
700 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
701 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
702 final StaleMeter staleMeter, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
703 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
706 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
707 final BundleId bundleIdValue,
708 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
709 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
710 for (Group group : flowNode.nonnullGroup().values()) {
711 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
712 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
715 for (Table table : flowNode.nonnullTable().values()) {
716 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
717 for (Flow flow : table.nonnullFlow().values()) {
718 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
719 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
722 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
726 private static void handleStaleEntityDeletionResultFuture(final FluentFuture<? extends CommitInfo> submitFuture) {
727 submitFuture.addCallback(new FutureCallback<CommitInfo>() {
729 public void onSuccess(final CommitInfo result) {
730 LOG.debug("Stale entity removal success");
734 public void onFailure(final Throwable throwable) {
735 LOG.debug("Stale entity removal failed", throwable);
737 }, MoreExecutors.directExecutor());
740 private static Flow getDeleteAllFlow() {
741 return new FlowBuilder().setTableId(OFConstants.OFPTT_ALL).build();
744 private static Group getDeleteAllGroup() {
745 return new GroupBuilder()
746 .setGroupType(GroupTypes.GroupAll)
747 .setGroupId(new GroupId(OFConstants.OFPG_ALL))
751 private static Messages createMessages(final NodeRef nodeRef) {
752 final List<Message> messages = new ArrayList<>();
753 messages.add(new MessageBuilder().setNode(nodeRef)
754 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
755 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
758 messages.add(new MessageBuilder().setNode(nodeRef)
759 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
760 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
762 return new MessagesBuilder().setMessage(messages).build();