Merge "OPNFLWPLUG-929 : Remove deprecated guava library in applications"
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / impl / strategy / SyncPlanPushStrategyIncrementalImpl.java
1 /**
2  * Copyright (c) 2016 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
9 package org.opendaylight.openflowplugin.applications.frsync.impl.strategy;
10
11 import com.google.common.collect.Iterables;
12 import com.google.common.util.concurrent.AsyncFunction;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.JdkFutureAdapters;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.List;
20 import java.util.Map;
21 import org.opendaylight.openflowplugin.applications.frsync.SyncPlanPushStrategy;
22 import org.opendaylight.openflowplugin.applications.frsync.util.CrudCounts;
23 import org.opendaylight.openflowplugin.applications.frsync.util.FxChainUtil;
24 import org.opendaylight.openflowplugin.applications.frsync.util.ItemSyncBox;
25 import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;
26 import org.opendaylight.openflowplugin.applications.frsync.util.ReconcileUtil;
27 import org.opendaylight.openflowplugin.applications.frsync.util.SyncCrudCounters;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.FlowCapableTransactionService;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
51 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
52 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Execute CRUD API for flow + group + meter involving one-by-one (incremental) strategy.
61  */
62 public class SyncPlanPushStrategyIncrementalImpl implements SyncPlanPushStrategy {
63
64     private static final Logger LOG = LoggerFactory.getLogger(SyncPlanPushStrategyIncrementalImpl.class);
65
66     private FlowForwarder flowForwarder;
67     private MeterForwarder meterForwarder;
68     private GroupForwarder groupForwarder;
69     private TableForwarder tableForwarder;
70     private FlowCapableTransactionService transactionService;
71
72     @Override
73     public ListenableFuture<RpcResult<Void>> executeSyncStrategy(ListenableFuture<RpcResult<Void>> resultVehicle,
74                                                                  final SynchronizationDiffInput diffInput,
75                                                                  final SyncCrudCounters counters) {
76         final InstanceIdentifier<FlowCapableNode> nodeIdent = diffInput.getNodeIdent();
77         final NodeId nodeId = PathUtil.digNodeId(nodeIdent);
78
79         /* Tables - have to be pushed before groups */
80         // TODO enable table-update when ready
81         //resultVehicle = updateTableFeatures(nodeIdent, configTree);
82
83         resultVehicle = Futures.transformAsync(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
84             @Override
85             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
86                 if (!input.isSuccessful()) {
87                     //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input);
88                     //final ListenableFuture<RpcResult<Void>> singleVoidUpdateResult = Futures.transform(
89                     //        Futures.asList Arrays.asList(input, output),
90                     //        ReconcileUtil.<UpdateFlowOutput>createRpcResultCondenser("TODO"));
91                 }
92                 return addMissingGroups(nodeId, nodeIdent, diffInput.getGroupsToAddOrUpdate(), counters);
93             }
94         });
95         Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "addMissingGroups"),
96                 MoreExecutors.directExecutor());
97         resultVehicle = Futures.transformAsync(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
98             @Override
99             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
100                 if (!input.isSuccessful()) {
101                     //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input);
102                 }
103                 return addMissingMeters(nodeId, nodeIdent, diffInput.getMetersToAddOrUpdate(), counters);
104             }
105         });
106         Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "addMissingMeters"),
107                 MoreExecutors.directExecutor());
108         resultVehicle = Futures.transformAsync(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
109             @Override
110             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
111                 if (!input.isSuccessful()) {
112                     //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input);
113                 }
114                 return addMissingFlows(nodeId, nodeIdent, diffInput.getFlowsToAddOrUpdate(), counters);
115             }
116         });
117         Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "addMissingFlows"),
118                 MoreExecutors.directExecutor());
119
120
121         resultVehicle = Futures.transformAsync(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
122             @Override
123             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
124                 if (!input.isSuccessful()) {
125                     //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input);
126                 }
127                 return removeRedundantFlows(nodeId, nodeIdent, diffInput.getFlowsToRemove(), counters);
128             }
129         });
130         Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "removeRedundantFlows"),
131                 MoreExecutors.directExecutor());
132         resultVehicle = Futures.transformAsync(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
133             @Override
134             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
135                 if (!input.isSuccessful()) {
136                     //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input);
137                 }
138                 return removeRedundantMeters(nodeId, nodeIdent, diffInput.getMetersToRemove(), counters);
139             }
140         });
141         Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "removeRedundantMeters"),
142                 MoreExecutors.directExecutor());
143         resultVehicle = Futures.transformAsync(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
144             @Override
145             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
146                 if (!input.isSuccessful()) {
147                     //TODO chain errors but not skip processing on first error return Futures.immediateFuture(input);
148                 }
149                 return removeRedundantGroups(nodeId, nodeIdent, diffInput.getGroupsToRemove(), counters);
150             }
151         });
152         Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "removeRedundantGroups"),
153                 MoreExecutors.directExecutor());
154         return resultVehicle;
155     }
156
157
158     ListenableFuture<RpcResult<Void>> addMissingFlows(final NodeId nodeId,
159                                                       final InstanceIdentifier<FlowCapableNode> nodeIdent,
160                                                       final Map<TableKey, ItemSyncBox<Flow>> flowsInTablesSyncBox,
161                                                       final SyncCrudCounters counters) {
162         if (flowsInTablesSyncBox.isEmpty()) {
163             LOG.trace("no tables in config for node: {} -> SKIPPING", nodeId.getValue());
164             return RpcResultBuilder.<Void>success().buildFuture();
165         }
166
167         final List<ListenableFuture<RpcResult<AddFlowOutput>>> allResults = new ArrayList<>();
168         final List<ListenableFuture<RpcResult<UpdateFlowOutput>>> allUpdateResults = new ArrayList<>();
169         final CrudCounts flowCrudCounts = counters.getFlowCrudCounts();
170
171         for (Map.Entry<TableKey, ItemSyncBox<Flow>> flowsInTableBoxEntry : flowsInTablesSyncBox.entrySet()) {
172             final TableKey tableKey = flowsInTableBoxEntry.getKey();
173             final ItemSyncBox<Flow> flowSyncBox = flowsInTableBoxEntry.getValue();
174
175             final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class, tableKey);
176
177             for (final Flow flow : flowSyncBox.getItemsToPush()) {
178                 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, flow.getKey());
179
180                 LOG.trace("adding flow {} in table {} - absent on device {} match{}",
181                         flow.getId(), tableKey, nodeId, flow.getMatch());
182
183                 allResults.add(JdkFutureAdapters.listenInPoolThread(
184                         flowForwarder.add(flowIdent, flow, nodeIdent)));
185                 flowCrudCounts.incAdded();
186             }
187
188             for (final ItemSyncBox.ItemUpdateTuple<Flow> flowUpdate : flowSyncBox.getItemsToUpdate()) {
189                 final Flow existingFlow = flowUpdate.getOriginal();
190                 final Flow updatedFlow = flowUpdate.getUpdated();
191
192                 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class, updatedFlow.getKey());
193                 LOG.trace("flow {} in table {} - needs update on device {} match{}",
194                         updatedFlow.getId(), tableKey, nodeId, updatedFlow.getMatch());
195
196                 allUpdateResults.add(JdkFutureAdapters.listenInPoolThread(
197                         flowForwarder.update(flowIdent, existingFlow, updatedFlow, nodeIdent)));
198                 flowCrudCounts.incUpdated();
199             }
200         }
201
202         final ListenableFuture<RpcResult<Void>> singleVoidAddResult = Futures.transform(
203                 Futures.allAsList(allResults),
204                 ReconcileUtil.<AddFlowOutput>createRpcResultCondenser("flow adding"));
205
206         final ListenableFuture<RpcResult<Void>> singleVoidUpdateResult = Futures.transform(
207                 Futures.allAsList(allUpdateResults),
208                 ReconcileUtil.<UpdateFlowOutput>createRpcResultCondenser("flow updating"));
209
210         return Futures.transform(Futures.allAsList(singleVoidAddResult, singleVoidUpdateResult),
211                 ReconcileUtil.<Void>createRpcResultCondenser("flow add/update"));
212     }
213
214     ListenableFuture<RpcResult<Void>> removeRedundantFlows(final NodeId nodeId,
215                                                            final InstanceIdentifier<FlowCapableNode> nodeIdent,
216                                                            final Map<TableKey, ItemSyncBox<Flow>> removalPlan,
217                                                            final SyncCrudCounters counters) {
218         if (removalPlan.isEmpty()) {
219             LOG.trace("no tables in operational for node: {} -> SKIPPING", nodeId.getValue());
220             return RpcResultBuilder.<Void>success().buildFuture();
221         }
222
223         final List<ListenableFuture<RpcResult<RemoveFlowOutput>>> allResults = new ArrayList<>();
224         final CrudCounts flowCrudCounts = counters.getFlowCrudCounts();
225
226         for (final Map.Entry<TableKey, ItemSyncBox<Flow>> flowsPerTable : removalPlan.entrySet()) {
227             final KeyedInstanceIdentifier<Table, TableKey> tableIdent =
228                     nodeIdent.child(Table.class, flowsPerTable.getKey());
229
230             // loop flows on device and check if the are configured
231             for (final Flow flow : flowsPerTable.getValue().getItemsToPush()) {
232                 final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent =
233                         tableIdent.child(Flow.class, flow.getKey());
234                 allResults.add(JdkFutureAdapters.listenInPoolThread(
235                         flowForwarder.remove(flowIdent, flow, nodeIdent)));
236                 flowCrudCounts.incRemoved();
237             }
238         }
239
240         final ListenableFuture<RpcResult<Void>> singleVoidResult = Futures.transform(
241                 Futures.allAsList(allResults), ReconcileUtil.<RemoveFlowOutput>createRpcResultCondenser("flow remove"));
242         return Futures.transformAsync(singleVoidResult,
243                 ReconcileUtil.chainBarrierFlush(PathUtil.digNodePath(nodeIdent), transactionService));
244
245     }
246
247     ListenableFuture<RpcResult<Void>> removeRedundantMeters(final NodeId nodeId,
248                                                             final InstanceIdentifier<FlowCapableNode> nodeIdent,
249                                                             final ItemSyncBox<Meter> meterRemovalPlan,
250                                                             final SyncCrudCounters counters) {
251         if (meterRemovalPlan.isEmpty()) {
252             LOG.trace("no meters on device for node: {} -> SKIPPING", nodeId.getValue());
253             return RpcResultBuilder.<Void>success().buildFuture();
254         }
255
256         final CrudCounts meterCrudCounts = counters.getMeterCrudCounts();
257
258         final List<ListenableFuture<RpcResult<RemoveMeterOutput>>> allResults = new ArrayList<>();
259         for (Meter meter : meterRemovalPlan.getItemsToPush()) {
260             LOG.trace("removing meter {} - absent in config {}",
261                     meter.getMeterId(), nodeId);
262             final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent =
263                     nodeIdent.child(Meter.class, meter.getKey());
264             allResults.add(JdkFutureAdapters.listenInPoolThread(
265                     meterForwarder.remove(meterIdent, meter, nodeIdent)));
266             meterCrudCounts.incRemoved();
267         }
268
269         return Futures.transform(Futures.allAsList(allResults),
270                 ReconcileUtil.<RemoveMeterOutput>createRpcResultCondenser("meter remove"));
271     }
272
273     ListenableFuture<RpcResult<Void>> removeRedundantGroups(final NodeId nodeId,
274                                                             final InstanceIdentifier<FlowCapableNode> nodeIdent,
275                                                             final List<ItemSyncBox<Group>> groupsRemovalPlan,
276                                                             final SyncCrudCounters counters) {
277         if (groupsRemovalPlan.isEmpty()) {
278             LOG.trace("no groups on device for node: {} -> SKIPPING", nodeId.getValue());
279             return RpcResultBuilder.<Void>success().buildFuture();
280         }
281
282         final CrudCounts groupCrudCounts = counters.getGroupCrudCounts();
283
284         ListenableFuture<RpcResult<Void>> chainedResult = RpcResultBuilder.<Void>success().buildFuture();
285         try {
286             groupCrudCounts.setRemoved(ReconcileUtil.countTotalPushed(groupsRemovalPlan));
287             if (LOG.isDebugEnabled()) {
288                 LOG.debug("removing groups: planSteps={}, toRemoveTotal={}",
289                         groupsRemovalPlan.size(), groupCrudCounts.getRemoved());
290             }
291             Collections.reverse(groupsRemovalPlan);
292             for (final ItemSyncBox<Group> groupsPortion : groupsRemovalPlan) {
293                 chainedResult =
294                         Futures.transformAsync(chainedResult, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
295                             @Override
296                             public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input)
297                                     throws Exception {
298                                 final ListenableFuture<RpcResult<Void>> result;
299                                 if (input.isSuccessful()) {
300                                     result = flushRemoveGroupPortionAndBarrier(nodeIdent, groupsPortion);
301                                 } else {
302                                     // pass through original unsuccessful rpcResult
303                                     result = Futures.immediateFuture(input);
304                                 }
305
306                                 return result;
307                             }
308                         });
309             }
310         } catch (IllegalStateException e) {
311             chainedResult = RpcResultBuilder.<Void>failed()
312                     .withError(RpcError.ErrorType.APPLICATION, "failed to add missing groups", e)
313                     .buildFuture();
314         }
315
316         return chainedResult;
317     }
318
319     private ListenableFuture<RpcResult<Void>> flushRemoveGroupPortionAndBarrier(
320             final InstanceIdentifier<FlowCapableNode> nodeIdent,
321             final ItemSyncBox<Group> groupsPortion) {
322         List<ListenableFuture<RpcResult<RemoveGroupOutput>>> allResults = new ArrayList<>();
323         for (Group group : groupsPortion.getItemsToPush()) {
324             final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class, group.getKey());
325             allResults.add(JdkFutureAdapters.listenInPoolThread(groupForwarder.remove(groupIdent, group, nodeIdent)));
326         }
327
328         final ListenableFuture<RpcResult<Void>> singleVoidResult = Futures.transform(
329                 Futures.allAsList(allResults),
330                 ReconcileUtil.<RemoveGroupOutput>createRpcResultCondenser("group remove"));
331
332         return Futures.transformAsync(singleVoidResult,
333                 ReconcileUtil.chainBarrierFlush(PathUtil.digNodePath(nodeIdent), transactionService));
334     }
335
336     ListenableFuture<RpcResult<Void>> updateTableFeatures(final InstanceIdentifier<FlowCapableNode> nodeIdent,
337                                                           final FlowCapableNode flowCapableNodeConfigured) {
338         // CHECK if while pushing the update, updateTableInput can be null to emulate a table add
339         final List<Table> tableList = ReconcileUtil.safeTables(flowCapableNodeConfigured);
340
341         final List<ListenableFuture<RpcResult<UpdateTableOutput>>> allResults = new ArrayList<>();
342         for (Table table : tableList) {
343             TableKey tableKey = table.getKey();
344             KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdent
345                     .child(TableFeatures.class, new TableFeaturesKey(tableKey.getId()));
346             List<TableFeatures> tableFeatures = flowCapableNodeConfigured.getTableFeatures();
347             if (tableFeatures != null) {
348                 for (TableFeatures tableFeaturesItem : tableFeatures) {
349                     // TODO uncomment java.lang.NullPointerException
350                     // at
351                     // org.opendaylight.openflowjava.protocol.impl.serialization.match.AbstractOxmMatchEntrySerializer.serializeHeader(AbstractOxmMatchEntrySerializer.java:31
352                     // allResults.add(JdkFutureAdapters.listenInPoolThread(
353                     // tableForwarder.update(tableFeaturesII, null, tableFeaturesItem, nodeIdent)));
354                 }
355             }
356         }
357
358         final ListenableFuture<RpcResult<Void>> singleVoidResult = Futures.transform(
359                 Futures.allAsList(allResults),
360                 ReconcileUtil.<UpdateTableOutput>createRpcResultCondenser("table update"));
361
362         return Futures.transformAsync(singleVoidResult,
363                 ReconcileUtil.chainBarrierFlush(PathUtil.digNodePath(nodeIdent), transactionService));
364     }
365
366     private ListenableFuture<RpcResult<Void>> flushAddGroupPortionAndBarrier(
367             final InstanceIdentifier<FlowCapableNode> nodeIdent,
368             final ItemSyncBox<Group> groupsPortion) {
369         final List<ListenableFuture<RpcResult<AddGroupOutput>>> allResults = new ArrayList<>();
370         final List<ListenableFuture<RpcResult<UpdateGroupOutput>>> allUpdateResults = new ArrayList<>();
371
372         for (Group group : groupsPortion.getItemsToPush()) {
373             final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class, group.getKey());
374             allResults.add(JdkFutureAdapters.listenInPoolThread(groupForwarder.add(groupIdent, group, nodeIdent)));
375
376         }
377
378         for (ItemSyncBox.ItemUpdateTuple<Group> groupTuple : groupsPortion.getItemsToUpdate()) {
379             final Group existingGroup = groupTuple.getOriginal();
380             final Group group = groupTuple.getUpdated();
381
382             final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class, group.getKey());
383             allUpdateResults.add(JdkFutureAdapters.listenInPoolThread(
384                     groupForwarder.update(groupIdent, existingGroup, group, nodeIdent)));
385         }
386
387         final ListenableFuture<RpcResult<Void>> singleVoidAddResult = Futures.transform(
388                 Futures.allAsList(allResults), ReconcileUtil.<AddGroupOutput>createRpcResultCondenser("group add"));
389
390         final ListenableFuture<RpcResult<Void>> singleVoidUpdateResult = Futures.transform(
391                 Futures.allAsList(allUpdateResults),
392                 ReconcileUtil.<UpdateGroupOutput>createRpcResultCondenser("group update"));
393
394         final ListenableFuture<RpcResult<Void>> summaryResult = Futures.transform(
395                 Futures.allAsList(singleVoidAddResult, singleVoidUpdateResult),
396                 ReconcileUtil.<Void>createRpcResultCondenser("group add/update"));
397
398
399         return Futures.transformAsync(summaryResult, ReconcileUtil.chainBarrierFlush(
400                 PathUtil.digNodePath(nodeIdent), transactionService));
401     }
402
403     ListenableFuture<RpcResult<Void>> addMissingMeters(final NodeId nodeId,
404                                                        final InstanceIdentifier<FlowCapableNode> nodeIdent,
405                                                        final ItemSyncBox<Meter> syncBox,
406                                                        final SyncCrudCounters counters) {
407         if (syncBox.isEmpty()) {
408             LOG.trace("no meters configured for node: {} -> SKIPPING", nodeId.getValue());
409             return RpcResultBuilder.<Void>success().buildFuture();
410         }
411
412         final CrudCounts meterCrudCounts = counters.getMeterCrudCounts();
413
414         final List<ListenableFuture<RpcResult<AddMeterOutput>>> allResults = new ArrayList<>();
415         final List<ListenableFuture<RpcResult<UpdateMeterOutput>>> allUpdateResults = new ArrayList<>();
416         for (Meter meter : syncBox.getItemsToPush()) {
417             final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class, meter.getKey());
418             LOG.debug("adding meter {} - absent on device {}",
419                     meter.getMeterId(), nodeId);
420             allResults.add(JdkFutureAdapters.listenInPoolThread(
421                     meterForwarder.add(meterIdent, meter, nodeIdent)));
422             meterCrudCounts.incAdded();
423         }
424
425         for (ItemSyncBox.ItemUpdateTuple<Meter> meterTuple : syncBox.getItemsToUpdate()) {
426             final Meter existingMeter = meterTuple.getOriginal();
427             final Meter updated = meterTuple.getUpdated();
428             final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class, updated.getKey());
429             LOG.trace("meter {} - needs update on device {}", updated.getMeterId(), nodeId);
430             allUpdateResults.add(JdkFutureAdapters.listenInPoolThread(
431                     meterForwarder.update(meterIdent, existingMeter, updated, nodeIdent)));
432             meterCrudCounts.incUpdated();
433         }
434
435         final ListenableFuture<RpcResult<Void>> singleVoidAddResult = Futures.transform(
436                 Futures.allAsList(allResults), ReconcileUtil.<AddMeterOutput>createRpcResultCondenser("meter add"));
437
438         final ListenableFuture<RpcResult<Void>> singleVoidUpdateResult = Futures.transform(
439                 Futures.allAsList(allUpdateResults),
440                 ReconcileUtil.<UpdateMeterOutput>createRpcResultCondenser("meter update"));
441
442         return Futures.transform(Futures.allAsList(singleVoidUpdateResult, singleVoidAddResult),
443                 ReconcileUtil.<Void>createRpcResultCondenser("meter add/update"));
444     }
445
446     ListenableFuture<RpcResult<Void>> addMissingGroups(final NodeId nodeId,
447                                                        final InstanceIdentifier<FlowCapableNode> nodeIdent,
448                                                        final List<ItemSyncBox<Group>> groupsAddPlan,
449                                                        final SyncCrudCounters counters) {
450         if (groupsAddPlan.isEmpty()) {
451             LOG.trace("no groups configured for node: {} -> SKIPPING", nodeId.getValue());
452             return RpcResultBuilder.<Void>success().buildFuture();
453         }
454
455         ListenableFuture<RpcResult<Void>> chainedResult;
456         try {
457             if (!groupsAddPlan.isEmpty()) {
458                 final CrudCounts groupCrudCounts = counters.getGroupCrudCounts();
459                 groupCrudCounts.setAdded(ReconcileUtil.countTotalPushed(groupsAddPlan));
460                 groupCrudCounts.setUpdated(ReconcileUtil.countTotalUpdated(groupsAddPlan));
461
462                 if (LOG.isDebugEnabled()) {
463                     LOG.debug("adding groups: planSteps={}, toAddTotal={}, toUpdateTotal={}",
464                             groupsAddPlan.size(),
465                             groupCrudCounts.getAdded(),
466                             groupCrudCounts.getUpdated());
467                 }
468
469                 chainedResult = flushAddGroupPortionAndBarrier(nodeIdent, groupsAddPlan.get(0));
470                 for (final ItemSyncBox<Group> groupsPortion : Iterables.skip(groupsAddPlan, 1)) {
471                     chainedResult =
472                             Futures.transformAsync(chainedResult, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
473                                 @Override
474                                 public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input)
475                                         throws Exception {
476                                     final ListenableFuture<RpcResult<Void>> result;
477                                     if (input.isSuccessful()) {
478                                         result = flushAddGroupPortionAndBarrier(nodeIdent, groupsPortion);
479                                     } else {
480                                         // pass through original unsuccessful rpcResult
481                                         result = Futures.immediateFuture(input);
482                                     }
483
484                                     return result;
485                                 }
486                             });
487                 }
488             } else {
489                 chainedResult = RpcResultBuilder.<Void>success().buildFuture();
490             }
491         } catch (IllegalStateException e) {
492             chainedResult = RpcResultBuilder.<Void>failed()
493                     .withError(RpcError.ErrorType.APPLICATION, "failed to add missing groups", e)
494                     .buildFuture();
495         }
496
497         return chainedResult;
498     }
499
500
501     public SyncPlanPushStrategyIncrementalImpl setFlowForwarder(final FlowForwarder flowForwarder) {
502         this.flowForwarder = flowForwarder;
503         return this;
504     }
505
506     public SyncPlanPushStrategyIncrementalImpl setTableForwarder(final TableForwarder tableForwarder) {
507         this.tableForwarder = tableForwarder;
508         return this;
509     }
510
511     public SyncPlanPushStrategyIncrementalImpl setMeterForwarder(final MeterForwarder meterForwarder) {
512         this.meterForwarder = meterForwarder;
513         return this;
514     }
515
516     public SyncPlanPushStrategyIncrementalImpl setGroupForwarder(final GroupForwarder groupForwarder) {
517         this.groupForwarder = groupForwarder;
518         return this;
519     }
520
521     public SyncPlanPushStrategyIncrementalImpl setTransactionService(final FlowCapableTransactionService transactionService) {
522         this.transactionService = transactionService;
523         return this;
524     }
525
526 }