Rate limiting for ARP packet punts
[netvirt.git] / elanmanager / api / src / main / java / org / opendaylight / netvirt / elan / arp / responder / ArpResponderUtil.java
1 /*
2  * Copyright © 2016, 2017 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.elan.arp.responder;
9
10 import java.math.BigInteger;
11 import java.text.MessageFormat;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Collections;
15 import java.util.List;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.atomic.AtomicInteger;
19 import java.util.function.Supplier;
20 import java.util.stream.Collectors;
21
22 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
23 import org.opendaylight.genius.mdsalutil.ActionInfo;
24 import org.opendaylight.genius.mdsalutil.BucketInfo;
25 import org.opendaylight.genius.mdsalutil.FlowEntity;
26 import org.opendaylight.genius.mdsalutil.GroupEntity;
27 import org.opendaylight.genius.mdsalutil.InstructionInfo;
28 import org.opendaylight.genius.mdsalutil.MDSALUtil;
29 import org.opendaylight.genius.mdsalutil.MatchInfo;
30 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
31 import org.opendaylight.genius.mdsalutil.NwConstants;
32 import org.opendaylight.genius.mdsalutil.actions.ActionDrop;
33 import org.opendaylight.genius.mdsalutil.actions.ActionLoadIpToSpa;
34 import org.opendaylight.genius.mdsalutil.actions.ActionLoadMacToSha;
35 import org.opendaylight.genius.mdsalutil.actions.ActionMoveShaToTha;
36 import org.opendaylight.genius.mdsalutil.actions.ActionMoveSourceDestinationEth;
37 import org.opendaylight.genius.mdsalutil.actions.ActionMoveSpaToTpa;
38 import org.opendaylight.genius.mdsalutil.actions.ActionNxLoadInPort;
39 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
40 import org.opendaylight.genius.mdsalutil.actions.ActionSetArpOp;
41 import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource;
42 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
43 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
44 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
45 import org.opendaylight.genius.mdsalutil.matches.MatchArpOp;
46 import org.opendaylight.genius.mdsalutil.matches.MatchArpTpa;
47 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
48 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
49 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetEgressActionsForTunnelInputBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetEgressActionsForTunnelOutput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.add.group.input.buckets.bucket.action.action.NxActionResubmitRpcAddGroupCase;
64 import org.opendaylight.yangtools.yang.common.RpcResult;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 /**
69  * Arp Responder Utility Class.
70  */
71 public final class ArpResponderUtil {
72
73     private static final Logger LOG = LoggerFactory.getLogger(ArpResponderUtil.class);
74
75     private static final long WAIT_TIME_FOR_SYNC_INSTALL = Long.getLong("wait.time.sync.install", 300L);
76
77     /**
78      * A Utility class.
79      */
80     private ArpResponderUtil() {
81     }
82
83     /**
84      * Install Group flow on the DPN.
85      *
86      * @param mdSalManager
87      *            Reference of MDSAL API RPC that provides API for installing
88      *            group flow
89      * @param dpnId
90      *            DPN on which group flow to be installed
91      * @param groupdId
92      *            Uniquely identifiable Group Id for the group flow
93      * @param groupName
94      *            Name of the group flow
95      * @param buckets
96      *            List of the bucket actions for the group flow
97      */
98     public static void installGroup(IMdsalApiManager mdSalManager, BigInteger dpnId, long groupdId, String groupName,
99             List<BucketInfo> buckets) {
100         LOG.trace("Installing group flow on dpn {}", dpnId);
101         GroupEntity groupEntity = MDSALUtil.buildGroupEntity(dpnId, groupdId, groupName, GroupTypes.GroupAll, buckets);
102         mdSalManager.syncInstallGroup(groupEntity);
103         try {
104             Thread.sleep(WAIT_TIME_FOR_SYNC_INSTALL);
105         } catch (InterruptedException e1) {
106             LOG.warn("Error while waiting for ARP Responder Group Entry to be installed on DPN {} ", dpnId);
107         }
108     }
109
110     /**
111      * Get Default ARP Responder Drop flow on the DPN.
112      *
113      * @param dpnId
114      *            DPN on which group flow to be installed
115      */
116     public static FlowEntity getArpResponderTableMissFlow(BigInteger dpnId) {
117         return MDSALUtil.buildFlowEntity(dpnId, NwConstants.ARP_RESPONDER_TABLE,
118                 String.valueOf(NwConstants.ARP_RESPONDER_TABLE), NwConstants.TABLE_MISS_PRIORITY,
119                 ArpResponderConstant.DROP_FLOW_NAME.value(), 0, 0, NwConstants.COOKIE_ARP_RESPONDER,
120                 new ArrayList<MatchInfo>(),
121                 Collections.singletonList(new InstructionApplyActions(Collections.singletonList(new ActionDrop()))));
122     }
123
124     /**
125      * Get Bucket Actions for ARP Responder Group Flow.
126      *
127      * <p>
128      * Install Default Groups, Group has 1 Bucket
129      * </p>
130      * <ul>
131      * <li>Resubmit to Table {@link NwConstants#ARP_RESPONDER_TABLE}, for ARP
132      * Auto response from DPN itself</li>
133      * </ul>
134      *
135      * @param resubmitTableId
136      *            Resubmit Flow Table Id
137      * @return List of bucket actions
138      */
139     public static List<BucketInfo> getDefaultBucketInfos(short resubmitTableId) {
140         return Arrays.asList(
141                 new BucketInfo(Collections.singletonList(new ActionNxResubmit(resubmitTableId))));
142     }
143
144     /**
145      * Get Match Criteria for the ARP Responder Flow.
146      *
147      * <p>
148      * List of Match Criteria for ARP Responder
149      * </p>
150      * <ul>
151      * <li>Packet is ARP</li>
152      * <li>Packet is ARP Request</li>
153      * <li>The ARP packet is requesting for Gateway IP</li>
154      * <li>Metadata which is generated by using Service
155      * Index({@link NwConstants#L3VPN_SERVICE_INDEX}) Lport Tag
156      * ({@link MetaDataUtil#METADATA_MASK_LPORT_TAG}) and VRF
157      * ID({@link MetaDataUtil#METADATA_MASK_VRFID})</li>
158      * </ul>
159      *
160      * @param lportTag
161      *            LPort Tag
162      * @param elanInstance
163      *            Elan Instance
164      * @param ipAddress
165      *            Ip Address to be matched to this flow
166      * @return List of Match criteria
167      */
168     public static List<MatchInfo> getMatchCriteria(int lportTag, ElanInstance elanInstance,
169             String ipAddress) {
170
171         BigInteger metadata = ElanHelper.getElanMetadataLabel(elanInstance.getElanTag(), lportTag);
172         BigInteger metadataMask = ElanHelper.getElanMetadataMask();
173         return Arrays.asList(MatchEthernetType.ARP, MatchArpOp.REQUEST, new MatchArpTpa(ipAddress, "32"),
174                 new MatchMetadata(metadata, metadataMask));
175
176     }
177
178     /**
179      * Get List of actions for ARP Responder Flows.
180      *
181      * <p>
182      * Actions consists of all the ARP actions and Resubmit Action to table
183      * {@link NwConstants#ELAN_BASE_TABLE} such that packets can flow ELAN Rule
184      *
185      * @param ipAddress
186      *            IP Address for which ARP Response packet is to be generated
187      * @param macAddress
188      *            MacAddress for which ARP Response packet is to be generated
189      * @return List of ARP Responder Actions actions
190      */
191     public static List<Action> getActions(IInterfaceManager ifaceMgrRpcService, ItmRpcService itmRpcService,
192                                           String ifName, String ipAddress, String macAddress,
193                                           boolean isTunnelInterface) {
194
195         AtomicInteger actionCounter = new AtomicInteger();
196         List<Action> actions = arpActions.apply(actionCounter, macAddress, ipAddress);
197         actions.addAll(getEgressActionsForInterface(ifaceMgrRpcService, itmRpcService, ifName, actionCounter.get(),
198                 isTunnelInterface));
199         LOG.trace("Total Number of actions is {}", actionCounter);
200         return actions;
201
202     }
203
204     /**
205      * A Interface that represent lambda TriFunction.
206      *
207      * @param <T>
208      *            Input type
209      * @param <U>
210      *            Input type
211      * @param <S>
212      *            Input type
213      * @param <R>
214      *            Return Type
215      */
216     @SuppressWarnings("checkstyle:ParameterName")
217     public interface TriFunction<T, U, S, R> {
218         /**
219          * Apply the Action.
220          *
221          * @param t
222          *            Input1
223          * @param u
224          *            Input2
225          * @param s
226          *            Input3
227          * @return computed result
228          */
229         R apply(T t, U u, S s);
230     }
231
232     /**
233      * Lambda to apply arpAction. Inputs action counter, mac address and ip
234      * address
235      */
236     private static TriFunction<AtomicInteger, String, String, List<Action>> arpActions = (actionCounter, mac, ip) -> {
237         List<Action> actions = new ArrayList<>();
238         Collections.addAll(actions, new ActionMoveSourceDestinationEth().buildAction(actionCounter.getAndIncrement()),
239                 new ActionSetFieldEthernetSource(new MacAddress(mac)).buildAction(actionCounter.getAndIncrement()),
240                 new ActionSetArpOp(NwConstants.ARP_REPLY).buildAction(actionCounter.getAndIncrement()),
241                 new ActionMoveShaToTha().buildAction(actionCounter.getAndIncrement()),
242                 new ActionMoveSpaToTpa().buildAction(actionCounter.getAndIncrement()),
243                 new ActionLoadMacToSha(new MacAddress(mac)).buildAction(actionCounter.getAndIncrement()),
244                 new ActionLoadIpToSpa(ip).buildAction(actionCounter.getAndIncrement()),
245                 new ActionNxLoadInPort(BigInteger.ZERO).buildAction(actionCounter.getAndIncrement()));
246         return actions;
247
248     };
249
250     /**
251      * Get instruction list for ARP responder flows.
252      */
253     public static List<Instruction> getInterfaceInstructions(IInterfaceManager ifaceMgrRpcService, String interfaceName,
254             String ipAddress, String macAddress, ItmRpcService itmRpcService) {
255         List<Action> actions = ArpResponderUtil.getActions(ifaceMgrRpcService, itmRpcService, interfaceName, ipAddress,
256                 macAddress, false);
257         return Collections.singletonList(MDSALUtil.buildApplyActionsInstruction(actions));
258     }
259
260     /**
261      * Get instruction list for ARP responder flows originated from ext-net e.g.
262      * router-gw/fip.<br>
263      * The split-horizon bit should be reset in order to allow traffic from
264      * provider network to be routed back to flat/VLAN network and override the
265      * egress table drop flow.<br>
266      * In order to allow write-metadata in the ARP responder table the resubmit
267      * action needs to be replaced with goto instruction.
268      */
269     public static List<Instruction> getExtInterfaceInstructions(IInterfaceManager ifaceMgrRpcService,
270                                                                 ItmRpcService itmRpcService,
271                                                                 String extInterfaceName, String ipAddress,
272                                                                 String macAddress) {
273         AtomicInteger tableId = new AtomicInteger(-1);
274         List<Instruction> instructions = new ArrayList<>();
275         List<Action> actions = getActions(ifaceMgrRpcService, itmRpcService, extInterfaceName, ipAddress, macAddress,
276                 false);
277         actions.removeIf(v -> {
278             org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action actionClass = v
279                     .getAction();
280             if (actionClass instanceof NxActionResubmitRpcAddGroupCase) {
281                 tableId.set(((NxActionResubmitRpcAddGroupCase) actionClass).getNxResubmit().getTable());
282                 return true;
283             } else {
284                 return false;
285             }
286         });
287
288         instructions.add(MDSALUtil.buildApplyActionsInstruction(actions, 0));
289
290         if (tableId.get() != -1) {
291             // replace resubmit action with goto so it can co-exist with
292             // write-metadata
293             if ((short) tableId.get() > NwConstants.ARP_RESPONDER_TABLE) {
294                 instructions.add(new InstructionGotoTable((short) tableId.get()).buildInstruction(2));
295             } else {
296                 LOG.warn("Failed to insall responder flow for interface {}. Resubmit to {} can't be replaced with goto",
297                         extInterfaceName, tableId);
298             }
299         }
300
301         return instructions;
302     }
303
304     /**
305      * Install ARP Responder FLOW.
306      *
307      * @param mdSalManager
308      *            Reference of MDSAL API RPC that provides API for installing
309      *            flow
310      * @param dpnId
311      *            DPN on which flow to be installed
312      * @param flowId
313      *            Uniquely Identifiable Arp Responder Table flow Id
314      * @param flowName
315      *            Readable flow name
316      * @param priority
317      *            Flow Priority
318      * @param cookie
319      *            Flow Cookie
320      * @param matches
321      *            List of Match Criteria for the flow
322      * @param instructions
323      *            List of Instructions for the flow
324      */
325     public static void installFlow(IMdsalApiManager mdSalManager, BigInteger dpnId, String flowId, String flowName,
326             int priority, BigInteger cookie, List<MatchInfo> matches, List<Instruction> instructions) {
327         Flow flowEntity = MDSALUtil.buildFlowNew(NwConstants.ARP_RESPONDER_TABLE, flowId, priority, flowName, 0, 0,
328                 cookie, matches, instructions);
329         mdSalManager.installFlow(dpnId, flowEntity);
330     }
331
332     /**
333      * Remove flow form DPN.
334      *
335      * @param mdSalManager
336      *            Reference of MDSAL API RPC that provides API for installing
337      *            flow
338      * @param dpnId
339      *            DPN form which flow to be removed
340      * @param flowId
341      *            Uniquely Identifiable Arp Responder Table flow Id that is to
342      *            be removed
343      */
344     public static void removeFlow(IMdsalApiManager mdSalManager, BigInteger dpnId, String flowId) {
345         Flow flowEntity = MDSALUtil.buildFlow(NwConstants.ARP_RESPONDER_TABLE, flowId);
346         mdSalManager.removeFlow(dpnId, flowEntity);
347     }
348
349     /**
350      * Creates Uniquely Identifiable flow Id.
351      *
352      * @param lportTag
353      *            LportTag of the flow
354      * @param ipAdress
355      *            Gateway IP for which ARP Response flow to be installed
356      * @return Unique Flow Id
357      *
358      * @see ArpResponderConstant#FLOW_ID_FORMAT_WITH_LPORT
359      * @see ArpResponderConstant#FLOW_ID_FORMAT_WITHOUT_LPORT
360      */
361     public static String getFlowId(int lportTag, String ipAdress) {
362         return MessageFormat.format(ArpResponderConstant.FLOW_ID_FORMAT_WITH_LPORT.value(),
363                         NwConstants.ARP_RESPONDER_TABLE, lportTag, ipAdress);
364     }
365
366     /**
367      * Generate Cookie per flow.
368      *
369      * <p>
370      * Cookie is generated by Summation of
371      * {@link NwConstants#COOKIE_ARP_RESPONDER} + 1 + lportTag + Gateway IP
372      *
373      * @param lportTag
374      *            Lport Tag of the flow
375      * @param ipAddress
376      *            Gateway IP for which ARP Response flow to be installed
377      * @return Cookie
378      */
379     public static BigInteger generateCookie(int lportTag, String ipAddress) {
380         LOG.trace("IPAddress in long {}", ipAddress);
381         BigInteger cookie = NwConstants.COOKIE_ARP_RESPONDER.add(BigInteger.valueOf(255))
382                 .add(BigInteger.valueOf(ipTolong(ipAddress)));
383         return cookie.add(BigInteger.valueOf(lportTag));
384     }
385
386     private static BigInteger buildCookie(short tableId, int arpOpType) {
387         return NwConstants.COOKIE_ARP_RESPONDER.add(BigInteger.ONE).add(
388                 BigInteger.valueOf(tableId).add(BigInteger.valueOf(arpOpType)));
389     }
390
391     private static String buildFlowRef(short tableId, int arpOpType) {
392         return (tableId == NwConstants.ARP_CHECK_TABLE
393                 ? ArpResponderConstant.FLOWID_PREFIX_FOR_ARP_CHECK.value()
394                 : ArpResponderConstant.FLOWID_PREFIX_FOR_MY_GW_MAC.value()) + tableId + NwConstants.FLOWID_SEPARATOR
395                 + (arpOpType == NwConstants.ARP_REQUEST ? "arp.request" : "arp.replay");
396     }
397
398     public static FlowEntity createArpDefaultFlow(BigInteger dpId, short tableId, int arpOpType,
399             Supplier<List<MatchInfo>> matches, Supplier<List<ActionInfo>> actions) {
400
401         List<InstructionInfo> instructions = Collections.singletonList(new InstructionApplyActions(actions.get()));
402         return MDSALUtil.buildFlowEntity(dpId, tableId, buildFlowRef(tableId, arpOpType),
403                 NwConstants.DEFAULT_ARP_FLOW_PRIORITY, buildFlowRef(tableId, arpOpType), 0, 0,
404                 buildCookie(tableId, arpOpType), matches.get(), instructions);
405     }
406
407     /**
408      * Get IP Address in Long from String.
409      *
410      * @param address
411      *            IP Address that to be converted to long
412      * @return Long value of the IP Address
413      */
414     private static long ipTolong(String address) {
415
416         // Parse IP parts into an int array
417         long[] ip = new long[4];
418         String[] parts = address.split("\\.");
419
420         for (int i = 0; i < 4; i++) {
421             ip[i] = Long.parseLong(parts[i]);
422         }
423         // Add the above IP parts into an int number representing your IP
424         // in a 32-bit binary form
425         long ipNumbers = 0;
426         for (int i = 0; i < 4; i++) {
427             ipNumbers += ip[i] << (24 - (8 * i));
428         }
429         return ipNumbers;
430
431     }
432
433     /**
434      * Get List of Egress Action for the VPN interface.
435      *
436      * @param ifaceMgrRpcService
437      *            Interface Manager RPC reference that invokes API to retrieve
438      *            Egress Action
439      * @param ifName
440      *            VPN Interface for which Egress Action to be retrieved
441      * @param actionCounter
442      *            Action Key
443      * @return List of Egress Actions
444      */
445     public static List<Action> getEgressActionsForInterface(IInterfaceManager ifaceMgrRpcService,
446                                                             ItmRpcService itmRpcService, String ifName,
447                                                             int actionCounter, boolean isTunnelInterface) {
448         if (isTunnelInterface && ifaceMgrRpcService.isItmDirectTunnelsEnabled()) {
449             try {
450                 RpcResult result = itmRpcService.getEgressActionsForTunnel(new GetEgressActionsForTunnelInputBuilder()
451                         .setIntfName(ifName).build()).get();
452                 List<Action> listActions = new ArrayList<>();
453                 if (!result.isSuccessful()) {
454                     LOG.error("getEgressActionsForInterface: RPC Call to Get egress actions for interface {} "
455                             + "returned with Errors {}", ifName, result.getErrors());
456                 } else {
457                     listActions = ((GetEgressActionsForTunnelOutput) result.getResult()).getAction();
458                 }
459                 return listActions;
460             } catch (InterruptedException | ExecutionException e) {
461                 LOG.error("getEgressActionsForInterface: Exception when egress actions for interface {}", ifName, e);
462             }
463         } else {
464             List<ActionInfo> actionInfos = ifaceMgrRpcService.getInterfaceEgressActions(ifName);
465             AtomicInteger counter = new AtomicInteger(actionCounter);
466             return actionInfos.stream().map(v -> v.buildAction(counter.getAndIncrement())).collect(Collectors.toList());
467         }
468         return Collections.emptyList();
469     }
470
471     /**
472      * Uses the IdManager to retrieve ARP Responder GroupId from ELAN pool.
473      *
474      * @param idManager
475      *            the id manager
476      * @return the integer
477      */
478     public static Long retrieveStandardArpResponderGroupId(IdManagerService idManager) {
479
480         AllocateIdInput getIdInput = new AllocateIdInputBuilder()
481                 .setPoolName(ArpResponderConstant.ELAN_ID_POOL_NAME.value())
482                 .setIdKey(ArpResponderConstant.ARP_RESPONDER_GROUP_ID.value()).build();
483
484         try {
485             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
486             RpcResult<AllocateIdOutput> rpcResult = result.get();
487             if (rpcResult.isSuccessful()) {
488                 LOG.trace("Retrieved Group Id is {}", rpcResult.getResult().getIdValue());
489                 return rpcResult.getResult().getIdValue();
490             } else {
491                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
492             }
493         } catch (InterruptedException | ExecutionException e) {
494             LOG.warn("Exception when Allocating Id", e);
495         }
496         return 0L;
497     }
498
499 }