UnitTests for StateInterface Helpers
[vpnservice.git] / interfacemgr / interfacemgr-impl / src / main / java / org / opendaylight / vpnservice / interfacemgr / servicebindings / flowbased / utilities / FlowBasedServicesUtils.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 package org.opendaylight.vpnservice.interfacemgr.servicebindings.flowbased.utilities;
9
10 import com.google.common.base.Optional;
11 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
12 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
13 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
14 import org.opendaylight.vpnservice.interfacemgr.IfmConstants;
15 import org.opendaylight.vpnservice.interfacemgr.IfmUtil;
16 import org.opendaylight.vpnservice.interfacemgr.commons.InterfaceManagerCommonUtils;
17 import org.opendaylight.vpnservice.mdsalutil.*;
18 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
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.FlowKey;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.WriteMetadataCase;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.ServiceBindings;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.StypeOpenflow;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.ServicesInfo;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.ServicesInfoKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.servicebinding.rev151015.service.bindings.services.info.BoundServices;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import java.math.BigInteger;
43 import java.util.ArrayList;
44 import java.util.List;
45
46 public class FlowBasedServicesUtils {
47     private static final Logger LOG = LoggerFactory.getLogger(FlowBasedServicesUtils.class);
48
49     public static ServicesInfo getServicesInfoForInterface(String interfaceName, DataBroker dataBroker) {
50         ServicesInfoKey servicesInfoKey = new ServicesInfoKey(interfaceName);
51         InstanceIdentifier.InstanceIdentifierBuilder<ServicesInfo> servicesInfoIdentifierBuilder =
52                 InstanceIdentifier.builder(ServiceBindings.class).child(ServicesInfo.class, servicesInfoKey);
53         Optional<ServicesInfo> servicesInfoOptional = IfmUtil.read(LogicalDatastoreType.CONFIGURATION,
54                 servicesInfoIdentifierBuilder.build(), dataBroker);
55
56         if (servicesInfoOptional.isPresent()) {
57             return servicesInfoOptional.get();
58         }
59
60         return null;
61     }
62
63     public static NodeConnectorId getNodeConnectorIdFromInterface(Interface iface, DataBroker dataBroker) {
64         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface ifState =
65                 InterfaceManagerCommonUtils.getInterfaceStateFromOperDS(iface.getName(), dataBroker);
66         List<String> ofportIds = ifState.getLowerLayerIf();
67         return new NodeConnectorId(ofportIds.get(0));
68     }
69
70     public static List<MatchInfo> getMatchInfoForVlanPortAtIngressTable(BigInteger dpId, long portNo, long vlanId) {
71         List<MatchInfo> matches = new ArrayList<>();
72         matches.add(new MatchInfo(MatchFieldType.in_port, new BigInteger[] {dpId, BigInteger.valueOf(portNo)}));
73         if (vlanId > 0) {
74             LOG.error("VlanId matching support is not fully available in Be.");
75             matches.add(new MatchInfo(MatchFieldType.vlan_vid, new long[]{vlanId}));
76         }
77         return matches;
78     }
79
80     public static List<MatchInfo> getMatchInfoForTunnelPortAtIngressTable(BigInteger dpId, long portNo, Interface iface) {
81         List<MatchInfo> matches = new ArrayList<MatchInfo>();
82         matches.add(new MatchInfo(MatchFieldType.in_port, new BigInteger[]{dpId, BigInteger.valueOf(portNo)}));
83         return matches;
84     }
85
86     public static List<MatchInfo> getMatchInfoForDispatcherTable(BigInteger dpId, Interface iface,
87                                                                  int interfaceTag, short servicePriority) {
88         List<MatchInfo> matches = new ArrayList<MatchInfo>();
89         matches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
90                 MetaDataUtil.getMetaDataForLPortDispatcher(interfaceTag, servicePriority),
91                 MetaDataUtil.getMetaDataMaskForLPortDispatcher() }));
92         return matches;
93     }
94
95     public static Long getLPortTag(Interface iface, DataBroker dataBroker) {
96         /*ParentRefs parentRefs = iface.getAugmentation(ParentRefs.class);
97         String portName = parentRefs.getParentInterface();
98         BigInteger dpIdFromInterface = parentRefs.getDatapathNodeIdentifier();
99         String portKey = FlowBasedServicesUtils.getInterfaceRefInfo(dpIdFromInterface.toString(), portName);
100         if (iface.getType().isAssignableFrom(L2vlan.class)) {
101             InterfacesMetaKey interfacesMetaKey = new InterfacesMetaKey(portKey);
102             InterfacesInfoKey interfacesInfoKey = new InterfacesInfoKey(iface.getName());
103             InterfacesInfo interfacesInfo = VlanInterfaceUtilities.getInterfacesInfoFromConfigDS(interfacesMetaKey,
104                     interfacesInfoKey, dataBroker);
105             return interfacesInfo.getLporttag();
106         } else if (iface.getType().isAssignableFrom(Tunnel.class)) {
107             TunnelInterfaceRefInfoKey tunnelInterfaceRefInfoKey = new TunnelInterfaceRefInfoKey(portKey);
108             TunnelInterfaceEntries tunnelInterfaceEntries =
109                     TunnelInterfaceUtilities.getTunnelInterfaceRefEntriesFromConfigDs(
110                             tunnelInterfaceRefInfoKey, iface.getName(), dataBroker);
111             return tunnelInterfaceEntries.getLportTag();
112         } */
113         return 0L;
114     }
115
116     public static void installInterfaceIngressFlow(BigInteger dpId, String interfaceName, int vlanId,
117                                                    BoundServices boundServiceNew,
118                                                    DataBroker dataBroker, WriteTransaction t,
119                                                    List<MatchInfo> matches, int lportTag, short tableId) {
120         List<Instruction> instructions = boundServiceNew.getAugmentation(StypeOpenflow.class).getInstruction();
121
122         int serviceInstructionsSize = instructions.size();
123         List<Instruction> instructionSet = new ArrayList<Instruction>();
124         if (vlanId != 0) {
125             // incrementing instructionSize and using it as actionKey. Because it won't clash with any other instructions
126             int actionKey = ++serviceInstructionsSize;
127             instructionSet.add(MDSALUtil.buildAndGetPopVlanActionInstruction(actionKey, ++serviceInstructionsSize));
128         }
129
130         if (lportTag != 0L) {
131             BigInteger[] metadataValues = IfmUtil.mergeOpenflowMetadataWriteInstructions(instructions);
132             short sIndex = boundServiceNew.getServicePriority();
133             BigInteger metadata = MetaDataUtil.getMetaDataForLPortDispatcher(lportTag,
134                     ++sIndex, metadataValues[0]);
135             BigInteger metadataMask = MetaDataUtil.getMetaDataMaskForLPortDispatcher(
136                     MetaDataUtil.METADATA_MASK_SERVICE_INDEX,
137                     MetaDataUtil.METADATA_MASK_LPORT_TAG, metadataValues[1]);
138             instructionSet.add(MDSALUtil.buildAndGetWriteMetadaInstruction(metadata, metadataMask,
139                     ++serviceInstructionsSize));
140         }
141
142         if (instructions != null && !instructions.isEmpty()) {
143             for (Instruction info : instructions) {
144                 // Skip meta data write as that is handled already
145                 if (info.getInstruction() instanceof WriteMetadataCase) {
146                     continue;
147                 }
148                 instructionSet.add(info);
149             }
150         }
151
152         String serviceRef = boundServiceNew.getServiceName();
153         String flowRef = getFlowRef(dpId, interfaceName, boundServiceNew);
154         StypeOpenflow stypeOpenflow = boundServiceNew.getAugmentation(StypeOpenflow.class);
155         Flow ingressFlow = MDSALUtil.buildFlowNew(tableId, flowRef,
156                 stypeOpenflow.getFlowPriority(), serviceRef, 0, 0,
157                 stypeOpenflow.getFlowCookie(), matches, instructionSet);
158         installFlow(dpId, ingressFlow, dataBroker, t);
159     }
160
161     private static void installFlow(BigInteger dpId, Flow flow, DataBroker dataBroker, WriteTransaction t) {
162         FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
163         Node nodeDpn = buildInventoryDpnNode(dpId);
164         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
165                 .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
166                 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class,flowKey).build();
167
168         t.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flow, true);
169     }
170
171     private static Node buildInventoryDpnNode(BigInteger dpnId) {
172         NodeId nodeId = new NodeId("openflow:" + dpnId);
173         Node nodeDpn = new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
174
175         return nodeDpn;
176     }
177
178     public static void installLPortDispatcherFlow(BigInteger dpId, BoundServices boundService, Interface iface,
179                                                   DataBroker dataBroker, WriteTransaction t, int interfaceTag) {
180         LOG.debug("Installing LPort Dispatcher Flows {}, {}", dpId, iface);
181         short serviceIndex = boundService.getServicePriority();
182         String serviceRef = boundService.getServiceName();
183         List<MatchInfo> matches = FlowBasedServicesUtils.getMatchInfoForDispatcherTable(dpId, iface,
184                 interfaceTag, serviceIndex);
185
186         // Get the metadata and mask from the service's write metadata instruction
187         StypeOpenflow stypeOpenFlow = boundService.getAugmentation(StypeOpenflow.class);
188         List<Instruction> serviceInstructions = stypeOpenFlow.getInstruction();
189         int instructionSize = serviceInstructions.size();
190         BigInteger[] metadataValues = IfmUtil.mergeOpenflowMetadataWriteInstructions(serviceInstructions);
191         BigInteger metadata = MetaDataUtil.getMetaDataForLPortDispatcher(interfaceTag, ++serviceIndex, metadataValues[0]);
192         BigInteger metadataMask = MetaDataUtil.getMetaDataMaskForLPortDispatcher(MetaDataUtil.METADATA_MASK_SERVICE_INDEX,
193                 MetaDataUtil.METADATA_MASK_LPORT_TAG, metadataValues[1]);
194
195         // build the final instruction for LPort Dispatcher table flow entry
196         List<Instruction> instructions = new ArrayList<Instruction>();
197         instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(metadata, metadataMask, ++instructionSize));
198         if (serviceInstructions != null && !serviceInstructions.isEmpty()) {
199             for (Instruction info : serviceInstructions) {
200                 // Skip meta data write as that is handled already
201                 if (info.getInstruction() instanceof WriteMetadataCase) {
202                     continue;
203                 }
204                 instructions.add(info);
205             }
206         }
207
208         // build the flow and install it
209         String flowRef = getFlowRef(dpId, iface.getName(), boundService);
210         Flow ingressFlow = MDSALUtil.buildFlowNew(stypeOpenFlow.getDispatcherTableId(), flowRef,
211                 boundService.getServicePriority(), serviceRef, 0, 0, stypeOpenFlow.getFlowCookie(), matches, instructions);
212         installFlow(dpId, ingressFlow, dataBroker, t);
213     }
214
215     public static void removeIngressFlow(Interface iface, BoundServices serviceOld, BigInteger dpId,
216                                          DataBroker dataBroker, WriteTransaction t) {
217         LOG.debug("Removing Ingress Flows");
218         String flowKeyStr = getFlowRef(dpId, iface.getName(), serviceOld);
219         FlowKey flowKey = new FlowKey(new FlowId(flowKeyStr));
220         Node nodeDpn = buildInventoryDpnNode(dpId);
221         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
222                 .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
223                 .child(Table.class, new TableKey(IfmConstants.VLAN_INTERFACE_INGRESS_TABLE)).child(Flow.class, flowKey).build();
224
225         t.delete(LogicalDatastoreType.CONFIGURATION, flowInstanceId);
226     }
227
228     public static void removeLPortDispatcherFlow(BigInteger dpId, Interface iface, BoundServices boundServicesOld,
229                                                  DataBroker dataBroker, WriteTransaction t) {
230         LOG.debug("Removing LPort Dispatcher Flows {}, {}", dpId, iface);
231         Long interfaceTag = FlowBasedServicesUtils.getLPortTag(iface, dataBroker);
232
233         StypeOpenflow stypeOpenFlow = boundServicesOld.getAugmentation(StypeOpenflow.class);
234         String flowKeyStr = iface.getName() + boundServicesOld.getServicePriority() +
235                 boundServicesOld.getServiceName() + stypeOpenFlow.getDispatcherTableId();
236         FlowKey flowKey = new FlowKey(new FlowId(flowKeyStr));
237         Node nodeDpn = buildInventoryDpnNode(dpId);
238         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
239                 .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
240                 .child(Table.class, new TableKey(stypeOpenFlow.getDispatcherTableId())).child(Flow.class, flowKey).build();
241
242         t.delete(LogicalDatastoreType.CONFIGURATION, flowInstanceId);
243     }
244
245     private static String getFlowRef(BigInteger dpnId, String iface, BoundServices service) {
246         return new StringBuffer().append(dpnId).append(IfmConstants.VLAN_INTERFACE_INGRESS_TABLE).append(NwConstants.FLOWID_SEPARATOR)
247                 .append(iface).append(NwConstants.FLOWID_SEPARATOR).append(service.getServiceName()).append(NwConstants.FLOWID_SEPARATOR)
248                 .append(service.getServicePriority()).toString();
249     }
250 }