2 * Copyright (c) 2014 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;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Lists;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.JdkFutureAdapters;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.ListIterator;
29 import java.util.Map.Entry;
30 import java.util.HashMap;
31 import java.util.concurrent.Callable;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.TimeoutException;
36 import java.util.concurrent.atomic.AtomicInteger;
37 import javax.annotation.Nonnull;
39 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
40 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
41 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
42 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
43 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
44 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
45 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
46 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
47 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
48 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
49 import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
81 import org.opendaylight.yangtools.concepts.ListenerRegistration;
82 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
83 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
89 * forwardingrules-manager
90 * org.opendaylight.openflowplugin.applications.frm
92 * FlowNode Reconciliation Listener
93 * Reconciliation for a new FlowNode
95 * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
97 * Created: Jun 13, 2014
99 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
101 private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
104 * The number of nanoseconds to wait for a single group to be added.
106 private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
109 * The maximum number of nanoseconds to wait for completion of add-group
112 private static final long MAX_ADD_GROUP_TIMEOUT =
113 TimeUnit.SECONDS.toNanos(20);
115 private final DataBroker dataBroker;
117 private final ForwardingRulesManager provider;
118 private static final String SEPARATOR = ":";
120 private ListenerRegistration<FlowNodeReconciliationImpl> listenerRegistration;
122 private static final int THREAD_POOL_SIZE = 4;
123 ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
125 private static final InstanceIdentifier<FlowCapableNode> II_TO_FLOW_CAPABLE_NODE
126 = InstanceIdentifier.builder(Nodes.class)
128 .augmentation(FlowCapableNode.class)
131 public FlowNodeReconciliationImpl (final ForwardingRulesManager manager, final DataBroker db) {
132 this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
133 dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
135 final InstanceIdentifier<FlowCapableNode> flowNodeWildCardIdentifier = InstanceIdentifier.create(Nodes.class)
136 .child(Node.class).augmentation(FlowCapableNode.class);
138 final DataTreeIdentifier<FlowCapableNode> treeId =
139 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, flowNodeWildCardIdentifier);
142 SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(ForwardingRulesManagerImpl.STARTUP_LOOP_TICK,
143 ForwardingRulesManagerImpl.STARTUP_LOOP_MAX_RETRIES);
145 listenerRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<FlowNodeReconciliationImpl>>() {
147 public ListenerRegistration<FlowNodeReconciliationImpl> call() throws Exception {
148 return dataBroker.registerDataTreeChangeListener(treeId, FlowNodeReconciliationImpl.this);
151 } catch (Exception e) {
152 LOG.warn("data listener registration failed: {}", e.getMessage());
153 LOG.debug("data listener registration failed.. ", e);
154 throw new IllegalStateException("FlowNodeReconciliation startup fail! System needs restart.", e);
159 public void close() {
160 if (listenerRegistration != null) {
162 listenerRegistration.close();
163 } catch (Exception e) {
164 LOG.warn("Error by stop FRM FlowNodeReconilListener: {}", e.getMessage());
165 LOG.debug("Error by stop FRM FlowNodeReconilListener..", e);
167 listenerRegistration = null;
172 public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<FlowCapableNode>> changes) {
173 Preconditions.checkNotNull(changes, "Changes may not be null!");
175 for (DataTreeModification<FlowCapableNode> change : changes) {
176 final InstanceIdentifier<FlowCapableNode> key = change.getRootPath().getRootIdentifier();
177 final DataObjectModification<FlowCapableNode> mod = change.getRootNode();
178 final InstanceIdentifier<FlowCapableNode> nodeIdent =
179 key.firstIdentifierOf(FlowCapableNode.class);
181 switch (mod.getModificationType()) {
183 if (mod.getDataAfter() == null) {
184 remove(key, mod.getDataBefore(), nodeIdent);
187 case SUBTREE_MODIFIED:
188 //NO-OP since we donot need to reconciliate on Node-updated
191 if (mod.getDataBefore() == null) {
192 add(key, mod.getDataAfter(), nodeIdent);
196 throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
203 public void remove(InstanceIdentifier<FlowCapableNode> identifier, FlowCapableNode del,
204 InstanceIdentifier<FlowCapableNode> nodeIdent) {
205 if(compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE)){
206 if (LOG.isDebugEnabled()) {
207 LOG.debug("Node removed: {}",nodeIdent.firstKeyOf(Node.class).getId().getValue());
210 if ( ! nodeIdent.isWildcarded()) {
211 flowNodeDisconnected(nodeIdent);
217 public void add(InstanceIdentifier<FlowCapableNode> identifier, FlowCapableNode add,
218 InstanceIdentifier<FlowCapableNode> nodeIdent) {
219 if(compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE)){
220 if (LOG.isDebugEnabled()) {
221 LOG.debug("Node added: {}",nodeIdent.firstKeyOf(Node.class).getId().getValue());
224 if ( ! nodeIdent.isWildcarded()) {
225 flowNodeConnected(nodeIdent);
231 public void flowNodeDisconnected(InstanceIdentifier<FlowCapableNode> disconnectedNode) {
232 provider.unregistrateNode(disconnectedNode);
236 public void flowNodeConnected(InstanceIdentifier<FlowCapableNode> connectedNode) {
237 flowNodeConnected(connectedNode, false);
240 private void flowNodeConnected(InstanceIdentifier<FlowCapableNode> connectedNode, boolean force) {
241 if (force || !provider.isNodeActive(connectedNode)) {
242 provider.registrateNewNode(connectedNode);
244 if(!provider.isNodeOwner(connectedNode)) { return; }
246 if (provider.getConfiguration().isStaleMarkingEnabled()) {
247 LOG.info("Stale-Marking is ENABLED and proceeding with deletion of stale-marked entities on switch {}",
248 connectedNode.toString());
249 reconciliationPreProcess(connectedNode);
251 ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
252 executor.execute(reconciliationTask);
256 private class ReconciliationTask implements Runnable {
258 InstanceIdentifier<FlowCapableNode> nodeIdentity;
260 public ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
261 nodeIdentity = nodeIdent;
267 String sNode = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
268 BigInteger nDpId = getDpnIdFromNodeName(sNode);
270 ReadOnlyTransaction trans = provider.getReadTranaction();
271 Optional<FlowCapableNode> flowNode = Optional.absent();
273 //initialize the counter
276 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
277 } catch (Exception e) {
278 LOG.error("Fail with read Config/DS for Node {} !", nodeIdentity, e);
281 if (flowNode.isPresent()) {
282 /* Tables - have to be pushed before groups */
283 // CHECK if while pusing the update, updateTableInput can be null to emulate a table add
284 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
285 ? flowNode.get().getTableFeatures() : Collections.<TableFeatures>emptyList();
286 for (TableFeatures tableFeaturesItem : tableList) {
287 TableFeaturesKey tableKey = tableFeaturesItem.getKey();
288 KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII
289 = nodeIdentity.child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
290 provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
293 /* Groups - have to be first */
294 List<Group> groups = flowNode.get().getGroup() != null
295 ? flowNode.get().getGroup() : Collections.<Group>emptyList();
296 List<Group> toBeInstalledGroups = new ArrayList<>();
297 toBeInstalledGroups.addAll(groups);
298 //new list for suspected groups pointing to ports .. when the ports come up late
299 List<Group> suspectedGroups = new ArrayList<>();
300 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
302 while ((!(toBeInstalledGroups.isEmpty()) || !(suspectedGroups.isEmpty())) &&
303 (counter <= provider.getConfiguration().getReconciliationRetryCount())) { //also check if the counter has not crossed the threshold
305 if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
306 LOG.error("These Groups are pointing to node-connectors that are not up yet {}", suspectedGroups.toString());
307 toBeInstalledGroups.addAll(suspectedGroups);
311 ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
312 while (iterator.hasNext()) {
313 Group group = iterator.next();
314 boolean okToInstall = true;
315 Buckets buckets = group.getBuckets();
316 List<Bucket> bucketList = (buckets == null)
317 ? null : buckets.getBucket();
318 if (bucketList == null) {
319 bucketList = Collections.<Bucket>emptyList();
321 for (Bucket bucket : bucketList) {
322 List<Action> actions = bucket.getAction();
323 if (actions == null) {
324 actions = Collections.<Action>emptyList();
326 for (Action action : actions) {
328 if (action.getAction().getImplementedInterface().getName()
329 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase")) {
330 String nodeConnectorUri = ((OutputActionCase) (action.getAction()))
331 .getOutputAction().getOutputNodeConnector().getValue();
333 LOG.warn("Installing the group for node connector {}", nodeConnectorUri);
335 //check if the nodeconnector is there in the multimap
336 boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
337 .isNodeConnectorUpdated(nDpId, nodeConnectorUri);
338 //if yes set okToInstall = true
342 }//else put it in a different list and still set okToInstall = true
344 suspectedGroups.add(group);
345 LOG.error("Not yet received the node-connector updated for {} " +
346 "for the group with id {}", nodeConnectorUri, group.getGroupId().toString());
353 else if (action.getAction().getImplementedInterface().getName()
354 .equals("org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase")) {
355 Long groupId = ((GroupActionCase) (action.getAction())).getGroupAction().getGroupId();
356 ListenableFuture<?> future =
357 groupFutures.get(groupId);
358 if (future == null) {
363 // Need to ensure that the group specified
364 // by group-action is already installed.
365 awaitGroup(sNode, future);
369 //increment retry counter value
376 addGroup(groupFutures, group);
378 // resetting the counter to zero
384 /* installation of suspected groups*/
385 if (!toBeInstalledGroups.isEmpty()) {
386 for (Group group : toBeInstalledGroups) {
387 LOG.error("Installing the group {} finally although the port is not up after checking for {} times "
388 , group.getGroupId().toString(), provider.getConfiguration().getReconciliationRetryCount());
389 addGroup(groupFutures, group);
393 List<Meter> meters = flowNode.get().getMeter() != null
394 ? flowNode.get().getMeter() : Collections.<Meter>emptyList();
395 for (Meter meter : meters) {
396 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent =
397 nodeIdentity.child(Meter.class, meter.getKey());
398 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
401 // Need to wait for all groups to be installed before adding
403 awaitGroups(sNode, groupFutures.values());
406 List<Table> tables = flowNode.get().getTable() != null
407 ? flowNode.get().getTable() : Collections.<Table>emptyList();
408 for (Table table : tables) {
409 final KeyedInstanceIdentifier<Table, TableKey> tableIdent =
410 nodeIdentity.child(Table.class, table.getKey());
411 List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
412 for (Flow flow : flows) {
413 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent =
414 tableIdent.child(Flow.class, flow.getKey());
415 provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
419 /* clean transaction */
424 * Invoke add-group RPC, and put listenable future associated with the
425 * RPC into the given map.
427 * @param map The map to store listenable futures associated with
429 * @param group The group to add.
431 private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
432 KeyedInstanceIdentifier<Group, GroupKey> groupIdent =
433 nodeIdentity.child(Group.class, group.getKey());
434 final Long groupId = group.getGroupId().getValue();
435 ListenableFuture<?> future = JdkFutureAdapters.listenInPoolThread(
436 provider.getGroupCommiter().add(
437 groupIdent, group, nodeIdentity));
439 Futures.addCallback(future, new FutureCallback<Object>() {
441 public void onSuccess(Object result) {
442 if (LOG.isTraceEnabled()) {
443 LOG.trace("add-group RPC completed: node={}, id={}",
444 nodeIdentity.firstKeyOf(Node.class).getId().
445 getValue(), groupId);
450 public void onFailure(Throwable cause) {
451 String msg = "add-group RPC failed: node=" +
452 nodeIdentity.firstKeyOf(Node.class).getId().getValue() +
454 LOG.error(msg, cause);
458 map.put(groupId, future);
462 * Wait for completion of add-group RPC.
464 * @param nodeId The identifier for the target node.
465 * @param future Future associated with add-group RPC that installs
468 private void awaitGroup(String nodeId, ListenableFuture<?> future) {
469 awaitGroups(nodeId, Collections.singleton(future));
473 * Wait for completion of add-group RPCs.
475 * @param nodeId The identifier for the target node.
476 * @param futures A collection of futures associated with add-group
479 private void awaitGroups(String nodeId,
480 Collection<ListenableFuture<?>> futures) {
481 if (!futures.isEmpty()) {
482 long timeout = Math.min(
483 ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
485 Futures.successfulAsList(futures).
486 get(timeout, TimeUnit.NANOSECONDS);
487 LOG.trace("awaitGroups() completed: node={}", nodeId);
488 } catch (TimeoutException e) {
489 LOG.warn("add-group RPCs did not complete: node={}",
491 } catch (Exception e) {
492 LOG.error("Unhandled exception while waiting for group installation on node {}",
499 private BigInteger getDpnIdFromNodeName(String nodeName) {
501 String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
502 return new BigInteger(dpId);
505 private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
507 List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
508 List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
509 List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
512 ReadOnlyTransaction trans = provider.getReadTranaction();
513 Optional<FlowCapableNode> flowNode = Optional.absent();
516 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
518 catch (Exception e) {
519 LOG.error("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
522 if (flowNode.isPresent()) {
524 LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
525 nodeIdent.toString());
526 /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
527 List<Table> tables = flowNode.get().getTable() != null
528 ? flowNode.get().getTable() : Collections.<Table> emptyList();
529 for (Table table : tables) {
530 final KeyedInstanceIdentifier<Table, TableKey> tableIdent =
531 nodeIdent.child(Table.class, table.getKey());
532 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow() : Collections.<StaleFlow> emptyList();
533 for (StaleFlow staleFlow : staleFlows) {
535 FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
536 Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
538 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent =
539 tableIdent.child(Flow.class, toBeDeletedFlow.getKey());
542 this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
544 staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
549 LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
550 nodeIdent.toString());
552 // TODO: Should we collate the futures of RPC-calls to be sure that groups are Flows are fully deleted
553 // before attempting to delete groups - just in case there are references
555 /* Stale-marked Groups - Can be deleted after flows */
556 List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null
557 ? flowNode.get().getStaleGroup() : Collections.<StaleGroup> emptyList();
558 for (StaleGroup staleGroup : staleGroups) {
560 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
561 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
563 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent =
564 nodeIdent.child(Group.class, toBeDeletedGroup.getKey());
566 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
568 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
571 LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
572 nodeIdent.toString());
573 /* Stale-marked Meters - can be deleted anytime - so least priority */
574 List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null
575 ? flowNode.get().getStaleMeter() : Collections.<StaleMeter> emptyList();
577 for (StaleMeter staleMeter : staleMeters) {
579 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
580 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
582 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent =
583 nodeIdent.child(Meter.class, toBeDeletedMeter.getKey());
586 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
588 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
592 /* clean transaction */
595 LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
596 nodeIdent.toString());
597 // Now, do the bulk deletions
598 deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
599 deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
600 deleteDSStaleMeters(staleMetersToBeBulkDeleted);
605 private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete){
606 ImmutableList.Builder<InstanceIdentifier<StaleFlow>> builder = ImmutableList.builder();
608 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
610 for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete){
611 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
614 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
615 handleStaleEntityDeletionResultFuture(submitFuture);
618 private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete){
619 ImmutableList.Builder<InstanceIdentifier<StaleGroup>> builder = ImmutableList.builder();
621 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
623 for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete){
624 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
627 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
628 handleStaleEntityDeletionResultFuture(submitFuture);
632 private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete){
633 ImmutableList.Builder<InstanceIdentifier<StaleMeter>> builder = ImmutableList.builder();
635 WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
637 for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete){
638 writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
641 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
642 handleStaleEntityDeletionResultFuture(submitFuture);
648 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
650 .child(Table.class, new TableKey(staleFlow.getTableId()))
651 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
652 new StaleFlowKey(new FlowId(staleFlow.getId())));
655 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
657 .child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
661 private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
663 .child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
667 private void handleStaleEntityDeletionResultFuture(CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
668 Futures.addCallback(submitFuture, new FutureCallback<Void>() {
670 public void onSuccess(Void result) {
671 LOG.debug("Stale entity removal success");
675 public void onFailure(Throwable t) {
676 LOG.error("Stale entity removal failed {}", t);
683 private boolean compareInstanceIdentifierTail(InstanceIdentifier<?> identifier1,
684 InstanceIdentifier<?> identifier2) {
685 return Iterables.getLast(identifier1.getPathArguments()).equals(Iterables.getLast(identifier2.getPathArguments()));