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