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