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