Merge "Remove unneeded boxing"
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / BundleFlowForwarder.java
1 /*
2  * Copyright (c) 2018 Ericsson India Global Services Pvt Ltd. 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.applications.frm.util.FrmUtil.buildGroupInstanceIdentifier;
11 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getFlowId;
12 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getNodeIdValueFromNodeIdentifier;
13 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getTableId;
14 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.isFlowDependentOnGroup;
15 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.isGroupExistsOnDevice;
16
17 import com.google.common.base.Preconditions;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.concurrent.ExecutionException;
28 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
29 import org.opendaylight.mdsal.binding.api.ReadTransaction;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.openflowplugin.applications.frm.BundleMessagesCommiter;
32 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
33 import org.opendaylight.openflowplugin.applications.frm.NodeConfigurator;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupRef;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.BundleInnerMessage;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddFlowCaseBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddGroupCaseBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.flow._case.AddFlowCaseDataBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.group._case.AddGroupCaseDataBuilder;
54 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;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
57 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
58 import org.opendaylight.yangtools.yang.common.RpcError;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
61 import org.opendaylight.yangtools.yang.common.Uint32;
62 import org.opendaylight.yangtools.yang.common.Uint8;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 public class BundleFlowForwarder implements BundleMessagesCommiter<Flow> {
67
68     private static final Logger LOG = LoggerFactory.getLogger(BundleFlowForwarder.class);
69     private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
70     private final ForwardingRulesManager forwardingRulesManager;
71     private final NodeConfigurator nodeConfigurator;
72
73     public BundleFlowForwarder(ForwardingRulesManager forwardingRulesManager) {
74         this.forwardingRulesManager = Preconditions.checkNotNull(forwardingRulesManager,
75                 "ForwardingRulesManager can not be null!");
76         this.nodeConfigurator = Preconditions.checkNotNull(forwardingRulesManager.getNodeConfigurator(),
77                 "NodeConfigurator can not be null!");
78     }
79
80     @Override
81     public void remove(final InstanceIdentifier<Flow> identifier,
82                        final Flow flow,
83                        final InstanceIdentifier<FlowCapableNode> nodeIdent,
84                        final BundleId bundleId) {
85         final String nodeId = getNodeIdValueFromNodeIdentifier(nodeIdent);
86         nodeConfigurator.enqueueJob(nodeId, () -> {
87             final List<Message> messages = new ArrayList<>(1);
88             String node = nodeIdent.firstKeyOf(Node.class).getId().getValue();
89             BundleInnerMessage bundleInnerMessage = new BundleRemoveFlowCaseBuilder()
90                 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(flow).build()).build();
91             Message message = new MessageBuilder()
92                 .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
93                 .setBundleInnerMessage(bundleInnerMessage)
94                 .build();
95             messages.add(message);
96             AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
97                 .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
98                 .setBundleId(bundleId)
99                 .setFlags(BUNDLE_FLAGS).setMessages(new MessagesBuilder()
100                         .setMessage(messages)
101                         .build())
102                 .build();
103             final ListenableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture = forwardingRulesManager
104                 .getSalBundleService().addBundleMessages(addBundleMessagesInput);
105             LOG.trace("Pushing flow remove message {} to bundle {} for device {}", addBundleMessagesInput,
106                 bundleId.getValue(), node);
107             LoggingFutures.addErrorLogging(resultFuture, LOG, "removeBundleFlow");
108             return resultFuture;
109         });
110     }
111
112     @Override
113     public void update(final InstanceIdentifier<Flow> identifier,
114                        final Flow originalFlow,
115                        final Flow updatedFlow,
116                        final InstanceIdentifier<FlowCapableNode> nodeIdent,
117                        final BundleId bundleId) {
118         remove(identifier, originalFlow, nodeIdent, bundleId);
119         add(identifier, updatedFlow, nodeIdent, bundleId);
120     }
121
122     @Override
123     public ListenableFuture<RpcResult<AddBundleMessagesOutput>> add(final InstanceIdentifier<Flow> identifier,
124                                                                     final Flow flow,
125                                                                     final InstanceIdentifier<FlowCapableNode> nodeIdent,
126                                                                     final BundleId bundleId) {
127         final String nodeId = getNodeIdValueFromNodeIdentifier(nodeIdent);
128         return nodeConfigurator.enqueueJob(nodeId, () -> {
129             BundleInnerMessage bundleInnerMessage = new BundleAddFlowCaseBuilder()
130                     .setAddFlowCaseData(new AddFlowCaseDataBuilder(flow)
131                             .build())
132                     .build();
133             Message message = new MessageBuilder().setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
134                     .setBundleInnerMessage(bundleInnerMessage)
135                     .build();
136             ListenableFuture<RpcResult<AddBundleMessagesOutput>> groupFuture = pushDependentGroup(nodeIdent, flow,
137                     identifier, bundleId);
138             SettableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture = SettableFuture.create();
139             Futures.addCallback(groupFuture,
140                     new BundleFlowCallBack(nodeIdent, bundleId, message, identifier, resultFuture),
141                     MoreExecutors.directExecutor());
142             return resultFuture;
143         });
144     }
145
146     private ListenableFuture<RpcResult<AddBundleMessagesOutput>> pushDependentGroup(
147             final InstanceIdentifier<FlowCapableNode> nodeIdent,
148             final Flow updatedFlow,
149             final InstanceIdentifier<Flow> identifier,
150             final BundleId bundleId) {
151         //TODO This read to the DS might have a performance impact.
152         //if the dependent group is not installed than we should just cache the parent group,
153         //till we receive the dependent group DTCN and then push it.
154         Uint32 groupId = isFlowDependentOnGroup(updatedFlow);
155         ListenableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture;
156         if (groupId != null) {
157             LOG.trace("The flow {} is dependent on group {}. Checking if the group is already present",
158                     getFlowId(identifier), groupId);
159             if (isGroupExistsOnDevice(nodeIdent, groupId, forwardingRulesManager)) {
160                 LOG.trace("The dependent group {} is already programmed. Updating the flow {}", groupId,
161                         getFlowId(identifier));
162                 resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>success().build());
163             } else {
164                 LOG.trace("The dependent group {} isn't programmed yet. Pushing the group", groupId);
165                 InstanceIdentifier<Group> groupIdent = buildGroupInstanceIdentifier(nodeIdent, groupId);
166                 LOG.info("Reading the group from config inventory: {}", groupId);
167                 try (ReadTransaction readTransaction = forwardingRulesManager.getReadTransaction()) {
168                     Optional<Group> group = readTransaction.read(LogicalDatastoreType.CONFIGURATION, groupIdent).get();
169                     if (group.isPresent()) {
170                         final AddGroupInputBuilder builder = new AddGroupInputBuilder(group.get());
171                         builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
172                         builder.setGroupRef(new GroupRef(nodeIdent));
173                         builder.setTransactionUri(new Uri(forwardingRulesManager.getNewTransactionId()));
174                         BundleInnerMessage bundleInnerMessage = new BundleAddGroupCaseBuilder()
175                                 .setAddGroupCaseData(new AddGroupCaseDataBuilder(group.get()).build()).build();
176                         Message groupMessage = new MessageBuilder()
177                                 .setNode(
178                                 new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
179                                 .setBundleInnerMessage(bundleInnerMessage)
180                                 .build();
181                         final List<Message> messages = new ArrayList<>(1);
182                         messages.add(groupMessage);
183                         AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
184                                 .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
185                                 .setBundleId(bundleId)
186                                 .setFlags(BUNDLE_FLAGS)
187                                 .setMessages(new MessagesBuilder()
188                                         .setMessage(messages).build())
189                                 .build();
190                         LOG.trace("Pushing flow update message {} to bundle {} for device {}", addBundleMessagesInput,
191                                 bundleId.getValue(), getNodeIdValueFromNodeIdentifier(nodeIdent));
192                         resultFuture = forwardingRulesManager
193                                 .getSalBundleService()
194                                 .addBundleMessages(addBundleMessagesInput);
195                         Futures.transformAsync(resultFuture, rpcResult -> {
196                             if (rpcResult.isSuccessful()) {
197                                 forwardingRulesManager.getDevicesGroupRegistry()
198                                         .storeGroup(getNodeIdValueFromNodeIdentifier(nodeIdent), groupId);
199                                 LOG.trace("Group {} stored in cache", groupId);
200                             }
201                             return Futures.immediateFuture(null);
202                         }, MoreExecutors.directExecutor());
203                     } else {
204                         LOG.debug("Group {} not present in the config inventory", groupId);
205                         resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>failed()
206                                 .withError(RpcError.ErrorType.APPLICATION,
207                                         "Group " + groupId + " not present in the config inventory").build());
208                     }
209                 } catch (InterruptedException | ExecutionException e) {
210                     LOG.error("Error while reading group from config datastore for the group ID {}", groupId, e);
211                     resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>failed()
212                             .withError(RpcError.ErrorType.APPLICATION,
213                                     "Group " + groupId + " not present in the config inventory").build());
214                 }
215             }
216         } else {
217             resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>success().build());
218         }
219         return resultFuture;
220     }
221
222     private final class BundleFlowCallBack implements FutureCallback<RpcResult<AddBundleMessagesOutput>> {
223         private final InstanceIdentifier<FlowCapableNode> nodeIdent;
224         private final BundleId bundleId;
225         private final Message messages;
226         private final String nodeId;
227         private final String flowId;
228         private final Uint8 tableId;
229         private final SettableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture;
230
231         BundleFlowCallBack(InstanceIdentifier<FlowCapableNode> nodeIdent, BundleId bundleId, Message messages,
232             InstanceIdentifier<Flow> identifier , SettableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture) {
233             this.nodeIdent = nodeIdent;
234             this.bundleId = bundleId;
235             this.messages = messages;
236             this.resultFuture = resultFuture;
237             this.flowId = getFlowId(identifier);
238             this.tableId = getTableId(identifier);
239             nodeId = getNodeIdValueFromNodeIdentifier(nodeIdent);
240         }
241
242         @Override
243         public void onSuccess(RpcResult<AddBundleMessagesOutput> rpcResult) {
244             if (rpcResult.isSuccessful()) {
245                 AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
246                         .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
247                         .setBundleId(bundleId)
248                         .setFlags(BUNDLE_FLAGS)
249                         .setMessages(new MessagesBuilder()
250                                 .setMessage(
251                                         Collections.singletonList(messages)).build())
252                         .build();
253
254                 LOG.trace("Pushing flow add message {} to bundle {} for device {}", addBundleMessagesInput,
255                         bundleId.getValue(), nodeId);
256
257                 final ListenableFuture<RpcResult<AddBundleMessagesOutput>> addFuture =
258                         forwardingRulesManager.getSalBundleService().addBundleMessages(addBundleMessagesInput);
259                 Futures.addCallback(addFuture, new FutureCallback<RpcResult<AddBundleMessagesOutput>>() {
260                     @Override
261                     public void onSuccess(RpcResult<AddBundleMessagesOutput> result) {
262                         resultFuture.set(result);
263                         if (!result.getErrors().isEmpty()) {
264                             LOG.error("Flow add with flowId {} and tableId {} failed for node {} with error: {}",
265                                     flowId, tableId, nodeId, result.getErrors().toString());
266                         }
267
268                     }
269
270                     @Override
271                     public void onFailure(Throwable failure) {
272                         resultFuture.setException(failure);
273                     }
274                 },  MoreExecutors.directExecutor());
275             } else {
276                 LOG.error("Error {} while pushing flow add bundle {} for device {}", rpcResult.getErrors(), messages,
277                         nodeId);
278                 resultFuture.set(rpcResult);
279             }
280         }
281
282         @Override
283         public void onFailure(Throwable throwable) {
284             LOG.error("Error while pushing flow add bundle {} for device {}", messages, nodeId);
285             resultFuture.setException(throwable);
286         }
287     }
288 }