Bump MRI upstreams
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / util / ReconcileUtil.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 package org.opendaylight.openflowplugin.applications.frsync.util;
9
10 import com.google.common.base.Function;
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.ListenableFuture;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.Set;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.FlowCapableTransactionService;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.SendBarrierInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.SendBarrierInputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.SendBarrierOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.opendaylight.yangtools.yang.common.ErrorType;
44 import org.opendaylight.yangtools.yang.common.RpcError;
45 import org.opendaylight.yangtools.yang.common.RpcResult;
46 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
47 import org.opendaylight.yangtools.yang.common.Uint32;
48 import org.opendaylight.yangtools.yang.common.Uint8;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * Util methods for group reconcil task (future chaining, transforms).
54  */
55 public final class ReconcileUtil {
56     private static final Logger LOG = LoggerFactory.getLogger(ReconcileUtil.class);
57
58     private ReconcileUtil() {
59         // Hidden on purpose
60     }
61
62     /**
63      * Creates a single rpc result of type Void honoring all partial rpc results.
64      *
65      * @param previousItemAction description for case when the triggering future contains failure
66      * @param <D>                type of rpc output (gathered in list)
67      * @return single rpc result of type Void honoring all partial rpc results
68      */
69     public static <D> Function<List<RpcResult<D>>, RpcResult<Void>> createRpcResultCondenser(
70             final String previousItemAction) {
71         return input -> {
72             final RpcResultBuilder<Void> resultSink;
73             if (input != null) {
74                 List<RpcError> errors = new ArrayList<>();
75                 for (RpcResult<D> rpcResult : input) {
76                     if (!rpcResult.isSuccessful()) {
77                         errors.addAll(rpcResult.getErrors());
78                     }
79                 }
80                 if (errors.isEmpty()) {
81                     resultSink = RpcResultBuilder.success();
82                 } else {
83                     resultSink = RpcResultBuilder.<Void>failed().withRpcErrors(errors);
84                 }
85             } else {
86                 resultSink = RpcResultBuilder.<Void>failed()
87                         .withError(ErrorType.APPLICATION, "previous " + previousItemAction + " failed");
88             }
89             return resultSink.build();
90         };
91     }
92
93     /**
94      * Creates a single rpc result of type Void honoring all partial rpc results.
95      *
96      * @param actionDescription description for case when the triggering future contains failure
97      * @param <D>               type of rpc output (gathered in list)
98      * @return single rpc result of type Void honoring all partial rpc results
99      */
100     public static <D> Function<RpcResult<D>, RpcResult<Void>> createRpcResultToVoidFunction(
101             final String actionDescription) {
102         return input -> {
103             final RpcResultBuilder<Void> resultSink;
104             if (input != null) {
105                 List<RpcError> errors = new ArrayList<>();
106                 if (!input.isSuccessful()) {
107                     errors.addAll(input.getErrors());
108                     resultSink = RpcResultBuilder.<Void>failed().withRpcErrors(errors);
109                 } else {
110                     resultSink = RpcResultBuilder.success();
111                 }
112             } else {
113                 resultSink = RpcResultBuilder.<Void>failed()
114                         .withError(ErrorType.APPLICATION, "action of " + actionDescription + " failed");
115             }
116             return resultSink.build();
117         };
118     }
119
120     /**
121      * Flushes a chain barrier.
122      *
123      * @param nodeIdent flow capable node path - target device for routed rpc
124      * @param flowCapableTransactionService barrier rpc service
125      * @return async barrier result
126      */
127     public static AsyncFunction<RpcResult<Void>, RpcResult<Void>> chainBarrierFlush(
128             final InstanceIdentifier<Node> nodeIdent,
129             final FlowCapableTransactionService flowCapableTransactionService) {
130         return input -> {
131             final SendBarrierInput barrierInput = new SendBarrierInputBuilder()
132                     .setNode(new NodeRef(nodeIdent))
133                     .build();
134             ListenableFuture<RpcResult<SendBarrierOutput>> result
135                     = flowCapableTransactionService.sendBarrier(barrierInput);
136
137             return Futures.transformAsync(result, input1 -> {
138                 if (input1.isSuccessful()) {
139                     return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
140                 } else {
141                     return Futures.immediateFailedFuture(null);
142                 }
143             }, MoreExecutors.directExecutor());
144         };
145     }
146
147     /**
148      * Returns a list of safe synchronization steps with updates.
149      *
150      * @param nodeId target node
151      * @param installedGroupsArg groups resent on device
152      * @param pendingGroups      groups configured for device
153      * @return list of safe synchronization steps with updates
154      */
155     public static List<ItemSyncBox<Group>> resolveAndDivideGroupDiffs(final NodeId nodeId,
156                                                                       final Map<Uint32, Group> installedGroupsArg,
157                                                                       final Collection<Group> pendingGroups) {
158         return resolveAndDivideGroupDiffs(nodeId, installedGroupsArg, pendingGroups, true);
159     }
160
161     /**
162      * Returns a list of safe synchronization steps.
163      *
164      * @param nodeId             target node
165      * @param installedGroupsArg groups resent on device
166      * @param pendingGroups      groups configured for device
167      * @param gatherUpdates      check content of pending item if present on device (and create update task eventually)
168      * @return list of safe synchronization steps
169      */
170     public static List<ItemSyncBox<Group>> resolveAndDivideGroupDiffs(final NodeId nodeId,
171                                                                       final Map<Uint32, Group> installedGroupsArg,
172                                                                       final Collection<Group> pendingGroups,
173                                                                       final boolean gatherUpdates) {
174         final Map<Uint32, Group> installedGroups = new HashMap<>(installedGroupsArg);
175         final List<ItemSyncBox<Group>> plan = new ArrayList<>();
176
177         while (!Iterables.isEmpty(pendingGroups)) {
178             final ItemSyncBox<Group> stepPlan = new ItemSyncBox<>();
179             final Iterator<Group> iterator = pendingGroups.iterator();
180             final Map<Uint32, Group> installIncrement = new HashMap<>();
181
182             while (iterator.hasNext()) {
183                 final Group group = iterator.next();
184
185                 final Group existingGroup = installedGroups.get(group.getGroupId().getValue());
186                 if (existingGroup != null) {
187                     if (!gatherUpdates || group.equals(existingGroup)) {
188                         iterator.remove();
189                     } else if (checkGroupPrecondition(installedGroups.keySet(), group)) {
190                         // check buckets and eventually update
191                         iterator.remove();
192                         LOG.trace("Group {} on device {} differs - planned for update", group.getGroupId(), nodeId);
193                         stepPlan.getItemsToUpdate().add(new ItemSyncBox.ItemUpdateTuple<>(existingGroup, group));
194                     }
195                 } else if (checkGroupPrecondition(installedGroups.keySet(), group)) {
196                     iterator.remove();
197                     installIncrement.put(group.getGroupId().getValue(), group);
198                     stepPlan.getItemsToPush().add(group);
199                 }
200             }
201
202             if (!stepPlan.isEmpty()) {
203                 // atomic update of installed flows in order to keep plan portions clean of local group dependencies
204                 installedGroups.putAll(installIncrement);
205                 plan.add(stepPlan);
206             } else if (!pendingGroups.isEmpty()) {
207                 LOG.warn("Failed to resolve and divide groups into preconditions-match based ordered plan: {}, "
208                         + "resolving stuck at level {}", nodeId.getValue(), plan.size());
209                 throw new IllegalStateException("Failed to resolve and divide groups when matching preconditions");
210             }
211         }
212
213         return plan;
214     }
215
216     public static boolean checkGroupPrecondition(final Set<Uint32> installedGroupIds, final Group pendingGroup) {
217         boolean okToInstall = true;
218         // check each bucket in the pending group
219         for (Bucket bucket : pendingGroup.getBuckets().nonnullBucket().values()) {
220             for (Action action : bucket.nonnullAction().values()) {
221                 // if the output action is a group
222                 if (GroupActionCase.class.equals(action.getAction().implementedInterface())) {
223                     Uint32 groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
224                     // see if that output group is installed
225                     if (!installedGroupIds.contains(groupId)) {
226                         // if not installed, we have missing dependencies and cannot install this pending group
227                         okToInstall = false;
228                         break;
229                     }
230                 }
231             }
232             if (!okToInstall) {
233                 break;
234             }
235         }
236         return okToInstall;
237     }
238
239     public static <E> int countTotalPushed(final Iterable<ItemSyncBox<E>> groupsAddPlan) {
240         int count = 0;
241         for (ItemSyncBox<E> groupItemSyncBox : groupsAddPlan) {
242             count += groupItemSyncBox.getItemsToPush().size();
243         }
244         return count;
245     }
246
247     public static <E> int countTotalUpdated(final Iterable<ItemSyncBox<E>> groupsAddPlan) {
248         int count = 0;
249         for (ItemSyncBox<E> groupItemSyncBox : groupsAddPlan) {
250             count += groupItemSyncBox.getItemsToUpdate().size();
251         }
252         return count;
253     }
254
255     /**
256      * Resolves meter differences.
257      *
258      * @param nodeId              target node
259      * @param meterOperationalMap meters present on device
260      * @param metersConfigured    meters configured for device
261      * @param gatherUpdates       check content of pending item if present on device (and create update task eventually)
262      * @return synchronization box
263      */
264     public static ItemSyncBox<Meter> resolveMeterDiffs(final NodeId nodeId,
265                                                        final Map<MeterId, Meter> meterOperationalMap,
266                                                        final Collection<Meter> metersConfigured,
267                                                        final boolean gatherUpdates) {
268         LOG.trace("resolving meters for {}", nodeId.getValue());
269         final ItemSyncBox<Meter> syncBox = new ItemSyncBox<>();
270         for (Meter meter : metersConfigured) {
271             final Meter existingMeter = meterOperationalMap.get(meter.getMeterId());
272             if (existingMeter == null) {
273                 syncBox.getItemsToPush().add(meter);
274             } else {
275                 // compare content and eventually update
276                 if (gatherUpdates && !meter.equals(existingMeter)) {
277                     syncBox.getItemsToUpdate().add(new ItemSyncBox.ItemUpdateTuple<>(existingMeter, meter));
278                 }
279             }
280         }
281         return syncBox;
282     }
283
284     /**
285      * Resolves flow differences in a table.
286      *
287      * @param flowsConfigured    flows resent on device
288      * @param flowOperationalMap flows configured for device
289      * @param gatherUpdates      check content of pending item if present on device (and create update task eventually)
290      * @return list of safe synchronization steps
291      */
292     private static ItemSyncBox<Flow> resolveFlowDiffsInTable(final Collection<Flow> flowsConfigured,
293                                                             final Map<FlowDescriptor, Flow> flowOperationalMap,
294                                                             final boolean gatherUpdates) {
295         final ItemSyncBox<Flow> flowsSyncBox = new ItemSyncBox<>();
296         // loop configured flows and check if already present on device
297         for (final Flow flow : flowsConfigured) {
298             final Flow existingFlow = FlowCapableNodeLookups.flowMapLookupExisting(flow, flowOperationalMap);
299
300             if (existingFlow == null) {
301                 flowsSyncBox.getItemsToPush().add(flow);
302             } else {
303                 // check instructions and eventually update
304                 if (gatherUpdates && !Objects.equals(flow.getInstructions(), existingFlow.getInstructions())) {
305                     flowsSyncBox.getItemsToUpdate().add(new ItemSyncBox.ItemUpdateTuple<>(existingFlow, flow));
306                 }
307             }
308         }
309         return flowsSyncBox;
310     }
311
312     /**
313      * Resolves flow differences in all tables.
314      *
315      * @param nodeId              target node
316      * @param tableOperationalMap flow-tables resent on device
317      * @param tablesConfigured    flow-tables configured for device
318      * @param gatherUpdates       check content of pending item if present on device (and create update task eventually)
319      * @return map : key={@link TableKey}, value={@link ItemSyncBox} of safe synchronization steps
320      */
321     public static Map<TableKey, ItemSyncBox<Flow>> resolveFlowDiffsInAllTables(final NodeId nodeId,
322             final Map<Uint8, Table> tableOperationalMap, final Collection<Table> tablesConfigured,
323             final boolean gatherUpdates) {
324         LOG.trace("resolving flows in tables for {}", nodeId.getValue());
325         final Map<TableKey, ItemSyncBox<Flow>> tableFlowSyncBoxes = new HashMap<>();
326         for (final Table tableConfigured : tablesConfigured) {
327             final Collection<Flow> flowsConfigured = tableConfigured.nonnullFlow().values();
328             if (flowsConfigured.isEmpty()) {
329                 continue;
330             }
331
332             // lookup table (on device)
333             final Table tableOperational = tableOperationalMap.get(tableConfigured.getId());
334             // wrap existing (on device) flows in current table into map
335             final Map<FlowDescriptor, Flow> flowOperationalMap = FlowCapableNodeLookups.wrapFlowsToMap(
336                     tableOperational != null
337                             ? tableOperational.nonnullFlow().values()
338                             : null);
339
340
341             final ItemSyncBox<Flow> flowsSyncBox = resolveFlowDiffsInTable(
342                     flowsConfigured, flowOperationalMap, gatherUpdates);
343             if (!flowsSyncBox.isEmpty()) {
344                 tableFlowSyncBoxes.put(tableConfigured.key(), flowsSyncBox);
345             }
346         }
347         return tableFlowSyncBoxes;
348     }
349
350     public static Collection<Group> safeGroups(FlowCapableNode node) {
351         return node == null ? Collections.emptyList() : node.nonnullGroup().values();
352     }
353
354     public static Collection<Table> safeTables(FlowCapableNode node) {
355         return node == null ? Collections.emptyList() : node.nonnullTable().values();
356     }
357
358     public static Collection<Meter> safeMeters(FlowCapableNode node) {
359         return node == null ? Collections.emptyList() : node.nonnullMeter().values();
360     }
361 }