2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import fj.data.Either;
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
30 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
31 import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory;
32 import org.openecomp.sdc.be.components.csar.CsarInfo;
33 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
36 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
37 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
41 import org.openecomp.sdc.be.dao.api.ActionStatus;
42 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
46 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
48 import org.openecomp.sdc.be.impl.ComponentsUtils;
49 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
50 import org.openecomp.sdc.be.model.ArtifactDefinition;
51 import org.openecomp.sdc.be.model.CapabilityDefinition;
52 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
53 import org.openecomp.sdc.be.model.InterfaceDefinition;
54 import org.openecomp.sdc.be.model.LifecycleStateEnum;
55 import org.openecomp.sdc.be.model.PropertyDefinition;
56 import org.openecomp.sdc.be.model.RequirementDefinition;
57 import org.openecomp.sdc.be.model.Resource;
58 import org.openecomp.sdc.be.model.UploadResourceInfo;
59 import org.openecomp.sdc.be.model.User;
60 import org.openecomp.sdc.be.model.category.CategoryDefinition;
61 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
62 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
63 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
64 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
65 import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
66 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
67 import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
68 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
69 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
70 import org.openecomp.sdc.be.utils.TypeUtils;
71 import org.openecomp.sdc.common.log.wrappers.Logger;
72 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
73 import org.openecomp.sdc.common.util.ValidationUtils;
74 import org.openecomp.sdc.exception.ResponseFormat;
75 import org.springframework.beans.factory.annotation.Autowired;
76 import org.springframework.stereotype.Component;
77 import org.springframework.web.context.WebApplicationContext;
78 import org.yaml.snakeyaml.Yaml;
80 import javax.servlet.ServletContext;
81 import java.util.ArrayList;
82 import java.util.Arrays;
83 import java.util.HashMap;
84 import java.util.HashSet;
85 import java.util.Iterator;
86 import java.util.List;
88 import java.util.Map.Entry;
90 import java.util.function.Function;
91 import java.util.regex.Pattern;
92 import java.util.stream.Collectors;
94 @Component("resourceImportManager")
95 public class ResourceImportManager {
96 static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("[\\w\\-\\_\\d\\:]+");
97 private static final String IMPLEMENTATION = "implementation";
99 private ServletContext servletContext;
101 private AuditingManager auditingManager;
102 private ResourceBusinessLogic resourceBusinessLogic;
103 private InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
105 private IGraphLockOperation graphLockOperation;
106 protected ToscaOperationFacade toscaOperationFacade;
108 protected final ComponentsUtils componentsUtils;
109 private final CapabilityTypeOperation capabilityTypeOperation;
111 private ResponseFormatManager responseFormatManager;
113 private static final Logger log = Logger.getLogger(ResourceImportManager.class);
116 public ResourceImportManager(ComponentsUtils componentsUtils, CapabilityTypeOperation capabilityTypeOperation) {
117 this.componentsUtils = componentsUtils;
118 this.capabilityTypeOperation = capabilityTypeOperation;
122 public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
123 this.toscaOperationFacade = toscaOperationFacade;
126 public ImmutablePair<Resource, ActionStatus> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
128 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
129 lifecycleChangeInfo.setUserRemarks("certification on import");
130 Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
132 return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false);
135 public ImmutablePair<Resource, ActionStatus> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
137 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
138 lifecycleChangeInfo.setUserRemarks("certification on import");
139 Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
141 return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false);
144 public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
145 Function<Resource, Boolean> validationFunction,
146 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) {
147 Resource resource = new Resource();
148 ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
149 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
151 String latestCertifiedResourceId = null;
153 boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
154 setConstantMetaData(resource, shouldBeCertified);
155 setMetaDataFromJson(resourceMetaData, resource);
157 populateResourceFromYaml(resourceYml, resource);
159 Boolean isValidResource = validationFunction.apply(resource);
160 if (!createNewVersion) {
161 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
162 if (latestByName.isLeft()) {
163 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName());
166 resource = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left;
167 Resource changeStateResponse;
169 if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) {
170 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
171 resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
172 if (handleNodeTypeArtifactsRes.isRight()) {
173 //TODO: should be used more correct action
174 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
177 latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
178 changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
179 responsePair = new ImmutablePair<>(changeStateResponse, response.left()
182 catch (RuntimeException e) {
183 handleImportResourceException(resourceMetaData, creator, true, e);
186 if (latestCertifiedResourceId != null && needLock) {
187 log.debug("unlock resource {}", latestCertifiedResourceId);
188 graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
195 private ResponseFormat getResponseFormatFromComponentException(RuntimeException e) {
196 if(e instanceof ComponentException){
197 return ((ComponentException) e).getResponseFormat() == null ?
198 componentsUtils.getResponseFormat(((ComponentException) e).getActionStatus(), ((ComponentException) e).getParams()) :
199 ((ComponentException) e).getResponseFormat();
204 private String getLatestCertifiedResourceId(Resource resource) {
205 Map<String, String> allVersions = resource.getAllVersions();
206 Double latestCertifiedVersion = 0.0;
207 if (allVersions != null) {
208 for (String version : allVersions.keySet()) {
209 Double dVersion = Double.valueOf(version);
210 if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) {
211 latestCertifiedVersion = dVersion;
214 return allVersions.get(String.valueOf(latestCertifiedVersion));
221 public void populateResourceMetadata(UploadResourceInfo resourceMetaData, Resource resource) {
222 if (resource != null && resourceMetaData != null) {
223 resource.setDescription(resourceMetaData.getDescription());
224 resource.setTags(resourceMetaData.getTags());
225 resource.setCategories(resourceMetaData.getCategories());
226 resource.setContactId(resourceMetaData.getContactId());
227 resource.setName(resourceMetaData.getName());
228 resource.setIcon(resourceMetaData.getResourceIconPath());
229 resource.setResourceVendorModelNumber(resourceMetaData.getResourceVendorModelNumber());
230 resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType()));
231 if (resourceMetaData.getVendorName() != null) {
232 resource.setVendorName(resourceMetaData.getVendorName());
234 if (resourceMetaData.getVendorRelease() != null) {
235 resource.setVendorRelease(resourceMetaData.getVendorRelease());
240 public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) {
242 Resource resource = new Resource();
243 ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
246 setMetaDataFromJson(resourceMetaData, resource);
248 populateResourceFromYaml(resourceYml, resource);
250 // currently import VF isn't supported. In future will be supported
251 // import VF only with CSAR file!!
252 if (ResourceTypeEnum.VF == resource.getResourceType()) {
253 log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only");
254 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
257 resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
258 Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
260 responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator,
261 false, isInTransaction, true, null, null, false);
264 catch (RuntimeException e) {
265 handleImportResourceException(resourceMetaData, creator, false, e);
271 void populateResourceFromYaml(String resourceYml, Resource resource) {
272 @SuppressWarnings("unchecked")
273 // Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
274 Object ymlObj = new Yaml().load(resourceYml);
275 if (ymlObj instanceof Map) {
276 Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj;
277 Map<String, Object> toscaJson = toscaJsonAll;
279 // Checks if exist and builds the node_types map
280 if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
281 toscaJson = new HashMap<>();
282 toscaJson.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()));
285 Resource parentResource = setDerivedFrom(toscaJson, resource);
286 if (StringUtils.isEmpty(resource.getToscaResourceName())) {
287 setToscaResourceName(toscaJson, resource);
289 setAttributes(toscaJson, resource);
290 setCapabilities(toscaJson, resource, parentResource);
291 setProperties(toscaJson, resource);
292 setRequirements(toscaJson, resource, parentResource);
293 setInterfaceLifecycle(toscaJson, resource);
296 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
301 private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
302 Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
303 if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) {
304 String toscaResourceName = toscaElement.left().value().keySet().iterator().next();
305 resource.setToscaResourceName(toscaResourceName);
309 private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource) {
310 Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.INTERFACES);
311 if (toscaInterfaces.isLeft()) {
312 Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
313 Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<>();
314 Iterator<Entry<String, Object>> interfacesNameValue = jsonInterfaces.entrySet().iterator();
315 while (interfacesNameValue.hasNext()) {
316 Entry<String, Object> interfaceNameValue = interfacesNameValue.next();
317 Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue
318 .getValue(), resource);
319 if (eitherInterface.isRight()) {
320 log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
323 moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value());
327 if (moduleInterfaces.size() > 0) {
328 resource.setInterfaces(moduleInterfaces);
333 private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(Object interfaceJson, Resource resource) {
334 InterfaceDefinition interf = new InterfaceDefinition();
335 Either<InterfaceDefinition, ResultStatusEnum> result = Either.left(interf);
338 if (interfaceJson instanceof String) {
339 String requirementJsonString = (String) interfaceJson;
340 interf.setType(requirementJsonString);
342 else if (interfaceJson instanceof Map && ResourceTypeEnum.VFC.equals(resource.getResourceType())) {
343 Map<String, Object> requirementJsonMap = (Map<String, Object>) interfaceJson;
344 Map<String, OperationDataDefinition> operations = new HashMap<>();
346 for (final Entry<String, Object> entry : requirementJsonMap.entrySet()) {
347 if (entryIsInterfaceType(entry)) {
348 String type = (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName());
349 interf.setType(type);
350 interf.setUniqueId(type.toLowerCase());
351 } else if (entryContainsImplementationForAKnownOperation(entry, interf.getType())){
353 OperationDataDefinition operation = new OperationDataDefinition();
354 operation.setName(entry.getKey());
356 ArtifactDataDefinition implementation = new ArtifactDataDefinition();
357 // Adding the artifact name in quotes to indicate that this is a literal value, rather than a reference to
359 implementation.setArtifactName(Constants.ESCAPED_DOUBLE_QUOTE + ((Map<String, String>)entry.getValue()).get(IMPLEMENTATION) + Constants.ESCAPED_DOUBLE_QUOTE);
360 operation.setImplementation(implementation);
362 operations.put(entry.getKey(), operation);
365 if (!operations.isEmpty()) {
366 interf.setOperations(operations);
370 result = Either.right(ResultStatusEnum.GENERAL_ERROR);
374 catch (Exception e) {
375 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
376 log.debug("error when creating interface, message:{}", e.getMessage(), e);
377 result = Either.right(ResultStatusEnum.GENERAL_ERROR);
383 private boolean entryIsInterfaceType(final Entry<String, Object> entry) {
384 if(entry.getKey().equals(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
385 if (entry.getValue() instanceof String) {
388 throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
393 private boolean entryContainsImplementationForAKnownOperation(final Entry<String, Object> entry, final String interfaceType) {
394 if (entry.getValue() instanceof Map && ((Map<?, ?>)entry.getValue()).containsKey(IMPLEMENTATION)) {
395 if (isAKnownOperation(interfaceType, entry.getKey())){
398 throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_FOUND);
403 private boolean isAKnownOperation(String interfaceType, String operation) {
404 Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes = interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes();
405 if (interfaceLifecycleTypes.isRight() || interfaceLifecycleTypes.left().value() == null) {
409 for (Entry<String, InterfaceDefinition> interfaceLifecycleType : interfaceLifecycleTypes.left().value().entrySet()) {
410 if (interfaceTypeAndOperationMatches(interfaceLifecycleType, interfaceType, operation)) {
417 private boolean interfaceTypeAndOperationMatches(Entry<String, InterfaceDefinition> interfaceLifecycleType, String interfaceType, String operation) {
418 if (interfaceLifecycleType.getKey().equalsIgnoreCase(interfaceType) && interfaceLifecycleType.getValue().getOperations() != null) {
419 for (String interfaceLifecycleTypeOperation : interfaceLifecycleType.getValue().getOperations().keySet()) {
420 if (interfaceLifecycleTypeOperation != null && interfaceLifecycleTypeOperation.equalsIgnoreCase(operation)){
428 private void setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
429 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, TypeUtils.ToscaTagNamesEnum.REQUIREMENTS);
430 if (toscaRequirements.isLeft()) {
431 List<Object> jsonRequirements = toscaRequirements.left().value();
432 Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<>();
433 // Checking for name duplication
434 Set<String> reqNames = new HashSet<>();
435 // Getting flattened list of capabilities of parent node - cap name
437 Map<String, String> reqName2TypeMap = getReqName2Type(parentResource);
438 for (Object jsonRequirementObj : jsonRequirements) {
440 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
441 String requirementName = requirementJsonWrapper.keySet().iterator().next();
442 String reqNameLowerCase = requirementName.toLowerCase();
443 if (reqNames.contains(reqNameLowerCase)) {
444 log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
445 throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase);
447 reqNames.add(reqNameLowerCase);
448 RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper
449 .get(requirementName));
450 requirementDef.setName(requirementName);
451 if (moduleRequirements.containsKey(requirementDef.getCapability())) {
452 moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
455 List<RequirementDefinition> list = new ArrayList<>();
456 list.add(requirementDef);
457 moduleRequirements.put(requirementDef.getCapability(), list);
460 // Validating against req/cap of "derived from" node
461 Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef
462 .getCapability(), requirementDef.getName());
463 if (!validateVsParentCap) {
464 log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource
466 throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef
468 .toLowerCase(), parentResource.getName());
471 if (moduleRequirements.size() > 0) {
472 resource.setRequirements(moduleRequirements);
478 private RequirementDefinition createRequirementFromImportFile(Object requirementJson) {
479 RequirementDefinition requirement = new RequirementDefinition();
481 if (requirementJson instanceof String) {
482 String requirementJsonString = (String) requirementJson;
483 requirement.setCapability(requirementJsonString);
485 else if (requirementJson instanceof Map) {
486 Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
487 if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) {
488 requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName()));
491 if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) {
492 requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName()));
495 if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
496 requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
498 if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
499 List<Object> occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
500 validateOccurrences(occurrencesList);
501 requirement.setMinOccurrences(occurrencesList.get(0).toString());
502 requirement.setMaxOccurrences(occurrencesList.get(1).toString());
506 throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
511 private void setProperties(Map<String, Object> toscaJson, Resource resource) {
512 Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
513 ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
514 Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
515 if (properties.isLeft()) {
516 List<PropertyDefinition> propertiesList = new ArrayList<>();
517 Map<String, PropertyDefinition> value = properties.left().value();
519 for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
520 String name = entry.getKey();
521 if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
522 log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName());
523 throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
525 PropertyDefinition propertyDefinition = entry.getValue();
526 propertyDefinition.setName(name);
527 propertiesList.add(propertyDefinition);
530 resource.setProperties(propertiesList);
532 else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
533 throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(properties
535 .value(), JsonPresentationFields.PROPERTY));
539 private ResultStatusEnum setAttributes(Map<String, Object> toscaJson, Resource resource) {
540 ResultStatusEnum result = ResultStatusEnum.OK;
541 Either<Map<String, PropertyDefinition>, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson);
542 if (attributes.isLeft()) {
543 List<PropertyDefinition> attributeList = new ArrayList<>();
544 Map<String, PropertyDefinition> value = attributes.left().value();
546 for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
547 String name = entry.getKey();
548 PropertyDefinition attributeDef = entry.getValue();
549 attributeDef.setName(name);
550 attributeList.add(attributeDef);
553 resource.setAttributes(attributeList);
556 result = attributes.right().value();
561 private Resource setDerivedFrom(Map<String, Object> toscaJson, Resource resource) {
562 Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM);
563 Resource derivedFromResource = null;
564 if (toscaDerivedFromElement.isLeft()) {
565 String derivedFrom = toscaDerivedFromElement.left().value();
566 log.debug("Derived from TOSCA name is {}", derivedFrom);
567 resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
568 Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
570 if (latestByToscaResourceName.isRight()) {
571 StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
572 if (operationStatus == StorageOperationStatus.NOT_FOUND) {
573 operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
575 log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
576 ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
577 BeEcompErrorManager.getInstance()
578 .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
579 throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom);
581 derivedFromResource = latestByToscaResourceName.left().value();
583 return derivedFromResource;
586 private void setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
587 Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES);
588 if (toscaCapabilities.isLeft()) {
589 Map<String, Object> jsonCapabilities = toscaCapabilities.left().value();
590 Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<>();
591 Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
592 Set<String> capNames = new HashSet<>();
593 // Getting flattened list of capabilities of parent node - cap name
595 Map<String, String> capName2TypeMap = getCapName2Type(parentResource);
596 while (capabilitiesNameValue.hasNext()) {
597 Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
599 // Validating that no req/cap duplicates exist in imported YAML
600 String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
601 if (capNames.contains(capNameLowerCase)) {
602 log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
603 throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase);
605 capNames.add(capNameLowerCase);
607 CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue
609 capabilityDef.setName(capabilityNameValue.getKey());
610 if (moduleCapabilities.containsKey(capabilityDef.getType())) {
611 moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
614 List<CapabilityDefinition> list = new ArrayList<>();
615 list.add(capabilityDef);
616 moduleCapabilities.put(capabilityDef.getType(), list);
619 // Validating against req/cap of "derived from" node
620 Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef
621 .getType(), capabilityDef.getName());
623 if (!validateVsParentCap) {
624 // Here parentResource is for sure not null, so it's
626 log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource
628 throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef
630 .toLowerCase(), parentResource.getName());
633 if (moduleCapabilities.size() > 0) {
634 resource.setCapabilities(moduleCapabilities);
639 private Map<String, String> getCapName2Type(Resource parentResource) {
640 Map<String, String> capName2type = new HashMap<>();
641 if (parentResource != null) {
642 Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities();
643 if (capabilities != null) {
644 for (List<CapabilityDefinition> capDefinitions : capabilities.values()) {
645 for (CapabilityDefinition capDefinition : capDefinitions) {
646 String nameLowerCase = capDefinition.getName().toLowerCase();
647 if (capName2type.get(nameLowerCase) != null) {
648 String parentResourceName = parentResource.getName();
649 log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase);
650 BeEcompErrorManager.getInstance()
651 .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR);
652 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
654 capName2type.put(nameLowerCase, capDefinition.getType());
662 private Map<String, String> getReqName2Type(Resource parentResource) {
663 Map<String, String> reqName2type = new HashMap<>();
664 if (parentResource != null) {
665 Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements();
666 if (requirements != null) {
667 for (List<RequirementDefinition> reqDefinitions : requirements.values()) {
668 for (RequirementDefinition reqDefinition : reqDefinitions) {
669 String nameLowerCase = reqDefinition.getName().toLowerCase();
670 if (reqName2type.get(nameLowerCase) != null) {
671 String parentResourceName = parentResource.getName();
672 log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase);
673 BeEcompErrorManager.getInstance()
674 .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR);
675 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
677 reqName2type.put(nameLowerCase, reqDefinition.getCapability());
685 private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
686 String capNameLowerCase = reqCapName.toLowerCase();
687 log.trace("Validating capability {} vs parent resource", capNameLowerCase);
688 String parentCapType = parentCapName2Type.get(capNameLowerCase);
689 if (parentCapType != null) {
690 if (childCapabilityType.equals(parentCapType)) {
691 log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType);
694 Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
695 if (capabilityTypeDerivedFrom.isRight()) {
696 log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
697 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom
701 return capabilityTypeDerivedFrom.left().value();
706 private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) {
708 CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
710 if (capabilityJson instanceof String) {
711 String capabilityJsonString = (String) capabilityJson;
712 capabilityDefinition.setType(capabilityJsonString);
714 else if (capabilityJson instanceof Map) {
715 Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
717 if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
718 capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
721 if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
722 capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES
726 if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
727 capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName()));
729 if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
730 List<Object> occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
731 validateOccurrences(occurrencesList);
732 capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
733 capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
735 if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) {
737 Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
738 if (propertiesRes.isRight()) {
739 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
746 .forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
747 List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left()
751 .map(p -> new ComponentInstanceProperty(p, p
752 .getDefaultValue(), null))
753 .collect(Collectors.toList());
754 capabilityDefinition.setProperties(capabilityProperties);
758 else if (!(capabilityJson instanceof List)) {
759 throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
761 return capabilityDefinition;
764 private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
765 ResponseFormat responseFormat;
766 ComponentException newException;
767 if (e instanceof ComponentException) {
768 ComponentException componentException = (ComponentException)e;
769 responseFormat = componentException.getResponseFormat();
770 if (responseFormat == null) {
771 responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams());
773 newException = componentException;
776 responseFormat = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
777 newException = new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
779 String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : "";
780 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName);
781 log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e);
782 auditErrorImport(resourceMetaData, user, responseFormat, isNormative);
786 private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
787 String version, lifeCycleState;
789 version = TypeUtils.getFirstCertifiedVersionVersion();
790 lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
794 lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
799 if (errorResponseWrapper.getMessageId() != null) {
800 message = errorResponseWrapper.getMessageId() + ": ";
802 message += errorResponseWrapper.getFormattedMessage();
805 AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
806 CommonAuditData.newBuilder()
807 .status(errorResponseWrapper.getStatus())
808 .description(message)
809 .requestId(ThreadLocalsHolder.getUuid())
811 new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
812 ResourceVersionInfo.newBuilder()
813 .state(lifeCycleState)
816 ResourceVersionInfo.newBuilder()
821 getAuditingManager().auditEvent(factory);
825 private void setMetaDataFromJson(final UploadResourceInfo resourceMetaData, final Resource resource) {
826 this.populateResourceMetadata(resourceMetaData, resource);
827 resource.setCreatorUserId(resourceMetaData.getContactId());
829 final String payloadData = resourceMetaData.getPayloadData();
830 if (payloadData != null) {
831 resource.setToscaVersion(getToscaVersion(payloadData));
834 final List<CategoryDefinition> categories = resourceMetaData.getCategories();
835 calculateResourceIsAbstract(resource, categories);
838 private String getToscaVersion(final String payloadData) {
839 final String decodedPayload = new String(Base64.decodeBase64(payloadData));
840 final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(decodedPayload);
841 final Either<String, ResultStatusEnum> findFirstToscaStringElement =
842 ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
843 return findFirstToscaStringElement.left().value();
846 private void calculateResourceIsAbstract(Resource resource, List<CategoryDefinition> categories) {
847 if (categories != null && !categories.isEmpty()) {
848 CategoryDefinition categoryDef = categories.get(0);
849 resource.setAbstract(false);
850 if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName()
851 .equals(Constants.ABSTRACT_CATEGORY_NAME)) {
852 SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
853 if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
854 resource.setAbstract(true);
860 private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
862 LifecycleStateEnum state;
863 if (shouldBeCertified) {
864 version = TypeUtils.getFirstCertifiedVersionVersion();
865 state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
868 version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
869 state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
871 resource.setVersion(version);
872 resource.setLifecycleState(state);
873 resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
874 resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
875 resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
879 private void validateOccurrences(List<Object> occurrensesList) {
881 if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
882 log.debug("Occurrenses list empty");
883 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
886 if (occurrensesList.size() < 2) {
887 log.debug("Occurrenses list size not 2");
888 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
890 Object minObj = occurrensesList.get(0);
891 Object maxObj = occurrensesList.get(1);
892 Integer minOccurrences;
893 Integer maxOccurrences;
894 if (minObj instanceof Integer) {
895 minOccurrences = (Integer) minObj;
898 log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj);
899 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
901 if (minOccurrences < 0) {
902 log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
903 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
906 if (maxObj instanceof String){
907 if(!"UNBOUNDED".equals(maxObj)) {
908 log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
909 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
913 if (maxObj instanceof Integer) {
914 maxOccurrences = (Integer) maxObj;
917 log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
918 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
921 if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
922 log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
923 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
928 public synchronized void init(ServletContext servletContext) {
929 if (this.servletContext == null) {
930 this.servletContext = servletContext;
931 responseFormatManager = ResponseFormatManager.getInstance();
932 resourceBusinessLogic = getResourceBL(servletContext);
936 public boolean isResourceExist(String resourceName) {
937 return resourceBusinessLogic.isResourceExist(resourceName);
940 private ResourceBusinessLogic getResourceBL(ServletContext context) {
941 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
942 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
943 return webApplicationContext.getBean(ResourceBusinessLogic.class);
946 public ServletContext getServletContext() {
947 return servletContext;
950 public AuditingManager getAuditingManager() {
951 return auditingManager;
954 public ResponseFormatManager getResponseFormatManager() {
955 return responseFormatManager;
958 public void setResponseFormatManager(ResponseFormatManager responseFormatManager) {
959 this.responseFormatManager = responseFormatManager;
962 public ResourceBusinessLogic getResourceBusinessLogic() {
963 return resourceBusinessLogic;
967 public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) {
968 this.resourceBusinessLogic = resourceBusinessLogic;
972 public void setInterfaceOperationBusinessLogic(InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {
973 this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
976 public IGraphLockOperation getGraphLockOperation() {
977 return graphLockOperation;
981 public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
982 this.graphLockOperation = graphLockOperation;
985 public void setServletContext(ServletContext servletContext) {
986 this.servletContext = servletContext;
990 public void setAuditingManager(AuditingManager auditingManager) {
991 this.auditingManager = auditingManager;