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