2 * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.openflowplugin.applications.frm.impl;
10 import static org.opendaylight.openflowplugin.api.openflow.ReconciliationState.ReconciliationStatus.COMPLETED;
11 import static org.opendaylight.openflowplugin.api.openflow.ReconciliationState.ReconciliationStatus.FAILED;
12 import static org.opendaylight.openflowplugin.api.openflow.ReconciliationState.ReconciliationStatus.STARTED;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Lists;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.JdkFutureAdapters;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.ThreadFactoryBuilder;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.math.BigInteger;
25 import java.time.LocalDateTime;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.ListIterator;
33 import java.util.Optional;
34 import java.util.concurrent.Callable;
35 import java.util.concurrent.ConcurrentHashMap;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ThreadFactory;
40 import java.util.concurrent.TimeUnit;
41 import java.util.concurrent.TimeoutException;
42 import java.util.concurrent.atomic.AtomicLong;
43 import org.opendaylight.mdsal.binding.api.DataBroker;
44 import org.opendaylight.mdsal.binding.api.ReadTransaction;
45 import org.opendaylight.mdsal.binding.api.WriteTransaction;
46 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
47 import org.opendaylight.openflowplugin.api.OFConstants;
48 import org.opendaylight.openflowplugin.api.openflow.FlowGroupCacheManager;
49 import org.opendaylight.openflowplugin.api.openflow.ReconciliationState;
50 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
51 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
52 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
53 import org.opendaylight.openflowplugin.applications.frm.util.FrmUtil;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
96 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;
97 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;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
104 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
105 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
106 import org.opendaylight.yangtools.yang.common.RpcResult;
107 import org.opendaylight.yangtools.yang.common.Uint32;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
112 * Default implementation of {@link ForwardingRulesManager}.
114 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
116 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
118 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
119 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
121 // The number of nanoseconds to wait for a single group to be added.
122 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
124 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
125 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
126 private static final String SEPARATOR = ":";
127 private static final int THREAD_POOL_SIZE = 4;
128 private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
129 .setNameFormat("BundleResync-%d")
131 .setUncaughtExceptionHandler((thread, ex) -> LOG.error("Uncaught exception {}", thread, ex))
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;
138 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new ConcurrentHashMap<>();
140 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
142 private final SalBundleService salBundleService;
144 private static final AtomicLong BUNDLE_ID = new AtomicLong();
145 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
146 private Map<String, ReconciliationState> reconciliationStates;
148 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
149 final String serviceName, final int priority, final ResultState resultState,
150 final FlowGroupCacheManager flowGroupCacheManager) {
151 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
152 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
153 this.serviceName = serviceName;
154 this.priority = priority;
155 this.resultState = resultState;
156 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
157 "salBundleService can not be null!");
158 reconciliationStates = flowGroupCacheManager.getReconciliationStates();
162 public void close() {
163 if (executor != null) {
164 executor.shutdownNow();
169 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
170 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
171 // Clearing the group registry cache for the connected node if exists
172 String nodeId = FrmUtil.getNodeIdValueFromNodeIdentifier(connectedNode);
173 provider.getDevicesGroupRegistry().clearNodeGroups(nodeId);
174 if (provider.isStaleMarkingEnabled()) {
175 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
177 reconciliationPreProcess(connectedNode);
179 if (provider.isBundleBasedReconciliationEnabled()) {
180 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
181 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
183 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
184 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
189 public void flowNodeDisconnected(InstanceIdentifier<FlowCapableNode> disconnectedNode) {
190 String node = disconnectedNode.firstKeyOf(Node.class).getId().getValue();
191 BigInteger dpnId = getDpnIdFromNodeName(node);
192 reconciliationStates.remove(dpnId.toString());
195 private class BundleBasedReconciliationTask implements Callable<Boolean> {
196 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
198 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
199 nodeIdentity = nodeIdent;
203 public Boolean call() {
204 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
205 Optional<FlowCapableNode> flowNode = Optional.empty();
206 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
207 BigInteger dpnId = getDpnIdFromNodeName(node);
208 ExecutorService service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
209 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
210 try (ReadTransaction trans = provider.getReadTransaction()) {
211 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
212 } catch (ExecutionException | InterruptedException e) {
213 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
216 if (flowNode.isPresent()) {
217 ReconciliationState reconciliationState = new ReconciliationState(
218 STARTED, LocalDateTime.now());
219 //put the dpn info into the map
220 reconciliationStates.put(dpnId.toString(), reconciliationState);
221 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
222 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
223 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
225 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
226 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
227 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
229 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
230 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
231 .setType(BundleControlType.ONFBCTOPENREQUEST).build();
233 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
234 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
235 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
237 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
238 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
239 .setMessages(createMessages(nodeRef)).build();
241 LOG.debug("Closing openflow bundle for device {}", dpnId);
242 /* Close previously opened bundle on the openflow switch if any */
243 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
244 = salBundleService.controlBundle(closeBundleInput);
246 /* Open a new bundle on the switch */
247 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
248 Futures.transformAsync(closeBundle,
249 rpcResult -> 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 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
258 return Futures.immediateFuture(null);
261 /* Push flows and groups via bundle add messages */
262 Optional<FlowCapableNode> finalFlowNode = flowNode;
263 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
264 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
265 if (rpcResult.isSuccessful()) {
266 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
267 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
270 return Futures.immediateFuture(null);
273 /* Commit the bundle on the openflow switch */
274 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture
275 = Futures.transformAsync(addbundlesFuture, rpcResult -> {
276 LOG.debug("Adding bundle messages completed for device {}", dpnId);
277 return salBundleService.controlBundle(commitBundleInput);
280 /* Bundles not supported for meters */
281 Collection<Meter> meters = flowNode.get().nonnullMeter().values();
282 Futures.transformAsync(commitBundleFuture,
284 if (rpcResult.isSuccessful()) {
285 for (Meter meter : meters) {
286 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
287 .child(Meter.class, meter.key());
288 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
291 return Futures.immediateFuture(null);
294 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
295 if (bundleFuture != null && bundleFuture.isSuccessful()) {
296 reconciliationState.setState(COMPLETED, LocalDateTime.now());
297 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
298 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
301 reconciliationState.setState(FAILED, LocalDateTime.now());
302 LOG.error("commit bundle failed for device {} with error {}", dpnId,
303 commitBundleFuture.get().getErrors());
306 } catch (InterruptedException | ExecutionException e) {
307 reconciliationState.setState(FAILED, LocalDateTime.now());
308 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId, e);
314 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
320 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
321 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
322 .augmentation(FlowCapableNode.class);
323 // Clearing the group registry cache for the connected node if exists
324 provider.getDevicesGroupRegistry().clearNodeGroups(node.toString());
325 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
329 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
330 ListenableFuture<Boolean> listenableFuture = futureMap.computeIfPresent(node, (key, future) -> future);
331 if (listenableFuture != null) {
332 listenableFuture.cancel(true);
333 futureMap.remove(node);
335 return Futures.immediateFuture(true);
339 public int getPriority() {
344 public String getName() {
349 public ResultState getResultState() {
353 private class ReconciliationTask implements Callable<Boolean> {
355 InstanceIdentifier<FlowCapableNode> nodeIdentity;
357 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
358 nodeIdentity = nodeIdent;
362 public Boolean call() {
363 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
364 BigInteger dpnId = getDpnIdFromNodeName(node);
365 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
367 Optional<FlowCapableNode> flowNode;
368 // initialize the counter
370 try (ReadTransaction trans = provider.getReadTransaction()) {
371 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
372 } catch (ExecutionException | InterruptedException e) {
373 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
377 if (flowNode.isPresent()) {
378 /* Tables - have to be pushed before groups */
379 // CHECK if while pushing the update, updateTableInput can be null to emulate a
381 ReconciliationState reconciliationState = new ReconciliationState(
382 STARTED, LocalDateTime.now());
383 //put the dpn info into the map
384 reconciliationStates.put(dpnId.toString(), reconciliationState);
385 LOG.debug("Triggering reconciliation for node {} with state: {}", dpnId, STARTED);
386 Collection<TableFeatures> tableList = flowNode.get().nonnullTableFeatures().values();
387 for (TableFeatures tableFeaturesItem : tableList) {
388 TableFeaturesKey tableKey = tableFeaturesItem.key();
389 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
390 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
391 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
394 /* Groups - have to be first */
395 Collection<Group> groups = flowNode.get().nonnullGroup().values();
396 List<Group> toBeInstalledGroups = new ArrayList<>();
397 toBeInstalledGroups.addAll(groups);
398 // new list for suspected groups pointing to ports .. when the ports come up
400 List<Group> suspectedGroups = new ArrayList<>();
401 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
403 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
404 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
405 // crossed the threshold
407 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
408 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
410 toBeInstalledGroups.addAll(suspectedGroups);
414 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
415 while (iterator.hasNext()) {
416 Group group = iterator.next();
417 boolean okToInstall = true;
418 Buckets buckets = group.getBuckets();
419 Collection<Bucket> bucketList = buckets == null ? null : buckets.nonnullBucket().values();
420 if (bucketList == null) {
421 bucketList = Collections.<Bucket>emptyList();
423 for (Bucket bucket : bucketList) {
424 Collection<Action> actions = bucket.nonnullAction().values();
425 if (actions == null) {
426 actions = Collections.<Action>emptyList();
428 for (Action action : actions) {
430 if (action.getAction().implementedInterface().getName()
431 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
432 + ".action.types.rev131112.action.action.OutputActionCase")) {
433 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
434 .getOutputNodeConnector().getValue();
436 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
438 // check if the nodeconnector is there in the multimap
439 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
440 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
441 // if yes set okToInstall = true
446 // else put it in a different list and still set okToInstall = true
447 suspectedGroups.add(group);
449 "Not yet received the node-connector updated for {} "
450 + "for the group with id {}",
451 nodeConnectorUri, group.getGroupId());
454 } else if (action.getAction().implementedInterface().getName()
455 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
456 + ".action.types.rev131112.action.action.GroupActionCase")) {
458 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
460 ListenableFuture<?> future = groupFutures.get(groupId);
461 if (future == null) {
465 // Need to ensure that the group specified
466 // by group-action is already installed.
467 awaitGroup(node, future);
471 // increment retry counter value
477 addGroup(groupFutures, group);
479 // resetting the counter to zero
485 /* installation of suspected groups */
486 if (!toBeInstalledGroups.isEmpty()) {
487 for (Group group : toBeInstalledGroups) {
489 "Installing the group {} finally although "
490 + "the port is not up after checking for {} times ",
491 group.getGroupId(), provider.getReconciliationRetryCount());
492 addGroup(groupFutures, group);
496 Collection<Meter> meters = flowNode.get().nonnullMeter().values();
497 for (Meter meter : meters) {
498 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
500 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
503 // Need to wait for all groups to be installed before adding
505 awaitGroups(node, groupFutures.values());
508 Collection<Table> tables = flowNode.get().getTable() != null ? flowNode.get().nonnullTable().values()
509 : Collections.<Table>emptyList();
511 for (Table table : tables) {
512 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
514 Collection<Flow> flows = table.nonnullFlow().values();
515 flowCount += flows.size();
516 for (Flow flow : flows) {
517 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
519 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
522 reconciliationState.setState(COMPLETED, LocalDateTime.now());
523 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
529 * Invoke add-group RPC, and put listenable future associated with the RPC into
533 * The map to store listenable futures associated with add-group RPC.
537 private void addGroup(Map<Uint32, ListenableFuture<?>> map, Group group) {
538 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
539 final Uint32 groupId = group.getGroupId().getValue();
540 ListenableFuture<?> future = JdkFutureAdapters
541 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
543 Futures.addCallback(future, new FutureCallback<Object>() {
545 public void onSuccess(Object result) {
546 if (LOG.isTraceEnabled()) {
547 LOG.trace("add-group RPC completed: node={}, id={}",
548 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
553 public void onFailure(Throwable cause) {
554 LOG.debug("add-group RPC failed: node={}, id={}",
555 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
557 }, MoreExecutors.directExecutor());
559 map.put(groupId, future);
563 * Wait for completion of add-group RPC.
566 * The identifier for the target node.
568 * Future associated with add-group RPC that installs the target
571 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
572 awaitGroups(nodeId, Collections.singleton(future));
576 * Wait for completion of add-group RPCs.
579 * The identifier for the target node.
581 * A collection of futures associated with add-group RPCs.
583 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
584 if (!futures.isEmpty()) {
585 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
587 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
588 LOG.trace("awaitGroups() completed: node={}", nodeId);
589 } catch (TimeoutException | InterruptedException | ExecutionException e) {
590 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
596 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
597 justification = "https://github.com/spotbugs/spotbugs/issues/811")
598 private BigInteger getDpnIdFromNodeName(String nodeName) {
600 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
601 return new BigInteger(dpId);
604 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
605 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
606 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
607 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
609 Optional<FlowCapableNode> flowNode = Optional.empty();
611 try (ReadTransaction trans = provider.getReadTransaction()) {
612 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
613 } catch (ExecutionException | InterruptedException e) {
614 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
617 if (flowNode.isPresent()) {
619 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
621 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
622 Collection<Table> tables = flowNode.get().nonnullTable().values();
623 for (Table table : tables) {
624 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
626 Collection<StaleFlow> staleFlows = table.nonnullStaleFlow().values();
627 for (StaleFlow staleFlow : staleFlows) {
629 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
630 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
632 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
633 toBeDeletedFlow.key());
635 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
637 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
641 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
644 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
645 // Flows are fully deleted
646 // before attempting to delete groups - just in case there are references
648 /* Stale-marked Groups - Can be deleted after flows */
649 Collection<StaleGroup> staleGroups = flowNode.get().nonnullStaleGroup().values();
650 for (StaleGroup staleGroup : staleGroups) {
652 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
653 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
655 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
656 toBeDeletedGroup.key());
658 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
660 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
663 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
665 /* Stale-marked Meters - can be deleted anytime - so least priority */
666 Collection<StaleMeter> staleMeters = flowNode.get().getStaleMeter().values();
668 for (StaleMeter staleMeter : staleMeters) {
670 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
671 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
673 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
674 toBeDeletedMeter.key());
676 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
678 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
683 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
685 // Now, do the bulk deletions
686 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
687 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
688 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
691 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
692 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
694 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
695 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
698 FluentFuture<?> submitFuture = writeTransaction.commit();
699 handleStaleEntityDeletionResultFuture(submitFuture);
702 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
703 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
705 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
706 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
709 FluentFuture<?> submitFuture = writeTransaction.commit();
710 handleStaleEntityDeletionResultFuture(submitFuture);
713 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
714 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
716 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
717 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
720 FluentFuture<?> submitFuture = writeTransaction.commit();
721 handleStaleEntityDeletionResultFuture(submitFuture);
724 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
725 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
726 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
727 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
728 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
729 new StaleFlowKey(new FlowId(staleFlow.getId())));
732 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
733 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
734 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
735 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
738 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
739 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
740 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
741 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
744 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
745 justification = "https://github.com/spotbugs/spotbugs/issues/811")
746 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
747 final BundleId bundleIdValue,
748 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
749 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
750 for (Group group : flowNode.nonnullGroup().values()) {
751 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
752 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
755 for (Table table : flowNode.nonnullTable().values()) {
756 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
757 for (Flow flow : table.nonnullFlow().values()) {
758 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
759 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
762 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
766 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
767 submitFuture.addCallback(new FutureCallback<Object>() {
769 public void onSuccess(Object result) {
770 LOG.debug("Stale entity removal success");
774 public void onFailure(Throwable throwable) {
775 LOG.debug("Stale entity removal failed", throwable);
777 }, MoreExecutors.directExecutor());
780 private Flow getDeleteAllFlow() {
781 final FlowBuilder flowBuilder = new FlowBuilder();
782 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
783 return flowBuilder.build();
786 private Group getDeleteAllGroup() {
787 final GroupBuilder groupBuilder = new GroupBuilder();
788 groupBuilder.setGroupType(GroupTypes.GroupAll);
789 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
790 return groupBuilder.build();
793 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
794 justification = "https://github.com/spotbugs/spotbugs/issues/811")
795 private Messages createMessages(final NodeRef nodeRef) {
796 final List<Message> messages = new ArrayList<>();
797 messages.add(new MessageBuilder().setNode(nodeRef)
798 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
799 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
802 messages.add(new MessageBuilder().setNode(nodeRef)
803 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
804 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
806 return new MessagesBuilder().setMessage(messages).build();