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 fj.data.Either;
20 import org.apache.commons.codec.binary.Base64;
21 import org.apache.commons.collections.CollectionUtils;
22 import org.apache.commons.collections.MapUtils;
23 import org.apache.commons.lang3.tuple.ImmutablePair;
24 import org.openecomp.sdc.be.components.csar.CsarInfo;
25 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
26 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
27 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
28 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
29 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
30 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.dao.api.ActionStatus;
34 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
35 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
36 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
37 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
38 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
39 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterPropertyDataDefinition;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
46 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
48 import org.openecomp.sdc.be.impl.ComponentsUtils;
49 import org.openecomp.sdc.be.model.ArtifactDefinition;
50 import org.openecomp.sdc.be.model.AttributeDefinition;
51 import org.openecomp.sdc.be.model.CapabilityDefinition;
52 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
53 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
54 import org.openecomp.sdc.be.model.Component;
55 import org.openecomp.sdc.be.model.ComponentInstance;
56 import org.openecomp.sdc.be.model.ComponentInstanceInput;
57 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
58 import org.openecomp.sdc.be.model.ComponentParametersView;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.InputDefinition;
61 import org.openecomp.sdc.be.model.InterfaceDefinition;
62 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
63 import org.openecomp.sdc.be.model.LifecycleStateEnum;
64 import org.openecomp.sdc.be.model.NodeTypeInfo;
65 import org.openecomp.sdc.be.model.Operation;
66 import org.openecomp.sdc.be.model.OutputDefinition;
67 import org.openecomp.sdc.be.model.PropertyDefinition;
68 import org.openecomp.sdc.be.model.RelationshipImpl;
69 import org.openecomp.sdc.be.model.RelationshipInfo;
70 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
71 import org.openecomp.sdc.be.model.RequirementDefinition;
72 import org.openecomp.sdc.be.model.Resource;
73 import org.openecomp.sdc.be.model.Service;
74 import org.openecomp.sdc.be.model.UploadCapInfo;
75 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
76 import org.openecomp.sdc.be.model.UploadInfo;
77 import org.openecomp.sdc.be.model.UploadInterfaceInfo;
78 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
79 import org.openecomp.sdc.be.model.UploadPropInfo;
80 import org.openecomp.sdc.be.model.UploadReqInfo;
81 import org.openecomp.sdc.be.model.UploadResourceInfo;
82 import org.openecomp.sdc.be.model.User;
83 import org.openecomp.sdc.be.model.category.CategoryDefinition;
84 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
85 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
86 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
87 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
88 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
89 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
90 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
91 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
94 import org.openecomp.sdc.be.tosca.CsarUtils;
95 import org.openecomp.sdc.be.utils.CommonBeUtils;
96 import org.openecomp.sdc.be.utils.TypeUtils;
97 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
98 import org.openecomp.sdc.common.api.Constants;
99 import org.openecomp.sdc.common.log.wrappers.Logger;
100 import org.openecomp.sdc.common.util.GeneralUtility;
101 import org.openecomp.sdc.common.util.ValidationUtils;
102 import org.openecomp.sdc.exception.ResponseFormat;
103 import org.yaml.snakeyaml.DumperOptions;
104 import org.yaml.snakeyaml.Yaml;
106 import java.util.ArrayList;
107 import java.util.EnumMap;
108 import java.util.HashMap;
109 import java.util.Iterator;
110 import java.util.List;
111 import java.util.ListIterator;
112 import java.util.Map;
113 import java.util.Optional;
114 import java.util.Set;
115 import java.util.function.Function;
117 import static java.util.stream.Collectors.joining;
118 import static java.util.stream.Collectors.toList;
119 import static java.util.stream.Collectors.toMap;
120 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
123 @org.springframework.stereotype.Component
124 public class ServiceImportParseLogic {
126 private static final String INITIAL_VERSION = "0.1";
127 private static final String CREATE_RESOURCE = "Create Resource";
128 private static final String IN_RESOURCE = " in resource {} ";
129 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
130 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
131 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
132 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
133 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
134 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
135 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
136 private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class);
137 private final ServiceBusinessLogic serviceBusinessLogic;
138 private final ComponentsUtils componentsUtils;
139 private final ToscaOperationFacade toscaOperationFacade;
140 private final LifecycleBusinessLogic lifecycleBusinessLogic;
141 private final InputsBusinessLogic inputsBusinessLogic;
142 private final ResourceImportManager resourceImportManager;
143 private final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic;
144 private final IInterfaceLifecycleOperation interfaceTypeOperation;
145 private final ICapabilityTypeOperation capabilityTypeOperation;
146 private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
147 private final GroupBusinessLogic groupBusinessLogic;
148 private final OutputsBusinessLogic outputsBusinessLogic;
150 public ServiceImportParseLogic(final ServiceBusinessLogic serviceBusinessLogic, final ComponentsUtils componentsUtils,
151 final ToscaOperationFacade toscaOperationFacade, final LifecycleBusinessLogic lifecycleBusinessLogic,
152 final InputsBusinessLogic inputsBusinessLogic, final ResourceImportManager resourceImportManager,
153 final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic,
154 final IInterfaceLifecycleOperation interfaceTypeOperation, final ICapabilityTypeOperation capabilityTypeOperation,
155 final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic,
156 final GroupBusinessLogic groupBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic) {
157 this.serviceBusinessLogic = serviceBusinessLogic;
158 this.componentsUtils = componentsUtils;
159 this.toscaOperationFacade = toscaOperationFacade;
160 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
161 this.inputsBusinessLogic = inputsBusinessLogic;
162 this.resourceImportManager = resourceImportManager;
163 this.substitutionFilterBusinessLogic = substitutionFilterBusinessLogic;
164 this.interfaceTypeOperation = interfaceTypeOperation;
165 this.capabilityTypeOperation = capabilityTypeOperation;
166 this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
167 this.groupBusinessLogic = groupBusinessLogic;
168 this.outputsBusinessLogic = outputsBusinessLogic;
171 public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
172 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
173 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
174 Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
175 .left(nodeTypesArtifactsToHandle);
177 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
178 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
179 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
180 csarInfo.getCsarUUID());
181 extractedVfcToscaNames.forEach(
182 (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
183 extractedVfcsArtifacts, namespace, vfcToscaNames));
184 } catch (Exception e) {
185 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
186 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
187 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
189 return nodeTypesArtifactsToHandleRes;
192 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
194 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
195 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
196 if (!nodes.isEmpty()) {
197 Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
198 while (nodesNameEntry.hasNext()) {
199 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
200 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
202 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
205 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
206 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
208 return vfcToscaNames;
211 public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
213 // We need to create a Yaml from each node_types in order to create
215 // resource from each node type using import normative flow.
216 DumperOptions options = new DumperOptions();
217 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
218 Yaml yaml = new Yaml(options);
219 Map<String, Object> node = new HashMap<>();
220 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
221 nodeNameValue.getValue());
222 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
223 return yaml.dumpAsMap(mapToConvert);
226 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
229 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
230 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
231 actualType = ResourceTypeEnum.VFC.name();
233 actualVfName = vfResourceName;
234 actualType = nodeResourceType;
236 String nameWithouNamespacePrefix;
238 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
239 if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
240 nameWithouNamespacePrefix = nodeTypeFullName;
242 nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
244 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
245 String resourceType = findTypes[0];
246 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
247 if (actualName.startsWith(Constants.ABSTRACT)) {
248 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
250 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
252 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
253 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
254 previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
255 } catch (Exception e) {
256 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
257 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
258 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
262 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
263 Map<String, Object> nodes = new HashMap<>();
264 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
265 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
267 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
271 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
272 Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
273 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
274 if (eitherNodeTypes.isLeft()) {
275 nodes.putAll(eitherNodeTypes.left().value());
279 protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
280 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
281 Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
282 ImmutablePair<String, String> vfcToscaNames) {
283 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
284 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
285 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
286 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
287 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
288 if (extractedVfcsArtifacts.containsKey(namespace)) {
289 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
291 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
292 } else if (curNodeType != null) {
293 // delete all artifacts if have not received artifacts from
297 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
298 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
299 // delete all informational artifacts
300 artifactsToDelete.addAll(
301 curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
303 // delete all deployment artifacts
304 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
305 if (!artifactsToDelete.isEmpty()) {
306 curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
308 } catch (Exception e) {
309 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
310 log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
311 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft());
314 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
315 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
319 protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
320 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
321 artifactsToAdd.stream().forEach(a -> {
322 if (!vfcArtifactNames.contains(a.getArtifactName())) {
325 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
330 protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName,
331 StorageOperationStatus status) {
332 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
333 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
334 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
335 } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
336 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
337 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
342 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
343 List<ArtifactDefinition> extractedArtifacts) {
344 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
346 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
347 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
348 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
349 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
350 collectExistingArtifacts(curNodeType));
351 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
352 } catch (Exception e) {
353 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
354 throw new ComponentException(ActionStatus.GENERAL_ERROR);
356 return nodeTypeArtifactsToHandle;
359 protected Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
360 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
361 if (curNodeType == null) {
362 return existingArtifacts;
364 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
365 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
367 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
368 existingArtifacts.putAll(
369 curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
370 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
372 return existingArtifacts;
375 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
376 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
377 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
378 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
379 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
380 if (!artifactsToUpload.isEmpty()) {
381 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
383 if (!artifactsToUpdate.isEmpty()) {
384 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
386 if (!artifactsToDelete.isEmpty()) {
387 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
390 return nodeTypeArtifactsToHandle;
393 protected void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
394 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
395 Map<String, ArtifactDefinition> existingArtifacts) {
397 if (!existingArtifacts.isEmpty()) {
398 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
399 artifactsToDelete.addAll(existingArtifacts.values());
401 } catch (Exception e) {
402 log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
403 throw new ComponentException(ActionStatus.GENERAL_ERROR);
407 protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
408 Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
409 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
410 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
411 if (foundArtifact.isPresent()) {
412 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
413 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
414 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
415 artifactsToUpload.remove(currNewArtifact);
417 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
418 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
419 currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
424 protected void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
425 ArtifactDefinition foundArtifact) {
426 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
427 foundArtifact.setPayload(currNewArtifact.getPayloadData());
428 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
429 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
430 artifactsToUpdate.add(foundArtifact);
434 public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
435 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
436 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
437 && eitherNonMetaArtifacts.isLeft()) {
438 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
439 if (eitherResult.isLeft()) {
440 createdArtifacts.add(eitherResult.left().value());
445 public boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
446 return !org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
449 public void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
450 groupsAsList.forEach(groupDefinition -> {
451 groupDefinition.setInvariantName(groupDefinition.getName());
452 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
456 public String getComponentTypeForResponse(Component component) {
457 String componentTypeForResponse = "SERVICE";
458 if (component instanceof Resource) {
459 componentTypeForResponse = ((Resource) component).getResourceType().name();
461 return componentTypeForResponse;
464 public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
465 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
466 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
467 csarInfo.addNodeToQueue(nodeName);
468 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
471 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
473 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
474 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
475 validateLifecycleTypesCreate(user, resource, actionEnum);
476 validateResourceType(user, resource, actionEnum);
477 resource.setCreatorUserId(user.getUserId());
478 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
479 resource.setContactId(resource.getContactId().toLowerCase());
480 if (org.apache.commons.lang.StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
481 String resourceSystemName;
482 if (csarInfo != null && org.apache.commons.lang.StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
483 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
485 resourceSystemName = resource.getSystemName();
488 .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
490 // Generate invariant UUID - must be here and not in operation since it
492 // should stay constant during clone
495 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
496 resource.setInvariantUUID(invariantUUID);
500 protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
501 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
502 if (resource.getResourceType() == null) {
503 log.debug("Invalid resource type for resource");
504 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
505 eitherResult = Either.right(errorResponse);
506 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
511 protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
512 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
513 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
514 log.debug("validate interface lifecycle Types Exist");
515 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
516 while (intItr.hasNext() && eitherResult.isLeft()) {
517 InterfaceDefinition interfaceDefinition = intItr.next();
518 String intType = interfaceDefinition.getUniqueId();
519 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(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 (!ValidationUtils.validateStringNotEmpty(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 (!ValidationUtils.validateStringNotEmpty(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 (!ValidationUtils.validateStringNotEmpty(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 (!ValidationUtils.validateStringNotEmpty(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) {
1404 // validate resource name uniqueness
1405 log.debug("validate resource name");
1406 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
1407 .validateComponentNameExists(service.getName(), null, service.getComponentType());
1408 if (eitherValidation.isRight()) {
1409 log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
1410 ResponseFormat errorResponse = componentsUtils
1411 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1412 throw new ComponentException(errorResponse);
1414 if (eitherValidation.left().value()) {
1415 log.debug("resource with name: {}, already exists", service.getName());
1416 ResponseFormat errorResponse = componentsUtils
1417 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1418 throw new ComponentException(errorResponse);
1420 log.debug("send resource {} to dao for create", service.getName());
1421 createArtifactsPlaceHolderData(service, user);
1424 log.debug("enrich resource with creator, version and state");
1425 service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1426 service.setVersion(INITIAL_VERSION);
1427 service.setHighestVersion(true);
1429 return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
1432 public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1433 ResponseFormat responseFormat = componentsUtils
1434 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1435 throw new ComponentException(responseFormat);
1438 protected void createArtifactsPlaceHolderData(Service service, User user) {
1439 setInformationalArtifactsPlaceHolder(service, user);
1440 serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1441 serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1444 @SuppressWarnings("unchecked")
1445 protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1446 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1447 if (artifactMap == null) {
1448 artifactMap = new HashMap<>();
1450 String resourceUniqueId = service.getUniqueId();
1451 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1452 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1453 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1454 .getInformationalResourceArtifacts();
1455 List<CategoryDefinition> categories = service.getCategories();
1456 boolean isCreateArtifact = true;
1457 if (exludeResourceCategory != null) {
1458 String category = categories.get(0).getName();
1459 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1461 if (informationalResourceArtifacts != null && isCreateArtifact) {
1462 Set<String> keys = informationalResourceArtifacts.keySet();
1463 for (String informationalResourceArtifactName : keys) {
1464 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1465 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1466 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1467 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1468 ArtifactGroupTypeEnum.INFORMATIONAL);
1469 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1473 service.setArtifacts(artifactMap);
1476 public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
1477 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1478 if (!inTransaction) {
1479 serviceBusinessLogic.janusGraphDao.rollback();
1481 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1482 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1483 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), service.getName());
1487 public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1488 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
1491 private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1493 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1496 private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1498 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
1499 .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
1500 if (resourceResponse.isRight()) {
1501 throw new ByResponseFormatComponentException(resourceResponse.right().value());
1503 return resourceResponse.left().value();
1506 public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
1507 boolean hasBeenCertified) {
1508 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1509 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1510 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
1511 log.trace("Update normative types");
1512 return Either.left(true);
1514 String derivedFromCurrent = currentDerivedFrom.get(0);
1515 String derivedFromUpdated = updatedDerivedFrom.get(0);
1516 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1517 if (!hasBeenCertified) {
1518 validateDerivedFromExist(null, updateInfoResource, null);
1520 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
1522 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1523 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1524 return validateDerivedFromExtending;
1528 return Either.left(true);
1531 protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
1532 AuditingActionEnum actionEnum) {
1533 String currentTemplateName = currentResource.getDerivedFrom().get(0);
1534 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1535 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1536 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
1537 if (dataModelResponse.isRight()) {
1538 StorageOperationStatus storageStatus = dataModelResponse.right().value();
1539 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1540 ResponseFormat responseFormat = componentsUtils
1541 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1542 log.trace("audit before sending response");
1543 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1544 return Either.right(responseFormat);
1546 if (!dataModelResponse.left().value()) {
1547 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
1548 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1549 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1550 return Either.right(responseFormat);
1552 return Either.left(true);
1555 public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1556 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1559 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1560 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1561 log.debug("validate resource name before update");
1562 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1563 log.debug("validate description before update");
1564 if (serviceBusinessLogic.componentDescriptionValidator != null) {
1565 serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1567 log.debug("validate icon before update");
1568 log.debug("validate tags before update");
1569 if (serviceBusinessLogic.componentTagsValidator != null) {
1570 serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1572 log.debug("validate vendor name before update");
1573 log.debug("validate resource vendor model number before update");
1574 log.debug("validate vendor release before update");
1575 log.debug("validate contact info before update");
1576 if (serviceBusinessLogic.componentContactIdValidator != null) {
1577 serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1579 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1580 log.debug("validate category before update");
1583 protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
1584 String resourceNameUpdated = updateInfoResource.getName();
1585 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1586 if (isNested || !hasBeenCertified) {
1587 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1588 currentResource.setName(resourceNameUpdated);
1589 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1590 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1592 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
1593 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1598 protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1599 String resourceNameUpdated = updateInfoResource.getName();
1600 String resourceNameCurrent = currentResource.getName();
1601 if (resourceNameCurrent.equals(resourceNameUpdated)) {
1604 return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
1605 .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1608 public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
1609 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1611 return lifecycleBusinessLogic
1612 .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
1613 inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
1618 protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1619 if (response.getRequestError() != null) {
1620 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
1621 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1622 ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
1624 throw new ComponentException(response);
1627 public Resource handleResourceGenericType(Resource resource) {
1628 Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1629 if (resource.shouldGenerateInputs()) {
1630 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1632 return genericResource;
1635 public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1636 List<InputDefinition> resourceProperties = resource.getInputs();
1637 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1638 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
1639 if (createInputs.isRight()) {
1640 throw new ComponentException(createInputs.right().value());
1645 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1646 if (updatedResource.isRight()) {
1647 throw new ComponentException(
1648 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1650 return updatedResource.left().value();
1653 protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1654 List<GroupDefinition> groupsFromResource = resource.getGroups();
1655 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1656 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1657 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1658 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1659 if (isNotEmpty(groupsFromResource)) {
1660 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1661 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1663 groupsToCreate.addAll(groupsAsList);
1665 if (isNotEmpty(groupsToCreate)) {
1666 fillGroupsFinalFields(groupsToCreate);
1667 if (isNotEmpty(groupsFromResource)) {
1668 groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1670 groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1673 if (isNotEmpty(groupsToDelete)) {
1674 groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
1676 if (isNotEmpty(groupsToUpdate)) {
1677 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
1678 .on(serviceBusinessLogic::throwComponentException);
1682 protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1683 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1684 for (GroupDefinition group : groupsAsList) {
1685 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
1687 if (op.isPresent()) {
1688 GroupDefinition groupToUpdate = op.get();
1689 groupToUpdate.setMembers(group.getMembers());
1690 groupToUpdate.setCapabilities(group.getCapabilities());
1691 groupToUpdate.setProperties(group.getProperties());
1692 groupsToUpdate.add(groupToUpdate);
1694 groupsToCreate.add(group);
1699 protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1700 List<GroupDefinition> groupsToDelete) {
1701 for (GroupDefinition group : groupsFromResource) {
1702 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1703 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1704 groupsToDelete.add(group);
1709 protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1710 List<GroupDefinition> result = new ArrayList<>();
1711 List<ComponentInstance> componentInstances = component.getComponentInstances();
1712 if (groups != null) {
1713 for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1714 String groupName = entry.getKey();
1715 GroupDefinition groupDefinition = entry.getValue();
1716 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1717 updatedGroupDefinition.setMembers(null);
1718 Map<String, String> members = groupDefinition.getMembers();
1719 if (members != null) {
1720 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1722 result.add(updatedGroupDefinition);
1728 public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
1729 List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1730 Set<String> compInstancesNames = members.keySet();
1731 if (CollectionUtils.isEmpty(componentInstances)) {
1732 String membersAstString = compInstancesNames.stream().collect(joining(","));
1733 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
1734 groupName, component.getNormalizedName());
1735 throw new ComponentException(componentsUtils
1736 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1737 getComponentTypeForResponse(component)));
1739 // Find all component instances with the member names
1740 Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1741 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1742 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
1743 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1744 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1745 List<String> foundMembers = new ArrayList<>();
1746 if (relevantInstances != null) {
1747 foundMembers = relevantInstances.keySet().stream().collect(toList());
1749 compInstancesNames.removeAll(foundMembers);
1750 String membersAstString = compInstancesNames.stream().collect(joining(","));
1751 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1752 throw new ComponentException(componentsUtils
1753 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1754 getComponentTypeForResponse(component)));
1756 updatedGroupDefinition.setMembers(relevantInstances);
1759 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
1760 boolean isInTransaction, boolean needLock,
1761 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1762 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1763 boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
1765 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1766 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1767 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1768 return resourceImportManager
1769 .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
1770 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1773 public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
1774 Map<String, Object> mapToConvert, Service resourceVf,
1776 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1777 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1778 boolean forceCertificationAllowed, CsarInfo csarInfo,
1780 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1781 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1782 user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1783 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1784 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1787 protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
1788 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1789 // validate nodetype name prefix
1790 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1791 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1792 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1794 String actualName = this.getNodeTypeActualName(nodeName);
1795 String namePrefix = nodeName.replace(actualName, "");
1796 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1797 // if we import from csar, the node_type name can be
1799 // org.openecomp.resource.abstract.node_name - in this case we always
1802 if (resourceType.equals(Constants.ABSTRACT)) {
1803 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1806 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1807 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1808 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1811 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1812 // Setting type from name
1813 String type = resourceType.toUpperCase();
1814 resourceMetaData.setResourceType(type);
1815 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1816 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1817 resourceMetaData.setContactId(user.getUserId());
1819 List<String> tags = new ArrayList<>();
1820 tags.add(resourceMetaData.getName());
1821 resourceMetaData.setTags(tags);
1823 CategoryDefinition category = new CategoryDefinition();
1824 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1825 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1826 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1827 category.addSubCategory(subCategory);
1828 List<CategoryDefinition> categories = new ArrayList<>();
1829 categories.add(category);
1830 resourceMetaData.setCategories(categories);
1831 return resourceMetaData;
1834 public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1835 boolean needLock, boolean forceCertificationAllowed) {
1836 Either<Resource, ResponseFormat> result = null;
1838 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
1839 .isFirstCertification(resource.getVersion())) {
1840 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1842 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
1843 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
1844 .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
1847 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
1848 } catch (Exception e) {
1849 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
1852 if (result == null || result.isRight()) {
1853 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
1854 if (!inTransaction) {
1855 serviceBusinessLogic.janusGraphDao.rollback();
1857 } else if (!inTransaction) {
1858 serviceBusinessLogic.janusGraphDao.commit();
1863 public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1864 Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
1865 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1866 csarInfo.addNodeToQueue(nodeName);
1867 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1870 public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1871 if (MapUtils.isEmpty(groups)) {
1874 updateOrCreateGroups(resource, groups);
1876 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1877 if (updatedResource.isRight()) {
1878 throw new ComponentException(
1879 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1881 return updatedResource.left().value();
1884 protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
1885 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
1886 if (artifactMap == null) {
1887 artifactMap = new HashMap<>();
1889 String resourceUniqueId = resource.getUniqueId();
1890 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1891 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1892 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1893 .getInformationalResourceArtifacts();
1894 List<CategoryDefinition> categories = resource.getCategories();
1895 boolean isCreateArtifact = true;
1896 if (exludeResourceCategory != null) {
1897 String category = categories.get(0).getName();
1898 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1900 if (isCreateArtifact && exludeResourceType != null) {
1901 String resourceType = resource.getResourceType().name();
1902 isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
1904 if (informationalResourceArtifacts != null && isCreateArtifact) {
1905 Set<String> keys = informationalResourceArtifacts.keySet();
1906 for (String informationalResourceArtifactName : keys) {
1907 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1908 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1909 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1910 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1911 ArtifactGroupTypeEnum.INFORMATIONAL);
1912 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1916 resource.setArtifacts(artifactMap);
1919 public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1920 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1921 if (!inTransaction) {
1922 serviceBusinessLogic.janusGraphDao.rollback();
1924 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1925 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1926 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
1930 public void createArtifactsPlaceHolderData(Resource resource, User user) {
1931 setInformationalArtifactsPlaceHolder(resource, user);
1932 setDeploymentArtifactsPlaceHolder(resource, user);
1933 serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
1936 public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
1937 List<InputDefinition> inputs = service.getInputs();
1938 if (MapUtils.isNotEmpty(groups)) {
1939 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1940 .forEach(p -> handleGetInputs(p, inputs));
1944 public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1945 List<InputDefinition> inputs = resource.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 protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1953 if (isNotEmpty(property.getGetInputValues())) {
1954 if (inputs == null || inputs.isEmpty()) {
1955 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1956 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1957 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1959 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1960 while (getInputValuesIter.hasNext()) {
1961 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1962 InputDefinition input = findInputByName(inputs, getInput);
1963 getInput.setInputId(input.getUniqueId());
1964 if (getInput.getGetInputIndex() != null) {
1965 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1966 input = findInputByName(inputs, getInputIndex);
1967 getInputIndex.setInputId(input.getUniqueId());
1968 getInputValuesIter.add(getInputIndex);
1974 public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1975 Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
1976 if (!inputOpt.isPresent()) {
1977 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1978 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1980 return inputOpt.get();
1983 public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
1984 Map<String, List<ComponentInstanceProperty>> instProperties) {
1986 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
1987 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
1988 if (addPropToInst.isRight()) {
1989 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
1990 throw new ComponentException(
1991 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
1993 } catch (Exception e) {
1994 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
1995 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1999 public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2000 Map<String, List<ComponentInstanceInput>> instInputs) {
2001 if (MapUtils.isNotEmpty(instInputs)) {
2002 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2003 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2004 if (addInputToInst.isRight()) {
2005 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
2006 throw new ComponentException(
2007 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2012 public void associateComponentInstanceInterfacesToComponent(
2015 Map<String, Map<String, InterfaceDefinition>> instInterfaces
2017 if (MapUtils.isNotEmpty(instInterfaces)) {
2018 Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> addInterfaceToInst =
2019 toscaOperationFacade
2020 .associateComponentInstanceInterfacesToComponent(
2022 service.getUniqueId()
2024 if (addInterfaceToInst.isRight()) {
2025 log.error("failed to associate interfaces value of service {}, status is {}", service.getUniqueId(), addInterfaceToInst.right().value());
2026 throw new ComponentException(
2027 componentsUtils.getResponseFormat(
2028 componentsUtils.convertFromStorageResponse(
2029 addInterfaceToInst.right().value()
2038 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2039 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2040 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2041 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2042 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2043 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2047 public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2048 StorageOperationStatus addArtToInst;
2049 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
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 associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2057 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2058 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2059 StorageOperationStatus addArtToInst;
2060 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2061 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2062 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2063 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2067 public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2068 Map<String, List<AttributeDefinition>> instAttributes) {
2069 StorageOperationStatus addArtToInst;
2070 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2071 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2072 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2073 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2077 public Resource getResourceAfterCreateRelations(Resource resource) {
2078 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2079 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2080 if (eitherGetResource.isRight()) {
2081 throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
2083 return eitherGetResource.left().value();
2086 public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2087 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
2088 throw new ComponentException(responseFormat);
2091 public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2092 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2093 for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2094 if (originCapabilities.containsKey(currEntry.getKey())) {
2095 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2098 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2099 capabilities.getValue().stream().forEach(cap -> {
2100 if (uploadedCapabilities.containsKey(cap.getName())) {
2101 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2102 c.setName(cap.getName());
2103 c.setType(cap.getType());
2110 public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
2111 Map<String, List<CapabilityDefinition>> defaultCapabilities,
2112 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2113 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2114 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
2115 return validCapabilitiesMap;
2118 public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2119 if (MapUtils.isNotEmpty(instInputs)) {
2120 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2121 .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2122 if (addInputToInst.isRight()) {
2123 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
2124 throw new ComponentException(
2125 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2130 public void associateCINodeFilterToComponent(String yamlName, Service service, Map<String, UploadNodeFilterInfo> nodeFilter) {
2131 log.trace("************* Going to associate all resource node filters {}", yamlName);
2132 if (MapUtils.isNotEmpty(nodeFilter)) {
2133 StorageOperationStatus status = componentNodeFilterBusinessLogic.associateNodeFilterToComponentInstance(service.getUniqueId(),
2135 if (status != StorageOperationStatus.OK) {
2136 throw new ComponentException(
2137 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2142 public void associateComponentInstancePropertiesToComponent(String yamlName, Service service,
2143 Map<String, List<ComponentInstanceProperty>> instProperties) {
2144 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2145 .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2146 if (addPropToInst.isRight()) {
2147 throw new ComponentException(
2148 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2152 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
2153 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2154 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2155 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2156 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2157 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2161 public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2162 StorageOperationStatus addArtToInst;
2163 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
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 associateOrAddCalculatedCapReq(String yamlName, Service resource,
2171 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2172 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2173 StorageOperationStatus addArtToInst;
2174 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2175 log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
2176 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2177 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2178 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2182 public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
2183 Map<String, List<AttributeDefinition>> instAttributes) {
2184 StorageOperationStatus addArtToInst;
2185 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2186 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2187 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2188 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2192 public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2193 StorageOperationStatus addReqToService;
2194 addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
2195 if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2196 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
2197 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2201 public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
2202 StorageOperationStatus addCapToService;
2203 addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
2204 if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2205 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
2206 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2210 public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2211 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2212 .associateResourceInstances(service, service.getUniqueId(), relations);
2213 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2214 StorageOperationStatus status = relationsEither.right().value();
2215 log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
2216 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2220 public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2221 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
2222 originCapabilities.put(type, list);
2225 public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2226 for (UploadCapInfo capability : capabilities) {
2227 if (isNotEmpty(capability.getProperties())) {
2228 newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
2233 public Service getServiceWithGroups(String resourceId) {
2234 ComponentParametersView filter = new ComponentParametersView();
2235 filter.setIgnoreGroups(false);
2236 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2237 if (updatedResource.isRight()) {
2238 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2240 return updatedResource.left().value();
2243 public Resource getResourceWithGroups(String resourceId) {
2244 ComponentParametersView filter = new ComponentParametersView();
2245 filter.setIgnoreGroups(false);
2246 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2247 if (updatedResource.isRight()) {
2248 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2250 return updatedResource.left().value();
2253 public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2254 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2255 .associateResourceInstances(resource, resource.getUniqueId(), relations);
2256 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2257 StorageOperationStatus status = relationsEither.right().value();
2258 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
2259 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2263 public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2264 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2265 for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2266 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2267 ComponentInstance currentCompInstance = null;
2268 for (ComponentInstance compInstance : componentInstancesList) {
2269 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2270 currentCompInstance = compInstance;
2274 if (currentCompInstance == null) {
2275 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
2276 BeEcompErrorManager.getInstance()
2277 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
2278 BeEcompErrorManager.ErrorSeverity.ERROR);
2279 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2280 throw new ComponentException(responseFormat);
2282 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2283 if (addRelationToRiRes.getStatus() != 200) {
2284 throw new ComponentException(addRelationToRiRes);
2289 protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
2290 List<RequirementCapabilityRelDef> relations) {
2291 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2292 ComponentInstance currentCompInstance = null;
2293 for (ComponentInstance compInstance : componentInstancesList) {
2294 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2295 currentCompInstance = compInstance;
2299 if (currentCompInstance == null) {
2300 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
2301 BeEcompErrorManager.getInstance()
2302 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
2303 BeEcompErrorManager.ErrorSeverity.ERROR);
2304 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2306 String resourceInstanceId = currentCompInstance.getUniqueId();
2307 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2308 if (regMap != null) {
2309 Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2310 while (nodesRegValue.hasNext()) {
2311 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2312 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2313 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2314 log.debug("Going to create relation {}", uploadRegInfo.getName());
2315 String regName = uploadRegInfo.getName();
2316 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2317 regCapRelDef.setFromNode(resourceInstanceId);
2318 log.debug("try to find available requirement {} ", regName);
2319 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAvailableRequirement(regName, yamlName, nodesInfoValue,
2320 currentCompInstance, uploadRegInfo.getCapabilityName());
2321 if (eitherReqStatus.isRight()) {
2322 return eitherReqStatus.right().value();
2324 RequirementDefinition validReq = eitherReqStatus.left().value();
2325 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2326 if (reqAndRelationshipPairList == null) {
2327 reqAndRelationshipPairList = new ArrayList<>();
2329 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2330 reqAndRelationshipPair.setRequirement(regName);
2331 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2332 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2333 RelationshipImpl relationship = new RelationshipImpl();
2334 relationship.setType(validReq.getCapability());
2335 reqAndRelationshipPair.setRelationships(relationship);
2336 ComponentInstance currentCapCompInstance = null;
2337 for (ComponentInstance compInstance : componentInstancesList) {
2338 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2339 currentCapCompInstance = compInstance;
2343 if (currentCapCompInstance == null) {
2344 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
2345 BeEcompErrorManager.getInstance()
2346 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
2347 BeEcompErrorManager.ErrorSeverity.ERROR);
2348 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2350 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2351 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2352 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2353 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2354 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2355 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2356 if (aviableCapForRel == null) {
2357 BeEcompErrorManager.getInstance().logInternalDataError(
2358 "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2359 .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2360 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2362 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2363 capReqRel.setRelation(reqAndRelationshipPair);
2364 reqAndRelationshipPairList.add(capReqRel);
2365 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2366 relations.add(regCapRelDef);
2369 } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2370 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2372 return componentsUtils.getResponseFormat(ActionStatus.OK);