Merge "fix critical sonar bugs"
[so.git] / adapters / mso-openstack-adapters / src / main / java / org / onap / so / adapters / audit / HeatStackAudit.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.adapters.audit;
22
23 import java.net.URI;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import java.util.stream.Collectors;
31 import java.util.stream.Stream;
32
33 import org.onap.aai.domain.yang.LInterface;
34 import org.onap.aai.domain.yang.LInterfaces;
35 import org.onap.aai.domain.yang.Vserver;
36 import org.onap.so.openstack.utils.MsoHeatUtils;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.stereotype.Component;
41
42 import com.woorea.openstack.heat.model.Link;
43 import com.woorea.openstack.heat.model.Resource;
44 import com.woorea.openstack.heat.model.Resources;
45 import com.woorea.openstack.heat.model.Stack;
46
47 @Component
48 public class HeatStackAudit {
49
50         private static final String RESOURCES = "/resources";
51
52         protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class);
53
54         @Autowired
55         protected MsoHeatUtils heat;
56
57         @Autowired
58         protected AuditVServer auditVservers;
59
60         public boolean auditHeatStack(String cloudRegion, String cloudOwner, String tenantId, String heatStackName) {
61                 try {
62                         logger.debug("Fetching Top Level Stack Information");
63                         Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName);
64                         List<Resource> novaResources = resources.getList().stream()
65                                         .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
66                         List<Resource> resourceGroups = resources.getList().stream()
67                                         .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces")).collect(Collectors.toList());
68                         if(novaResources.isEmpty())
69                                 return true;
70                         else{                           
71                                 Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources);
72                                 Set<Vserver> vserversWithSubInterfaces = processSubInterfaces(cloudRegion, tenantId, resourceGroups,
73                                         vserversToAudit);
74                                 return auditVservers.auditVservers(vserversWithSubInterfaces, tenantId, cloudOwner, cloudRegion);
75                         }
76                 } catch (Exception e) {
77                         logger.error("Error during auditing stack resources", e);
78                         return false;
79                 }
80         } 
81
82         protected Set<Vserver> processSubInterfaces(String cloudRegion, String tenantId, List<Resource> resourceGroups,
83                         Set<Vserver> vServersToAudit) throws Exception {
84                 for (Resource resourceGroup : resourceGroups) {
85                         processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup);
86                 }
87                 return vServersToAudit;
88         }
89
90         protected void processResourceGroups(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
91                         Resource resourceGroup) throws Exception {
92                 Optional<Link> stackLink = resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel()))
93                                 .findAny();
94                 if (stackLink.isPresent()) {
95                         try {
96                                 Optional<String> path = extractResourcePathFromHref(stackLink.get().getHref());
97                                 if (path.isPresent()) {
98                                         logger.debug("Fetching nested Resource Stack Information");
99                                         Resources nestedResourceGroupResources = heat.executeHeatClientRequest(path.get(), cloudRegion,
100                                                         tenantId, Resources.class);
101                                         processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface,
102                                                         nestedResourceGroupResources);
103                                 } else
104                                         throw new Exception("Error finding Path from Self Link");
105                         } catch (Exception e) {
106                                 logger.error("Error Parsing Link to obtain Path", e);
107                                 throw new Exception("Error finding Path from Self Link");
108                         }
109
110                 }
111         }
112
113         protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
114                         Resources nestedResourceGroupResources) throws Exception {
115                 for (Resource resourceGroupNested : nestedResourceGroupResources) {
116                         Optional<Link> subInterfaceStackLink = resourceGroupNested.getLinks().stream()
117                                         .filter(link -> "nested".equals(link.getRel())).findAny();
118                         if (subInterfaceStackLink.isPresent()) {
119                                 addSubInterface(cloudRegion, tenantId, vServersWithLInterface,subInterfaceStackLink.get());
120                         }
121                 }
122         }
123
124         protected void addSubInterface(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, Link subInterfaceStackLink) throws Exception {
125                         Optional<String> resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref());
126                         Optional<String> stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref());
127                         if (resourcePath.isPresent() && stackPath.isPresent()) {
128                                 logger.debug("Fetching nested Sub-Interface Stack Information");
129                                 Stack subinterfaceStack = heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class);
130                                 Resources subinterfaceResources = heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class);
131                                 if (subinterfaceStack != null) {
132                                         addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources);
133                                 }
134                         } else
135                                 throw new Exception("Error finding Path from Self Link");
136                 
137         }
138
139         protected void addSubInterfaceToVserver(Set<Vserver> vServersWithLInterface, Stack subinterfaceStack, Resources subinterfaceResources) throws Exception {
140                 String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface");
141                 logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId());
142                 for (Vserver auditVserver : vServersWithLInterface)
143                         for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface())
144                                 
145                                 if (parentNeutronPortId.equals(lInterface.getInterfaceId())) {
146                                         logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), lInterface.getInterfaceId());
147                                         Resource contrailVm = subinterfaceResources.getList().stream().filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())).findAny()
148                         .orElse(null);
149                                         if(contrailVm == null){
150                                                 throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: "+ subinterfaceStack.getId());
151                                         }
152                                         LInterface subInterface = new LInterface();
153                                         subInterface.setInterfaceId(contrailVm.getPhysicalResourceId());
154                                         
155                                         if(lInterface.getLInterfaces() == null)
156                                                 lInterface.setLInterfaces(new LInterfaces());
157                                         
158                                         lInterface.getLInterfaces().getLInterface().add(subInterface);
159                                 }else
160                                         logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}",auditVserver.getVserverId(), 
161                                                         lInterface.getInterfaceId(),subinterfaceStack.getId());
162         }
163
164         protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources) {
165                 Set<Vserver> vserversToAudit = new HashSet<>();
166                 for (Resource novaResource : novaResources) {
167                         Vserver auditVserver = new Vserver();
168                         auditVserver.setLInterfaces(new LInterfaces());
169                         auditVserver.setVserverId(novaResource.getPhysicalResourceId());
170                         Stream<Resource> filteredNeutronNetworks = resources.getList().stream()
171                                         .filter(resource -> resource.getRequiredBy().contains(novaResource.getLogicalResourceId()))
172                                         .filter(resource -> "OS::Neutron::Port".equals(resource.getType()));
173                         filteredNeutronNetworks.forEach(network -> {
174                                 LInterface lInterface = new LInterface();
175                                 lInterface.setInterfaceId(network.getPhysicalResourceId());
176                                 auditVserver.getLInterfaces().getLInterface().add(lInterface);
177                         });
178                         vserversToAudit.add(auditVserver);
179                 }
180                 return vserversToAudit;
181         }
182
183         protected Optional<String> extractResourcePathFromHref(String href) {           
184                 try {
185                         Optional<String> stackPath = extractStackPathFromHref(href);
186                         if (stackPath.isPresent()){                                             
187                                 return Optional.of(stackPath.get()+RESOURCES);
188                         }else
189                                 return Optional.empty();
190                 } catch (Exception e) {
191                         logger.error("Error parsing URI", e);
192                 }
193                 return Optional.empty();
194         }
195         
196         protected Optional<String> extractStackPathFromHref(String href) {
197                 try {
198                         URI uri = new URI(href);        
199                         Pattern p = Pattern.compile("/stacks.*");
200                         Matcher m = p.matcher(uri.getPath());
201                         if (m.find()){                                          
202                                 return Optional.of(m.group());
203                         }else
204                                 return Optional.empty();
205                 } catch (Exception e) {
206                         logger.error("Error parsing URI", e);
207                 }
208                 return Optional.empty();
209         }
210         
211         
212 }