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
9 package org.opendaylight.openflowplugin.applications.frm.impl;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.JdkFutureAdapters;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
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.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.controller.md.sal.binding.api.DataBroker;
36 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
37 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.openflowplugin.api.OFConstants;
41 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
42 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
43 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
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.NodeRef;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
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.BundleAddFlowCaseBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddGroupCaseBuilder;
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.add.flow._case.AddFlowCaseDataBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.group._case.AddGroupCaseDataBuilder;
91 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;
92 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;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
99 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
100 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
101 import org.opendaylight.yangtools.yang.common.RpcResult;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
106 * Default implementation of {@link ForwardingRulesManager}.
108 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
110 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
112 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
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;
122 private final DataBroker dataBroker;
123 private final ForwardingRulesManager provider;
124 private final String serviceName;
125 private final int priority;
126 private final ResultState resultState;
127 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
129 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
131 private final SalBundleService salBundleService;
133 private static final AtomicLong BUNDLE_ID = new AtomicLong();
134 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
136 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
137 final String serviceName, final int priority, final ResultState resultState) {
138 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
139 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
140 this.serviceName = serviceName;
141 this.priority = priority;
142 this.resultState = resultState;
143 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
144 "salBundleService can not be null!");
148 public void close() {
149 if (executor != null) {
150 executor.shutdownNow();
155 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
156 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
157 if (provider.isStaleMarkingEnabled()) {
158 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
159 connectedNode.toString());
160 reconciliationPreProcess(connectedNode);
162 LOG.debug("Bundle based reconciliation status : {}",
163 provider.isBundleBasedReconciliationEnabled() ? "Enable" : "Disable");
164 if (provider.isBundleBasedReconciliationEnabled()) {
165 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
166 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
168 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
169 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
173 private class BundleBasedReconciliationTask implements Callable<Boolean> {
174 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
176 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
177 nodeIdentity = nodeIdent;
181 public Boolean call() {
182 String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
183 Optional<FlowCapableNode> flowNode = Optional.absent();
184 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
185 BigInteger dpnId = getDpnIdFromNodeName(node);
186 LOG.debug("Triggering bundle based reconciliation for device :{}", dpnId);
187 ReadOnlyTransaction trans = provider.getReadTranaction();
189 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
190 } catch (ExecutionException | InterruptedException e) {
191 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
194 if (flowNode.isPresent()) {
195 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
196 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
198 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
199 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
202 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
203 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
204 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
206 final AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
207 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
208 .setMessages(createMessages(nodeRef, flowNode)).build();
210 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle
211 = salBundleService.controlBundle(openBundleInput);
213 ListenableFuture<RpcResult<AddBundleMessagesOutput>> addBundleMessagesFuture = Futures
214 .transformAsync(JdkFutureAdapters.listenInPoolThread(openBundle), rpcResult -> {
215 if (rpcResult.isSuccessful()) {
216 return JdkFutureAdapters
217 .listenInPoolThread(salBundleService.addBundleMessages(addBundleMessagesInput));
219 return Futures.immediateFuture(null);
220 }, MoreExecutors.directExecutor());
221 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture
222 = Futures.transformAsync(addBundleMessagesFuture, rpcResult -> {
223 if (rpcResult.isSuccessful()) {
224 return JdkFutureAdapters
225 .listenInPoolThread(salBundleService.controlBundle(commitBundleInput));
227 return Futures.immediateFuture(null);
228 }, MoreExecutors.directExecutor());
230 /* Bundles not supported for meters */
231 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
232 : Collections.emptyList();
233 Futures.transformAsync(commitBundleFuture,
235 if (rpcResult.isSuccessful()) {
236 for (Meter meter : meters) {
237 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
238 .child(Meter.class, meter.getKey());
239 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
242 return Futures.immediateFuture(null);
243 }, MoreExecutors.directExecutor());
247 if (commitBundleFuture.get().isSuccessful()) {
248 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
253 } catch (InterruptedException | ExecutionException e) {
254 LOG.error("Error while doing bundle based reconciliation for device ID:{}", nodeIdentity);
258 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
264 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
265 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
266 .augmentation(FlowCapableNode.class);
267 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
271 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
272 futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
273 futureMap.remove(node);
274 return Futures.immediateFuture(true);
278 public int getPriority() {
283 public String getName() {
288 public ResultState getResultState() {
292 private class ReconciliationTask implements Callable<Boolean> {
294 InstanceIdentifier<FlowCapableNode> nodeIdentity;
296 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
297 nodeIdentity = nodeIdent;
301 public Boolean call() {
302 String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
303 BigInteger dpnId = getDpnIdFromNodeName(node);
305 ReadOnlyTransaction trans = provider.getReadTranaction();
306 Optional<FlowCapableNode> flowNode;
307 // initialize the counter
310 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
311 } catch (ExecutionException | InterruptedException e) {
312 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
316 if (flowNode.isPresent()) {
317 /* Tables - have to be pushed before groups */
318 // CHECK if while pushing the update, updateTableInput can be null to emulate a
320 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
321 ? flowNode.get().getTableFeatures()
322 : Collections.<TableFeatures>emptyList();
323 for (TableFeatures tableFeaturesItem : tableList) {
324 TableFeaturesKey tableKey = tableFeaturesItem.getKey();
325 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
326 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
327 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
330 /* Groups - have to be first */
331 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
332 : Collections.<Group>emptyList();
333 List<Group> toBeInstalledGroups = new ArrayList<>();
334 toBeInstalledGroups.addAll(groups);
335 // new list for suspected groups pointing to ports .. when the ports come up
337 List<Group> suspectedGroups = new ArrayList<>();
338 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
340 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
341 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
342 // crossed the threshold
344 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
345 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
346 suspectedGroups.toString());
347 toBeInstalledGroups.addAll(suspectedGroups);
351 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
352 while (iterator.hasNext()) {
353 Group group = iterator.next();
354 boolean okToInstall = true;
355 Buckets buckets = group.getBuckets();
356 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
357 if (bucketList == null) {
358 bucketList = Collections.<Bucket>emptyList();
360 for (Bucket bucket : bucketList) {
361 List<Action> actions = bucket.getAction();
362 if (actions == null) {
363 actions = Collections.<Action>emptyList();
365 for (Action action : actions) {
367 if (action.getAction().getImplementedInterface().getName()
368 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
369 + ".action.types.rev131112.action.action.OutputActionCase")) {
370 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
371 .getOutputNodeConnector().getValue();
373 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
375 // check if the nodeconnector is there in the multimap
376 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
377 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
378 // if yes set okToInstall = true
383 // else put it in a different list and still set okToInstall = true
384 suspectedGroups.add(group);
386 "Not yet received the node-connector updated for {} "
387 + "for the group with id {}",
388 nodeConnectorUri, group.getGroupId().toString());
391 } else if (action.getAction().getImplementedInterface().getName()
392 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
393 + ".action.types.rev131112.action.action.GroupActionCase")) {
395 Long groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
396 ListenableFuture<?> future = groupFutures.get(groupId);
397 if (future == null) {
401 // Need to ensure that the group specified
402 // by group-action is already installed.
403 awaitGroup(node, future);
407 // increment retry counter value
413 addGroup(groupFutures, group);
415 // resetting the counter to zero
421 /* installation of suspected groups */
422 if (!toBeInstalledGroups.isEmpty()) {
423 for (Group group : toBeInstalledGroups) {
425 "Installing the group {} finally although "
426 + "the port is not up after checking for {} times ",
427 group.getGroupId().toString(), provider.getReconciliationRetryCount());
428 addGroup(groupFutures, group);
432 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
433 : Collections.<Meter>emptyList();
434 for (Meter meter : meters) {
435 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
437 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
440 // Need to wait for all groups to be installed before adding
442 awaitGroups(node, groupFutures.values());
445 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
446 : Collections.<Table>emptyList();
447 for (Table table : tables) {
448 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
450 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
451 for (Flow flow : flows) {
452 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
454 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
458 /* clean transaction */
464 * Invoke add-group RPC, and put listenable future associated with the RPC into
468 * The map to store listenable futures associated with add-group RPC.
472 private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
473 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.getKey());
474 final Long groupId = group.getGroupId().getValue();
475 ListenableFuture<?> future = JdkFutureAdapters
476 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
478 Futures.addCallback(future, new FutureCallback<Object>() {
480 public void onSuccess(Object result) {
481 if (LOG.isTraceEnabled()) {
482 LOG.trace("add-group RPC completed: node={}, id={}",
483 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
488 public void onFailure(Throwable cause) {
489 String msg = "add-group RPC failed: node=" + nodeIdentity.firstKeyOf(Node.class).getId().getValue()
491 LOG.debug(msg, cause);
493 }, MoreExecutors.directExecutor());
495 map.put(groupId, future);
499 * Wait for completion of add-group RPC.
502 * The identifier for the target node.
504 * Future associated with add-group RPC that installs the target
507 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
508 awaitGroups(nodeId, Collections.singleton(future));
512 * Wait for completion of add-group RPCs.
515 * The identifier for the target node.
517 * A collection of futures associated with add-group RPCs.
519 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
520 if (!futures.isEmpty()) {
521 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
523 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
524 LOG.trace("awaitGroups() completed: node={}", nodeId);
525 } catch (TimeoutException | InterruptedException | ExecutionException e) {
526 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
532 private BigInteger getDpnIdFromNodeName(String nodeName) {
534 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
535 return new BigInteger(dpId);
538 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
539 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
540 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
541 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
543 ReadOnlyTransaction trans = provider.getReadTranaction();
544 Optional<FlowCapableNode> flowNode = Optional.absent();
547 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
548 } catch (ExecutionException | InterruptedException e) {
549 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
552 if (flowNode.isPresent()) {
554 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
555 nodeIdent.toString());
556 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
557 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
558 : Collections.<Table>emptyList();
559 for (Table table : tables) {
560 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
562 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
563 : Collections.<StaleFlow>emptyList();
564 for (StaleFlow staleFlow : staleFlows) {
566 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
567 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
569 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
570 toBeDeletedFlow.getKey());
572 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
574 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
578 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
579 nodeIdent.toString());
581 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
582 // Flows are fully deleted
583 // before attempting to delete groups - just in case there are references
585 /* Stale-marked Groups - Can be deleted after flows */
586 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
587 : Collections.<StaleGroup>emptyList();
588 for (StaleGroup staleGroup : staleGroups) {
590 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
591 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
593 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
594 toBeDeletedGroup.getKey());
596 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
598 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
601 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
602 nodeIdent.toString());
603 /* Stale-marked Meters - can be deleted anytime - so least priority */
604 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
605 : Collections.<StaleMeter>emptyList();
607 for (StaleMeter staleMeter : staleMeters) {
609 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
610 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
612 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
613 toBeDeletedMeter.getKey());
615 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
617 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
621 /* clean transaction */
624 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
625 nodeIdent.toString());
626 // Now, do the bulk deletions
627 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
628 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
629 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
632 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
633 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
635 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
636 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
639 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
640 handleStaleEntityDeletionResultFuture(submitFuture);
643 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
644 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
646 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
647 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
650 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
651 handleStaleEntityDeletionResultFuture(submitFuture);
654 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
655 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
657 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
658 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
661 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
662 handleStaleEntityDeletionResultFuture(submitFuture);
665 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
666 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
667 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
668 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
669 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
670 new StaleFlowKey(new FlowId(staleFlow.getId())));
673 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
674 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
675 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
676 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
679 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
680 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
681 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
682 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
685 private void handleStaleEntityDeletionResultFuture(
686 CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
687 Futures.addCallback(submitFuture, new FutureCallback<Void>() {
689 public void onSuccess(Void result) {
690 LOG.debug("Stale entity removal success");
694 public void onFailure(Throwable throwable) {
695 LOG.debug("Stale entity removal failed {}", throwable);
697 }, MoreExecutors.directExecutor());
700 private Flow getDeleteAllFlow() {
701 final FlowBuilder flowBuilder = new FlowBuilder();
702 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
703 return flowBuilder.build();
706 private Group getDeleteAllGroup() {
707 final GroupBuilder groupBuilder = new GroupBuilder();
708 groupBuilder.setGroupType(GroupTypes.GroupAll);
709 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
710 return groupBuilder.build();
713 private Messages createMessages(final NodeRef nodeRef, final Optional<FlowCapableNode> flowNode) {
714 final List<Message> messages = new ArrayList<>();
715 messages.add(new MessageBuilder().setNode(nodeRef)
716 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
717 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
720 messages.add(new MessageBuilder().setNode(nodeRef)
721 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
722 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
725 if (flowNode.get().getGroup() != null) {
726 for (Group gr : flowNode.get().getGroup()) {
727 messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddGroupCaseBuilder()
728 .setAddGroupCaseData(new AddGroupCaseDataBuilder(gr).build()).build()).build());
732 if (flowNode.get().getTable() != null) {
733 for (Table table : flowNode.get().getTable()) {
734 for (Flow flow : table.getFlow()) {
736 new MessageBuilder().setNode(nodeRef)
737 .setBundleInnerMessage(new BundleAddFlowCaseBuilder()
738 .setAddFlowCaseData(new AddFlowCaseDataBuilder(flow).build()).build())
744 LOG.debug("The size of the flows and group messages created in createMessage() {}", messages.size());
745 return new MessagesBuilder().setMessage(messages).build();