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