Merge "fixed CandidateType json serialization"
[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                         Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources);
69                         Set<Vserver> vserversWithSubInterfaces = processSubInterfaces(cloudRegion, tenantId, resourceGroups,
70                                         vserversToAudit); 
71                         return auditVservers.auditVservers(vserversWithSubInterfaces, tenantId, cloudOwner, cloudRegion);
72                 } catch (Exception e) {
73                         logger.error("Error during auditing stack resources", e);
74                         return false;
75                 }
76         } 
77
78         protected Set<Vserver> processSubInterfaces(String cloudRegion, String tenantId, List<Resource> resourceGroups,
79                         Set<Vserver> vServersToAudit) throws Exception {
80                 for (Resource resourceGroup : resourceGroups) {
81                         processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup);
82                 }
83                 return vServersToAudit;
84         }
85
86         protected void processResourceGroups(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
87                         Resource resourceGroup) throws Exception {
88                 Optional<Link> stackLink = resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel()))
89                                 .findAny();
90                 if (stackLink.isPresent()) {
91                         try {
92                                 Optional<String> path = extractResourcePathFromHref(stackLink.get().getHref());
93                                 if (path.isPresent()) {
94                                         logger.debug("Fetching nested Resource Stack Information");
95                                         Resources nestedResourceGroupResources = heat.executeHeatClientRequest(path.get(), cloudRegion,
96                                                         tenantId, Resources.class);
97                                         processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface,
98                                                         nestedResourceGroupResources);
99                                 } else
100                                         throw new Exception("Error finding Path from Self Link");
101                         } catch (Exception e) {
102                                 logger.error("Error Parsing Link to obtain Path", e);
103                                 throw new Exception("Error finding Path from Self Link");
104                         }
105
106                 }
107         }
108
109         protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
110                         Resources nestedResourceGroupResources) throws Exception {
111                 for (Resource resourceGroupNested : nestedResourceGroupResources) {
112                         Optional<Link> subInterfaceStackLink = resourceGroupNested.getLinks().stream()
113                                         .filter(link -> "nested".equals(link.getRel())).findAny();
114                         if (subInterfaceStackLink.isPresent()) {
115                                 addSubInterface(cloudRegion, tenantId, vServersWithLInterface,subInterfaceStackLink.get());
116                         }
117                 }
118         }
119
120         protected void addSubInterface(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, Link subInterfaceStackLink) throws Exception {
121                         Optional<String> resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref());
122                         Optional<String> stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref());
123                         if (resourcePath.isPresent() && stackPath.isPresent()) {
124                                 logger.debug("Fetching nested Sub-Interface Stack Information");
125                                 Stack subinterfaceStack = heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class);
126                                 Resources subinterfaceResources = heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class);
127                                 if (subinterfaceStack != null) {
128                                         addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources);
129                                 }
130                         } else
131                                 throw new Exception("Error finding Path from Self Link");
132                 
133         }
134
135         protected void addSubInterfaceToVserver(Set<Vserver> vServersWithLInterface, Stack subinterfaceStack, Resources subinterfaceResources) throws Exception {
136                 String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface");
137                 logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId());
138                 for (Vserver auditVserver : vServersWithLInterface)
139                         for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface())
140                                 
141                                 if (parentNeutronPortId.equals(lInterface.getInterfaceId())) {
142                                         logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), lInterface.getInterfaceId());
143                                         Resource contrailVm = subinterfaceResources.getList().stream().filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())).findAny()
144                         .orElse(null);
145                                         if(contrailVm == null){
146                                                 throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: "+ subinterfaceStack.getId());
147                                         }
148                                         LInterface subInterface = new LInterface();
149                                         subInterface.setInterfaceId(contrailVm.getPhysicalResourceId());
150                                         
151                                         if(lInterface.getLInterfaces() == null)
152                                                 lInterface.setLInterfaces(new LInterfaces());
153                                         
154                                         lInterface.getLInterfaces().getLInterface().add(subInterface);
155                                 }else
156                                         logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}",auditVserver.getVserverId(), 
157                                                         lInterface.getInterfaceId(),subinterfaceStack.getId());
158         }
159
160         protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources) {
161                 Set<Vserver> vserversToAudit = new HashSet<>();
162                 for (Resource novaResource : novaResources) {
163                         Vserver auditVserver = new Vserver();
164                         auditVserver.setLInterfaces(new LInterfaces());
165                         auditVserver.setVserverId(novaResource.getPhysicalResourceId());
166                         Stream<Resource> filteredNeutronNetworks = resources.getList().stream()
167                                         .filter(resource -> resource.getRequiredBy().contains(novaResource.getLogicalResourceId()))
168                                         .filter(resource -> "OS::Neutron::Port".equals(resource.getType()));
169                         filteredNeutronNetworks.forEach(network -> {
170                                 LInterface lInterface = new LInterface();
171                                 lInterface.setInterfaceId(network.getPhysicalResourceId());
172                                 auditVserver.getLInterfaces().getLInterface().add(lInterface);
173                         });
174                         vserversToAudit.add(auditVserver);
175                 }
176                 return vserversToAudit;
177         }
178
179         protected Optional<String> extractResourcePathFromHref(String href) {           
180                 try {
181                         Optional<String> stackPath = extractStackPathFromHref(href);
182                         if (stackPath.isPresent()){                                             
183                                 return Optional.of(stackPath.get()+RESOURCES);
184                         }else
185                                 return Optional.empty();
186                 } catch (Exception e) {
187                         logger.error("Error parsing URI", e);
188                 }
189                 return Optional.empty();
190         }
191         
192         protected Optional<String> extractStackPathFromHref(String href) {
193                 try {
194                         URI uri = new URI(href);        
195                         Pattern p = Pattern.compile("/stacks.*");
196                         Matcher m = p.matcher(uri.getPath());
197                         if (m.find()){                                          
198                                 return Optional.of(m.group());
199                         }else
200                                 return Optional.empty();
201                 } catch (Exception e) {
202                         logger.error("Error parsing URI", e);
203                 }
204                 return Optional.empty();
205         }
206         
207         
208 }