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