2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.services;
23 import static java.util.stream.Collectors.toList;
24 import static java.util.stream.Collectors.toMap;
25 import static java.util.stream.Collectors.toSet;
26 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
27 import static org.onap.vid.utils.Streams.not;
29 import com.fasterxml.jackson.databind.JsonNode;
30 import com.google.common.collect.ImmutableList;
31 import java.util.Collections;
32 import java.util.List;
34 import java.util.Objects;
35 import java.util.Optional;
37 import java.util.concurrent.Callable;
38 import java.util.concurrent.ConcurrentSkipListSet;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Future;
41 import java.util.concurrent.TimeUnit;
42 import java.util.stream.Collectors;
43 import java.util.stream.Stream;
44 import javax.inject.Inject;
45 import org.apache.commons.lang3.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
47 import org.apache.commons.lang3.tuple.Pair;
48 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
49 import org.onap.portalsdk.core.util.SystemProperties;
50 import org.onap.vid.aai.AaiClientInterface;
51 import org.onap.vid.aai.ExceptionWithRequestInfo;
52 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship;
53 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipData;
54 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList;
55 import org.onap.vid.aai.util.AAITreeNodeUtils;
56 import org.onap.vid.exceptions.GenericUncheckedException;
57 import org.onap.vid.model.aaiTree.AAITreeNode;
58 import org.onap.vid.model.aaiTree.FailureAAITreeNode;
59 import org.onap.vid.model.aaiTree.NodeType;
60 import org.onap.vid.mso.model.CloudConfiguration;
61 import org.onap.vid.properties.VidProperties;
62 import org.onap.vid.utils.Logging;
63 import org.onap.vid.utils.Streams;
64 import org.onap.vid.utils.Tree;
65 import org.onap.vid.utils.Unchecked;
67 import org.springframework.http.HttpMethod;
68 import org.springframework.stereotype.Component;
72 public class AAITreeNodeBuilder {
74 private static final String RESULTS = "results";
75 private final AaiClientInterface aaiClient;
76 private final Logging logging;
78 private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AAITreeNodeBuilder.class);
81 public enum AAIBaseProperties {
82 ORCHESTRATION_STATUS("orchestration-status"),
83 PROV_STATUS("prov-status"),
85 MODEL_VERSION_ID("model-version-id"),
86 MODEL_CUSTOMIZATION_ID("model-customization-id"),
87 MODEL_INVARIANT_ID("model-invariant-id"),
88 RELATIONSHIP_LIST("relationship-list");
90 private final String aaiKey;
92 AAIBaseProperties(String aaiKey) {
96 public String getAaiKey() {
102 public AAITreeNodeBuilder(AaiClientInterface aaiClient, Logging logging) {
103 this.aaiClient = aaiClient;
104 this.logging = logging;
107 List<AAITreeNode> buildNode(NodeType nodeType,
111 ConcurrentSkipListSet<AAITreeNode> nodesAccumulator,
112 ExecutorService threadPool,
113 Tree<AAIServiceTree.AaiRelationship> pathsTree) {
115 JsonNode jsonNode = aaiClient.typedAaiRest(Unchecked.toURI(requestURL), JsonNode.class, payload, method, false);
117 List<Pair<AAITreeNode, List<Relationship>>> nodes = getNodesWithRelationships(jsonNode, nodeType, nodesAccumulator, pathsTree);
119 String timeout = SystemProperties.getProperty(VidProperties.VID_THREAD_TIMEOUT);
120 long timeoutNum = Long.parseLong(StringUtils.defaultIfEmpty(timeout, "30"));
122 for (Pair<AAITreeNode, List<Relationship>> entry : nodes) {
123 fetchChildrenAsync(threadPool, nodesAccumulator, entry.getKey(), entry.getValue(), pathsTree, timeoutNum);
125 if (getNextLevelInPathsTree(pathsTree, NodeType.VF_MODULE.getType()) != null) {
126 getRelatedVfModules(threadPool, nodesAccumulator, requestURL, entry.getKey());
130 return nodes.stream()
132 .collect(Collectors.toList());
135 private List<Pair<AAITreeNode, List<Relationship>>> getNodesWithRelationships(JsonNode jsonNode, NodeType nodeType,
136 ConcurrentSkipListSet<AAITreeNode> nodesAccumulator,
137 Tree<AAIServiceTree.AaiRelationship> pathsTree) {
138 if (isListOfKeyResults(jsonNode)) {
139 return Streams.fromIterable(jsonNode.get(RESULTS))
140 .filter(item -> item.has(nodeType.getType()))
141 .map(item -> item.get(nodeType.getType()))
142 .map(item -> parseNodeAndFilterRelationships(item, nodeType, nodesAccumulator, pathsTree))
143 .collect(Collectors.toList());
144 } else if (isArray(jsonNode, nodeType)) {
145 return Streams.fromIterable(jsonNode.get(nodeType.getType()))
146 .map(item -> parseNodeAndFilterRelationships(item, nodeType, nodesAccumulator, pathsTree))
147 .collect(Collectors.toList());
149 return ImmutableList.of(parseNodeAndFilterRelationships(jsonNode, nodeType, nodesAccumulator, pathsTree));
153 Pair<AAITreeNode, List<Relationship>> parseNodeAndFilterRelationships(JsonNode jsonNode, NodeType nodeType,
154 ConcurrentSkipListSet<AAITreeNode> nodesAccumulator,
155 Tree<AAIServiceTree.AaiRelationship> pathsTree) {
156 AAITreeNode node = createAaiNode(nodeType, jsonNode, nodesAccumulator);
158 enrichPlacementData(node);
160 List<Relationship> filteredRelationships = getFilteredRelationships(jsonNode, pathsTree);
162 return ImmutablePair.of(node, filteredRelationships);
165 boolean isArray(JsonNode json, NodeType nodeType) {
166 return json != null && json.has(nodeType.getType()) && json.get(nodeType.getType()).isArray();
169 boolean isListOfKeyResults(JsonNode jsonNode) {
170 return jsonNode != null && jsonNode.has(RESULTS) && jsonNode.get(RESULTS).isArray();
173 AAITreeNode createAaiNode(NodeType nodeType, JsonNode jsonNode, ConcurrentSkipListSet<AAITreeNode> nodesAccumulator) {
174 AAITreeNode node = jsonNodeToAaiNode(nodeType, jsonNode);
176 nodesAccumulator.add(node);
181 private void addChildren(AAITreeNode node, Future<List<AAITreeNode>> children) {
183 node.addChildren(children.get());
184 } catch (Exception e) {
185 node.getChildren().add(createFailureNode(e));
189 private Map<String,String> convertRelationshipDataToMap(List<RelationshipData> relationshipData) {
190 return relationshipData.stream().collect(
191 Collectors.toMap(RelationshipData::getKey, RelationshipData::getValue));
194 void enrichPlacementData(AAITreeNode node){
195 Optional<Relationship> tenantRelationShip = AAITreeNodeUtils.findFirstRelationshipByRelatedTo(node.getRelationshipList(), "tenant");
196 enrichPlacementDataUsingTenantInfo(node, tenantRelationShip);
199 void enrichPlacementDataUsingTenantInfo(AAITreeNode node, Optional<Relationship> tenantRelationShip) {
200 //no tenant relationship in this node - so no placement data
201 if (!tenantRelationShip.isPresent()) {
205 Map<String, String> relationshipsDataMap = convertRelationshipDataToMap(tenantRelationShip.get().getRelationDataList());
206 node.setCloudConfiguration(new CloudConfiguration(
207 relationshipsDataMap.get("cloud-region.cloud-region-id"),
208 relationshipsDataMap.get("tenant.tenant-id"),
209 relationshipsDataMap.get("cloud-region.cloud-owner")));
211 catch (Exception exception) {
212 LOGGER.error("Failed to extract placement form tenant relationship of {}:{}", node.getType(), node.getId(), exception);
216 private void getRelatedVfModules(ExecutorService threadPool, ConcurrentSkipListSet<AAITreeNode> nodesAccumulator, String parentURL, AAITreeNode parentNode) {
218 VNFs do not report their direct related-to vf-modules, so try
219 directly fetching a resource URI.
222 Future<?> vfModulesTask = threadPool.submit(withCopyOfMDC(() -> {
223 // the response is an array of vf-modules
224 final JsonNode jsonNode;
226 jsonNode = aaiClient.typedAaiGet(Unchecked.toURI(parentURL + "/vf-modules"), JsonNode.class);
227 } catch (ExceptionWithRequestInfo e) {
228 if (e.getHttpCode().equals(404)) {
229 // it's ok, as we're just optimistically fetching
230 // the /vf-modules uri; 404 says this time it was a bad guess
237 if (isArray(jsonNode, NodeType.VF_MODULE)) {
238 //create list of AAITreeNode represent the VfModules from AAI result
239 List<AAITreeNode> vfModules = Streams.fromIterable(jsonNode.get(NodeType.VF_MODULE.getType()))
240 .map(vfModuleNode -> createAaiNode(NodeType.VF_MODULE, vfModuleNode, nodesAccumulator))
242 //enrich each of the VfModule with placement info
243 vfModules.forEach(vfModule -> enrichPlacementDataUsingTenantInfo(
245 AAITreeNodeUtils.findFirstRelationshipByRelatedTo(vfModule.getRelationshipList(), "vserver")
247 //add all VfModules to children list of parent node
248 parentNode.getChildren().addAll(vfModules);
250 LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to get vf-modules for vnf " + parentNode.getId());
253 return true; // the Callable<> contract requires a return value
256 waitForCompletion(vfModulesTask);
259 private void waitForCompletion(Future<?> future) {
262 } catch (Exception e) {
263 throw new GenericUncheckedException(e);
267 List<Relationship> getFilteredRelationships(JsonNode json, Tree<AAIServiceTree.AaiRelationship> pathsTree) {
268 RelationshipList relationshipList = JACKSON_OBJECT_MAPPER.convertValue(json.get(AAIBaseProperties.RELATIONSHIP_LIST.getAaiKey()), RelationshipList.class);
269 if (relationshipList != null) {
270 return relationshipList.getRelationship().stream()
271 .filter(rel -> getNextLevelInPathsTree(pathsTree, rel.getRelatedTo()) != null)
272 .filter(rel -> !Objects.equals(rel.getRelatedTo(), NodeType.VF_MODULE.getType())) // vf-modules are handled separately
276 return Collections.emptyList();
279 void fetchChildrenAsync(ExecutorService threadPool, ConcurrentSkipListSet<AAITreeNode> nodesAccumulator,
280 AAITreeNode node, List<Relationship> relationships, Tree<AAIServiceTree.AaiRelationship> pathsTree, long timeout) {
282 if (!relationships.isEmpty()) {
283 List<Callable<List<AAITreeNode>>> tasks = relationships.stream()
285 withCopyOfMDC(() -> getChildNode(threadPool, nodesAccumulator, relationship.getRelatedTo(),
286 relationship.getRelatedLink(), pathsTree)))
287 .collect(Collectors.toList());
290 int depth = pathsTree.getChildrenDepth();
291 threadPool.invokeAll(tasks, timeout * depth, TimeUnit.SECONDS)
293 addChildren(node, future)
295 } catch (Exception e) {
296 throw new GenericUncheckedException(e);
301 private <V> Callable<V> withCopyOfMDC(Callable<V> callable) {
302 return logging.withMDC(MDC.getCopyOfContextMap(), callable);
305 private List<AAITreeNode> getChildNode(ExecutorService threadPool, ConcurrentSkipListSet<AAITreeNode> nodesAccumulator,
306 String childNodeType, String childNodeUrl,
307 Tree<AAIServiceTree.AaiRelationship> pathsTree) {
309 Tree<AAIServiceTree.AaiRelationship> subTree = getNextLevelInPathsTree(pathsTree, childNodeType);
311 return buildNode(NodeType.fromString(childNodeType), childNodeUrl, null, HttpMethod.GET, nodesAccumulator, threadPool, subTree);
314 Tree<AAIServiceTree.AaiRelationship> getNextLevelInPathsTree(Tree<AAIServiceTree.AaiRelationship> pathsTree, String nodeType) {
315 return pathsTree.getSubTree(new AAIServiceTree.AaiRelationship(nodeType));
319 private AAITreeNode jsonNodeToAaiNode(NodeType nodeType, JsonNode jsonNode) {
320 AAITreeNode node = new AAITreeNode();
321 node.setType(nodeType);
322 node.setOrchestrationStatus(getStringDataFromJsonIfExists(jsonNode, AAIBaseProperties.ORCHESTRATION_STATUS.getAaiKey()));
323 node.setProvStatus(getStringDataFromJsonIfExists(jsonNode, AAIBaseProperties.PROV_STATUS.getAaiKey()));
324 node.setInMaint(getBooleanDataFromJsonIfExists(jsonNode, AAIBaseProperties.IN_MAINT.getAaiKey()));
325 node.setModelVersionId(getStringDataFromJsonIfExists(jsonNode, AAIBaseProperties.MODEL_VERSION_ID.getAaiKey()));
326 node.setModelCustomizationId(getStringDataFromJsonIfExists(jsonNode, AAIBaseProperties.MODEL_CUSTOMIZATION_ID.getAaiKey()));
327 node.setModelInvariantId(getStringDataFromJsonIfExists(jsonNode, AAIBaseProperties.MODEL_INVARIANT_ID.getAaiKey()));
328 node.setId(getStringDataFromJsonIfExists(jsonNode, nodeType.getId()));
329 node.setName(getStringDataFromJsonIfExists(jsonNode, nodeType.getName()));
330 node.setAdditionalProperties(aggregateAllOtherProperties(jsonNode, nodeType));
331 node.setRelationshipList(JACKSON_OBJECT_MAPPER.convertValue(jsonNode.get(AAIBaseProperties.RELATIONSHIP_LIST.getAaiKey()), RelationshipList.class));
335 private AAITreeNode createFailureNode(Exception exception) {
336 return FailureAAITreeNode.of(exception);
339 private String getStringDataFromJsonIfExists(JsonNode model, String key) {
340 if (!NodeType.NONE.equals(key) && model.has(key)) {
341 return model.get(key).asText();
346 private Boolean getBooleanDataFromJsonIfExists(JsonNode model, String key) {
347 if (model.has(key)) {
348 return model.get(key).asBoolean();
353 Map<String, Object> aggregateAllOtherProperties(JsonNode model, NodeType nodeType) {
354 Set<String> ignoreProperties = Stream.of(AAIBaseProperties.values())
355 .map(AAIBaseProperties::getAaiKey).collect(toSet());
356 return Streams.fromIterator(model.fields())
357 .filter(not(field -> StringUtils.equals(field.getKey(), nodeType.getId())))
358 .filter(not(field -> StringUtils.equals(field.getKey(), nodeType.getName())))
359 .filter(not(field -> ignoreProperties.contains(field.getKey())))
360 .collect(toMap(Map.Entry::getKey, v -> ifTextualGetAsText(v.getValue())));
363 private Object ifTextualGetAsText(JsonNode jsonNode) {
364 return jsonNode.isTextual() ? jsonNode.asText() : jsonNode;