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