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.JdkFutureAdapters;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import com.google.common.util.concurrent.ThreadFactoryBuilder;
22 import java.math.BigInteger;
23 import java.time.LocalDateTime;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.ListIterator;
31 import java.util.Optional;
32 import java.util.concurrent.Callable;
33 import java.util.concurrent.ConcurrentHashMap;
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.binding.api.WriteTransaction;
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.AddBundleMessagesInput;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
94 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;
95 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;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
102 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
103 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
104 import org.opendaylight.yangtools.yang.common.RpcResult;
105 import org.opendaylight.yangtools.yang.common.Uint32;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
110 * Default implementation of {@link ForwardingRulesManager}.
112 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
114 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
116 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
117 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
119 // The number of nanoseconds to wait for a single group to be added.
120 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
122 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
123 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
124 private static final String SEPARATOR = ":";
125 private static final int THREAD_POOL_SIZE = 4;
126 private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
127 .setNameFormat("BundleResync-%d")
129 .setUncaughtExceptionHandler((thread, ex) -> LOG.error("Uncaught exception {}", thread, ex))
131 private final DataBroker dataBroker;
132 private final ForwardingRulesManager provider;
133 private final String serviceName;
134 private final int priority;
135 private final ResultState resultState;
136 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new ConcurrentHashMap<>();
138 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
140 private final SalBundleService salBundleService;
142 private static final AtomicLong BUNDLE_ID = new AtomicLong();
143 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
144 private final Map<String, ReconciliationState> reconciliationStates;
146 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
147 final String serviceName, final int priority, final ResultState resultState,
148 final FlowGroupCacheManager flowGroupCacheManager) {
149 this.provider = requireNonNull(manager, "ForwardingRulesManager can not be null!");
150 dataBroker = requireNonNull(db, "DataBroker can not be null!");
151 this.serviceName = serviceName;
152 this.priority = priority;
153 this.resultState = resultState;
154 salBundleService = requireNonNull(manager.getSalBundleService(), "salBundleService can not be null!");
155 reconciliationStates = flowGroupCacheManager.getReconciliationStates();
159 public void close() {
160 if (executor != null) {
161 executor.shutdownNow();
166 public ListenableFuture<Boolean> reconcileConfiguration(final InstanceIdentifier<FlowCapableNode> connectedNode) {
167 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
168 // Clearing the group registry cache for the connected node if exists
169 String nodeId = FrmUtil.getNodeIdValueFromNodeIdentifier(connectedNode);
170 provider.getDevicesGroupRegistry().clearNodeGroups(nodeId);
171 if (provider.isStaleMarkingEnabled()) {
172 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
174 reconciliationPreProcess(connectedNode);
176 if (provider.isBundleBasedReconciliationEnabled()) {
177 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
178 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
180 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
181 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
186 public void flowNodeDisconnected(final InstanceIdentifier<FlowCapableNode> disconnectedNode) {
187 String node = disconnectedNode.firstKeyOf(Node.class).getId().getValue();
188 BigInteger dpnId = getDpnIdFromNodeName(node);
189 reconciliationStates.remove(dpnId.toString());
192 private class BundleBasedReconciliationTask implements Callable<Boolean> {
193 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
195 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
196 nodeIdentity = nodeIdent;
200 public Boolean call() {
201 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
202 Optional<FlowCapableNode> flowNode = Optional.empty();
203 BundleId bundleIdValue = new BundleId(Uint32.valueOf(BUNDLE_ID.getAndIncrement()));
204 BigInteger dpnId = getDpnIdFromNodeName(node);
205 ExecutorService service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
206 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
207 try (ReadTransaction trans = provider.getReadTransaction()) {
208 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
209 } catch (ExecutionException | InterruptedException e) {
210 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
213 if (flowNode.isPresent()) {
214 ReconciliationState reconciliationState = new ReconciliationState(
215 STARTED, LocalDateTime.now());
216 //put the dpn info into the map
217 reconciliationStates.put(dpnId.toString(), reconciliationState);
218 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
219 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
220 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
222 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
223 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
224 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
226 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
227 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
228 .setType(BundleControlType.ONFBCTOPENREQUEST).build();
230 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
231 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
232 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
234 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
235 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
236 .setMessages(createMessages(nodeRef)).build();
238 LOG.debug("Closing openflow bundle for device {}", dpnId);
239 /* Close previously opened bundle on the openflow switch if any */
240 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
241 = salBundleService.controlBundle(closeBundleInput);
243 /* Open a new bundle on the switch */
244 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle
245 = Futures.transformAsync(closeBundle, rpcResult -> {
246 if (rpcResult.isSuccessful()) {
247 LOG.debug("Existing bundle is successfully closed for device {}", dpnId);
249 return salBundleService.controlBundle(openBundleInput);
252 /* Push groups and flows via bundle add messages */
253 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
254 = Futures.transformAsync(openBundle, rpcResult -> {
255 if (rpcResult.isSuccessful()) {
256 LOG.debug("Open bundle is successful for device {}", dpnId);
257 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
259 return Futures.immediateFuture(null);
262 /* Push flows and groups via bundle add messages */
263 Optional<FlowCapableNode> finalFlowNode = flowNode;
264 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
265 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
266 if (rpcResult.isSuccessful()) {
267 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
268 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
271 return Futures.immediateFuture(null);
274 /* Commit the bundle on the openflow switch */
275 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture
276 = Futures.transformAsync(addbundlesFuture, rpcResult -> {
277 LOG.debug("Adding bundle messages completed for device {}", dpnId);
278 return salBundleService.controlBundle(commitBundleInput);
281 /* Bundles not supported for meters */
282 Collection<Meter> meters = flowNode.get().nonnullMeter().values();
283 Futures.transformAsync(commitBundleFuture,
285 if (rpcResult.isSuccessful()) {
286 for (Meter meter : meters) {
287 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
288 .child(Meter.class, meter.key());
289 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
292 return Futures.immediateFuture(null);
295 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
296 if (bundleFuture != null && bundleFuture.isSuccessful()) {
297 reconciliationState.setState(COMPLETED, LocalDateTime.now());
298 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
299 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
302 reconciliationState.setState(FAILED, LocalDateTime.now());
303 LOG.error("commit bundle failed for device {} with error {}", dpnId,
304 commitBundleFuture.get().getErrors());
307 } catch (InterruptedException | ExecutionException e) {
308 reconciliationState.setState(FAILED, LocalDateTime.now());
309 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId, e);
315 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
321 public ListenableFuture<Boolean> startReconciliation(final DeviceInfo node) {
322 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
323 .augmentation(FlowCapableNode.class);
324 // Clearing the group registry cache for the connected node if exists
325 provider.getDevicesGroupRegistry().clearNodeGroups(node.toString());
326 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
330 public ListenableFuture<Boolean> endReconciliation(final DeviceInfo node) {
331 ListenableFuture<Boolean> listenableFuture = futureMap.computeIfPresent(node, (key, future) -> future);
332 if (listenableFuture != null) {
333 listenableFuture.cancel(true);
334 futureMap.remove(node);
336 return Futures.immediateFuture(true);
340 public int getPriority() {
345 public String getName() {
350 public ResultState getResultState() {
354 private class ReconciliationTask implements Callable<Boolean> {
356 InstanceIdentifier<FlowCapableNode> nodeIdentity;
358 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
359 nodeIdentity = nodeIdent;
363 public Boolean call() {
364 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
365 BigInteger dpnId = getDpnIdFromNodeName(node);
366 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
368 Optional<FlowCapableNode> flowNode;
369 // initialize the counter
371 try (ReadTransaction trans = provider.getReadTransaction()) {
372 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
373 } catch (ExecutionException | InterruptedException e) {
374 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
378 if (flowNode.isPresent()) {
379 /* Tables - have to be pushed before groups */
380 // CHECK if while pushing the update, updateTableInput can be null to emulate a
382 ReconciliationState reconciliationState = new ReconciliationState(
383 STARTED, LocalDateTime.now());
384 //put the dpn info into the map
385 reconciliationStates.put(dpnId.toString(), reconciliationState);
386 LOG.debug("Triggering reconciliation for node {} with state: {}", dpnId, STARTED);
387 Collection<TableFeatures> tableList = flowNode.get().nonnullTableFeatures().values();
388 for (TableFeatures tableFeaturesItem : tableList) {
389 TableFeaturesKey tableKey = tableFeaturesItem.key();
390 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
391 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
392 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
395 /* Groups - have to be first */
396 Collection<Group> groups = flowNode.get().nonnullGroup().values();
397 List<Group> toBeInstalledGroups = new ArrayList<>();
398 toBeInstalledGroups.addAll(groups);
399 // new list for suspected groups pointing to ports .. when the ports come up
401 List<Group> suspectedGroups = new ArrayList<>();
402 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
404 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
405 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
406 // crossed the threshold
408 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
409 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
411 toBeInstalledGroups.addAll(suspectedGroups);
415 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
416 while (iterator.hasNext()) {
417 Group group = iterator.next();
418 boolean okToInstall = true;
419 Buckets buckets = group.getBuckets();
420 Collection<Bucket> bucketList = buckets == null ? null : buckets.nonnullBucket().values();
421 if (bucketList == null) {
422 bucketList = Collections.<Bucket>emptyList();
424 for (Bucket bucket : bucketList) {
425 Collection<Action> actions = bucket.nonnullAction().values();
426 if (actions == null) {
427 actions = Collections.<Action>emptyList();
429 for (Action action : actions) {
431 if (action.getAction().implementedInterface().getName()
432 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
433 + ".action.types.rev131112.action.action.OutputActionCase")) {
434 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
435 .getOutputNodeConnector().getValue();
437 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
439 // check if the nodeconnector is there in the multimap
440 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
441 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
442 // if yes set okToInstall = true
447 // else put it in a different list and still set okToInstall = true
448 suspectedGroups.add(group);
450 "Not yet received the node-connector updated for {} "
451 + "for the group with id {}",
452 nodeConnectorUri, group.getGroupId());
455 } else if (action.getAction().implementedInterface().getName()
456 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
457 + ".action.types.rev131112.action.action.GroupActionCase")) {
459 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
461 ListenableFuture<?> future = groupFutures.get(groupId);
462 if (future == null) {
466 // Need to ensure that the group specified
467 // by group-action is already installed.
468 awaitGroup(node, future);
472 // increment retry counter value
478 addGroup(groupFutures, group);
480 // resetting the counter to zero
486 /* installation of suspected groups */
487 if (!toBeInstalledGroups.isEmpty()) {
488 for (Group group : toBeInstalledGroups) {
490 "Installing the group {} finally although "
491 + "the port is not up after checking for {} times ",
492 group.getGroupId(), provider.getReconciliationRetryCount());
493 addGroup(groupFutures, group);
497 Collection<Meter> meters = flowNode.get().nonnullMeter().values();
498 for (Meter meter : meters) {
499 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
501 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
504 // Need to wait for all groups to be installed before adding
506 awaitGroups(node, groupFutures.values());
509 Collection<Table> tables = flowNode.get().getTable() != null ? flowNode.get().nonnullTable().values()
510 : Collections.<Table>emptyList();
512 for (Table table : tables) {
513 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
515 Collection<Flow> flows = table.nonnullFlow().values();
516 flowCount += flows.size();
517 for (Flow flow : flows) {
518 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
520 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
523 reconciliationState.setState(COMPLETED, LocalDateTime.now());
524 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
530 * Invoke add-group RPC, and put listenable future associated with the RPC into
534 * The map to store listenable futures associated with add-group RPC.
538 private void addGroup(final Map<Uint32, ListenableFuture<?>> map, final Group group) {
539 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
540 final Uint32 groupId = group.getGroupId().getValue();
541 ListenableFuture<?> future = JdkFutureAdapters
542 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
544 Futures.addCallback(future, new FutureCallback<Object>() {
546 public void onSuccess(final Object result) {
547 if (LOG.isTraceEnabled()) {
548 LOG.trace("add-group RPC completed: node={}, id={}",
549 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
554 public void onFailure(final Throwable cause) {
555 LOG.debug("add-group RPC failed: node={}, id={}",
556 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
558 }, MoreExecutors.directExecutor());
560 map.put(groupId, future);
564 * Wait for completion of add-group RPC.
567 * The identifier for the target node.
569 * Future associated with add-group RPC that installs the target
572 private void awaitGroup(final String nodeId, final ListenableFuture<?> future) {
573 awaitGroups(nodeId, Collections.singleton(future));
577 * Wait for completion of add-group RPCs.
580 * The identifier for the target node.
582 * A collection of futures associated with add-group RPCs.
584 private void awaitGroups(final String nodeId, final Collection<ListenableFuture<?>> futures) {
585 if (!futures.isEmpty()) {
586 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
588 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
589 LOG.trace("awaitGroups() completed: node={}", nodeId);
590 } catch (TimeoutException | InterruptedException | ExecutionException e) {
591 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
597 private static BigInteger getDpnIdFromNodeName(final String nodeName) {
598 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
599 return new BigInteger(dpId);
602 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
603 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = new ArrayList<>();
604 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = new ArrayList<>();
605 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = new ArrayList<>();
607 Optional<FlowCapableNode> flowNode = Optional.empty();
609 try (ReadTransaction trans = provider.getReadTransaction()) {
610 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
611 } catch (ExecutionException | InterruptedException e) {
612 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
615 if (flowNode.isPresent()) {
617 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
619 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
620 Collection<Table> tables = flowNode.get().nonnullTable().values();
621 for (Table table : tables) {
622 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
624 Collection<StaleFlow> staleFlows = table.nonnullStaleFlow().values();
625 for (StaleFlow staleFlow : staleFlows) {
627 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
628 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
630 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
631 toBeDeletedFlow.key());
633 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
635 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
639 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
642 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
643 // Flows are fully deleted
644 // before attempting to delete groups - just in case there are references
646 /* Stale-marked Groups - Can be deleted after flows */
647 Collection<StaleGroup> staleGroups = flowNode.get().nonnullStaleGroup().values();
648 for (StaleGroup staleGroup : staleGroups) {
650 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
651 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
653 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
654 toBeDeletedGroup.key());
656 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
658 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
661 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
663 /* Stale-marked Meters - can be deleted anytime - so least priority */
664 Collection<StaleMeter> staleMeters = flowNode.get().getStaleMeter().values();
666 for (StaleMeter staleMeter : staleMeters) {
668 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
669 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
671 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
672 toBeDeletedMeter.key());
674 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
676 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
681 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
683 // Now, do the bulk deletions
684 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
685 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
686 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
689 private void deleteDSStaleFlows(final List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
690 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
692 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
693 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
696 FluentFuture<?> submitFuture = writeTransaction.commit();
697 handleStaleEntityDeletionResultFuture(submitFuture);
700 private void deleteDSStaleGroups(final List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
701 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
703 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
704 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
707 FluentFuture<?> submitFuture = writeTransaction.commit();
708 handleStaleEntityDeletionResultFuture(submitFuture);
711 private void deleteDSStaleMeters(final List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
712 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
714 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
715 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
718 FluentFuture<?> submitFuture = writeTransaction.commit();
719 handleStaleEntityDeletionResultFuture(submitFuture);
722 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
723 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
724 final StaleFlow staleFlow, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
725 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
726 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
727 new StaleFlowKey(new FlowId(staleFlow.getId())));
730 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
731 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
732 final StaleGroup staleGroup, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
733 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
736 private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
737 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
738 final StaleMeter staleMeter, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
739 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
742 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
743 final BundleId bundleIdValue,
744 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
745 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
746 for (Group group : flowNode.nonnullGroup().values()) {
747 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
748 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
751 for (Table table : flowNode.nonnullTable().values()) {
752 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
753 for (Flow flow : table.nonnullFlow().values()) {
754 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
755 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
758 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
762 private static void handleStaleEntityDeletionResultFuture(final FluentFuture<?> submitFuture) {
763 submitFuture.addCallback(new FutureCallback<Object>() {
765 public void onSuccess(final Object result) {
766 LOG.debug("Stale entity removal success");
770 public void onFailure(final Throwable throwable) {
771 LOG.debug("Stale entity removal failed", throwable);
773 }, MoreExecutors.directExecutor());
776 private static Flow getDeleteAllFlow() {
777 return new FlowBuilder().setTableId(OFConstants.OFPTT_ALL).build();
780 private static Group getDeleteAllGroup() {
781 return new GroupBuilder()
782 .setGroupType(GroupTypes.GroupAll)
783 .setGroupId(new GroupId(OFConstants.OFPG_ALL))
787 private static Messages createMessages(final NodeRef nodeRef) {
788 final List<Message> messages = new ArrayList<>();
789 messages.add(new MessageBuilder().setNode(nodeRef)
790 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
791 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
794 messages.add(new MessageBuilder().setNode(nodeRef)
795 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
796 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
798 return new MessagesBuilder().setMessage(messages).build();