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