1c3ded8b7bc051b2c6517f4189ee5a7aaf213473
[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.getNodeIdFromNodeIdentifier;
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.flow.service.rev130819.FlowTableRef;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupRef;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.BundleInnerMessage;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddFlowCaseBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddGroupCaseBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
55 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;
56 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;
57 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;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
60 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
61 import org.opendaylight.yangtools.yang.common.RpcResult;
62 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
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     public void remove(final InstanceIdentifier<Flow> identifier, final Flow flow,
81             final InstanceIdentifier<FlowCapableNode> nodeIdent, final BundleId bundleId) {
82         final List<Message> messages = new ArrayList<>(1);
83         String node = nodeIdent.firstKeyOf(Node.class).getId().getValue();
84         BundleInnerMessage bundleInnerMessage = new BundleRemoveFlowCaseBuilder()
85                 .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(flow).build()).build();
86         Message message = new MessageBuilder().setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
87                 .setBundleInnerMessage(bundleInnerMessage).build();
88         messages.add(message);
89         AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
90                 .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class))).setBundleId(bundleId)
91                 .setFlags(BUNDLE_FLAGS).setMessages(new MessagesBuilder().setMessage(messages).build()).build();
92         final ListenableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture = forwardingRulesManager
93                 .getSalBundleService().addBundleMessages(addBundleMessagesInput);
94         LOG.trace("Pushing flow remove message {} to bundle {} for device {}", addBundleMessagesInput,
95                 bundleId.getValue(), node);
96         LoggingFutures.addErrorLogging(resultFuture, LOG, "removeBundleFlow");
97     }
98
99     public void update(final InstanceIdentifier<Flow> identifier, final Flow originalFlow, final Flow updatedFlow,
100             final InstanceIdentifier<FlowCapableNode> nodeIdent, final BundleId bundleId) {
101         remove(identifier, originalFlow, nodeIdent, bundleId);
102         add(identifier, updatedFlow, nodeIdent, bundleId);
103     }
104
105     @Override
106     public ListenableFuture<RpcResult<AddBundleMessagesOutput>> add(final InstanceIdentifier<Flow> identifier,
107                                                                     final Flow flow,
108             final InstanceIdentifier<FlowCapableNode> nodeIdent, final BundleId bundleId) {
109         final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
110         return nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
111             BundleInnerMessage bundleInnerMessage = new BundleAddFlowCaseBuilder()
112                     .setAddFlowCaseData(new AddFlowCaseDataBuilder(flow).build()).build();
113             Message message = new MessageBuilder().setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
114                     .setBundleInnerMessage(bundleInnerMessage).build();
115             ListenableFuture<RpcResult<AddBundleMessagesOutput>> groupFuture = pushDependentGroup(nodeIdent, flow,
116                     identifier, bundleId);
117             SettableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture = SettableFuture.create();
118             Futures.addCallback(groupFuture, new BundleFlowCallBack(nodeIdent, bundleId, message, identifier,
119                     resultFuture), MoreExecutors.directExecutor());
120             return resultFuture;
121         });
122     }
123
124     private ListenableFuture<RpcResult<AddBundleMessagesOutput>> pushDependentGroup(
125             final InstanceIdentifier<FlowCapableNode> nodeIdent, Flow updatedFlow, InstanceIdentifier<Flow> identifier,
126             BundleId bundleId) {
127         //TODO This read to the DS might have a performance impact.
128         //if the dependent group is not installed than we should just cache the parent group,
129         //till we receive the dependent group DTCN and then push it.
130         Long groupId = isFlowDependentOnGroup(updatedFlow);
131         ListenableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture;
132         if (groupId != null) {
133             LOG.trace("The flow {} is dependent on group {}. Checking if the group is already present",
134                     getFlowId(new FlowRef(identifier)), groupId);
135             if (isGroupExistsOnDevice(nodeIdent, groupId, forwardingRulesManager)) {
136                 LOG.trace("The dependent group {} is already programmed. Updating the flow {}", groupId,
137                         getFlowId(new FlowRef(identifier)));
138                 resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>success().build());
139             } else {
140                 LOG.trace("The dependent group {} isn't programmed yet. Pushing the group", groupId);
141                 InstanceIdentifier<Group> groupIdent = buildGroupInstanceIdentifier(nodeIdent, groupId);
142                 LOG.info("Reading the group from config inventory: {}", groupId);
143                 try (ReadTransaction readTransaction = forwardingRulesManager.getReadTransaction()) {
144                     Optional<Group> group = readTransaction.read(LogicalDatastoreType.CONFIGURATION, groupIdent).get();
145                     if (group.isPresent()) {
146                         final AddGroupInputBuilder builder = new AddGroupInputBuilder(group.get());
147                         builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
148                         builder.setGroupRef(new GroupRef(nodeIdent));
149                         builder.setTransactionUri(new Uri(forwardingRulesManager.getNewTransactionId()));
150                         BundleInnerMessage bundleInnerMessage = new BundleAddGroupCaseBuilder()
151                                 .setAddGroupCaseData(new AddGroupCaseDataBuilder(group.get()).build()).build();
152                         Message groupMessage = new MessageBuilder().setNode(
153                                 new NodeRef(nodeIdent.firstIdentifierOf(Node.class)))
154                                 .setBundleInnerMessage(bundleInnerMessage).build();
155                         final List<Message> messages = new ArrayList<>(1);
156                         messages.add(groupMessage);
157                         AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
158                                 .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class))).setBundleId(bundleId)
159                                 .setFlags(BUNDLE_FLAGS).setMessages(new MessagesBuilder().setMessage(messages).build())
160                                 .build();
161                         LOG.trace("Pushing flow update message {} to bundle {} for device {}", addBundleMessagesInput,
162                                 bundleId.getValue(), getNodeIdFromNodeIdentifier(nodeIdent));
163                         resultFuture = forwardingRulesManager
164                                 .getSalBundleService().addBundleMessages(addBundleMessagesInput);
165                         Futures.transformAsync(resultFuture, rpcResult -> {
166                             if (rpcResult.isSuccessful()) {
167                                 forwardingRulesManager.getDevicesGroupRegistry()
168                                         .storeGroup(getNodeIdFromNodeIdentifier(nodeIdent), groupId);
169                                 LOG.trace("Group {} stored in cache", groupId);
170                             }
171                             return Futures.immediateFuture(null);
172                         }, MoreExecutors.directExecutor());
173                     } else {
174                         LOG.debug("Group {} not present in the config inventory", groupId);
175                         resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>success()
176                                 .build());
177                     }
178                 } catch (InterruptedException | ExecutionException e) {
179                     LOG.error("Error while reading group from config datastore for the group ID {}", groupId, e);
180                     resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>success().build());
181                 }
182             }
183         } else {
184             resultFuture = Futures.immediateFuture(RpcResultBuilder.<AddBundleMessagesOutput>success().build());
185         }
186         return resultFuture;
187     }
188
189     private final class BundleFlowCallBack implements FutureCallback<RpcResult<AddBundleMessagesOutput>> {
190         private final InstanceIdentifier<FlowCapableNode> nodeIdent;
191         private final BundleId bundleId;
192         private final Message messages;
193         private final NodeId nodeId;
194         private final String flowId;
195         private final short tableId;
196         private final SettableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture;
197
198         BundleFlowCallBack(InstanceIdentifier<FlowCapableNode> nodeIdent, BundleId bundleId, Message messages,
199             InstanceIdentifier<Flow> identifier , SettableFuture<RpcResult<AddBundleMessagesOutput>> resultFuture) {
200             this.nodeIdent = nodeIdent;
201             this.bundleId = bundleId;
202             this.messages = messages;
203             this.resultFuture = resultFuture;
204             this.flowId = getFlowId(new FlowRef(identifier));
205             this.tableId = getTableId(new FlowTableRef(identifier));
206             nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
207         }
208
209         @Override
210         public void onSuccess(RpcResult<AddBundleMessagesOutput> rpcResult) {
211             if (rpcResult.isSuccessful()) {
212                 AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
213                         .setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class))).setBundleId(bundleId)
214                         .setFlags(BUNDLE_FLAGS).setMessages(new MessagesBuilder().setMessage(
215                                 Collections.singletonList(messages)).build()).build();
216
217                 LOG.trace("Pushing flow add message {} to bundle {} for device {}", addBundleMessagesInput,
218                         bundleId.getValue(), nodeId.getValue());
219
220                 final ListenableFuture<RpcResult<AddBundleMessagesOutput>> addFuture =
221                         forwardingRulesManager.getSalBundleService().addBundleMessages(addBundleMessagesInput);
222                 Futures.addCallback(addFuture, new FutureCallback<RpcResult<AddBundleMessagesOutput>>() {
223                     @Override
224                     public void onSuccess(RpcResult<AddBundleMessagesOutput> result) {
225                         resultFuture.set(result);
226                         if (!result.getErrors().isEmpty()) {
227                             LOG.error("Flow add with flowId {} and tableId {} failed for node {} with error: {}",
228                                     flowId, tableId, nodeId.getValue(), result.getErrors().toString());
229                         }
230
231                     }
232
233                     @Override
234                     public void onFailure(Throwable failure) {
235                         resultFuture.setException(failure);
236                     }
237                 },  MoreExecutors.directExecutor());
238             } else {
239                 resultFuture.set(rpcResult);
240             }
241         }
242
243         @Override
244         public void onFailure(Throwable throwable) {
245             LOG.error("Error while pushing flow add bundle {} for device {}", messages, nodeId.getValue());
246             resultFuture.setException(throwable);
247         }
248     }
249 }