2 * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.openflowplugin.applications.frm.impl;
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Lists;
12 import com.google.common.util.concurrent.FluentFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.JdkFutureAdapters;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import com.google.common.util.concurrent.ThreadFactoryBuilder;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.ListIterator;
28 import java.util.Optional;
29 import java.util.concurrent.Callable;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ThreadFactory;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.concurrent.atomic.AtomicLong;
38 import org.opendaylight.mdsal.binding.api.DataBroker;
39 import org.opendaylight.mdsal.binding.api.ReadTransaction;
40 import org.opendaylight.mdsal.binding.api.WriteTransaction;
41 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
42 import org.opendaylight.openflowplugin.api.OFConstants;
43 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
44 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
45 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
46 import org.opendaylight.openflowplugin.applications.frm.util.FrmUtil;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
89 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;
90 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;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
97 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
98 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
99 import org.opendaylight.yangtools.yang.common.RpcResult;
100 import org.opendaylight.yangtools.yang.common.Uint32;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
105 * Default implementation of {@link ForwardingRulesManager}.
107 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
109 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
111 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
112 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
114 // The number of nanoseconds to wait for a single group to be added.
115 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
117 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
118 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
119 private static final String SEPARATOR = ":";
120 private static final int THREAD_POOL_SIZE = 4;
121 private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
122 .setNameFormat("BundleResync-%d")
124 .setUncaughtExceptionHandler((thread, ex) -> LOG.error("Uncaught exception {}", thread, ex))
126 private final DataBroker dataBroker;
127 private final ForwardingRulesManager provider;
128 private final String serviceName;
129 private final int priority;
130 private final ResultState resultState;
131 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new ConcurrentHashMap<>();
133 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
135 private final SalBundleService salBundleService;
137 private static final AtomicLong BUNDLE_ID = new AtomicLong();
138 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
140 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
141 final String serviceName, final int priority, final ResultState resultState) {
142 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
143 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
144 this.serviceName = serviceName;
145 this.priority = priority;
146 this.resultState = resultState;
147 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
148 "salBundleService can not be null!");
152 public void close() {
153 if (executor != null) {
154 executor.shutdownNow();
159 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
160 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
161 // Clearing the group registry cache for the connected node if exists
162 String nodeId = FrmUtil.getNodeIdValueFromNodeIdentifier(connectedNode);
163 provider.getDevicesGroupRegistry().clearNodeGroups(nodeId);
164 if (provider.isStaleMarkingEnabled()) {
165 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
167 reconciliationPreProcess(connectedNode);
169 if (provider.isBundleBasedReconciliationEnabled()) {
170 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
171 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
173 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
174 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
178 private class BundleBasedReconciliationTask implements Callable<Boolean> {
179 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
181 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
182 nodeIdentity = nodeIdent;
186 public Boolean call() {
187 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
188 Optional<FlowCapableNode> flowNode = Optional.empty();
189 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
190 BigInteger dpnId = getDpnIdFromNodeName(node);
191 ExecutorService service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
192 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
193 try (ReadTransaction trans = provider.getReadTransaction()) {
194 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
195 } catch (ExecutionException | InterruptedException e) {
196 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
199 if (flowNode.isPresent()) {
200 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
201 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
202 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
204 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
205 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
206 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
208 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
209 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
210 .setType(BundleControlType.ONFBCTOPENREQUEST).build();
212 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
213 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
214 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
216 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
217 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
218 .setMessages(createMessages(nodeRef)).build();
220 LOG.debug("Closing openflow bundle for device {}", dpnId);
221 /* Close previously opened bundle on the openflow switch if any */
222 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
223 = salBundleService.controlBundle(closeBundleInput);
225 /* Open a new bundle on the switch */
226 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
227 Futures.transformAsync(closeBundle,
228 rpcResult -> salBundleService.controlBundle(openBundleInput),
231 /* Push groups and flows via bundle add messages */
232 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
233 = Futures.transformAsync(openBundle, rpcResult -> {
234 if (rpcResult.isSuccessful()) {
235 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
237 return Futures.immediateFuture(null);
240 /* Push flows and groups via bundle add messages */
241 Optional<FlowCapableNode> finalFlowNode = flowNode;
242 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
243 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
244 if (rpcResult.isSuccessful()) {
245 LOG.debug("Adding delete all flow/group message is successful for device {}",dpnId);
246 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
249 return Futures.immediateFuture(null);
252 /* Commit the bundle on the openflow switch */
253 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture = Futures.transformAsync(
254 addbundlesFuture, rpcResult -> {
255 LOG.debug("Adding bundle messages completed for device {}", dpnId);
256 return salBundleService.controlBundle(commitBundleInput);
259 /* Bundles not supported for meters */
260 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
261 : Collections.emptyList();
262 Futures.transformAsync(commitBundleFuture,
264 if (rpcResult.isSuccessful()) {
265 for (Meter meter : meters) {
266 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
267 .child(Meter.class, meter.key());
268 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
271 return Futures.immediateFuture(null);
274 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
275 if (bundleFuture != null && bundleFuture.isSuccessful()) {
276 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
277 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
280 LOG.error("commit bundle failed for device {} with error {}", dpnId,
281 commitBundleFuture.get().getErrors());
284 } catch (InterruptedException | ExecutionException e) {
285 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId);
289 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
298 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
299 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
300 .augmentation(FlowCapableNode.class);
301 // Clearing the group registry cache for the connected node if exists
302 provider.getDevicesGroupRegistry().clearNodeGroups(node.toString());
303 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
307 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
308 ListenableFuture<Boolean> listenableFuture = futureMap.computeIfPresent(node, (key, future) -> future);
309 if (listenableFuture != null) {
310 listenableFuture.cancel(true);
311 futureMap.remove(node);
313 return Futures.immediateFuture(true);
317 public int getPriority() {
322 public String getName() {
327 public ResultState getResultState() {
331 private class ReconciliationTask implements Callable<Boolean> {
333 InstanceIdentifier<FlowCapableNode> nodeIdentity;
335 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
336 nodeIdentity = nodeIdent;
340 public Boolean call() {
341 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
342 BigInteger dpnId = getDpnIdFromNodeName(node);
343 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
345 Optional<FlowCapableNode> flowNode;
346 // initialize the counter
348 try (ReadTransaction trans = provider.getReadTransaction()) {
349 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
350 } catch (ExecutionException | InterruptedException e) {
351 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
355 if (flowNode.isPresent()) {
356 /* Tables - have to be pushed before groups */
357 // CHECK if while pushing the update, updateTableInput can be null to emulate a
359 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
360 ? flowNode.get().getTableFeatures()
361 : Collections.<TableFeatures>emptyList();
362 for (TableFeatures tableFeaturesItem : tableList) {
363 TableFeaturesKey tableKey = tableFeaturesItem.key();
364 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
365 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
366 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
369 /* Groups - have to be first */
370 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
371 : Collections.<Group>emptyList();
372 List<Group> toBeInstalledGroups = new ArrayList<>();
373 toBeInstalledGroups.addAll(groups);
374 // new list for suspected groups pointing to ports .. when the ports come up
376 List<Group> suspectedGroups = new ArrayList<>();
377 Map<Uint32, ListenableFuture<?>> groupFutures = new HashMap<>();
379 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
380 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
381 // crossed the threshold
383 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
384 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
386 toBeInstalledGroups.addAll(suspectedGroups);
390 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
391 while (iterator.hasNext()) {
392 Group group = iterator.next();
393 boolean okToInstall = true;
394 Buckets buckets = group.getBuckets();
395 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
396 if (bucketList == null) {
397 bucketList = Collections.<Bucket>emptyList();
399 for (Bucket bucket : bucketList) {
400 List<Action> actions = bucket.getAction();
401 if (actions == null) {
402 actions = Collections.<Action>emptyList();
404 for (Action action : actions) {
406 if (action.getAction().implementedInterface().getName()
407 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
408 + ".action.types.rev131112.action.action.OutputActionCase")) {
409 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
410 .getOutputNodeConnector().getValue();
412 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
414 // check if the nodeconnector is there in the multimap
415 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
416 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
417 // if yes set okToInstall = true
422 // else put it in a different list and still set okToInstall = true
423 suspectedGroups.add(group);
425 "Not yet received the node-connector updated for {} "
426 + "for the group with id {}",
427 nodeConnectorUri, group.getGroupId());
430 } else if (action.getAction().implementedInterface().getName()
431 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
432 + ".action.types.rev131112.action.action.GroupActionCase")) {
434 Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction()
436 ListenableFuture<?> future = groupFutures.get(groupId);
437 if (future == null) {
441 // Need to ensure that the group specified
442 // by group-action is already installed.
443 awaitGroup(node, future);
447 // increment retry counter value
453 addGroup(groupFutures, group);
455 // resetting the counter to zero
461 /* installation of suspected groups */
462 if (!toBeInstalledGroups.isEmpty()) {
463 for (Group group : toBeInstalledGroups) {
465 "Installing the group {} finally although "
466 + "the port is not up after checking for {} times ",
467 group.getGroupId(), provider.getReconciliationRetryCount());
468 addGroup(groupFutures, group);
472 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
473 : Collections.<Meter>emptyList();
474 for (Meter meter : meters) {
475 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
477 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
480 // Need to wait for all groups to be installed before adding
482 awaitGroups(node, groupFutures.values());
485 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
486 : Collections.<Table>emptyList();
488 for (Table table : tables) {
489 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
491 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
492 flowCount += flows.size();
493 for (Flow flow : flows) {
494 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
496 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
499 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
505 * Invoke add-group RPC, and put listenable future associated with the RPC into
509 * The map to store listenable futures associated with add-group RPC.
513 private void addGroup(Map<Uint32, ListenableFuture<?>> map, Group group) {
514 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
515 final Uint32 groupId = group.getGroupId().getValue();
516 ListenableFuture<?> future = JdkFutureAdapters
517 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
519 Futures.addCallback(future, new FutureCallback<Object>() {
521 public void onSuccess(Object result) {
522 if (LOG.isTraceEnabled()) {
523 LOG.trace("add-group RPC completed: node={}, id={}",
524 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
529 public void onFailure(Throwable cause) {
530 LOG.debug("add-group RPC failed: node={}, id={}",
531 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
533 }, MoreExecutors.directExecutor());
535 map.put(groupId, future);
539 * Wait for completion of add-group RPC.
542 * The identifier for the target node.
544 * Future associated with add-group RPC that installs the target
547 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
548 awaitGroups(nodeId, Collections.singleton(future));
552 * Wait for completion of add-group RPCs.
555 * The identifier for the target node.
557 * A collection of futures associated with add-group RPCs.
559 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
560 if (!futures.isEmpty()) {
561 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
563 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
564 LOG.trace("awaitGroups() completed: node={}", nodeId);
565 } catch (TimeoutException | InterruptedException | ExecutionException e) {
566 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
572 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
573 justification = "https://github.com/spotbugs/spotbugs/issues/811")
574 private BigInteger getDpnIdFromNodeName(String nodeName) {
576 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
577 return new BigInteger(dpId);
580 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
581 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
582 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
583 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
585 Optional<FlowCapableNode> flowNode = Optional.empty();
587 try (ReadTransaction trans = provider.getReadTransaction()) {
588 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
589 } catch (ExecutionException | InterruptedException e) {
590 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
593 if (flowNode.isPresent()) {
595 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
597 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
598 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
599 : Collections.<Table>emptyList();
600 for (Table table : tables) {
601 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
603 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
604 : Collections.<StaleFlow>emptyList();
605 for (StaleFlow staleFlow : staleFlows) {
607 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
608 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
610 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
611 toBeDeletedFlow.key());
613 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
615 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
619 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
622 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
623 // Flows are fully deleted
624 // before attempting to delete groups - just in case there are references
626 /* Stale-marked Groups - Can be deleted after flows */
627 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
628 : Collections.<StaleGroup>emptyList();
629 for (StaleGroup staleGroup : staleGroups) {
631 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
632 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
634 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
635 toBeDeletedGroup.key());
637 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
639 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
642 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
644 /* Stale-marked Meters - can be deleted anytime - so least priority */
645 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
646 : Collections.<StaleMeter>emptyList();
648 for (StaleMeter staleMeter : staleMeters) {
650 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
651 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
653 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
654 toBeDeletedMeter.key());
656 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
658 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
663 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
665 // Now, do the bulk deletions
666 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
667 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
668 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
671 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
672 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
674 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
675 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
678 FluentFuture<?> submitFuture = writeTransaction.commit();
679 handleStaleEntityDeletionResultFuture(submitFuture);
682 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
683 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
685 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
686 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
689 FluentFuture<?> submitFuture = writeTransaction.commit();
690 handleStaleEntityDeletionResultFuture(submitFuture);
693 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
694 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
696 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
697 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
700 FluentFuture<?> submitFuture = writeTransaction.commit();
701 handleStaleEntityDeletionResultFuture(submitFuture);
704 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
705 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
706 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
707 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
708 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
709 new StaleFlowKey(new FlowId(staleFlow.getId())));
712 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
713 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
714 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
715 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
718 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
719 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
720 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
721 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
724 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
725 justification = "https://github.com/spotbugs/spotbugs/issues/811")
726 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
727 final BundleId bundleIdValue,
728 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
729 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
730 for (Group group : flowNode.nonnullGroup()) {
731 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
732 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
735 for (Table table : flowNode.nonnullTable()) {
736 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
737 for (Flow flow : table.nonnullFlow()) {
738 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
739 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
742 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
746 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
747 submitFuture.addCallback(new FutureCallback<Object>() {
749 public void onSuccess(Object result) {
750 LOG.debug("Stale entity removal success");
754 public void onFailure(Throwable throwable) {
755 LOG.debug("Stale entity removal failed", throwable);
757 }, MoreExecutors.directExecutor());
760 private Flow getDeleteAllFlow() {
761 final FlowBuilder flowBuilder = new FlowBuilder();
762 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
763 return flowBuilder.build();
766 private Group getDeleteAllGroup() {
767 final GroupBuilder groupBuilder = new GroupBuilder();
768 groupBuilder.setGroupType(GroupTypes.GroupAll);
769 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
770 return groupBuilder.build();
773 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
774 justification = "https://github.com/spotbugs/spotbugs/issues/811")
775 private Messages createMessages(final NodeRef nodeRef) {
776 final List<Message> messages = new ArrayList<>();
777 messages.add(new MessageBuilder().setNode(nodeRef)
778 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
779 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
782 messages.add(new MessageBuilder().setNode(nodeRef)
783 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
784 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
786 return new MessagesBuilder().setMessage(messages).build();