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