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.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
100 * Default implementation of {@link ForwardingRulesManager}.
102 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
104 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
106 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
107 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
109 // The number of nanoseconds to wait for a single group to be added.
110 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
112 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
113 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
114 private static final String SEPARATOR = ":";
115 private static final int THREAD_POOL_SIZE = 4;
117 private final DataBroker dataBroker;
118 private final ForwardingRulesManager provider;
119 private final String serviceName;
120 private final int priority;
121 private final ResultState resultState;
122 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
124 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
126 private final SalBundleService salBundleService;
128 private static final AtomicLong BUNDLE_ID = new AtomicLong();
129 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
131 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
132 final String serviceName, final int priority, final ResultState resultState) {
133 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
134 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
135 this.serviceName = serviceName;
136 this.priority = priority;
137 this.resultState = resultState;
138 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
139 "salBundleService can not be null!");
143 public void close() {
144 if (executor != null) {
145 executor.shutdownNow();
150 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
151 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
152 if (provider.isStaleMarkingEnabled()) {
153 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
154 connectedNode.toString());
155 reconciliationPreProcess(connectedNode);
157 if (provider.isBundleBasedReconciliationEnabled()) {
158 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
159 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
161 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
162 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
166 private class BundleBasedReconciliationTask implements Callable<Boolean> {
167 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
169 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
170 nodeIdentity = nodeIdent;
174 public Boolean call() {
175 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
176 Optional<FlowCapableNode> flowNode = Optional.empty();
177 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
178 BigInteger dpnId = getDpnIdFromNodeName(node);
179 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
180 try (ReadTransaction trans = provider.getReadTransaction()) {
181 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
182 } catch (ExecutionException | InterruptedException e) {
183 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
186 if (flowNode.isPresent()) {
187 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
188 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
189 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
191 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
192 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
193 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
195 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
196 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
199 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
200 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
201 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
203 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
204 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
205 .setMessages(createMessages(nodeRef)).build();
207 LOG.debug("Closing openflow bundle for device {}", dpnId);
208 /* Close previously opened bundle on the openflow switch if any */
209 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
210 = salBundleService.controlBundle(closeBundleInput);
212 /* Open a new bundle on the switch */
213 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
214 Futures.transformAsync(closeBundle,
215 rpcResult -> salBundleService.controlBundle(openBundleInput),
216 MoreExecutors.directExecutor());
218 /* Push groups and flows via bundle add messages */
219 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
220 = Futures.transformAsync(openBundle, rpcResult -> {
221 if (rpcResult.isSuccessful()) {
222 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
224 return Futures.immediateFuture(null);
225 }, MoreExecutors.directExecutor());
227 /* Push flows and groups via bundle add messages */
228 Optional<FlowCapableNode> finalFlowNode = flowNode;
229 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
230 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
231 if (rpcResult.isSuccessful()) {
232 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
233 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
236 return Futures.immediateFuture(null);
237 }, MoreExecutors.directExecutor());
239 /* Commit the bundle on the openflow switch */
240 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture = Futures.transformAsync(
241 addbundlesFuture, rpcResult -> {
242 LOG.debug("Adding bundle messages completed for device {}", dpnId);
243 return salBundleService.controlBundle(commitBundleInput);
244 }, MoreExecutors.directExecutor());
246 /* Bundles not supported for meters */
247 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
248 : Collections.emptyList();
249 Futures.transformAsync(commitBundleFuture,
251 if (rpcResult.isSuccessful()) {
252 for (Meter meter : meters) {
253 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
254 .child(Meter.class, meter.key());
255 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
258 return Futures.immediateFuture(null);
259 }, MoreExecutors.directExecutor());
261 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
262 if (bundleFuture != null && bundleFuture.isSuccessful()) {
263 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
264 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
267 LOG.error("commit bundle failed for device {} with error {}", dpnId,
268 commitBundleFuture.get().getErrors());
271 } catch (InterruptedException | ExecutionException e) {
272 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId);
276 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
282 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
283 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
284 .augmentation(FlowCapableNode.class);
285 // Clearing the group registry cache for the connected node if exists
286 provider.getDevicesGroupRegistry().clearNodeGroups(node.getNodeId());
287 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
291 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
292 futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
293 futureMap.remove(node);
294 return Futures.immediateFuture(true);
298 public int getPriority() {
303 public String getName() {
308 public ResultState getResultState() {
312 private class ReconciliationTask implements Callable<Boolean> {
314 InstanceIdentifier<FlowCapableNode> nodeIdentity;
316 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
317 nodeIdentity = nodeIdent;
321 public Boolean call() {
322 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
323 BigInteger dpnId = getDpnIdFromNodeName(node);
324 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
326 Optional<FlowCapableNode> flowNode;
327 // initialize the counter
329 try (ReadTransaction trans = provider.getReadTransaction()) {
330 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
331 } catch (ExecutionException | InterruptedException e) {
332 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
336 if (flowNode.isPresent()) {
337 /* Tables - have to be pushed before groups */
338 // CHECK if while pushing the update, updateTableInput can be null to emulate a
340 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
341 ? flowNode.get().getTableFeatures()
342 : Collections.<TableFeatures>emptyList();
343 for (TableFeatures tableFeaturesItem : tableList) {
344 TableFeaturesKey tableKey = tableFeaturesItem.key();
345 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
346 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
347 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
350 /* Groups - have to be first */
351 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
352 : Collections.<Group>emptyList();
353 List<Group> toBeInstalledGroups = new ArrayList<>();
354 toBeInstalledGroups.addAll(groups);
355 // new list for suspected groups pointing to ports .. when the ports come up
357 List<Group> suspectedGroups = new ArrayList<>();
358 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
360 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
361 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
362 // crossed the threshold
364 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
365 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
366 suspectedGroups.toString());
367 toBeInstalledGroups.addAll(suspectedGroups);
371 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
372 while (iterator.hasNext()) {
373 Group group = iterator.next();
374 boolean okToInstall = true;
375 Buckets buckets = group.getBuckets();
376 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
377 if (bucketList == null) {
378 bucketList = Collections.<Bucket>emptyList();
380 for (Bucket bucket : bucketList) {
381 List<Action> actions = bucket.getAction();
382 if (actions == null) {
383 actions = Collections.<Action>emptyList();
385 for (Action action : actions) {
387 if (action.getAction().implementedInterface().getName()
388 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
389 + ".action.types.rev131112.action.action.OutputActionCase")) {
390 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
391 .getOutputNodeConnector().getValue();
393 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
395 // check if the nodeconnector is there in the multimap
396 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
397 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
398 // if yes set okToInstall = true
403 // else put it in a different list and still set okToInstall = true
404 suspectedGroups.add(group);
406 "Not yet received the node-connector updated for {} "
407 + "for the group with id {}",
408 nodeConnectorUri, group.getGroupId().toString());
411 } else if (action.getAction().implementedInterface().getName()
412 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
413 + ".action.types.rev131112.action.action.GroupActionCase")) {
415 Long groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
416 ListenableFuture<?> future = groupFutures.get(groupId);
417 if (future == null) {
421 // Need to ensure that the group specified
422 // by group-action is already installed.
423 awaitGroup(node, future);
427 // increment retry counter value
433 addGroup(groupFutures, group);
435 // resetting the counter to zero
441 /* installation of suspected groups */
442 if (!toBeInstalledGroups.isEmpty()) {
443 for (Group group : toBeInstalledGroups) {
445 "Installing the group {} finally although "
446 + "the port is not up after checking for {} times ",
447 group.getGroupId().toString(), provider.getReconciliationRetryCount());
448 addGroup(groupFutures, group);
452 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
453 : Collections.<Meter>emptyList();
454 for (Meter meter : meters) {
455 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
457 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
460 // Need to wait for all groups to be installed before adding
462 awaitGroups(node, groupFutures.values());
465 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
466 : Collections.<Table>emptyList();
468 for (Table table : tables) {
469 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
471 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
472 flowCount += flows.size();
473 for (Flow flow : flows) {
474 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
476 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
479 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
485 * Invoke add-group RPC, and put listenable future associated with the RPC into
489 * The map to store listenable futures associated with add-group RPC.
493 private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
494 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
495 final Long groupId = group.getGroupId().getValue();
496 ListenableFuture<?> future = JdkFutureAdapters
497 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
499 Futures.addCallback(future, new FutureCallback<Object>() {
501 public void onSuccess(Object result) {
502 if (LOG.isTraceEnabled()) {
503 LOG.trace("add-group RPC completed: node={}, id={}",
504 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
509 public void onFailure(Throwable cause) {
510 LOG.debug("add-group RPC failed: node={}, id={}",
511 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
513 }, MoreExecutors.directExecutor());
515 map.put(groupId, future);
519 * Wait for completion of add-group RPC.
522 * The identifier for the target node.
524 * Future associated with add-group RPC that installs the target
527 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
528 awaitGroups(nodeId, Collections.singleton(future));
532 * Wait for completion of add-group RPCs.
535 * The identifier for the target node.
537 * A collection of futures associated with add-group RPCs.
539 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
540 if (!futures.isEmpty()) {
541 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
543 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
544 LOG.trace("awaitGroups() completed: node={}", nodeId);
545 } catch (TimeoutException | InterruptedException | ExecutionException e) {
546 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
552 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
553 justification = "https://github.com/spotbugs/spotbugs/issues/811")
554 private BigInteger getDpnIdFromNodeName(String nodeName) {
556 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
557 return new BigInteger(dpId);
560 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
561 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
562 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
563 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
565 Optional<FlowCapableNode> flowNode = Optional.empty();
567 try (ReadTransaction trans = provider.getReadTransaction()) {
568 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
569 } catch (ExecutionException | InterruptedException e) {
570 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
573 if (flowNode.isPresent()) {
575 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
576 nodeIdent.toString());
577 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
578 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
579 : Collections.<Table>emptyList();
580 for (Table table : tables) {
581 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
583 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
584 : Collections.<StaleFlow>emptyList();
585 for (StaleFlow staleFlow : staleFlows) {
587 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
588 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
590 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
591 toBeDeletedFlow.key());
593 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
595 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
599 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
600 nodeIdent.toString());
602 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
603 // Flows are fully deleted
604 // before attempting to delete groups - just in case there are references
606 /* Stale-marked Groups - Can be deleted after flows */
607 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
608 : Collections.<StaleGroup>emptyList();
609 for (StaleGroup staleGroup : staleGroups) {
611 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
612 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
614 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
615 toBeDeletedGroup.key());
617 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
619 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
622 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
623 nodeIdent.toString());
624 /* Stale-marked Meters - can be deleted anytime - so least priority */
625 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
626 : Collections.<StaleMeter>emptyList();
628 for (StaleMeter staleMeter : staleMeters) {
630 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
631 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
633 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
634 toBeDeletedMeter.key());
636 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
638 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
643 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
644 nodeIdent.toString());
645 // Now, do the bulk deletions
646 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
647 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
648 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
651 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
652 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
654 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
655 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
658 FluentFuture<?> submitFuture = writeTransaction.commit();
659 handleStaleEntityDeletionResultFuture(submitFuture);
662 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
663 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
665 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
666 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
669 FluentFuture<?> submitFuture = writeTransaction.commit();
670 handleStaleEntityDeletionResultFuture(submitFuture);
673 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
674 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
676 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
677 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
680 FluentFuture<?> submitFuture = writeTransaction.commit();
681 handleStaleEntityDeletionResultFuture(submitFuture);
684 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
685 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
686 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
687 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
688 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
689 new StaleFlowKey(new FlowId(staleFlow.getId())));
692 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
693 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
694 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
695 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
698 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
699 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
700 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
701 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
704 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
705 justification = "https://github.com/spotbugs/spotbugs/issues/811")
706 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
707 final BundleId bundleIdValue,
708 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
709 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
710 for (Group group : flowNode.nonnullGroup()) {
711 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
712 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
715 for (Table table : flowNode.nonnullTable()) {
716 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
717 for (Flow flow : table.nonnullFlow()) {
718 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
719 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
722 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
726 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
727 submitFuture.addCallback(new FutureCallback<Object>() {
729 public void onSuccess(Object result) {
730 LOG.debug("Stale entity removal success");
734 public void onFailure(Throwable throwable) {
735 LOG.debug("Stale entity removal failed", throwable);
737 }, MoreExecutors.directExecutor());
740 private Flow getDeleteAllFlow() {
741 final FlowBuilder flowBuilder = new FlowBuilder();
742 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
743 return flowBuilder.build();
746 private Group getDeleteAllGroup() {
747 final GroupBuilder groupBuilder = new GroupBuilder();
748 groupBuilder.setGroupType(GroupTypes.GroupAll);
749 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
750 return groupBuilder.build();
753 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
754 justification = "https://github.com/spotbugs/spotbugs/issues/811")
755 private Messages createMessages(final NodeRef nodeRef) {
756 final List<Message> messages = new ArrayList<>();
757 messages.add(new MessageBuilder().setNode(nodeRef)
758 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
759 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
762 messages.add(new MessageBuilder().setNode(nodeRef)
763 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
764 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
766 return new MessagesBuilder().setMessage(messages).build();