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.openflowplugin.applications.frm.util.FrmUtil;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
87 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;
88 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;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
95 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
96 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
97 import org.opendaylight.yangtools.yang.common.RpcResult;
98 import org.opendaylight.yangtools.yang.common.Uint32;
99 import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
103 * Default implementation of {@link ForwardingRulesManager}.
105 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
107 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
109 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
110 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
112 // The number of nanoseconds to wait for a single group to be added.
113 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
115 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
116 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
117 private static final String SEPARATOR = ":";
118 private static final int THREAD_POOL_SIZE = 4;
120 private final DataBroker dataBroker;
121 private final ForwardingRulesManager provider;
122 private final String serviceName;
123 private final int priority;
124 private final ResultState resultState;
125 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
127 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
129 private final SalBundleService salBundleService;
131 private static final AtomicLong BUNDLE_ID = new AtomicLong();
132 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
134 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
135 final String serviceName, final int priority, final ResultState resultState) {
136 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
137 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
138 this.serviceName = serviceName;
139 this.priority = priority;
140 this.resultState = resultState;
141 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
142 "salBundleService can not be null!");
146 public void close() {
147 if (executor != null) {
148 executor.shutdownNow();
153 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
154 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
155 // Clearing the group registry cache for the connected node if exists
156 NodeId nodeId = FrmUtil.getNodeIdFromNodeIdentifier(connectedNode);
157 provider.getDevicesGroupRegistry().clearNodeGroups(nodeId);
158 if (provider.isStaleMarkingEnabled()) {
159 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
161 reconciliationPreProcess(connectedNode);
163 if (provider.isBundleBasedReconciliationEnabled()) {
164 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
165 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
167 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
168 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
172 private class BundleBasedReconciliationTask implements Callable<Boolean> {
173 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
175 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
176 nodeIdentity = nodeIdent;
180 public Boolean call() {
181 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
182 Optional<FlowCapableNode> flowNode = Optional.empty();
183 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
184 BigInteger dpnId = getDpnIdFromNodeName(node);
185 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
186 try (ReadTransaction trans = provider.getReadTransaction()) {
187 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
188 } catch (ExecutionException | InterruptedException e) {
189 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
192 if (flowNode.isPresent()) {
193 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
194 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
195 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
197 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
198 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
199 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
201 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
202 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
205 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
206 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
207 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
209 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
210 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
211 .setMessages(createMessages(nodeRef)).build();
213 LOG.debug("Closing openflow bundle for device {}", dpnId);
214 /* Close previously opened bundle on the openflow switch if any */
215 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
216 = salBundleService.controlBundle(closeBundleInput);
218 /* Open a new bundle on the switch */
219 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
220 Futures.transformAsync(closeBundle,
221 rpcResult -> salBundleService.controlBundle(openBundleInput),
222 MoreExecutors.directExecutor());
224 /* Push groups and flows via bundle add messages */
225 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
226 = Futures.transformAsync(openBundle, rpcResult -> {
227 if (rpcResult.isSuccessful()) {
228 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
230 return Futures.immediateFuture(null);
231 }, MoreExecutors.directExecutor());
233 /* Push flows and groups via bundle add messages */
234 Optional<FlowCapableNode> finalFlowNode = flowNode;
235 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
236 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
237 if (rpcResult.isSuccessful()) {
238 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
239 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
242 return Futures.immediateFuture(null);
243 }, MoreExecutors.directExecutor());
245 /* Commit the bundle on the openflow switch */
246 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture = Futures.transformAsync(
247 addbundlesFuture, rpcResult -> {
248 LOG.debug("Adding bundle messages completed for device {}", dpnId);
249 return salBundleService.controlBundle(commitBundleInput);
250 }, MoreExecutors.directExecutor());
252 /* Bundles not supported for meters */
253 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
254 : Collections.emptyList();
255 Futures.transformAsync(commitBundleFuture,
257 if (rpcResult.isSuccessful()) {
258 for (Meter meter : meters) {
259 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
260 .child(Meter.class, meter.key());
261 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
264 return Futures.immediateFuture(null);
265 }, MoreExecutors.directExecutor());
267 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
268 if (bundleFuture != null && bundleFuture.isSuccessful()) {
269 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
270 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
273 LOG.error("commit bundle failed for device {} with error {}", dpnId,
274 commitBundleFuture.get().getErrors());
277 } catch (InterruptedException | ExecutionException e) {
278 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId);
282 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
288 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
289 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
290 .augmentation(FlowCapableNode.class);
291 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
295 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
296 ListenableFuture<Boolean> listenableFuture = futureMap.computeIfPresent(node, (key, future) -> future);
297 if (listenableFuture != null) {
298 listenableFuture.cancel(true);
299 futureMap.remove(node);
301 return Futures.immediateFuture(true);
305 public int getPriority() {
310 public String getName() {
315 public ResultState getResultState() {
319 private class ReconciliationTask implements Callable<Boolean> {
321 InstanceIdentifier<FlowCapableNode> nodeIdentity;
323 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
324 nodeIdentity = nodeIdent;
328 public Boolean call() {
329 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
330 BigInteger dpnId = getDpnIdFromNodeName(node);
331 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
333 Optional<FlowCapableNode> flowNode;
334 // initialize the counter
336 try (ReadTransaction trans = provider.getReadTransaction()) {
337 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
338 } catch (ExecutionException | InterruptedException e) {
339 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
343 if (flowNode.isPresent()) {
344 /* Tables - have to be pushed before groups */
345 // CHECK if while pushing the update, updateTableInput can be null to emulate a
347 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
348 ? flowNode.get().getTableFeatures()
349 : Collections.<TableFeatures>emptyList();
350 for (TableFeatures tableFeaturesItem : tableList) {
351 TableFeaturesKey tableKey = tableFeaturesItem.key();
352 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
353 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
354 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
357 /* Groups - have to be first */
358 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
359 : Collections.<Group>emptyList();
360 List<Group> toBeInstalledGroups = new ArrayList<>();
361 toBeInstalledGroups.addAll(groups);
362 // new list for suspected groups pointing to ports .. when the ports come up
364 List<Group> suspectedGroups = new ArrayList<>();
365 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
367 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
368 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
369 // crossed the threshold
371 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
372 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
374 toBeInstalledGroups.addAll(suspectedGroups);
378 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
379 while (iterator.hasNext()) {
380 Group group = iterator.next();
381 boolean okToInstall = true;
382 Buckets buckets = group.getBuckets();
383 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
384 if (bucketList == null) {
385 bucketList = Collections.<Bucket>emptyList();
387 for (Bucket bucket : bucketList) {
388 List<Action> actions = bucket.getAction();
389 if (actions == null) {
390 actions = Collections.<Action>emptyList();
392 for (Action action : actions) {
394 if (action.getAction().implementedInterface().getName()
395 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
396 + ".action.types.rev131112.action.action.OutputActionCase")) {
397 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
398 .getOutputNodeConnector().getValue();
400 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
402 // check if the nodeconnector is there in the multimap
403 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
404 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
405 // if yes set okToInstall = true
410 // else put it in a different list and still set okToInstall = true
411 suspectedGroups.add(group);
413 "Not yet received the node-connector updated for {} "
414 + "for the group with id {}",
415 nodeConnectorUri, group.getGroupId());
418 } else if (action.getAction().implementedInterface().getName()
419 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
420 + ".action.types.rev131112.action.action.GroupActionCase")) {
422 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
424 ListenableFuture<?> future = groupFutures.get(groupId);
425 if (future == null) {
429 // Need to ensure that the group specified
430 // by group-action is already installed.
431 awaitGroup(node, future);
435 // increment retry counter value
441 addGroup(groupFutures, group);
443 // resetting the counter to zero
449 /* installation of suspected groups */
450 if (!toBeInstalledGroups.isEmpty()) {
451 for (Group group : toBeInstalledGroups) {
453 "Installing the group {} finally although "
454 + "the port is not up after checking for {} times ",
455 group.getGroupId(), provider.getReconciliationRetryCount());
456 addGroup(groupFutures, group);
460 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
461 : Collections.<Meter>emptyList();
462 for (Meter meter : meters) {
463 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
465 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
468 // Need to wait for all groups to be installed before adding
470 awaitGroups(node, groupFutures.values());
473 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
474 : Collections.<Table>emptyList();
476 for (Table table : tables) {
477 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
479 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
480 flowCount += flows.size();
481 for (Flow flow : flows) {
482 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
484 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
487 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
493 * Invoke add-group RPC, and put listenable future associated with the RPC into
497 * The map to store listenable futures associated with add-group RPC.
501 private void addGroup(Map<Uint32, ListenableFuture<?>> map, Group group) {
502 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
503 final Uint32 groupId = group.getGroupId().getValue();
504 ListenableFuture<?> future = JdkFutureAdapters
505 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
507 Futures.addCallback(future, new FutureCallback<Object>() {
509 public void onSuccess(Object result) {
510 if (LOG.isTraceEnabled()) {
511 LOG.trace("add-group RPC completed: node={}, id={}",
512 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
517 public void onFailure(Throwable cause) {
518 LOG.debug("add-group RPC failed: node={}, id={}",
519 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
521 }, MoreExecutors.directExecutor());
523 map.put(groupId, future);
527 * Wait for completion of add-group RPC.
530 * The identifier for the target node.
532 * Future associated with add-group RPC that installs the target
535 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
536 awaitGroups(nodeId, Collections.singleton(future));
540 * Wait for completion of add-group RPCs.
543 * The identifier for the target node.
545 * A collection of futures associated with add-group RPCs.
547 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
548 if (!futures.isEmpty()) {
549 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
551 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
552 LOG.trace("awaitGroups() completed: node={}", nodeId);
553 } catch (TimeoutException | InterruptedException | ExecutionException e) {
554 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
560 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
561 justification = "https://github.com/spotbugs/spotbugs/issues/811")
562 private BigInteger getDpnIdFromNodeName(String nodeName) {
564 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
565 return new BigInteger(dpId);
568 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
569 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
570 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
571 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
573 Optional<FlowCapableNode> flowNode = Optional.empty();
575 try (ReadTransaction trans = provider.getReadTransaction()) {
576 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
577 } catch (ExecutionException | InterruptedException e) {
578 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
581 if (flowNode.isPresent()) {
583 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
585 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
586 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
587 : Collections.<Table>emptyList();
588 for (Table table : tables) {
589 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
591 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
592 : Collections.<StaleFlow>emptyList();
593 for (StaleFlow staleFlow : staleFlows) {
595 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
596 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
598 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
599 toBeDeletedFlow.key());
601 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
603 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
607 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
610 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
611 // Flows are fully deleted
612 // before attempting to delete groups - just in case there are references
614 /* Stale-marked Groups - Can be deleted after flows */
615 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
616 : Collections.<StaleGroup>emptyList();
617 for (StaleGroup staleGroup : staleGroups) {
619 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
620 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
622 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
623 toBeDeletedGroup.key());
625 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
627 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
630 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
632 /* Stale-marked Meters - can be deleted anytime - so least priority */
633 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
634 : Collections.<StaleMeter>emptyList();
636 for (StaleMeter staleMeter : staleMeters) {
638 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
639 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
641 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
642 toBeDeletedMeter.key());
644 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
646 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
651 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
653 // Now, do the bulk deletions
654 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
655 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
656 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
659 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
660 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
662 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
663 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
666 FluentFuture<?> submitFuture = writeTransaction.commit();
667 handleStaleEntityDeletionResultFuture(submitFuture);
670 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
671 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
673 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
674 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
677 FluentFuture<?> submitFuture = writeTransaction.commit();
678 handleStaleEntityDeletionResultFuture(submitFuture);
681 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
682 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
684 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
685 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
688 FluentFuture<?> submitFuture = writeTransaction.commit();
689 handleStaleEntityDeletionResultFuture(submitFuture);
692 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
693 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
694 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
695 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
696 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
697 new StaleFlowKey(new FlowId(staleFlow.getId())));
700 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
701 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
702 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
703 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
706 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
707 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
708 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
709 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
712 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
713 justification = "https://github.com/spotbugs/spotbugs/issues/811")
714 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
715 final BundleId bundleIdValue,
716 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
717 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
718 for (Group group : flowNode.nonnullGroup()) {
719 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
720 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
723 for (Table table : flowNode.nonnullTable()) {
724 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
725 for (Flow flow : table.nonnullFlow()) {
726 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
727 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
730 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
734 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
735 submitFuture.addCallback(new FutureCallback<Object>() {
737 public void onSuccess(Object result) {
738 LOG.debug("Stale entity removal success");
742 public void onFailure(Throwable throwable) {
743 LOG.debug("Stale entity removal failed", throwable);
745 }, MoreExecutors.directExecutor());
748 private Flow getDeleteAllFlow() {
749 final FlowBuilder flowBuilder = new FlowBuilder();
750 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
751 return flowBuilder.build();
754 private Group getDeleteAllGroup() {
755 final GroupBuilder groupBuilder = new GroupBuilder();
756 groupBuilder.setGroupType(GroupTypes.GroupAll);
757 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
758 return groupBuilder.build();
761 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
762 justification = "https://github.com/spotbugs/spotbugs/issues/811")
763 private Messages createMessages(final NodeRef nodeRef) {
764 final List<Message> messages = new ArrayList<>();
765 messages.add(new MessageBuilder().setNode(nodeRef)
766 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
767 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
770 messages.add(new MessageBuilder().setNode(nodeRef)
771 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
772 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
774 return new MessagesBuilder().setMessage(messages).build();