2 * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openecomp.sdc.be.components.impl;
18 import static java.util.stream.Collectors.joining;
19 import static java.util.stream.Collectors.toList;
20 import static java.util.stream.Collectors.toMap;
21 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
22 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
23 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
26 import fj.data.Either;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Optional;
37 import java.util.regex.Pattern;
40 import org.apache.commons.collections.CollectionUtils;
41 import org.apache.commons.collections.MapUtils;
42 import org.apache.commons.lang3.tuple.ImmutablePair;
43 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
44 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
45 import org.openecomp.sdc.be.components.csar.CsarInfo;
46 import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
47 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
48 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
49 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
50 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
51 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
52 import org.openecomp.sdc.be.components.impl.utils.CreateServiceFromYamlParameter;
53 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
54 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
55 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
56 import org.openecomp.sdc.be.components.path.ForwardingPathValidator;
57 import org.openecomp.sdc.be.components.validation.NodeFilterValidator;
58 import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
59 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
60 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
61 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
62 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
63 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
64 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
65 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
66 import org.openecomp.sdc.be.config.BeEcompErrorManager;
67 import org.openecomp.sdc.be.config.ConfigurationManager;
68 import org.openecomp.sdc.be.dao.api.ActionStatus;
69 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
70 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
71 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
72 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
75 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
76 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
77 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
79 import org.openecomp.sdc.be.impl.ComponentsUtils;
80 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
81 import org.openecomp.sdc.be.model.ArtifactDefinition;
82 import org.openecomp.sdc.be.model.CapabilityDefinition;
83 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
84 import org.openecomp.sdc.be.model.Component;
85 import org.openecomp.sdc.be.model.ComponentInstance;
86 import org.openecomp.sdc.be.model.ComponentInstanceInput;
87 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
88 import org.openecomp.sdc.be.model.ComponentParametersView;
89 import org.openecomp.sdc.be.model.DataTypeDefinition;
90 import org.openecomp.sdc.be.model.DistributionStatusEnum;
91 import org.openecomp.sdc.be.model.GroupDefinition;
92 import org.openecomp.sdc.be.model.InputDefinition;
93 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
94 import org.openecomp.sdc.be.model.LifecycleStateEnum;
95 import org.openecomp.sdc.be.model.NodeTypeInfo;
96 import org.openecomp.sdc.be.model.Operation;
97 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
98 import org.openecomp.sdc.be.model.PropertyDefinition;
99 import org.openecomp.sdc.be.model.RelationshipImpl;
100 import org.openecomp.sdc.be.model.RelationshipInfo;
101 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
102 import org.openecomp.sdc.be.model.RequirementDefinition;
103 import org.openecomp.sdc.be.model.Resource;
104 import org.openecomp.sdc.be.model.Service;
105 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
106 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
107 import org.openecomp.sdc.be.model.UploadPropInfo;
108 import org.openecomp.sdc.be.model.UploadReqInfo;
109 import org.openecomp.sdc.be.model.UploadResourceInfo;
110 import org.openecomp.sdc.be.model.User;
111 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
112 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
113 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
114 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
115 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
116 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
117 import org.openecomp.sdc.be.model.operations.StorageException;
118 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
119 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
120 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
121 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
122 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
123 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
124 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
125 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
126 import org.openecomp.sdc.be.tosca.CsarUtils;
127 import org.openecomp.sdc.be.utils.TypeUtils;
128 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
129 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
130 import org.openecomp.sdc.common.api.Constants;
131 import org.openecomp.sdc.common.datastructure.Wrapper;
132 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
133 import org.openecomp.sdc.common.log.wrappers.Logger;
134 import org.openecomp.sdc.common.util.ValidationUtils;
135 import org.openecomp.sdc.exception.ResponseFormat;
136 import org.springframework.beans.factory.annotation.Autowired;
137 import org.yaml.snakeyaml.Yaml;
141 @org.springframework.stereotype.Component("serviceImportBusinessLogic")
142 public class ServiceImportBusinessLogic{
144 private final UiComponentDataConverter uiComponentDataConverter;
145 private static final String INITIAL_VERSION = "0.1";
146 private static final String CREATE_RESOURCE = "Create Resource";
147 private static final String IN_RESOURCE = " in resource {} ";
148 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
149 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
150 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
151 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
152 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
153 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
154 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
158 private ServiceBusinessLogic serviceBusinessLogic;
159 public ServiceBusinessLogic getServiceBusinessLogic() {
160 return serviceBusinessLogic;
163 public void setServiceBusinessLogic(
164 ServiceBusinessLogic serviceBusinessLogic) {
165 this.serviceBusinessLogic = serviceBusinessLogic;
169 private CsarBusinessLogic csarBusinessLogic;
171 protected ComponentsUtils componentsUtils;
173 protected ToscaOperationFacade toscaOperationFacade;
175 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
177 private LifecycleBusinessLogic lifecycleBusinessLogic;
179 private CompositionBusinessLogic compositionBusinessLogic;
181 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
183 private ServiceImportParseLogic serviceImportParseLogic;
185 private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
187 public ServiceImportBusinessLogic(IElementOperation elementDao,
188 IGroupOperation groupOperation,
189 IGroupInstanceOperation groupInstanceOperation,
190 IGroupTypeOperation groupTypeOperation,
191 GroupBusinessLogic groupBusinessLogic,
192 InterfaceOperation interfaceOperation,
193 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
194 ArtifactsBusinessLogic artifactsBusinessLogic,
195 IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
196 ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator,
197 UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation,
198 NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation,
199 ComponentContactIdValidator componentContactIdValidator,
200 ComponentNameValidator componentNameValidator,
201 ComponentTagsValidator componentTagsValidator,
202 ComponentValidator componentValidator,
203 ComponentIconValidator componentIconValidator,
204 ComponentProjectCodeValidator componentProjectCodeValidator,
205 ComponentDescriptionValidator componentDescriptionValidator) {
206 this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
207 this.uiComponentDataConverter = uiComponentDataConverter;
210 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
212 public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
213 log.debug("enter createService");
214 service.setCreatorUserId(user.getUserId());
215 service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
216 service.setVersion(INITIAL_VERSION);
217 service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
218 service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
219 service.setInstantiationType("A-la-carte");
220 service.setEnvironmentContext("General_Revenue-Bearing");
221 service.setEcompGeneratedNaming(true);
224 serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction);
226 log.debug("enter createService,validateServiceBeforeCreate success");
227 String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName;
229 log.debug("enter createService,get csarUUID:{}", csarUUID);
230 csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID);
231 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
232 return createServiceFromCsar(service, user, csarUIPayload, csarUUID);
233 }catch (Exception e){
234 log.debug("Exception occured when createService,error is:{}",e.getMessage(),e);
235 //ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
236 throw new ComponentException(ActionStatus.GENERAL_ERROR);
240 protected Service createServiceFromCsar(Service service, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
241 log.trace("************* created successfully from YAML, resource TOSCA ");
243 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
245 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
246 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
247 .findNodeTypesArtifactsToHandle(
248 nodeTypesInfo, csarInfo, service);
249 if (findNodeTypesArtifactsToHandleRes.isRight()) {
250 log.debug("failed to find node types for update with artifacts during import csar {}. ",
251 csarInfo.getCsarUUID());
252 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
254 Service cService = createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
255 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
258 }catch (Exception e){
259 log.debug("Exception occured when createServiceFromCsar,error is:{}",e.getMessage(),e);
260 throw new ComponentException(ActionStatus.GENERAL_ERROR);
264 protected Service createServiceFromYaml(Service service, String topologyTemplateYaml,
265 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
266 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
267 boolean shouldLock, boolean inTransaction, String nodeName) {
269 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
270 Service createdService;
271 CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter();
274 parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service);
275 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances())) {
276 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
278 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", service.getName());
279 csfyp.setYamlName(yamlName);
280 csfyp.setParsedToscaYamlInfo(parsedToscaYamlInfo);
281 csfyp.setCreatedArtifacts(createdArtifacts);
282 csfyp.setTopologyTemplateYaml(topologyTemplateYaml);
283 csfyp.setNodeTypesInfo(nodeTypesInfo);
284 csfyp.setCsarInfo(csarInfo);
285 csfyp.setNodeName(nodeName);
287 createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp);
288 log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName());
289 } catch (ComponentException e) {
290 log.debug("create Service From Yaml failed,get ComponentException:{}", e);
292 } catch (StorageException e) {
293 log.debug("create Service From Yaml failed,get StorageException:{}", e);
296 return createdService;
299 protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative,
300 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
301 boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp) {
303 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
304 String yamlName = csfyp.getYamlName();
305 ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo();
306 List<ArtifactDefinition> createdArtifacts = csfyp.getCreatedArtifacts();
307 String topologyTemplateYaml = csfyp.getTopologyTemplateYaml();
308 Map<String, NodeTypeInfo> nodeTypesInfo = csfyp.getNodeTypesInfo();
309 CsarInfo csarInfo = csfyp.getCsarInfo();
310 String nodeName = csfyp.getNodeName();
313 Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE);
314 if (lockResult.isRight()) {
315 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
316 throw new ComponentException(lockResult.right().value());
318 log.debug("name is locked {} status = {}", service.getSystemName(), lockResult);
321 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
322 service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative);
323 log.trace("************* Going to add inputs from yaml {}", yamlName);
325 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
326 service = serviceImportParseLogic.createInputsOnService(service, inputs);
327 log.trace("************* Finish to add inputs from yaml {}", yamlName);
329 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
331 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
333 service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap,
334 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
335 nodeTypesArtifactsToCreate, nodeName);
336 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
337 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
338 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName());
339 if (validateUpdateVfGroupNamesRes.isRight()) {
340 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
341 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
343 Map<String, GroupDefinition> groups;
344 log.trace("************* Going to add groups from yaml {}", yamlName);
346 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
347 groups = validateUpdateVfGroupNamesRes.left().value();
349 groups = parsedToscaYamlInfo.getGroups();
352 Either<Service, ResponseFormat> createGroupsOnResource = createGroupsOnResource(service, groups);
353 if (createGroupsOnResource.isRight()) {
354 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
355 throw new ComponentException(createGroupsOnResource.right().value());
357 service = createGroupsOnResource.left().value();
358 log.trace("************* Going to add artifacts from yaml {}", yamlName);
360 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
361 nodeTypesArtifactsToCreate);
363 Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
364 ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
365 csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
366 if (createArtifactsEither.isRight()) {
367 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
368 throw new ComponentException(createArtifactsEither.right().value());
370 service = serviceImportParseLogic.getServiceWithGroups(createArtifactsEither.left().value().getUniqueId());
371 ASDCKpiApi.countCreatedResourcesKPI();
373 } catch (ComponentException | StorageException e) {
374 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
377 if (!inTransaction) {
378 serviceBusinessLogic.janusGraphDao.commit();
381 serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(),
382 NodeTypeEnum.Resource);
387 protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(
388 ArtifactsBusinessLogic.ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
389 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
390 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
392 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
393 Resource resource = preparedResource;
395 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
396 .getNodeTypesArtifactsToHandle();
397 if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
398 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
399 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
400 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
401 if (handleNodeTypeArtifactsRes.isRight()) {
402 return Either.right(handleNodeTypeArtifactsRes.right().value());
406 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
407 new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
408 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
409 if (createdCsarArtifactsEither.isRight()) {
410 return createdCsarArtifactsEither;
412 resource = createdCsarArtifactsEither.left().value();
414 return Either.left(resource);
417 protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
418 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
419 boolean inTransaction) {
420 if (csarInfo.getCsar() != null) {
421 createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
423 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
424 createdArtifacts, shouldLock, inTransaction, artifactOperation);
425 if (eitherCreateResult.isRight()) {
426 return Either.right(eitherCreateResult.right().value());
428 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
429 if (eitherGerResource.isRight()) {
430 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
431 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
432 return Either.right(responseFormat);
434 resource = eitherGerResource.left().value();
435 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
437 if (artifacsMetaCsarStatus.isLeft()) {
438 return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction, artifacsMetaCsarStatus);
440 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
443 return Either.left(resource);
446 protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction) {
447 String vendorLicenseModelId = null;
448 String vfLicenseModelId = null;
449 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
450 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
451 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
452 for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
453 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
454 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
456 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
457 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
462 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
463 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
464 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
465 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
466 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
468 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
469 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
470 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
471 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
472 artifactOperation, null, true, shouldLock, inTransaction);
475 protected Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction, Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus) {
477 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
478 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
479 Either<Resource, ResponseFormat> createArtifactsFromCsar;
480 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
481 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
482 .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName,
485 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
486 .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName,
487 createdArtifacts, shouldLock, inTransaction);
488 if ((result.left().value() instanceof Resource) && result.isLeft()) {
489 Resource service1 = (Resource) result.left().value();
490 createArtifactsFromCsar = Either.left(service1);
492 createArtifactsFromCsar = Either.right(result.right().value());
495 if (createArtifactsFromCsar.isRight()) {
496 log.debug("Couldn't create artifacts from artifacts.meta");
497 return Either.right(createArtifactsFromCsar.right().value());
499 return Either.left(createArtifactsFromCsar.left().value());
500 }catch(Exception e) {
501 log.debug("Exception occured in getResourceResponseFormatEither, message:{}", e.getMessage(), e);
502 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
506 protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
507 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
508 ArtifactOperationInfo artifactOperation) {
509 Either<Resource, ResponseFormat> resStatus = null;
510 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
512 Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
513 if (artifactPathAndNameList.isRight()) {
514 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
515 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
517 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
519 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
520 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
521 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
523 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
524 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
525 if (findVfCsarArtifactsToHandleRes.isRight()) {
526 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
528 if (resStatus == null) {
529 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
532 if (resStatus == null && vfCsarArtifactsToHandle != null) {
533 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
535 if (resStatus == null) {
536 resStatus = Either.left(resource);
538 } catch (Exception e) {
539 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
540 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
542 CsarUtils.handleWarningMessages(collectedWarningMessages);
547 protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
548 Resource resource, List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, User user) {
550 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
551 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
552 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
554 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
555 existingArtifacts.addAll(resource.getArtifacts().values());
557 existingArtifacts = existingArtifacts.stream()
558 .filter(this::isNonMetaArtifact).collect(toList());
560 List<String> artifactsToIgnore = new ArrayList<>();
561 if (resource.getGroups() != null) {
562 resource.getGroups().stream().forEach(g -> {
563 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
564 artifactsToIgnore.addAll(g.getArtifacts());
568 existingArtifacts = existingArtifacts.stream()
569 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
570 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
573 protected boolean isNonMetaArtifact(ArtifactDefinition artifact) {
574 boolean result = true;
575 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
581 private boolean isValidArtifactType(ArtifactDefinition artifact) {
582 boolean result = true;
583 if (artifact.getArtifactType() == null
584 || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE)
585 || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VF_LICENSE)) {
591 protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
592 List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
593 Resource resource, User user) {
595 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
596 ArtifactsBusinessLogic.ArtifactOperationEnum.class);
597 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
598 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
599 .left(nodeTypeArtifactsToHandle);
601 // add all found Csar artifacts to list to upload
602 List<CsarUtils.NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
603 List<CsarUtils.NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
604 List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
605 for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
606 ArtifactDefinition foundArtifact;
607 if (!existingArtifactsToHandle.isEmpty()) {
608 foundArtifact = existingArtifactsToHandle.stream()
609 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
611 if (foundArtifact != null) {
612 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact
613 .getArtifactType())) {
614 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
615 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
616 artifactsToUpdate.add(currNewArtifact);
618 existingArtifactsToHandle.remove(foundArtifact);
619 artifactsToUpload.remove(currNewArtifact);
621 log.debug("Can't upload two artifact with the same name {}.",
622 currNewArtifact.getArtifactName());
623 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
624 ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
625 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
626 foundArtifact.getArtifactType());
627 AuditingActionEnum auditingAction = serviceBusinessLogic.artifactsBusinessLogic
628 .detectAuditingType(new ArtifactOperationInfo(false, false,
629 ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
630 serviceBusinessLogic.artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
631 user, null, null, foundArtifact.getUniqueId(), responseFormat,
632 resource.getComponentType(), null);
633 responseWrapper.setInnerElement(responseFormat);
639 if (responseWrapper.isEmpty()) {
640 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
641 if (currArtifact.getIsFromCsar()) {
642 artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
644 artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
649 if (responseWrapper.isEmpty()) {
650 if (!artifactsToUpload.isEmpty()) {
651 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
653 if (!artifactsToUpdate.isEmpty()) {
654 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
656 if (!artifactsToDelete.isEmpty()) {
657 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
660 if (!responseWrapper.isEmpty()) {
661 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
663 } catch (Exception e) {
664 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
665 responseWrapper.setInnerElement(responseFormat);
666 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
667 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
669 return nodeTypeArtifactsToHandleRes;
672 protected Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Resource, ResponseFormat> resStatus, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
673 for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
675 Optional<ResponseFormat> optionalCreateInDBError =
676 currArtifactOperationPair.getValue().stream()
677 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
678 e.getArtifactName(), e.getArtifactType(),
679 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
680 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
681 new ArtifactOperationInfo(false, false,
682 currArtifactOperationPair.getKey()),
683 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
684 .filter(Either::isRight).
685 map(e -> e.right().value()).
687 if (optionalCreateInDBError.isPresent()) {
688 resStatus = Either.right(optionalCreateInDBError.get());
695 protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
696 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
697 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
698 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
699 boolean inTransaction) {
700 byte[] artifactFileBytes = null;
702 if (csarInfo.getCsar().containsKey(artifactPath)) {
703 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
705 Either<Boolean, ResponseFormat> result = Either.left(true);
706 if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
707 if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
708 Either<ArtifactDefinition, ResponseFormat> handleDelete = serviceBusinessLogic.artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource,
709 shouldLock, inTransaction);
710 if (handleDelete.isRight()) {
711 result = Either.right(handleDelete.right().value());
715 if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
716 operation = new ArtifactOperationInfo(false, false,
717 ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
720 if (artifactFileBytes != null) {
721 Map<String, Object> vendorLicenseModelJson = ArtifactUtils
722 .buildJsonForUpdateArtifact(artifactId, artifactFileName,
723 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
724 artifactFileBytes, null, isFromCsar);
725 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
726 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
727 serviceImportParseLogic
728 .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
729 if (eitherNonMetaArtifacts.isRight()) {
730 BeEcompErrorManager.getInstance()
731 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
732 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
733 BeEcompErrorManager.ErrorSeverity.WARNING);
734 return Either.right(eitherNonMetaArtifacts.right().value());
740 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
741 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
742 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
743 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
744 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
745 Either<Resource, ResponseFormat> changeStateResponse;
747 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
748 if (changeStateResponse.isRight()) {
749 return Either.right(changeStateResponse.right().value());
751 nodeTypeResource = changeStateResponse.left().value();
753 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
754 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
755 for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
757 ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
758 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
759 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
760 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
761 nodeTypeResource.getName());
762 handleNodeTypeArtifactsRequestRes = serviceBusinessLogic.artifactsBusinessLogic
763 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
764 createdArtifacts, new ArtifactOperationInfo(false,
765 ignoreLifecycleState, curOperation),
766 false, inTransaction);
767 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
768 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
770 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
773 if (handleNodeTypeArtifactsRes == null) {
774 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
776 } catch (Exception e) {
777 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
778 handleNodeTypeArtifactsRes = Either.right(responseFormat);
779 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
781 return handleNodeTypeArtifactsRes;
784 protected Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
785 Either<Resource, ResponseFormat> checkoutResourceRes;
787 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
788 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
789 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
790 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
791 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
792 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR),
793 inTransaction, true);
794 if (checkoutRes.isRight()) {
795 checkoutResourceRes = Either.right(checkoutRes.right().value());
797 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
800 checkoutResourceRes = Either.left(resource);
802 } catch (Exception e) {
803 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
804 checkoutResourceRes = Either.right(responseFormat);
805 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
808 return checkoutResourceRes;
811 protected Either<Service, ResponseFormat> createOrUpdateArtifacts(
812 ArtifactsBusinessLogic.ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
813 String yamlFileName, CsarInfo csarInfo, Service preparedService,
814 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
816 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
817 Service resource = preparedService;
818 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
819 .getNodeTypesArtifactsToHandle();
821 Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
822 new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
823 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
824 if (createdCsarArtifactsEither.isRight()) {
825 return createdCsarArtifactsEither;
827 resource = createdCsarArtifactsEither.left().value();
828 return Either.left(resource);
831 protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo,
832 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
833 boolean inTransaction) {
835 if (csarInfo.getCsar() != null) {
836 String vendorLicenseModelId = null;
837 String vfLicenseModelId = null;
838 if (artifactOperation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE) {
839 Map<String, ArtifactDefinition> deploymentArtifactsMap = service.getDeploymentArtifacts();
840 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
841 for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
842 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
843 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
845 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
846 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
851 createOrUpdateSingleNonMetaArtifact(service, csarInfo,
852 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
853 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
854 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
855 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
857 createOrUpdateSingleNonMetaArtifact(service, csarInfo,
858 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
859 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
860 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
861 artifactOperation, null, true, shouldLock, inTransaction);
863 Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service,
864 createdArtifacts, shouldLock, inTransaction, artifactOperation);
865 if (eitherCreateResult.isRight()) {
866 return Either.right(eitherCreateResult.right().value());
868 Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade
869 .getToscaElement(service.getUniqueId());
870 if (eitherGerResource.isRight()) {
871 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
872 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, ComponentTypeEnum.SERVICE);
873 return Either.right(responseFormat);
875 service = eitherGerResource.left().value();
876 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
878 if (artifacsMetaCsarStatus.isLeft()) {
879 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
880 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
881 Either<Service, ResponseFormat> createArtifactsFromCsar;
882 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
883 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts);
885 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
886 if ((result.left().value() instanceof Service) && result.isLeft()) {
887 Service service1 = (Service) result.left().value();
888 createArtifactsFromCsar = Either.left(service1);
890 createArtifactsFromCsar = Either.right(result.right().value());
893 if (createArtifactsFromCsar.isRight()) {
894 log.debug("Couldn't create artifacts from artifacts.meta");
895 return Either.right(createArtifactsFromCsar.right().value());
897 return Either.left(createArtifactsFromCsar.left().value());
899 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(service, csarInfo, shouldLock, inTransaction);
902 return Either.left(service);
905 protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
906 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
907 ArtifactOperationInfo artifactOperation) {
908 Either<Service, ResponseFormat> resStatus = null;
909 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
912 Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
913 if (artifactPathAndNameList.isRight()) {
914 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
915 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
917 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
919 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
920 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
921 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
923 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
924 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
926 if (findVfCsarArtifactsToHandleRes.isRight()) {
927 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
929 if (resStatus == null) {
930 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
933 if (resStatus == null && vfCsarArtifactsToHandle != null) {
934 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
936 if (resStatus == null) {
937 resStatus = Either.left(resource);
939 } catch (Exception e) {
940 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
941 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
943 CsarUtils.handleWarningMessages(collectedWarningMessages);
948 protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
949 Service resource, List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, User user) {
950 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
951 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
952 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
954 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
955 existingArtifacts.addAll(resource.getArtifacts().values());
957 existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
959 List<String> artifactsToIgnore = new ArrayList<>();
960 if (resource.getGroups() != null) {
961 resource.getGroups().stream().forEach(g -> {
962 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
963 artifactsToIgnore.addAll(g.getArtifacts());
967 existingArtifacts = existingArtifacts.stream()
968 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
969 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
972 protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
973 List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
974 Service resource, User user) {
975 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
976 ArtifactsBusinessLogic.ArtifactOperationEnum.class);
977 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
978 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
979 .left(nodeTypeArtifactsToHandle);
981 List<CsarUtils.NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
982 List<CsarUtils.NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
983 List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
984 for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
985 ArtifactDefinition foundArtifact;
987 if (!existingArtifactsToHandle.isEmpty()) {
988 foundArtifact = existingArtifactsToHandle.stream()
989 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
991 if (foundArtifact != null) {
992 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact
993 .getArtifactType())) {
994 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
995 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
996 artifactsToUpdate.add(currNewArtifact);
998 existingArtifactsToHandle.remove(foundArtifact);
999 artifactsToUpload.remove(currNewArtifact);
1001 log.debug("Can't upload two artifact with the same name {}.",
1002 currNewArtifact.getArtifactName());
1003 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
1004 ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
1005 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
1006 foundArtifact.getArtifactType());
1007 AuditingActionEnum auditingAction = serviceBusinessLogic.artifactsBusinessLogic
1008 .detectAuditingType(new ArtifactOperationInfo(false, false,
1009 ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
1010 serviceBusinessLogic.artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
1011 user, null, null, foundArtifact.getUniqueId(), responseFormat,
1012 resource.getComponentType(), null);
1013 responseWrapper.setInnerElement(responseFormat);
1019 if (responseWrapper.isEmpty()) {
1020 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
1021 if (currArtifact.getIsFromCsar()) {
1022 artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
1024 artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
1028 if (responseWrapper.isEmpty()) {
1029 if (!artifactsToUpload.isEmpty()) {
1030 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
1032 if (!artifactsToUpdate.isEmpty()) {
1033 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
1035 if (!artifactsToDelete.isEmpty()) {
1036 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
1039 if (!responseWrapper.isEmpty()) {
1040 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
1042 } catch (Exception e) {
1043 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1044 responseWrapper.setInnerElement(responseFormat);
1045 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
1046 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
1048 return nodeTypeArtifactsToHandleRes;
1051 protected Either<Service, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Service resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Service, ResponseFormat> resStatus, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
1052 for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1054 Optional<ResponseFormat> optionalCreateInDBError =
1055 currArtifactOperationPair.getValue().stream()
1056 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
1057 e.getArtifactName(), e.getArtifactType(),
1058 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
1059 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
1060 new ArtifactOperationInfo(false, false,
1061 currArtifactOperationPair.getKey()),
1062 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
1063 .filter(Either::isRight).
1064 map(e -> e.right().value()).
1066 if (optionalCreateInDBError.isPresent()) {
1067 resStatus = Either.right(optionalCreateInDBError.get());
1074 public ComponentsUtils getComponentsUtils() {
1075 return this.componentsUtils;
1078 public void setComponentsUtils(ComponentsUtils componentsUtils) {
1079 this.componentsUtils = componentsUtils;
1082 protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
1083 List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList =
1084 csarInfo.getCsar().entrySet().stream()
1085 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
1087 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
1088 collectedWarningMessages))
1089 .filter(Either::isLeft)
1090 .map(e -> e.left().value())
1092 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
1093 for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
1094 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
1095 return Either.right(nonMetaArtifactInfo.getArtifactName());
1098 return Either.left(artifactPathAndNameList);
1101 protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Service service, CsarInfo csarInfo,
1102 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1103 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1104 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1105 boolean inTransaction) {
1106 byte[] artifactFileBytes = null;
1107 if (csarInfo.getCsar().containsKey(artifactPath)) {
1108 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1110 Either<Boolean, ResponseFormat> result = Either.left(true);
1111 if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
1112 if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1113 Either<ArtifactDefinition, ResponseFormat> handleDelete = serviceBusinessLogic.artifactsBusinessLogic.handleDelete(service.getUniqueId(), artifactId, csarInfo.getModifier(), service,
1114 shouldLock, inTransaction);
1115 if (handleDelete.isRight()) {
1116 result = Either.right(handleDelete.right().value());
1120 if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1121 operation = new ArtifactOperationInfo(false, false,
1122 ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
1125 if (artifactFileBytes != null) {
1126 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1127 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1128 artifactFileBytes, null, isFromCsar);
1129 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1130 service, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1131 serviceImportParseLogic
1132 .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1133 if (eitherNonMetaArtifacts.isRight()) {
1134 BeEcompErrorManager.getInstance()
1135 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1136 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1137 BeEcompErrorManager.ErrorSeverity.WARNING);
1138 return Either.right(eitherNonMetaArtifacts.right().value());
1144 protected Either<Service, ResponseFormat> createGroupsOnResource(Service service,
1145 Map<String, GroupDefinition> groups) {
1146 if (groups != null && !groups.isEmpty()) {
1147 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
1148 serviceImportParseLogic.handleGroupsProperties(service, groups);
1149 serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
1150 Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(service,
1151 groupsAsList, true);
1152 if (createGroups.isRight()) {
1153 return Either.right(createGroups.right().value());
1156 return Either.left(service);
1158 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
1159 .getToscaElement(service.getUniqueId());
1160 if (updatedResource.isRight()) {
1161 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
1162 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE);
1163 return Either.right(responseFormat);
1165 return Either.left(updatedResource.left().value());
1168 protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1169 List<GroupDefinition> result = new ArrayList<>();
1170 List<ComponentInstance> componentInstances = component.getComponentInstances();
1171 if (groups != null) {
1172 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = serviceImportParseLogic.validateCyclicGroupsDependencies(groups);
1173 if (validateCyclicGroupsDependencies.isRight()) {
1174 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1176 for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1177 String groupName = entry.getKey();
1178 GroupDefinition groupDefinition = entry.getValue();
1179 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1180 updatedGroupDefinition.setMembers(null);
1181 Map<String, String> members = groupDefinition.getMembers();
1182 if (members != null) {
1183 serviceImportParseLogic
1184 .updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1186 result.add(updatedGroupDefinition);
1193 protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1194 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1195 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1196 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1197 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1200 log.debug("************* Going to create all nodes {}", yamlName);
1201 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1202 nodeTypesInfo, csarInfo, nodeName);
1203 log.debug("************* Going to create all resource instances {}", yamlName);
1204 resource = createResourceInstances(yamlName, resource,
1205 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1206 log.debug("************* Finished to create all resource instances {}", yamlName);
1207 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1208 log.debug("************* Going to create positions {}", yamlName);
1209 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1210 log.debug("************* Finished to set positions {}", yamlName);
1212 } catch (Exception e) {
1213 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1217 protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
1218 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1219 log.debug("#createResourceInstancesRelations - Going to create relations ");
1220 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
1221 if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
1222 resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
1223 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
1224 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR);
1225 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1227 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1228 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1229 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1230 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1231 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1232 Map<String, List<AttributeDataDefinition>> instAttributes = new HashMap<>();
1233 Map<String, Resource> originCompMap = new HashMap<>();
1234 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1235 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1237 log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1238 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
1239 if (allDataTypes.isRight()) {
1240 JanusGraphOperationStatus status = allDataTypes.right().value();
1241 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
1242 "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
1243 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
1244 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
1246 Resource finalResource = resource;
1247 uploadResInstancesMap
1249 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
1250 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
1251 instArtifacts, instAttributes, originCompMap, instInputs, i));
1252 serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
1253 serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
1254 serviceImportParseLogic
1255 .associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
1256 serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
1257 serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
1258 serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
1259 resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
1261 serviceImportParseLogic
1262 .addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
1263 serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
1264 handleSubstitutionMappings(resource, uploadResInstancesMap);
1265 log.debug("************* in create relations, getResource start");
1266 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1267 log.debug("************* in create relations, getResource end");
1268 if (eitherGetResource.isRight()) {
1269 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1270 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
1272 return eitherGetResource.left().value();
1275 protected void processComponentInstance(String yamlName, Resource resource,
1276 List<ComponentInstance> componentInstancesList,
1277 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
1278 Map<String, List<ComponentInstanceProperty>> instProperties,
1279 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1280 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
1281 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1282 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
1283 Map<String, List<AttributeDataDefinition>> instAttributes,
1284 Map<String, Resource> originCompMap,
1285 Map<String, List<ComponentInstanceInput>> instInputs,
1286 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
1287 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
1288 .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName()))
1290 if (!currentCompInstanceOpt.isPresent()) {
1291 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
1292 resource.getUniqueId());
1293 BeEcompErrorManager.getInstance().logInternalDataError(
1294 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
1295 resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
1296 ResponseFormat responseFormat = componentsUtils
1297 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1298 throw new ComponentException(responseFormat);
1300 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
1301 String resourceInstanceId = currentCompInstance.getUniqueId();
1302 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
1303 log.debug("enter processComponentInstance,get originResource Requirements:{}",
1304 originResource.getRequirements());
1305 if (MapUtils.isNotEmpty(originResource.getRequirements())) {
1306 instRequirements.put(currentCompInstance, originResource.getRequirements());
1308 if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
1309 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
1310 currentCompInstance, originResource);
1312 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
1313 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
1315 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
1316 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
1318 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
1319 instAttributes.put(resourceInstanceId, originResource.getAttributes());
1321 if (originResource.getResourceType() != ResourceTypeEnum.VF) {
1322 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
1323 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
1324 if (addPropertiesValueToRiRes.getStatus() != 200) {
1325 throw new ComponentException(addPropertiesValueToRiRes);
1328 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
1329 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
1333 protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
1334 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
1335 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
1336 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1338 if (MapUtils.isNotEmpty(propMap)) {
1339 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
1340 List<ComponentInstanceInput> instPropList = new ArrayList<>();
1342 if (CollectionUtils.isEmpty(originResource.getInputs())) {
1343 log.debug("failed to find properties ");
1344 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
1346 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
1347 for (List<UploadPropInfo> propertyList : propMap.values()) {
1348 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
1350 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
1351 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
1353 } catch (Exception e) {
1354 log.debug("failed to add Inputs Values To Ri");
1355 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1359 protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
1360 UploadPropInfo propertyInfo = propertyList.get(0);
1361 String propName = propertyInfo.getName();
1362 if (!currPropertiesMap.containsKey(propName)) {
1363 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
1366 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
1367 ComponentInstanceInput property = null;
1369 String value = null;
1370 List<GetInputValueDataDefinition> getInputs = null;
1371 boolean isValidate = true;
1372 if (propertyInfo.getValue() != null) {
1373 getInputs = propertyInfo.getGet_input();
1374 isValidate = getInputs == null || getInputs.isEmpty();
1376 value = getPropertyJsonStringValue(propertyInfo.getValue(),
1377 curPropertyDef.getType());
1379 value = getPropertyJsonStringValue(propertyInfo.getValue(),
1380 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1383 String innerType = null;
1384 property = new ComponentInstanceInput(curPropertyDef, value, null);
1385 String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1386 property.setValue(validPropertyVAlue);
1388 if (isNotEmpty(getInputs)) {
1389 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1390 for (GetInputValueDataDefinition getInput : getInputs) {
1391 List<InputDefinition> inputs = resource.getInputs();
1392 if (CollectionUtils.isEmpty(inputs)) {
1393 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1396 Optional<InputDefinition> optional = inputs.stream()
1397 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
1398 if (!optional.isPresent()) {
1399 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1401 InputDefinition input = optional.get();
1402 getInput.setInputId(input.getUniqueId());
1403 getInputValues.add(getInput);
1405 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1406 processGetInput(getInputValues, inputs, getInputIndex);
1408 property.setGetInputValues(getInputValues);
1410 instPropList.add(property);
1411 currPropertiesMap.remove(property.getName());
1414 protected void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1415 if (resource.getResourceType() == ResourceTypeEnum.VF) {
1416 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
1417 if (getResourceRes.isRight()) {
1418 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1419 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1420 throw new ComponentException(responseFormat);
1422 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
1423 uploadResInstancesMap);
1424 if (getResourceRes.isRight()) {
1425 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1426 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1427 throw new ComponentException(responseFormat);
1432 protected Resource createResourceInstances(String yamlName, Resource resource,
1433 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1434 Map<String, Resource> nodeNamespaceMap) {
1435 Either<Resource, ResponseFormat> eitherResource = null;
1436 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1437 if (MapUtils.isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1438 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1439 throw new ComponentException(responseFormat);
1441 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1442 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
1443 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
1445 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
1446 uploadResInstancesMap
1448 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
1450 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
1452 toscaOperationFacade.associateComponentInstancesToComponent(resource,
1453 resourcesInstancesMap, false, false);
1454 } catch (StorageException exp) {
1455 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
1456 log.debug("Failed to add component instances to container component {}", resource.getName());
1457 ResponseFormat responseFormat = componentsUtils
1458 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
1459 eitherResource = Either.right(responseFormat);
1460 throw new ByResponseFormatComponentException(eitherResource.right().value());
1464 log.debug("*************Going to get resource {}", resource.getUniqueId());
1465 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
1466 .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
1467 log.debug("*************finished to get resource {}", resource.getUniqueId());
1468 if (eitherGetResource.isRight()) {
1469 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1470 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
1471 throw new ComponentException(responseFormat);
1473 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
1474 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1475 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
1476 BeEcompErrorManager.getInstance().logBeDaoSystemError(
1477 "Error when create resource instance from csar. ComponentInstances list empty");
1478 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
1480 return eitherGetResource.left().value();
1483 protected void handleNodeTypes(String yamlName, Resource resource,
1484 String topologyTemplateYaml, boolean needLock,
1485 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1486 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1487 CsarInfo csarInfo, String nodeName) {
1489 for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1490 if (nodeTypeEntry.getValue().isNested()) {
1492 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1493 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1494 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1497 Map<String, Object> mappedToscaTemplate = null;
1498 if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
1499 && nodeTypesInfo.containsKey(nodeName)) {
1500 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1502 if (MapUtils.isEmpty(mappedToscaTemplate)) {
1503 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1505 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1506 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1507 } catch (ComponentException e) {
1508 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
1509 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1510 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1512 } catch (StorageException e) {
1513 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1514 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1516 }catch (Exception e){
1517 log.debug("Exception occured when handleNodeTypes, error is:{}", e.getMessage(), e);
1518 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1522 protected Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1523 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1525 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1526 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1528 log.debug("************* Going to create node types from yaml {}", yamlName);
1529 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1530 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1532 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1533 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1534 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1535 csarInfo, nodeName, yamlName);
1540 protected Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1541 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1542 String nodeName, String yamlName) {
1543 Resource oldComplexVfc = null;
1544 Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1545 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1546 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1547 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1548 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1549 serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(),
1550 nodeName).getRight());
1552 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1553 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1554 } else if (oldComplexVfcRes.isLeft()) {
1555 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1556 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate(
1557 oldComplexVfcRes.left().value(), newComplexVfc,
1558 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1559 if (eitherValidation.isLeft()) {
1560 oldComplexVfc = oldComplexVfcRes.left().value();
1563 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1564 oldComplexVfc, newComplexVfc);
1565 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1566 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1567 CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1568 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1569 final Resource result = serviceImportParseLogic
1570 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1572 csarInfo.getCreatedNodes().put(nodeName, result);
1573 csarInfo.removeNodeFromQueue();
1577 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1578 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1579 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1580 CsarInfo csarInfo) {
1581 Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1582 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1583 if (toscaVersion.isRight()) {
1584 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1586 Map<String, Object> mapToConvert = new HashMap<>();
1587 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1588 Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
1589 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1590 return csarInfo.getCreatedNodes();
1593 protected void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1594 Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1595 Resource vfcCreated = null;
1596 while (nodesNameValueIter.hasNext()) {
1597 Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
1598 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1599 || nodeTypesArtifactsToHandle.isEmpty() ? null
1600 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1602 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1603 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1604 vfcCreated = handleNestedVfc(resource,
1605 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1607 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1608 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1609 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
1610 log.trace("************* Going to create node {}", nodeType.getKey());
1611 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
1612 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
1614 log.debug("************* Finished to create node {}", nodeType.getKey());
1616 vfcCreated = resourceCreated.getLeft();
1617 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
1618 vfcCreated.getToscaResourceName());
1620 if (vfcCreated != null) {
1621 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1623 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1627 protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1628 String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1629 Resource resourceVf, boolean needLock,
1630 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1631 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1633 UploadResourceInfo resourceMetaData = serviceImportParseLogic
1634 .fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1636 String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert,
1637 resourceMetaData.getResourceType(), csarInfo);
1638 user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1639 return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1640 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1641 nodeNameValue.getKey(), isNested);
1644 protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
1645 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1646 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1647 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1648 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1650 log.debug("************* Going to create all nodes {}", yamlName);
1651 handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
1652 log.debug("************* Going to create all resource instances {}", yamlName);
1653 service = createServiceInstances(yamlName, service, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1654 log.debug("************* Going to create all relations {}", yamlName);
1655 service = createServiceInstancesRelations(csarInfo.getModifier(), yamlName, service, uploadComponentInstanceInfoMap);
1656 log.debug("************* Going to create positions {}", yamlName);
1657 compositionBusinessLogic.setPositionsForComponentInstances(service, csarInfo.getModifier().getUserId());
1658 log.debug("************* Finished to set positions {}", yamlName);
1662 protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
1663 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1664 log.debug("#createResourceInstancesRelations - Going to create relations ");
1665 List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1666 if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances
1667 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", service.getUniqueId(), yamlName);
1668 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR);
1669 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1671 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1672 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1673 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1674 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1675 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1676 Map<String, List<AttributeDataDefinition>> instAttributes = new HashMap<>();
1677 Map<String, Resource> originCompMap = new HashMap<>();
1678 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1679 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1681 log.debug("enter ServiceImportBusinessLogic createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1682 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
1683 if (allDataTypes.isRight()) {
1684 JanusGraphOperationStatus status = allDataTypes.right().value();
1685 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
1686 "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
1687 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
1688 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
1690 Service finalResource = service;
1691 uploadResInstancesMap
1693 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
1694 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
1695 instArtifacts, instAttributes, originCompMap, instInputs, i));
1696 serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
1697 serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
1698 serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
1699 serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
1700 serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
1701 log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}",
1702 instRequirements, instCapabilities);
1703 serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
1704 ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
1705 Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
1706 Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
1708 serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
1709 serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
1710 service = getResourceAfterCreateRelations(service);
1712 addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
1713 serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
1714 handleSubstitutionMappings(service, uploadResInstancesMap);
1715 log.debug("************* in create relations, getResource start");
1716 Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1717 log.debug("************* in create relations, getResource end");
1718 if (eitherGetResource.isRight()) {
1719 throw new ComponentException(componentsUtils.getResponseFormatByComponent(
1720 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, service.getComponentType()));
1722 return eitherGetResource.left().value();
1725 protected void processComponentInstance(String yamlName, Service service,
1726 List<ComponentInstance> componentInstancesList,
1727 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
1728 Map<String, List<ComponentInstanceProperty>> instProperties,
1729 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1730 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
1731 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1732 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
1733 Map<String, List<AttributeDataDefinition>> instAttributes,
1734 Map<String, Resource> originCompMap,
1735 Map<String, List<ComponentInstanceInput>> instInputs,
1736 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
1737 log.debug("enter ServiceImportBusinessLogic processComponentInstance");
1738 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
1739 .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName()))
1741 if (!currentCompInstanceOpt.isPresent()) {
1742 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
1743 service.getUniqueId());
1744 BeEcompErrorManager.getInstance().logInternalDataError(
1745 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
1746 service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
1747 ResponseFormat responseFormat = componentsUtils
1748 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1749 throw new ComponentException(responseFormat);
1751 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
1752 String resourceInstanceId = currentCompInstance.getUniqueId();
1753 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
1755 if (MapUtils.isNotEmpty(originResource.getRequirements())) {
1756 instRequirements.put(currentCompInstance, originResource.getRequirements());
1758 if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
1759 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
1760 currentCompInstance, originResource);
1762 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
1763 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
1765 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
1766 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
1768 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
1769 instAttributes.put(resourceInstanceId, originResource.getAttributes());
1771 if (originResource.getResourceType() != ResourceTypeEnum.VF) {
1772 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, service,
1773 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
1774 if (addPropertiesValueToRiRes.getStatus() != 200) {
1775 throw new ComponentException(addPropertiesValueToRiRes);
1778 addInputsValuesToRi(uploadComponentInstanceInfo, service,
1779 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
1783 protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
1784 Service resource, Resource originResource, ComponentInstance currentCompInstance,
1785 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
1786 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1787 if (MapUtils.isNotEmpty(propMap)) {
1788 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
1789 List<ComponentInstanceInput> instPropList = new ArrayList<>();
1791 if (CollectionUtils.isEmpty(originResource.getInputs())) {
1792 log.debug("failed to find properties ");
1793 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
1795 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
1796 for (List<UploadPropInfo> propertyList : propMap.values()) {
1797 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
1799 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
1800 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
1804 protected void processProperty(Service resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
1805 UploadPropInfo propertyInfo = propertyList.get(0);
1806 String propName = propertyInfo.getName();
1807 if (!currPropertiesMap.containsKey(propName)) {
1808 log.debug("failed to find property {} ", propName);
1809 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
1812 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
1813 ComponentInstanceInput property = null;
1815 String value = null;
1816 List<GetInputValueDataDefinition> getInputs = null;
1817 boolean isValidate = true;
1818 if (propertyInfo.getValue() != null) {
1819 getInputs = propertyInfo.getGet_input();
1820 isValidate = getInputs == null || getInputs.isEmpty();
1822 value = getPropertyJsonStringValue(propertyInfo.getValue(),
1823 curPropertyDef.getType());
1825 value = getPropertyJsonStringValue(propertyInfo.getValue(),
1826 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1829 String innerType = null;
1830 property = new ComponentInstanceInput(curPropertyDef, value, null);
1831 String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1832 property.setValue(validPropertyVAlue);
1834 if (isNotEmpty(getInputs)) {
1835 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1836 for (GetInputValueDataDefinition getInput : getInputs) {
1837 List<InputDefinition> inputs = resource.getInputs();
1838 if (CollectionUtils.isEmpty(inputs)) {
1839 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1841 Optional<InputDefinition> optional = inputs.stream()
1842 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
1843 if (!optional.isPresent()) {
1844 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1846 InputDefinition input = optional.get();
1847 getInput.setInputId(input.getUniqueId());
1848 getInputValues.add(getInput);
1850 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1851 processGetInput(getInputValues, inputs, getInputIndex);
1853 property.setGetInputValues(getInputValues);
1855 instPropList.add(property);
1856 currPropertiesMap.remove(property.getName());
1859 protected void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
1860 Optional<InputDefinition> optional;
1861 if (getInputIndex != null) {
1862 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
1864 if (!optional.isPresent()) {
1865 log.debug("Failed to find input {} ", getInputIndex.getInputName());
1866 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1868 InputDefinition inputIndex = optional.get();
1869 getInputIndex.setInputId(inputIndex.getUniqueId());
1870 getInputValues.add(getInputIndex);
1874 protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
1875 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
1876 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
1877 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1878 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
1880 List<PropertyDefinition> listFromMap = originResource.getProperties();
1881 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
1882 log.debug("failed to find properties ");
1883 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
1885 if (listFromMap == null || listFromMap.isEmpty()) {
1886 return componentsUtils.getResponseFormat(ActionStatus.OK);
1888 for (PropertyDefinition prop : listFromMap) {
1889 String propName = prop.getName();
1890 if (!currPropertiesMap.containsKey(propName)) {
1891 currPropertiesMap.put(propName, prop);
1894 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
1895 if (propMap != null && propMap.size() > 0) {
1896 for (List<UploadPropInfo> propertyList : propMap.values()) {
1897 UploadPropInfo propertyInfo = propertyList.get(0);
1898 String propName = propertyInfo.getName();
1899 if (!currPropertiesMap.containsKey(propName)) {
1900 log.debug("failed to find property {} ", propName);
1901 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
1904 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
1905 ComponentInstanceProperty property = null;
1907 String value = null;
1908 List<GetInputValueDataDefinition> getInputs = null;
1909 boolean isValidate = true;
1910 if (propertyInfo.getValue() != null) {
1911 getInputs = propertyInfo.getGet_input();
1912 isValidate = getInputs == null || getInputs.isEmpty();
1914 value = getPropertyJsonStringValue(propertyInfo.getValue(),
1915 curPropertyDef.getType());
1917 value = getPropertyJsonStringValue(propertyInfo.getValue(),
1918 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1921 String innerType = null;
1922 property = new ComponentInstanceProperty(curPropertyDef, value, null);
1924 String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1925 property.setValue(validatePropValue);
1927 if (getInputs != null && !getInputs.isEmpty()) {
1928 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1929 for (GetInputValueDataDefinition getInput : getInputs) {
1930 List<InputDefinition> inputs = resource.getInputs();
1931 if (inputs == null || inputs.isEmpty()) {
1932 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
1933 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1935 .map(GetInputValueDataDefinition::getInputName)
1936 .collect(toList()).toString());
1938 InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
1939 getInput.setInputId(input.getUniqueId());
1940 getInputValues.add(getInput);
1942 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1943 if (getInputIndex != null) {
1944 input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
1945 getInputIndex.setInputId(input.getUniqueId());
1946 getInputValues.add(getInputIndex);
1949 property.setGetInputValues(getInputValues);
1951 instPropList.add(property);
1952 currPropertiesMap.remove(property.getName());
1955 if (!currPropertiesMap.isEmpty()) {
1956 for (PropertyDefinition value : currPropertiesMap.values()) {
1957 instPropList.add(new ComponentInstanceProperty(value));
1960 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
1961 return componentsUtils.getResponseFormat(ActionStatus.OK);
1964 protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
1965 Service service, Resource originResource, ComponentInstance currentCompInstance,
1966 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
1967 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1968 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
1970 List<PropertyDefinition> listFromMap = originResource.getProperties();
1971 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
1972 log.debug("failed to find properties ");
1973 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
1975 if (listFromMap == null || listFromMap.isEmpty()) {
1976 return componentsUtils.getResponseFormat(ActionStatus.OK);
1978 for (PropertyDefinition prop : listFromMap) {
1979 String propName = prop.getName();
1980 if (!currPropertiesMap.containsKey(propName)) {
1981 currPropertiesMap.put(propName, prop);
1984 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
1985 if (propMap != null && propMap.size() > 0) {
1986 for (List<UploadPropInfo> propertyList : propMap.values()) {
1988 UploadPropInfo propertyInfo = propertyList.get(0);
1989 String propName = propertyInfo.getName();
1990 if (!currPropertiesMap.containsKey(propName)) {
1991 log.debug("failed to find property {} ", propName);
1992 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
1995 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
1996 ComponentInstanceProperty property = null;
1998 String value = null;
1999 List<GetInputValueDataDefinition> getInputs = null;
2000 boolean isValidate = true;
2001 if (propertyInfo.getValue() != null) {
2002 getInputs = propertyInfo.getGet_input();
2003 isValidate = getInputs == null || getInputs.isEmpty();
2005 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2006 curPropertyDef.getType());
2008 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2009 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2012 String innerType = null;
2013 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2015 String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2016 property.setValue(validatePropValue);
2018 if (getInputs != null && !getInputs.isEmpty()) {
2019 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2020 for (GetInputValueDataDefinition getInput : getInputs) {
2021 List<InputDefinition> inputs = service.getInputs();
2022 if (inputs == null || inputs.isEmpty()) {
2023 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2024 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2026 .map(GetInputValueDataDefinition::getInputName)
2027 .collect(toList()).toString());
2029 InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
2030 getInput.setInputId(input.getUniqueId());
2031 getInputValues.add(getInput);
2033 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2034 if (getInputIndex != null) {
2035 input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
2036 getInputIndex.setInputId(input.getUniqueId());
2037 getInputValues.add(getInputIndex);
2040 property.setGetInputValues(getInputValues);
2042 instPropList.add(property);
2043 currPropertiesMap.remove(property.getName());
2046 if (!currPropertiesMap.isEmpty()) {
2047 for (PropertyDefinition value : currPropertiesMap.values()) {
2048 instPropList.add(new ComponentInstanceProperty(value));
2051 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2052 return componentsUtils.getResponseFormat(ActionStatus.OK);
2055 protected void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2056 log.debug("enter processComponentInstanceCapabilities");
2057 Map<String, List<CapabilityDefinition>> originCapabilities;
2058 if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2059 originCapabilities = new HashMap<>();
2060 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2061 originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic
2062 .addCapabilities(originCapabilities, k, v));
2063 uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> serviceImportParseLogic
2064 .addCapabilitiesProperties(newPropertiesMap, l));
2065 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2067 originCapabilities = originResource.getCapabilities();
2069 instCapabilties.put(currentCompInstance, originCapabilities);
2072 protected void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2073 originCapabilities.values().stream()
2074 .flatMap(Collection::stream)
2075 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2076 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2079 protected void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2080 Map<String, DataTypeDefinition> allDataTypes) {
2081 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2084 protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2085 Map<String, DataTypeDefinition> allDataTypes) {
2086 String value = null;
2087 List<GetInputValueDataDefinition> getInputs = null;
2088 boolean isValidate = true;
2089 if (null != propertyInfo && propertyInfo.getValue() != null) {
2090 getInputs = propertyInfo.getGet_input();
2091 isValidate = getInputs == null || getInputs.isEmpty();
2093 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2095 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2096 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2099 property.setValue(value);
2100 return serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2103 protected Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2104 Resource originResource;
2105 log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource");
2106 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2107 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2108 .getToscaFullElement(currentCompInstance.getComponentUid());
2109 if (getOriginResourceRes.isRight()) {
2110 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2111 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2112 throw new ComponentException(responseFormat);
2114 originResource = getOriginResourceRes.left().value();
2115 originCompMap.put(originResource.getUniqueId(), originResource);
2117 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2119 return originResource;
2122 protected void handleSubstitutionMappings(Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2124 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
2125 if (getResourceRes.isRight()) {
2126 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
2127 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE);
2128 throw new ComponentException(responseFormat);
2130 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2131 uploadResInstancesMap);
2132 if (getResourceRes.isRight()) {
2133 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
2134 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE);
2135 throw new ComponentException(responseFormat);
2140 protected Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2141 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2142 Either<Resource, StorageOperationStatus> updateRes = null;
2143 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2144 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2145 StorageOperationStatus status = toscaOperationFacade
2146 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2147 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2149 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2150 resource.getUniqueId(), status);
2151 updateRes = Either.right(status);
2153 if (updateRes == null) {
2154 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2155 updatedInstCapabilities, updatedInstRequirements);
2156 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2158 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2159 updateRes = Either.right(status);
2162 if (updateRes == null) {
2163 updateRes = Either.left(resource);
2168 protected void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2169 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2170 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2171 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2172 componentInstances.stream().forEach(i -> {
2173 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2174 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2175 fillUpdatedInstRequirements(updatedInstRequirements, i,
2176 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2180 protected void fillUpdatedInstCapabilities(
2181 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2182 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2183 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2184 Set<String> updatedCapNames = new HashSet<>();
2185 if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
2186 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2187 updatedCapabilities.put(requirements.getKey(),
2188 requirements.getValue().stream()
2189 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2190 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2192 c.setParentName(c.getName());
2193 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2194 updatedCapNames.add(c.getName());
2196 }).collect(toList()));
2199 if (MapUtils.isNotEmpty(updatedCapabilities)) {
2200 updatedInstCapabilties.put(instance, updatedCapabilities);
2204 protected void fillUpdatedInstRequirements(
2205 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2206 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2207 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2208 Set<String> updatedReqNames = new HashSet<>();
2209 if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
2210 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2211 updatedRequirements.put(requirements.getKey(),
2212 requirements.getValue().stream()
2213 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2214 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2216 r.setParentName(r.getName());
2217 r.setName(requirementsNamesToUpdate.get(r.getName()));
2218 updatedReqNames.add(r.getName());
2220 }).collect(toList()));
2223 if (MapUtils.isNotEmpty(updatedRequirements)) {
2224 updatedInstRequirements.put(instance, updatedRequirements);
2228 protected void addRelationsToRI(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2229 for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2230 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2231 ComponentInstance currentCompInstance = null;
2232 for (ComponentInstance compInstance : componentInstancesList) {
2233 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2234 currentCompInstance = compInstance;
2238 if (currentCompInstance == null) {
2239 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2240 service.getUniqueId());
2241 BeEcompErrorManager.getInstance().logInternalDataError(
2242 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2243 service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2244 ResponseFormat responseFormat = componentsUtils
2245 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2246 throw new ComponentException(responseFormat);
2249 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
2250 if (addRelationToRiRes.getStatus() != 200) {
2251 throw new ComponentException(addRelationToRiRes);
2256 protected ResponseFormat addRelationToRI(String yamlName, Service service,
2257 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2258 List<ComponentInstance> componentInstancesList = service.getComponentInstances();
2259 ComponentInstance currentCompInstance = null;
2260 for (ComponentInstance compInstance : componentInstancesList) {
2261 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2262 currentCompInstance = compInstance;
2266 if (currentCompInstance == null) {
2267 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2268 service.getUniqueId());
2269 BeEcompErrorManager.getInstance().logInternalDataError(
2270 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2271 service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2272 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2275 String resourceInstanceId = currentCompInstance.getUniqueId();
2276 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2278 if (regMap != null) {
2279 Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2280 while (nodesRegValue.hasNext()) {
2281 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2282 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2283 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2284 log.debug("Going to create relation {}", uploadRegInfo.getName());
2285 String regName = uploadRegInfo.getName();
2286 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2287 regCapRelDef.setFromNode(resourceInstanceId);
2288 log.debug("try to find available requirement {} ", regName);
2289 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic.findAviableRequiremen(regName,
2290 yamlName, nodesInfoValue, currentCompInstance,
2291 uploadRegInfo.getCapabilityName());
2292 if (eitherReqStatus.isRight()) {
2293 log.debug("failed to find available requirement {} status is {}", regName,
2294 eitherReqStatus.right().value());
2295 return eitherReqStatus.right().value();
2298 RequirementDefinition validReq = eitherReqStatus.left().value();
2299 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2300 .getRelationships();
2301 if (reqAndRelationshipPairList == null) {
2302 reqAndRelationshipPairList = new ArrayList<>();
2304 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2305 reqAndRelationshipPair.setRequirement(regName);
2306 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2307 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2308 RelationshipImpl relationship = new RelationshipImpl();
2309 relationship.setType(validReq.getCapability());
2310 reqAndRelationshipPair.setRelationships(relationship);
2312 ComponentInstance currentCapCompInstance = null;
2313 for (ComponentInstance compInstance : componentInstancesList) {
2314 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2315 currentCapCompInstance = compInstance;
2319 if (currentCapCompInstance == null) {
2320 log.debug("The component instance with name {} not found on resource {} ",
2321 uploadRegInfo.getNode(), service.getUniqueId());
2322 BeEcompErrorManager.getInstance().logInternalDataError(
2323 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2324 service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2325 return componentsUtils
2326 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2328 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2329 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2330 CapabilityDefinition aviableCapForRel = serviceImportParseLogic.findAvailableCapabilityByTypeOrName(validReq,
2331 currentCapCompInstance, uploadRegInfo);
2332 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2333 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2334 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2335 if (aviableCapForRel == null) {
2336 BeEcompErrorManager.getInstance().logInternalDataError(
2337 "aviable capability was not found. req name is " + validReq.getName()
2338 + " component instance is " + currentCapCompInstance.getUniqueId(),
2339 service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2340 return componentsUtils
2341 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2343 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2344 capReqRel.setRelation(reqAndRelationshipPair);
2345 reqAndRelationshipPairList.add(capReqRel);
2346 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2347 relations.add(regCapRelDef);
2351 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2354 protected Service getResourceAfterCreateRelations(Service service) {
2355 ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
2356 Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2357 .getToscaElement(service.getUniqueId(), parametersView);
2358 if (eitherGetResource.isRight()) {
2359 serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
2361 return eitherGetResource.left().value();
2364 protected Service createServiceInstances(String yamlName, Service service,
2365 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2366 Map<String, Resource> nodeNamespaceMap) {
2367 Either<Resource, ResponseFormat> eitherResource = null;
2368 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2369 if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances
2370 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2371 throw new ComponentException(responseFormat);
2373 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2374 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2375 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2377 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2378 uploadResInstancesMap
2380 .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2382 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
2384 toscaOperationFacade.associateComponentInstancesToComponent(service,
2385 resourcesInstancesMap, false, false);
2386 } catch (StorageException exp) {
2387 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
2388 log.debug("Failed to add component instances to container component {}", service.getName());
2389 ResponseFormat responseFormat = componentsUtils
2390 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
2391 eitherResource = Either.right(responseFormat);
2392 throw new ComponentException(eitherResource.right().value());
2396 Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2397 .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
2398 log.debug("*************finished to get resource {}", service.getUniqueId());
2399 if (eitherGetResource.isRight()) {
2400 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
2401 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, ComponentTypeEnum.SERVICE);
2402 throw new ComponentException(responseFormat);
2404 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
2405 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
2406 BeEcompErrorManager.getInstance().logBeDaoSystemError(
2407 "Error when create resource instance from csar. ComponentInstances list empty");
2408 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
2410 return eitherGetResource.left().value();
2413 protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
2414 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
2415 Either<Resource, ResponseFormat> eitherResource;
2416 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
2418 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2419 uploadComponentInstanceInfo
2420 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
2422 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
2423 existingnodeTypeMap);
2425 ComponentInstance componentInstance = new ComponentInstance();
2426 componentInstance.setComponentUid(refResource.getUniqueId());
2428 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
2429 if (directives != null && !directives.isEmpty()) {
2430 componentInstance.setDirectives(new ArrayList<>(directives));
2432 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
2433 if (uploadNodeFilterInfo != null) {
2434 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
2435 componentInstance.getUniqueId()));
2438 ComponentTypeEnum containerComponentType = resource.getComponentType();
2439 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
2440 if (containerNodeType.equals(NodeTypeEnum.Resource)
2441 && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
2442 && MapUtils.isNotEmpty(refResource.getCapabilities())) {
2443 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
2444 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic.getValidComponentInstanceCapabilities(
2445 refResource.getUniqueId(), refResource.getCapabilities(),
2446 uploadComponentInstanceInfo.getCapabilities());
2447 componentInstance.setCapabilities(validComponentInstanceCapabilities);
2449 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
2450 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2451 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2452 throw new ComponentException(responseFormat);
2454 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
2455 componentInstance.setName(uploadComponentInstanceInfo.getName());
2456 componentInstance.setIcon(origResource.getIcon());
2457 resourcesInstancesMap.put(componentInstance, origResource);
2458 } catch (Exception e) {
2459 throw new ComponentException(ActionStatus.GENERAL_ERROR,e.getMessage());
2463 protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
2464 Service service, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
2465 Either<Resource, ResponseFormat> eitherResource;
2466 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
2468 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2469 uploadComponentInstanceInfo
2470 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
2472 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
2473 existingnodeTypeMap);
2475 ComponentInstance componentInstance = new ComponentInstance();
2476 componentInstance.setComponentUid(refResource.getUniqueId());
2477 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
2478 if (directives != null && !directives.isEmpty()) {
2479 componentInstance.setDirectives(new ArrayList<>(directives));
2481 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
2482 if (uploadNodeFilterInfo != null) {
2483 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
2484 componentInstance.getUniqueId()));
2487 ComponentTypeEnum containerComponentType = service.getComponentType();
2488 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
2489 if (containerNodeType.equals(NodeTypeEnum.Resource)
2490 && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
2491 && MapUtils.isNotEmpty(refResource.getCapabilities())) {
2492 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
2493 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic.getValidComponentInstanceCapabilities(
2494 refResource.getUniqueId(), refResource.getCapabilities(),
2495 uploadComponentInstanceInfo.getCapabilities());
2496 componentInstance.setCapabilities(validComponentInstanceCapabilities);
2498 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
2500 "createResourceInstances - not found lates version for resource instance with name {} and type ",
2501 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2502 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2503 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2504 throw new ComponentException(responseFormat);
2506 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
2507 componentInstance.setName(uploadComponentInstanceInfo.getName());
2508 componentInstance.setIcon(origResource.getIcon());
2509 resourcesInstancesMap.put(componentInstance, origResource);
2510 } catch (Exception e) {
2511 throw new ComponentException(ActionStatus.GENERAL_ERROR,e.getMessage());
2515 protected Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
2516 Map<String, Resource> nodeNamespaceMap) {
2517 Resource refResource;
2519 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2520 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
2522 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
2523 .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
2524 if (findResourceEither.isRight()) {
2525 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2526 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
2527 throw new ComponentException(responseFormat);
2529 refResource = findResourceEither.left().value();
2530 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
2532 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
2533 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
2534 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
2535 refResource.getComponentType().getValue(), refResource.getName(), componentState);
2536 throw new ComponentException(responseFormat);
2538 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
2539 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
2540 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2541 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2542 throw new ComponentException(responseFormat);
2545 } catch (Exception e) {
2546 throw new ComponentException(ActionStatus.GENERAL_ERROR,e.getMessage());
2550 protected void handleServiceNodeTypes(String yamlName, Service service,
2551 String topologyTemplateYaml, boolean needLock,
2552 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2553 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2554 CsarInfo csarInfo, String nodeName) {
2556 for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2557 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
2558 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
2559 handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
2560 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
2561 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2564 Map<String, Object> mappedToscaTemplate = null;
2565 if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
2566 && nodeTypesInfo.containsKey(nodeName)) {
2567 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2569 if (MapUtils.isEmpty(mappedToscaTemplate)) {
2570 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2572 createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2573 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2574 } catch (ComponentException e) {
2576 } catch (StorageException e) {
2578 }catch (Exception e){
2579 log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e);
2580 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2584 protected boolean validateResourceNotExisted(String type) {
2586 Either<Resource, StorageOperationStatus> latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type);
2587 return latestResource.isRight() ? true : false;
2588 } catch (Exception e) {
2589 log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e);
2590 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2594 protected Resource handleNestedVF(Service service, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2595 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2598 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2599 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2601 createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false,
2602 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
2603 log.debug("************* Finished to create node types from yaml {}", yamlName);
2605 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2606 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2607 Resource resource = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2608 csarInfo, nodeName, yamlName);
2611 return new Resource();
2612 } catch (Exception e) {
2613 log.debug("Exception occured when handleNestedVF, error is:{}", e.getMessage(), e);
2614 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2618 protected Resource handleNestedVfc(Service service, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2619 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2622 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2623 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2624 createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false,
2625 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
2626 log.debug("************* Finished to create node types from yaml {}", yamlName);
2628 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2629 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2630 Resource resource = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2631 csarInfo, nodeName, yamlName);
2634 return new Resource();
2635 } catch (Exception e) {
2636 log.debug("Exception occured when handleNestedVFc, error is:{}", e.getMessage(), e);
2637 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2641 protected Resource handleComplexVfc(Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2642 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2643 String nodeName, String yamlName) {
2645 Resource oldComplexVfc = null;
2646 Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
2647 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
2648 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
2649 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
2650 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
2651 serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(),
2652 nodeName).getRight());
2654 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
2655 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
2656 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
2657 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2658 } else if (oldComplexVfcRes.isLeft()) {
2659 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
2660 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate(
2661 oldComplexVfcRes.left().value(), newComplexVfc,
2662 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
2663 if (eitherValidation.isLeft()) {
2664 oldComplexVfc = oldComplexVfcRes.left().value();
2667 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
2668 oldComplexVfc, newComplexVfc);
2669 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
2670 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
2671 CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
2672 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
2673 final Resource result = serviceImportParseLogic
2674 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
2676 csarInfo.getCreatedNodes().put(nodeName, result);
2677 csarInfo.removeNodeFromQueue();
2679 } catch (Exception e) {
2680 log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2681 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2685 protected Resource handleComplexVfc(Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2686 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2687 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
2688 Resource handleComplexVfcRes;
2690 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
2691 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
2692 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
2693 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
2694 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
2695 if (oldComplexVfc == null) {
2696 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
2697 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
2699 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
2700 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
2701 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
2703 return handleComplexVfcRes;
2704 } catch (Exception e) {
2705 log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2706 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2710 protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
2711 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
2712 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
2713 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2714 String nodeName, boolean isNested) {
2715 boolean inTransaction = true;
2716 boolean shouldLock = false;
2717 Resource preparedResource = null;
2718 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
2720 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource);
2721 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
2722 if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
2723 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
2725 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
2726 inTransaction, shouldLock, isNested).left;
2727 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
2728 serviceImportParseLogic.handleResourceGenericType(preparedResource);
2729 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
2730 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
2731 preparedResource = serviceImportParseLogic
2732 .createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
2733 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
2734 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
2735 } catch (ComponentException e) {
2736 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2737 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2738 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2740 } catch (StorageException e) {
2741 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2742 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2743 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2746 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
2747 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
2748 preparedResource.getSystemName());
2749 if (validateUpdateVfGroupNamesRes.isRight()) {
2750 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2752 Map<String, GroupDefinition> groups;
2753 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2754 groups = validateUpdateVfGroupNamesRes.left().value();
2756 groups = uploadComponentInstanceInfoMap.getGroups();
2758 serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
2759 preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
2760 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
2761 nodeTypesArtifactsToHandle);
2763 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(
2764 ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
2765 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2766 if (updateArtifactsEither.isRight()) {
2767 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
2768 throw new ComponentException(updateArtifactsEither.right().value());
2770 preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
2772 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
2773 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
2774 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
2776 throw new ComponentException(responseFormat);
2778 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
2779 return preparedResource;
2782 protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
2783 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2784 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2785 boolean shouldLock, boolean inTransaction, String nodeName) {
2786 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2787 Resource createdResource;
2789 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
2790 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
2791 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2793 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
2794 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
2795 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
2796 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
2797 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
2798 } catch (ComponentException e) {
2799 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2800 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2802 } catch (StorageException e) {
2803 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2804 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2807 return createdResource;
2810 protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
2811 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
2812 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
2813 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2814 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2815 boolean shouldLock, boolean inTransaction, String nodeName) {
2816 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
2818 Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(resource.getSystemName(), resource,
2820 if (lockResult.isRight()) {
2821 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2822 throw new ComponentException(lockResult.right().value());
2824 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
2827 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
2828 Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
2829 resource = createResourceTransaction(resource,
2830 csarInfo.getModifier(), isNormative);
2831 log.trace("************* Going to add inputs from yaml {}", yamlName);
2833 Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
2834 Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
2835 String type = (String) metadata.get("type");
2836 if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type))
2837 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
2838 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
2839 resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
2840 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
2842 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
2843 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2844 nodeTypesArtifactsToCreate, nodeName);
2845 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
2846 // validate update vf module group names
2847 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
2848 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
2849 if (validateUpdateVfGroupNamesRes.isRight()) {
2850 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2851 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2853 Map<String, GroupDefinition> groups;
2854 log.trace("************* Going to add groups from yaml {}", yamlName);
2856 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2857 groups = validateUpdateVfGroupNamesRes.left().value();
2859 groups = parsedToscaYamlInfo.getGroups();
2862 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
2864 if (createGroupsOnResource.isRight()) {
2865 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2866 throw new ComponentException(createGroupsOnResource.right().value());
2868 resource = createGroupsOnResource.left().value();
2869 log.trace("************* Going to add artifacts from yaml {}", yamlName);
2871 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
2873 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
2874 ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
2875 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2876 if (createArtifactsEither.isRight()) {
2877 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2878 throw new ComponentException(createArtifactsEither.right().value());
2881 resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
2882 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
2883 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
2884 ASDCKpiApi.countCreatedResourcesKPI();
2886 } catch (ComponentException | StorageException e) {
2887 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2890 if (!inTransaction) {
2891 serviceBusinessLogic.janusGraphDao.commit();
2894 serviceBusinessLogic.graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
2899 protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
2900 Map<String, GroupDefinition> groups) {
2901 if (groups != null && !groups.isEmpty()) {
2902 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
2904 serviceImportParseLogic.handleGroupsProperties(resource, groups);
2905 serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
2906 Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
2907 groupsAsList, true);
2908 if (createGroups.isRight()) {
2909 return Either.right(createGroups.right().value());
2912 return Either.left(resource);
2914 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
2915 .getToscaElement(resource.getUniqueId());
2916 if (updatedResource.isRight()) {
2917 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2918 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
2919 return Either.right(responseFormat);
2921 return Either.left(updatedResource.left().value());
2924 protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
2925 List<GroupDefinition> result = new ArrayList<>();
2926 List<ComponentInstance> componentInstances = component.getComponentInstances();
2928 if (groups != null) {
2929 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = serviceImportParseLogic.validateCyclicGroupsDependencies(groups);
2930 if (validateCyclicGroupsDependencies.isRight()) {
2931 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
2933 for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
2934 String groupName = entry.getKey();
2935 GroupDefinition groupDefinition = entry.getValue();
2936 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2937 updatedGroupDefinition.setMembers(null);
2938 Map<String, String> members = groupDefinition.getMembers();
2939 if (members != null) {
2940 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
2942 result.add(updatedGroupDefinition);
2948 protected void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
2949 Set<String> compInstancesNames = members.keySet();
2950 if (CollectionUtils.isEmpty(componentInstances)) {
2951 String membersAstString = compInstancesNames.stream().collect(joining(","));
2952 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
2953 membersAstString, groupName, component.getNormalizedName());
2954 throw new ComponentException(componentsUtils.getResponseFormat(
2955 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
2956 component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component)));
2958 Map<String, String> memberNames = componentInstances.stream()
2959 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2960 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
2961 Map<String, String> relevantInstances = memberNames.entrySet().stream()
2962 .filter(n -> compInstancesNames.contains(n.getKey()))
2963 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
2965 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2966 List<String> foundMembers = new ArrayList<>();
2967 if (relevantInstances != null) {
2968 foundMembers = relevantInstances.keySet().stream().collect(toList());
2970 compInstancesNames.removeAll(foundMembers);
2971 String membersAstString = compInstancesNames.stream().collect(joining(","));
2972 throw new ComponentException(componentsUtils.getResponseFormat(
2973 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
2974 component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component)));
2976 updatedGroupDefinition.setMembers(relevantInstances);
2979 protected Resource createResourceTransaction(Resource resource, User user,
2980 boolean isNormative) {
2981 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
2982 resource.getName(), resource.getResourceType(), resource.getComponentType());
2983 if (eitherValidation.isRight()) {
2984 ResponseFormat errorResponse = componentsUtils
2985 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
2986 throw new ComponentException(errorResponse);
2988 if (eitherValidation.left().value()) {
2989 log.debug("resource with name: {}, already exists", resource.getName());
2990 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
2991 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
2992 throw new ComponentException(errorResponse);
2994 log.debug("send resource {} to dao for create", resource.getName());
2995 serviceImportParseLogic.createArtifactsPlaceHolderData(resource, user);
2997 log.debug("enrich resource with creator, version and state");
2998 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2999 resource.setVersion(INITIAL_VERSION);
3000 resource.setHighestVersion(true);
3001 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.VF) {
3002 resource.setAbstract(false);
3005 return toscaOperationFacade.createToscaComponent(resource)
3007 .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
3010 protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3011 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3013 String lockedResourceId = oldResource.getUniqueId();
3014 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3015 oldResource.getVersion(), oldResource.getLifecycleState());
3016 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3018 serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3019 oldResource = serviceImportParseLogic
3020 .prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3021 serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
3022 serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3023 serviceImportParseLogic
3024 .validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3025 createNewResourceToOldResource(newResource, oldResource, user);
3027 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3028 .overrideComponent(newResource, oldResource);
3029 if (overrideResource.isRight()) {
3030 ResponseFormat responseFormat = new ResponseFormat();
3031 serviceBusinessLogic.throwComponentException(responseFormat);
3033 log.debug("Resource updated successfully!!!");
3034 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3036 return resourcePair;
3038 if (resourcePair == null) {
3039 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3040 serviceBusinessLogic.janusGraphDao.rollback();
3041 } else if (!inTransaction) {
3042 serviceBusinessLogic.janusGraphDao.commit();
3045 log.debug("unlock resource {}", lockedResourceId);
3046 serviceBusinessLogic.graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3051 protected void createNewResourceToOldResource(Resource newResource, Resource oldResource, User user) {
3052 newResource.setContactId(newResource.getContactId().toLowerCase());
3053 newResource.setCreatorUserId(user.getUserId());
3054 newResource.setCreatorFullName(user.getFullName());
3055 newResource.setLastUpdaterUserId(user.getUserId());
3056 newResource.setLastUpdaterFullName(user.getFullName());
3057 newResource.setUniqueId(oldResource.getUniqueId());
3058 newResource.setVersion(oldResource.getVersion());
3059 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3060 newResource.setLifecycleState(oldResource.getLifecycleState());
3061 newResource.setUUID(oldResource.getUUID());
3062 newResource.setNormalizedName(oldResource.getNormalizedName());
3063 newResource.setSystemName(oldResource.getSystemName());
3064 if (oldResource.getCsarUUID() != null) {
3065 newResource.setCsarUUID(oldResource.getCsarUUID());
3067 if (oldResource.getImportedToscaChecksum() != null) {
3068 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3070 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3071 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3073 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3074 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3076 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3077 serviceBusinessLogic.setToscaArtifactsPlaceHolders(newResource, user);
3079 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3080 newResource.setInterfaces(oldResource.getInterfaces());
3082 if (CollectionUtils.isEmpty(newResource.getProperties())) {
3083 newResource.setProperties(oldResource.getProperties());
3087 protected Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map<String, Object> mappedToscaTemplate, boolean needLock,
3088 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
3089 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
3090 CsarInfo csarInfo) {
3092 Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
3093 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
3094 if (toscaVersion.isRight()) {
3095 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
3097 Map<String, Object> mapToConvert = new HashMap<>();
3098 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
3099 Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
3100 createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
3101 return csarInfo.getCreatedNodes();
3102 } catch (Exception e) {
3103 log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}",e.getMessage(),e);
3104 throw new ComponentException(ActionStatus.GENERAL_ERROR);
3108 protected void createNodeTypes(String yamlName, Service service, boolean needLock, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
3109 Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
3110 Resource vfcCreated = null;
3111 while (nodesNameValueIter.hasNext()) {
3112 Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
3113 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
3114 || nodeTypesArtifactsToHandle.isEmpty() ? null
3115 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
3117 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
3118 vfcCreated = handleNestedVfc(service,
3119 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
3121 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
3122 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
3123 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
3124 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
3125 .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
3126 service, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
3128 log.debug("************* Finished to create node {}", nodeType.getKey());
3130 vfcCreated = resourceCreated.getLeft();
3131 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
3132 vfcCreated.getName());
3134 if (vfcCreated != null) {
3135 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
3137 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());