Bump odlparent->6.0.0,mdsal->5.0.3
[netvirt.git] / vpnmanager / impl / src / main / java / org / opendaylight / netvirt / vpnmanager / intervpnlink / InterVpnLinkLocator.java
1 /*
2  * Copyright (c) 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.vpnmanager.intervpnlink;
9
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import java.util.ArrayList;
12 import java.util.HashSet;
13 import java.util.List;
14 import java.util.Objects;
15 import java.util.Set;
16 import java.util.function.Predicate;
17 import java.util.stream.Collectors;
18 import javax.inject.Inject;
19 import javax.inject.Singleton;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.genius.mdsalutil.NWUtil;
23 import org.opendaylight.netvirt.vpnmanager.VpnUtil;
24 import org.opendaylight.netvirt.vpnmanager.api.intervpnlink.InterVpnLinkCache;
25 import org.opendaylight.netvirt.vpnmanager.api.intervpnlink.InterVpnLinkDataComposite;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnTargets;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.vpntargets.VpnTarget;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netvirt.inter.vpn.link.rev160311.inter.vpn.links.InterVpnLink;
30 import org.opendaylight.yangtools.yang.common.Uint64;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * This class is responsible for searching the best possible DPN(s) to place
36  * an InterVpnLink.
37  *
38  */
39 @Singleton
40 public class InterVpnLinkLocator {
41
42     private static final Logger LOG = LoggerFactory.getLogger(InterVpnLinkLocator.class);
43     protected static final String NBR_OF_DPNS_PROPERTY_NAME = "vpnservice.intervpnlink.number.dpns";
44
45     private final DataBroker dataBroker;
46     private final InterVpnLinkCache interVpnLinkCache;
47     private final VpnUtil vpnUtil;
48
49     @Inject
50     public InterVpnLinkLocator(final DataBroker dataBroker, final InterVpnLinkCache interVpnLinkCache,
51                                final VpnUtil vpnUtil) {
52         this.dataBroker = dataBroker;
53         this.interVpnLinkCache = interVpnLinkCache;
54         this.vpnUtil = vpnUtil;
55     }
56
57     /**
58      * Retrieves a list of randomly selected DPNs avoiding to select DPNs
59      * where there is already an InterVpnLink of the same group (i.e., an
60      * InterVpnLink that links similar L3VPNs).
61      *
62      * @param interVpnLink InterVpnLink to find suitable DPNs for.
63      * @return the list of the selected DPN Ids
64      */
65     public List<Uint64> selectSuitableDpns(InterVpnLink interVpnLink) {
66         int numberOfDpns = Integer.getInteger(NBR_OF_DPNS_PROPERTY_NAME, 1);
67         List<Uint64> dpnIdPool = NWUtil.getOperativeDPNs(dataBroker).stream()
68                                                                         .map(dpn -> dpn)
69                                                                         .collect(Collectors.toList());
70         LOG.trace("selectSuitableDpns for {} with numberOfDpns={} and availableDpns={}",
71                   interVpnLink.getName(), numberOfDpns, dpnIdPool);
72         int poolSize = dpnIdPool.size();
73         if (poolSize <= numberOfDpns) {
74             // You requested more than there is, I give you all I have.
75             return dpnIdPool;
76         }
77
78         List<InterVpnLinkDataComposite> allInterVpnLinks = interVpnLinkCache.getAllInterVpnLinks();
79
80         // 1st criteria is to select those DPNs where there is no InterVpnLink at all
81         List<Uint64> dpnsWithNoIVL = findDPNsWithNoInterVpnLink(dpnIdPool, allInterVpnLinks);
82         if (dpnsWithNoIVL.size() >= numberOfDpns) {
83             return dpnsWithNoIVL.subList(0, numberOfDpns); // Best case scenario
84         }
85
86         // Not enough. 2nd criteria is to avoid DPNs where there are InterVpnLinks of the same group
87         List<Uint64> result = new ArrayList<>(dpnsWithNoIVL);
88         dpnIdPool.removeAll(result);
89         int pendingDPNs = numberOfDpns - result.size();
90
91         List<Uint64> dpnsToAvoid = findDpnsWithSimilarIVpnLinks(interVpnLink, allInterVpnLinks);
92         result.addAll(dpnIdPool.stream().filter(dpId -> !dpnsToAvoid.contains(dpId))
93                                .limit(pendingDPNs).collect(Collectors.toList()));
94
95         int currentNbrOfItems = result.size();
96         if (currentNbrOfItems < numberOfDpns) {
97             // Still not enough. 3rd criteria: whatever is available
98             dpnIdPool.removeAll(result);
99             pendingDPNs = numberOfDpns - currentNbrOfItems;
100             result.addAll(dpnIdPool.subList(0, Math.max(dpnIdPool.size(), pendingDPNs)));
101         }
102
103         return result;
104     }
105
106     /*
107      * Given a list of Dpn Ids and a list of InterVpnLinks, this method finds
108      * the DPNs in the first list where no InterVpnLink is instantiated there.
109      *
110      * @param dpnList A list of DPN IDs
111      * @param interVpnLinks A List of InterVpnLinks to avoid
112      *
113      * @return the list of available DPNs among the specified ones
114      */
115     private List<Uint64> findDPNsWithNoInterVpnLink(List<Uint64> dpnList,
116                                                         List<InterVpnLinkDataComposite> interVpnLinks) {
117         List<Uint64> occupiedDpns = new ArrayList<>();
118         for (InterVpnLinkDataComposite ivl : interVpnLinks) {
119             if (ivl.isActive()) {
120                 occupiedDpns.addAll(ivl.getFirstEndpointDpns());
121                 occupiedDpns.addAll(ivl.getSecondEndpointDpns());
122             }
123         }
124
125         List<Uint64> result = new ArrayList<>(dpnList);
126         result.removeAll(occupiedDpns);
127         return result;
128     }
129
130     /*
131      * Given an InterVpnLink, this method finds those DPNs where there is an
132      * InterVpnLink of the same group. Two InterVpnLinks are in the same group
133      * if they link 2 L3VPNs that are from the same group, and 2 L3VPNs are in
134      * the same group if their iRTs match.
135      *
136      * @param interVpnLink InterVpnLink to be checked
137      * @return the list of dpnIds where the specified InterVpnLink should not
138      *     be installed
139      */
140     @NonNull
141     private List<Uint64> findDpnsWithSimilarIVpnLinks(InterVpnLink interVpnLink,
142                                                           List<InterVpnLinkDataComposite> allInterVpnLinks) {
143         List<InterVpnLinkDataComposite> sameGroupInterVpnLinks = findInterVpnLinksSameGroup(interVpnLink,
144                                                                                             allInterVpnLinks);
145         Set<Uint64> resultDpns = new HashSet<>();
146         for (InterVpnLinkDataComposite ivl : sameGroupInterVpnLinks) {
147             resultDpns.addAll(ivl.getFirstEndpointDpns());
148             resultDpns.addAll(ivl.getSecondEndpointDpns());
149         }
150         return new ArrayList<>(resultDpns);
151     }
152
153     private List<String> getRts(VpnInstanceOpDataEntry vpnInstance, VpnTarget.VrfRTType rtType) {
154         String name = vpnInstance.getVpnInstanceName();
155         VpnTargets targets = vpnInstance.getVpnTargets();
156         if (targets == null) {
157             LOG.trace("vpn targets not available for {}", name);
158             return new ArrayList<>();
159         }
160         List<VpnTarget> vpnTargets = targets.getVpnTarget();
161         if (vpnTargets == null) {
162             LOG.trace("vpnTarget values not available for {}", name);
163             return new ArrayList<>();
164         }
165         return vpnTargets.stream()
166             .filter(target -> Objects.equals(target.getVrfRTType(), rtType)
167                 || Objects.equals(target.getVrfRTType(), VpnTarget.VrfRTType.Both))
168             .map(VpnTarget::getVrfRTValue)
169             .collect(Collectors.toList());
170     }
171
172     private List<String> getIRTsByVpnName(String vpnName) {
173         String vpn1Rd = vpnUtil.getVpnRd(vpnName);
174         final VpnInstanceOpDataEntry vpnInstance = vpnUtil.getVpnInstanceOpData(vpn1Rd);
175         return getRts(vpnInstance, VpnTarget.VrfRTType.ImportExtcommunity);
176     }
177
178     @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE")
179     private boolean haveSameIRTs(List<String> irts1, List<String> irts2) {
180         if (irts1 == null && irts2 == null) {
181             return true;
182         }
183         if (irts1 == null || irts2 == null) {
184             return false;
185         }
186
187         // FindBugs reports "Possible null pointer dereference of irts1 on branch that might be infeasible" but irts1
188         // can't be null here.
189         if (irts1.size() != irts2.size()) {
190             return false;
191         }
192         irts1.sort(/*comparator*/ null);
193         irts2.sort(/*comparator*/ null);
194         return irts1.equals(irts2);
195     }
196
197     public List<InterVpnLinkDataComposite> findInterVpnLinksSameGroup(InterVpnLink ivpnLinkToMatch,
198                                                                       List<InterVpnLinkDataComposite> interVpnLinks) {
199
200         List<String> vpnToMatch1IRTs = getIRTsByVpnName(ivpnLinkToMatch.getFirstEndpoint().getVpnUuid().getValue());
201         List<String> vpnToMatch2IRTs = getIRTsByVpnName(ivpnLinkToMatch.getSecondEndpoint().getVpnUuid().getValue());
202
203         Predicate<InterVpnLinkDataComposite> areSameGroup = (ivl) -> {
204             if (ivl.getInterVpnLinkName().equals(ivpnLinkToMatch.getName())) {
205                 return false; // ivl and ivpnLinlToMatch are the same InterVpnLink
206             }
207             String vpn1Name = ivl.getFirstEndpointVpnUuid().orNull();
208             String vpn2Name = ivl.getSecondEndpointVpnUuid().orNull();
209             if (vpn1Name == null) {
210                 return false;
211             }
212             List<String> vpn1IRTs = getIRTsByVpnName(vpn1Name);
213             List<String> vpn2IRTs = getIRTsByVpnName(vpn2Name);
214             return haveSameIRTs(vpn1IRTs, vpnToMatch1IRTs) && haveSameIRTs(vpn2IRTs, vpnToMatch2IRTs)
215                 || haveSameIRTs(vpn1IRTs, vpnToMatch2IRTs) && haveSameIRTs(vpn2IRTs, vpnToMatch1IRTs);
216         };
217
218         return interVpnLinks.stream().filter(areSameGroup).collect(Collectors.toList());
219     }
220 }