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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.math.BigInteger;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.ListIterator;
27 import java.util.Optional;
28 import java.util.concurrent.Callable;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.TimeoutException;
34 import java.util.concurrent.atomic.AtomicLong;
35 import org.opendaylight.mdsal.binding.api.DataBroker;
36 import org.opendaylight.mdsal.binding.api.ReadTransaction;
37 import org.opendaylight.mdsal.binding.api.WriteTransaction;
38 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
39 import org.opendaylight.openflowplugin.api.OFConstants;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
41 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
42 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
85 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;
86 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;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
93 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
94 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
95 import org.opendaylight.yangtools.yang.common.RpcResult;
96 import org.opendaylight.yangtools.yang.common.Uint32;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
101 * Default implementation of {@link ForwardingRulesManager}.
103 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
105 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
107 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
108 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
110 // The number of nanoseconds to wait for a single group to be added.
111 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
113 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
114 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
115 private static final String SEPARATOR = ":";
116 private static final int THREAD_POOL_SIZE = 4;
118 private final DataBroker dataBroker;
119 private final ForwardingRulesManager provider;
120 private final String serviceName;
121 private final int priority;
122 private final ResultState resultState;
123 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
125 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
127 private final SalBundleService salBundleService;
129 private static final AtomicLong BUNDLE_ID = new AtomicLong();
130 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
132 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
133 final String serviceName, final int priority, final ResultState resultState) {
134 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
135 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
136 this.serviceName = serviceName;
137 this.priority = priority;
138 this.resultState = resultState;
139 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
140 "salBundleService can not be null!");
144 public void close() {
145 if (executor != null) {
146 executor.shutdownNow();
151 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
152 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
153 if (provider.isStaleMarkingEnabled()) {
154 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
155 connectedNode.toString());
156 reconciliationPreProcess(connectedNode);
158 if (provider.isBundleBasedReconciliationEnabled()) {
159 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
160 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
162 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
163 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
167 private class BundleBasedReconciliationTask implements Callable<Boolean> {
168 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
170 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
171 nodeIdentity = nodeIdent;
175 public Boolean call() {
176 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
177 Optional<FlowCapableNode> flowNode = Optional.empty();
178 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
179 BigInteger dpnId = getDpnIdFromNodeName(node);
180 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
181 try (ReadTransaction trans = provider.getReadTransaction()) {
182 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
183 } catch (ExecutionException | InterruptedException e) {
184 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
187 if (flowNode.isPresent()) {
188 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
189 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
190 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
192 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
193 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
194 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
196 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
197 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
200 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
201 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
202 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
204 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
205 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
206 .setMessages(createMessages(nodeRef)).build();
208 LOG.debug("Closing openflow bundle for device {}", dpnId);
209 /* Close previously opened bundle on the openflow switch if any */
210 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
211 = salBundleService.controlBundle(closeBundleInput);
213 /* Open a new bundle on the switch */
214 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
215 Futures.transformAsync(closeBundle,
216 rpcResult -> salBundleService.controlBundle(openBundleInput),
217 MoreExecutors.directExecutor());
219 /* Push groups and flows via bundle add messages */
220 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
221 = Futures.transformAsync(openBundle, rpcResult -> {
222 if (rpcResult.isSuccessful()) {
223 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
225 return Futures.immediateFuture(null);
226 }, MoreExecutors.directExecutor());
228 /* Push flows and groups via bundle add messages */
229 Optional<FlowCapableNode> finalFlowNode = flowNode;
230 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
231 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
232 if (rpcResult.isSuccessful()) {
233 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
234 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
237 return Futures.immediateFuture(null);
238 }, MoreExecutors.directExecutor());
240 /* Commit the bundle on the openflow switch */
241 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture = Futures.transformAsync(
242 addbundlesFuture, rpcResult -> {
243 LOG.debug("Adding bundle messages completed for device {}", dpnId);
244 return salBundleService.controlBundle(commitBundleInput);
245 }, MoreExecutors.directExecutor());
247 /* Bundles not supported for meters */
248 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
249 : Collections.emptyList();
250 Futures.transformAsync(commitBundleFuture,
252 if (rpcResult.isSuccessful()) {
253 for (Meter meter : meters) {
254 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
255 .child(Meter.class, meter.key());
256 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
259 return Futures.immediateFuture(null);
260 }, MoreExecutors.directExecutor());
262 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
263 if (bundleFuture != null && bundleFuture.isSuccessful()) {
264 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
265 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
268 LOG.error("commit bundle failed for device {} with error {}", dpnId,
269 commitBundleFuture.get().getErrors());
272 } catch (InterruptedException | ExecutionException e) {
273 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId);
277 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
283 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
284 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
285 .augmentation(FlowCapableNode.class);
286 // Clearing the group registry cache for the connected node if exists
287 provider.getDevicesGroupRegistry().clearNodeGroups(node.getNodeId());
288 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
292 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
293 futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
294 futureMap.remove(node);
295 return Futures.immediateFuture(true);
299 public int getPriority() {
304 public String getName() {
309 public ResultState getResultState() {
313 private class ReconciliationTask implements Callable<Boolean> {
315 InstanceIdentifier<FlowCapableNode> nodeIdentity;
317 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
318 nodeIdentity = nodeIdent;
322 public Boolean call() {
323 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
324 BigInteger dpnId = getDpnIdFromNodeName(node);
325 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
327 Optional<FlowCapableNode> flowNode;
328 // initialize the counter
330 try (ReadTransaction trans = provider.getReadTransaction()) {
331 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
332 } catch (ExecutionException | InterruptedException e) {
333 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
337 if (flowNode.isPresent()) {
338 /* Tables - have to be pushed before groups */
339 // CHECK if while pushing the update, updateTableInput can be null to emulate a
341 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
342 ? flowNode.get().getTableFeatures()
343 : Collections.<TableFeatures>emptyList();
344 for (TableFeatures tableFeaturesItem : tableList) {
345 TableFeaturesKey tableKey = tableFeaturesItem.key();
346 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
347 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
348 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
351 /* Groups - have to be first */
352 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
353 : Collections.<Group>emptyList();
354 List<Group> toBeInstalledGroups = new ArrayList<>();
355 toBeInstalledGroups.addAll(groups);
356 // new list for suspected groups pointing to ports .. when the ports come up
358 List<Group> suspectedGroups = new ArrayList<>();
359 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
361 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
362 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
363 // crossed the threshold
365 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
366 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
367 suspectedGroups.toString());
368 toBeInstalledGroups.addAll(suspectedGroups);
372 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
373 while (iterator.hasNext()) {
374 Group group = iterator.next();
375 boolean okToInstall = true;
376 Buckets buckets = group.getBuckets();
377 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
378 if (bucketList == null) {
379 bucketList = Collections.<Bucket>emptyList();
381 for (Bucket bucket : bucketList) {
382 List<Action> actions = bucket.getAction();
383 if (actions == null) {
384 actions = Collections.<Action>emptyList();
386 for (Action action : actions) {
388 if (action.getAction().implementedInterface().getName()
389 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
390 + ".action.types.rev131112.action.action.OutputActionCase")) {
391 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
392 .getOutputNodeConnector().getValue();
394 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
396 // check if the nodeconnector is there in the multimap
397 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
398 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
399 // if yes set okToInstall = true
404 // else put it in a different list and still set okToInstall = true
405 suspectedGroups.add(group);
407 "Not yet received the node-connector updated for {} "
408 + "for the group with id {}",
409 nodeConnectorUri, group.getGroupId().toString());
412 } else if (action.getAction().implementedInterface().getName()
413 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
414 + ".action.types.rev131112.action.action.GroupActionCase")) {
416 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
418 ListenableFuture<?> future = groupFutures.get(groupId);
419 if (future == null) {
423 // Need to ensure that the group specified
424 // by group-action is already installed.
425 awaitGroup(node, future);
429 // increment retry counter value
435 addGroup(groupFutures, group);
437 // resetting the counter to zero
443 /* installation of suspected groups */
444 if (!toBeInstalledGroups.isEmpty()) {
445 for (Group group : toBeInstalledGroups) {
447 "Installing the group {} finally although "
448 + "the port is not up after checking for {} times ",
449 group.getGroupId().toString(), provider.getReconciliationRetryCount());
450 addGroup(groupFutures, group);
454 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
455 : Collections.<Meter>emptyList();
456 for (Meter meter : meters) {
457 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
459 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
462 // Need to wait for all groups to be installed before adding
464 awaitGroups(node, groupFutures.values());
467 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
468 : Collections.<Table>emptyList();
470 for (Table table : tables) {
471 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
473 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
474 flowCount += flows.size();
475 for (Flow flow : flows) {
476 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
478 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
481 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
487 * Invoke add-group RPC, and put listenable future associated with the RPC into
491 * The map to store listenable futures associated with add-group RPC.
495 private void addGroup(Map<Uint32, ListenableFuture<?>> map, Group group) {
496 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
497 final Uint32 groupId = group.getGroupId().getValue();
498 ListenableFuture<?> future = JdkFutureAdapters
499 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
501 Futures.addCallback(future, new FutureCallback<Object>() {
503 public void onSuccess(Object result) {
504 if (LOG.isTraceEnabled()) {
505 LOG.trace("add-group RPC completed: node={}, id={}",
506 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
511 public void onFailure(Throwable cause) {
512 LOG.debug("add-group RPC failed: node={}, id={}",
513 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
515 }, MoreExecutors.directExecutor());
517 map.put(groupId, future);
521 * Wait for completion of add-group RPC.
524 * The identifier for the target node.
526 * Future associated with add-group RPC that installs the target
529 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
530 awaitGroups(nodeId, Collections.singleton(future));
534 * Wait for completion of add-group RPCs.
537 * The identifier for the target node.
539 * A collection of futures associated with add-group RPCs.
541 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
542 if (!futures.isEmpty()) {
543 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
545 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
546 LOG.trace("awaitGroups() completed: node={}", nodeId);
547 } catch (TimeoutException | InterruptedException | ExecutionException e) {
548 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
554 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
555 justification = "https://github.com/spotbugs/spotbugs/issues/811")
556 private BigInteger getDpnIdFromNodeName(String nodeName) {
558 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
559 return new BigInteger(dpId);
562 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
563 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
564 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
565 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
567 Optional<FlowCapableNode> flowNode = Optional.empty();
569 try (ReadTransaction trans = provider.getReadTransaction()) {
570 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
571 } catch (ExecutionException | InterruptedException e) {
572 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
575 if (flowNode.isPresent()) {
577 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
578 nodeIdent.toString());
579 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
580 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
581 : Collections.<Table>emptyList();
582 for (Table table : tables) {
583 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
585 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
586 : Collections.<StaleFlow>emptyList();
587 for (StaleFlow staleFlow : staleFlows) {
589 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
590 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
592 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
593 toBeDeletedFlow.key());
595 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
597 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
601 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
602 nodeIdent.toString());
604 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
605 // Flows are fully deleted
606 // before attempting to delete groups - just in case there are references
608 /* Stale-marked Groups - Can be deleted after flows */
609 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
610 : Collections.<StaleGroup>emptyList();
611 for (StaleGroup staleGroup : staleGroups) {
613 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
614 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
616 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
617 toBeDeletedGroup.key());
619 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
621 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
624 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
625 nodeIdent.toString());
626 /* Stale-marked Meters - can be deleted anytime - so least priority */
627 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
628 : Collections.<StaleMeter>emptyList();
630 for (StaleMeter staleMeter : staleMeters) {
632 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
633 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
635 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
636 toBeDeletedMeter.key());
638 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
640 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
645 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
646 nodeIdent.toString());
647 // Now, do the bulk deletions
648 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
649 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
650 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
653 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
654 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
656 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
657 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
660 FluentFuture<?> submitFuture = writeTransaction.commit();
661 handleStaleEntityDeletionResultFuture(submitFuture);
664 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
665 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
667 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
668 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
671 FluentFuture<?> submitFuture = writeTransaction.commit();
672 handleStaleEntityDeletionResultFuture(submitFuture);
675 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
676 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
678 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
679 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
682 FluentFuture<?> submitFuture = writeTransaction.commit();
683 handleStaleEntityDeletionResultFuture(submitFuture);
686 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
687 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
688 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
689 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
690 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
691 new StaleFlowKey(new FlowId(staleFlow.getId())));
694 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
695 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
696 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
697 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
700 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
701 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
702 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
703 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
706 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
707 justification = "https://github.com/spotbugs/spotbugs/issues/811")
708 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
709 final BundleId bundleIdValue,
710 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
711 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
712 for (Group group : flowNode.nonnullGroup()) {
713 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
714 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
717 for (Table table : flowNode.nonnullTable()) {
718 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
719 for (Flow flow : table.nonnullFlow()) {
720 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
721 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
724 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
728 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
729 submitFuture.addCallback(new FutureCallback<Object>() {
731 public void onSuccess(Object result) {
732 LOG.debug("Stale entity removal success");
736 public void onFailure(Throwable throwable) {
737 LOG.debug("Stale entity removal failed", throwable);
739 }, MoreExecutors.directExecutor());
742 private Flow getDeleteAllFlow() {
743 final FlowBuilder flowBuilder = new FlowBuilder();
744 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
745 return flowBuilder.build();
748 private Group getDeleteAllGroup() {
749 final GroupBuilder groupBuilder = new GroupBuilder();
750 groupBuilder.setGroupType(GroupTypes.GroupAll);
751 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
752 return groupBuilder.build();
755 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
756 justification = "https://github.com/spotbugs/spotbugs/issues/811")
757 private Messages createMessages(final NodeRef nodeRef) {
758 final List<Message> messages = new ArrayList<>();
759 messages.add(new MessageBuilder().setNode(nodeRef)
760 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
761 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
764 messages.add(new MessageBuilder().setNode(nodeRef)
765 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
766 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
768 return new MessagesBuilder().setMessage(messages).build();