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=========================================================
21 package org.openecomp.sdc.be.components.impl;
24 import fj.data.Either;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
31 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
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.ArtifactsBusinessLogic.ArtifactOperationInfo;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
36 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
37 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
39 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
40 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
41 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
42 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
45 import org.openecomp.sdc.be.config.ConfigurationManager;
46 import org.openecomp.sdc.be.dao.api.ActionStatus;
47 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
48 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
49 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
50 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
51 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
58 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
59 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
60 import org.openecomp.sdc.be.impl.ComponentsUtils;
61 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
62 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
63 import org.openecomp.sdc.be.model.*;
64 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
65 import org.openecomp.sdc.be.model.category.CategoryDefinition;
66 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
67 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
68 import org.openecomp.sdc.be.model.operations.StorageException;
69 import org.openecomp.sdc.be.model.operations.api.*;
70 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
71 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
72 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
73 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
74 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
75 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
76 import org.openecomp.sdc.be.tosca.CsarUtils;
77 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
78 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
79 import org.openecomp.sdc.be.user.IUserBusinessLogic;
80 import org.openecomp.sdc.be.user.UserBusinessLogic;
81 import org.openecomp.sdc.be.utils.CommonBeUtils;
82 import org.openecomp.sdc.be.utils.TypeUtils;
83 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
84 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
85 import org.openecomp.sdc.common.api.Constants;
86 import org.openecomp.sdc.common.datastructure.Wrapper;
87 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
88 import org.openecomp.sdc.common.log.wrappers.Logger;
89 import org.openecomp.sdc.common.util.GeneralUtility;
90 import org.openecomp.sdc.common.util.ValidationUtils;
91 import org.openecomp.sdc.exception.ResponseFormat;
92 import org.springframework.beans.factory.annotation.Autowired;
93 import org.springframework.web.context.WebApplicationContext;
94 import org.yaml.snakeyaml.DumperOptions;
95 import org.yaml.snakeyaml.Yaml;
97 import javax.servlet.ServletContext;
99 import java.util.Map.Entry;
100 import java.util.function.Function;
101 import java.util.regex.Pattern;
103 import static java.util.stream.Collectors.*;
104 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
105 import static org.apache.commons.collections.MapUtils.isEmpty;
106 import static org.apache.commons.collections.MapUtils.isNotEmpty;
107 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
108 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
109 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
111 @org.springframework.stereotype.Component("resourceBusinessLogic")
112 public class ResourceBusinessLogic extends ComponentBusinessLogic {
114 private static final String DELETE_RESOURCE = "Delete Resource";
115 private static final String IN_RESOURCE = " in resource {} ";
116 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
117 public static final String INITIAL_VERSION = "0.1";
118 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
119 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
120 private static final String CREATE_RESOURCE = "Create Resource";
121 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
122 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
123 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
124 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
125 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
129 private ICapabilityTypeOperation capabilityTypeOperation = null;
132 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
135 private LifecycleBusinessLogic lifecycleBusinessLogic;
138 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
141 private ResourceImportManager resourceImportManager;
144 private InputsBusinessLogic inputsBusinessLogic;
147 private CompositionBusinessLogic compositionBusinessLogic;
150 private ICacheMangerOperation cacheManagerOperation;
153 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
156 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
159 private MergeInstanceUtils mergeInstanceUtils;
162 private UiComponentDataConverter uiComponentDataConverter;
165 private CsarBusinessLogic csarBusinessLogic;
168 * Default constructor
170 public ResourceBusinessLogic() {
171 log.debug("ResourceBusinessLogic started");
174 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
175 return lifecycleBusinessLogic;
178 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
179 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
182 public IElementOperation getElementDao() {
186 public void setElementDao(IElementOperation elementDao) {
187 this.elementDao = elementDao;
190 public IUserBusinessLogic getUserAdmin() {
191 return this.userAdmin;
194 public void setUserAdmin(UserBusinessLogic userAdmin) {
195 this.userAdmin = userAdmin;
198 public ComponentsUtils getComponentsUtils() {
199 return this.componentsUtils;
202 public void setComponentsUtils(ComponentsUtils componentsUtils) {
203 this.componentsUtils = componentsUtils;
206 public ArtifactsBusinessLogic getArtifactsManager() {
207 return artifactsBusinessLogic;
210 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
211 this.artifactsBusinessLogic = artifactsManager;
214 public ApplicationDataTypeCache getApplicationDataTypeCache() {
215 return applicationDataTypeCache;
218 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
219 this.applicationDataTypeCache = applicationDataTypeCache;
222 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
223 this.interfaceTypeOperation = interfaceTypeOperation;
227 * the method returns a list of all the resources that are certified, the
228 * returned resources are only abstract or only none abstract according to
235 public List<Resource> getAllCertifiedResources(boolean getAbstract,
236 HighestFilterEnum highestFilter, String userId) {
237 User user = validateUserExists(userId, "get All Certified Resources", false);
238 Boolean isHighest = null;
239 switch (highestFilter) {
245 case NON_HIGHEST_ONLY:
251 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
252 .getAllCertifiedResources(getAbstract, isHighest);
254 if (getResponse.isRight()) {
255 throw new StorageException(getResponse.right().value());
258 return getResponse.left().value();
261 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
262 ResourceTypeEnum resourceTypeEnum, String userId) {
264 validateUserExists(userId, "validate Resource Name Exists", false);
266 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
267 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
271 if (dataModelResponse.isLeft()) {
272 Map<String, Boolean> result = new HashMap<>();
273 result.put("isValid", dataModelResponse.left().value());
274 log.debug("validation was successfully performed.");
275 return Either.left(result);
278 ResponseFormat responseFormat = componentsUtils
279 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
281 return Either.right(responseFormat);
284 public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
285 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
286 validateResourceBeforeCreate(resource, user, false);
287 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
288 if (StringUtils.isNotEmpty(csarUUID)) {
289 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
290 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
291 return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
294 return createResourceByDao(resource, user, auditingAction, false, false);
297 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
298 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
299 String csarUUID = payloadName;
300 String csarVersion = null;
301 Resource updatedResource = null;
302 if (payloadName == null) {
303 csarUUID = resource.getCsarUUID();
304 csarVersion = resource.getCsarVersion();
306 if (csarUUID != null && !csarUUID.isEmpty()) {
307 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
308 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
309 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
310 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
311 overrideImmutableMetadata(oldResource, resource);
313 validateResourceBeforeCreate(resource, user, false);
314 String oldCsarVersion = oldResource.getCsarVersion();
315 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
317 // (on boarding flow): If the update includes same csarUUID and
318 // same csarVersion as already in the VF - no need to import the
319 // csar (do only metadata changes if there are).
320 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
321 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
324 updatedResource = updateResourceFromCsar(oldResource, resource, user,
325 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
328 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
329 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
331 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
332 throw new ComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
334 return updatedResource;
337 private void validateCsarIsNotAlreadyUsed(Resource oldResource,
338 Resource resource, String csarUUID, User user) {
339 // (on boarding flow): If the update includes a csarUUID: verify this
340 // csarUUID is not in use by another VF, If it is - use same error as
342 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
343 // select another or update the existing VF." %1 - csarUUID, %2 - VF
345 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
346 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
347 if (resourceLinkedToCsarRes.isRight()) {
348 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
349 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
350 resource.getSystemName());
351 throw new StorageException(resourceLinkedToCsarRes.right().value());
353 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
354 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
355 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
356 resourceLinkedToCsarRes.left().value().getName());
357 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
358 throw new ComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
359 resourceLinkedToCsarRes.left().value().getName());
363 private void validateCsarUuidMatching(Resource resource,
364 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
365 // (on boarding flow): If the update includes csarUUID which is
366 // different from the csarUUID of the VF - fail with
367 // error: "Error: Resource %1 cannot be updated using since it is linked
368 // to a different VSP" %1 - VF name
369 String oldCsarUUID = oldResource.getCsarUUID();
370 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
372 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
373 resourceUniqueId, csarUUID, oldCsarUUID);
374 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
375 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
376 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
377 throw new ComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
381 private Resource getResourceByUniqueId(String resourceUniqueId) {
382 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
383 if (oldResourceRes.isRight()) {
384 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
385 oldResourceRes.right().value());
386 throw new StorageException(oldResourceRes.right().value());
388 return oldResourceRes.left().value();
391 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
392 resource.setName(oldRresource.getName());
393 resource.setIcon(oldRresource.getIcon());
394 resource.setTags(oldRresource.getTags());
395 resource.setCategories(oldRresource.getCategories());
396 resource.setDerivedFrom(oldRresource.getDerivedFrom());
399 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
400 User user, AuditingActionEnum updateResource, boolean inTransaction,
401 Map<String, byte[]> csarUIPayload, String csarUUID) {
402 Resource updatedResource = null;
403 validateLifecycleState(oldResource, user);
404 String lockedResourceId = oldResource.getUniqueId();
405 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
406 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
407 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
408 "update Resource From Csar");
409 if (lockResult.isRight()) {
410 throw new ComponentException(lockResult.right().value());
413 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
415 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
416 nodeTypesInfo, csarInfo, oldResource);
417 if (findNodeTypesArtifactsToHandleRes.isRight()) {
418 log.debug("failed to find node types for update with artifacts during import csar {}. ",
419 csarInfo.getCsarUUID());
420 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
422 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
425 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
426 csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
428 connectUiRelations(oldResource, updatedResource);
430 } catch (ComponentException|StorageException e){
431 rollback(inTransaction, newResource, createdArtifacts, null);
436 log.debug("unlock resource {}", lockedResourceId);
437 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
439 return updatedResource;
443 private void validateLifecycleState(Resource oldResource, User user) {
444 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
445 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
446 log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
447 oldResource.getLastUpdaterUserId(), user.getUserId());
448 throw new ComponentException(ActionStatus.RESTRICTED_OPERATION);
452 private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
453 Either<Resource, ResponseFormat> result;
455 List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
457 StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
458 if (status == StorageOperationStatus.OK) {
459 newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
460 result = Either.left(newResource);
462 result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
468 private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
469 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
470 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
471 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
472 String nodeName, boolean isNested) {
473 boolean inTransaction = true;
474 boolean shouldLock = false;
475 Resource preparedResource = null;
476 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
478 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
479 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
480 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
481 inTransaction, shouldLock, isNested).left;
482 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
483 handleResourceGenericType(preparedResource);
484 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
485 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
486 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
487 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
488 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
489 } catch (ComponentException e) {
490 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
491 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
492 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
494 } catch (StorageException e){
495 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
496 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
497 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
500 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
501 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
502 preparedResource.getSystemName());
503 if (validateUpdateVfGroupNamesRes.isRight()) {
505 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
507 // add groups to resource
508 Map<String, GroupDefinition> groups;
510 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
511 groups = validateUpdateVfGroupNamesRes.left().value();
513 groups = uploadComponentInstanceInfoMap.getGroups();
515 handleGroupsProperties(preparedResource, groups);
516 preparedResource = updateGroupsOnResource(preparedResource, groups);
517 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
518 nodeTypesArtifactsToHandle);
520 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
521 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
522 if (updateArtifactsEither.isRight()) {
523 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
524 throw new ComponentException(updateArtifactsEither.right().value());
526 preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
528 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
529 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
530 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
532 throw new ComponentException(responseFormat);
534 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
535 return preparedResource;
538 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
539 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
540 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
542 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
543 Resource resource = preparedResource;
545 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
546 .getNodeTypesArtifactsToHandle();
547 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
548 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
549 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
550 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
551 if (handleNodeTypeArtifactsRes.isRight()) {
552 return Either.right(handleNodeTypeArtifactsRes.right().value());
556 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
557 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
558 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
559 if (createdCsarArtifactsEither.isRight()) {
560 return createdCsarArtifactsEither;
563 resource = createdCsarArtifactsEither.left().value();
565 return Either.left(resource);
568 private Resource handleResourceGenericType(Resource resource) {
569 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
570 if (resource.shouldGenerateInputs()) {
571 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
573 return genericResource;
576 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
577 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
579 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
580 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
581 = Either.left(nodeTypesArtifactsToHandle);
584 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
585 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
586 extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
587 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
588 oldResource.getName(), csarInfo.getCsarUUID());
589 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
590 extractedVfcsArtifacts,
591 namespace, vfcToscaNames));
592 } catch (Exception e) {
593 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
594 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
595 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
597 return nodeTypesArtifactsToHandleRes;
600 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
601 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
603 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
604 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
605 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
606 if (!isEmpty(extractedVfcsArtifacts)) {
607 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
608 if (extractedVfcsArtifacts.containsKey(namespace)) {
609 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
611 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
612 } else if (curNodeType != null) {
613 // delete all artifacts if have not received artifacts from
615 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
616 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
617 // delete all informational artifacts
618 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
619 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
621 // delete all deployment artifacts
622 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
623 if (!artifactsToDelete.isEmpty()) {
624 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
627 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
628 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
632 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
633 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
634 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
635 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
636 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
637 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
638 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
639 return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
641 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
646 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
647 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
649 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
651 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
652 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
653 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
654 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
655 collectExistingArtifacts(curNodeType));
656 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
657 } catch (Exception e) {
658 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
659 throw new ComponentException(ActionStatus.GENERAL_ERROR);
661 return nodeTypeArtifactsToHandle;
664 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
665 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
666 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
667 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
668 if (!artifactsToUpload.isEmpty()) {
669 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
671 if (!artifactsToUpdate.isEmpty()) {
672 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
674 if (!artifactsToDelete.isEmpty()) {
675 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
678 return nodeTypeArtifactsToHandle;
681 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
682 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
683 Map<String, ArtifactDefinition> existingArtifacts) {
684 if (!existingArtifacts.isEmpty()) {
685 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
686 artifactsToDelete.addAll(existingArtifacts.values());
690 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
691 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
693 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
695 if (foundArtifact.isPresent()) {
696 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
697 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
698 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
699 artifactsToUpload.remove(currNewArtifact);
701 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
702 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
703 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
704 foundArtifact.get().getArtifactType());
709 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
710 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
711 foundArtifact.setPayload(currNewArtifact.getPayloadData());
712 foundArtifact.setPayloadData(
713 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
714 foundArtifact.setArtifactChecksum(GeneralUtility
715 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
716 artifactsToUpdate.add(foundArtifact);
720 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
721 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
722 if (curNodeType == null) {
723 return existingArtifacts;
725 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
726 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
728 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
730 .putAll(curNodeType.getArtifacts().entrySet()
732 .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
733 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
735 return existingArtifacts;
739 * Changes resource life cycle state to checked out
743 * @param inTransaction
746 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
747 Either<Resource, ResponseFormat> checkoutResourceRes;
749 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
750 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
752 "************* Going to change life cycle state of resource {} to not certified checked out. ",
754 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
755 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
756 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
757 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
758 inTransaction, true);
759 if (checkoutRes.isRight()) {
760 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
761 resource.getComponentType().getNodeType(), resource.getUniqueId(),
762 checkoutRes.right().value().getStatus());
763 checkoutResourceRes = Either.right(checkoutRes.right().value());
765 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
768 checkoutResourceRes = Either.left(resource);
770 } catch (Exception e) {
771 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
772 checkoutResourceRes = Either.right(responseFormat);
773 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
776 return checkoutResourceRes;
780 * Handles Artifacts of NodeType
782 * @param nodeTypeResource
783 * @param nodeTypeArtifactsToHandle
785 * @param inTransaction
788 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
789 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
790 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
791 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
792 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
793 Either<Resource, ResponseFormat> changeStateResponse;
795 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
796 if (changeStateResponse.isRight()) {
797 return Either.right(changeStateResponse.right().value());
799 nodeTypeResource = changeStateResponse.left().value();
801 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
802 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
803 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
805 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
806 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
807 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
808 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
809 nodeTypeResource.getName());
810 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
811 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
812 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
813 ignoreLifecycleState, curOperation),
814 false, inTransaction);
815 if (handleNodeTypeArtifactsRequestRes.isRight()) {
816 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
819 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
820 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
822 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
825 if (handleNodeTypeArtifactsRes == null) {
826 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
828 } catch (Exception e) {
829 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
830 handleNodeTypeArtifactsRes = Either.right(responseFormat);
831 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
833 return handleNodeTypeArtifactsRes;
836 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
837 String vfResourceName, CsarInfo csarInfo) {
838 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
840 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
841 if (!nodes.isEmpty()) {
842 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
843 while (nodesNameEntry.hasNext()) {
844 Entry<String, Object> nodeType = nodesNameEntry.next();
845 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
846 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
847 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
850 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
851 vfcToscaNames.put(cvfc.getType(),
852 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
854 return vfcToscaNames;
857 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
858 Map<String, Object> nodes = new HashMap<>();
859 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
860 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
862 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
866 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
867 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
868 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
869 if (eitherNodeTypes.isLeft()) {
870 nodes.putAll(eitherNodeTypes.left().value());
874 public Resource createResourceFromCsar(Resource resource, User user,
875 Map<String, byte[]> csarUIPayload, String csarUUID) {
876 log.trace("************* created successfully from YAML, resource TOSCA ");
878 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
880 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
881 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
882 nodeTypesInfo, csarInfo, resource);
883 if (findNodeTypesArtifactsToHandleRes.isRight()) {
884 log.debug("failed to find node types for update with artifacts during import csar {}. ",
885 csarInfo.getCsarUUID());
886 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
888 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
889 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
891 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
892 vfResource.getToscaResourceName());
896 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
897 log.trace("validating resource before create");
898 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
899 // validate user role
900 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
901 // VF / PNF "derivedFrom" should be null (or ignored)
902 if (ModelConverter.isAtomicComponent(resource)) {
903 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
905 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
909 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
910 // nodeTypesArtifactsToCreate, true, false, null
911 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
912 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
913 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
914 boolean shouldLock, boolean inTransaction, String nodeName) {
916 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
917 Resource createdResource;
919 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
920 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
921 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
922 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
923 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
924 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
925 } catch (ComponentException e) {
926 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
927 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
929 } catch (StorageException e){
930 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
931 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
934 return createdResource;
938 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
939 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
940 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
943 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
944 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
945 if (toscaVersion.isRight()) {
946 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
948 Map<String, Object> mapToConvert = new HashMap<>();
949 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
950 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
951 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
952 return csarInfo.getCreatedNodes();
955 private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
956 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
957 .left().orValue(HashMap::new);
960 private void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
961 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
962 Resource vfcCreated = null;
963 while (nodesNameValueIter.hasNext()) {
964 Entry<String, Object> nodeType = nodesNameValueIter.next();
965 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
966 || nodeTypesArtifactsToHandle.isEmpty() ? null
967 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
969 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
970 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
971 vfcCreated = handleNestedVfc(resource,
972 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
974 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
975 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
976 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
977 log.trace("************* Going to create node {}", nodeType.getKey());
978 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
979 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
981 log.debug("************* Finished to create node {}", nodeType.getKey());
983 vfcCreated = resourceCreated.getLeft();
984 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
985 vfcCreated.getToscaResourceName());
987 if (vfcCreated != null) {
988 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
990 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
994 private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
995 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
998 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
999 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1001 log.debug("************* Going to create node types from yaml {}", yamlName);
1002 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1003 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1004 log.debug("************* Finished to create node types from yaml {}", yamlName);
1006 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1007 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1008 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1009 csarInfo, nodeName, yamlName);
1014 private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1015 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1016 String nodeName, String yamlName) {
1018 Resource oldComplexVfc = null;
1019 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1020 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1021 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1022 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1023 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1024 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1025 nodeName).getRight());
1027 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1028 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1029 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1030 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1031 } else if (oldComplexVfcRes.isLeft()) {
1032 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1033 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1034 oldComplexVfcRes.left().value(), newComplexVfc,
1035 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1036 if (eitherValidation.isLeft()) {
1037 oldComplexVfc = oldComplexVfcRes.left().value();
1040 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1041 oldComplexVfc, newComplexVfc);
1042 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1043 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1044 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1045 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1046 Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1048 if (result.isRight()) {
1049 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1051 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1052 csarInfo.removeNodeFromQueue();
1053 return result.left().value();
1056 private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1057 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1058 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1060 Resource handleComplexVfcRes;
1061 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1062 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1063 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1064 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1065 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1066 if (oldComplexVfc == null) {
1067 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1068 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1070 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1071 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1072 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1074 return handleComplexVfcRes;
1077 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1078 Map<String, NodeTypeInfo> nodesInfo) {
1080 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1081 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1082 csarInfo.addNodeToQueue(nodeName);
1083 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1084 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1087 private String getNodeTypeActualName(String fullName) {
1088 String nameWithouNamespacePrefix = fullName
1089 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1090 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1091 String resourceType = findTypes[0];
1092 return nameWithouNamespacePrefix.substring(resourceType.length());
1095 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1096 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1097 Resource resourceVf, boolean needLock,
1098 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1099 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1102 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1104 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1105 resourceMetaData.getResourceType(), csarInfo);
1106 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1107 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1108 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1109 nodeNameValue.getKey(), isNested);
1112 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1113 String nodeResourceType, CsarInfo csarInfo) {
1114 // We need to create a Yaml from each node_types in order to create
1115 // resource from each node type using import normative flow.
1116 DumperOptions options = new DumperOptions();
1117 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1118 Yaml yaml = new Yaml(options);
1120 Map<String, Object> node = new HashMap<>();
1121 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1122 .getLeft(), nodeNameValue.getValue());
1123 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1125 return yaml.dumpAsMap(mapToConvert);
1128 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1129 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1130 return Either.left(true);
1133 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1134 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1135 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1136 String nodeName, boolean isNested) {
1138 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1139 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1140 Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1141 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1142 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1143 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1144 .left().on(this::failOnCertification);
1147 private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1148 throw new ComponentException(error);
1151 private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1152 String nodeName, User user) {
1153 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1155 // validate nodetype name prefix
1156 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1157 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1158 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1159 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1160 yamlName, resourceMetaData.getName(), nodeName);
1163 String actualName = this.getNodeTypeActualName(nodeName);
1164 String namePrefix = nodeName.replace(actualName, "");
1165 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1167 // if we import from csar, the node_type name can be
1168 // org.openecomp.resource.abstract.node_name - in this case we always
1170 if (resourceType.equals(Constants.ABSTRACT)) {
1171 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1174 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1175 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1176 ResourceTypeEnum.values());
1177 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1178 yamlName, resourceMetaData.getName(), nodeName);
1182 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1184 // Setting type from name
1185 String type = resourceType.toUpperCase();
1186 resourceMetaData.setResourceType(type);
1188 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1189 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1190 resourceMetaData.setContactId(user.getUserId());
1191 resourceMetaData.setVendorName(resourceVf.getVendorName());
1192 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1195 List<String> tags = new ArrayList<>();
1196 tags.add(resourceMetaData.getName());
1197 resourceMetaData.setTags(tags);
1200 CategoryDefinition category = new CategoryDefinition();
1201 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1202 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1203 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1204 category.addSubCategory(subCategory);
1205 List<CategoryDefinition> categories = new ArrayList<>();
1206 categories.add(category);
1207 resourceMetaData.setCategories(categories);
1209 return resourceMetaData;
1212 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1213 Map<String, NodeTypeInfo> nodesInfo) {
1214 Resource cvfc = new Resource();
1215 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1216 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1217 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1218 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1219 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1220 cvfc.setAbstract(true);
1221 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1222 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1223 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1224 cvfc.setContactId(csarInfo.getModifier().getUserId());
1225 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1226 cvfc.setVendorName(resourceVf.getVendorName());
1227 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1228 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1229 cvfc.setToscaResourceName(
1230 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1232 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1234 List<String> tags = new ArrayList<>();
1235 tags.add(cvfc.getName());
1238 CategoryDefinition category = new CategoryDefinition();
1239 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1240 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1241 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1242 category.addSubCategory(subCategory);
1243 List<CategoryDefinition> categories = new ArrayList<>();
1244 categories.add(category);
1245 cvfc.setCategories(categories);
1247 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1248 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1249 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1254 private String buildCvfcName(String resourceVfName, String nodeName) {
1255 String nameWithouNamespacePrefix = nodeName
1256 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1257 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1258 String resourceType = findTypes[0];
1259 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1260 return addCvfcSuffixToResourceName(resourceName);
1263 private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1264 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1265 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1266 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1267 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1268 boolean shouldLock, boolean inTransaction, String nodeName) {
1270 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1273 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1275 if (lockResult.isRight()) {
1276 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1277 throw new ComponentException(lockResult.right().value());
1279 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1282 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1283 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1284 resource = createResourceTransaction(resource,
1285 csarInfo.getModifier(), isNormative);
1286 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1287 log.trace("************* Going to add inputs from yaml {}", yamlName);
1288 if (resource.shouldGenerateInputs())
1289 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1291 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1292 resource = createInputsOnResource(resource, inputs);
1293 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1295 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1297 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1299 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1300 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1301 nodeTypesArtifactsToCreate, nodeName);
1302 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1303 // validate update vf module group names
1304 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1305 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1306 if (validateUpdateVfGroupNamesRes.isRight()) {
1307 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1308 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
1310 // add groups to resource
1311 Map<String, GroupDefinition> groups;
1312 log.trace("************* Going to add groups from yaml {}", yamlName);
1314 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1315 groups = validateUpdateVfGroupNamesRes.left().value();
1317 groups = parsedToscaYamlInfo.getGroups();
1320 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1322 if (createGroupsOnResource.isRight()) {
1323 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1324 throw new ComponentException(createGroupsOnResource.right().value());
1326 resource = createGroupsOnResource.left().value();
1327 log.trace("************* Finished to add groups from yaml {}", yamlName);
1329 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1331 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1332 nodeTypesArtifactsToCreate);
1334 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1335 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1336 if (createArtifactsEither.isRight()) {
1337 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1338 throw new ComponentException(createArtifactsEither.right().value());
1341 resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1343 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1344 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1345 ASDCKpiApi.countCreatedResourcesKPI();
1348 } catch(ComponentException|StorageException e) {
1349 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1352 if (!inTransaction) {
1356 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1357 NodeTypeEnum.Resource);
1362 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1363 if(!inTransaction) {
1364 titanDao.rollback();
1366 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1367 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1368 log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1372 private Resource getResourceWithGroups(String resourceId) {
1374 ComponentParametersView filter = new ComponentParametersView();
1375 filter.setIgnoreGroups(false);
1376 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1377 if (updatedResource.isRight()) {
1378 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1380 return updatedResource.left().value();
1383 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1384 Map<String, GroupDefinition> groups) {
1385 if (groups != null && !groups.isEmpty()) {
1386 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1388 handleGroupsProperties(resource, groups);
1389 fillGroupsFinalFields(groupsAsList);
1390 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1391 groupsAsList, true);
1392 if (createGroups.isRight()) {
1393 return Either.right(createGroups.right().value());
1396 return Either.left(resource);
1398 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1399 .getToscaElement(resource.getUniqueId());
1400 if (updatedResource.isRight()) {
1401 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1402 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1403 return Either.right(responseFormat);
1405 return Either.left(updatedResource.left().value());
1408 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1409 List<InputDefinition> inputs = resource.getInputs();
1410 if (MapUtils.isNotEmpty(groups)) {
1413 .filter(g -> isNotEmpty(g.getProperties()))
1414 .flatMap(g -> g.getProperties().stream())
1415 .forEach(p -> handleGetInputs(p, inputs));
1419 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1420 if (isNotEmpty(property.getGetInputValues())) {
1421 if (inputs == null || inputs.isEmpty()) {
1422 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1423 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1425 .map(GetInputValueDataDefinition::getInputName)
1426 .collect(toList()).toString());
1428 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1429 while (getInputValuesIter.hasNext()) {
1430 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1431 InputDefinition input = findInputByName(inputs, getInput);
1432 getInput.setInputId(input.getUniqueId());
1433 if (getInput.getGetInputIndex() != null) {
1434 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1435 input = findInputByName(inputs, getInputIndex);
1436 getInputIndex.setInputId(input.getUniqueId());
1437 getInputValuesIter.add(getInputIndex);
1443 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1444 Optional<InputDefinition> inputOpt = inputs.stream()
1445 .filter(p -> p.getName().equals(getInput.getInputName()))
1447 if (!inputOpt.isPresent()) {
1448 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1449 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1451 return inputOpt.get();
1454 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1455 groupsAsList.forEach(groupDefinition -> {
1456 groupDefinition.setInvariantName(groupDefinition.getName());
1457 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1461 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1462 if (isEmpty(groups)) {
1465 updateOrCreateGroups(resource, groups);
1467 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1468 .getToscaElement(resource.getUniqueId());
1469 if (updatedResource.isRight()) {
1470 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1471 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1473 return updatedResource.left().value();
1476 private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1477 List<GroupDefinition> groupsFromResource = resource.getGroups();
1478 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1479 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1480 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1481 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1482 if (isNotEmpty(groupsFromResource)) {
1483 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1484 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1486 groupsToCreate.addAll(groupsAsList);
1488 if (isNotEmpty(groupsToCreate)) {
1489 fillGroupsFinalFields(groupsToCreate);
1490 if (isNotEmpty(groupsFromResource)) {
1491 groupBusinessLogic.addGroups(resource,
1492 groupsToCreate, true)
1494 .on(this::throwComponentException);
1496 groupBusinessLogic.createGroups(resource,
1497 groupsToCreate, true)
1499 .on(this::throwComponentException);
1502 if (isNotEmpty(groupsToDelete)) {
1503 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1505 .on(this::throwComponentException);
1507 if (isNotEmpty(groupsToUpdate)) {
1508 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1510 .on(this::throwComponentException);
1514 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1515 for (GroupDefinition group : groupsFromResource) {
1516 Optional<GroupDefinition> op = groupsAsList.stream()
1517 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1518 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1519 groupsToDelete.add(group);
1524 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1525 for (GroupDefinition group : groupsAsList) {
1526 Optional<GroupDefinition> op = groupsFromResource.stream()
1527 .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1528 if (op.isPresent()) {
1529 GroupDefinition groupToUpdate = op.get();
1530 groupToUpdate.setMembers(group.getMembers());
1531 groupToUpdate.setCapabilities(group.getCapabilities());
1532 groupToUpdate.setProperties(group.getProperties());
1533 groupsToUpdate.add(groupToUpdate);
1535 groupsToCreate.add(group);
1540 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1541 List<InputDefinition> resourceProperties = resource.getInputs();
1542 if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1544 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1546 if (createInputs.isRight()) {
1547 throw new ComponentException(createInputs.right().value());
1552 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1553 .getToscaElement(resource.getUniqueId());
1554 if (updatedResource.isRight()) {
1555 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1556 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1558 return updatedResource.left().value();
1561 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1563 List<GroupDefinition> result = new ArrayList<>();
1564 List<ComponentInstance> componentInstances = component.getComponentInstances();
1566 if (groups != null) {
1567 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1568 if (validateCyclicGroupsDependencies.isRight()) {
1569 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1571 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1572 String groupName = entry.getKey();
1573 GroupDefinition groupDefinition = entry.getValue();
1574 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1575 updatedGroupDefinition.setMembers(null);
1576 Map<String, String> members = groupDefinition.getMembers();
1577 if (members != null) {
1578 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1580 result.add(updatedGroupDefinition);
1586 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1587 Set<String> compInstancesNames = members.keySet();
1589 if (CollectionUtils.isEmpty(componentInstances)) {
1590 String membersAstString = compInstancesNames.stream().collect(joining(","));
1591 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1592 membersAstString, groupName, component.getNormalizedName());
1593 throw new ComponentException(componentsUtils.getResponseFormat(
1594 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1595 component.getNormalizedName(), getComponentTypeForResponse(component)));
1597 // Find all component instances with the member names
1598 Map<String, String> memberNames = componentInstances.stream()
1599 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1600 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1601 Map<String, String> relevantInstances = memberNames.entrySet().stream()
1602 .filter(n -> compInstancesNames.contains(n.getKey()))
1603 .collect(toMap(Entry::getKey, Entry::getValue));
1605 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1607 List<String> foundMembers = new ArrayList<>();
1608 if (relevantInstances != null) {
1609 foundMembers = relevantInstances.keySet().stream().collect(toList());
1611 compInstancesNames.removeAll(foundMembers);
1612 String membersAstString = compInstancesNames.stream().collect(joining(","));
1613 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1614 groupName, component.getNormalizedName());
1615 throw new ComponentException(componentsUtils.getResponseFormat(
1616 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1617 component.getNormalizedName(), getComponentTypeForResponse(component)));
1619 updatedGroupDefinition.setMembers(relevantInstances);
1623 * This Method validates that there is no cyclic group dependencies. meaning
1624 * group A as member in group B which is member in group A
1629 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1631 Either<Boolean, ResponseFormat> result = Either.left(true);
1633 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1634 while (allGroupsItr.hasNext() && result.isLeft()) {
1635 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1636 // Fetches a group member A
1637 String groupAName = groupAEntry.getKey();
1638 // Finds all group members in group A
1639 Set<String> allGroupAMembersNames = new HashSet<>();
1640 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1641 // If A is a group member of itself found cyclic dependency
1642 if (allGroupAMembersNames.contains(groupAName)) {
1643 ResponseFormat responseFormat = componentsUtils
1644 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1645 result = Either.right(responseFormat);
1648 } catch (Exception e) {
1649 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1650 result = Either.right(responseFormat);
1651 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1657 * This Method fills recursively the set groupMembers with all the members
1658 * of the given group which are also of type group.
1662 * @param allGroupMembers
1665 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1666 Set<String> allGroupMembers) {
1668 // Found Cyclic dependency
1669 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1672 GroupDefinition groupDefinition = allGroups.get(groupName);
1673 // All Members Of Current Group Resource Instances & Other Groups
1674 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1675 // Filtered Members Of Current Group containing only members which
1677 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1678 // Keep Only Elements of type group and not Resource Instances
1679 filter(allGroups::containsKey).
1680 // Add Filtered Elements to main Set
1681 peek(allGroupMembers::add).
1685 // Recursively call the method for all the filtered group members
1686 for (String innerGroupName : currGroupFilteredMembers) {
1687 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1692 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1693 Set<String> allGroupMembers) {
1695 boolean stop = false;
1696 // In Case Not Group Stop
1697 if (!allGroups.containsKey(groupName)) {
1700 // In Case Group Has no members stop
1702 GroupDefinition groupDefinition = allGroups.get(groupName);
1703 stop = isEmpty(groupDefinition.getMembers());
1706 // In Case all group members already contained stop
1708 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1709 Set<String> membersOfTypeGroup = allMembers.stream().
1710 // Filter In Only Group members
1711 filter(allGroups::containsKey).
1714 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1719 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1720 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1721 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1722 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1723 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1726 log.debug("************* Going to create all nodes {}", yamlName);
1727 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1728 nodeTypesInfo, csarInfo, nodeName);
1729 log.debug("************* Finished to create all nodes {}", yamlName);
1730 log.debug("************* Going to create all resource instances {}", yamlName);
1731 resource = createResourceInstances(yamlName, resource,
1732 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1733 log.debug("************* Finished to create all resource instances {}", yamlName);
1734 log.debug("************* Going to create all relations {}", yamlName);
1735 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1736 log.debug("************* Finished to create all relations {}", yamlName);
1737 log.debug("************* Going to create positions {}", yamlName);
1738 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1739 log.debug("************* Finished to set positions {}", yamlName);
1743 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1744 List<ArtifactDefinition> artifactsToAdd) {
1745 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1747 artifactsToAdd.stream().forEach(a -> {
1748 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1749 vfcArtifacts.add(a);
1751 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1757 @SuppressWarnings("unchecked")
1758 private void handleNodeTypes(String yamlName, Resource resource,
1759 String topologyTemplateYaml, boolean needLock,
1760 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1761 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1762 CsarInfo csarInfo, String nodeName) {
1764 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1765 if (nodeTypeEntry.getValue().isNested()) {
1767 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1768 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1769 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1772 Map<String, Object> mappedToscaTemplate = null;
1773 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1774 && nodeTypesInfo.containsKey(nodeName)) {
1775 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1777 if (isEmpty(mappedToscaTemplate)) {
1778 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1780 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1781 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1782 } catch(ComponentException e){
1783 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
1784 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1785 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1787 } catch (StorageException e){
1788 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1789 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1792 // add the created node types to the cache although they are not in the
1794 csarInfo.getCreatedNodes().values().stream()
1795 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1798 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1799 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1800 boolean inTransaction) {
1802 if (csarInfo.getCsar() != null) {
1803 String vendorLicenseModelId = null;
1804 String vfLicenseModelId = null;
1806 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1807 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1808 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1809 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1810 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1811 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1813 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1814 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1820 // Specific Behavior for license artifacts
1821 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1822 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1823 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1824 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1825 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1827 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1828 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1829 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1830 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1831 artifactOperation, null, true, shouldLock, inTransaction);
1833 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1834 createdArtifacts, shouldLock, inTransaction, artifactOperation);
1835 if (eitherCreateResult.isRight()) {
1836 return Either.right(eitherCreateResult.right().value());
1838 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1839 .getToscaElement(resource.getUniqueId());
1840 if (eitherGerResource.isRight()) {
1841 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1842 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1844 return Either.right(responseFormat);
1847 resource = eitherGerResource.left().value();
1849 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1851 if (artifacsMetaCsarStatus.isLeft()) {
1852 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1853 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1854 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1855 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1856 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1858 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1861 if (createArtifactsFromCsar.isRight()) {
1862 log.debug("Couldn't create artifacts from artifacts.meta");
1863 return Either.right(createArtifactsFromCsar.right().value());
1866 return Either.left(createArtifactsFromCsar.left().value());
1869 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1873 return Either.left(resource);
1877 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1878 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1879 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1880 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1881 boolean inTransaction) {
1882 byte[] artifactFileBytes = null;
1884 if (csarInfo.getCsar().containsKey(artifactPath)) {
1885 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1887 Either<Boolean, ResponseFormat> result = Either.left(true);
1888 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1889 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1890 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1891 shouldLock, inTransaction);
1892 if (handleDelete.isRight()) {
1893 result = Either.right(handleDelete.right().value());
1899 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1900 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1901 ArtifactOperationEnum.CREATE);
1905 if (artifactFileBytes != null) {
1906 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1907 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1908 artifactFileBytes, null, isFromCsar);
1909 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1910 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1911 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1912 if (eitherNonMetaArtifacts.isRight()) {
1913 BeEcompErrorManager.getInstance()
1914 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1915 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1916 ErrorSeverity.WARNING);
1917 return Either.right(eitherNonMetaArtifacts.right().value());
1923 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1924 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
1928 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
1929 List<ArtifactDefinition> createdArtifacts,
1930 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1931 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
1932 && eitherNonMetaArtifacts.isLeft()) {
1933 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1934 if (eitherResult.isLeft()) {
1935 createdArtifacts.add(eitherResult.left().value());
1941 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
1942 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
1943 ArtifactOperationInfo artifactOperation) {
1945 Either<Resource, ResponseFormat> resStatus = null;
1946 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
1949 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
1950 if (artifactPathAndNameList.isRight()) {
1951 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
1952 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
1954 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
1956 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1957 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
1958 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
1960 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
1961 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
1963 if (findVfCsarArtifactsToHandleRes.isRight()) {
1964 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
1966 if (resStatus == null) {
1967 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
1970 if (resStatus == null && vfCsarArtifactsToHandle != null) {
1971 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
1973 if (resStatus == null) {
1974 resStatus = Either.left(resource);
1976 } catch (Exception e) {
1977 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1978 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
1980 CsarUtils.handleWarningMessages(collectedWarningMessages);
1985 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Resource, ResponseFormat> resStatus, EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
1986 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1989 Optional<ResponseFormat> optionalCreateInDBError =
1990 // Stream of artifacts to be created
1991 currArtifactOperationPair.getValue().stream()
1992 // create each artifact
1993 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
1994 e.getArtifactName(), e.getArtifactType().getType(),
1995 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
1996 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
1997 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1998 currArtifactOperationPair.getKey()),
1999 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2000 // filter in only error
2001 .filter(Either::isRight).
2002 // Convert the error from either to
2004 map(e -> e.right().value()).
2005 // Check if an error occurred
2007 // Error found on artifact Creation
2008 if (optionalCreateInDBError.isPresent()) {
2009 resStatus = Either.right(optionalCreateInDBError.get());
2016 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2017 List<NonMetaArtifactInfo> artifactPathAndNameList =
2018 // Stream of file paths contained in csar
2019 csarInfo.getCsar().entrySet().stream()
2020 // Filter in only VF artifact path location
2021 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2023 // Validate and add warnings
2024 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2025 collectedWarningMessages))
2026 // Filter in Non Warnings
2027 .filter(Either::isLeft)
2028 // Convert from Either to NonMetaArtifactInfo
2029 .map(e -> e.left().value())
2032 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2033 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2034 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2035 return Either.right(nonMetaArtifactInfo.getArtifactName());
2038 return Either.left(artifactPathAndNameList);
2041 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2042 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2044 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2045 // collect all Deployment and Informational artifacts of VF
2046 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2047 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2049 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2050 existingArtifacts.addAll(resource.getArtifacts().values());
2052 existingArtifacts = existingArtifacts.stream()
2053 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2054 // was created from HEAT.meta
2055 .filter(this::isNonMetaArtifact).collect(toList());
2057 List<String> artifactsToIgnore = new ArrayList<>();
2058 // collect IDs of Artifacts of VF which belongs to any group
2059 if (resource.getGroups() != null) {
2060 resource.getGroups().stream().forEach(g -> {
2061 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2062 artifactsToIgnore.addAll(g.getArtifacts());
2066 existingArtifacts = existingArtifacts.stream()
2067 // filter artifacts which belongs to any group
2068 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2069 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2072 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2073 boolean result = true;
2074 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2080 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2081 boolean result = true;
2082 if (artifact.getArtifactType() == null
2083 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2084 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2090 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2091 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2092 log.debug("#createResourceInstancesRelations - Going to create relations ");
2093 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2094 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) {
2095 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2096 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations","No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2097 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2099 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2100 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2101 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2102 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2103 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2104 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2105 Map<String, Resource> originCompMap = new HashMap<>();
2106 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2107 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2109 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2110 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2111 if (allDataTypes.isRight()) {
2112 TitanOperationStatus status = allDataTypes.right().value();
2113 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2114 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2115 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2116 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2119 Resource finalResource = resource;
2120 uploadResInstancesMap
2122 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2123 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2124 instArtifacts, instAttributes, originCompMap, instInputs, i));
2126 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2127 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2128 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2129 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2130 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2131 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2133 resource = getResourceAfterCreateRelations(resource);
2135 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2136 associateResourceInstances(yamlName, resource, relations);
2137 handleSubstitutionMappings(resource, uploadResInstancesMap);
2138 log.debug("************* in create relations, getResource start");
2139 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2140 log.debug("************* in create relations, getResource end");
2141 if (eitherGetResource.isRight()) {
2142 throw new ComponentException(componentsUtils.getResponseFormatByResource(
2143 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2145 return eitherGetResource.left().value();
2148 private Resource getResourceAfterCreateRelations(Resource resource) {
2149 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2150 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2151 .getToscaElement(resource.getUniqueId(), parametersView);
2153 if (eitherGetResource.isRight()) {
2154 throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2156 return eitherGetResource.left().value();
2159 private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2160 StorageOperationStatus addArtToInst;
2161 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2162 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2163 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2165 throw new ComponentException(componentsUtils
2166 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2170 private ComponentParametersView getComponentFilterAfterCreateRelations() {
2171 ComponentParametersView parametersView = new ComponentParametersView();
2172 parametersView.disableAll();
2173 parametersView.setIgnoreComponentInstances(false);
2174 parametersView.setIgnoreComponentInstancesProperties(false);
2175 parametersView.setIgnoreCapabilities(false);
2176 parametersView.setIgnoreRequirements(false);
2177 parametersView.setIgnoreGroups(false);
2178 return parametersView;
2181 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2182 StorageOperationStatus addArtToInst;
2183 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2184 resource.getUniqueId());
2185 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2186 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2188 throw new ComponentException(componentsUtils
2189 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2193 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2194 StorageOperationStatus addArtToInst;
2195 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2196 resource.getUniqueId());
2197 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2198 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2200 throw new ComponentException(componentsUtils
2201 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2205 private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2206 StorageOperationStatus addArtToInst;
2208 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2209 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2210 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2211 throw new ComponentException(componentsUtils
2212 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2216 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2217 StorageOperationStatus addArtToInst = toscaOperationFacade
2218 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2219 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2220 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2221 throw new ComponentException(componentsUtils
2222 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2226 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2227 if (MapUtils.isNotEmpty(instInputs)) {
2228 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2229 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2230 if (addInputToInst.isRight()) {
2231 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2232 addInputToInst.right().value());
2233 throw new ComponentException(componentsUtils.getResponseFormat(
2234 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2239 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2240 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2241 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2242 if (addPropToInst.isRight()) {
2243 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2244 addPropToInst.right().value());
2245 throw new ComponentException(componentsUtils.getResponseFormat(
2246 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2250 private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2251 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2252 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2253 if (getResourceRes.isRight()) {
2254 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2255 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2256 throw new ComponentException(responseFormat);
2258 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2259 uploadResInstancesMap);
2260 if (getResourceRes.isRight()) {
2261 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2262 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2263 throw new ComponentException(responseFormat);
2268 private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2269 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2270 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2271 ComponentInstance currentCompInstance = null;
2272 for (ComponentInstance compInstance : componentInstancesList) {
2274 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2275 currentCompInstance = compInstance;
2280 if (currentCompInstance == null) {
2281 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2282 resource.getUniqueId());
2283 BeEcompErrorManager.getInstance().logInternalDataError(
2284 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2285 resource.getUniqueId(), ErrorSeverity.ERROR);
2286 ResponseFormat responseFormat = componentsUtils
2287 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2288 throw new ComponentException(responseFormat);
2291 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2292 if (addRelationToRiRes.getStatus() != 200) {
2293 throw new ComponentException(addRelationToRiRes);
2298 private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList, Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<ComponentInstanceProperty>> instProperties, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap, Map<String, List<ComponentInstanceInput>> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2299 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2300 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2302 if (!currentCompInstanceOpt.isPresent()) {
2303 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2304 resource.getUniqueId());
2305 BeEcompErrorManager.getInstance().logInternalDataError(
2306 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2307 resource.getUniqueId(), ErrorSeverity.ERROR);
2308 ResponseFormat responseFormat = componentsUtils
2309 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2310 throw new ComponentException(responseFormat);
2312 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2313 String resourceInstanceId = currentCompInstance.getUniqueId();
2314 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2315 if (isNotEmpty(originResource.getRequirements())) {
2316 instRequirements.put(currentCompInstance, originResource.getRequirements());
2318 if (isNotEmpty(originResource.getCapabilities())) {
2319 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2320 currentCompInstance, originResource);
2322 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2323 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2325 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2326 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2328 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2329 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2331 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2332 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2333 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2334 if (addPropertiesValueToRiRes.getStatus() != 200) {
2335 throw new ComponentException(addPropertiesValueToRiRes);
2338 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2339 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2343 private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2344 Resource originResource;
2345 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2346 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2347 .getToscaFullElement(currentCompInstance.getComponentUid());
2348 if (getOriginResourceRes.isRight()) {
2349 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2350 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2351 getOriginResourceRes);
2352 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2353 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2354 throw new ComponentException(responseFormat);
2356 originResource = getOriginResourceRes.left().value();
2357 originCompMap.put(originResource.getUniqueId(), originResource);
2359 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2361 return originResource;
2364 private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2365 Map<String, List<CapabilityDefinition>> originCapabilities;
2366 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2367 originCapabilities = new HashMap<>();
2368 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2369 originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
2370 uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2371 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2373 originCapabilities = originResource.getCapabilities();
2375 instCapabilties.put(currentCompInstance, originCapabilities);
2378 private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2379 originCapabilities.values().stream()
2380 .flatMap(Collection::stream)
2381 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2382 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2385 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2386 for (UploadCapInfo capability : capabilities) {
2387 if (isNotEmpty(capability.getProperties())) {
2388 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2389 .collect(toMap(UploadInfo::getName, p -> p)));
2394 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2395 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2397 originCapabilities.put(type, list);
2400 private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2401 Map<String, DataTypeDefinition> allDataTypes) {
2402 properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2405 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2406 Map<String, DataTypeDefinition> allDataTypes) {
2407 String value = null;
2408 List<GetInputValueDataDefinition> getInputs = null;
2409 boolean isValidate = true;
2410 if (null != propertyInfo && propertyInfo.getValue() != null) {
2411 getInputs = propertyInfo.getGet_input();
2412 isValidate = getInputs == null || getInputs.isEmpty();
2414 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2416 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2417 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2420 property.setValue(value);
2421 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2424 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2425 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2426 Either<Resource, StorageOperationStatus> updateRes = null;
2427 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2428 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2429 StorageOperationStatus status = toscaOperationFacade
2430 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2431 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2433 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2434 resource.getUniqueId(), status);
2435 updateRes = Either.right(status);
2437 if (updateRes == null) {
2438 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2439 updatedInstCapabilities, updatedInstRequirements);
2440 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2441 resource.getUniqueId());
2442 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2444 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2445 resource.getUniqueId(), status);
2446 updateRes = Either.right(status);
2449 if (updateRes == null) {
2450 updateRes = Either.left(resource);
2455 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2456 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2457 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2458 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2460 componentInstances.stream().forEach(i -> {
2461 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2462 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2463 fillUpdatedInstRequirements(updatedInstRequirements, i,
2464 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2468 private void fillUpdatedInstRequirements(
2469 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2470 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2471 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2472 Set<String> updatedReqNames = new HashSet<>();
2473 if (isNotEmpty(requirementsNamesToUpdate)) {
2474 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2475 updatedRequirements.put(requirements.getKey(),
2476 requirements.getValue().stream()
2477 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2478 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2480 r.setParentName(r.getName());
2481 r.setName(requirementsNamesToUpdate.get(r.getName()));
2482 updatedReqNames.add(r.getName());
2484 }).collect(toList()));
2487 if (isNotEmpty(updatedRequirements)) {
2488 updatedInstRequirements.put(instance, updatedRequirements);
2492 private void fillUpdatedInstCapabilities(
2493 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2494 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2495 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2496 Set<String> updatedCapNames = new HashSet<>();
2497 if (isNotEmpty(capabilitiesNamesToUpdate)) {
2498 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2499 updatedCapabilities.put(requirements.getKey(),
2500 requirements.getValue().stream()
2501 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2502 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2504 c.setParentName(c.getName());
2505 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2506 updatedCapNames.add(c.getName());
2508 }).collect(toList()));
2511 if (isNotEmpty(updatedCapabilities)) {
2512 updatedInstCapabilties.put(instance, updatedCapabilities);
2516 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2517 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2518 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2520 ComponentInstance currentCompInstance = null;
2522 for (ComponentInstance compInstance : componentInstancesList) {
2524 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2525 currentCompInstance = compInstance;
2531 if (currentCompInstance == null) {
2532 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2533 resource.getUniqueId());
2534 BeEcompErrorManager.getInstance().logInternalDataError(
2535 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2536 resource.getUniqueId(), ErrorSeverity.ERROR);
2537 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2540 String resourceInstanceId = currentCompInstance.getUniqueId();
2542 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2544 if (regMap != null) {
2545 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2547 while (nodesRegValue.hasNext()) {
2548 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2550 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2551 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2552 log.debug("Going to create relation {}", uploadRegInfo.getName());
2553 String regName = uploadRegInfo.getName();
2554 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2555 regCapRelDef.setFromNode(resourceInstanceId);
2556 log.debug("try to find available requirement {} ", regName);
2557 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2558 yamlName, nodesInfoValue, currentCompInstance,
2559 uploadRegInfo.getCapabilityName());
2560 if (eitherReqStatus.isRight()) {
2561 log.debug("failed to find available requirement {} status is {}", regName,
2562 eitherReqStatus.right().value());
2563 return eitherReqStatus.right().value();
2566 RequirementDefinition validReq = eitherReqStatus.left().value();
2567 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2568 .getRelationships();
2569 if (reqAndRelationshipPairList == null) {
2570 reqAndRelationshipPairList = new ArrayList<>();
2572 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2573 reqAndRelationshipPair.setRequirement(regName);
2574 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2575 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2576 RelationshipImpl relationship = new RelationshipImpl();
2577 relationship.setType(validReq.getCapability());
2578 reqAndRelationshipPair.setRelationships(relationship);
2580 ComponentInstance currentCapCompInstance = null;
2581 for (ComponentInstance compInstance : componentInstancesList) {
2582 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2583 currentCapCompInstance = compInstance;
2588 if (currentCapCompInstance == null) {
2589 log.debug("The component instance with name {} not found on resource {} ",
2590 uploadRegInfo.getNode(), resource.getUniqueId());
2591 BeEcompErrorManager.getInstance().logInternalDataError(
2592 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2593 resource.getUniqueId(), ErrorSeverity.ERROR);
2594 return componentsUtils
2595 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2597 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2598 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2599 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2600 currentCapCompInstance, uploadRegInfo);
2601 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2602 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2603 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2604 if (aviableCapForRel == null) {
2605 log.debug("aviable capability was not found. req name is {} component instance is {}",
2606 validReq.getName(), currentCapCompInstance.getUniqueId());
2607 BeEcompErrorManager.getInstance().logInternalDataError(
2608 "aviable capability was not found. req name is " + validReq.getName()
2609 + " component instance is " + currentCapCompInstance.getUniqueId(),
2610 resource.getUniqueId(), ErrorSeverity.ERROR);
2611 return componentsUtils
2612 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2614 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2615 capReqRel.setRelation(reqAndRelationshipPair);
2616 reqAndRelationshipPairList.add(capReqRel);
2617 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2618 relations.add(regCapRelDef);
2621 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2622 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2624 return componentsUtils.getResponseFormat(ActionStatus.OK);
2627 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2628 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2629 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2630 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2631 if (MapUtils.isNotEmpty(propMap)) {
2632 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2633 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2635 if (CollectionUtils.isEmpty( originResource.getInputs())) {
2636 log.debug("failed to find properties ");
2637 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2639 originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2640 for (List<UploadPropInfo> propertyList : propMap.values()) {
2641 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2643 currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2644 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2648 private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2649 UploadPropInfo propertyInfo = propertyList.get(0);
2650 String propName = propertyInfo.getName();
2651 if (!currPropertiesMap.containsKey(propName)) {
2652 log.debug("failed to find property {} ", propName);
2653 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2656 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2657 ComponentInstanceInput property = null;
2659 String value = null;
2660 List<GetInputValueDataDefinition> getInputs = null;
2661 boolean isValidate = true;
2662 if (propertyInfo.getValue() != null) {
2663 getInputs = propertyInfo.getGet_input();
2664 isValidate = getInputs == null || getInputs.isEmpty();
2666 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2667 curPropertyDef.getType());
2669 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2670 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2673 String innerType = null;
2674 property = new ComponentInstanceInput(curPropertyDef, value, null);
2676 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2678 property.setValue(validPropertyVAlue);
2680 if (isNotEmpty(getInputs)) {
2681 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2682 for (GetInputValueDataDefinition getInput : getInputs) {
2683 List<InputDefinition> inputs = resource.getInputs();
2684 if (CollectionUtils.isEmpty(inputs)) {
2685 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2686 property, currentCompInstance.getUniqueId());
2687 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2690 Optional<InputDefinition> optional = inputs.stream()
2691 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2692 if (!optional.isPresent()) {
2693 log.debug("Failed to find input {} ", getInput.getInputName());
2694 // @@TODO error message
2695 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2697 InputDefinition input = optional.get();
2698 getInput.setInputId(input.getUniqueId());
2699 getInputValues.add(getInput);
2701 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2702 processGetInput(getInputValues, inputs, getInputIndex);
2704 property.setGetInputValues(getInputValues);
2706 instPropList.add(property);
2707 // delete overriden property
2708 currPropertiesMap.remove(property.getName());
2711 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2712 Optional<InputDefinition> optional;
2713 if (getInputIndex != null) {
2714 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2716 if (!optional.isPresent()) {
2717 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2718 // @@TODO error message
2719 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2721 InputDefinition inputIndex = optional.get();
2722 getInputIndex.setInputId(inputIndex.getUniqueId());
2723 getInputValues.add(getInputIndex);
2727 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2728 String propName = prop.getName();
2729 if (!currPropertiesMap.containsKey(propName)) {
2730 currPropertiesMap.put(propName, prop);
2734 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2735 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2736 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2738 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2739 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2741 List<PropertyDefinition> listFromMap = originResource.getProperties();
2742 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2743 log.debug("failed to find properties ");
2744 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2746 if (listFromMap == null || listFromMap.isEmpty()) {
2747 return componentsUtils.getResponseFormat(ActionStatus.OK);
2749 for (PropertyDefinition prop : listFromMap) {
2750 String propName = prop.getName();
2751 if (!currPropertiesMap.containsKey(propName)) {
2752 currPropertiesMap.put(propName, prop);
2755 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2756 if (propMap != null && propMap.size() > 0) {
2757 for (List<UploadPropInfo> propertyList : propMap.values()) {
2759 UploadPropInfo propertyInfo = propertyList.get(0);
2760 String propName = propertyInfo.getName();
2761 if (!currPropertiesMap.containsKey(propName)) {
2762 log.debug("failed to find property {} ", propName);
2763 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2766 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2767 ComponentInstanceProperty property = null;
2769 String value = null;
2770 List<GetInputValueDataDefinition> getInputs = null;
2771 boolean isValidate = true;
2772 if (propertyInfo.getValue() != null) {
2773 getInputs = propertyInfo.getGet_input();
2774 isValidate = getInputs == null || getInputs.isEmpty();
2776 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2777 curPropertyDef.getType());
2779 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2780 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2783 String innerType = null;
2784 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2786 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2787 property.setValue(validatePropValue);
2789 if (getInputs != null && !getInputs.isEmpty()) {
2790 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2791 for (GetInputValueDataDefinition getInput : getInputs) {
2792 List<InputDefinition> inputs = resource.getInputs();
2793 if (inputs == null || inputs.isEmpty()) {
2794 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2795 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2797 .map(GetInputValueDataDefinition::getInputName)
2798 .collect(toList()).toString());
2800 InputDefinition input = findInputByName(inputs, getInput);
2801 getInput.setInputId(input.getUniqueId());
2802 getInputValues.add(getInput);
2804 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2805 if (getInputIndex != null) {
2806 input = findInputByName(inputs, getInputIndex);
2807 getInputIndex.setInputId(input.getUniqueId());
2808 getInputValues.add(getInputIndex);
2813 property.setGetInputValues(getInputValues);
2815 instPropList.add(property);
2816 // delete overriden property
2817 currPropertiesMap.remove(property.getName());
2820 // add rest of properties
2821 if (!currPropertiesMap.isEmpty()) {
2822 for (PropertyDefinition value : currPropertiesMap.values()) {
2823 instPropList.add(new ComponentInstanceProperty(value));
2826 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2827 return componentsUtils.getResponseFormat(ActionStatus.OK);
2830 // US740820 Relate RIs according to capability name
2831 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2832 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2833 if (null == uploadReqInfo.getCapabilityName()
2834 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2838 return findAvailableCapability(validReq, currentCapCompInstance);
2840 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2843 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2844 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2845 CapabilityDefinition cap = null;
2846 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2847 if (!capMap.containsKey(validReq.getCapability())) {
2850 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2851 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2852 if (!capByName.isPresent()) {
2855 cap = capByName.get();
2857 if (isBoundedByOccurrences(cap)) {
2858 String leftOccurrences = cap.getLeftOccurrences();
2859 int left = Integer.parseInt(leftOccurrences);
2862 cap.setLeftOccurrences(String.valueOf(left));
2870 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2871 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2872 if (capMap.containsKey(validReq.getCapability())) {
2873 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2875 for (CapabilityDefinition cap : capList) {
2876 if (isBoundedByOccurrences(cap)) {
2877 String leftOccurrences = cap.getLeftOccurrences() != null ?
2878 cap.getLeftOccurrences() : cap.getMaxOccurrences();
2879 int left = Integer.parseInt(leftOccurrences);
2882 cap.setLeftOccurrences(String.valueOf(left));
2893 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2894 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2897 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2898 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2900 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2901 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2902 RequirementDefinition validRegDef = null;
2904 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2905 for (RequirementDefinition reqDef : entry.getValue()) {
2906 if (reqDef.getName().equals(regName)) {
2907 if (reqDef.getMaxOccurrences() != null
2908 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2909 String leftOccurrences = reqDef.getLeftOccurrences();
2910 if (leftOccurrences == null) {
2911 leftOccurrences = reqDef.getMaxOccurrences();
2913 int left = Integer.parseInt(leftOccurrences);
2916 reqDef.setLeftOccurrences(String.valueOf(left));
2917 validRegDef = reqDef;
2923 validRegDef = reqDef;
2929 if (validRegDef != null) {
2934 for (RequirementDefinition reqDef : list) {
2935 if (reqDef.getName().equals(regName)) {
2936 if (reqDef.getMaxOccurrences() != null
2937 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2938 String leftOccurrences = reqDef.getLeftOccurrences();
2939 if (leftOccurrences == null) {
2940 leftOccurrences = reqDef.getMaxOccurrences();
2942 int left = Integer.parseInt(leftOccurrences);
2945 reqDef.setLeftOccurrences(String.valueOf(left));
2946 validRegDef = reqDef;
2952 validRegDef = reqDef;
2958 if (validRegDef == null) {
2959 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2960 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2961 return Either.right(responseFormat);
2963 return Either.left(validRegDef);
2966 private Resource createResourceInstances(String yamlName, Resource resource,
2967 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2968 Map<String, Resource> nodeNamespaceMap) {
2970 Either<Resource, ResponseFormat> eitherResource = null;
2971 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2972 if (isEmpty(uploadResInstancesMap)) {
2973 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2974 throw new ComponentException(responseFormat);
2976 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2977 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2978 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2980 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2981 uploadResInstancesMap
2983 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2985 if (isNotEmpty(resourcesInstancesMap)) {
2986 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
2987 resourcesInstancesMap, false);
2988 if (status != null && status != StorageOperationStatus.OK) {
2989 log.debug("Failed to add component instances to container component {}", resource.getName());
2990 ResponseFormat responseFormat = componentsUtils
2991 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
2992 eitherResource = Either.right(responseFormat);
2993 throw new ComponentException(eitherResource.right().value());
2996 log.debug("*************Going to get resource {}", resource.getUniqueId());
2997 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2998 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
2999 log.debug("*************finished to get resource {}", resource.getUniqueId());
3000 if (eitherGetResource.isRight()) {
3001 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3002 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3003 throw new ComponentException(responseFormat);
3005 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) {
3006 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3007 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3008 "Error when create resource instance from csar. ComponentInstances list empty");
3009 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3011 return eitherGetResource.left().value();
3014 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3015 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3016 Either<Resource, ResponseFormat> eitherResource;
3017 log.debug("*************Going to create resource instances {}", yamlName);
3018 // updating type if the type is node type name - we need to take the
3020 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3021 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3022 uploadComponentInstanceInfo
3023 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3025 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3026 existingnodeTypeMap);
3028 ComponentInstance componentInstance = new ComponentInstance();
3029 componentInstance.setComponentUid(refResource.getUniqueId());
3031 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3032 if(directives != null && !directives.isEmpty()) {
3033 componentInstance.setDirectives(new ArrayList<>(directives));
3035 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3036 if (uploadNodeFilterInfo != null){
3037 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3038 componentInstance.getUniqueId()));
3041 ComponentTypeEnum containerComponentType = resource.getComponentType();
3042 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3043 if (containerNodeType.equals(NodeTypeEnum.Resource)
3044 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3045 && isNotEmpty(refResource.getCapabilities())) {
3046 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3047 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3048 refResource.getUniqueId(), refResource.getCapabilities(),
3049 uploadComponentInstanceInfo.getCapabilities());
3050 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3052 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3054 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3055 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3056 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3057 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3058 throw new ComponentException(responseFormat);
3060 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3061 componentInstance.setName(uploadComponentInstanceInfo.getName());
3062 componentInstance.setIcon(origResource.getIcon());
3063 resourcesInstancesMap.put(componentInstance, origResource);
3066 private ComponentParametersView getComponentWithInstancesFilter() {
3067 ComponentParametersView parametersView = new ComponentParametersView();
3068 parametersView.disableAll();
3069 parametersView.setIgnoreComponentInstances(false);
3070 parametersView.setIgnoreInputs(false);
3071 // inputs are read when creating
3072 // property values on instances
3073 parametersView.setIgnoreUsers(false);
3074 return parametersView;
3077 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3078 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3079 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3080 if (originCapabilities.containsKey(currEntry.getKey())) {
3081 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3084 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3085 capabilities.getValue().stream().forEach(cap -> {
3086 if (uploadedCapabilities.containsKey(cap.getName())) {
3087 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3088 c.setName(cap.getName());
3089 c.setType(cap.getType());
3097 private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3098 Map<String, Resource> nodeNamespaceMap) {
3100 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3101 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3102 Resource refResource;
3103 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3104 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3106 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3107 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3108 if (findResourceEither.isRight()) {
3110 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3111 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3112 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3113 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3114 throw new ComponentException(responseFormat);
3116 refResource = findResourceEither.left().value();
3117 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3119 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3120 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3122 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3123 refResource.getName(), componentState);
3124 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3125 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3126 throw new ComponentException(responseFormat);
3129 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3130 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3131 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3132 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3133 throw new ComponentException(responseFormat);
3139 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3140 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3141 boolean forceCertificationAllowed) {
3143 Either<Resource, ResponseFormat> result = null;
3145 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3146 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3147 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3148 if (result.isRight()) {
3151 resource = result.left().value();
3153 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3154 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3155 resource, user, false, inTransaction, needLock);
3156 result = eitherPopulated.isLeft() ? Either.left(resource)
3157 : Either.right(eitherPopulated.right().value());
3160 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3161 } catch (Exception e) {
3162 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3163 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3165 if (result == null || result.isRight()) {
3166 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3167 if (!inTransaction) {
3168 titanDao.rollback();
3170 } else if (!inTransaction) {
3176 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3177 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3178 return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3179 lifecycleChangeInfo, inTransaction, needLock);
3182 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3183 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3184 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3188 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3189 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3190 CsarInfo csarInfo, String nodeName, boolean isNested) {
3192 ImmutablePair<Resource, ActionStatus> result = null;
3193 // check if resource already exists (search by tosca name = type)
3194 boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3195 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3196 .getLatestByToscaResourceName(resource.getToscaResourceName());
3198 if (latestByToscaName.isLeft()) {
3199 Resource foundResource = latestByToscaName.left().value();
3200 // we don't allow updating names of top level types
3201 if (!isNestedResource &&
3202 !StringUtils.equals(resource.getName(), foundResource.getName())) {
3203 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3204 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3205 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3206 foundResource.getName(), resource.getToscaResourceName());
3207 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3208 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3209 throwComponentException(responseFormat);
3211 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3212 } else if (isNotFound(latestByToscaName)) {
3213 if (isNestedResource) {
3214 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3216 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3219 StorageOperationStatus status = latestByToscaName.right().value();
3220 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3221 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3222 componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3223 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3224 throwComponentException(responseFormat);
3229 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3230 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3233 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3234 Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3235 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3236 if (latestByToscaName.isLeft()) {
3237 Resource nestedResource = (Resource) latestByToscaName.left().value();
3238 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3239 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3240 ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3241 if (eitherValidation.isRight()) {
3242 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3244 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3246 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3250 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3251 return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3254 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3255 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3256 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3257 validateResourceBeforeCreate(resource, user,
3258 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3259 Resource createdResource = createResourceByDao(resource, user,
3260 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3261 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3262 ActionStatus.CREATED);
3263 ASDCKpiApi.countImportResourcesKPI();
3264 return resourcePair;
3267 public boolean isResourceExist(String resourceName) {
3268 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3269 return latestByName.isLeft();
3272 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3273 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3275 String lockedResourceId = oldResource.getUniqueId();
3276 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3277 oldResource.getVersion(), oldResource.getLifecycleState());
3278 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3280 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3281 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3282 mergeOldResourceMetadataWithNew(oldResource, newResource);
3284 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3285 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3286 // contact info normalization
3287 newResource.setContactId(newResource.getContactId().toLowerCase());
3288 // non-updatable fields
3289 newResource.setCreatorUserId(user.getUserId());
3290 newResource.setCreatorFullName(user.getFullName());
3291 newResource.setLastUpdaterUserId(user.getUserId());
3292 newResource.setLastUpdaterFullName(user.getFullName());
3293 newResource.setUniqueId(oldResource.getUniqueId());
3294 newResource.setVersion(oldResource.getVersion());
3295 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3296 newResource.setLifecycleState(oldResource.getLifecycleState());
3297 newResource.setUUID(oldResource.getUUID());
3298 newResource.setNormalizedName(oldResource.getNormalizedName());
3299 newResource.setSystemName(oldResource.getSystemName());
3300 if (oldResource.getCsarUUID() != null) {
3301 newResource.setCsarUUID(oldResource.getCsarUUID());
3303 if (oldResource.getImportedToscaChecksum() != null) {
3304 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3306 newResource.setAbstract(oldResource.isAbstract());
3308 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3309 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3311 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3312 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3314 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3315 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3318 // created without tosca artifacts - add the placeholders
3319 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3320 setToscaArtifactsPlaceHolders(newResource, user);
3323 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3324 newResource.setInterfaces(oldResource.getInterfaces());
3327 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3328 .overrideComponent(newResource, oldResource);
3330 if (overrideResource.isRight()) {
3331 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3332 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3333 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3335 throwComponentException(responseFormat);
3338 log.debug("Resource updated successfully!!!");
3339 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3340 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3341 ResourceVersionInfo.newBuilder()
3342 .state(oldResource.getLifecycleState()
3344 .version(oldResource.getVersion())
3347 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3349 return resourcePair;
3351 if (resourcePair == null) {
3352 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3353 titanDao.rollback();
3354 } else if (!inTransaction) {
3358 log.debug("unlock resource {}", lockedResourceId);
3359 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3366 * Merge old resource with new. Keep old category and vendor name without
3369 * @param oldResource
3370 * @param newResource
3372 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3374 // keep old category and vendor name without change
3375 // merge the rest of the resource metadata
3376 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3377 newResource.setTags(oldResource.getTags());
3380 if (newResource.getDescription() == null) {
3381 newResource.setDescription(oldResource.getDescription());
3384 if (newResource.getVendorRelease() == null) {
3385 newResource.setVendorRelease(oldResource.getVendorRelease());
3388 if (newResource.getResourceVendorModelNumber() == null) {
3389 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3392 if (newResource.getContactId() == null) {
3393 newResource.setContactId(oldResource.getContactId());
3396 newResource.setCategories(oldResource.getCategories());
3397 if (newResource.getVendorName() == null) {
3398 newResource.setVendorName(oldResource.getVendorName());
3402 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3403 boolean inTransaction, boolean needLock) {
3405 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3407 return lifecycleBusinessLogic.changeState(
3408 oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3409 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3411 .on(response -> failOnChangeState(response, user, oldResource, newResource));
3416 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3417 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3418 response.getFormattedMessage());
3419 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3420 ResourceVersionInfo.newBuilder()
3421 .state(oldResource.getLifecycleState().name())
3422 .version(oldResource.getVersion())
3424 throw new ComponentException(response);
3427 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3429 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3430 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3431 validateLifecycleTypesCreate(user, resource, actionEnum);
3432 validateResourceType(user, resource, actionEnum);
3433 resource.setCreatorUserId(user.getUserId());
3434 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3435 resource.setContactId(resource.getContactId().toLowerCase());
3436 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3437 String resourceSystemName;
3438 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3439 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3441 resourceSystemName = resource.getSystemName();
3443 resource.setToscaResourceName(CommonBeUtils
3444 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3447 // Generate invariant UUID - must be here and not in operation since it
3448 // should stay constant during clone
3450 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3451 resource.setInvariantUUID(invariantUUID);
3456 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3457 AuditingActionEnum actionEnum) {
3458 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3459 if (resource.getResourceType() == null) {
3460 log.debug("Invalid resource type for resource");
3461 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3462 eitherResult = Either.right(errorResponse);
3463 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3465 return eitherResult;
3468 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3469 AuditingActionEnum actionEnum) {
3470 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3471 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3472 log.debug("validate interface lifecycle Types Exist");
3473 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3474 while (intItr.hasNext() && eitherResult.isLeft()) {
3475 InterfaceDefinition interfaceDefinition = intItr.next();
3476 String intType = interfaceDefinition.getUniqueId();
3477 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3478 .getInterface(intType);
3479 if (eitherCapTypeFound.isRight()) {
3480 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3481 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3482 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3483 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3484 intType, resource.getName());
3485 BeEcompErrorManager.getInstance()
3486 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3487 log.debug("request to data model failed with error: {}",
3488 eitherCapTypeFound.right().value().name());
3491 ResponseFormat errorResponse = componentsUtils
3492 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3493 eitherResult = Either.right(errorResponse);
3494 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3499 return eitherResult;
3502 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3503 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3504 boolean inTransaction) {
3506 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3507 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3508 log.debug("validate capability Types Exist - capabilities section");
3510 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3512 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3513 eitherResult, typeEntry, inTransaction);
3514 if (eitherResult.isRight()) {
3515 return Either.right(eitherResult.right().value());
3520 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3521 log.debug("validate capability Types Exist - requirements section");
3522 for (String type : resource.getRequirements().keySet()) {
3523 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3524 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3525 if (eitherResult.isRight()) {
3526 return Either.right(eitherResult.right().value());
3531 return eitherResult;
3534 // @param typeObject- the object to which the validation is done
3535 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3536 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3537 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3538 boolean inTransaction) {
3539 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3540 .getCapabilityType(type, inTransaction);
3541 if (eitherCapTypeFound.isRight()) {
3542 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3543 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3544 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3545 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3546 resource.getName());
3547 BeEcompErrorManager.getInstance()
3548 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3550 log.debug("Trying to get capability type {} failed with error: {}", type,
3551 eitherCapTypeFound.right().value().name());
3552 ResponseFormat errorResponse = null;
3554 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3556 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3559 eitherResult = Either.right(errorResponse);
3560 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3562 return eitherResult;
3565 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3566 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3567 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3568 boolean inTransaction) {
3569 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3570 .getCapabilityType(typeEntry.getKey(), inTransaction);
3571 if (eitherCapTypeFound.isRight()) {
3572 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3573 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3574 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3575 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3576 typeEntry.getKey(), resource.getName());
3577 BeEcompErrorManager.getInstance()
3578 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3580 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3581 eitherCapTypeFound.right().value().name());
3582 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3583 typeEntry.getKey());
3584 eitherResult = Either.right(errorResponse);
3585 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3587 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3588 if (capabilityTypeDefinition.getProperties() != null) {
3589 for (CapabilityDefinition capDef : typeEntry.getValue()) {
3590 List<ComponentInstanceProperty> properties = capDef.getProperties();
3591 if (properties == null || properties.isEmpty()) {
3592 properties = new ArrayList<>();
3593 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3594 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3595 properties.add(newProp);
3598 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3599 PropertyDefinition porpFromDef = prop.getValue();
3600 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3601 for (ComponentInstanceProperty cip : properties) {
3602 if (!cip.getName().equals(porpFromDef.getName())) {
3603 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3604 propsToAdd.add(newProp);
3607 if (!propsToAdd.isEmpty()) {
3608 properties.addAll(propsToAdd);
3612 capDef.setProperties(properties);
3615 return eitherResult;
3618 public Resource createResourceByDao(Resource resource, User user,
3619 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3622 // lock new resource name in order to avoid creation resource with same
3624 Resource createdResource = null;
3625 if (!inTransaction) {
3626 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3628 if (lockResult.isRight()) {
3629 ResponseFormat responseFormat = lockResult.right().value();
3630 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3631 throw new ComponentException(responseFormat);
3634 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3637 if (resource.deriveFromGeneric()) {
3638 handleResourceGenericType(resource);
3640 createdResource = createResourceTransaction(resource, user, isNormative
3642 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3643 createdResource, actionEnum);
3644 ASDCKpiApi.countCreatedResourcesKPI();
3645 } catch(ComponentException e) {
3646 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3647 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3649 } catch (StorageException e){
3650 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3651 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3655 if (!inTransaction) {
3656 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3657 NodeTypeEnum.Resource);
3660 return createdResource;
3663 private Resource createResourceTransaction(Resource resource, User user,
3664 boolean isNormative) {
3665 // validate resource name uniqueness
3666 log.debug("validate resource name");
3667 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3668 resource.getName(), resource.getResourceType(), resource.getComponentType());
3669 if (eitherValidation.isRight()) {
3670 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3671 eitherValidation.right().value());
3672 ResponseFormat errorResponse = componentsUtils
3673 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3674 throw new ComponentException(errorResponse);
3676 if (eitherValidation.left().value()) {
3677 log.debug("resource with name: {}, already exists", resource.getName());
3678 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3679 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3680 throw new ComponentException(errorResponse);
3683 log.debug("send resource {} to dao for create", resource.getName());
3685 createArtifactsPlaceHolderData(resource, user);
3688 log.debug("enrich resource with creator, version and state");
3689 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3690 resource.setVersion(INITIAL_VERSION);
3691 resource.setHighestVersion(true);
3692 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3693 resource.setAbstract(false);
3696 return toscaOperationFacade.createToscaComponent(resource)
3698 .on(r->throwComponentExceptionByResource(r, resource));
3701 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3702 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3703 componentsUtils.convertFromStorageResponse(status), resource);
3704 throw new ComponentException(responseFormat);
3707 private void createArtifactsPlaceHolderData(Resource resource, User user) {
3708 // create mandatory artifacts
3710 // TODO it must be removed after that artifact uniqueId creation will be
3711 // moved to ArtifactOperation
3713 setInformationalArtifactsPlaceHolder(resource, user);
3714 setDeploymentArtifactsPlaceHolder(resource, user);
3715 setToscaArtifactsPlaceHolders(resource, user);
3718 @SuppressWarnings("unchecked")
3720 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3721 Resource resource = (Resource) component;
3722 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3723 if (artifactMap == null) {
3724 artifactMap = new HashMap<>();
3726 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3727 .getConfiguration().getDeploymentResourceArtifacts();
3728 if (deploymentResourceArtifacts != null) {
3729 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3730 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3732 resource.setDeploymentArtifacts(artifactMap);
3735 private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3736 boolean shouldCreateArtifact = true;
3737 Map<String, Object> artifactDetails = (Map<String, Object>) v;
3738 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3739 if (object != null) {
3740 List<String> artifactTypes = (List<String>) object;
3741 if (!artifactTypes.contains(resource.getResourceType().name())) {
3742 shouldCreateArtifact = false;
3746 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3749 if (shouldCreateArtifact) {
3750 if (artifactsBusinessLogic != null) {
3751 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3752 resource.getUniqueId(), k, (Map<String, Object>) v,
3753 user, ArtifactGroupTypeEnum.DEPLOYMENT);
3754 if (artifactDefinition != null
3755 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3756 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3762 @SuppressWarnings("unchecked")
3763 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3764 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3765 if (artifactMap == null) {
3766 artifactMap = new HashMap<>();
3768 String resourceUniqueId = resource.getUniqueId();
3769 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3770 .getExcludeResourceCategory();
3771 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3772 .getExcludeResourceType();
3773 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3774 .getConfiguration().getInformationalResourceArtifacts();
3775 List<CategoryDefinition> categories = resource.getCategories();
3776 boolean isCreateArtifact = true;
3777 if (exludeResourceCategory != null) {
3778 String category = categories.get(0).getName();
3779 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3781 if (isCreateArtifact && exludeResourceType != null) {
3782 String resourceType = resource.getResourceType().name();
3783 isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3785 if (informationalResourceArtifacts != null && isCreateArtifact) {
3786 Set<String> keys = informationalResourceArtifacts.keySet();
3787 for (String informationalResourceArtifactName : keys) {
3788 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3789 .get(informationalResourceArtifactName);
3790 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3791 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3792 ArtifactGroupTypeEnum.INFORMATIONAL);
3793 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3797 resource.setArtifacts(artifactMap);
3807 public ResponseFormat deleteResource(String resourceId, User user) {
3808 ResponseFormat responseFormat;
3809 validateUserExists(user, DELETE_RESOURCE, false);
3811 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3812 if (resourceStatus.isRight()) {
3813 log.debug("failed to get resource {}", resourceId);
3814 return componentsUtils
3815 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3818 Resource resource = resourceStatus.left().value();
3820 StorageOperationStatus result = StorageOperationStatus.OK;
3821 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3822 if (lockResult.isRight()) {
3823 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3828 result = markComponentToDelete(resource);
3829 if (result.equals(StorageOperationStatus.OK)) {
3830 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3832 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3833 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3835 return responseFormat;
3838 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3839 titanDao.rollback();
3843 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3848 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3849 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3850 validateUserExists(user, DELETE_RESOURCE, false);
3851 Resource resource = null;
3852 StorageOperationStatus result = StorageOperationStatus.OK;
3855 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3856 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3857 if (resourceStatus.isRight()) {
3858 log.debug("failed to get resource {} version {}", resourceName, version);
3859 return componentsUtils.getResponseFormatByResource(
3860 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3863 resource = resourceStatus.left().value();
3866 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3867 titanDao.rollback();
3868 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3869 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3874 if (resource != null) {
3875 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3877 if (lockResult.isRight()) {
3878 result = StorageOperationStatus.GENERAL_ERROR;
3879 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3882 result = markComponentToDelete(resource);
3883 if (!result.equals(StorageOperationStatus.OK)) {
3884 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3885 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3886 return responseFormat;
3890 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3891 titanDao.rollback();
3895 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3898 return responseFormat;
3901 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3904 validateUserExists(user, CREATE_RESOURCE, false);
3907 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3908 if (storageStatus.isRight()) {
3909 log.debug("failed to get resource by id {}", resourceId);
3910 return Either.right(componentsUtils.getResponseFormatByResource(
3911 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3913 if (!(storageStatus.left().value() instanceof Resource)) {
3914 return Either.right(componentsUtils.getResponseFormatByResource(
3915 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3917 return Either.left(storageStatus.left().value());
3921 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3924 validateUserExists(userId, "get Resource By Name And Version", false);
3926 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
3927 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
3928 if (getResource.isRight()) {
3929 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
3930 return Either.right(componentsUtils.getResponseFormatByResource(
3931 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
3933 return Either.left(getResource.left().value());
3937 * updateResourceMetadata
3939 * @param user - modifier data (userId)
3940 * @param inTransaction TODO
3941 * @param resourceIdToUpdate - the resource identifier
3942 * @param newResource
3943 * @return Either<Resource , responseFormat>
3945 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
3946 Resource currentResource, User user, boolean inTransaction) {
3948 validateUserExists(user.getUserId(), "update Resource Metadata", false);
3950 log.debug("Get resource with id {}", resourceIdToUpdate);
3951 boolean needToUnlock = false;
3952 boolean rollbackNeeded = true;
3955 if (currentResource == null) {
3956 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
3957 .getToscaElement(resourceIdToUpdate);
3958 if (storageStatus.isRight()) {
3959 throw new ComponentException(componentsUtils.getResponseFormatByResource(
3960 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
3963 currentResource = storageStatus.left().value();
3965 // verify that resource is checked-out and the user is the last
3967 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
3968 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3972 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
3973 NodeTypeEnum.Resource);
3974 if (!lockResult.equals(StorageOperationStatus.OK)) {
3975 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
3976 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
3977 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
3978 ResponseFormat responseFormat = componentsUtils
3979 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
3980 throw new ComponentException(responseFormat);
3983 needToUnlock = true;
3985 // critical section starts here
3986 // convert json to object
3988 // Update and updated resource must have a non-empty "derivedFrom"
3990 // This code is not called from import resources, because of root
3991 // VF "derivedFrom" should be null (or ignored)
3992 if (ModelConverter.isAtomicComponent(currentResource)) {
3993 validateDerivedFromNotEmpty(null, newResource, null);
3994 validateDerivedFromNotEmpty(null, currentResource, null);
3996 newResource.setDerivedFrom(null);
3999 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4000 user, currentResource, false, true);
4001 if (dataModelResponse.isRight()) {
4002 log.debug("failed to update resource metadata!!!");
4003 rollbackNeeded = true;
4004 throw new ComponentException(dataModelResponse.right().value());
4007 log.debug("Resource metadata updated successfully!!!");
4008 rollbackNeeded = false;
4009 return dataModelResponse.left().value();
4011 } catch (ComponentException|StorageException e){
4012 rollback(inTransaction, newResource, null, null);
4016 if (!inTransaction) {
4020 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4025 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4026 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4027 updateVfModuleGroupsNames(currentResource, newResource);
4028 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4029 // Setting last updater and uniqueId
4030 newResource.setContactId(newResource.getContactId().toLowerCase());
4031 newResource.setLastUpdaterUserId(user.getUserId());
4032 newResource.setUniqueId(resourceIdToUpdate);
4033 // Cannot set highest version through UI
4034 newResource.setHighestVersion(currentResource.isHighestVersion());
4035 newResource.setCreationDate(currentResource.getCreationDate());
4037 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4038 newResource, user.getUserId(), inTransaction);
4040 if (processUpdateOfDerivedFrom.isRight()) {
4041 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4042 return Either.right(processUpdateOfDerivedFrom.right().value());
4045 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4046 if (isNotEmpty(newResource.getGroups())) {
4047 for (GroupDefinition group : newResource.getGroups()) {
4048 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4049 groupBusinessLogic.validateAndUpdateGroupMetadata(
4050 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4051 user, newResource.getComponentType(), group, true, false);
4055 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4056 .updateToscaElement(newResource);
4058 if (dataModelResponse.isRight()) {
4059 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4060 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4061 return Either.right(responseFormat);
4062 } else if (dataModelResponse.left().value() == null) {
4063 log.debug("No response from updateResource");
4064 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4066 return Either.left(dataModelResponse.left().value());
4070 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4071 if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4072 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4074 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4076 newResource.setGroups(updatedGroups);
4080 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4081 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4082 if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4083 String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4084 String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4085 updatedGroup.setName(newGroupName);
4087 return updatedGroup;
4090 * validateResourceFieldsBeforeCreate
4092 * @param user - modifier data (userId)
4093 * @return Either<Boolean , ErrorResponse>
4095 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4096 AuditingActionEnum actionEnum, boolean inTransaction) {
4097 validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4098 // validate category
4099 log.debug("validate category");
4100 validateCategory(user, resource, actionEnum, inTransaction);
4101 // validate vendor name & release & model number
4102 log.debug("validate vendor name");
4103 validateVendorName(user, resource, actionEnum);
4104 log.debug("validate vendor release");
4105 validateVendorReleaseName(user, resource, actionEnum);
4106 log.debug("validate resource vendor model number");
4107 validateResourceVendorModelNumber(user, resource, actionEnum);
4109 log.debug("validate cost");
4110 validateCost(resource);
4111 // validate licenseType
4112 log.debug("validate licenseType");
4113 validateLicenseType(user, resource, actionEnum);
4114 // validate template (derived from)
4115 log.debug("validate derived from");
4116 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4117 resource.setDerivedFrom(null);
4119 validateDerivedFromExist(user, resource, actionEnum);
4120 // warn about non-updatable fields
4121 checkComponentFieldsForOverrideAttempt(resource);
4122 String currentCreatorFullName = resource.getCreatorFullName();
4123 if (currentCreatorFullName != null) {
4124 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4127 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4128 if (currentLastUpdaterFullName != null) {
4129 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4132 Long currentLastUpdateDate = resource.getLastUpdateDate();
4133 if (currentLastUpdateDate != null) {
4134 log.debug("Resource last update date is automatically set and cannot be updated");
4137 Boolean currentAbstract = resource.isAbstract();
4138 if (currentAbstract != null) {
4139 log.debug("Resource abstract is automatically set and cannot be updated");
4142 return Either.left(true);
4146 * validateResourceFieldsBeforeUpdate
4148 * @param currentResource - Resource object to validate
4151 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4152 boolean inTransaction, boolean isNested) {
4153 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4154 warnNonEditableFields(currentResource, updateInfoResource);
4157 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4158 String currentResourceVersion = currentResource.getVersion();
4159 String updatedResourceVersion = updateInfoResource.getVersion();
4161 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4162 log.debug("Resource version is automatically set and cannot be updated");
4165 String currentCreatorUserId = currentResource.getCreatorUserId();
4166 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4168 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4169 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4172 String currentCreatorFullName = currentResource.getCreatorFullName();
4173 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4175 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4176 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4179 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4180 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4182 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4183 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4186 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4187 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4189 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4190 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4193 Long currentCreationDate = currentResource.getCreationDate();
4194 Long updatedCreationDate = updateInfoResource.getCreationDate();
4196 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4197 log.debug("Resource Creation date is automatically set and cannot be updated");
4200 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4201 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4203 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4204 log.debug("Resource last update date is automatically set and cannot be updated");
4207 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4208 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4210 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4211 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4214 Boolean currentAbstract = currentResource.isAbstract();
4215 Boolean updatedAbstract = updateInfoResource.isAbstract();
4217 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4218 log.debug("Resource abstract is automatically set and cannot be updated");
4221 Boolean currentHighestVersion = currentResource.isHighestVersion();
4222 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4224 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4225 log.debug("Resource highest version is automatically set and cannot be updated");
4228 String currentUuid = currentResource.getUUID();
4229 String updatedUuid = updateInfoResource.getUUID();
4231 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4232 log.debug("Resource UUID is automatically set and cannot be updated");
4235 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4236 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4238 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4239 log.debug("Resource Type cannot be updated");
4242 updateInfoResource.setResourceType(currentResource.getResourceType());
4244 String currentInvariantUuid = currentResource.getInvariantUUID();
4245 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4247 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4248 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4249 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4253 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4254 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4255 log.debug("validate resource name before update");
4256 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4257 log.debug("validate description before update");
4258 validateDescriptionAndCleanup(null, updateInfoResource, null);
4259 log.debug("validate icon before update");
4260 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4261 log.debug("validate tags before update");
4262 validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4263 log.debug("validate vendor name before update");
4264 validateVendorName(null, updateInfoResource, null);
4265 log.debug("validate resource vendor model number before update");
4266 validateResourceVendorModelNumber(currentResource, updateInfoResource);
4267 log.debug("validate vendor release before update");
4268 validateVendorReleaseName(null, updateInfoResource, null);
4269 log.debug("validate contact info before update");
4270 validateContactId(null, updateInfoResource, null);
4271 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4272 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4273 log.debug("validate category before update");
4274 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4278 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4279 String resourceNameUpdated = updateInfoResource.getName();
4280 String resourceNameCurrent = currentResource.getName();
4281 if (resourceNameCurrent.equals(resourceNameUpdated)) {
4284 // In case of CVFC type we should support the case of old VF with CVFC
4285 // instances that were created without the "Cvfc" suffix
4286 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4287 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4290 private String addCvfcSuffixToResourceName(String resourceName) {
4291 return resourceName + "Cvfc";
4294 private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4295 boolean hasBeenCertified, boolean isNested) {
4296 String resourceNameUpdated = updateInfoResource.getName();
4297 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4298 if (isNested || !hasBeenCertified) {
4299 validateComponentName(null, updateInfoResource, null);
4300 validateResourceNameUniqueness(updateInfoResource);
4301 currentResource.setName(resourceNameUpdated);
4302 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4303 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4306 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4307 resourceNameUpdated);
4308 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4313 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4314 String iconUpdated = updateInfoResource.getIcon();
4315 String iconCurrent = currentResource.getIcon();
4316 if (!iconCurrent.equals(iconUpdated)) {
4317 if (!hasBeenCertified) {
4318 validateIcon(null, updateInfoResource, null);
4320 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4321 throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4326 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4327 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4328 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4329 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4330 validateResourceVendorModelNumber(null, updateInfoResource, null);
4334 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4335 boolean hasBeenCertified, boolean inTransaction) {
4336 validateCategory(null, updateInfoResource, null, inTransaction);
4337 if (hasBeenCertified) {
4338 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4339 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4340 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4341 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4342 if (!currentCategory.getName().equals(updateCategory.getName())
4343 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4344 log.info("Category {} cannot be updated once the resource has been certified once.",
4345 currentResource.getCategories());
4346 ResponseFormat errorResponse = componentsUtils
4347 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4348 return Either.right(errorResponse);
4351 return Either.left(true);
4354 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4355 Resource updateInfoResource, boolean hasBeenCertified) {
4357 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4358 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4359 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4360 || updatedDerivedFrom.isEmpty()) {
4361 log.trace("Update normative types");
4362 return Either.left(true);
4365 String derivedFromCurrent = currentDerivedFrom.get(0);
4366 String derivedFromUpdated = updatedDerivedFrom.get(0);
4368 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4369 if (!hasBeenCertified) {
4370 validateDerivedFromExist(null, updateInfoResource, null);
4372 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4373 currentResource, updateInfoResource, null);
4375 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4376 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4377 return validateDerivedFromExtending;
4381 // For derived from, we must know whether it was actually changed,
4382 // otherwise we must do no action.
4383 // Due to changes it inflicts on data model (remove artifacts,
4384 // properties...), it's not like a flat field which can be
4385 // overwritten if not changed.
4386 // So we must indicate that derived from is not changed
4387 updateInfoResource.setDerivedFrom(null);
4389 return Either.left(true);
4392 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4393 Resource updateInfoResource, boolean hasBeenCertified) {
4395 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4396 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4397 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4398 || updatedDerivedFrom.isEmpty()) {
4399 log.trace("Update normative types");
4400 return Either.left(true);
4403 String derivedFromCurrent = currentDerivedFrom.get(0);
4404 String derivedFromUpdated = updatedDerivedFrom.get(0);
4406 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4407 if (!hasBeenCertified) {
4408 validateDerivedFromExist(null, updateInfoResource, null);
4410 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4411 currentResource, updateInfoResource, null);
4413 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4414 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4415 return validateDerivedFromExtending;
4419 return Either.left(true);
4422 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
4423 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4426 String templateName = resource.getDerivedFrom().get(0);
4427 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4428 .validateToscaResourceNameExists(templateName);
4429 if (dataModelResponse.isRight()) {
4430 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4431 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4432 log.debug("request to data model failed with error: {}", storageStatus);
4433 ResponseFormat responseFormat = componentsUtils
4434 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4435 log.trace("audit before sending response");
4436 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4437 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4438 } else if (!dataModelResponse.left().value()) {
4439 log.info("resource template with name: {}, does not exists", templateName);
4440 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4441 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4442 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4446 // Tal G for extending inheritance US815447
4447 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4448 Resource updateInfoResource, AuditingActionEnum actionEnum) {
4449 String currentTemplateName = currentResource.getDerivedFrom().get(0);
4450 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4452 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4453 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4454 if (dataModelResponse.isRight()) {
4455 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4456 BeEcompErrorManager.getInstance()
4457 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4458 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4459 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4460 log.trace("audit before sending response");
4461 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4462 return Either.right(responseFormat);
4465 if (!dataModelResponse.left().value()) {
4466 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4467 currentTemplateName);
4468 ResponseFormat responseFormat = componentsUtils
4469 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4470 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4472 return Either.right(responseFormat);
4475 return Either.left(true);
4478 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4479 log.debug("validate resource derivedFrom field");
4480 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4481 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4482 log.info("derived from (template) field is missing for the resource");
4483 ResponseFormat responseFormat = componentsUtils
4484 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4485 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4487 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4491 private void validateResourceNameUniqueness(Resource resource) {
4493 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4494 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4495 resource.getComponentType());
4496 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4497 log.debug("resource with name: {}, already exists", resource.getName());
4498 throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4499 resource.getName());
4500 } else if(resourceOperationResponse.isRight()){
4501 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4502 throw new StorageException(resourceOperationResponse.right().value());
4507 private void validateCategory(User user, Resource resource,
4508 AuditingActionEnum actionEnum, boolean inTransaction) {
4510 List<CategoryDefinition> categories = resource.getCategories();
4511 if (CollectionUtils.isEmpty(categories)) {
4512 log.debug(CATEGORY_IS_EMPTY);
4513 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4514 ComponentTypeEnum.RESOURCE.getValue());
4515 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4516 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4517 ComponentTypeEnum.RESOURCE.getValue());
4519 if (categories.size() > 1) {
4520 log.debug("Must be only one category for resource");
4521 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4523 CategoryDefinition category = categories.get(0);
4524 List<SubCategoryDefinition> subcategories = category.getSubcategories();
4525 if (CollectionUtils.isEmpty(subcategories)) {
4526 log.debug("Missinig subcategory for resource");
4527 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4529 if (subcategories.size() > 1) {
4530 log.debug("Must be only one sub category for resource");
4531 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4534 SubCategoryDefinition subcategory = subcategories.get(0);
4536 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4537 log.debug(CATEGORY_IS_EMPTY);
4538 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4539 ComponentTypeEnum.RESOURCE.getValue());
4540 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4541 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4542 ComponentTypeEnum.RESOURCE.getValue());
4544 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4545 log.debug(CATEGORY_IS_EMPTY);
4546 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4547 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4548 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4549 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4552 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4555 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4556 User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4557 ResponseFormat responseFormat;
4558 if (category != null && subcategory != null) {
4559 log.debug("validating resource category {} against valid categories list", category);
4560 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4561 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4562 if (categories.isRight()) {
4563 log.debug("failed to retrive resource categories from Titan");
4564 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4565 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4566 throw new ComponentException(categories.right().value());
4568 List<CategoryDefinition> categoryList = categories.left().value();
4569 Optional<CategoryDefinition> foundCategory = categoryList.stream()
4570 .filter(cat -> cat.getName().equals(category.getName()))
4572 if(!foundCategory.isPresent()){
4573 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4574 category, categoryList);
4575 failOnInvalidCategory(user, resource, actionEnum);
4577 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4580 .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4582 if(!foundSubcategory.isPresent()){
4583 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4584 subcategory, foundCategory.get().getSubcategories());
4585 failOnInvalidCategory(user, resource, actionEnum);
4590 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4591 ResponseFormat responseFormat;
4592 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4593 ComponentTypeEnum.RESOURCE.getValue());
4594 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4595 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4596 ComponentTypeEnum.RESOURCE.getValue());
4599 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4600 String vendorRelease = resource.getVendorRelease();
4601 log.debug("validate vendor relese name");
4602 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4603 log.info("vendor relese name is missing.");
4604 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4605 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4606 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4609 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4612 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4613 if (vendorRelease != null) {
4614 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4615 log.info("vendor release exceds limit.");
4616 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4617 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4618 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4619 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4622 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4623 log.info("vendor release is not valid.");
4624 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4625 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4626 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4631 private void validateVendorName(User user, Resource resource,
4632 AuditingActionEnum actionEnum) {
4633 String vendorName = resource.getVendorName();
4634 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4635 log.info("vendor name is missing.");
4636 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4637 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4638 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
4640 validateVendorName(vendorName, user, resource, actionEnum);
4643 private void validateVendorName(String vendorName, User user, Resource resource,
4644 AuditingActionEnum actionEnum) {
4645 if (vendorName != null) {
4646 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4647 log.info("vendor name exceds limit.");
4648 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4649 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4650 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4651 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4652 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4655 if (!ValidationUtils.validateVendorName(vendorName)) {
4656 log.info("vendor name is not valid.");
4657 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4658 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4659 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
4664 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4665 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4666 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4667 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4668 log.info("resource vendor model number exceeds limit.");
4669 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4670 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4671 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4672 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4673 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4674 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4676 // resource vendor model number is currently validated as vendor
4678 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4679 log.info("resource vendor model number is not valid.");
4680 ResponseFormat errorResponse = componentsUtils
4681 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4682 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4683 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4689 private void validateCost(Resource resource) {
4690 String cost = resource.getCost();
4692 if (!ValidationUtils.validateCost(cost)) {
4693 log.debug("resource cost is invalid.");
4694 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4699 private void validateLicenseType(User user, Resource resource,
4700 AuditingActionEnum actionEnum) {
4701 log.debug("validate licenseType");
4702 String licenseType = resource.getLicenseType();
4703 if (licenseType != null) {
4704 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4706 if (!licenseTypes.contains(licenseType)) {
4707 log.debug("License type {} isn't configured", licenseType);
4708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4709 if (actionEnum != null) {
4710 // In update case, no audit is required
4711 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4713 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4718 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4719 Resource updatedResource, String userId, boolean inTransaction) {
4720 Either<Operation, ResponseFormat> deleteArtifactByInterface;
4721 if (updatedResource.getDerivedFrom() != null) {
4722 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4723 log.debug("1. Removing interface artifacts from graph");
4724 // Remove all interface artifacts of resource
4725 String resourceId = updatedResource.getUniqueId();
4726 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4728 if (interfaces != null) {
4729 Collection<InterfaceDefinition> values = interfaces.values();
4730 for (InterfaceDefinition interfaceDefinition : values) {
4731 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4733 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4734 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4735 if (operations != null) {
4736 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4737 Operation operation = operationEntry.getValue();
4738 ArtifactDefinition implementation = operation.getImplementationArtifact();
4739 if (implementation != null) {
4740 String uniqueId = implementation.getUniqueId();
4741 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4742 uniqueId, operationEntry.getKey(), interfaceType);
4743 // only thing that transacts and locks here
4744 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4747 if (deleteArtifactByInterface.isRight()) {
4748 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4749 if (!inTransaction) {
4750 titanDao.rollback();
4752 return Either.right(deleteArtifactByInterface.right().value());
4755 log.trace("No implementation found for operation {} - nothing to delete",
4756 operationEntry.getKey());
4760 log.trace("No operations found for interface type {}", interfaceType);
4764 log.debug("2. Removing properties");
4765 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4766 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4768 if (findPropertiesOfNode.isRight()
4769 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4770 log.debug("Failed to remove all properties of resource");
4771 if (!inTransaction) {
4772 titanDao.rollback();
4774 return Either.right(componentsUtils.getResponseFormat(
4775 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4779 log.debug("Derived from wasn't changed during update");
4782 if (inTransaction) {
4783 return Either.left(true);
4786 return Either.left(true);
4790 /**** Auditing *******************/
4792 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4793 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4794 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4796 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4798 return webApplicationContext.getBean(class1);
4801 public ICapabilityTypeOperation getCapabilityTypeOperation() {
4802 return capabilityTypeOperation;
4805 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4806 this.capabilityTypeOperation = capabilityTypeOperation;
4809 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4810 log.debug("validate resource properties default values");
4811 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4812 List<PropertyDefinition> properties = resource.getProperties();
4813 if (properties != null) {
4814 eitherResult = iterateOverProperties(properties);
4816 return eitherResult;
4819 public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4820 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4822 String innerType = null;
4823 for (PropertyDefinition property : properties) {
4824 if (!propertyOperation.isPropertyTypeValid(property)) {
4825 log.info("Invalid type for property {}", property);
4826 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4827 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4828 eitherResult = Either.right(responseFormat);
4832 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4833 applicationDataTypeCache);
4834 if (allDataTypes.isRight()) {
4835 return Either.right(allDataTypes.right().value());
4838 type = property.getType();
4840 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4841 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4842 if(responseFormat != null) {
4846 eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4848 return eitherResult;
4851 private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4852 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4853 log.info("Invalid default value for property {}", property);
4854 ResponseFormat responseFormat;
4855 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4856 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4857 property.getName(), type, innerType, property.getDefaultValue());
4859 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4860 property.getName(), type, property.getDefaultValue());
4862 return Either.right(responseFormat);
4865 return Either.left(true);
4868 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4869 ResponseFormat responseFormat = null;
4870 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4871 .isPropertyInnerTypeValid(property, allDataTypes);
4872 innerType = propertyInnerTypeValid.getLeft();
4873 if (!propertyInnerTypeValid.getRight().booleanValue()) {
4874 log.info("Invalid inner type for property {}", property);
4875 responseFormat = componentsUtils.getResponseFormat(
4876 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4878 return responseFormat;
4882 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4883 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4887 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4888 return componentInstanceBusinessLogic;
4891 private String getComponentTypeForResponse(Component component) {
4892 String componentTypeForResponse = "SERVICE";
4893 if (component instanceof Resource) {
4894 componentTypeForResponse = ((Resource) component).getResourceType().name();
4896 return componentTypeForResponse;
4899 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4902 validateUserExists(user, "Get resource from csar UUID",
4905 // get resource from csar uuid
4906 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4907 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4908 if (either.isRight()) {
4909 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4911 return Either.right(resp);
4914 return Either.left(either.left().value());
4918 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4919 String componentId, String userId) {
4923 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4924 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
4925 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4927 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
4928 uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
4929 return validCapabilitiesMap;
4932 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
4933 String capabilityType = capabilities.get(0).getType();
4934 if (defaultCapabilities.containsKey(capabilityType)) {
4935 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
4936 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
4937 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
4938 validCapabilityList.add(defaultCapability);
4939 validCapabilitiesMap.put(key, validCapabilityList);
4941 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
4945 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
4946 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
4947 && isNotEmpty(capabilities.get(0).getProperties())) {
4948 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
4949 defaultCapability.getName(), resourceId);
4951 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
4952 defaultCapability.getName());
4953 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
4954 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
4955 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
4959 private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
4960 CapabilityDefinition defaultCapability;
4961 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
4962 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
4964 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
4965 .getToscaFullElement(resourceId);
4966 if (getFullComponentRes.isRight()) {
4967 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
4968 getFullComponentRes.right().value());
4969 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
4972 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
4974 return defaultCapability;
4977 private void validateUniquenessUpdateUploadedComponentInstanceCapability(
4978 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
4979 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
4980 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
4981 .collect(toMap(PropertyDefinition::getName, Function.identity()));
4982 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
4983 for (UploadPropInfo property : uploadedProperties) {
4984 String propertyName = property.getName().toLowerCase();
4985 String propertyType = property.getType();
4986 ComponentInstanceProperty validProperty;
4987 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
4988 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
4991 validProperty = new ComponentInstanceProperty();
4992 validProperty.setName(propertyName);
4993 if (property.getValue() != null) {
4994 validProperty.setValue(property.getValue().toString());
4996 validProperty.setDescription(property.getDescription());
4997 validProperty.setPassword(property.isPassword());
4998 validProperties.add(validProperty);
5000 defaultCapability.setProperties(validProperties);
5003 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
5004 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5007 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5008 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5009 Resource resource, User user) {
5011 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5012 ArtifactOperationEnum.class);
5013 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5014 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5015 .left(nodeTypeArtifactsToHandle);
5017 // add all found Csar artifacts to list to upload
5018 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5019 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5020 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5021 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5022 ArtifactDefinition foundArtifact;
5024 if (!existingArtifactsToHandle.isEmpty()) {
5025 foundArtifact = existingArtifactsToHandle.stream()
5026 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5028 if (foundArtifact != null) {
5029 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5030 .getArtifactType()) {
5031 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5032 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5033 // if current artifact already exists, but has
5034 // different content, add him to the list to
5036 artifactsToUpdate.add(currNewArtifact);
5038 // remove found artifact from the list of existing
5039 // artifacts to handle, because it was already
5041 existingArtifactsToHandle.remove(foundArtifact);
5042 // and remove found artifact from the list to
5043 // upload, because it should either be updated or be
5045 artifactsToUpload.remove(currNewArtifact);
5047 log.debug("Can't upload two artifact with the same name {}.",
5048 currNewArtifact.getArtifactName());
5049 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5050 ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5051 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5052 foundArtifact.getArtifactType());
5053 AuditingActionEnum auditingAction = artifactsBusinessLogic
5054 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5055 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5056 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5057 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5058 resource.getComponentType(), null);
5059 responseWrapper.setInnerElement(responseFormat);
5065 if (responseWrapper.isEmpty()) {
5066 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5067 if (currArtifact.getIsFromCsar()) {
5068 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5070 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5075 if (responseWrapper.isEmpty()) {
5076 if (!artifactsToUpload.isEmpty()) {
5077 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5079 if (!artifactsToUpdate.isEmpty()) {
5080 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5082 if (!artifactsToDelete.isEmpty()) {
5083 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5086 if (!responseWrapper.isEmpty()) {
5087 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5089 } catch (Exception e) {
5090 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5091 responseWrapper.setInnerElement(responseFormat);
5092 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5093 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5095 return nodeTypeArtifactsToHandleRes;
5098 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5099 String nodeTypeFullName) {
5101 String actualVfName;
5102 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5103 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5104 actualType = ResourceTypeEnum.VFC.name();
5106 actualVfName = vfResourceName;
5107 actualType = nodeResourceType;
5111 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5112 String nameWithouNamespacePrefix = nodeTypeFullName
5113 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5114 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5115 String resourceType = findTypes[0];
5116 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5118 if (actualName.startsWith(Constants.ABSTRACT)) {
5119 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5120 .append(ValidationUtils.convertToSystemName(actualVfName));
5122 toscaResourceName.append(actualType.toLowerCase()).append('.')
5123 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5125 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5126 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5127 previousToscaResourceName
5128 .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5130 } catch (Exception e) {
5131 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
5132 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5133 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5137 public ICacheMangerOperation getCacheManagerOperation() {
5138 return cacheManagerOperation;
5141 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5142 this.cacheManagerOperation = cacheManagerOperation;
5146 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
5148 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5149 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
5152 if (resourceResultEither.isRight()) {
5153 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5154 log.debug("Failed to found resource with id {} ", resourceId);
5155 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5158 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5159 return Either.right(componentsUtils.getResponseFormatByResource(
5160 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5163 Resource resource = resourceResultEither.left().value();
5164 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5165 dataParamsToReturn);
5166 return Either.left(dataTransfer);
5170 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5171 Resource resource = (Resource) clonedComponent;
5172 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5173 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5174 .shouldUpgradeToLatestDerived(resource);
5175 if (shouldUpgradeToLatestDerived.isRight()) {
5176 return Either.right(
5177 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5179 return Either.left(shouldUpgradeToLatestDerived.left().value());
5181 return super.shouldUpgradeToLatestDerived(clonedComponent);