creation of tunnel ingress flow and lfib table entries moved to interface
[vpnservice.git] / mdsalutil / mdsalutil-impl / src / main / java / org / opendaylight / vpnservice / mdsalutil / internal / MDSALManager.java
1 /*
2  * Copyright (c) 2015 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
9 package org.opendaylight.vpnservice.mdsalutil.internal;
10
11 import java.math.BigInteger;
12 import java.util.ArrayList;
13 import java.util.List;
14 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
15 import org.opendaylight.vpnservice.mdsalutil.ActionType;
16 import org.opendaylight.vpnservice.mdsalutil.FlowEntity;
17 import org.opendaylight.vpnservice.mdsalutil.GroupEntity;
18 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
44 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
45 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
46 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
47 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
48
49 import com.google.common.util.concurrent.CheckedFuture;
50 import com.google.common.util.concurrent.FutureCallback;
51 import com.google.common.util.concurrent.Futures;
52
53 public class MDSALManager implements AutoCloseable {
54
55     private static final Logger s_logger = LoggerFactory.getLogger(MDSALManager.class);
56
57     private DataBroker m_dataBroker;
58
59     private PacketProcessingService m_packetProcessingService;
60
61     /**
62      * Writes the flows and Groups to the MD SAL DataStore
63      * which will be sent to the openflowplugin for installing flows/groups on the switch.
64      * Other modules of VPN service that wants to install flows / groups on the switch
65      * uses this utility
66      *
67      * @param db - dataBroker reference
68      * @param pktProcService- PacketProcessingService for sending the packet outs
69      */
70     public MDSALManager(final DataBroker db, PacketProcessingService pktProcService) {
71         m_dataBroker = db;
72         m_packetProcessingService = pktProcService;
73         s_logger.info( "MDSAL Manager Initialized ") ;
74     }
75
76     @Override
77     public void close() throws Exception {
78         s_logger.info("MDSAL Manager Closed");
79     }
80
81     public void installFlow(FlowEntity flowEntity) {
82
83         try {
84             s_logger.trace("InstallFlow for flowEntity {} ", flowEntity);
85
86             if (flowEntity.getCookie() == null) {
87                flowEntity.setCookie(new BigInteger("0110000", 16));
88             }
89
90             FlowKey flowKey = new FlowKey( new FlowId(flowEntity.getFlowId()) );
91
92             FlowBuilder flowbld = flowEntity.getFlowBuilder();
93
94             Node nodeDpn = buildDpnNode(flowEntity.getDpnId());
95             InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
96                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
97                     .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class,flowKey).build();
98
99             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
100
101             modification.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flowbld.build(),true );
102
103             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
104
105             Futures.addCallback(submitFuture, new FutureCallback<Void>() {
106
107                 @Override
108                 public void onSuccess(final Void result) {
109                     // Commited successfully
110                     s_logger.debug( "Install Flow -- Committedsuccessfully ") ;
111                 }
112
113                 @Override
114                 public void onFailure(final Throwable t) {
115                     // Transaction failed
116
117                     if(t instanceof OptimisticLockFailedException) {
118                         // Failed because of concurrent transaction modifying same data
119                         s_logger.error( "Install Flow -- Failed because of concurrent transaction modifying same data ") ;
120                     } else {
121                        // Some other type of TransactionCommitFailedException
122                         s_logger.error( "Install Flow -- Some other type of TransactionCommitFailedException " + t) ;
123                     }
124                 }
125             });
126         } catch (Exception e) {
127             s_logger.error("Could not install flow: {}", flowEntity, e);
128         }
129     }
130
131     public CheckedFuture<Void,TransactionCommitFailedException> installFlow(BigInteger dpId, Flow flow) {
132         FlowKey flowKey = new FlowKey( new FlowId(flow.getId()) );
133         Node nodeDpn = buildDpnNode(dpId);
134         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
135                 .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
136                 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class,flowKey).build();
137         WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
138         modification.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flow, true);
139         return modification.submit();
140     }
141
142     public void installGroup(GroupEntity groupEntity) {
143         try {
144             Group group = groupEntity.getGroupBuilder().build();
145
146             Node nodeDpn = buildDpnNode(groupEntity.getDpnId());
147
148             InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
149                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
150                     .child(Group.class, new GroupKey(new GroupId(groupEntity.getGroupId()))).build();
151
152             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
153
154             modification.put(LogicalDatastoreType.CONFIGURATION, groupInstanceId, group, true);
155
156             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
157
158             Futures.addCallback(submitFuture, new FutureCallback<Void>() {
159                 @Override
160                 public void onSuccess(final Void result) {
161                     // Commited successfully
162                     s_logger.debug( "Install Group -- Committedsuccessfully ") ;
163                 }
164
165                 @Override
166                 public void onFailure(final Throwable t) {
167                     // Transaction failed
168
169                     if(t instanceof OptimisticLockFailedException) {
170                         // Failed because of concurrent transaction modifying same data
171                         s_logger.error( "Install Group -- Failed because of concurrent transaction modifying same data ") ;
172                     } else {
173                        // Some other type of TransactionCommitFailedException
174                         s_logger.error( "Install Group -- Some other type of TransactionCommitFailedException " + t) ;
175                     }
176                 }
177              });
178            } catch (Exception e) {
179             s_logger.error("Could not install Group: {}", groupEntity, e);
180             throw e;
181         }
182     }
183
184     public void removeFlow(FlowEntity flowEntity) {
185         try {
186             s_logger.debug("Remove flow {}",flowEntity);
187             Node nodeDpn = buildDpnNode(flowEntity.getDpnId());
188             FlowKey flowKey = new FlowKey(new FlowId(flowEntity.getFlowId()));
189             InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
190                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
191                     .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class, flowKey).build();
192
193
194                 WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
195                 modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId);
196
197                 CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
198
199                 Futures.addCallback(submitFuture, new FutureCallback<Void>() {
200                     @Override
201                     public void onSuccess(final Void result) {
202                         // Commited successfully
203                         s_logger.debug( "Delete Flow -- Committedsuccessfully ") ;
204                     }
205
206                     @Override
207                     public void onFailure(final Throwable t) {
208                         // Transaction failed
209                         if(t instanceof OptimisticLockFailedException) {
210                             // Failed because of concurrent transaction modifying same data
211                             s_logger.error( "Delete Flow -- Failed because of concurrent transaction modifying same data ") ;
212                         } else {
213                            // Some other type of TransactionCommitFailedException
214                             s_logger.error( "Delete Flow -- Some other type of TransactionCommitFailedException " + t) ;
215                         }
216                     }
217
218                 });
219         } catch (Exception e) {
220             s_logger.error("Could not remove Flow: {}", flowEntity, e);
221         }
222     }
223
224     public CheckedFuture<Void,TransactionCommitFailedException> removeFlowNew(BigInteger dpnId, Flow flowEntity) {
225         s_logger.debug("Remove flow {}",flowEntity);
226         Node nodeDpn = buildDpnNode(dpnId);
227         FlowKey flowKey = new FlowKey(new FlowId(flowEntity.getId()));
228         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
229                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
230                     .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class, flowKey).build();
231         WriteTransaction  modification = m_dataBroker.newWriteOnlyTransaction();
232         modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId );
233         return modification.submit();
234     }
235
236     public void removeGroup(GroupEntity groupEntity) {
237         try {
238             Node nodeDpn = buildDpnNode(groupEntity.getDpnId());
239             InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
240                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
241                     .child(Group.class, new GroupKey(new GroupId(groupEntity.getGroupId()))).build();
242
243             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
244
245             modification.delete(LogicalDatastoreType.CONFIGURATION,groupInstanceId );
246
247             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
248
249             Futures.addCallback(submitFuture, new FutureCallback<Void>() {
250                 @Override
251                 public void onSuccess(final Void result) {
252                     // Commited successfully
253                     s_logger.debug( "Install Group -- Committedsuccessfully ") ;
254                 }
255
256                 @Override
257                 public void onFailure(final Throwable t) {
258                     // Transaction failed
259                     if(t instanceof OptimisticLockFailedException) {
260                         // Failed because of concurrent transaction modifying same data
261                         s_logger.error( "Install Group -- Failed because of concurrent transaction modifying same data ") ;
262                     } else {
263                        // Some other type of TransactionCommitFailedException
264                         s_logger.error( "Install Group -- Some other type of TransactionCommitFailedException " + t) ;
265                     }
266                 }
267             });
268         } catch (Exception e) {
269             s_logger.error("Could not remove Group: {}", groupEntity, e);
270         }
271     }
272
273     public void modifyGroup(GroupEntity groupEntity) {
274
275         installGroup(groupEntity);
276     }
277
278     public void sendPacketOut(BigInteger dpnId, int groupId, byte[] payload) {
279
280         List<ActionInfo> actionInfos = new ArrayList<ActionInfo>();
281         actionInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
282
283         sendPacketOutWithActions(dpnId, groupId, payload, actionInfos);
284     }
285
286     public void sendPacketOutWithActions(BigInteger dpnId, long groupId, byte[] payload, List<ActionInfo> actionInfos) {
287
288         m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actionInfos, payload, dpnId,
289                 getNodeConnRef("openflow:" + dpnId, "0xfffffffd")));
290     }
291
292     public void sendARPPacketOutWithActions(BigInteger dpnId, byte[] payload, List<ActionInfo> actions) {
293         m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actions, payload, dpnId,
294                 getNodeConnRef("openflow:" + dpnId, "0xfffffffd")));
295     }
296
297     public InstanceIdentifier<Node> nodeToInstanceId(Node node) {
298         return InstanceIdentifier.builder(Nodes.class).child(Node.class, node.getKey()).toInstance();
299     }
300
301     private static NodeConnectorRef getNodeConnRef(final String nodeId, final String port) {
302         StringBuilder _stringBuilder = new StringBuilder(nodeId);
303         StringBuilder _append = _stringBuilder.append(":");
304         StringBuilder sBuild = _append.append(port);
305         String _string = sBuild.toString();
306         NodeConnectorId _nodeConnectorId = new NodeConnectorId(_string);
307         NodeConnectorKey _nodeConnectorKey = new NodeConnectorKey(_nodeConnectorId);
308         NodeConnectorKey nConKey = _nodeConnectorKey;
309         InstanceIdentifierBuilder<Nodes> _builder = InstanceIdentifier.<Nodes> builder(Nodes.class);
310         NodeId _nodeId = new NodeId(nodeId);
311         NodeKey _nodeKey = new NodeKey(_nodeId);
312         InstanceIdentifierBuilder<Node> _child = _builder.<Node, NodeKey> child(Node.class, _nodeKey);
313         InstanceIdentifierBuilder<NodeConnector> _child_1 = _child.<NodeConnector, NodeConnectorKey> child(
314                 NodeConnector.class, nConKey);
315         InstanceIdentifier<NodeConnector> path = _child_1.toInstance();
316         NodeConnectorRef _nodeConnectorRef = new NodeConnectorRef(path);
317         return _nodeConnectorRef;
318     }
319
320     private Node buildDpnNode(BigInteger dpnId) {
321         NodeId nodeId = new NodeId("openflow:" + dpnId);
322         Node nodeDpn = new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
323
324         return nodeDpn;
325     }
326
327 }