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;
23 import fj.data.Either;
24 import java.util.ArrayList;
25 import java.util.EnumMap;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.ListIterator;
31 import java.util.Optional;
33 import java.util.function.Function;
35 import org.apache.commons.codec.binary.Base64;
36 import org.apache.commons.collections.CollectionUtils;
37 import org.apache.commons.collections.MapUtils;
38 import org.apache.commons.lang3.StringUtils;
39 import org.apache.commons.lang3.tuple.ImmutablePair;
40 import org.openecomp.sdc.be.components.csar.CsarInfo;
41 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
42 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
43 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
44 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
45 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
46 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
47 import org.openecomp.sdc.be.config.BeEcompErrorManager;
48 import org.openecomp.sdc.be.config.ConfigurationManager;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterPropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
61 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
62 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
64 import org.openecomp.sdc.be.impl.ComponentsUtils;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.AttributeDefinition;
67 import org.openecomp.sdc.be.model.CapabilityDefinition;
68 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
69 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
70 import org.openecomp.sdc.be.model.Component;
71 import org.openecomp.sdc.be.model.ComponentInstance;
72 import org.openecomp.sdc.be.model.ComponentInstanceInput;
73 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
74 import org.openecomp.sdc.be.model.ComponentParametersView;
75 import org.openecomp.sdc.be.model.GroupDefinition;
76 import org.openecomp.sdc.be.model.InputDefinition;
77 import org.openecomp.sdc.be.model.InterfaceDefinition;
78 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
79 import org.openecomp.sdc.be.model.LifecycleStateEnum;
80 import org.openecomp.sdc.be.model.NodeTypeInfo;
81 import org.openecomp.sdc.be.model.Operation;
82 import org.openecomp.sdc.be.model.OutputDefinition;
83 import org.openecomp.sdc.be.model.PropertyDefinition;
84 import org.openecomp.sdc.be.model.RelationshipImpl;
85 import org.openecomp.sdc.be.model.RelationshipInfo;
86 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
87 import org.openecomp.sdc.be.model.RequirementDefinition;
88 import org.openecomp.sdc.be.model.Resource;
89 import org.openecomp.sdc.be.model.Service;
90 import org.openecomp.sdc.be.model.UploadCapInfo;
91 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
92 import org.openecomp.sdc.be.model.UploadInfo;
93 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
94 import org.openecomp.sdc.be.model.UploadPropInfo;
95 import org.openecomp.sdc.be.model.UploadReqInfo;
96 import org.openecomp.sdc.be.model.UploadResourceInfo;
97 import org.openecomp.sdc.be.model.User;
98 import org.openecomp.sdc.be.model.category.CategoryDefinition;
99 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
100 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
101 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
102 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
103 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
104 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
105 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
106 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
107 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
108 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
109 import org.openecomp.sdc.be.tosca.CsarUtils;
110 import org.openecomp.sdc.be.utils.CommonBeUtils;
111 import org.openecomp.sdc.be.utils.TypeUtils;
112 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
113 import org.openecomp.sdc.common.api.Constants;
114 import org.openecomp.sdc.common.log.wrappers.Logger;
115 import org.openecomp.sdc.common.util.GeneralUtility;
116 import org.openecomp.sdc.common.util.ValidationUtils;
117 import org.openecomp.sdc.exception.ResponseFormat;
118 import org.yaml.snakeyaml.DumperOptions;
119 import org.yaml.snakeyaml.Yaml;
122 @org.springframework.stereotype.Component
123 public class ServiceImportParseLogic {
125 private static final String INITIAL_VERSION = "0.1";
126 private static final String CREATE_RESOURCE = "Create Resource";
127 private static final String IN_RESOURCE = " in resource {} ";
128 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
129 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
130 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
131 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
132 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
133 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
134 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
135 private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class);
136 private final ServiceBusinessLogic serviceBusinessLogic;
137 private final ComponentsUtils componentsUtils;
138 private final ToscaOperationFacade toscaOperationFacade;
139 private final LifecycleBusinessLogic lifecycleBusinessLogic;
140 private final InputsBusinessLogic inputsBusinessLogic;
141 private final ResourceImportManager resourceImportManager;
142 private final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic;
143 private final IInterfaceLifecycleOperation interfaceTypeOperation;
144 private final ICapabilityTypeOperation capabilityTypeOperation;
145 private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
146 private final GroupBusinessLogic groupBusinessLogic;
147 private final OutputsBusinessLogic outputsBusinessLogic;
149 public ServiceImportParseLogic(final ServiceBusinessLogic serviceBusinessLogic, final ComponentsUtils componentsUtils,
150 final ToscaOperationFacade toscaOperationFacade, final LifecycleBusinessLogic lifecycleBusinessLogic,
151 final InputsBusinessLogic inputsBusinessLogic, final ResourceImportManager resourceImportManager,
152 final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic,
153 final IInterfaceLifecycleOperation interfaceTypeOperation, final ICapabilityTypeOperation capabilityTypeOperation,
154 final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic,
155 final GroupBusinessLogic groupBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic) {
156 this.serviceBusinessLogic = serviceBusinessLogic;
157 this.componentsUtils = componentsUtils;
158 this.toscaOperationFacade = toscaOperationFacade;
159 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
160 this.inputsBusinessLogic = inputsBusinessLogic;
161 this.resourceImportManager = resourceImportManager;
162 this.substitutionFilterBusinessLogic = substitutionFilterBusinessLogic;
163 this.interfaceTypeOperation = interfaceTypeOperation;
164 this.capabilityTypeOperation = capabilityTypeOperation;
165 this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
166 this.groupBusinessLogic = groupBusinessLogic;
167 this.outputsBusinessLogic = outputsBusinessLogic;
170 public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
171 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
172 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
173 Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
174 .left(nodeTypesArtifactsToHandle);
176 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
177 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
178 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
179 csarInfo.getCsarUUID());
180 extractedVfcToscaNames.forEach(
181 (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
182 extractedVfcsArtifacts, namespace, vfcToscaNames));
183 } catch (Exception e) {
184 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
185 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
186 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
188 return nodeTypesArtifactsToHandleRes;
191 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
193 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
194 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
195 if (!nodes.isEmpty()) {
196 Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
197 while (nodesNameEntry.hasNext()) {
198 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
199 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
201 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
204 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
205 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
207 return vfcToscaNames;
210 public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
212 // We need to create a Yaml from each node_types in order to create
214 // resource from each node type using import normative flow.
215 DumperOptions options = new DumperOptions();
216 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
217 Yaml yaml = new Yaml(options);
218 Map<String, Object> node = new HashMap<>();
219 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
220 nodeNameValue.getValue());
221 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
222 return yaml.dumpAsMap(mapToConvert);
225 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
228 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
229 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
230 actualType = ResourceTypeEnum.VFC.name();
232 actualVfName = vfResourceName;
233 actualType = nodeResourceType;
235 String nameWithouNamespacePrefix;
237 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
238 if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
239 nameWithouNamespacePrefix = nodeTypeFullName;
241 nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
243 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
244 String resourceType = findTypes[0];
245 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
246 if (actualName.startsWith(Constants.ABSTRACT)) {
247 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
249 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
251 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
252 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
253 previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
254 } catch (Exception e) {
255 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
256 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
257 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
261 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
262 Map<String, Object> nodes = new HashMap<>();
263 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
264 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
266 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
270 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
271 Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
272 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
273 if (eitherNodeTypes.isLeft()) {
274 nodes.putAll(eitherNodeTypes.left().value());
278 protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
279 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
280 Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
281 ImmutablePair<String, String> vfcToscaNames) {
282 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
283 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
284 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
285 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
286 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
287 if (extractedVfcsArtifacts.containsKey(namespace)) {
288 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
290 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
291 } else if (curNodeType != null) {
292 // delete all artifacts if have not received artifacts from
296 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
297 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
298 // delete all informational artifacts
299 artifactsToDelete.addAll(
300 curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
302 // delete all deployment artifacts
303 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
304 if (!artifactsToDelete.isEmpty()) {
305 curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
307 } catch (Exception e) {
308 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
309 log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
310 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft());
313 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
314 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
318 protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
319 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
320 artifactsToAdd.stream().forEach(a -> {
321 if (!vfcArtifactNames.contains(a.getArtifactName())) {
324 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
329 protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName,
330 StorageOperationStatus status) {
331 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
332 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
333 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
334 } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
335 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
336 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
341 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
342 List<ArtifactDefinition> extractedArtifacts) {
343 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
345 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
346 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
347 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
348 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
349 collectExistingArtifacts(curNodeType));
350 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
351 } catch (Exception e) {
352 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
353 throw new ComponentException(ActionStatus.GENERAL_ERROR);
355 return nodeTypeArtifactsToHandle;
358 protected Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
359 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
360 if (curNodeType == null) {
361 return existingArtifacts;
363 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
364 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
366 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
367 existingArtifacts.putAll(
368 curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
369 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
371 return existingArtifacts;
374 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
375 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
376 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
377 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
378 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
379 if (!artifactsToUpload.isEmpty()) {
380 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
382 if (!artifactsToUpdate.isEmpty()) {
383 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
385 if (!artifactsToDelete.isEmpty()) {
386 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
389 return nodeTypeArtifactsToHandle;
392 protected void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
393 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
394 Map<String, ArtifactDefinition> existingArtifacts) {
396 if (!existingArtifacts.isEmpty()) {
397 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
398 artifactsToDelete.addAll(existingArtifacts.values());
400 } catch (Exception e) {
401 log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
402 throw new ComponentException(ActionStatus.GENERAL_ERROR);
406 protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
407 Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
408 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
409 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
410 if (foundArtifact.isPresent()) {
411 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
412 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
413 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
414 artifactsToUpload.remove(currNewArtifact);
416 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
417 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
418 currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
423 protected void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
424 ArtifactDefinition foundArtifact) {
425 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
426 foundArtifact.setPayload(currNewArtifact.getPayloadData());
427 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
428 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
429 artifactsToUpdate.add(foundArtifact);
433 public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
434 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
435 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
436 && eitherNonMetaArtifacts.isLeft()) {
437 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
438 if (eitherResult.isLeft()) {
439 createdArtifacts.add(eitherResult.left().value());
444 public boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
445 return !org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
448 public void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
449 groupsAsList.forEach(groupDefinition -> {
450 groupDefinition.setInvariantName(groupDefinition.getName());
451 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
455 public String getComponentTypeForResponse(Component component) {
456 String componentTypeForResponse = "SERVICE";
457 if (component instanceof Resource) {
458 componentTypeForResponse = ((Resource) component).getResourceType().name();
460 return componentTypeForResponse;
463 public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
464 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
465 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
466 csarInfo.addNodeToQueue(nodeName);
467 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
470 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
472 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
473 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
474 validateLifecycleTypesCreate(user, resource, actionEnum);
475 validateResourceType(user, resource, actionEnum);
476 resource.setCreatorUserId(user.getUserId());
477 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
478 resource.setContactId(resource.getContactId().toLowerCase());
479 if (org.apache.commons.lang.StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
480 String resourceSystemName;
481 if (csarInfo != null && org.apache.commons.lang.StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
482 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
484 resourceSystemName = resource.getSystemName();
487 .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
489 // Generate invariant UUID - must be here and not in operation since it
491 // should stay constant during clone
494 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
495 resource.setInvariantUUID(invariantUUID);
499 protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
500 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
501 if (resource.getResourceType() == null) {
502 log.debug("Invalid resource type for resource");
503 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
504 eitherResult = Either.right(errorResponse);
505 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
510 protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
511 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
512 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
513 log.debug("validate interface lifecycle Types Exist");
514 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
515 while (intItr.hasNext() && eitherResult.isLeft()) {
516 InterfaceDefinition interfaceDefinition = intItr.next();
517 String intType = interfaceDefinition.getUniqueId();
518 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(
519 UniqueIdBuilder.buildInterfaceTypeUid(resource.getModel(), intType));
520 if (eitherCapTypeFound.isRight()) {
521 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
522 BeEcompErrorManager.getInstance()
523 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
524 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
525 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
526 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
528 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
529 eitherResult = Either.right(errorResponse);
530 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
537 public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
538 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
539 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
540 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
541 log.debug("validate capability Types Exist - capabilities section");
542 for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
543 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
545 if (eitherResult.isRight()) {
546 return Either.right(eitherResult.right().value());
550 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
551 log.debug("validate capability Types Exist - requirements section");
552 for (String type : resource.getRequirements().keySet()) {
553 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
554 eitherResult, type, inTransaction);
555 if (eitherResult.isRight()) {
556 return Either.right(eitherResult.right().value());
563 protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
564 Resource resource, AuditingActionEnum actionEnum,
565 Either<Boolean, ResponseFormat> eitherResult,
566 Map.Entry<String, List<CapabilityDefinition>> typeEntry,
567 boolean inTransaction) {
568 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
569 .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
570 if (eitherCapTypeFound.isRight()) {
571 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
572 BeEcompErrorManager.getInstance()
573 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
574 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
575 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
577 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
578 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
579 eitherResult = Either.right(errorResponse);
580 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
581 return Either.right(eitherResult.right().value());
583 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
584 if (capabilityTypeDefinition.getProperties() != null) {
585 for (CapabilityDefinition capDef : typeEntry.getValue()) {
586 List<ComponentInstanceProperty> properties = capDef.getProperties();
587 if (properties == null || properties.isEmpty()) {
588 properties = new ArrayList<>();
589 for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
590 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
591 properties.add(newProp);
594 for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
595 PropertyDefinition porpFromDef = prop.getValue();
596 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
597 for (ComponentInstanceProperty cip : properties) {
598 if (!cip.getName().equals(porpFromDef.getName())) {
599 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
600 propsToAdd.add(newProp);
603 if (!propsToAdd.isEmpty()) {
604 properties.addAll(propsToAdd);
608 capDef.setProperties(properties);
614 protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
615 Resource resource, List<?> validationObjects,
616 AuditingActionEnum actionEnum,
617 Either<Boolean, ResponseFormat> eitherResult, String type,
618 boolean inTransaction) {
620 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
621 .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
622 if (eitherCapTypeFound.isRight()) {
623 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
624 BeEcompErrorManager.getInstance()
625 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
626 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
627 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
629 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
630 ResponseFormat errorResponse = null;
632 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
634 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
636 eitherResult = Either.right(errorResponse);
637 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
639 } catch (Exception e) {
640 log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
641 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
646 protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum,
647 boolean inTransaction) {
648 serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
650 log.debug("validate category");
651 validateCategory(user, resource, actionEnum, inTransaction);
652 // validate vendor name & release & model number
653 log.debug("validate vendor name");
654 validateVendorName(user, resource, actionEnum);
655 log.debug("validate vendor release");
656 validateVendorReleaseName(user, resource, actionEnum);
657 log.debug("validate resource vendor model number");
658 validateResourceVendorModelNumber(user, resource, actionEnum);
660 log.debug("validate cost");
661 validateCost(resource);
662 // validate licenseType
663 log.debug("validate licenseType");
664 validateLicenseType(user, resource, actionEnum);
665 // validate template (derived from)
666 log.debug("validate derived from");
667 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.VF) {
668 resource.setDerivedFrom(null);
670 validateDerivedFromExist(user, resource, actionEnum);
671 serviceBusinessLogic.checkComponentFieldsForOverrideAttempt(resource);
672 String currentCreatorFullName = resource.getCreatorFullName();
673 if (currentCreatorFullName != null) {
674 log.debug("Resource Creator fullname is automatically set and cannot be updated");
676 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
677 if (currentLastUpdaterFullName != null) {
678 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
680 Long currentLastUpdateDate = resource.getLastUpdateDate();
681 if (currentLastUpdateDate != null) {
682 log.debug("Resource last update date is automatically set and cannot be updated");
684 Boolean currentAbstract = resource.isAbstract();
685 if (currentAbstract != null) {
686 log.debug("Resource abstract is automatically set and cannot be updated");
688 return Either.left(true);
691 protected void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
692 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
695 String templateName = resource.getDerivedFrom().get(0);
696 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
697 if (dataModelResponse.isRight()) {
698 StorageOperationStatus storageStatus = dataModelResponse.right().value();
699 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
700 log.debug("request to data model failed with error: {}", storageStatus);
701 ResponseFormat responseFormat = componentsUtils
702 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
703 log.trace("audit before sending response");
704 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
705 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
706 } else if (!dataModelResponse.left().value()) {
707 log.info("resource template with name: {}, does not exists", templateName);
708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
709 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
710 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
714 protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
715 log.debug("validate licenseType");
716 String licenseType = resource.getLicenseType();
717 if (licenseType != null) {
718 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
719 if (!licenseTypes.contains(licenseType)) {
720 log.debug("License type {} isn't configured", licenseType);
721 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
722 if (actionEnum != null) {
723 // In update case, no audit is required
724 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
726 throw new ComponentException(ActionStatus.INVALID_CONTENT);
731 protected void validateCost(Resource resource) {
732 String cost = resource.getCost();
734 if (!ValidationUtils.validateCost(cost)) {
735 log.debug("resource cost is invalid.");
736 throw new ComponentException(ActionStatus.INVALID_CONTENT);
741 protected void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
742 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
743 if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
744 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
745 log.info("resource vendor model number exceeds limit.");
746 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
747 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
748 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
749 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
750 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
752 // resource vendor model number is currently validated as vendor
755 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
756 log.info("resource vendor model number is not valid.");
757 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
758 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
759 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
764 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
765 String vendorRelease = resource.getVendorRelease();
766 log.debug("validate vendor relese name");
767 if (StringUtils.isEmpty(vendorRelease)) {
768 log.info("vendor relese name is missing.");
769 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
770 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
771 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
773 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
776 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
777 if (vendorRelease != null) {
778 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
779 log.info("vendor release exceds limit.");
780 ResponseFormat errorResponse = componentsUtils
781 .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
782 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
783 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
785 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
786 log.info("vendor release is not valid.");
787 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
788 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
789 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
794 protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
795 List<CategoryDefinition> categories = resource.getCategories();
796 if (CollectionUtils.isEmpty(categories)) {
797 log.debug(CATEGORY_IS_EMPTY);
798 ResponseFormat responseFormat = componentsUtils
799 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
800 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
801 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
803 if (categories.size() > 1) {
804 log.debug("Must be only one category for resource");
805 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
807 CategoryDefinition category = categories.get(0);
808 List<SubCategoryDefinition> subcategories = category.getSubcategories();
809 if (CollectionUtils.isEmpty(subcategories)) {
810 log.debug("Missinig subcategory for resource");
811 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
813 if (subcategories.size() > 1) {
814 log.debug("Must be only one sub category for resource");
815 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
817 SubCategoryDefinition subcategory = subcategories.get(0);
818 if (StringUtils.isEmpty(category.getName())) {
819 log.debug(CATEGORY_IS_EMPTY);
820 ResponseFormat responseFormat = componentsUtils
821 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
822 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
823 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
825 if (StringUtils.isEmpty(subcategory.getName())) {
826 log.debug(CATEGORY_IS_EMPTY);
827 ResponseFormat responseFormat = componentsUtils
828 .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
829 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
830 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
832 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
835 protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
836 AuditingActionEnum actionEnum, boolean inTransaction) {
837 ResponseFormat responseFormat;
838 if (category != null && subcategory != null) {
840 log.debug("validating resource category {} against valid categories list", category);
841 Either<List<CategoryDefinition>, ActionStatus> categories = serviceBusinessLogic.elementDao
842 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
843 if (categories.isRight()) {
844 log.debug("failed to retrieve resource categories from Titan");
845 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
846 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
847 throw new ComponentException(categories.right().value());
849 List<CategoryDefinition> categoryList = categories.left().value();
850 Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
852 if (!foundCategory.isPresent()) {
853 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
854 failOnInvalidCategory(user, resource, actionEnum);
856 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
857 .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
858 if (!foundSubcategory.isPresent()) {
859 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
860 foundCategory.get().getSubcategories());
861 failOnInvalidCategory(user, resource, actionEnum);
863 } catch (Exception e) {
864 log.debug("Exception occured when validateCategoryListed, error is:{}", e.getMessage(), e);
865 throw new ComponentException(ActionStatus.GENERAL_ERROR);
870 protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
871 ResponseFormat responseFormat;
872 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
873 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
874 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
877 protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
878 String vendorName = resource.getVendorName();
879 if (StringUtils.isEmpty(vendorName)) {
880 log.info("vendor name is missing.");
881 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
882 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
883 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
885 validateVendorName(vendorName, user, resource, actionEnum);
888 protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
889 if (vendorName != null) {
890 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
891 log.info("vendor name exceds limit.");
892 ResponseFormat errorResponse = componentsUtils
893 .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
894 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
895 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
897 if (!ValidationUtils.validateVendorName(vendorName)) {
898 log.info("vendor name is not valid.");
899 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
900 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
901 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
906 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
907 Resource cvfc = new Resource();
908 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
909 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
910 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
911 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
912 cvfc.setResourceType(ResourceTypeEnum.VF);
913 cvfc.setAbstract(true);
914 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
915 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
916 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
917 cvfc.setContactId(csarInfo.getModifier().getUserId());
918 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
919 cvfc.setVendorName(resourceVf.getVendorName());
920 cvfc.setTenant(resourceVf.getTenant());
921 cvfc.setVendorRelease(resourceVf.getVendorRelease());
922 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
923 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
924 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
925 List<String> tags = new ArrayList<>();
926 tags.add(cvfc.getName());
928 CategoryDefinition category = new CategoryDefinition();
929 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
930 SubCategoryDefinition subCategory = new SubCategoryDefinition();
931 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
932 category.addSubCategory(subCategory);
933 List<CategoryDefinition> categories = new ArrayList<>();
934 categories.add(category);
935 cvfc.setCategories(categories);
936 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
937 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
938 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
942 private String buildCvfcName(String resourceVfName, String nodeName) {
943 String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
944 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
945 String resourceType = findTypes[0];
946 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
947 return addCvfcSuffixToResourceName(resourceName);
950 private String addCvfcSuffixToResourceName(String resourceName) {
951 return resourceName + "VF";
954 public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
955 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
956 // validate nodetype name prefix
957 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
958 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
959 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
961 String actualName = this.getNodeTypeActualName(nodeName);
962 String namePrefix = nodeName.replace(actualName, "");
963 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
964 // if we import from csar, the node_type name can be
966 // org.openecomp.resource.abstract.node_name - in this case we always
969 if (resourceType.equals(Constants.ABSTRACT)) {
970 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
973 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
974 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
975 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
978 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
979 // Setting type from name
980 String type = resourceType.toUpperCase();
981 resourceMetaData.setResourceType(type);
982 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
983 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
984 resourceMetaData.setContactId(user.getUserId());
985 resourceMetaData.setVendorName(resourceVf.getVendorName());
986 resourceMetaData.setTenant(resourceVf.getTenant());
987 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
989 List<String> tags = new ArrayList<>();
990 tags.add(resourceMetaData.getName());
991 resourceMetaData.setTags(tags);
993 CategoryDefinition category = new CategoryDefinition();
994 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
995 SubCategoryDefinition subCategory = new SubCategoryDefinition();
996 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
997 category.addSubCategory(subCategory);
998 List<CategoryDefinition> categories = new ArrayList<>();
999 categories.add(category);
1000 resourceMetaData.setCategories(categories);
1001 return resourceMetaData;
1004 protected String getNodeTypeActualName(String fullName) {
1005 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1006 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1007 String resourceType = findTypes[0];
1008 return nameWithouNamespacePrefix.substring(resourceType.length());
1011 public void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
1012 String propName = prop.getName();
1013 if (!currPropertiesMap.containsKey(propName)) {
1014 currPropertiesMap.put(propName, prop);
1018 public Either<RequirementDefinition, ResponseFormat> findAvailableRequirement(String regName, String yamlName,
1019 UploadComponentInstanceInfo uploadComponentInstanceInfo,
1020 ComponentInstance currentCompInstance, String capName) {
1021 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
1022 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
1023 RequirementDefinition validRegDef = null;
1025 for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
1026 for (RequirementDefinition reqDef : entry.getValue()) {
1027 if (reqDef.getName().equals(regName)) {
1028 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1029 String leftOccurrences = reqDef.getLeftOccurrences();
1030 if (leftOccurrences == null) {
1031 leftOccurrences = reqDef.getMaxOccurrences();
1033 int left = Integer.parseInt(leftOccurrences);
1036 reqDef.setLeftOccurrences(String.valueOf(left));
1037 validRegDef = reqDef;
1041 validRegDef = reqDef;
1046 if (validRegDef != null) {
1051 for (RequirementDefinition reqDef : list) {
1052 if (reqDef.getName().equals(regName)) {
1053 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1054 String leftOccurrences = reqDef.getLeftOccurrences();
1055 if (leftOccurrences == null) {
1056 leftOccurrences = reqDef.getMaxOccurrences();
1058 int left = Integer.parseInt(leftOccurrences);
1061 reqDef.setLeftOccurrences(String.valueOf(left));
1062 validRegDef = reqDef;
1066 validRegDef = reqDef;
1072 if (validRegDef == null) {
1073 ResponseFormat responseFormat = componentsUtils
1074 .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
1075 uploadComponentInstanceInfo.getType());
1076 return Either.right(responseFormat);
1078 return Either.left(validRegDef);
1081 public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1082 UploadReqInfo uploadReqInfo) {
1084 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
1085 // get by capability type
1086 return findAvailableCapability(validReq, currentCapCompInstance);
1088 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
1089 } catch (Exception e) {
1090 log.debug("Exception occured when findAvailableCapabilityByTypeOrName, error is:{}", e.getMessage(), e);
1091 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1095 protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
1096 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
1097 if (capMap.containsKey(validReq.getCapability())) {
1098 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
1099 for (CapabilityDefinition cap : capList) {
1100 if (isBoundedByOccurrences(cap)) {
1101 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
1102 int left = Integer.parseInt(leftOccurrences);
1105 cap.setLeftOccurrences(String.valueOf(left));
1116 protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1117 UploadReqInfo uploadReqInfo) {
1118 CapabilityDefinition cap = null;
1119 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
1120 if (!capMap.containsKey(validReq.getCapability())) {
1123 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
1124 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
1125 if (!capByName.isPresent()) {
1128 cap = capByName.get();
1129 if (isBoundedByOccurrences(cap)) {
1130 String leftOccurrences = cap.getLeftOccurrences();
1131 int left = Integer.parseInt(leftOccurrences);
1134 cap.setLeftOccurrences(String.valueOf(left));
1140 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
1141 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
1144 public ComponentParametersView getComponentFilterAfterCreateRelations() {
1145 ComponentParametersView parametersView = new ComponentParametersView();
1146 parametersView.disableAll();
1147 parametersView.setIgnoreComponentInstances(false);
1148 parametersView.setIgnoreComponentInstancesProperties(false);
1149 parametersView.setIgnoreCapabilities(false);
1150 parametersView.setIgnoreRequirements(false);
1151 parametersView.setIgnoreGroups(false);
1152 return parametersView;
1155 public ComponentParametersView getComponentWithInstancesFilter() {
1156 ComponentParametersView parametersView = new ComponentParametersView();
1157 parametersView.disableAll();
1158 parametersView.setIgnoreComponentInstances(false);
1159 parametersView.setIgnoreInputs(false);
1160 // inputs are read when creating
1162 // property values on instances
1163 parametersView.setIgnoreUsers(false);
1164 return parametersView;
1167 protected void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
1168 Map<String, List<CapabilityDefinition>> defaultCapabilities,
1169 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
1170 String capabilityType = capabilities.get(0).getType();
1171 if (defaultCapabilities.containsKey(capabilityType)) {
1172 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
1173 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
1174 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
1175 validCapabilityList.add(defaultCapability);
1176 validCapabilitiesMap.put(key, validCapabilityList);
1178 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
1182 protected CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
1183 String capabilityType) {
1184 CapabilityDefinition defaultCapability;
1185 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
1186 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
1188 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
1189 if (getFullComponentRes.isRight()) {
1190 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
1191 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId));
1193 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
1195 return defaultCapability;
1198 protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
1199 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
1200 log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
1201 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
1202 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
1203 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
1204 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
1208 protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
1209 UploadCapInfo uploadedCapability) {
1210 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
1211 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
1212 .collect(toMap(PropertyDefinition::getName, Function.identity()));
1213 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
1214 for (UploadPropInfo property : uploadedProperties) {
1215 String propertyName = property.getName().toLowerCase();
1216 String propertyType = property.getType();
1217 ComponentInstanceProperty validProperty;
1218 if (defaultProperties.containsKey(propertyName) && propertyTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
1219 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName));
1221 validProperty = new ComponentInstanceProperty();
1222 validProperty.setName(propertyName);
1223 if (property.getValue() != null) {
1224 validProperty.setValue(property.getValue().toString());
1226 validProperty.setDescription(property.getDescription());
1227 validProperty.setPassword(property.isPassword());
1228 validProperties.add(validProperty);
1230 defaultCapability.setProperties(validProperties);
1233 private boolean propertyTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
1234 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
1237 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1238 if (component instanceof Service) {
1239 Service service = (Service) component;
1240 Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
1241 if (artifactMap == null) {
1242 artifactMap = new HashMap<>();
1244 service.setDeploymentArtifacts(artifactMap);
1245 } else if (component instanceof Resource) {
1246 Resource resource = (Resource) component;
1247 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
1248 if (artifactMap == null) {
1249 artifactMap = new HashMap<>();
1251 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1252 .getDeploymentResourceArtifacts();
1253 if (deploymentResourceArtifacts != null) {
1254 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
1255 deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
1257 resource.setDeploymentArtifacts(artifactMap);
1261 protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
1262 boolean shouldCreateArtifact = true;
1263 Map<String, Object> artifactDetails = (Map<String, Object>) v;
1264 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
1265 if (object != null) {
1266 List<String> artifactTypes = (List<String>) object;
1267 if (!artifactTypes.contains(resource.getResourceType().name())) {
1271 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
1273 if (shouldCreateArtifact) {
1274 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1275 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1276 .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
1277 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
1278 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1284 public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
1285 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
1286 newResource.setTags(oldResource.getTags());
1288 if (newResource.getDescription() == null) {
1289 newResource.setDescription(oldResource.getDescription());
1291 if (newResource.getContactId() == null) {
1292 newResource.setContactId(oldResource.getContactId());
1294 newResource.setCategories(oldResource.getCategories());
1297 protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1298 Resource cvfc = new Resource();
1299 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1300 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1301 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1302 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1303 cvfc.setResourceType(ResourceTypeEnum.VF);
1304 cvfc.setAbstract(true);
1305 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1306 cvfc.setDescription(ImportUtils.Constants.VF_DESCRIPTION);
1307 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1308 cvfc.setContactId(csarInfo.getModifier().getUserId());
1309 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1310 cvfc.setVendorName("cmri");
1311 cvfc.setTenant("tenant");
1312 cvfc.setVendorRelease("1.0");
1313 cvfc.setResourceVendorModelNumber("");
1314 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1315 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1316 List<String> tags = new ArrayList<>();
1317 tags.add(cvfc.getName());
1319 CategoryDefinition category = new CategoryDefinition();
1320 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1321 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1322 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1323 category.addSubCategory(subCategory);
1324 List<CategoryDefinition> categories = new ArrayList<>();
1325 categories.add(category);
1326 cvfc.setCategories(categories);
1327 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1328 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1329 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1333 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1334 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1338 private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
1339 log.debug("validate resource derivedFrom field");
1340 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
1341 .getDerivedFrom().get(0).trim().isEmpty())) {
1342 log.info("derived from (template) field is missing for the resource");
1343 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1344 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
1345 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1349 public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
1350 List<InputDefinition> resourceProperties = service.getInputs();
1351 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1352 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service);
1353 if (createInputs.isRight()) {
1354 throw new ComponentException(createInputs.right().value());
1359 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1360 if (updatedResource.isRight()) {
1361 throw new ComponentException(componentsUtils
1362 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1363 ComponentTypeEnum.SERVICE));
1365 return updatedResource.left().value();
1368 public Service createOutputsOnService(final Service service, final Map<String, OutputDefinition> outputs, final String userId) {
1369 if (MapUtils.isNotEmpty(outputs) || isNotEmpty(service.getOutputs())) {
1370 final Either<List<OutputDefinition>, ResponseFormat> createOutputs = outputsBusinessLogic.createOutputsInGraph(outputs, service, userId);
1371 if (createOutputs.isRight()) {
1372 throw new ComponentException(createOutputs.right().value());
1377 final Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1378 if (updatedResource.isRight()) {
1379 throw new ComponentException(
1380 componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1381 ComponentTypeEnum.SERVICE));
1383 return updatedResource.left().value();
1386 public Service createSubstitutionFilterOnService(Service service,
1387 ListDataDefinition<SubstitutionFilterPropertyDataDefinition> substitutionFilterProperties)
1388 throws BusinessLogicException {
1389 if (substitutionFilterProperties == null || substitutionFilterProperties.isEmpty()) {
1392 substitutionFilterBusinessLogic.addSubstitutionFilterInGraph(service.getUniqueId(), substitutionFilterProperties);
1393 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1394 if (updatedResource.isRight()) {
1395 throw new ComponentException(componentsUtils
1396 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1397 ComponentTypeEnum.SERVICE));
1399 return updatedResource.left().value();
1403 public Service createServiceTransaction(Service service, User user, boolean isNormative, AuditingActionEnum auditingAction) {
1404 if (!AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) &&
1405 !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
1406 // validate resource name uniqueness
1407 log.debug("validate resource name");
1408 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
1409 .validateComponentNameExists(service.getName(), null, service.getComponentType());
1410 if (eitherValidation.isRight()) {
1411 log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
1412 ResponseFormat errorResponse = componentsUtils
1413 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1414 throw new ComponentException(errorResponse);
1416 if (eitherValidation.left().value()) {
1417 log.debug("resource with name: {}, already exists", service.getName());
1418 ResponseFormat errorResponse = componentsUtils
1419 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1420 throw new ComponentException(errorResponse);
1423 log.debug("send resource {} to dao for create", service.getName());
1424 createArtifactsPlaceHolderData(service, user);
1426 if (!isNormative && !AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) &&
1427 !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
1428 log.debug("enrich resource with creator, version and state");
1429 service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1430 service.setVersion(INITIAL_VERSION);
1431 service.setHighestVersion(true);
1433 if (AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) ||
1434 AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
1435 toscaOperationFacade.deleteService(service.getInvariantUUID(), false);
1437 return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
1440 public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1441 ResponseFormat responseFormat = componentsUtils
1442 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1443 throw new ComponentException(responseFormat);
1446 protected void createArtifactsPlaceHolderData(Service service, User user) {
1447 setInformationalArtifactsPlaceHolder(service, user);
1448 serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1449 serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1452 @SuppressWarnings("unchecked")
1453 protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1454 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1455 if (artifactMap == null) {
1456 artifactMap = new HashMap<>();
1458 String resourceUniqueId = service.getUniqueId();
1459 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1460 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1461 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1462 .getInformationalResourceArtifacts();
1463 List<CategoryDefinition> categories = service.getCategories();
1464 boolean isCreateArtifact = true;
1465 if (exludeResourceCategory != null) {
1466 String category = categories.get(0).getName();
1467 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1469 if (informationalResourceArtifacts != null && isCreateArtifact) {
1470 Set<String> keys = informationalResourceArtifacts.keySet();
1471 for (String informationalResourceArtifactName : keys) {
1472 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1473 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1474 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1475 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1476 ArtifactGroupTypeEnum.INFORMATIONAL);
1477 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1481 service.setArtifacts(artifactMap);
1484 public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
1485 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1486 if (!inTransaction) {
1487 serviceBusinessLogic.janusGraphDao.rollback();
1489 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1490 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1491 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), service.getName());
1495 public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1496 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
1499 private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1501 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1504 private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1506 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
1507 .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
1508 if (resourceResponse.isRight()) {
1509 throw new ByResponseFormatComponentException(resourceResponse.right().value());
1511 return resourceResponse.left().value();
1514 public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
1515 boolean hasBeenCertified) {
1516 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1517 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1518 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
1519 log.trace("Update normative types");
1520 return Either.left(true);
1522 String derivedFromCurrent = currentDerivedFrom.get(0);
1523 String derivedFromUpdated = updatedDerivedFrom.get(0);
1524 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1525 if (!hasBeenCertified) {
1526 validateDerivedFromExist(null, updateInfoResource, null);
1528 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
1530 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1531 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1532 return validateDerivedFromExtending;
1536 return Either.left(true);
1539 protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
1540 AuditingActionEnum actionEnum) {
1541 String currentTemplateName = currentResource.getDerivedFrom().get(0);
1542 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1543 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1544 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
1545 if (dataModelResponse.isRight()) {
1546 StorageOperationStatus storageStatus = dataModelResponse.right().value();
1547 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1548 ResponseFormat responseFormat = componentsUtils
1549 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1550 log.trace("audit before sending response");
1551 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1552 return Either.right(responseFormat);
1554 if (!dataModelResponse.left().value()) {
1555 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
1556 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1557 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1558 return Either.right(responseFormat);
1560 return Either.left(true);
1563 public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1564 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1567 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1568 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1569 log.debug("validate resource name before update");
1570 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1571 log.debug("validate description before update");
1572 if (serviceBusinessLogic.componentDescriptionValidator != null) {
1573 serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1575 log.debug("validate icon before update");
1576 log.debug("validate tags before update");
1577 if (serviceBusinessLogic.componentTagsValidator != null) {
1578 serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1580 log.debug("validate vendor name before update");
1581 log.debug("validate resource vendor model number before update");
1582 log.debug("validate vendor release before update");
1583 log.debug("validate contact info before update");
1584 if (serviceBusinessLogic.componentContactIdValidator != null) {
1585 serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1587 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1588 log.debug("validate category before update");
1591 protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
1592 String resourceNameUpdated = updateInfoResource.getName();
1593 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1594 if (isNested || !hasBeenCertified) {
1595 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1596 currentResource.setName(resourceNameUpdated);
1597 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1598 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1600 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
1601 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1606 protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1607 String resourceNameUpdated = updateInfoResource.getName();
1608 String resourceNameCurrent = currentResource.getName();
1609 if (resourceNameCurrent.equals(resourceNameUpdated)) {
1612 return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
1613 .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1616 public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
1617 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1619 return lifecycleBusinessLogic
1620 .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
1621 inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
1626 protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1627 if (response.getRequestError() != null) {
1628 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
1629 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1630 ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
1632 throw new ComponentException(response);
1635 public Resource handleResourceGenericType(Resource resource) {
1636 Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1637 if (resource.shouldGenerateInputs()) {
1638 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1640 return genericResource;
1643 public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1644 List<InputDefinition> resourceProperties = resource.getInputs();
1645 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1646 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
1647 if (createInputs.isRight()) {
1648 throw new ComponentException(createInputs.right().value());
1653 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1654 if (updatedResource.isRight()) {
1655 throw new ComponentException(
1656 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1658 return updatedResource.left().value();
1661 protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1662 List<GroupDefinition> groupsFromResource = resource.getGroups();
1663 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1664 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1665 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1666 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1667 if (isNotEmpty(groupsFromResource)) {
1668 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1669 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1671 groupsToCreate.addAll(groupsAsList);
1673 if (isNotEmpty(groupsToCreate)) {
1674 fillGroupsFinalFields(groupsToCreate);
1675 if (isNotEmpty(groupsFromResource)) {
1676 groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1678 groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1681 if (isNotEmpty(groupsToDelete)) {
1682 groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
1684 if (isNotEmpty(groupsToUpdate)) {
1685 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
1686 .on(serviceBusinessLogic::throwComponentException);
1690 protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1691 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1692 for (GroupDefinition group : groupsAsList) {
1693 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
1695 if (op.isPresent()) {
1696 GroupDefinition groupToUpdate = op.get();
1697 groupToUpdate.setMembers(group.getMembers());
1698 groupToUpdate.setCapabilities(group.getCapabilities());
1699 groupToUpdate.setProperties(group.getProperties());
1700 groupsToUpdate.add(groupToUpdate);
1702 groupsToCreate.add(group);
1707 protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1708 List<GroupDefinition> groupsToDelete) {
1709 for (GroupDefinition group : groupsFromResource) {
1710 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1711 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1712 groupsToDelete.add(group);
1717 protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1718 List<GroupDefinition> result = new ArrayList<>();
1719 List<ComponentInstance> componentInstances = component.getComponentInstances();
1720 if (groups != null) {
1721 for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1722 String groupName = entry.getKey();
1723 GroupDefinition groupDefinition = entry.getValue();
1724 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1725 updatedGroupDefinition.setMembers(null);
1726 Map<String, String> members = groupDefinition.getMembers();
1727 if (members != null) {
1728 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1730 result.add(updatedGroupDefinition);
1736 public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
1737 List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1738 Set<String> compInstancesNames = members.keySet();
1739 if (CollectionUtils.isEmpty(componentInstances)) {
1740 String membersAstString = compInstancesNames.stream().collect(joining(","));
1741 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
1742 groupName, component.getNormalizedName());
1743 throw new ComponentException(componentsUtils
1744 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1745 getComponentTypeForResponse(component)));
1747 // Find all component instances with the member names
1748 Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1749 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1750 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
1751 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1752 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1753 List<String> foundMembers = new ArrayList<>();
1754 if (relevantInstances != null) {
1755 foundMembers = relevantInstances.keySet().stream().collect(toList());
1757 compInstancesNames.removeAll(foundMembers);
1758 String membersAstString = compInstancesNames.stream().collect(joining(","));
1759 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1760 throw new ComponentException(componentsUtils
1761 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1762 getComponentTypeForResponse(component)));
1764 updatedGroupDefinition.setMembers(relevantInstances);
1767 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
1768 boolean isInTransaction, boolean needLock,
1769 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1770 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1771 boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
1773 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1774 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1775 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1776 return resourceImportManager
1777 .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
1778 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested, null);
1781 public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
1782 Map<String, Object> mapToConvert, Service resourceVf,
1784 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1785 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1786 boolean forceCertificationAllowed, CsarInfo csarInfo,
1788 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1789 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1790 user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1791 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1792 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1795 protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
1796 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1797 // validate nodetype name prefix
1798 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1799 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1800 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1802 String actualName = this.getNodeTypeActualName(nodeName);
1803 String namePrefix = nodeName.replace(actualName, "");
1804 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1805 // if we import from csar, the node_type name can be
1807 // org.openecomp.resource.abstract.node_name - in this case we always
1810 if (resourceType.equals(Constants.ABSTRACT)) {
1811 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1814 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1815 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1816 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1819 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1820 // Setting type from name
1821 String type = resourceType.toUpperCase();
1822 resourceMetaData.setResourceType(type);
1823 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1824 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1825 resourceMetaData.setContactId(user.getUserId());
1827 List<String> tags = new ArrayList<>();
1828 tags.add(resourceMetaData.getName());
1829 resourceMetaData.setTags(tags);
1831 CategoryDefinition category = new CategoryDefinition();
1832 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1833 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1834 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1835 category.addSubCategory(subCategory);
1836 List<CategoryDefinition> categories = new ArrayList<>();
1837 categories.add(category);
1838 resourceMetaData.setCategories(categories);
1839 return resourceMetaData;
1842 public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1843 boolean needLock, boolean forceCertificationAllowed) {
1844 Either<Resource, ResponseFormat> result = null;
1846 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
1847 .isFirstCertification(resource.getVersion())) {
1848 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1850 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
1851 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
1852 .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
1855 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
1856 } catch (Exception e) {
1857 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
1860 if (result == null || result.isRight()) {
1861 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
1862 if (!inTransaction) {
1863 serviceBusinessLogic.janusGraphDao.rollback();
1865 } else if (!inTransaction) {
1866 serviceBusinessLogic.janusGraphDao.commit();
1871 public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1872 Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
1873 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1874 csarInfo.addNodeToQueue(nodeName);
1875 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1878 public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1879 if (MapUtils.isEmpty(groups)) {
1882 updateOrCreateGroups(resource, groups);
1884 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1885 if (updatedResource.isRight()) {
1886 throw new ComponentException(
1887 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1889 return updatedResource.left().value();
1892 protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
1893 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
1894 if (artifactMap == null) {
1895 artifactMap = new HashMap<>();
1897 String resourceUniqueId = resource.getUniqueId();
1898 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1899 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1900 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1901 .getInformationalResourceArtifacts();
1902 List<CategoryDefinition> categories = resource.getCategories();
1903 boolean isCreateArtifact = true;
1904 if (exludeResourceCategory != null) {
1905 String category = categories.get(0).getName();
1906 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1908 if (isCreateArtifact && exludeResourceType != null) {
1909 String resourceType = resource.getResourceType().name();
1910 isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
1912 if (informationalResourceArtifacts != null && isCreateArtifact) {
1913 Set<String> keys = informationalResourceArtifacts.keySet();
1914 for (String informationalResourceArtifactName : keys) {
1915 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1916 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1917 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1918 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1919 ArtifactGroupTypeEnum.INFORMATIONAL);
1920 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1924 resource.setArtifacts(artifactMap);
1927 public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1928 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1929 if (!inTransaction) {
1930 serviceBusinessLogic.janusGraphDao.rollback();
1932 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1933 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1934 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
1938 public void createArtifactsPlaceHolderData(Resource resource, User user) {
1939 setInformationalArtifactsPlaceHolder(resource, user);
1940 setDeploymentArtifactsPlaceHolder(resource, user);
1941 serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
1944 public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
1945 List<InputDefinition> inputs = service.getInputs();
1946 if (MapUtils.isNotEmpty(groups)) {
1947 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1948 .forEach(p -> handleGetInputs(p, inputs));
1952 public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1953 List<InputDefinition> inputs = resource.getInputs();
1954 if (MapUtils.isNotEmpty(groups)) {
1955 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1956 .forEach(p -> handleGetInputs(p, inputs));
1960 protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1961 if (isNotEmpty(property.getGetInputValues())) {
1962 if (inputs == null || inputs.isEmpty()) {
1963 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1964 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1965 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1967 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1968 while (getInputValuesIter.hasNext()) {
1969 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1970 InputDefinition input = findInputByName(inputs, getInput);
1971 getInput.setInputId(input.getUniqueId());
1972 if (getInput.getGetInputIndex() != null) {
1973 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1974 input = findInputByName(inputs, getInputIndex);
1975 getInputIndex.setInputId(input.getUniqueId());
1976 getInputValuesIter.add(getInputIndex);
1982 public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1983 Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
1984 if (!inputOpt.isPresent()) {
1985 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1986 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1988 return inputOpt.get();
1991 public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
1992 Map<String, List<ComponentInstanceProperty>> instProperties) {
1994 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
1995 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
1996 if (addPropToInst.isRight()) {
1997 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
1998 throw new ComponentException(
1999 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2001 } catch (Exception e) {
2002 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
2003 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2007 public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2008 Map<String, List<ComponentInstanceInput>> instInputs) {
2009 if (MapUtils.isNotEmpty(instInputs)) {
2010 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2011 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2012 if (addInputToInst.isRight()) {
2013 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
2014 throw new ComponentException(
2015 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2020 public void associateComponentInstanceInterfacesToComponent(
2023 Map<String, Map<String, InterfaceDefinition>> instInterfaces
2025 if (MapUtils.isNotEmpty(instInterfaces)) {
2026 Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> addInterfaceToInst =
2027 toscaOperationFacade
2028 .associateComponentInstanceInterfacesToComponent(
2030 service.getUniqueId()
2032 if (addInterfaceToInst.isRight()) {
2033 log.error("failed to associate interfaces value of service {}, status is {}", service.getUniqueId(),
2034 addInterfaceToInst.right().value());
2035 throw new ComponentException(
2036 componentsUtils.getResponseFormat(
2037 componentsUtils.convertFromStorageResponse(
2038 addInterfaceToInst.right().value()
2047 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2048 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2049 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2050 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2051 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2052 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2056 public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2057 StorageOperationStatus addArtToInst;
2058 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2059 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2060 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2061 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2065 public void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2066 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2067 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2068 StorageOperationStatus addArtToInst;
2069 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2070 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2071 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2072 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2076 public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2077 Map<String, List<AttributeDefinition>> instAttributes) {
2078 StorageOperationStatus addArtToInst;
2079 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2080 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2081 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2082 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2086 public Resource getResourceAfterCreateRelations(Resource resource) {
2087 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2088 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2089 if (eitherGetResource.isRight()) {
2090 throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
2092 return eitherGetResource.left().value();
2095 public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2096 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
2097 throw new ComponentException(responseFormat);
2100 public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2101 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2102 for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2103 if (originCapabilities.containsKey(currEntry.getKey())) {
2104 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2107 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2108 capabilities.getValue().stream().forEach(cap -> {
2109 if (uploadedCapabilities.containsKey(cap.getName())) {
2110 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2111 c.setName(cap.getName());
2112 c.setType(cap.getType());
2119 public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
2120 Map<String, List<CapabilityDefinition>> defaultCapabilities,
2121 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2122 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2123 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
2124 return validCapabilitiesMap;
2127 public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2128 if (MapUtils.isNotEmpty(instInputs)) {
2129 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2130 .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2131 if (addInputToInst.isRight()) {
2132 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
2133 throw new ComponentException(
2134 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2139 public void associateCINodeFilterToComponent(String yamlName, Service service, Map<String, UploadNodeFilterInfo> nodeFilter) {
2140 log.trace("************* Going to associate all resource node filters {}", yamlName);
2141 if (MapUtils.isNotEmpty(nodeFilter)) {
2142 StorageOperationStatus status = componentNodeFilterBusinessLogic.associateNodeFilterToComponentInstance(service.getUniqueId(),
2144 if (status != StorageOperationStatus.OK) {
2145 throw new ComponentException(
2146 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2151 public void associateComponentInstancePropertiesToComponent(String yamlName, Service service,
2152 Map<String, List<ComponentInstanceProperty>> instProperties) {
2153 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2154 .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2155 if (addPropToInst.isRight()) {
2156 throw new ComponentException(
2157 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2161 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
2162 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2163 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2164 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2165 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2166 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2170 public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2171 StorageOperationStatus addArtToInst;
2172 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2173 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2174 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2175 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2179 public void associateOrAddCalculatedCapReq(String yamlName, Service resource,
2180 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2181 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2182 StorageOperationStatus addArtToInst;
2183 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2184 log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
2185 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2186 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2187 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2191 public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
2192 Map<String, List<AttributeDefinition>> instAttributes) {
2193 StorageOperationStatus addArtToInst;
2194 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2195 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2196 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2197 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2201 public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2202 StorageOperationStatus addReqToService;
2203 addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
2204 if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2205 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
2206 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2210 public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
2211 StorageOperationStatus addCapToService;
2212 addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
2213 if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2214 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
2215 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2219 public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2220 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2221 .associateResourceInstances(service, service.getUniqueId(), relations);
2222 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2223 StorageOperationStatus status = relationsEither.right().value();
2224 log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
2225 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2229 public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2230 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
2231 originCapabilities.put(type, list);
2234 public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2235 for (UploadCapInfo capability : capabilities) {
2236 if (isNotEmpty(capability.getProperties())) {
2237 newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
2242 public Service getServiceWithGroups(String resourceId) {
2243 ComponentParametersView filter = new ComponentParametersView();
2244 filter.setIgnoreGroups(false);
2245 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2246 if (updatedResource.isRight()) {
2247 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2249 return updatedResource.left().value();
2252 public Resource getResourceWithGroups(String resourceId) {
2253 ComponentParametersView filter = new ComponentParametersView();
2254 filter.setIgnoreGroups(false);
2255 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2256 if (updatedResource.isRight()) {
2257 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2259 return updatedResource.left().value();
2262 public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2263 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2264 .associateResourceInstances(resource, resource.getUniqueId(), relations);
2265 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2266 StorageOperationStatus status = relationsEither.right().value();
2267 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
2268 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2272 public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2273 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2274 for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2275 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2276 ComponentInstance currentCompInstance = null;
2277 for (ComponentInstance compInstance : componentInstancesList) {
2278 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2279 currentCompInstance = compInstance;
2283 if (currentCompInstance == null) {
2284 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
2285 BeEcompErrorManager.getInstance()
2286 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
2287 BeEcompErrorManager.ErrorSeverity.ERROR);
2288 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2289 throw new ComponentException(responseFormat);
2291 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2292 if (addRelationToRiRes.getStatus() != 200) {
2293 throw new ComponentException(addRelationToRiRes);
2298 protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
2299 List<RequirementCapabilityRelDef> relations) {
2300 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2301 ComponentInstance currentCompInstance = null;
2302 for (ComponentInstance compInstance : componentInstancesList) {
2303 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2304 currentCompInstance = compInstance;
2308 if (currentCompInstance == null) {
2309 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
2310 BeEcompErrorManager.getInstance()
2311 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
2312 BeEcompErrorManager.ErrorSeverity.ERROR);
2313 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2315 String resourceInstanceId = currentCompInstance.getUniqueId();
2316 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2317 if (regMap != null) {
2318 Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2319 while (nodesRegValue.hasNext()) {
2320 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2321 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2322 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2323 log.debug("Going to create relation {}", uploadRegInfo.getName());
2324 String regName = uploadRegInfo.getName();
2325 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2326 regCapRelDef.setFromNode(resourceInstanceId);
2327 log.debug("try to find available requirement {} ", regName);
2328 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAvailableRequirement(regName, yamlName, nodesInfoValue,
2329 currentCompInstance, uploadRegInfo.getCapabilityName());
2330 if (eitherReqStatus.isRight()) {
2331 return eitherReqStatus.right().value();
2333 RequirementDefinition validReq = eitherReqStatus.left().value();
2334 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2335 if (reqAndRelationshipPairList == null) {
2336 reqAndRelationshipPairList = new ArrayList<>();
2338 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2339 reqAndRelationshipPair.setRequirement(regName);
2340 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2341 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2342 RelationshipImpl relationship = new RelationshipImpl();
2343 relationship.setType(validReq.getCapability());
2344 reqAndRelationshipPair.setRelationships(relationship);
2345 ComponentInstance currentCapCompInstance = null;
2346 for (ComponentInstance compInstance : componentInstancesList) {
2347 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2348 currentCapCompInstance = compInstance;
2352 if (currentCapCompInstance == null) {
2353 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
2354 BeEcompErrorManager.getInstance()
2355 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
2356 BeEcompErrorManager.ErrorSeverity.ERROR);
2357 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2359 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2360 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2361 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2362 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2363 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2364 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2365 if (aviableCapForRel == null) {
2366 BeEcompErrorManager.getInstance().logInternalDataError(
2367 "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2368 .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2369 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2371 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2372 capReqRel.setRelation(reqAndRelationshipPair);
2373 reqAndRelationshipPairList.add(capReqRel);
2374 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2375 relations.add(regCapRelDef);
2378 } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2379 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2381 return componentsUtils.getResponseFormat(ActionStatus.OK);