OPNFLWPLUG-986: Administrative Reconciliation for multiple/all Nodes
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / FlowNodeReconciliationImpl.java
1 /**
2  * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.openflowplugin.applications.frm.impl;
10
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;
27 import java.util.Map;
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.Future;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.TimeoutException;
35 import java.util.concurrent.atomic.AtomicLong;
36 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
37 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
38 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.openflowplugin.api.OFConstants;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
43 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
44 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
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.SalBundleService;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddFlowCaseBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddGroupCaseBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
88 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;
89 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;
90 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;
91 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;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
98 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
99 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
100 import org.opendaylight.yangtools.yang.common.RpcResult;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103
104 /**
105  * Default implementation of {@link ForwardingRulesManager}.
106  *
107  * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
108  */
109 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
110
111     private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
112
113     // The number of nanoseconds to wait for a single group to be added.
114     private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
115
116     // The maximum number of nanoseconds to wait for completion of add-group RPCs.
117     private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
118     private static final String SEPARATOR = ":";
119     private static final int THREAD_POOL_SIZE = 4;
120
121     private final DataBroker dataBroker;
122     private final ForwardingRulesManager provider;
123     private final String serviceName;
124     private final int priority;
125     private final ResultState resultState;
126     private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
127
128     private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
129
130     private final SalBundleService salBundleService;
131
132     private static final AtomicLong BUNDLE_ID = new AtomicLong();
133     private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
134
135     public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
136             final String serviceName, final int priority, final ResultState resultState) {
137         this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
138         dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
139         this.serviceName = serviceName;
140         this.priority = priority;
141         this.resultState = resultState;
142         salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
143                 "salBundleService can not be null!");
144     }
145
146     @Override
147     public void close() {
148         if (executor != null) {
149             executor.shutdownNow();
150         }
151     }
152
153     @Override
154     public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
155         LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
156         if (provider.isStaleMarkingEnabled()) {
157             LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
158                     connectedNode.toString());
159             reconciliationPreProcess(connectedNode);
160         }
161         LOG.debug("Bundle based reconciliation status : {}",
162                 provider.isBundleBasedReconciliationEnabled() ? "Enable" : "Disable");
163         if (provider.isBundleBasedReconciliationEnabled()) {
164             BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
165             return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
166         } else {
167             ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
168             return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
169         }
170     }
171
172     private class BundleBasedReconciliationTask implements Callable<Boolean> {
173         final InstanceIdentifier<FlowCapableNode> nodeIdentity;
174
175         BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
176             nodeIdentity = nodeIdent;
177         }
178
179         @Override
180         public Boolean call() {
181             String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
182             Optional<FlowCapableNode> flowNode = Optional.absent();
183             BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
184             BigInteger dpnId = getDpnIdFromNodeName(node);
185             LOG.debug("Triggering bundle based reconciliation for device :{}", dpnId);
186             ReadOnlyTransaction trans = provider.getReadTranaction();
187             try {
188                 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
189             } catch (ExecutionException | InterruptedException e) {
190                 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
191             }
192
193             if (flowNode.isPresent()) {
194                 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
195                 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
196
197                 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
198                         .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
199                         .build();
200
201                 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
202                         .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
203                         .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
204
205                 final AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
206                         .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
207                         .setMessages(createMessages(nodeRef, flowNode)).build();
208
209                 Future<RpcResult<Void>> openBundle = salBundleService.controlBundle(openBundleInput);
210
211                 ListenableFuture<RpcResult<Void>> addBundleMessagesFuture = Futures
212                         .transformAsync(JdkFutureAdapters.listenInPoolThread(openBundle), rpcResult -> {
213                             if (rpcResult.isSuccessful()) {
214                                 return JdkFutureAdapters
215                                         .listenInPoolThread(salBundleService.addBundleMessages(addBundleMessagesInput));
216                             }
217                             return Futures.immediateFuture(null);
218                         }, MoreExecutors.directExecutor());
219                 ListenableFuture<RpcResult<Void>> commitBundleFuture = Futures.transformAsync(addBundleMessagesFuture,
220                     rpcResult -> {
221                         if (rpcResult.isSuccessful()) {
222                             return JdkFutureAdapters
223                                     .listenInPoolThread(salBundleService.controlBundle(commitBundleInput));
224                         }
225                         return Futures.immediateFuture(null);
226                     }, MoreExecutors.directExecutor());
227
228                 /* Bundles not supported for meters */
229                 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
230                         : Collections.emptyList();
231                 Futures.transformAsync(commitBundleFuture,
232                     rpcResult -> {
233                         if (rpcResult.isSuccessful()) {
234                             for (Meter meter : meters) {
235                                 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
236                                         .child(Meter.class, meter.getKey());
237                                 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
238                             }
239                         }
240                         return Futures.immediateFuture(null);
241                     }, MoreExecutors.directExecutor());
242
243                 trans.close();
244                 try {
245                     if (commitBundleFuture.get().isSuccessful()) {
246                         LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
247                         return true;
248                     } else {
249                         return false;
250                     }
251                 } catch (InterruptedException | ExecutionException e) {
252                     LOG.error("Error while doing bundle based reconciliation for device ID:{}", nodeIdentity);
253                     return false;
254                 }
255             }
256             LOG.error("FlowNode not present for Datapath ID {}", dpnId);
257             return false;
258         }
259     }
260
261     @Override
262     public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
263         InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
264                 .augmentation(FlowCapableNode.class);
265         return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
266     }
267
268     @Override
269     public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
270         futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
271         futureMap.remove(node);
272         return Futures.immediateFuture(true);
273     }
274
275     @Override
276     public int getPriority() {
277         return priority;
278     }
279
280     @Override
281     public String getName() {
282         return serviceName;
283     }
284
285     @Override
286     public ResultState getResultState() {
287         return resultState;
288     }
289
290     private class ReconciliationTask implements Callable<Boolean> {
291
292         InstanceIdentifier<FlowCapableNode> nodeIdentity;
293
294         ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
295             nodeIdentity = nodeIdent;
296         }
297
298         @Override
299         public Boolean call() {
300             String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
301             BigInteger dpnId = getDpnIdFromNodeName(node);
302
303             ReadOnlyTransaction trans = provider.getReadTranaction();
304             Optional<FlowCapableNode> flowNode;
305             // initialize the counter
306             int counter = 0;
307             try {
308                 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
309             } catch (ExecutionException | InterruptedException e) {
310                 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
311                 return false;
312             }
313
314             if (flowNode.isPresent()) {
315                 /* Tables - have to be pushed before groups */
316                 // CHECK if while pushing the update, updateTableInput can be null to emulate a
317                 // table add
318                 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
319                         ? flowNode.get().getTableFeatures()
320                         : Collections.<TableFeatures>emptyList();
321                 for (TableFeatures tableFeaturesItem : tableList) {
322                     TableFeaturesKey tableKey = tableFeaturesItem.getKey();
323                     KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
324                             .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
325                     provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
326                 }
327
328                 /* Groups - have to be first */
329                 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
330                         : Collections.<Group>emptyList();
331                 List<Group> toBeInstalledGroups = new ArrayList<>();
332                 toBeInstalledGroups.addAll(groups);
333                 // new list for suspected groups pointing to ports .. when the ports come up
334                 // late
335                 List<Group> suspectedGroups = new ArrayList<>();
336                 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
337
338                 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
339                         && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
340                                                                                 // crossed the threshold
341
342                     if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
343                         LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
344                                 suspectedGroups.toString());
345                         toBeInstalledGroups.addAll(suspectedGroups);
346                         break;
347                     }
348
349                     ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
350                     while (iterator.hasNext()) {
351                         Group group = iterator.next();
352                         boolean okToInstall = true;
353                         Buckets buckets = group.getBuckets();
354                         List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
355                         if (bucketList == null) {
356                             bucketList = Collections.<Bucket>emptyList();
357                         }
358                         for (Bucket bucket : bucketList) {
359                             List<Action> actions = bucket.getAction();
360                             if (actions == null) {
361                                 actions = Collections.<Action>emptyList();
362                             }
363                             for (Action action : actions) {
364                                 // chained-port
365                                 if (action.getAction().getImplementedInterface().getName()
366                                         .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
367                                                 + ".action.types.rev131112.action.action.OutputActionCase")) {
368                                     String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
369                                             .getOutputNodeConnector().getValue();
370
371                                     LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
372
373                                     // check if the nodeconnector is there in the multimap
374                                     boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
375                                             .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
376                                     // if yes set okToInstall = true
377
378                                     if (isPresent) {
379                                         break;
380                                     } else {
381                                         // else put it in a different list and still set okToInstall = true
382                                         suspectedGroups.add(group);
383                                         LOG.debug(
384                                                 "Not yet received the node-connector updated for {} "
385                                                         + "for the group with id {}",
386                                                 nodeConnectorUri, group.getGroupId().toString());
387                                         break;
388                                     }
389                                 } else if (action.getAction().getImplementedInterface().getName()
390                                         .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
391                                                 + ".action.types.rev131112.action.action.GroupActionCase")) {
392                                     // chained groups
393                                     Long groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
394                                     ListenableFuture<?> future = groupFutures.get(groupId);
395                                     if (future == null) {
396                                         okToInstall = false;
397                                         break;
398                                     }
399                                     // Need to ensure that the group specified
400                                     // by group-action is already installed.
401                                     awaitGroup(node, future);
402                                 }
403                             }
404                             if (!okToInstall) {
405                                 // increment retry counter value
406                                 counter++;
407                                 break;
408                             }
409                         }
410                         if (okToInstall) {
411                             addGroup(groupFutures, group);
412                             iterator.remove();
413                             // resetting the counter to zero
414                             counter = 0;
415                         }
416                     }
417                 }
418
419                 /* installation of suspected groups */
420                 if (!toBeInstalledGroups.isEmpty()) {
421                     for (Group group : toBeInstalledGroups) {
422                         LOG.debug(
423                                 "Installing the group {} finally although "
424                                         + "the port is not up after checking for {} times ",
425                                 group.getGroupId().toString(), provider.getReconciliationRetryCount());
426                         addGroup(groupFutures, group);
427                     }
428                 }
429                 /* Meters */
430                 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
431                         : Collections.<Meter>emptyList();
432                 for (Meter meter : meters) {
433                     final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
434                             meter.getKey());
435                     provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
436                 }
437
438                 // Need to wait for all groups to be installed before adding
439                 // flows.
440                 awaitGroups(node, groupFutures.values());
441
442                 /* Flows */
443                 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
444                         : Collections.<Table>emptyList();
445                 for (Table table : tables) {
446                     final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
447                             table.getKey());
448                     List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
449                     for (Flow flow : flows) {
450                         final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
451                                 flow.getKey());
452                         provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
453                     }
454                 }
455             }
456             /* clean transaction */
457             trans.close();
458             return true;
459         }
460
461         /**
462          * Invoke add-group RPC, and put listenable future associated with the RPC into
463          * the given map.
464          *
465          * @param map
466          *            The map to store listenable futures associated with add-group RPC.
467          * @param group
468          *            The group to add.
469          */
470         private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
471             KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.getKey());
472             final Long groupId = group.getGroupId().getValue();
473             ListenableFuture<?> future = JdkFutureAdapters
474                     .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
475
476             Futures.addCallback(future, new FutureCallback<Object>() {
477                 @Override
478                 public void onSuccess(Object result) {
479                     if (LOG.isTraceEnabled()) {
480                         LOG.trace("add-group RPC completed: node={}, id={}",
481                                 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
482                     }
483                 }
484
485                 @Override
486                 public void onFailure(Throwable cause) {
487                     String msg = "add-group RPC failed: node=" + nodeIdentity.firstKeyOf(Node.class).getId().getValue()
488                             + ", id=" + groupId;
489                     LOG.debug(msg, cause);
490                 }
491             }, MoreExecutors.directExecutor());
492
493             map.put(groupId, future);
494         }
495
496         /**
497          * Wait for completion of add-group RPC.
498          *
499          * @param nodeId
500          *            The identifier for the target node.
501          * @param future
502          *            Future associated with add-group RPC that installs the target
503          *            group.
504          */
505         private void awaitGroup(String nodeId, ListenableFuture<?> future) {
506             awaitGroups(nodeId, Collections.singleton(future));
507         }
508
509         /**
510          * Wait for completion of add-group RPCs.
511          *
512          * @param nodeId
513          *            The identifier for the target node.
514          * @param futures
515          *            A collection of futures associated with add-group RPCs.
516          */
517         private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
518             if (!futures.isEmpty()) {
519                 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
520                 try {
521                     Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
522                     LOG.trace("awaitGroups() completed: node={}", nodeId);
523                 } catch (TimeoutException | InterruptedException | ExecutionException e) {
524                     LOG.debug("add-group RPCs did not complete: node={}", nodeId);
525                 }
526             }
527         }
528     }
529
530     private BigInteger getDpnIdFromNodeName(String nodeName) {
531
532         String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
533         return new BigInteger(dpId);
534     }
535
536     private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
537         List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
538         List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
539         List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
540
541         ReadOnlyTransaction trans = provider.getReadTranaction();
542         Optional<FlowCapableNode> flowNode = Optional.absent();
543
544         try {
545             flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
546         } catch (ExecutionException | InterruptedException e) {
547             LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
548         }
549
550         if (flowNode.isPresent()) {
551
552             LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
553                     nodeIdent.toString());
554             /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
555             List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
556                     : Collections.<Table>emptyList();
557             for (Table table : tables) {
558                 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
559                         table.getKey());
560                 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
561                         : Collections.<StaleFlow>emptyList();
562                 for (StaleFlow staleFlow : staleFlows) {
563
564                     FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
565                     Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
566
567                     final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
568                             toBeDeletedFlow.getKey());
569
570                     this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
571
572                     staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
573                 }
574             }
575
576             LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
577                     nodeIdent.toString());
578
579             // TODO: Should we collate the futures of RPC-calls to be sure that groups are
580             // Flows are fully deleted
581             // before attempting to delete groups - just in case there are references
582
583             /* Stale-marked Groups - Can be deleted after flows */
584             List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
585                     : Collections.<StaleGroup>emptyList();
586             for (StaleGroup staleGroup : staleGroups) {
587
588                 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
589                 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
590
591                 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
592                         toBeDeletedGroup.getKey());
593
594                 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
595
596                 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
597             }
598
599             LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
600                     nodeIdent.toString());
601             /* Stale-marked Meters - can be deleted anytime - so least priority */
602             List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
603                     : Collections.<StaleMeter>emptyList();
604
605             for (StaleMeter staleMeter : staleMeters) {
606
607                 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
608                 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
609
610                 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
611                         toBeDeletedMeter.getKey());
612
613                 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
614
615                 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
616             }
617
618         }
619         /* clean transaction */
620         trans.close();
621
622         LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
623                 nodeIdent.toString());
624         // Now, do the bulk deletions
625         deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
626         deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
627         deleteDSStaleMeters(staleMetersToBeBulkDeleted);
628     }
629
630     private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
631         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
632
633         for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
634             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
635         }
636
637         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
638         handleStaleEntityDeletionResultFuture(submitFuture);
639     }
640
641     private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
642         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
643
644         for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
645             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
646         }
647
648         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
649         handleStaleEntityDeletionResultFuture(submitFuture);
650     }
651
652     private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
653         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
654
655         for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
656             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
657         }
658
659         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
660         handleStaleEntityDeletionResultFuture(submitFuture);
661     }
662
663     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
664         .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
665             StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
666         return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
667                 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
668                 new StaleFlowKey(new FlowId(staleFlow.getId())));
669     }
670
671     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
672         .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
673             StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
674         return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
675     }
676
677     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
678         .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
679             StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
680         return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
681     }
682
683     private void handleStaleEntityDeletionResultFuture(
684             CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
685         Futures.addCallback(submitFuture, new FutureCallback<Void>() {
686             @Override
687             public void onSuccess(Void result) {
688                 LOG.debug("Stale entity removal success");
689             }
690
691             @Override
692             public void onFailure(Throwable throwable) {
693                 LOG.debug("Stale entity removal failed {}", throwable);
694             }
695         }, MoreExecutors.directExecutor());
696     }
697
698     private Flow getDeleteAllFlow() {
699         final FlowBuilder flowBuilder = new FlowBuilder();
700         flowBuilder.setTableId(OFConstants.OFPTT_ALL);
701         return flowBuilder.build();
702     }
703
704     private Group getDeleteAllGroup() {
705         final GroupBuilder groupBuilder = new GroupBuilder();
706         groupBuilder.setGroupType(GroupTypes.GroupAll);
707         groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
708         return groupBuilder.build();
709     }
710
711     private Messages createMessages(final NodeRef nodeRef, final Optional<FlowCapableNode> flowNode) {
712         final List<Message> messages = new ArrayList<>();
713         messages.add(new MessageBuilder().setNode(nodeRef)
714                 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
715                         .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
716                 .build());
717
718         messages.add(new MessageBuilder().setNode(nodeRef)
719                 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
720                         .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
721                 .build());
722
723         if (flowNode.get().getGroup() != null) {
724             for (Group gr : flowNode.get().getGroup()) {
725                 messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddGroupCaseBuilder()
726                         .setAddGroupCaseData(new AddGroupCaseDataBuilder(gr).build()).build()).build());
727             }
728         }
729
730         if (flowNode.get().getTable() != null) {
731             for (Table table : flowNode.get().getTable()) {
732                 for (Flow flow : table.getFlow()) {
733                     messages.add(
734                             new MessageBuilder().setNode(nodeRef)
735                                     .setBundleInnerMessage(new BundleAddFlowCaseBuilder()
736                                             .setAddFlowCaseData(new AddFlowCaseDataBuilder(flow).build()).build())
737                                     .build());
738                 }
739             }
740         }
741
742         LOG.debug("The size of the flows and group messages created in createMessage() {}", messages.size());
743         return new MessagesBuilder().setMessage(messages).build();
744     }
745 }