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 java.math.BigInteger;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.ListIterator;
26 import java.util.Optional;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.TimeoutException;
33 import java.util.concurrent.atomic.AtomicLong;
34 import org.opendaylight.mdsal.binding.api.DataBroker;
35 import org.opendaylight.mdsal.binding.api.ReadTransaction;
36 import org.opendaylight.mdsal.binding.api.WriteTransaction;
37 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
38 import org.opendaylight.openflowplugin.api.OFConstants;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
40 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
41 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
84 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;
85 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;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
92 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
93 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
94 import org.opendaylight.yangtools.yang.common.RpcResult;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
99 * Default implementation of {@link ForwardingRulesManager}.
101 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
103 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
105 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
106 private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
108 // The number of nanoseconds to wait for a single group to be added.
109 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
111 // The maximum number of nanoseconds to wait for completion of add-group RPCs.
112 private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
113 private static final String SEPARATOR = ":";
114 private static final int THREAD_POOL_SIZE = 4;
116 private final DataBroker dataBroker;
117 private final ForwardingRulesManager provider;
118 private final String serviceName;
119 private final int priority;
120 private final ResultState resultState;
121 private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
123 private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
125 private final SalBundleService salBundleService;
127 private static final AtomicLong BUNDLE_ID = new AtomicLong();
128 private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
130 public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
131 final String serviceName, final int priority, final ResultState resultState) {
132 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
133 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
134 this.serviceName = serviceName;
135 this.priority = priority;
136 this.resultState = resultState;
137 salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
138 "salBundleService can not be null!");
142 public void close() {
143 if (executor != null) {
144 executor.shutdownNow();
149 public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
150 LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
151 if (provider.isStaleMarkingEnabled()) {
152 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
153 connectedNode.toString());
154 reconciliationPreProcess(connectedNode);
156 if (provider.isBundleBasedReconciliationEnabled()) {
157 BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
158 return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
160 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
161 return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
165 private class BundleBasedReconciliationTask implements Callable<Boolean> {
166 final InstanceIdentifier<FlowCapableNode> nodeIdentity;
168 BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
169 nodeIdentity = nodeIdent;
173 public Boolean call() {
174 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
175 Optional<FlowCapableNode> flowNode = Optional.empty();
176 BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
177 BigInteger dpnId = getDpnIdFromNodeName(node);
178 LOG.info("Triggering bundle based reconciliation for device : {}", dpnId);
179 try (ReadTransaction trans = provider.getReadTransaction()) {
180 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
181 } catch (ExecutionException | InterruptedException e) {
182 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
185 if (flowNode.isPresent()) {
186 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
187 OF_EVENT_LOG.debug("Bundle Reconciliation Start, Node: {}", dpnId);
188 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
190 final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
191 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
192 .setType(BundleControlType.ONFBCTCLOSEREQUEST).build();
194 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
195 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
198 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
199 .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
200 .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
202 final AddBundleMessagesInput deleteAllFlowGroupsInput = new AddBundleMessagesInputBuilder()
203 .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
204 .setMessages(createMessages(nodeRef)).build();
206 LOG.debug("Closing openflow bundle for device {}", dpnId);
207 /* Close previously opened bundle on the openflow switch if any */
208 ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle
209 = salBundleService.controlBundle(closeBundleInput);
211 /* Open a new bundle on the switch */
212 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle =
213 Futures.transformAsync(closeBundle,
214 rpcResult -> salBundleService.controlBundle(openBundleInput),
215 MoreExecutors.directExecutor());
217 /* Push groups and flows via bundle add messages */
218 ListenableFuture<RpcResult<AddBundleMessagesOutput>> deleteAllFlowGroupsFuture
219 = Futures.transformAsync(openBundle, rpcResult -> {
220 if (rpcResult.isSuccessful()) {
221 return salBundleService.addBundleMessages(deleteAllFlowGroupsInput);
223 return Futures.immediateFuture(null);
224 }, MoreExecutors.directExecutor());
226 /* Push flows and groups via bundle add messages */
227 Optional<FlowCapableNode> finalFlowNode = flowNode;
228 ListenableFuture<List<RpcResult<AddBundleMessagesOutput>>> addbundlesFuture
229 = Futures.transformAsync(deleteAllFlowGroupsFuture, rpcResult -> {
230 if (rpcResult.isSuccessful()) {
231 LOG.debug("Adding delete all flow/group message is successful for device {}", dpnId);
232 return Futures.allAsList(addBundleMessages(finalFlowNode.get(), bundleIdValue,
235 return Futures.immediateFuture(null);
236 }, MoreExecutors.directExecutor());
238 /* Commit the bundle on the openflow switch */
239 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture
240 = Futures.transformAsync(addbundlesFuture, rpcResult ->
241 salBundleService.controlBundle(commitBundleInput), MoreExecutors.directExecutor());
243 /* Bundles not supported for meters */
244 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
245 : Collections.emptyList();
246 Futures.transformAsync(commitBundleFuture,
248 if (rpcResult.isSuccessful()) {
249 for (Meter meter : meters) {
250 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
251 .child(Meter.class, meter.key());
252 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
255 return Futures.immediateFuture(null);
256 }, MoreExecutors.directExecutor());
258 RpcResult<ControlBundleOutput> bundleFuture = commitBundleFuture.get();
259 if (bundleFuture != null && bundleFuture.isSuccessful()) {
260 LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
261 OF_EVENT_LOG.debug("Bundle Reconciliation Finish, Node: {}", dpnId);
266 } catch (InterruptedException | ExecutionException e) {
267 LOG.error("Error while doing bundle based reconciliation for device ID:{}", dpnId);
271 LOG.error("FlowNode not present for Datapath ID {}", dpnId);
277 public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
278 InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
279 .augmentation(FlowCapableNode.class);
280 // Clearing the group registry cache for the connected node if exists
281 provider.getDevicesGroupRegistry().clearNodeGroups(node.getNodeId());
282 return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
286 public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
287 futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
288 futureMap.remove(node);
289 return Futures.immediateFuture(true);
293 public int getPriority() {
298 public String getName() {
303 public ResultState getResultState() {
307 private class ReconciliationTask implements Callable<Boolean> {
309 InstanceIdentifier<FlowCapableNode> nodeIdentity;
311 ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
312 nodeIdentity = nodeIdent;
316 public Boolean call() {
317 String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
318 BigInteger dpnId = getDpnIdFromNodeName(node);
319 OF_EVENT_LOG.debug("Reconciliation Start, Node: {}", dpnId);
321 Optional<FlowCapableNode> flowNode;
322 // initialize the counter
324 try (ReadTransaction trans = provider.getReadTransaction()) {
325 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
326 } catch (ExecutionException | InterruptedException e) {
327 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
331 if (flowNode.isPresent()) {
332 /* Tables - have to be pushed before groups */
333 // CHECK if while pushing the update, updateTableInput can be null to emulate a
335 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
336 ? flowNode.get().getTableFeatures()
337 : Collections.<TableFeatures>emptyList();
338 for (TableFeatures tableFeaturesItem : tableList) {
339 TableFeaturesKey tableKey = tableFeaturesItem.key();
340 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
341 .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
342 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
345 /* Groups - have to be first */
346 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
347 : Collections.<Group>emptyList();
348 List<Group> toBeInstalledGroups = new ArrayList<>();
349 toBeInstalledGroups.addAll(groups);
350 // new list for suspected groups pointing to ports .. when the ports come up
352 List<Group> suspectedGroups = new ArrayList<>();
353 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
355 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
356 && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
357 // crossed the threshold
359 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
360 LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
361 suspectedGroups.toString());
362 toBeInstalledGroups.addAll(suspectedGroups);
366 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
367 while (iterator.hasNext()) {
368 Group group = iterator.next();
369 boolean okToInstall = true;
370 Buckets buckets = group.getBuckets();
371 List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
372 if (bucketList == null) {
373 bucketList = Collections.<Bucket>emptyList();
375 for (Bucket bucket : bucketList) {
376 List<Action> actions = bucket.getAction();
377 if (actions == null) {
378 actions = Collections.<Action>emptyList();
380 for (Action action : actions) {
382 if (action.getAction().implementedInterface().getName()
383 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
384 + ".action.types.rev131112.action.action.OutputActionCase")) {
385 String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
386 .getOutputNodeConnector().getValue();
388 LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
390 // check if the nodeconnector is there in the multimap
391 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
392 .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
393 // if yes set okToInstall = true
398 // else put it in a different list and still set okToInstall = true
399 suspectedGroups.add(group);
401 "Not yet received the node-connector updated for {} "
402 + "for the group with id {}",
403 nodeConnectorUri, group.getGroupId().toString());
406 } else if (action.getAction().implementedInterface().getName()
407 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
408 + ".action.types.rev131112.action.action.GroupActionCase")) {
410 Long groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
411 ListenableFuture<?> future = groupFutures.get(groupId);
412 if (future == null) {
416 // Need to ensure that the group specified
417 // by group-action is already installed.
418 awaitGroup(node, future);
422 // increment retry counter value
428 addGroup(groupFutures, group);
430 // resetting the counter to zero
436 /* installation of suspected groups */
437 if (!toBeInstalledGroups.isEmpty()) {
438 for (Group group : toBeInstalledGroups) {
440 "Installing the group {} finally although "
441 + "the port is not up after checking for {} times ",
442 group.getGroupId().toString(), provider.getReconciliationRetryCount());
443 addGroup(groupFutures, group);
447 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
448 : Collections.<Meter>emptyList();
449 for (Meter meter : meters) {
450 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
452 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
455 // Need to wait for all groups to be installed before adding
457 awaitGroups(node, groupFutures.values());
460 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
461 : Collections.<Table>emptyList();
463 for (Table table : tables) {
464 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
466 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
467 flowCount += flows.size();
468 for (Flow flow : flows) {
469 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
471 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
474 OF_EVENT_LOG.debug("Reconciliation Finish, Node: {}, flow count: {}", dpnId, flowCount);
480 * Invoke add-group RPC, and put listenable future associated with the RPC into
484 * The map to store listenable futures associated with add-group RPC.
488 private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
489 KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
490 final Long groupId = group.getGroupId().getValue();
491 ListenableFuture<?> future = JdkFutureAdapters
492 .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
494 Futures.addCallback(future, new FutureCallback<Object>() {
496 public void onSuccess(Object result) {
497 if (LOG.isTraceEnabled()) {
498 LOG.trace("add-group RPC completed: node={}, id={}",
499 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
504 public void onFailure(Throwable cause) {
505 LOG.debug("add-group RPC failed: node={}, id={}",
506 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId, cause);
508 }, MoreExecutors.directExecutor());
510 map.put(groupId, future);
514 * Wait for completion of add-group RPC.
517 * The identifier for the target node.
519 * Future associated with add-group RPC that installs the target
522 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
523 awaitGroups(nodeId, Collections.singleton(future));
527 * Wait for completion of add-group RPCs.
530 * The identifier for the target node.
532 * A collection of futures associated with add-group RPCs.
534 private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
535 if (!futures.isEmpty()) {
536 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
538 Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
539 LOG.trace("awaitGroups() completed: node={}", nodeId);
540 } catch (TimeoutException | InterruptedException | ExecutionException e) {
541 LOG.debug("add-group RPCs did not complete: node={}", nodeId);
547 private BigInteger getDpnIdFromNodeName(String nodeName) {
549 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
550 return new BigInteger(dpId);
553 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
554 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
555 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
556 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
558 Optional<FlowCapableNode> flowNode = Optional.empty();
560 try (ReadTransaction trans = provider.getReadTransaction()) {
561 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
562 } catch (ExecutionException | InterruptedException e) {
563 LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
566 if (flowNode.isPresent()) {
568 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
569 nodeIdent.toString());
570 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
571 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
572 : Collections.<Table>emptyList();
573 for (Table table : tables) {
574 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
576 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
577 : Collections.<StaleFlow>emptyList();
578 for (StaleFlow staleFlow : staleFlows) {
580 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
581 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
583 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
584 toBeDeletedFlow.key());
586 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
588 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
592 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
593 nodeIdent.toString());
595 // TODO: Should we collate the futures of RPC-calls to be sure that groups are
596 // Flows are fully deleted
597 // before attempting to delete groups - just in case there are references
599 /* Stale-marked Groups - Can be deleted after flows */
600 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
601 : Collections.<StaleGroup>emptyList();
602 for (StaleGroup staleGroup : staleGroups) {
604 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
605 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
607 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
608 toBeDeletedGroup.key());
610 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
612 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
615 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
616 nodeIdent.toString());
617 /* Stale-marked Meters - can be deleted anytime - so least priority */
618 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
619 : Collections.<StaleMeter>emptyList();
621 for (StaleMeter staleMeter : staleMeters) {
623 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
624 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
626 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
627 toBeDeletedMeter.key());
629 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
631 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
636 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
637 nodeIdent.toString());
638 // Now, do the bulk deletions
639 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
640 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
641 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
644 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
645 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
647 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
648 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
651 FluentFuture<?> submitFuture = writeTransaction.commit();
652 handleStaleEntityDeletionResultFuture(submitFuture);
655 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
656 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
658 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
659 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
662 FluentFuture<?> submitFuture = writeTransaction.commit();
663 handleStaleEntityDeletionResultFuture(submitFuture);
666 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
667 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
669 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
670 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
673 FluentFuture<?> submitFuture = writeTransaction.commit();
674 handleStaleEntityDeletionResultFuture(submitFuture);
677 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
678 .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
679 StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
680 return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
681 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
682 new StaleFlowKey(new FlowId(staleFlow.getId())));
685 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
686 .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
687 StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
688 return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
691 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
692 .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
693 StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
694 return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
697 private List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> addBundleMessages(final FlowCapableNode flowNode,
698 final BundleId bundleIdValue,
699 final InstanceIdentifier<FlowCapableNode> nodeIdentity) {
700 List<ListenableFuture<RpcResult<AddBundleMessagesOutput>>> futureList = new ArrayList<>();
701 for (Group group : flowNode.nonnullGroup()) {
702 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.key());
703 futureList.add(provider.getBundleGroupListener().add(groupIdent, group, nodeIdentity, bundleIdValue));
706 for (Table table : flowNode.nonnullTable()) {
707 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class, table.key());
708 for (Flow flow : table.nonnullFlow()) {
709 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.key());
710 futureList.add(provider.getBundleFlowListener().add(flowIdent, flow, nodeIdentity, bundleIdValue));
713 OF_EVENT_LOG.debug("Flow/Group count is {}", futureList.size());
717 private void handleStaleEntityDeletionResultFuture(FluentFuture<?> submitFuture) {
718 submitFuture.addCallback(new FutureCallback<Object>() {
720 public void onSuccess(Object result) {
721 LOG.debug("Stale entity removal success");
725 public void onFailure(Throwable throwable) {
726 LOG.debug("Stale entity removal failed", throwable);
728 }, MoreExecutors.directExecutor());
731 private Flow getDeleteAllFlow() {
732 final FlowBuilder flowBuilder = new FlowBuilder();
733 flowBuilder.setTableId(OFConstants.OFPTT_ALL);
734 return flowBuilder.build();
737 private Group getDeleteAllGroup() {
738 final GroupBuilder groupBuilder = new GroupBuilder();
739 groupBuilder.setGroupType(GroupTypes.GroupAll);
740 groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
741 return groupBuilder.build();
744 private Messages createMessages(final NodeRef nodeRef) {
745 final List<Message> messages = new ArrayList<>();
746 messages.add(new MessageBuilder().setNode(nodeRef)
747 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
748 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
751 messages.add(new MessageBuilder().setNode(nodeRef)
752 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
753 .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
755 return new MessagesBuilder().setMessage(messages).build();