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