Working with OVS
[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
138         WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
139         modification.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flow, true);
140         return modification.submit();
141     }
142
143     public void installGroup(GroupEntity groupEntity) {
144         try {
145             Group group = groupEntity.getGroupBuilder().build();
146
147             Node nodeDpn = buildDpnNode(groupEntity.getDpnId());
148
149             InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
150                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
151                     .child(Group.class, new GroupKey(new GroupId(groupEntity.getGroupId()))).build();
152
153             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
154
155             modification.put(LogicalDatastoreType.CONFIGURATION, groupInstanceId, group, true);
156
157             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
158
159             Futures.addCallback(submitFuture, new FutureCallback<Void>() {
160                 @Override
161                 public void onSuccess(final Void result) {
162                     // Commited successfully
163                     s_logger.debug( "Install Group -- Committedsuccessfully ") ;
164                 }
165
166                 @Override
167                 public void onFailure(final Throwable t) {
168                     // Transaction failed
169
170                     if(t instanceof OptimisticLockFailedException) {
171                         // Failed because of concurrent transaction modifying same data
172                         s_logger.error( "Install Group -- Failed because of concurrent transaction modifying same data ") ;
173                     } else {
174                        // Some other type of TransactionCommitFailedException
175                         s_logger.error( "Install Group -- Some other type of TransactionCommitFailedException " + t) ;
176                     }
177                 }
178              });
179            } catch (Exception e) {
180             s_logger.error("Could not install Group: {}", groupEntity, e);
181             throw e;
182         }
183     }
184
185     public void removeFlow(FlowEntity flowEntity) {
186         try {
187             s_logger.debug("Remove flow {}",flowEntity);
188             Node nodeDpn = buildDpnNode(flowEntity.getDpnId());
189             FlowKey flowKey = new FlowKey(new FlowId(flowEntity.getFlowId()));
190             InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
191                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
192                     .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class, flowKey).build();
193
194
195                 WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
196                 modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId);
197
198                 CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
199
200                 Futures.addCallback(submitFuture, new FutureCallback<Void>() {
201                     @Override
202                     public void onSuccess(final Void result) {
203                         // Commited successfully
204                         s_logger.debug( "Delete Flow -- Committedsuccessfully ") ;
205                     }
206
207                     @Override
208                     public void onFailure(final Throwable t) {
209                         // Transaction failed
210                         if(t instanceof OptimisticLockFailedException) {
211                             // Failed because of concurrent transaction modifying same data
212                             s_logger.error( "Delete Flow -- Failed because of concurrent transaction modifying same data ") ;
213                         } else {
214                            // Some other type of TransactionCommitFailedException
215                             s_logger.error( "Delete Flow -- Some other type of TransactionCommitFailedException " + t) ;
216                         }
217                     }
218
219                 });
220         } catch (Exception e) {
221             s_logger.error("Could not remove Flow: {}", flowEntity, e);
222         }
223     }
224
225     public CheckedFuture<Void,TransactionCommitFailedException> removeFlowNew(FlowEntity flowEntity) {
226         s_logger.debug("Remove flow {}",flowEntity);
227         Node nodeDpn = buildDpnNode(flowEntity.getDpnId());
228         FlowKey flowKey = new FlowKey(new FlowId(flowEntity.getFlowId()));
229         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
230                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
231                     .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class, flowKey).build();
232         WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
233         modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId );
234         return modification.submit();
235     }
236
237     public void removeGroup(GroupEntity groupEntity) {
238         try {
239             Node nodeDpn = buildDpnNode(groupEntity.getDpnId());
240             InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
241                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
242                     .child(Group.class, new GroupKey(new GroupId(groupEntity.getGroupId()))).build();
243
244             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
245
246             modification.delete(LogicalDatastoreType.CONFIGURATION,groupInstanceId );
247
248             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
249
250             Futures.addCallback(submitFuture, new FutureCallback<Void>() {
251                 @Override
252                 public void onSuccess(final Void result) {
253                     // Commited successfully
254                     s_logger.debug( "Install Group -- Committedsuccessfully ") ;
255                 }
256
257                 @Override
258                 public void onFailure(final Throwable t) {
259                     // Transaction failed
260                     if(t instanceof OptimisticLockFailedException) {
261                         // Failed because of concurrent transaction modifying same data
262                         s_logger.error( "Install Group -- Failed because of concurrent transaction modifying same data ") ;
263                     } else {
264                        // Some other type of TransactionCommitFailedException
265                         s_logger.error( "Install Group -- Some other type of TransactionCommitFailedException " + t) ;
266                     }
267                 }
268             });
269         } catch (Exception e) {
270             s_logger.error("Could not remove Group: {}", groupEntity, e);
271         }
272     }
273
274     public void modifyGroup(GroupEntity groupEntity) {
275
276         installGroup(groupEntity);
277     }
278
279     public void sendPacketOut(BigInteger dpnId, int groupId, byte[] payload) {
280
281         List<ActionInfo> actionInfos = new ArrayList<ActionInfo>();
282         actionInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
283
284         sendPacketOutWithActions(dpnId, groupId, payload, actionInfos);
285     }
286
287     public void sendPacketOutWithActions(BigInteger dpnId, long groupId, byte[] payload, List<ActionInfo> actionInfos) {
288
289         m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actionInfos, payload, dpnId,
290                 getNodeConnRef("openflow:" + dpnId, "0xfffffffd")));
291     }
292
293     public void sendARPPacketOutWithActions(BigInteger dpnId, byte[] payload, List<ActionInfo> actions) {
294         m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actions, payload, dpnId,
295                 getNodeConnRef("openflow:" + dpnId, "0xfffffffd")));
296     }
297
298     public InstanceIdentifier<Node> nodeToInstanceId(Node node) {
299         return InstanceIdentifier.builder(Nodes.class).child(Node.class, node.getKey()).toInstance();
300     }
301
302     private static NodeConnectorRef getNodeConnRef(final String nodeId, final String port) {
303         StringBuilder _stringBuilder = new StringBuilder(nodeId);
304         StringBuilder _append = _stringBuilder.append(":");
305         StringBuilder sBuild = _append.append(port);
306         String _string = sBuild.toString();
307         NodeConnectorId _nodeConnectorId = new NodeConnectorId(_string);
308         NodeConnectorKey _nodeConnectorKey = new NodeConnectorKey(_nodeConnectorId);
309         NodeConnectorKey nConKey = _nodeConnectorKey;
310         InstanceIdentifierBuilder<Nodes> _builder = InstanceIdentifier.<Nodes> builder(Nodes.class);
311         NodeId _nodeId = new NodeId(nodeId);
312         NodeKey _nodeKey = new NodeKey(_nodeId);
313         InstanceIdentifierBuilder<Node> _child = _builder.<Node, NodeKey> child(Node.class, _nodeKey);
314         InstanceIdentifierBuilder<NodeConnector> _child_1 = _child.<NodeConnector, NodeConnectorKey> child(
315                 NodeConnector.class, nConKey);
316         InstanceIdentifier<NodeConnector> path = _child_1.toInstance();
317         NodeConnectorRef _nodeConnectorRef = new NodeConnectorRef(path);
318         return _nodeConnectorRef;
319     }
320
321     private Node buildDpnNode(BigInteger dpnId) {
322         NodeId nodeId = new NodeId("openflow:" + dpnId);
323         Node nodeDpn = new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
324
325         return nodeDpn;
326     }
327
328 }