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 com.google.common.base.Preconditions;
11 import com.google.common.collect.Lists;
12 import com.google.common.util.concurrent.FluentFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.JdkFutureAdapters;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import com.google.common.util.concurrent.ThreadFactoryBuilder;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.ListIterator;
28 import java.util.Optional;
29 import java.util.concurrent.Callable;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.ThreadFactory;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.TimeoutException;
36 import java.util.concurrent.atomic.AtomicLong;
37 import org.opendaylight.mdsal.binding.api.DataBroker;
38 import org.opendaylight.mdsal.binding.api.ReadTransaction;
39 import org.opendaylight.mdsal.binding.api.WriteTransaction;
40 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
41 import org.opendaylight.openflowplugin.api.OFConstants;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
43 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
44 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
45 import org.opendaylight.openflowplugin.applications.frm.util.FrmUtil;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.flow._case.RemoveFlowCaseDataBuilder;
89 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;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
96 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
97 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
98 import org.opendaylight.yangtools.yang.common.RpcResult;
99 import org.opendaylight.yangtools.yang.common.Uint32;
100 import org.slf4j.Logger;
101 import org.slf4j.LoggerFactory;
104 * Default implementation of {@link ForwardingRulesManager}.
106 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
108 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
110 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
111 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
113 // The number of nanoseconds to wait for a single group to be added.
114 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
116 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
117 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
118 private static final String SEPARATOR = ":";
119 private static final int THREAD_POOL_SIZE = 4;
120 private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
121 .setNameFormat("BundleResync-%d")
123 .setUncaughtExceptionHandler((thread, ex) -> LOG.error("Uncaught exception {}", thread, ex))
125 private final DataBroker dataBroker;
126 private final ForwardingRulesManager provider;
127 private final String serviceName;
128 private final int priority;
129 private final ResultState resultState;
130 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
132 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
134 private final SalBundleService salBundleService;
136 private static final AtomicLong BUNDLE_ID = new AtomicLong();
137 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
139 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
140 final String serviceName, final int priority, final ResultState resultState) {
141 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
142 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
143 this.serviceName = serviceName;
144 this.priority = priority;
145 this.resultState = resultState;
146 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
147 "salBundleService can not be null!");
151 public void close() {
152 if (executor != null) {
153 executor.shutdownNow();
158 public ListenableFuture<Boolean> reconcileConfiguration(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);
168 if (provider.isBundleBasedReconciliationEnabled()) {
169 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
170 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
172 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
173 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
177 private class BundleBasedReconciliationTask implements Callable<Boolean> {
178 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
180 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
181 nodeIdentity = nodeIdent;
185 public Boolean call() {
186 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
187 Optional<FlowCapableNode> flowNode = Optional.empty();
188 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
189 BigInteger dpnId = getDpnIdFromNodeName(node);
190 ExecutorService service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
191 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
192 try (ReadTransaction trans = provider.getReadTransaction()) {
193 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
194 } catch (ExecutionException | InterruptedException e) {
195 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
198 if (flowNode.isPresent()) {
199 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
200 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
201 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
203 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
204 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
205 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
207 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
208 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
209 .setType(BundleControlType.ONFBCTOPENREQUEST).build();
211 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
212 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
213 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
215 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
216 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
217 .setMessages(createMessages(nodeRef)).build();
219 LOG.debug("Closing openflow bundle for device {}", dpnId);
220 /* Close previously opened bundle on the openflow switch if any */
221 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
222 = salBundleService.controlBundle(closeBundleInput);
224 /* Open a new bundle on the switch */
225 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
226 Futures.transformAsync(closeBundle,
227 rpcResult -> salBundleService.controlBundle(openBundleInput),
230 /* Push groups and flows via bundle add messages */
231 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
232 = Futures.transformAsync(openBundle, rpcResult -> {
233 if (rpcResult.isSuccessful()) {
234 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
236 return Futures.immediateFuture(null);
239 /* Push flows and groups via bundle add messages */
240 Optional<FlowCapableNode> finalFlowNode = flowNode;
241 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
242 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
243 if (rpcResult.isSuccessful()) {
244 LOG.debug("Adding delete all flow/group message is successful for device {}",dpnId);
245 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
248 return Futures.immediateFuture(null);
251 /* Commit the bundle on the openflow switch */
252 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture = Futures.transformAsync(
253 addbundlesFuture, rpcResult -> {
254 LOG.debug("Adding bundle messages completed for device {}", dpnId);
255 return salBundleService.controlBundle(commitBundleInput);
258 /* Bundles not supported for meters */
259 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
260 : Collections.emptyList();
261 Futures.transformAsync(commitBundleFuture,
263 if (rpcResult.isSuccessful()) {
264 for (Meter meter : meters) {
265 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
266 .child(Meter.class, meter.key());
267 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
270 return Futures.immediateFuture(null);
273 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
274 if (bundleFuture != null && bundleFuture.isSuccessful()) {
275 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
276 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
279 LOG.error("commit bundle failed for device {} with error {}", dpnId,
280 commitBundleFuture.get().getErrors());
283 } catch (InterruptedException | ExecutionException e) {
284 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId);
288 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
297 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
298 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
299 .augmentation(FlowCapableNode.class);
300 // Clearing the group registry cache for the connected node if exists
301 provider.getDevicesGroupRegistry().clearNodeGroups(node.toString());
302 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
306 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
307 ListenableFuture<Boolean> listenableFuture = futureMap.computeIfPresent(node, (key, future) -> future);
308 if (listenableFuture != null) {
309 listenableFuture.cancel(true);
310 futureMap.remove(node);
312 return Futures.immediateFuture(true);
316 public int getPriority() {
321 public String getName() {
326 public ResultState getResultState() {
330 private class ReconciliationTask implements Callable<Boolean> {
332 InstanceIdentifier<FlowCapableNode> nodeIdentity;
334 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
335 nodeIdentity = nodeIdent;
339 public Boolean call() {
340 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
341 BigInteger dpnId = getDpnIdFromNodeName(node);
342 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
344 Optional<FlowCapableNode> flowNode;
345 // initialize the counter
347 try (ReadTransaction trans = provider.getReadTransaction()) {
348 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
349 } catch (ExecutionException | InterruptedException e) {
350 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
354 if (flowNode.isPresent()) {
355 /* Tables - have to be pushed before groups */
356 // CHECK if while pushing the update, updateTableInput can be null to emulate a
358 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
359 ? flowNode.get().getTableFeatures()
360 : Collections.<TableFeatures>emptyList();
361 for (TableFeatures tableFeaturesItem : tableList) {
362 TableFeaturesKey tableKey = tableFeaturesItem.key();
363 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
364 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
365 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
368 /* Groups - have to be first */
369 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
370 : Collections.<Group>emptyList();
371 List<Group> toBeInstalledGroups = new ArrayList<>();
372 toBeInstalledGroups.addAll(groups);
373 // new list for suspected groups pointing to ports .. when the ports come up
375 List<Group> suspectedGroups = new ArrayList<>();
376 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
378 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
379 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
380 // crossed the threshold
382 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
383 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
385 toBeInstalledGroups.addAll(suspectedGroups);
389 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
390 while (iterator.hasNext()) {
391 Group group = iterator.next();
392 boolean okToInstall = true;
393 Buckets buckets = group.getBuckets();
394 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
395 if (bucketList == null) {
396 bucketList = Collections.<Bucket>emptyList();
398 for (Bucket bucket : bucketList) {
399 List<Action> actions = bucket.getAction();
400 if (actions == null) {
401 actions = Collections.<Action>emptyList();
403 for (Action action : actions) {
405 if (action.getAction().implementedInterface().getName()
406 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
407 + ".action.types.rev131112.action.action.OutputActionCase")) {
408 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
409 .getOutputNodeConnector().getValue();
411 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
413 // check if the nodeconnector is there in the multimap
414 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
415 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
416 // if yes set okToInstall = true
421 // else put it in a different list and still set okToInstall = true
422 suspectedGroups.add(group);
424 "Not yet received the node-connector updated for {} "
425 + "for the group with id {}",
426 nodeConnectorUri, group.getGroupId());
429 } else if (action.getAction().implementedInterface().getName()
430 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
431 + ".action.types.rev131112.action.action.GroupActionCase")) {
433 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
435 ListenableFuture<?> future = groupFutures.get(groupId);
436 if (future == null) {
440 // Need to ensure that the group specified
441 // by group-action is already installed.
442 awaitGroup(node, future);
446 // increment retry counter value
452 addGroup(groupFutures, group);
454 // resetting the counter to zero
460 /* installation of suspected groups */
461 if (!toBeInstalledGroups.isEmpty()) {
462 for (Group group : toBeInstalledGroups) {
464 "Installing the group {} finally although "
465 + "the port is not up after checking for {} times ",
466 group.getGroupId(), provider.getReconciliationRetryCount());
467 addGroup(groupFutures, group);
471 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
472 : Collections.<Meter>emptyList();
473 for (Meter meter : meters) {
474 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
476 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
479 // Need to wait for all groups to be installed before adding
481 awaitGroups(node, groupFutures.values());
484 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
485 : Collections.<Table>emptyList();
487 for (Table table : tables) {
488 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
490 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
491 flowCount += flows.size();
492 for (Flow flow : flows) {
493 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
495 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
498 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
504 * Invoke add-group RPC, and put listenable future associated with the RPC into
508 * The map to store listenable futures associated with add-group RPC.
512 private void addGroup(Map<Uint32, ListenableFuture<?>> map, Group group) {
513 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
514 final Uint32 groupId = group.getGroupId().getValue();
515 ListenableFuture<?> future = JdkFutureAdapters
516 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
518 Futures.addCallback(future, new FutureCallback<Object>() {
520 public void onSuccess(Object result) {
521 if (LOG.isTraceEnabled()) {
522 LOG.trace("add-group RPC completed: node={}, id={}",
523 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
528 public void onFailure(Throwable cause) {
529 LOG.debug("add-group RPC failed: node={}, id={}",
530 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
532 }, MoreExecutors.directExecutor());
534 map.put(groupId, future);
538 * Wait for completion of add-group RPC.
541 * The identifier for the target node.
543 * Future associated with add-group RPC that installs the target
546 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
547 awaitGroups(nodeId, Collections.singleton(future));
551 * Wait for completion of add-group RPCs.
554 * The identifier for the target node.
556 * A collection of futures associated with add-group RPCs.
558 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
559 if (!futures.isEmpty()) {
560 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
562 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
563 LOG.trace("awaitGroups() completed: node={}", nodeId);
564 } catch (TimeoutException | InterruptedException | ExecutionException e) {
565 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
571 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
572 justification = "https://github.com/spotbugs/spotbugs/issues/811")
573 private BigInteger getDpnIdFromNodeName(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 = Lists.newArrayList();
581 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
582 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
584 Optional<FlowCapableNode> flowNode = Optional.empty();
586 try (ReadTransaction trans = provider.getReadTransaction()) {
587 flowNode = 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 (flowNode.isPresent()) {
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 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
598 : Collections.<Table>emptyList();
599 for (Table table : tables) {
600 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
602 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
603 : Collections.<StaleFlow>emptyList();
604 for (StaleFlow staleFlow : staleFlows) {
606 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
607 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
609 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
610 toBeDeletedFlow.key());
612 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
614 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
618 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
621 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
622 // Flows are fully deleted
623 // before attempting to delete groups - just in case there are references
625 /* Stale-marked Groups - Can be deleted after flows */
626 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
627 : Collections.<StaleGroup>emptyList();
628 for (StaleGroup staleGroup : staleGroups) {
630 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
631 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
633 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
634 toBeDeletedGroup.key());
636 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
638 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
641 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
643 /* Stale-marked Meters - can be deleted anytime - so least priority */
644 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
645 : Collections.<StaleMeter>emptyList();
647 for (StaleMeter staleMeter : staleMeters) {
649 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
650 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
652 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
653 toBeDeletedMeter.key());
655 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
657 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
662 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
664 // Now, do the bulk deletions
665 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
666 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
667 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
670 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
671 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
673 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
674 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
677 FluentFuture<?> submitFuture = writeTransaction.commit();
678 handleStaleEntityDeletionResultFuture(submitFuture);
681 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
682 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
684 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
685 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
688 FluentFuture<?> submitFuture = writeTransaction.commit();
689 handleStaleEntityDeletionResultFuture(submitFuture);
692 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
693 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
695 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
696 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
699 FluentFuture<?> submitFuture = writeTransaction.commit();
700 handleStaleEntityDeletionResultFuture(submitFuture);
703 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
704 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
705 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
706 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
707 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
708 new StaleFlowKey(new FlowId(staleFlow.getId())));
711 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
712 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
713 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
714 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
717 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
718 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
719 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
720 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
723 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
724 justification = "https://github.com/spotbugs/spotbugs/issues/811")
725 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
726 final BundleId bundleIdValue,
727 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
728 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
729 for (Group group : flowNode.nonnullGroup()) {
730 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
731 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
734 for (Table table : flowNode.nonnullTable()) {
735 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
736 for (Flow flow : table.nonnullFlow()) {
737 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
738 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
741 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
745 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
746 submitFuture.addCallback(new FutureCallback<Object>() {
748 public void onSuccess(Object result) {
749 LOG.debug("Stale entity removal success");
753 public void onFailure(Throwable throwable) {
754 LOG.debug("Stale entity removal failed", throwable);
756 }, MoreExecutors.directExecutor());
759 private Flow getDeleteAllFlow() {
760 final FlowBuilder flowBuilder = new FlowBuilder();
761 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
762 return flowBuilder.build();
765 private Group getDeleteAllGroup() {
766 final GroupBuilder groupBuilder = new GroupBuilder();
767 groupBuilder.setGroupType(GroupTypes.GroupAll);
768 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
769 return groupBuilder.build();
772 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
773 justification = "https://github.com/spotbugs/spotbugs/issues/811")
774 private Messages createMessages(final NodeRef nodeRef) {
775 final List<Message> messages = new ArrayList<>();
776 messages.add(new MessageBuilder().setNode(nodeRef)
777 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
778 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
781 messages.add(new MessageBuilder().setNode(nodeRef)
782 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
783 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
785 return new MessagesBuilder().setMessage(messages).build();