2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
23 import fj.data.Either;
24 import org.apache.commons.collections.CollectionUtils;
25 import org.apache.commons.collections.MapUtils;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.apache.tinkerpop.gremlin.structure.Direction;
29 import org.apache.tinkerpop.gremlin.structure.Edge;
30 import org.openecomp.sdc.be.config.Configuration;
31 import org.openecomp.sdc.be.config.ConfigurationManager;
32 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
33 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
34 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
35 import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao;
36 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
37 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
38 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
39 import org.openecomp.sdc.be.datatypes.elements.*;
40 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
41 import org.openecomp.sdc.be.datatypes.enums.*;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
44 import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
45 import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
46 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
47 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
48 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
49 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
50 import org.openecomp.sdc.be.model.operations.StorageException;
51 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
52 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
53 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
54 import org.openecomp.sdc.be.model.utils.GroupUtils;
55 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
56 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
57 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
58 import org.openecomp.sdc.common.log.wrappers.Logger;
59 import org.openecomp.sdc.common.util.ValidationUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
63 import java.util.Map.Entry;
64 import java.util.function.BiPredicate;
65 import java.util.stream.Collectors;
67 import static java.util.Objects.requireNonNull;
68 import static org.apache.commons.collections.CollectionUtils.isEmpty;
69 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
72 @org.springframework.stereotype.Component("tosca-operation-facade")
73 public class ToscaOperationFacade {
77 private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
78 private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. ";
79 private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
80 private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
81 private static final String SERVICE = "service";
82 private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
83 private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
84 private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
86 private NodeTypeOperation nodeTypeOperation;
88 private TopologyTemplateOperation topologyTemplateOperation;
90 private NodeTemplateOperation nodeTemplateOperation;
92 private GroupsOperation groupsOperation;
94 private HealingJanusGraphDao janusGraphDao;
96 private ContainerInstanceTypesData containerInstanceTypesData;
98 private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
101 // region - ToscaElement - GetById
102 public static final String PROXY_SUFFIX = "_proxy";
104 public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
105 ComponentParametersView filters = new ComponentParametersView();
106 filters.setIgnoreCapabiltyProperties(false);
107 filters.setIgnoreForwardingPath(false);
108 return getToscaElement(componentId, filters);
111 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
113 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
117 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
119 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
120 .getVertexById(componentId, filters.detectParseFlag());
121 if (getVertexEither.isRight()) {
122 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
123 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
126 return getToscaElementByOperation(getVertexEither.left().value(), filters);
129 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
131 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
132 .getVertexById(componentId, parseFlag);
133 if (getVertexEither.isRight()) {
134 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
135 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
138 return getToscaElementByOperation(getVertexEither.left().value());
141 public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
142 return getToscaElementByOperation(componentVertex);
145 public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
147 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
148 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
149 if (getVertexEither.isRight()) {
150 JanusGraphOperationStatus status = getVertexEither.right().value();
151 if (status == JanusGraphOperationStatus.NOT_FOUND) {
152 return Either.left(false);
154 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
155 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
158 return Either.left(true);
161 public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
162 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
163 props.put(GraphPropertyEnum.UUID, component.getUUID());
164 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
165 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
167 Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
168 .getByCriteria(ModelConverter.getVertexType(component), props);
169 if (getVertexEither.isRight()) {
170 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
171 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
174 return getToscaElementByOperation(getVertexEither.left().value().get(0));
178 // region - ToscaElement - GetByOperation
179 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
180 return getToscaElementByOperation(componentV, new ComponentParametersView());
183 private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV,
184 ComponentParametersView filters) {
185 if (componentV == null) {
186 log.debug("Unexpected null value for `componentV`");
187 return Either.right(StorageOperationStatus.GENERAL_ERROR);
189 VertexTypeEnum label = componentV.getLabel();
191 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
192 if (toscaOperation != null) {
193 log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass());
196 Either<ToscaElement, StorageOperationStatus> toscaElement;
197 String componentId = componentV.getUniqueId();
198 if (toscaOperation != null) {
199 log.debug("Need to fetch tosca element for id {}", componentId);
200 toscaElement = toscaOperation.getToscaElement(componentV, filters);
202 log.debug("not supported tosca type {} for id {}", label, componentId);
203 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
205 return toscaElement.left().map(ModelConverter::convertFromToscaElement);
210 private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
211 VertexTypeEnum label = componentV.getLabel();
214 return nodeTypeOperation;
215 case TOPOLOGY_TEMPLATE:
216 return topologyTemplateOperation;
222 public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
223 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
225 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
226 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
227 if (createToscaElement.isLeft()) {
228 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
229 T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
230 return Either.left(dataModel);
232 return Either.right(createToscaElement.right().value());
235 // region - ToscaElement Delete
236 public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
238 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
239 // component already marked for delete
240 return StorageOperationStatus.OK;
243 Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
244 .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
245 if (getResponse.isRight()) {
246 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
247 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());
250 GraphVertex componentV = getResponse.left().value();
252 // same operation for node type and topology template operations
253 Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
254 if (result.isRight()) {
255 return result.right().value();
257 return StorageOperationStatus.OK;
261 public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
263 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
264 .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
265 if (getVertexEither.isRight()) {
266 log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
267 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
270 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
271 if (deleteElement.isRight()) {
272 log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
273 return Either.right(deleteElement.right().value());
275 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
277 return Either.left(dataModel);
280 private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
281 VertexTypeEnum label = componentV.getLabel();
282 Either<ToscaElement, StorageOperationStatus> toscaElement;
283 Object componentId = componentV.getUniqueId();
286 log.debug("Need to fetch node type for id {}", componentId);
287 toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
289 case TOPOLOGY_TEMPLATE:
290 log.debug("Need to fetch topology template for id {}", componentId);
291 toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
294 log.debug("not supported tosca type {} for id {}", label, componentId);
295 toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
302 private ToscaElementOperation getToscaElementOperation(Component component) {
303 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
306 public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
307 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
310 public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
311 ComponentParametersView fetchAllFilter = new ComponentParametersView();
312 fetchAllFilter.setIgnoreForwardingPath(true);
313 fetchAllFilter.setIgnoreCapabiltyProperties(false);
314 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
317 public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
318 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
322 public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
324 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
325 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
327 Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
328 .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
330 if (resources.isRight()) {
331 if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
332 return StorageOperationStatus.OK;
334 log.debug("failed to get resources from graph with property name: {}", csarUUID);
335 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value());
338 return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
342 public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
343 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
344 if (componentType == ComponentTypeEnum.RESOURCE) {
345 followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
347 followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
350 Set<T> components = new HashSet<>();
351 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
352 return Either.right(followedResources.right().value());
354 if (followedResources.isLeft()) {
355 List<ToscaElement> toscaElements = followedResources.left().value();
356 toscaElements.forEach(te -> {
357 T component = ModelConverter.convertFromToscaElement(te);
358 components.add(component);
361 return Either.left(components);
364 public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
366 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
369 public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName,
370 VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
372 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
373 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
374 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
375 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
376 Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
377 .getByCriteria(vertexType, props, parseFlag);
382 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ",
383 vertexType, toscaResourceName, status);
384 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
389 double version = 0.0;
390 GraphVertex highestResource = null;
391 for (GraphVertex resource : resources) {
392 double resourceVersion = Double
393 .parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
394 if (resourceVersion > version) {
395 version = resourceVersion;
396 highestResource = resource;
399 if (highestResource != null) {
400 return getToscaFullElement(highestResource.getUniqueId());
402 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
403 return Either.right(StorageOperationStatus.GENERAL_ERROR);
409 public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName) {
410 if (toscaResourceName != null && toscaResourceName.contains("org.openecomp.resource.vf"))
411 return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.ParseMetadata);
413 return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
416 public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
418 Either<Resource, StorageOperationStatus> result = null;
419 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
420 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
421 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
422 if (!toscaResourceName.contains("org.openecomp.resource.vf")) {
423 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
426 Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
428 if (getLatestRes.isRight()) {
429 JanusGraphOperationStatus status = getLatestRes.right().value();
430 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
431 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
433 if (result == null) {
434 List<GraphVertex> resources = getLatestRes.left().value();
435 double version = 0.0;
436 GraphVertex highestResource = null;
437 for (GraphVertex resource : resources) {
438 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
439 if (resourceVersion > version) {
440 version = resourceVersion;
441 highestResource = resource;
445 if (highestResource != null) {
446 result = getToscaFullElement(highestResource.getUniqueId());
448 log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
449 result = Either.right(StorageOperationStatus.GENERAL_ERROR);
455 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
456 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
457 if (validateUniquenessRes.isLeft()) {
458 return Either.left(!validateUniquenessRes.left().value());
460 return validateUniquenessRes;
463 public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
464 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
468 * Allows to get fulfilled requirement by relation and received predicate
470 public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
471 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
475 * Allows to get fulfilled capability by relation and received predicate
477 public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
478 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
481 public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
482 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation.associateResourceInstances(component, componentId, relations);
483 if (component != null) {
484 updateInstancesCapAndReqOnComponentFromDB(component);
486 return reqAndCapListEither;
490 protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
492 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
493 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
495 Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
496 .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
498 if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
499 log.debug("failed to get resources from graph with property name: {}", name);
500 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
502 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
503 if (isNotEmpty(resourceList)) {
504 if (log.isDebugEnabled()) {
505 StringBuilder builder = new StringBuilder();
506 for (GraphVertex resourceData : resourceList) {
507 builder.append(resourceData.getUniqueId() + "|");
509 log.debug("resources with property name:{} exists in graph. found {}", name, builder);
511 return Either.left(false);
513 log.debug("resources with property name:{} does not exists in graph", name);
514 return Either.left(true);
519 // region - Component Update
521 public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
523 copyArtifactsToNewComponent(newComponent, oldComponent);
525 Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
526 .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
527 if (componentVEither.isRight()) {
528 log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
529 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
531 GraphVertex componentv = componentVEither.left().value();
532 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
533 if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
534 log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
535 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
538 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
539 if (deleteToscaComponent.isRight()) {
540 log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
541 return Either.right(deleteToscaComponent.right().value());
543 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
544 if (createToscaComponent.isRight()) {
545 log.debug("Failed to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
546 return Either.right(createToscaComponent.right().value());
548 Resource newElement = createToscaComponent.left().value();
549 Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao
550 .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
551 if (newVersionEither.isRight()) {
552 log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
553 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value()));
555 if (parentVertexEither.isLeft()) {
556 GraphVertex previousVersionV = parentVertexEither.left().value();
557 JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
558 if (createEdge != JanusGraphOperationStatus.OK) {
559 log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
560 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
563 return Either.left(newElement);
566 void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
567 // TODO - check if required
568 Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
569 if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
570 toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
572 newComponent.setToscaArtifacts(toscaArtifacts);
574 Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
575 if (artifacts != null && !artifacts.isEmpty()) {
576 artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
578 newComponent.setArtifacts(artifacts);
580 Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
581 if (depArtifacts != null && !depArtifacts.isEmpty()) {
582 depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
584 newComponent.setDeploymentArtifacts(depArtifacts);
587 newComponent.setLastUpdateDate(null);
588 newComponent.setHighestVersion(true);
591 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
592 return updateToscaElement(componentToUpdate, new ComponentParametersView());
595 public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
596 String componentId = componentToUpdate.getUniqueId();
597 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
598 .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
599 if (getVertexEither.isRight()) {
600 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
601 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
603 GraphVertex elementV = getVertexEither.left().value();
604 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
606 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
607 Either<ToscaElement, StorageOperationStatus> updateToscaElement = null;
608 if (toscaElementOperation != null) {
609 updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
611 log.debug("Null value returned by `getToscaElementOperation` with value {}", elementV);
612 updateToscaElement = Either.right(StorageOperationStatus.GENERAL_ERROR);
615 return updateToscaElement.bimap(
616 ModelConverter::convertFromToscaElement,
618 log.debug("Failed to update tosca element {} error {}", componentId, status);
623 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
624 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
627 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
628 Either<T, StorageOperationStatus> result;
630 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
631 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
633 propertiesToMatch.put(property, nodeName);
634 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
636 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
638 Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
639 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
640 if (highestResources.isRight()) {
641 JanusGraphOperationStatus status = highestResources.right().value();
642 log.debug("failed to find resource with name {}. status={} ", nodeName, status);
643 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
647 List<GraphVertex> resources = highestResources.left().value();
648 double version = 0.0;
649 GraphVertex highestResource = null;
650 for (GraphVertex vertex : resources) {
651 Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
652 double resourceVersion = Double.parseDouble((String) versionObj);
653 if (resourceVersion > version) {
654 version = resourceVersion;
655 highestResource = vertex;
658 return getToscaElementByOperation(highestResource, filter);
662 // region - Component Get By ..
663 private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
664 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
667 public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
669 Either<List<T>, StorageOperationStatus> result = null;
670 Either<T, StorageOperationStatus> getComponentRes;
671 List<T> components = new ArrayList<>();
672 List<GraphVertex> componentVertices;
673 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
674 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
676 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
677 if (componentType != null)
678 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
680 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
682 Either<List<GraphVertex>, JanusGraphOperationStatus> getComponentsRes = janusGraphDao
683 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
684 if (getComponentsRes.isRight()) {
685 JanusGraphOperationStatus status = getComponentsRes.right().value();
686 log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
687 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
689 if (result == null) {
690 componentVertices = getComponentsRes.left().value();
691 for (GraphVertex componentVertex : componentVertices) {
692 getComponentRes = getToscaElementByOperation(componentVertex);
693 if (getComponentRes.isRight()) {
694 log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
695 result = Either.right(getComponentRes.right().value());
698 T componentBySystemName = getComponentRes.left().value();
699 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
700 components.add(componentBySystemName);
703 if (result == null) {
704 result = Either.left(components);
709 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
710 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
713 public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
714 Either<T, StorageOperationStatus> result;
716 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
717 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
719 hasProperties.put(GraphPropertyEnum.NAME, name);
720 hasProperties.put(GraphPropertyEnum.VERSION, version);
721 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
722 if (componentType != null) {
723 hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
725 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
726 .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
727 if (getResourceRes.isRight()) {
728 JanusGraphOperationStatus status = getResourceRes.right().value();
729 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
730 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
733 return getToscaElementByOperation(getResourceRes.left().value().get(0));
736 public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) {
737 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
738 .collect(Collectors.toList());
739 return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
743 public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
744 List<T> components = new ArrayList<>();
745 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
746 List<ToscaElement> toscaElements = new ArrayList<>();
747 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
748 .collect(Collectors.toList());
750 switch (componentType) {
752 catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
753 if (catalogDataResult.isRight()) {
754 return Either.right(catalogDataResult.right().value());
756 toscaElements = catalogDataResult.left().value();
759 if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
762 catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
763 if (catalogDataResult.isRight()) {
764 return Either.right(catalogDataResult.right().value());
766 toscaElements = catalogDataResult.left().value();
769 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
770 return Either.right(StorageOperationStatus.BAD_REQUEST);
772 toscaElements.forEach(te -> {
773 T component = ModelConverter.convertFromToscaElement(te);
774 components.add(component);
776 return Either.left(components);
779 public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
780 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
781 switch (componentType) {
783 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
787 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
790 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
791 return Either.right(StorageOperationStatus.BAD_REQUEST);
793 if (allComponentsMarkedForDeletion.isRight()) {
794 return Either.right(allComponentsMarkedForDeletion.right().value());
796 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
797 return Either.left(checkIfInUseAndDelete(allMarked));
800 private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
801 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
802 List<String> deleted = new ArrayList<>();
804 for (GraphVertex elementV : allMarked) {
805 boolean isAllowedToDelete = true;
807 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
808 Either<Edge, JanusGraphOperationStatus> belongingEdgeByCriteria = janusGraphDao
809 .getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null);
810 if (belongingEdgeByCriteria.isLeft()) {
811 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
812 isAllowedToDelete = false;
817 if (isAllowedToDelete) {
818 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
819 if (deleteToscaElement.isRight()) {
820 log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
823 deleted.add(elementV.getUniqueId());
829 public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
830 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
831 switch (componentType) {
833 allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
837 allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
840 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
841 return Either.right(StorageOperationStatus.BAD_REQUEST);
843 if (allComponentsMarkedForDeletion.isRight()) {
844 return Either.right(allComponentsMarkedForDeletion.right().value());
846 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
849 // region - Component Update
850 public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
852 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
853 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
854 if (StringUtils.isEmpty(componentInstance.getIcon())) {
855 componentInstance.setIcon(origComponent.getIcon());
857 String nameToFindForCounter;
858 switch (componentInstance.getOriginType()) {
860 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName()) + PROXY_SUFFIX;
862 case ServiceSubstitution:
863 nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName());
866 nameToFindForCounter = origComponent.getName();
868 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
869 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
870 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
872 if (addResult.isRight()) {
873 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
874 result = Either.right(addResult.right().value());
876 if (result == null) {
877 updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
878 if (updateContainerComponentRes.isRight()) {
879 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
880 result = Either.right(updateContainerComponentRes.right().value());
883 if (result == null) {
884 Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
885 String createdInstanceId = addResult.left().value().getRight();
886 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
887 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
892 public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted, boolean isUpdateCsar) {
893 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
895 Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
896 .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
897 if (metadataVertex.isRight()) {
898 JanusGraphOperationStatus status = metadataVertex.right().value();
899 if (status == JanusGraphOperationStatus.NOT_FOUND) {
900 status = JanusGraphOperationStatus.INVALID_ID;
902 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
905 Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted, isUpdateCsar);
907 containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
911 public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
913 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
915 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
916 componentInstance.setIcon(origComponent.getIcon());
917 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
918 ModelConverter.convertToToscaElement(origComponent), componentInstance);
919 if (updateResult.isRight()) {
920 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
921 result = Either.right(updateResult.right().value());
923 if (result == null) {
924 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
925 String createdInstanceId = updateResult.left().value().getRight();
926 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
927 result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
932 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
933 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
936 public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
938 Either<Component, StorageOperationStatus> result = null;
940 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
942 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
943 if (updateResult.isRight()) {
944 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
945 result = Either.right(updateResult.right().value());
947 if (result == null) {
948 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
949 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
950 result = Either.left(updatedComponent);
956 public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
958 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
960 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
962 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
963 if (updateResult.isRight()) {
964 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
965 result = Either.right(updateResult.right().value());
967 if (result == null) {
968 Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
969 String deletedInstanceId = updateResult.left().value().getRight();
970 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
971 result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
976 private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
977 Integer nextCounter = 0;
978 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
979 String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
980 Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
981 if (maxCounter != null) {
982 nextCounter = maxCounter + 1;
985 return nextCounter.toString();
989 * @return max counter of component instance Id's, null if not found
991 private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
992 List<String> countersInNames = containerComponent.getComponentInstances().stream()
993 .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
994 .map(ci -> ci.getNormalizedName().split(normalizedName)[1])
995 .collect(Collectors.toList());
996 List<String> countersInIds = containerComponent.getComponentInstances().stream()
997 .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
998 .map(ci -> ci.getUniqueId().split(normalizedName)[1])
999 .collect(Collectors.toList());
1000 List<String> namesAndIdsList = new ArrayList<>(countersInNames);
1001 namesAndIdsList.addAll(countersInIds);
1002 return getMaxInteger(namesAndIdsList);
1005 private Integer getMaxInteger(List<String> counters) {
1006 Integer maxCounter = 0;
1007 Integer currCounter = null;
1008 for (String counter : counters) {
1010 currCounter = Integer.parseInt(counter);
1011 if (maxCounter < currCounter) {
1012 maxCounter = currCounter;
1014 } catch (NumberFormatException e) {
1018 return currCounter == null ? null : maxCounter;
1021 public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef requirementDef) {
1022 return nodeTemplateOperation.associateResourceInstances(component, componentId, requirementDef);
1026 public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
1028 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1029 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1030 if (getVertexEither.isRight()) {
1031 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1032 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1036 GraphVertex vertex = getVertexEither.left().value();
1037 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1039 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
1041 if (StorageOperationStatus.OK == status) {
1042 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1043 List<InputDefinition> inputsResList = null;
1044 if (inputsMap != null && !inputsMap.isEmpty()) {
1045 inputsResList = inputsMap.values().stream()
1046 .map(InputDefinition::new)
1047 .collect(Collectors.toList());
1049 return Either.left(inputsResList);
1051 return Either.right(status);
1055 public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1057 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1058 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1059 if (getVertexEither.isRight()) {
1060 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1061 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1065 GraphVertex vertex = getVertexEither.left().value();
1066 Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
1068 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1070 if (StorageOperationStatus.OK == status) {
1071 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1072 List<InputDefinition> inputsResList = null;
1073 if (inputsMap != null && !inputsMap.isEmpty()) {
1074 inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
1076 return Either.left(inputsResList);
1078 return Either.right(status);
1083 * Add data types into a Component.
1085 * @param dataTypes datatypes to be added. the key should be each name of data type.
1086 * @param componentId unique ID of Component.
1087 * @return list of data types.
1089 public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes, String componentId) {
1091 log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
1093 /* get component vertex */
1094 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1095 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1096 if (getVertexEither.isRight()) {
1097 /* not found / error */
1098 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1099 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1101 GraphVertex vertex = getVertexEither.left().value();
1102 log.trace("#addDataTypesToComponent - get vertex ok");
1104 // convert DataTypeDefinition to DataTypeDataDefinition
1105 Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
1106 .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
1108 // add datatype(s) to the Component.
1109 // if child vertex does not exist, it will be created.
1110 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex,
1111 EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
1113 if (StorageOperationStatus.OK == status) {
1114 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1115 List<DataTypeDefinition> inputsResList = null;
1116 if (!dataTypes.isEmpty()) {
1117 inputsResList = new ArrayList<>(dataTypes.values());
1119 return Either.left(inputsResList);
1122 log.trace("#addDataTypesToComponent - leave");
1123 return Either.right(status);
1126 private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
1127 DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
1128 if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
1129 List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream()
1130 .map(PropertyDataDefinition::new).collect(Collectors.toList());
1131 dataTypeData.setPropertiesData(propertyDataList);
1134 // if "derivedFrom" data_type exists, copy the name to "derivedFromName"
1135 if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
1136 // if names are different, log it
1137 if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
1138 log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})",
1139 dataType.getDerivedFromName(), dataType.getDerivedFrom().getName());
1141 dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
1144 // supply "name" field to toscaPresentationValue in each datatype object for DAO operations
1145 dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
1146 return dataTypeData;
1150 public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
1152 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1153 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1154 if (getVertexEither.isRight()) {
1155 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1156 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1160 Either<ToscaElement, StorageOperationStatus> toscaElement =
1161 topologyTemplateOperation.getToscaElement(componentId);
1162 if(toscaElement.isRight()) {
1163 return Either.right(toscaElement.right().value());
1166 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
1168 Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
1170 List<InputDefinition> inputs = new ArrayList<>();
1171 if(MapUtils.isNotEmpty(inputsMap)) {
1173 inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
1176 return Either.left(inputs);
1179 public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1181 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1182 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1183 if (getVertexEither.isRight()) {
1184 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1185 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1189 GraphVertex vertex = getVertexEither.left().value();
1190 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1192 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1194 if (StorageOperationStatus.OK == status) {
1195 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1196 List<InputDefinition> inputsResList = null;
1197 if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1198 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1200 return Either.left(inputsResList);
1202 return Either.right(status);
1206 // region - ComponentInstance
1207 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1209 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1210 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1211 if (getVertexEither.isRight()) {
1212 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1213 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1217 GraphVertex vertex = getVertexEither.left().value();
1218 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1219 if (instProperties != null) {
1221 MapPropertiesDataDefinition propertiesMap;
1222 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1223 propertiesMap = new MapPropertiesDataDefinition();
1225 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1227 instPropsMap.put(entry.getKey(), propertiesMap);
1231 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1233 if (StorageOperationStatus.OK == status) {
1234 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1235 return Either.left(instProperties);
1237 return Either.right(status);
1242 * saves the instInputs as the updated instance inputs of the component container in DB
1244 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1245 if (instInputs == null || instInputs.isEmpty()) {
1246 return Either.left(instInputs);
1248 StorageOperationStatus status;
1249 for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
1250 List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1251 List<String> pathKeysPerInst = new ArrayList<>();
1252 pathKeysPerInst.add(inputsPerIntance.getKey());
1253 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1254 if (status != StorageOperationStatus.OK) {
1255 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
1256 return Either.right(status);
1260 return Either.left(instInputs);
1264 * saves the instProps as the updated instance properties of the component container in DB
1266 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1267 if (instProps == null || instProps.isEmpty()) {
1268 return Either.left(instProps);
1270 StorageOperationStatus status;
1271 for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
1272 List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1273 List<String> pathKeysPerInst = new ArrayList<>();
1274 pathKeysPerInst.add(propsPerIntance.getKey());
1275 status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1276 if (status != StorageOperationStatus.OK) {
1277 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
1278 return Either.right(status);
1282 return Either.left(instProps);
1285 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1287 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
1288 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
1289 if (getVertexEither.isRight()) {
1290 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1291 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
1294 GraphVertex vertex = getVertexEither.left().value();
1295 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1296 if (instInputs != null) {
1298 MapPropertiesDataDefinition propertiesMap;
1299 for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1300 propertiesMap = new MapPropertiesDataDefinition();
1302 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
1304 instPropsMap.put(entry.getKey(), propertiesMap);
1308 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1310 if (StorageOperationStatus.OK == status) {
1311 log.debug(COMPONENT_CREATED_SUCCESSFULLY);
1312 return Either.left(instInputs);
1314 return Either.right(status);
1318 public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1319 requireNonNull(instProperties);
1320 StorageOperationStatus status;
1321 for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1322 List<ComponentInstanceInput> props = entry.getValue();
1323 String componentInstanceId = entry.getKey();
1324 if (!isEmpty(props)) {
1325 for (ComponentInstanceInput property : props) {
1326 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
1327 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
1328 .filter(p -> p.getName().equals(property.getName()))
1330 if (instanceProperty.isPresent()) {
1331 status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
1333 status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
1335 if (status != StorageOperationStatus.OK) {
1336 log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
1337 return Either.right(status);
1339 log.trace("instance input {} for instance {} updated", property, componentInstanceId);
1344 return Either.left(instProperties);
1347 public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
1348 requireNonNull(instProperties);
1349 for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1350 List<ComponentInstanceProperty> props = entry.getValue();
1351 String componentInstanceId = entry.getKey();
1352 List<ComponentInstanceProperty> originalComponentInstProps =
1353 containerComponent.getComponentInstancesProperties().get(componentInstanceId);
1354 Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
1356 if(isEmpty(props)) {
1359 for (ComponentInstanceProperty property : props) {
1360 StorageOperationStatus status = null;
1361 String propertyParentUniqueId = property.getParentUniqueId();
1362 Optional<CapabilityDefinition>
1363 capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
1364 if(capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
1365 status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId,
1366 containerComponentCapabilities, property, capPropDefinition.get());
1368 if(status == null) {
1369 status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId,
1370 originalComponentInstProps, property);
1372 if(status != StorageOperationStatus.OK) {
1373 return Either.right(status);
1377 return Either.left(instProperties);
1380 private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId,
1381 Map<String, List<CapabilityDefinition>> containerComponentCapabilities,
1382 ComponentInstanceProperty property,
1383 CapabilityDefinition capabilityDefinition) {
1384 List<CapabilityDefinition> capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType());
1385 if(CollectionUtils.isEmpty(capabilityDefinitions)) {
1388 Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
1389 .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
1390 if(capDefToGetProp.isPresent()) {
1391 return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
1396 private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId,
1397 Component containerComponent) {
1399 Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
1400 if(MapUtils.isEmpty(componentCapabilities)){
1401 return Optional.empty();
1403 List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
1404 .stream().flatMap(Collection::stream).collect(Collectors.toList());
1405 if(CollectionUtils.isEmpty(capabilityDefinitionList)){
1406 return Optional.empty();
1408 return capabilityDefinitionList.stream()
1409 .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
1413 private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent,
1414 String componentInstanceId, List<ComponentInstanceProperty> originalComponentInstProps,
1415 ComponentInstanceProperty property)
1417 StorageOperationStatus status;
1418 // check if the property already exists or not
1419 Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
1420 .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1421 if (instanceProperty.isPresent()) {
1422 status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
1424 status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
1426 if (status != StorageOperationStatus.OK) {
1427 log.debug("Failed to update instance property {} for instance {} error {} ",
1428 property, componentInstanceId, status);
1433 public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
1434 ComponentInstanceProperty property,
1435 CapabilityDefinition capabilityDefinition) {
1436 Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1437 if(!fetchedCIOptional.isPresent()) {
1438 return StorageOperationStatus.GENERAL_ERROR;
1440 Either<Component, StorageOperationStatus> getComponentRes =
1441 getToscaFullElement(fetchedCIOptional.get().getComponentUid());
1442 if(getComponentRes.isRight()) {
1443 return StorageOperationStatus.GENERAL_ERROR;
1445 Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
1447 if(!componentOptional.isPresent()) {
1448 propOwner = componentInstanceId;
1450 propOwner = fetchedCIOptional.get().getSourceModelUid();
1452 StorageOperationStatus status;
1453 StringBuilder sb = new StringBuilder(componentInstanceId);
1454 sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM)
1455 .append(capabilityDefinition.getType()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
1456 String capKey = sb.toString();
1457 status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
1458 if (status != StorageOperationStatus.OK) {
1459 log.debug("Failed to update instance capability property {} for instance {} error {} ", property,
1460 componentInstanceId, status);
1463 return StorageOperationStatus.OK;
1466 private Optional<Component> isNodeServiceProxy(Component component) {
1467 if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
1468 return Optional.empty();
1470 Resource resource = (Resource) component;
1471 ResourceTypeEnum resType = resource.getResourceType();
1472 if(resType.equals(ResourceTypeEnum.ServiceProxy)) {
1473 return Optional.of(component);
1475 return Optional.empty();
1478 public StorageOperationStatus associateCapabilitiesToService(Map<String,ListCapabilityDataDefinition> capabilities, String componentId) {
1480 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1481 if (getVertexEither.isRight()) {
1482 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1483 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1487 GraphVertex vertex = getVertexEither.left().value();
1488 if(MapUtils.isNotEmpty(capabilities)) {
1489 Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation.
1490 associateElementToData(vertex, VertexTypeEnum.CAPABILITIES,
1491 EdgeLabelEnum.CAPABILITIES, capabilities);
1492 if (associateElementToData.isRight()) {
1493 return associateElementToData.right().value();
1498 return StorageOperationStatus.OK;
1502 public StorageOperationStatus associateRequirementsToService(Map<String, ListRequirementDataDefinition> requirements, String componentId) {
1504 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1505 if (getVertexEither.isRight()) {
1506 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
1507 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1511 GraphVertex vertex = getVertexEither.left().value();
1512 if(MapUtils.isNotEmpty(requirements)) {
1513 Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation.
1514 associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS,
1515 EdgeLabelEnum.REQUIREMENTS, requirements);
1516 if (associateElementToData.isRight()) {
1517 return associateElementToData.right().value();
1521 return StorageOperationStatus.OK;
1525 public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Component component, User user) {
1527 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1528 if (getVertexEither.isRight()) {
1529 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1530 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1534 GraphVertex vertex = getVertexEither.left().value();
1535 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1536 if (instDeploymentArtifacts != null) {
1538 MapArtifactDataDefinition artifactsMap;
1539 for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1540 Map<String, ArtifactDefinition> artList = entry.getValue();
1541 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1542 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1544 instArtMap.put(entry.getKey(), artifactsMap);
1547 ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component);
1548 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1551 public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
1553 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1554 if (getVertexEither.isRight()) {
1555 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1556 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1560 GraphVertex vertex = getVertexEither.left().value();
1561 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1562 if (instArtifacts != null) {
1564 MapArtifactDataDefinition artifactsMap;
1565 for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1566 Map<String, ArtifactDefinition> artList = entry.getValue();
1567 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1568 artifactsMap = new MapArtifactDataDefinition(artifacts);
1570 instArtMap.put(entry.getKey(), artifactsMap);
1573 ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
1574 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1578 public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDataDefinition>> instArttributes, Component component) {
1580 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1581 if (getVertexEither.isRight()) {
1582 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1583 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1587 GraphVertex vertex = getVertexEither.left().value();
1588 Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
1589 if (instArttributes != null) {
1591 MapAttributesDataDefinition attributesMap;
1592 for (Entry<String, List<AttributeDataDefinition>> entry : instArttributes.entrySet()) {
1593 final List<AttributeDataDefinition> value = entry.getValue();
1594 attributesMap = new MapAttributesDataDefinition();
1595 attributesMap.setMapToscaDataDefinition(value.stream().map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, e -> e)));
1596 instAttr.put(entry.getKey(), attributesMap);
1599 setComponentInstanceAttributesOnComponent(component, instAttr);
1600 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1604 private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
1605 Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
1606 if (componentInstancesAttributes == null)
1607 componentInstancesAttributes = new HashMap<>();
1608 componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
1609 resource.setComponentInstancesAttributes(componentInstancesAttributes);
1612 public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, Component component) {
1613 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
1614 if (getVertexEither.isRight()) {
1615 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
1616 return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
1620 GraphVertex vertex = getVertexEither.left().value();
1622 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1624 Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
1625 Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
1626 if (instCapabilties != null) {
1627 for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1629 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1630 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1631 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1632 mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
1635 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1636 MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1638 MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1640 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1641 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
1645 if (instReg != null) {
1646 for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1648 Map<String, List<RequirementDefinition>> req = entry.getValue();
1649 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1650 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1651 mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
1654 MapListRequirementDataDefinition reqMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1656 String componentInstanceId = entry.getKey().getUniqueId();
1657 calcRequirements.put(componentInstanceId, reqMap);
1661 StorageOperationStatus storageOperationStatus = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1662 updateInstancesCapAndReqOnComponentFromDB(component);
1663 return storageOperationStatus;
1666 private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
1667 ComponentParametersView componentParametersView = new ComponentParametersView(true);
1668 componentParametersView.setIgnoreCapabilities(false);
1669 componentParametersView.setIgnoreRequirements(false);
1670 componentParametersView.setIgnoreCapabiltyProperties(false);
1671 componentParametersView.setIgnoreComponentInstances(false);
1672 Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView);
1673 if (componentEither.isRight()) {
1674 throw new StorageException(StorageOperationStatus.NOT_FOUND);
1676 Component updatedComponent = componentEither.left().value();
1677 component.setCapabilities(updatedComponent.getCapabilities());
1678 component.setRequirements(updatedComponent.getRequirements());
1679 component.setComponentInstances(updatedComponent.getComponentInstances());
1682 private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1683 List<Service> services = new ArrayList<>();
1684 List<LifecycleStateEnum> states = new ArrayList<>();
1686 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1687 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1690 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1691 hasNotProps.put(GraphPropertyEnum.STATE, states);
1692 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1693 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1694 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1697 private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1698 List<Service> services = null;
1699 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1700 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1701 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1702 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
1703 .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1704 if (getRes.isRight()) {
1705 if (getRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
1706 return Either.left(new ArrayList<>());
1708 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
1711 // region -> Fetch non checked-out services
1712 if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
1713 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1714 if (result.isRight()) {
1715 log.debug("Failed to fetch services for");
1716 return Either.right(result.right().value());
1718 services = result.left().value();
1719 if (log.isTraceEnabled() && isEmpty(services))
1720 log.trace("No relevant services available");
1723 List<Component> nonAbstractLatestComponents = new ArrayList<>();
1724 ComponentParametersView params = new ComponentParametersView(true);
1725 params.setIgnoreAllVersions(false);
1726 for (GraphVertex vertexComponent : getRes.left().value()) {
1727 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1728 if (componentRes.isRight()) {
1729 log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1730 return Either.right(componentRes.right().value());
1732 Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1733 nonAbstractLatestComponents.add(component);
1736 if (CollectionUtils.isNotEmpty(services)) {
1737 nonAbstractLatestComponents.addAll(services);
1739 return Either.left(nonAbstractLatestComponents);
1742 public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1744 Either<ComponentMetadataData, StorageOperationStatus> result;
1745 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1746 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1747 if (isHighest != null) {
1748 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
1750 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1751 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1752 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
1754 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
1755 .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1756 if (getRes.isRight()) {
1757 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
1759 List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1760 ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1761 : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1762 result = Either.left(latestVersion);
1767 public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1768 Either<ComponentMetadataData, StorageOperationStatus> result;
1769 Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
1770 .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1771 if (getRes.isRight()) {
1772 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
1774 ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1775 result = Either.left(componentMetadata);
1780 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
1781 String internalComponentType, List<String> componentUids) {
1783 List<Component> components = new ArrayList<>();
1784 if (componentUids == null) {
1785 Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
1786 if (componentUidsRes.isRight()) {
1787 return Either.right(componentUidsRes.right().value());
1789 componentUids = componentUidsRes.left().value();
1791 if (!isEmpty(componentUids)) {
1792 for (String componentUid : componentUids) {
1793 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1794 if ("vl".equalsIgnoreCase(internalComponentType)) {
1795 componentParametersView.setIgnoreCapabilities(false);
1796 componentParametersView.setIgnoreRequirements(false);
1798 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1799 if (getToscaElementRes.isRight()) {
1800 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1801 return Either.right(getToscaElementRes.right().value());
1803 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1804 nullifySomeComponentProperties(component);
1805 components.add(component);
1808 return Either.left(components);
1811 public void nullifySomeComponentProperties(Component component) {
1812 component.setContactId(null);
1813 component.setCreationDate(null);
1814 component.setCreatorUserId(null);
1815 component.setCreatorFullName(null);
1816 component.setLastUpdateDate(null);
1817 component.setLastUpdaterUserId(null);
1818 component.setLastUpdaterFullName(null);
1819 component.setNormalizedName(null);
1822 private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1824 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
1825 if (getToscaElementsRes.isRight()) {
1826 return Either.right(getToscaElementsRes.right().value());
1828 List<Component> collection = getToscaElementsRes.left().value();
1829 List<String> componentUids;
1830 if (collection == null) {
1831 componentUids = new ArrayList<>();
1833 componentUids = collection.stream()
1834 .map(Component::getUniqueId)
1835 .collect(Collectors.toList());
1837 return Either.left(componentUids);
1840 private ComponentParametersView buildComponentViewForNotAbstract() {
1841 ComponentParametersView componentParametersView = new ComponentParametersView();
1842 componentParametersView.disableAll();
1843 componentParametersView.setIgnoreCategories(false);
1844 componentParametersView.setIgnoreAllVersions(false);
1845 return componentParametersView;
1848 public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1849 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1850 if (result.isLeft()) {
1851 result = Either.left(!result.left().value());
1856 public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1857 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1858 String normalizedName = ValidationUtils.normaliseComponentName(name);
1859 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1860 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1861 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1863 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
1864 .getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1865 if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
1866 log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1867 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
1869 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1870 if (vertexList != null && !vertexList.isEmpty()) {
1871 return Either.left(false);
1873 return Either.left(true);
1877 private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps,
1878 final Map<GraphPropertyEnum, Object> hasNotProps,
1879 final String internalComponentType) {
1880 final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
1881 final List<String> allowedTypes;
1883 if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
1884 allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
1886 final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
1887 allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
1889 final List<String> allResourceTypes = configuration.getResourceTypes();
1890 if (allowedTypes == null) {
1891 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
1895 if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
1896 hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
1898 final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s))
1899 .collect(Collectors.toList());
1900 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
1904 private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
1905 switch (componentTypeEnum) {
1907 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1910 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1915 hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1918 private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1919 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1921 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1922 hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
1923 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1924 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1925 hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1926 if (internalComponentType != null) {
1927 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1930 fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
1934 private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1935 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1936 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1937 internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1939 if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
1940 internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1942 return internalVertexTypes;
1945 public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1946 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1947 List<Component> result = new ArrayList<>();
1948 for (VertexTypeEnum vertexType : internalVertexTypes) {
1949 Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
1950 if (listByVertexType.isRight()) {
1951 return listByVertexType;
1953 result.addAll(listByVertexType.left().value());
1955 return Either.left(result);
1959 private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1960 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1961 if (additionalPropertiesToMatch != null) {
1962 propertiesToMatch.putAll(additionalPropertiesToMatch);
1964 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1965 return getComponentListByUuid(componentUuid, propertiesToMatch);
1968 public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1969 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1971 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1972 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1974 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1975 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1976 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
1977 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1978 if (vertexEither.isRight()) {
1979 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
1982 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1983 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1984 return Either.right(StorageOperationStatus.NOT_FOUND);
1987 return getToscaElementByOperation(vertexList.get(0));
1990 public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1992 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1994 if (additionalPropertiesToMatch != null) {
1995 propertiesToMatch.putAll(additionalPropertiesToMatch);
1998 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
2000 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2001 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2002 propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
2004 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2005 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2007 if (vertexEither.isRight()) {
2008 log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
2009 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2011 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2013 if (vertexList == null || vertexList.isEmpty()) {
2014 log.debug("Component with uuid {} was not found", componentUuid);
2015 return Either.right(StorageOperationStatus.NOT_FOUND);
2018 ArrayList<Component> latestComponents = new ArrayList<>();
2019 for (GraphVertex vertex : vertexList) {
2020 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2022 if (toscaElementByOperation.isRight()) {
2023 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
2024 return Either.right(toscaElementByOperation.right().value());
2027 latestComponents.add(toscaElementByOperation.left().value());
2030 if (latestComponents.size() > 1) {
2031 for (Component component : latestComponents) {
2032 if (component.isHighestVersion()) {
2033 LinkedList<Component> highestComponent = new LinkedList<>();
2034 highestComponent.add(component);
2035 return Either.left(highestComponent);
2040 return Either.left(latestComponents);
2043 public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
2044 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2045 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2046 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
2049 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
2050 return getLatestComponentByUuid(componentUuid, null);
2053 public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
2055 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
2057 if (latestVersionListEither.isRight()) {
2058 return Either.right(latestVersionListEither.right().value());
2061 List<Component> latestVersionList = latestVersionListEither.left().value();
2063 if (latestVersionList.isEmpty()) {
2064 return Either.right(StorageOperationStatus.NOT_FOUND);
2066 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
2068 return Either.left(component);
2071 public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
2073 List<Resource> resources = new ArrayList<>();
2074 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2075 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2077 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
2078 if (isHighest != null) {
2079 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
2081 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2082 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
2083 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2085 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
2086 .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2088 if (getResourcesRes.isRight()) {
2089 log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
2090 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
2092 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
2093 for (GraphVertex resourceV : resourceVerticies) {
2094 Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
2095 if (getResourceRes.isRight()) {
2096 return Either.right(getResourceRes.right().value());
2098 resources.add(getResourceRes.left().value());
2100 return Either.left(resources);
2103 public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
2104 Either<T, StorageOperationStatus> result;
2106 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
2107 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
2109 hasProperties.put(GraphPropertyEnum.NAME, name);
2110 hasProperties.put(GraphPropertyEnum.VERSION, version);
2111 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2113 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
2115 Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
2116 .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
2117 if (getResourceRes.isRight()) {
2118 JanusGraphOperationStatus status = getResourceRes.right().value();
2119 log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
2120 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2123 return getToscaElementByOperation(getResourceRes.left().value().get(0));
2126 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
2127 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
2130 public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
2131 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2132 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
2133 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
2134 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2135 if (componentType != null) {
2136 props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
2138 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
2140 GraphVertex resourceMetadataData = null;
2141 List<GraphVertex> resourceMetadataDataList = null;
2142 Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
2143 .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
2144 if (byCsar.isRight()) {
2145 if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
2146 // Fix Defect DE256036
2147 if (StringUtils.isEmpty(systemName)) {
2148 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
2149 JanusGraphOperationStatus.NOT_FOUND));
2153 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2154 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
2155 Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
2156 .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
2157 if (bySystemname.isRight()) {
2158 log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
2159 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
2161 if (bySystemname.left().value().size() > 2) {
2162 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
2163 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2165 resourceMetadataDataList = bySystemname.left().value();
2166 if (resourceMetadataDataList.size() == 1) {
2167 resourceMetadataData = resourceMetadataDataList.get(0);
2169 for (GraphVertex curResource : resourceMetadataDataList) {
2170 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2171 resourceMetadataData = curResource;
2176 if (resourceMetadataData == null) {
2177 log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
2178 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2180 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
2181 log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
2182 // correct error will be returned from create flow. with all
2183 // correct audit records!!!!!
2184 return Either.right(StorageOperationStatus.NOT_FOUND);
2186 return getToscaElement((String) resourceMetadataData.getUniqueId());
2189 resourceMetadataDataList = byCsar.left().value();
2190 if (resourceMetadataDataList.size() > 2) {
2191 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
2192 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2194 if (resourceMetadataDataList.size() == 1) {
2195 resourceMetadataData = resourceMetadataDataList.get(0);
2197 for (GraphVertex curResource : resourceMetadataDataList) {
2198 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
2199 resourceMetadataData = curResource;
2204 if (resourceMetadataData == null) {
2205 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
2206 return Either.right(StorageOperationStatus.GENERAL_ERROR);
2208 return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
2213 public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
2215 String currentTemplateNameChecked = templateNameExtends;
2217 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
2218 Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
2220 if (latestByToscaResourceName.isRight()) {
2221 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
2224 Resource value = latestByToscaResourceName.left().value();
2226 if (value.getDerivedFrom() != null) {
2227 currentTemplateNameChecked = value.getDerivedFrom().get(0);
2229 currentTemplateNameChecked = null;
2233 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
2236 public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
2237 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
2238 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
2239 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
2240 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2241 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2242 Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
2243 .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
2245 if (resourcesByTypeEither.isRight()) {
2246 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
2249 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
2250 List<Component> components = new ArrayList<>();
2252 for (GraphVertex vertex : vertexList) {
2253 components.add(getToscaElementByOperation(vertex, filterBy).left().value());
2256 return Either.left(components);
2259 public void commit() {
2260 janusGraphDao.commit();
2263 public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
2264 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
2265 if (updateDistributionStatus.isRight()) {
2266 return Either.right(updateDistributionStatus.right().value());
2268 GraphVertex serviceV = updateDistributionStatus.left().value();
2269 service.setDistributionStatus(distributionStatus);
2270 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
2271 return Either.left(service);
2274 public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
2276 Either<ComponentMetadataData, StorageOperationStatus> result = null;
2277 GraphVertex serviceVertex;
2278 Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
2279 Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
2280 .getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
2281 if (getRes.isRight()) {
2282 JanusGraphOperationStatus status = getRes.right().value();
2283 log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
2284 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
2286 if (result == null) {
2287 serviceVertex = getRes.left().value();
2288 long lastUpdateDate = System.currentTimeMillis();
2289 serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
2290 component.setLastUpdateDate(lastUpdateDate);
2291 updateRes = janusGraphDao.updateVertex(serviceVertex);
2292 if (updateRes.isRight()) {
2293 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
2296 if (result == null) {
2297 result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
2302 public HealingJanusGraphDao getJanusGraphDao() {
2303 return janusGraphDao;
2306 public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2307 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2308 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2310 return getServicesWithDistStatus(distStatus, propertiesToMatch);
2313 public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2315 List<Service> servicesAll = new ArrayList<>();
2317 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2318 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2320 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2321 propertiesToMatch.putAll(additionalPropertiesToMatch);
2324 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2326 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2328 if (distStatus != null && !distStatus.isEmpty()) {
2329 for (DistributionStatusEnum state : distStatus) {
2330 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2331 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2332 if (fetchServicesByCriteria.isRight()) {
2333 return fetchServicesByCriteria;
2335 servicesAll = fetchServicesByCriteria.left().value();
2338 return Either.left(servicesAll);
2340 return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2344 private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2345 Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
2346 .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2347 if (getRes.isRight()) {
2348 if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
2349 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2350 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
2353 for (GraphVertex vertex : getRes.left().value()) {
2354 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2356 if (getServiceRes.isRight()) {
2357 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2358 return Either.right(getServiceRes.right().value());
2360 servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2364 return Either.left(servicesAll);
2367 public void rollback() {
2368 janusGraphDao.rollback();
2371 public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2372 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2374 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2377 public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
2378 StorageOperationStatus status = StorageOperationStatus.OK;
2379 if (MapUtils.isNotEmpty(artifacts)) {
2380 Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2381 status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2386 public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2387 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2390 public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2391 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2394 public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName,
2395 PropertyDefinition newPropertyDefinition,
2396 Component component) {
2397 newPropertyDefinition.setName(propertyName);
2399 StorageOperationStatus status = getToscaElementOperation(component)
2400 .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2401 if (status != StorageOperationStatus.OK) {
2402 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status);
2403 return Either.right(status);
2406 ComponentParametersView filter = new ComponentParametersView(true);
2407 filter.setIgnoreProperties(false);
2408 filter.setIgnoreInputs(false);
2409 Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2410 if (getUpdatedComponentRes.isRight()) {
2411 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2412 return Either.right(status);
2415 PropertyDefinition newProperty = null;
2416 List<PropertyDefinition> properties =
2417 (getUpdatedComponentRes.left().value()).getProperties();
2418 if (CollectionUtils.isNotEmpty(properties)) {
2419 Optional<PropertyDefinition> propertyOptional = properties.stream().filter(
2420 propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny();
2421 if (propertyOptional.isPresent()) {
2422 newProperty = propertyOptional.get();
2425 if (newProperty == null) {
2426 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2427 return Either.right(StorageOperationStatus.NOT_FOUND);
2430 return Either.left(newProperty);
2433 public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
2434 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2437 public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2438 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2441 public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2442 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2446 * Deletes a data type from a component.
2447 * @param component the container which has the data type
2448 * @param dataTypeName the data type name to be deleted
2449 * @return Operation result.
2451 public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
2452 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName, JsonPresentationFields.NAME);
2455 public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
2456 PropertyDefinition newPropertyDefinition) {
2458 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2459 Either<PropertyDefinition, StorageOperationStatus> result = null;
2460 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2461 if (status != StorageOperationStatus.OK) {
2462 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status);
2463 result = Either.right(status);
2465 if (result == null) {
2466 ComponentParametersView filter = new ComponentParametersView(true);
2467 filter.setIgnoreProperties(false);
2468 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2469 if (getUpdatedComponentRes.isRight()) {
2470 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2471 result = Either.right(status);
2474 if (result == null) {
2475 Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value())
2476 .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2477 if (newProperty.isPresent()) {
2478 result = Either.left(newProperty.get());
2480 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2481 result = Either.right(StorageOperationStatus.NOT_FOUND);
2488 public Either<AttributeDataDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) {
2490 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2491 Either<AttributeDataDefinition, StorageOperationStatus> result = null;
2492 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2493 String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2494 newAttributeDef.setUniqueId(attUniqueId);
2497 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2498 if (status != StorageOperationStatus.OK) {
2499 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2500 result = Either.right(status);
2502 if (result == null) {
2503 ComponentParametersView filter = new ComponentParametersView(true);
2504 filter.setIgnoreAttributesFrom(false);
2505 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2506 if (getUpdatedComponentRes.isRight()) {
2507 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2508 result = Either.right(status);
2511 if (result == null) {
2512 Optional<AttributeDataDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2513 if (newAttribute.isPresent()) {
2514 result = Either.left(newAttribute.get());
2516 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2517 result = Either.right(StorageOperationStatus.NOT_FOUND);
2523 public Either<AttributeDataDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) {
2525 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2526 Either<AttributeDataDefinition, StorageOperationStatus> result = null;
2527 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2528 if (status != StorageOperationStatus.OK) {
2529 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
2530 result = Either.right(status);
2532 if (result == null) {
2533 ComponentParametersView filter = new ComponentParametersView(true);
2534 filter.setIgnoreAttributesFrom(false);
2535 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2536 if (getUpdatedComponentRes.isRight()) {
2537 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2538 result = Either.right(status);
2541 if (result == null) {
2542 Optional<AttributeDataDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2543 if (newProperty.isPresent()) {
2544 result = Either.left(newProperty.get());
2546 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2547 result = Either.right(StorageOperationStatus.NOT_FOUND);
2553 public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2555 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2556 Either<InputDefinition, StorageOperationStatus> result = null;
2557 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2558 if (status != StorageOperationStatus.OK) {
2559 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2560 result = Either.right(status);
2562 if (result == null) {
2563 ComponentParametersView filter = new ComponentParametersView(true);
2564 filter.setIgnoreInputs(false);
2565 getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2566 if (getUpdatedComponentRes.isRight()) {
2567 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
2568 result = Either.right(status);
2571 if (result == null) {
2572 Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2573 if (updatedInput.isPresent()) {
2574 result = Either.left(updatedInput.get());
2576 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2577 result = Either.right(StorageOperationStatus.NOT_FOUND);
2584 * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2586 * @param containerComponent - container such as service
2587 * @param componentInstance - context component
2588 * @param componentInstanceId - id
2589 * @return - successfull/failed status
2591 public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2592 String uniqueId = componentInstance.getUniqueId();
2593 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2594 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2595 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2596 return Either.right(status);
2598 if (componentInstance.getGroupInstances() != null) {
2599 status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2600 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2601 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2602 return Either.right(status);
2605 return Either.left(status);
2608 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2609 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2612 public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2613 return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
2616 public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
2617 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2620 public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2621 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2624 public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2625 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2628 public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2629 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2632 public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2633 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2637 public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2638 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2641 public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute property){
2642 return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
2645 public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute attribute){
2646 return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
2649 public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2650 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2653 public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2654 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2657 public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2658 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2661 public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2662 this.nodeTypeOperation = nodeTypeOperation;
2665 public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2666 this.topologyTemplateOperation = topologyTemplateOperation;
2669 public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) {
2670 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
2673 public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityPropertyKey, ComponentInstanceProperty property) {
2674 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
2677 public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2678 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2679 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2680 .orElse(StorageOperationStatus.NOT_FOUND);
2683 public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition) {
2684 return nodeTemplateOperation.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
2687 public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
2688 MapInterfaceDataDefinition mapInterfaceDataDefinition =
2689 convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
2690 return topologyTemplateOperation
2691 .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
2694 public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2695 Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap =
2696 convertComponentCapabilitiesProperties(containerComponent);
2697 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2700 public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2701 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2702 if (status == StorageOperationStatus.OK) {
2703 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2705 if (status == StorageOperationStatus.OK) {
2706 status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2711 public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2712 String componentId = clonedResource.getUniqueId();
2713 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2714 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
2715 if (getVertexEither.isRight()) {
2716 log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2717 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
2720 GraphVertex nodeTypeV = getVertexEither.left().value();
2722 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2724 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2725 if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
2726 log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2727 return Either.right(shouldUpdateDerivedVersion.right().value());
2729 if (shouldUpdateDerivedVersion.isLeft()) {
2730 return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2732 return Either.left(clonedResource);
2736 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2738 public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2739 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2742 private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent,
2743 String componentInstanceId) {
2744 MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
2745 List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
2747 if(CollectionUtils.isNotEmpty(componentInterface)) {
2748 componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put
2749 (interfaceDef.getUniqueId(), interfaceDef));
2752 return mapInterfaceDataDefinition;
2755 private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2756 Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
2757 map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
2761 private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2762 return component.fetchInstanceById(instanceId)
2763 .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
2766 public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2767 Either<PolicyDefinition, StorageOperationStatus> result = null;
2768 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
2769 getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2770 if (getVertexEither.isRight()) {
2771 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2772 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
2774 if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
2775 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2776 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2779 if (result == null) {
2780 StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2781 if (status != StorageOperationStatus.OK) {
2782 return Either.right(status);
2785 if (result == null) {
2786 result = Either.left(policyDefinition);
2791 public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
2792 log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
2793 return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
2794 .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
2795 DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
2798 public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition, PromoteVersionEnum promoteVersionEnum) {
2799 Either<PolicyDefinition, StorageOperationStatus> result = null;
2800 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
2801 getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2802 if (getVertexEither.isRight()) {
2803 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2804 result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
2806 if (result == null) {
2807 policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion()));
2808 StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2809 if (status != StorageOperationStatus.OK) {
2810 return Either.right(status);
2813 if (result == null) {
2814 result = Either.left(policyDefinition);
2819 public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2820 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2821 return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2823 .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
2824 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2828 public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
2829 StorageOperationStatus status = null;
2830 Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
2831 .getVertexById(componentId, JsonParseFlagEnum.NoParse);
2832 if (getVertexEither.isRight()) {
2833 log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
2834 status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
2836 if (status == null) {
2837 status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
2842 public boolean canAddGroups(String componentId) {
2843 GraphVertex vertex = janusGraphDao.getVertexById(componentId)
2845 .on(this::onJanusGraphError);
2846 return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
2849 GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
2850 throw new StorageException(
2851 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
2854 public CatalogUpdateTimestamp updateCatalogTimes() {
2855 long now = System.currentTimeMillis();
2857 GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
2859 .on(this::onJanusGraphError);
2861 Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
2862 catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
2863 catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);
2865 janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);
2867 return new CatalogUpdateTimestamp(currentTime, now);
2870 public CatalogUpdateTimestamp getCatalogTimes() {
2873 GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
2875 .on(this::onJanusGraphError);
2877 Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
2878 Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);
2880 return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
2883 public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2884 topologyTemplateOperation
2885 .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2888 public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
2889 topologyTemplateOperation
2890 .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
2893 private TopologyTemplate getTopologyTemplate(String componentId) {
2894 return (TopologyTemplate) topologyTemplateOperation
2895 .getToscaElement(componentId, getFilterComponentWithCapProperties())
2897 .on(this::throwStorageException);
2900 private ComponentParametersView getFilterComponentWithCapProperties() {
2901 ComponentParametersView filter = new ComponentParametersView();
2902 filter.setIgnoreCapabiltyProperties(false);
2906 private ToscaElement throwStorageException(StorageOperationStatus status) {
2907 throw new StorageException(status);
2910 public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
2911 final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
2912 Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
2913 if (vertexById.isLeft()) {
2914 for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
2915 Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
2916 if(edgeItr != null && edgeItr.hasNext()){
2917 return Either.left(true);
2921 return Either.left(false);
2924 public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid
2925 (String componentInvariantUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2927 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2928 if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
2929 propertiesToMatch.putAll(additionalPropertiesToMatch);
2931 propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
2933 Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
2934 .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
2936 if (vertexEither.isRight()) {
2937 log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value());
2938 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
2940 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
2942 if (vertexList == null || vertexList.isEmpty()) {
2943 log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
2944 return Either.right(StorageOperationStatus.NOT_FOUND);
2947 ArrayList<Component> components = new ArrayList<>();
2948 for (GraphVertex vertex : vertexList) {
2949 Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
2950 if (toscaElementByOperation.isRight()) {
2951 log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
2952 return Either.right(toscaElementByOperation.right().value());
2954 components.add(toscaElementByOperation.left().value());
2957 return Either.left(components);
2960 public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
2961 List<Component> parentComponents = new ArrayList<>();
2962 final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
2963 Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
2964 if (vertexById.isLeft()) {
2965 for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
2966 Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
2967 .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
2968 if(parentVertexEither.isLeft()){
2969 Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
2970 if(componentEither.isLeft()){
2971 parentComponents.add(componentEither.left().value());
2976 return Either.left(parentComponents);
2978 public void updateCapReqPropertiesOwnerId(String componentId) {
2979 topologyTemplateOperation
2980 .updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
2983 public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
2984 return getLatestByName(GraphPropertyEnum.NAME, serviceName);