NETVIRT-1630 migrate to md-sal APIs
[netvirt.git] / cloud-servicechain / impl / src / main / java / org / opendaylight / netvirt / cloudservicechain / utils / ElanServiceChainUtils.java
1 /*
2  * Copyright (c) 2016 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.netvirt.cloudservicechain.utils;
9
10 import java.util.Optional;
11 import java.math.BigInteger;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.List;
17 import java.util.stream.Collectors;
18 import org.opendaylight.mdsal.binding.api.DataBroker;
19 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
20 import org.opendaylight.genius.mdsalutil.ActionInfo;
21 import org.opendaylight.genius.mdsalutil.MDSALUtil;
22 import org.opendaylight.genius.mdsalutil.MatchInfo;
23 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
24 import org.opendaylight.genius.mdsalutil.NwConstants;
25 import org.opendaylight.genius.mdsalutil.actions.ActionRegLoad;
26 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
27 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
28 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
29 import org.opendaylight.genius.utils.ServiceIndex;
30 import org.opendaylight.netvirt.cloudservicechain.CloudServiceChainConstants;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.cloud.servicechain.state.rev160711.ElanServiceChainState;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.cloud.servicechain.state.rev160711.elan.to.pseudo.port.data.list.ElanToPseudoPortData;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.cloud.servicechain.state.rev160711.elan.to.pseudo.port.data.list.ElanToPseudoPortDataBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.cloud.servicechain.state.rev160711.elan.to.pseudo.port.data.list.ElanToPseudoPortDataKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg2;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public final class ElanServiceChainUtils {
52
53     private static final Logger LOG = LoggerFactory.getLogger(ElanServiceChainUtils.class);
54
55     private ElanServiceChainUtils() { }
56
57     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigDataPath(String elanInstanceName) {
58         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class,
59                                                                      new ElanInstanceKey(elanInstanceName)).build();
60     }
61
62     public static Optional<ElanInstance> getElanInstanceByName(DataBroker broker, String elanName) {
63         return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, getElanInstanceConfigDataPath(elanName));
64     }
65
66     public static Collection<BigInteger> getElanDpnsByName(DataBroker broker, String elanInstanceName) {
67         InstanceIdentifier<ElanDpnInterfacesList> elanDpnIfacesIid =
68                 InstanceIdentifier.builder(ElanDpnInterfaces.class)
69                                   .child(ElanDpnInterfacesList.class,new ElanDpnInterfacesListKey(elanInstanceName))
70                                   .build();
71         Optional<ElanDpnInterfacesList> elanDpnIfacesOpc =
72                 MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnIfacesIid);
73         if (!elanDpnIfacesOpc.isPresent()) {
74             LOG.warn("Could not find and DpnInterface for elan {}", elanInstanceName);
75             return Collections.emptySet();
76         }
77
78         return elanDpnIfacesOpc.get().getDpnInterfaces().stream().map(DpnInterfaces::getDpId).collect(
79                 Collectors.toSet());
80     }
81
82     public static BigInteger getElanMetadataLabel(long elanTag) {
83         return BigInteger.valueOf(elanTag).shiftLeft(24);
84     }
85
86     /**
87      * This flow is in charge of handling packets coming from ExtTunnelTable
88      * that must be redirected to the SCF Pipeline.
89      *  + Matches on lportTag=ElanPseudoLportTag + SI=1
90      *  + Sets scfTag and sends to the DlSubsFilter table.
91      *
92      * @param dpnId Dpn Id where the flow must be installed
93      * @param elanLportTag the Elan Pseudo Lport Id in Dataplane
94      * @param elanTag the Elan Id in the Dataplane
95      * @param addOrRemove States if the flow must be added or removed
96      */
97     public static void programLPortDispatcherToScf(IMdsalApiManager mdsalManager, BigInteger dpnId, long elanTag,
98             int elanLportTag, short tableId, long scfTag, int addOrRemove) {
99         LOG.info("L2-ServiceChaining: programLPortDispatcherToScf dpId={} elanLportTag={} scfTag={} addOrRemove={} ",
100                  dpnId, elanLportTag, scfTag, addOrRemove);
101         String flowRef = buildLportDispToScfFlowRef(elanLportTag, scfTag);
102         if (addOrRemove == NwConstants.ADD_FLOW) {
103             int instructionKey = 0;
104             List<Instruction> instructions = new ArrayList<>();
105             List<ActionInfo> actionsInfos = new ArrayList<>();
106             actionsInfos.add(new ActionRegLoad(NxmNxReg2.class, 0, 31, scfTag));
107             instructions.add(MDSALUtil.buildApplyActionsInstruction(MDSALUtil
108                     .buildActions(actionsInfos),instructionKey++));
109             instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(tableId, instructionKey++));
110             List<MatchInfo> matches = Collections.singletonList(
111                     new MatchMetadata(
112                             MetaDataUtil.getMetaDataForLPortDispatcher(elanLportTag,
113                                     ServiceIndex.getIndex(NwConstants.SCF_SERVICE_NAME, NwConstants.SCF_SERVICE_INDEX)),
114                             MetaDataUtil.getMetaDataMaskForLPortDispatcher()));
115
116             Flow flow = MDSALUtil.buildFlowNew(NwConstants.LPORT_DISPATCHER_TABLE, flowRef,
117                     CloudServiceChainConstants.DEFAULT_SCF_FLOW_PRIORITY, flowRef,
118                     0, 0, CloudServiceChainConstants.COOKIE_LPORT_DISPATCHER_BASE.add(BigInteger.valueOf(elanTag)),
119                     matches, instructions);
120             mdsalManager.installFlow(dpnId, flow);
121         } else {
122             Flow flow = new FlowBuilder().setTableId(NwConstants.LPORT_DISPATCHER_TABLE)
123                                          .setId(new FlowId(flowRef)).build();
124             mdsalManager.removeFlow(dpnId, flow);
125         }
126     }
127
128     /**
129      * This flow is in charge of handling packets coming from the SCF Pipeline
130      * when there is no matching ServiceChain.
131      * <ul>
132      *  <li> Matches on ElanPseudoPortTag and SI=3 (ELAN)</li>
133      *  <li> Sets elanTag and sends to DMAC table</li>
134      * </ul>
135      * @param dpnId Dpn Id where the flow must be installed
136      * @param elanLportTag the Elan Pseudo Lport Id to be used in the Dataplane
137      * @param elanTag the Elan Id to be used in the Dataplane
138      * @param addOrRemove States if the flow must be added or removed
139      */
140     public static void programLPortDispatcherFromScf(IMdsalApiManager mdsalManager, BigInteger dpnId,
141                                                      int elanLportTag, long elanTag, int addOrRemove) {
142         LOG.info("L2-ServiceChaining: programLPortDispatcherFromScf dpId={} elanLportTag={} elanTag={} addOrRemove={} ",
143                  dpnId, elanLportTag, elanTag, addOrRemove);
144         String flowRef = buildLportDispFromScfFlowRef(elanTag, elanLportTag);
145         if (addOrRemove == NwConstants.ADD_FLOW) {
146             List<MatchInfo> matches = Collections.singletonList(
147                     new MatchMetadata(MetaDataUtil.getMetaDataForLPortDispatcher(elanLportTag,
148                             ServiceIndex.getIndex(NwConstants.ELAN_SERVICE_NAME, NwConstants.ELAN_SERVICE_INDEX)),
149                             MetaDataUtil.getMetaDataMaskForLPortDispatcher()));
150             int instructionKey = 0;
151             List<Instruction> instructions = Arrays.asList(
152                     // BigInter.ONE is for setting also the Split-Horizon flag since it could have been cleared
153                     // while going through the SCF Pipeline
154                     MDSALUtil.buildAndGetWriteMetadaInstruction(getElanMetadataLabel(elanTag).or(BigInteger.ONE),
155                             MetaDataUtil.METADATA_MASK_SERVICE.or(BigInteger.ONE),
156                             instructionKey++),
157                     MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.ELAN_SMAC_TABLE,
158                             instructionKey));
159
160             Flow flow =
161                     MDSALUtil.buildFlowNew(NwConstants.LPORT_DISPATCHER_TABLE, flowRef,
162                             CloudServiceChainConstants.DEFAULT_SCF_FLOW_PRIORITY,
163                             flowRef, 0, 0,
164                             CloudServiceChainConstants.COOKIE_LPORT_DISPATCHER_BASE.add(BigInteger.valueOf(elanTag)),
165                             matches, instructions);
166             mdsalManager.installFlow(dpnId, flow);
167         } else {
168             Flow flow = new FlowBuilder().setTableId(NwConstants.LPORT_DISPATCHER_TABLE)
169                     .setId(new FlowId(flowRef)).build();
170             mdsalManager.removeFlow(dpnId, flow);
171         }
172     }
173
174
175     /**
176      * This flow is in charge of receiving packets from the TOR and sending
177      * them to the SCF Pipeline by setting the LportTag of ElanPseudoPort.
178      * Note that ELAN already has a flow in this table that redirects packets
179      * to the ELAN Pipeline. However, the flow for the SCF Pipeline will have
180      * higher priority, and will only be present when there is a ServiceChain
181      * using this ElanPseudoPort.
182      * <ul>
183      *  <li> Matches on the VNI
184      *  <li> Sets SI=1 and ElanPseudoPort tag in the Metadata and sends to
185      *    LPortDispatcher via table 80.
186      * </ul>
187      * @param dpnId Dpn Id where the flow must be installed
188      * @param elanLportTag the Elan Pseudo Lport Id to be used in the Dataplane
189      * @param vni the VNI to which the Elan is related
190      * @param elanTag the Elan Id to be used in the Dataplane
191      * @param addOrRemove States if the flow must be added or removed
192      */
193     public static void programExternalTunnelTable(IMdsalApiManager mdsalManager, BigInteger dpnId, int elanLportTag,
194             long vni, int elanTag, int addOrRemove) {
195         LOG.info("L2-ServiceChaining: programExternalTunnelTable dpId={} vni={} elanLportTag={} addOrRemove={} ",
196                  dpnId, vni, elanLportTag, addOrRemove);
197         String flowRef = buildExtTunnelTblToLportDispFlowRef(vni, elanLportTag);
198         if (addOrRemove == NwConstants.ADD_FLOW) {
199             List<MatchInfo> matches = Collections.singletonList(new MatchTunnelId(BigInteger.valueOf(vni)));
200             List<Instruction> instructions = buildSetLportTagAndGotoLportDispInstructions(elanLportTag);
201             Flow flow = MDSALUtil.buildFlowNew(NwConstants.EXTERNAL_TUNNEL_TABLE, flowRef,
202                     CloudServiceChainConstants.DEFAULT_SCF_FLOW_PRIORITY, flowRef,
203                     0, 0, NwConstants.TUNNEL_TABLE_COOKIE.add(BigInteger.valueOf(elanTag)),
204                     matches, instructions);
205             mdsalManager.installFlow(dpnId, flow);
206         } else {
207             Flow flow =
208                 new FlowBuilder().setTableId(NwConstants.EXTERNAL_TUNNEL_TABLE).setId(new FlowId(flowRef)).build();
209             mdsalManager.removeFlow(dpnId, flow);
210         }
211     }
212
213     /**
214      * Builds a List of Instructions that set the ElanPseudoPort Tag in
215      * metadata and sends to LPortDispatcher table (via Table 80).
216      *
217      * @param lportTag Dataplane identifier of the ElanPseudoPort
218      *
219      * @return the List of Instructions
220      */
221     public static List<Instruction> buildSetLportTagAndGotoLportDispInstructions(int lportTag) {
222         int instructionKey = 0;
223         BigInteger metadata = MetaDataUtil.getMetaDataForLPortDispatcher(lportTag,
224                 ServiceIndex.getIndex(NwConstants.SCF_SERVICE_NAME, NwConstants.SCF_SERVICE_INDEX));
225         List<Instruction> result =
226                 Arrays.asList(MDSALUtil.buildAndGetWriteMetadaInstruction(metadata,
227                         MetaDataUtil.getMetaDataMaskForLPortDispatcher(),
228                         ++instructionKey),
229                         MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.L3_INTERFACE_TABLE, ++instructionKey));
230         return result;
231     }
232
233     private static String buildExtTunnelTblToLportDispFlowRef(long vni, int elanLportTag) {
234         return CloudServiceChainConstants.L2_FLOWID_PREFIX + vni
235                 + NwConstants.FLOWID_SEPARATOR + elanLportTag;
236     }
237
238     private static String buildLportDispToScfFlowRef(int elanLportTag, long scfTag) {
239         return CloudServiceChainConstants.ELAN_TO_SCF_L2_FLOWID_PREFIX + elanLportTag
240                 + NwConstants.FLOWID_SEPARATOR + scfTag;
241     }
242
243     private static String buildLportDispFromScfFlowRef(long elanTag, int elanLportTag) {
244         return CloudServiceChainConstants.SCF_TO_ELAN_L2_FLOWID_PREFIX + elanTag
245                 + NwConstants.FLOWID_SEPARATOR + elanLportTag;
246     }
247
248     /**
249      * Stores the relation between ElanLport and scfTag.
250      *
251      * @param broker dataBroker service reference
252      * @param elanInstanceName Name of the ELAN. Typically its UUID
253      * @param lportTag Dataplane identifier of the ElanPseudoPort
254      * @param scfTag Dataplane identifier of the SCF
255      * @param addOrRemove States if flows must be added or removed
256      */
257     public static void updateElanToLportTagMap(final DataBroker broker, final String elanInstanceName,
258                                                final int lportTag, final long scfTag, final int addOrRemove) {
259         Long portTag = Long.valueOf(lportTag);
260         ElanToPseudoPortDataKey key = new ElanToPseudoPortDataKey(portTag, scfTag);
261         InstanceIdentifier<ElanToPseudoPortData> path = InstanceIdentifier.builder(ElanInstances.class)
262                 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName))
263                 .augmentation(ElanServiceChainState.class)
264                 .child(ElanToPseudoPortData.class, key).build();
265
266         if (addOrRemove == NwConstants.ADD_FLOW) {
267             ElanToPseudoPortData newValue =
268                     new ElanToPseudoPortDataBuilder().withKey(key).setElanLportTag(portTag)
269                                                      .setScfTag(scfTag).build();
270             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, path, newValue);
271         } else {
272             MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, path);
273         }
274     }
275
276     /**
277      * Read from ElanToLportTagMap the PsuedoLogicalPort related with a given elan.
278      *
279      * @param broker dataBroker service reference
280      * @param elanInstanceName the name of the Elan
281      * @return the ElanToPseudoPortData object or Optional.empty() if it
282      *     cannot be found
283      */
284     public static Optional<ElanServiceChainState> getElanServiceChainState(final DataBroker broker,
285                                                                            final String elanInstanceName) {
286         InstanceIdentifier<ElanServiceChainState> path = InstanceIdentifier.builder(ElanInstances.class)
287                 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName))
288                 .augmentation(ElanServiceChainState.class).build();
289         Optional<ElanServiceChainState> elanServiceChainStateOpc =
290             MDSALUtil.read(broker,LogicalDatastoreType.CONFIGURATION, path);
291
292         return elanServiceChainStateOpc;
293
294     }
295 }
296