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