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