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.jsontitan.operations;
23 import java.util.ArrayList;
24 import java.util.EnumMap;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
29 import java.util.Optional;
30 import java.util.stream.Collectors;
32 import org.apache.commons.collections.CollectionUtils;
33 import org.apache.commons.collections.MapUtils;
34 import org.apache.commons.lang.StringUtils;
35 import org.apache.commons.lang3.tuple.ImmutablePair;
36 import org.apache.tinkerpop.gremlin.structure.Direction;
37 import org.apache.tinkerpop.gremlin.structure.Edge;
38 import org.apache.tinkerpop.gremlin.structure.Vertex;
39 import org.openecomp.sdc.be.config.ConfigurationManager;
40 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
41 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
42 import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
43 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
44 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
45 import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
46 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
47 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
48 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
49 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
59 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
60 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
61 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
62 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
63 import org.openecomp.sdc.be.model.ComponentParametersView;
64 import org.openecomp.sdc.be.model.DistributionStatusEnum;
65 import org.openecomp.sdc.be.model.LifecycleStateEnum;
66 import org.openecomp.sdc.be.model.User;
67 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
68 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
69 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
70 import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
71 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
72 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
73 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
74 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
75 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
79 import fj.data.Either;
81 @org.springframework.stereotype.Component("tosca-element-lifecycle-operation")
84 * Allows to perform lifecycle operations: checkin, checkout, submit for testing, start certification and certification process for tosca element
86 public class ToscaElementLifecycleOperation extends BaseOperation {
88 private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. ";
89 public static final String VERSION_DELIMETER = ".";
90 public static final String VERSION_DELIMETER_REGEXP = "\\.";
92 private static Logger logger = LoggerFactory.getLogger(ToscaElementLifecycleOperation.class.getName());
95 * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in"
98 * @param toscaElementId
103 public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) {
104 Either<GraphVertex, StorageOperationStatus> updateResult = null;
105 Either<ToscaElement, StorageOperationStatus> result = null;
106 Map<String, GraphVertex> vertices = null;
107 ToscaElementOperation operation;
109 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId));
110 if (getVerticesRes.isRight()) {
111 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
112 updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
114 vertices = getVerticesRes.left().value();
115 updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
117 if (updateResult.isLeft()) {
118 ComponentParametersView componentParametersView = buildComponentParametersViewAfterCheckin();
119 operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel());
120 result = operation.getToscaElement(updateResult.left().value().getUniqueId(), componentParametersView);
121 if (result.isRight()) {
122 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value());
125 result = Either.right(updateResult.right().value());
127 } catch (Exception e) {
128 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage());
134 * Returns vertex presenting owner of tosca element specified by uniqueId
136 * @param toscaElement
139 public Either<User, StorageOperationStatus> getToscaElementOwner(String toscaElementId) {
140 Either<User, StorageOperationStatus> result = null;
141 GraphVertex toscaElement = null;
142 Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
143 if (getToscaElementRes.isRight()) {
144 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
146 if (result == null) {
147 toscaElement = getToscaElementRes.left().value();
148 Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name());
149 if (vertices == null || !vertices.hasNext()) {
150 result = Either.right(StorageOperationStatus.NOT_FOUND);
152 result = Either.left(convertToUser(vertices.next()));
159 * Returns vertex presenting owner of tosca element specified by uniqueId
161 * @param toscaElement
164 public Either<User, StorageOperationStatus> getToscaElementOwner(GraphVertex toscaElement) {
165 Either<User, StorageOperationStatus> result = null;
166 Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name());
167 if (vertices == null || !vertices.hasNext()) {
168 result = Either.right(StorageOperationStatus.NOT_FOUND);
170 result = Either.left(convertToUser(vertices.next()));
176 * Performs checkout of a tosca element
178 * @param toscaElementId
184 public Either<ToscaElement, StorageOperationStatus> checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) {
185 Either<ToscaElement, StorageOperationStatus> result = null;
186 Map<String, GraphVertex> vertices = null;
188 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId));
189 if (getVerticesRes.isRight()) {
190 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
191 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
193 if (result == null) {
194 vertices = getVerticesRes.left().value();
195 // update previous component if not certified
196 StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId));
197 if (status != StorageOperationStatus.OK) {
198 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status);
199 result = Either.right(status);
202 if (result == null) {
203 result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId));
204 if (result.isRight()) {
205 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value());
209 } catch (Exception e) {
210 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage());
216 * Performs undo checkout for tosca element
218 * @param toscaElementId
221 public Either<ToscaElement, StorageOperationStatus> undoCheckout(String toscaElementId) {
222 Either<ToscaElement, StorageOperationStatus> result = null;
223 Either<GraphVertex, TitanOperationStatus> getToscaElementRes = null;
224 Iterator<Edge> nextVersionComponentIter = null;
225 ToscaElementOperation operation;
227 getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata);
228 if (getToscaElementRes.isRight()) {
229 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
230 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value()));
232 if (result == null && hasPreviousVersion(getToscaElementRes.left().value())) {
233 // find previous version
234 nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
235 if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) {
236 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString());
237 result = Either.right(StorageOperationStatus.NOT_FOUND);
239 if (result == null) {
240 StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex());
241 if (updateOldResourceResult != StorageOperationStatus.OK) {
242 result = Either.right(updateOldResourceResult);
246 if (result == null) {
247 operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel());
248 result = operation.deleteToscaElement(getToscaElementRes.left().value());
250 } catch (Exception e) {
251 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage());
256 private boolean hasPreviousVersion(GraphVertex toscaElementVertex) {
257 boolean hasPreviousVersion = true;
258 String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION);
259 if (StringUtils.isEmpty(version) || version.equals("0.1"))
260 hasPreviousVersion = false;
261 return hasPreviousVersion;
265 * Performs request certification for tosca element
267 * @param toscaElementId
272 public Either<ToscaElement, StorageOperationStatus> requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) {
273 Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
274 Either<ToscaElement, StorageOperationStatus> result = null;
275 GraphVertex toscaElement = null;
276 GraphVertex modifier = null;
279 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
280 if (getVerticesRes.isRight()) {
281 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
282 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
284 if (result == null) {
285 toscaElement = getVerticesRes.left().value().get(toscaElementId);
286 modifier = getVerticesRes.left().value().get(modifierId);
287 owner = getVerticesRes.left().value().get(ownerId);
289 StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner);
290 if (status != StorageOperationStatus.OK) {
291 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
294 if (result == null) {
295 LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION;
297 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
298 toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
300 resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
301 if (resultUpdate.isRight()) {
302 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
303 result = Either.right(resultUpdate.right().value());
306 if (result == null) {
307 ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
308 result = operation.getToscaElement(toscaElement.getUniqueId());
312 } catch (Exception e) {
313 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
319 * Starts certification of tosca element
321 * @param toscaElementId
326 public Either<ToscaElement, StorageOperationStatus> startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) {
327 Either<ToscaElement, StorageOperationStatus> result = null;
328 Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
329 GraphVertex toscaElement = null;
330 GraphVertex modifier = null;
333 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
334 if (getVerticesRes.isRight()) {
335 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
336 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
338 if (result == null) {
339 toscaElement = getVerticesRes.left().value().get(toscaElementId);
340 modifier = getVerticesRes.left().value().get(modifierId);
341 owner = getVerticesRes.left().value().get(ownerId);
343 StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner);
344 if (status != StorageOperationStatus.OK) {
345 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
348 if (result == null) {
349 LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS;
351 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
352 toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
354 resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
355 if (resultUpdate.isRight()) {
356 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
357 result = Either.right(resultUpdate.right().value());
360 if (result == null) {
361 ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
362 result = operation.getToscaElement(toscaElement.getUniqueId());
364 } catch (Exception e) {
365 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage());
370 public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) {
371 Either<ToscaElement, StorageOperationStatus> result = null;
372 Either<GraphVertex, StorageOperationStatus> cloneRes = null;
373 GraphVertex toscaElement = null;
374 GraphVertex modifier = null;
375 GraphVertex certifiedToscaElement = null;
376 Integer majorVersion = null;
378 StorageOperationStatus status;
380 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
381 if (getVerticesRes.isRight()) {
382 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
383 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
385 if (result == null) {
386 toscaElement = getVerticesRes.left().value().get(toscaElementId);
387 modifier = getVerticesRes.left().value().get(modifierId);
388 majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION));
389 status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion);
390 if (status != StorageOperationStatus.OK) {
391 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status);
394 if (result == null) {
395 cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion);
396 if (cloneRes.isRight()) {
397 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. ");
398 result = Either.right(cloneRes.right().value());
401 if (result == null) {
402 certifiedToscaElement = cloneRes.left().value();
403 status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement);
404 if (status != StorageOperationStatus.OK) {
405 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status);
408 if (result == null) {
409 return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId());
411 } catch (Exception e) {
412 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage());
418 * Deletes (marks as deleted) all tosca elements according received name and uuid
421 * @param componentType
422 * @param componentName
426 public Either<Boolean, StorageOperationStatus> deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) {
428 Either<Boolean, StorageOperationStatus> result = null;
429 ToscaElementOperation operation = getToscaElementOperation(componentType);
432 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
433 properties.put(GraphPropertyEnum.UUID, uuid);
434 properties.put(GraphPropertyEnum.NAME, componentName);
435 Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata);
436 if (getToscaElementsRes.isRight()) {
437 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value()));
439 if (result == null) {
440 result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value());
442 if (result == null) {
443 result = Either.left(true);
445 } catch (Exception e) {
446 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
452 * Performs cancelation or failure of certification for received tosca element
454 * @param toscaElementId
460 public Either<ToscaElement, StorageOperationStatus> cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) {
461 Either<ToscaElement, StorageOperationStatus> result = null;
462 StorageOperationStatus status;
463 ToscaElementOperation operation = null;
464 GraphVertex toscaElement = null;
465 GraphVertex modifier = null;
467 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
468 if (getVerticesRes.isRight()) {
469 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
470 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
472 if (result == null) {
473 toscaElement = getVerticesRes.left().value().get(toscaElementId);
474 modifier = getVerticesRes.left().value().get(modifierId);
475 operation = getToscaElementOperation(toscaElement.getLabel());
476 toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
477 toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId());
478 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
480 Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElement);
481 if (updateVertexRes.isRight()) {
482 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value());
483 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value()));
486 if (result == null) {
487 // cancel certification process
488 status = handleRelationsUponCancelCertification(toscaElement, nextState);
489 if (status != StorageOperationStatus.OK) {
490 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status);
493 if (result == null) {
494 // fail certification
495 status = handleRelationsUponFailCertification(toscaElement, nextState);
496 if (status != StorageOperationStatus.OK) {
497 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status);
500 if (result == null) {
501 result = operation.getToscaElement(toscaElementId);
503 } catch (Exception e) {
504 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage());
509 public Either<GraphVertex, TitanOperationStatus> findUser(String userId) {
510 return findUserVertex(userId);
513 private Either<Boolean, StorageOperationStatus> markToscaElementsAsDeleted(ToscaElementOperation operation, List<GraphVertex> toscaElements) {
514 Either<Boolean, StorageOperationStatus> result = Either.left(true);
515 for (GraphVertex resourceToDelete : toscaElements) {
516 if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
517 Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete);
518 if (deleteElementRes.isRight()) {
519 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value());
520 result = Either.right(deleteElementRes.right().value());
528 private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) {
529 StorageOperationStatus result = null;
530 Edge foundEdge = null;
531 Iterator<Edge> certReqUserEdgeIter = null;
532 // add rfc relation to preserve follower information
533 // get user of certification request
534 certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name());
535 if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) {
536 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. ");
537 result = StorageOperationStatus.NOT_FOUND;
539 if (result == null) {
540 TitanOperationStatus createVersionEdgeStatus = titanDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>());
541 if (createVersionEdgeStatus != TitanOperationStatus.OK) {
542 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(),certifiedToscaElement.getUniqueId(), createVersionEdgeStatus);
543 result = DaoStatusConverter.convertTitanStatusToStorageStatus(createVersionEdgeStatus);
548 while (certReqUserEdgeIter.hasNext()) {
549 Edge edge = certReqUserEdgeIter.next();
550 if (((String) titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) {
556 if (foundEdge == null) {
557 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. ");
558 result = StorageOperationStatus.NOT_FOUND;
561 if (result == null) {
562 TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge);
563 if (createEdgeRes != TitanOperationStatus.OK) {
564 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes);
565 result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes);
568 if (result == null) {
569 result = StorageOperationStatus.OK;
574 private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) {
575 StorageOperationStatus result = null;
576 TitanOperationStatus status = null;
579 if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) {
580 // fail certification
581 // delete relation CERTIFICATION_IN_PROGRESS
582 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
583 properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
585 Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties);
586 if (deleteResult.isRight()) {
587 status = deleteResult.right().value();
588 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status);
589 result = StorageOperationStatus.INCONSISTENCY;
591 if (result == null) {
592 // delete relation READY_FOR_CERTIFICATION
593 properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION);
594 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
595 if (deleteResult.isRight()) {
596 status = deleteResult.right().value();
597 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status);
598 result = StorageOperationStatus.INCONSISTENCY;
601 if (result == null) {
602 // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE)
603 properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
604 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
605 if (deleteResult.isRight()) {
606 status = deleteResult.right().value();
607 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status);
608 result = StorageOperationStatus.INCONSISTENCY;
611 if (result == null) {
612 // create new STATE relation NOT_CERTIFIED_CHECKIN
613 originEdge = deleteResult.left().value();
614 user = originEdge.outVertex();
615 status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge);
616 if (status != TitanOperationStatus.OK) {
617 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status);
618 result = StorageOperationStatus.INCONSISTENCY;
621 if (result == null) {
622 // delete relation LAST_MODIFIER (in order to change tester to designer)
623 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
624 if (status != TitanOperationStatus.OK) {
625 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status);
626 result = StorageOperationStatus.INCONSISTENCY;
629 if (result == null) {
630 // create new LAST_MODIFIER relation
631 originEdge = deleteResult.left().value();
632 status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge);
633 if (status != TitanOperationStatus.OK) {
634 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status);
635 result = StorageOperationStatus.INCONSISTENCY;
639 if (result == null) {
640 result = StorageOperationStatus.OK;
645 private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) {
646 StorageOperationStatus result = null;
648 if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) {
649 // delete relation CERTIFICATION_IN_PROGRESS
650 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
651 properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
652 Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties);
654 if (deleteResult.isRight()) {
655 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value());
656 result = StorageOperationStatus.INCONSISTENCY;
658 if (result == null) {
659 // delete relation READY_FOR_CERTIFICATION (LAST_STATE)
660 properties.put(GraphPropertyEnum.STATE, nextState);
661 deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties);
663 if (deleteResult.isRight()) {
664 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", deleteResult.right().value());
665 result = StorageOperationStatus.INCONSISTENCY;
668 if (result == null) {
669 // create relation READY_FOR_CERTIFICATION (STATE)
670 originEdge = deleteResult.left().value();
671 TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge);
672 if (status != TitanOperationStatus.OK) {
673 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status);
674 result = StorageOperationStatus.INCONSISTENCY;
677 if (result == null) {
678 result = StorageOperationStatus.OK;
684 private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) {
685 StorageOperationStatus result = null;
686 if (majorVersion > 0) {
687 Either<Vertex, StorageOperationStatus> findRes = findLastCertifiedToscaElementVertex(toscaElement);
688 if (findRes.isRight()) {
689 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value());
690 result = findRes.right().value();
692 if (result == null) {
693 Vertex lastCertifiedVertex = findRes.left().value();
694 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
695 properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
696 TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties);
697 if (status != TitanOperationStatus.OK) {
698 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status);
699 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
703 if (result == null) {
704 result = StorageOperationStatus.OK;
709 private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
710 TitanOperationStatus status;
711 StorageOperationStatus result = null;
713 if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
714 // remove CHECKOUT relation
715 Either<Edge, TitanOperationStatus> deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE);
716 if (deleteRes.isRight()) {
717 status = deleteRes.right().value();
718 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status);
719 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
721 if (result == null) {
722 // create CHECKIN relation
723 Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
724 properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
725 status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties);
726 if (status != TitanOperationStatus.OK) {
727 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status);
728 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
732 status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
733 if (status != TitanOperationStatus.OK) {
734 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
737 if (result == null) {
738 // create RFC relation
739 Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
740 properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION);
741 status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties);
742 if (status != TitanOperationStatus.OK) {
743 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status);
744 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
747 if (result == null) {
748 result = StorageOperationStatus.OK;
753 private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
755 StorageOperationStatus result = null;
756 TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
757 if (status != TitanOperationStatus.OK) {
758 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
760 if (result == null) {
761 Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
762 properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
763 status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
764 if (status != TitanOperationStatus.OK) {
765 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
766 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
769 if (result == null) {
770 Either<GraphVertex, StorageOperationStatus> updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier);
771 if (updateRelationsRes.isRight()) {
772 result = updateRelationsRes.right().value();
775 if (result == null) {
776 result = StorageOperationStatus.OK;
781 private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertex(GraphVertex toscaElement) {
782 return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex());
785 private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertexRecursively(Vertex vertex) {
786 if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) {
787 return Either.left(vertex);
789 Iterator<Edge> edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name());
790 if (!edgeIter.hasNext()) {
791 return Either.right(StorageOperationStatus.NOT_FOUND);
793 return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex());
796 private boolean isCertifiedVersion(String version) {
797 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
798 if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) {
804 private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) {
806 StorageOperationStatus result = StorageOperationStatus.OK;
807 String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value();
808 if (!previousVersion.endsWith(".0")) {
810 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
812 Map<String, Object> propertiesToUpdate = new HashMap<>();
813 propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
814 Map<String, Object> jsonMetadataMap = JsonParserUtils.parseToJson((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value());
815 jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
816 propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap));
818 titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate);
820 Iterator<Edge> edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name());
821 if (!edgesIter.hasNext()) {
822 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
823 result = StorageOperationStatus.NOT_FOUND;
825 Edge lastStateEdge = edgesIter.next();
826 Vertex lastModifier = lastStateEdge.outVertex();
827 TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE);
828 if (replaceRes != TitanOperationStatus.OK) {
829 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes);
830 result = StorageOperationStatus.INCONSISTENCY;
831 if (replaceRes != TitanOperationStatus.INVALID_ID) {
832 result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes);
836 } catch (Exception e) {
837 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage());
843 private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) {
844 StorageOperationStatus result = null;
845 String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID);
846 String toscaElementId = toscaElementVertex.getUniqueId();
847 if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) {
848 toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
849 Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex);
850 if (updateVertexRes.isRight()) {
851 TitanOperationStatus titatStatus = updateVertexRes.right().value();
852 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus);
853 result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus);
855 Either<Edge, TitanOperationStatus> deleteEdgeRes = null;
856 if (result == null) {
857 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId);
859 deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
860 if (deleteEdgeRes.isRight()) {
861 TitanOperationStatus titanStatus = deleteEdgeRes.right().value();
862 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus);
863 if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) {
864 result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
866 result = StorageOperationStatus.INCONSISTENCY;
870 if (result == null) {
871 TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value());
872 if (createEdgeRes != TitanOperationStatus.OK) {
873 result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes);
877 if (result == null) {
878 result = StorageOperationStatus.OK;
883 private Either<ToscaElement, StorageOperationStatus> cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
885 Either<ToscaElement, StorageOperationStatus> result = null;
886 Either<GraphVertex, StorageOperationStatus> cloneResult = null;
887 ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
888 // check if component with the next version doesn't exist.
889 Iterator<Edge> nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name());
890 if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) {
891 Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex();
892 String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value();
893 String fetchedName = (String)nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
894 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ",
895 toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion);
896 result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
898 if (result == null) {
899 cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex);
900 if (cloneResult.isRight()) {
901 result = Either.right(cloneResult.right().value());
904 GraphVertex clonedVertex = null;
905 if (result == null) {
906 clonedVertex = cloneResult.left().value();
907 TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
908 if (status != TitanOperationStatus.OK) {
909 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
910 toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
911 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
914 if (result == null) {
915 result = operation.getToscaElement(cloneResult.left().value().getUniqueId());
916 if (result.isRight()) {
920 ToscaElement toscaElement = result.left().value();
921 if (toscaElement.getToscaType() == ToscaElementTypeEnum.TopologyTemplate) {
922 result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement);
928 private Either<ToscaElement, StorageOperationStatus> handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either<ToscaElement, StorageOperationStatus> result, ToscaElementOperation operation, GraphVertex clonedVertex,
929 ToscaElement toscaElement) {
930 TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
931 Map<String, MapPropertiesDataDefinition> instInputs = topologyTemplate.getInstInputs();
932 Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups();
933 Map<String, MapArtifactDataDefinition> instArtifactsMap = topologyTemplate.getInstanceArtifacts();
934 Map<String, ToscaElement> origCompMap = new HashMap<>();
935 if (instInputs == null) {
936 instInputs = new HashMap<>();
938 if (instGroups == null) {
939 instGroups = new HashMap<>();
941 if (instArtifactsMap == null) {
942 instArtifactsMap = new HashMap<>();
944 Map<String, ComponentInstanceDataDefinition> instancesMap = topologyTemplate.getComponentInstances();
945 boolean isAddInstGroup = instGroups == null || instGroups.isEmpty();
946 boolean needUpdateComposition = false;
948 if (instancesMap != null && !instancesMap.isEmpty()) {
949 for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) {
950 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType());
951 if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) {
952 collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex);
954 needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap);
955 if(needUpdateComposition){
956 instancesMap.put(vfInst.getUniqueId(), vfInst);
959 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition);
960 if (!instInputs.isEmpty()) {
961 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size());
962 GraphVertex toscaDataVertex = null;
963 Either<GraphVertex, TitanOperationStatus> instInpVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson);
964 if (instInpVertexEither.isLeft()) {
965 toscaDataVertex = instInpVertexEither.left().value();
968 StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs);
969 if (status != StorageOperationStatus.OK) {
970 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status);
971 result = Either.right(status);
976 if (!instGroups.isEmpty()) {
977 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size());
978 GraphVertex toscaDataVertex = null;
979 Either<GraphVertex, TitanOperationStatus> instGrVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson);
980 if (instGrVertexEither.isLeft()) {
981 toscaDataVertex = instGrVertexEither.left().value();
984 StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups);
985 if (status != StorageOperationStatus.OK) {
986 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status);
987 result = Either.right(status);
992 if (needUpdateComposition) {
993 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before update Instances ");
994 Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) clonedVertex.getJson();
995 CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
996 compositionDataDefinition.setComponentInstances(instancesMap);
997 Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(clonedVertex);
998 if (updateElement.isRight()) {
999 TitanOperationStatus status = updateElement.right().value();
1000 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status);
1001 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1006 result = operation.getToscaElement(clonedVertex.getUniqueId());
1009 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId());
1014 //TODO remove after jsonModelMigration
1015 public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
1016 return fixToscaComponentName(vfInst, origCompMap);
1019 private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
1020 if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) {
1021 String ciUid = vfInst.getUniqueId();
1022 String origCompUid = vfInst.getComponentUid();
1023 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType());
1024 ToscaElement origComp = null;
1025 if (!origCompMap.containsKey(origCompUid)) {
1026 Either<ToscaElement, StorageOperationStatus> origCompEither;
1027 if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) {
1028 origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
1030 origCompEither = nodeTypeOperation.getToscaElement(origCompUid);
1032 if (origCompEither.isRight()) {
1033 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
1036 origComp = origCompEither.left().value();
1037 origCompMap.put(origCompUid, origComp);
1039 origComp = origCompMap.get(origCompUid);
1041 String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME);
1042 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName);
1043 vfInst.setToscaComponentName(toscaName);
1049 private void collectInstanceInputAndGroups(Map<String, MapPropertiesDataDefinition> instInputs, Map<String, MapGroupsDataDefinition> instGroups, Map<String, MapArtifactDataDefinition> instArtifactsMap, Map<String, ToscaElement> origCompMap,
1050 boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) {
1051 String ciUid = vfInst.getUniqueId();
1052 String origCompUid = vfInst.getComponentUid();
1053 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid);
1054 TopologyTemplate origComp = null;
1055 if (!origCompMap.containsKey(origCompUid)) {
1056 Either<ToscaElement, StorageOperationStatus> origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
1057 if (origCompEither.isRight()) {
1058 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
1061 origComp = (TopologyTemplate) origCompEither.left().value();
1062 origCompMap.put(origCompUid, origComp);
1064 origComp = (TopologyTemplate) origCompMap.get(origCompUid);
1066 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId());
1068 Map<String, PropertyDataDefinition> origInputs = origComp.getInputs();
1069 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size());
1070 if (origInputs != null) {
1071 if (!instInputs.containsKey(ciUid)) {
1072 MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs);
1073 instInputs.put(ciUid, instProperties);
1076 MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid);
1077 Map<String, PropertyDataDefinition> instProp = instInputMap.getMapToscaDataDefinition();
1078 origInputs.forEach((propName, propMap) -> {
1079 if (!instProp.containsKey(propName)) {
1080 instProp.put(propName, propMap);
1084 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid));
1087 if (isAddInstGroup) {
1088 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before create group instance. ");
1089 List<GroupDataDefinition> filteredGroups = null;
1092 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
1093 if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) {
1094 filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
1095 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
1097 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
1098 if (CollectionUtils.isNotEmpty(filteredGroups)) {
1099 MapArtifactDataDefinition instArifacts = null;
1100 if(!instArtifactsMap.containsKey(ciUid)){
1102 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "istance artifacts not found ");
1104 Map<String, ArtifactDataDefinition> deploymentArtifacts = origComp.getDeploymentArtifacts();
1107 instArifacts = new MapArtifactDataDefinition(deploymentArtifacts);
1108 addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid);
1110 instArtifactsMap.put(ciUid, instArifacts);
1113 instArifacts = instArtifactsMap.get(ciUid);
1116 if(instArifacts != null){
1117 Map<String, ArtifactDataDefinition> instDeplArtifMap = instArifacts.getMapToscaDataDefinition();
1119 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size());
1120 Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
1121 for(GroupDataDefinition group:filteredGroups){
1122 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName());
1123 GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst);
1124 List<String> artifactsUid = new ArrayList<>();
1125 List<String> artifactsId = new ArrayList<>();
1126 for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) {
1127 //CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", artifact.getA);
1128 Optional<String> op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny();
1129 if (op.isPresent()) {
1130 artifactsUid.add(artifact.getArtifactUUID());
1131 artifactsId.add(artifact.getUniqueId());
1135 groupInstance.setGroupInstanceArtifacts(artifactsId);
1136 groupInstance.setGroupInstanceArtifactsUuid(artifactsUid);
1137 groupInstanceToCreate.put(groupInstance.getName(), groupInstance);
1139 if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
1140 instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate));
1148 private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
1149 GraphVertex nextVersionToscaElementVertex = new GraphVertex();
1150 String uniqueId = UniqueIdBuilder.buildComponentUniqueId();
1151 Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties());
1152 nextVersionToscaElementVertex.setMetadataProperties(metadataProperties);
1153 nextVersionToscaElementVertex.setUniqueId(uniqueId);
1154 nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
1155 nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
1157 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
1158 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
1159 String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION));
1160 if (isFirstCheckoutAfterCertification(nextVersion)) {
1161 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID());
1163 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion);
1164 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1165 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1167 if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) {
1168 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue());
1170 if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) {
1171 nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson()));
1172 nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties();
1174 long currTime = System.currentTimeMillis();
1175 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime);
1176 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime);
1177 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
1178 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
1179 if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) {
1180 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
1183 if (!MapUtils.isEmpty(toscaElementVertex.getJson())) {
1184 nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
1186 return nextVersionToscaElementVertex;
1189 private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
1190 Either<GraphVertex, StorageOperationStatus> result;
1191 Either<List<GraphVertex>, StorageOperationStatus> deleteResult = null;
1192 GraphVertex clonedToscaElement = null;
1193 result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex);
1194 if (result.isRight()) {
1195 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value());
1197 clonedToscaElement = result.left().value();
1198 deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex);
1199 if (deleteResult.isRight()) {
1200 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value());
1201 result = Either.right(deleteResult.right().value());
1204 if (result.isLeft()) {
1205 result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion);
1210 private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement, List<GraphVertex> deletedVersions, Integer majorVersion) {
1211 Either<GraphVertex, StorageOperationStatus> result = null;
1212 Vertex previousCertifiedToscaElement = null;
1213 if (majorVersion > 0) {
1214 List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList());
1216 if (CollectionUtils.isEmpty(firstMinorVersionVertex)) {
1217 result = Either.right(StorageOperationStatus.NOT_FOUND);
1219 previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0));
1220 if (previousCertifiedToscaElement == null) {
1221 result = Either.right(StorageOperationStatus.NOT_FOUND);
1224 if (result == null) {
1225 TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
1226 if (status != TitanOperationStatus.OK) {
1227 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
1228 previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status);
1229 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1233 if (result == null) {
1234 result = Either.left(clonedToscaElement);
1239 private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) {
1241 Iterator<Edge> edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
1242 if (edges.hasNext()) {
1243 return edges.next().outVertex();
1248 private Either<List<GraphVertex>, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) {
1249 Either<List<GraphVertex>, StorageOperationStatus> result = null;
1251 ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
1252 List<GraphVertex> previosVersions = null;
1253 Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID);
1254 Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME);
1256 Map<GraphPropertyEnum, Object> properties = new HashMap<>();
1257 properties.put(GraphPropertyEnum.UUID, uuid);
1258 properties.put(GraphPropertyEnum.NAME, componentName);
1259 Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata);
1260 if (getToscaElementsRes.isRight()) {
1261 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value()));
1263 if (result == null) {
1264 previosVersions = getToscaElementsRes.left().value();
1265 Either<Boolean, StorageOperationStatus> deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value());
1266 if (deleteResult.isRight()) {
1267 result = Either.right(deleteResult.right().value());
1270 if (result == null) {
1271 result = Either.left(previosVersions);
1273 } catch (Exception e) {
1274 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
1279 private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
1281 GraphVertex nextVersionToscaElementVertex = new GraphVertex();
1282 String uniqueId = IdBuilderUtils.generateUniqueId();
1283 Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties());
1284 nextVersionToscaElementVertex.setMetadataProperties(metadataProperties);
1285 nextVersionToscaElementVertex.setUniqueId(uniqueId);
1286 nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
1287 nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
1289 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
1290 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
1291 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMETER + "0");
1292 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1293 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1294 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis());
1295 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null);
1296 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
1297 nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
1299 if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) {
1300 nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue());
1302 if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) {
1303 nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson()));
1304 nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties();
1306 if (!MapUtils.isEmpty(toscaElementVertex.getJson())) {
1307 nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
1309 return nextVersionToscaElementVertex;
1312 private ComponentParametersView buildComponentParametersViewAfterCheckin() {
1313 ComponentParametersView componentParametersView = new ComponentParametersView();
1314 componentParametersView.disableAll();
1315 componentParametersView.setIgnoreUsers(false);
1316 return componentParametersView;
1319 private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) {
1320 Either<GraphVertex, StorageOperationStatus> updateRelationsRes;
1321 Either<GraphVertex, StorageOperationStatus> result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex);
1322 if (result.isLeft()) {
1323 toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name());
1324 toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
1325 result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex);
1327 if (result.isLeft()) {
1328 updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex);
1329 if (updateRelationsRes.isRight()) {
1330 result = Either.right(updateRelationsRes.right().value());
1336 private Either<GraphVertex, StorageOperationStatus> updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) {
1338 Either<GraphVertex, StorageOperationStatus> result;
1340 Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex);
1341 if (updateVertexRes.isRight()) {
1342 TitanOperationStatus titatStatus = updateVertexRes.right().value();
1343 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus);
1344 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus));
1346 result = Either.left(updateVertexRes.left().value());
1351 private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
1352 Either<GraphVertex, StorageOperationStatus> result = null;
1353 LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
1354 String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}";
1356 if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) {
1357 // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN"
1358 Map<GraphPropertyEnum, Object> vertexProperties = new HashMap<>();
1359 vertexProperties.put(GraphPropertyEnum.STATE, nextState);
1360 Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties);
1361 if (deleteResult.isRight()) {
1362 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value());
1363 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to update last state relation");
1364 result = Either.right(StorageOperationStatus.INCONSISTENCY);
1367 if (result == null) {
1368 // Remove CHECKOUT relation
1369 Either<Edge, TitanOperationStatus> deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
1370 if (deleteEdgeResult.isRight()) {
1371 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
1372 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value()));
1375 if (result == null) {
1376 // Create CHECKIN relation
1377 Map<EdgePropertyEnum, Object> edgeProperties = new HashMap<>();
1378 edgeProperties.put(EdgePropertyEnum.STATE, nextState);
1379 TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties);
1380 if (createEdgeRes != TitanOperationStatus.OK) {
1381 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
1382 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes));
1385 if (result == null) {
1386 result = Either.left(toscaElementVertex);
1391 private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
1392 Either<GraphVertex, StorageOperationStatus> result = null;
1393 if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) {
1394 Either<Edge, TitanOperationStatus> deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER);
1395 if (deleteEdgeRes.isRight()) {
1396 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
1397 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value()));
1399 if (result == null) {
1400 TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
1402 if (createEdgeRes != TitanOperationStatus.OK) {
1403 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
1404 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes));
1406 result = Either.left(modifierVertex);
1410 result = Either.left(ownerVertex);
1415 private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) {
1416 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
1417 verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata));
1418 verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1419 verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1420 return verticesToGetParameters;
1423 private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) {
1424 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
1425 verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
1426 verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1427 verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1428 return verticesToGetParameters;
1431 private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) {
1432 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
1433 verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
1434 verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1435 verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
1436 return verticesToGetParameters;
1440 private String getNextCertifiedVersion(String version) {
1441 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
1442 Integer nextMajorVersion = Integer.parseInt(versionParts[0]) + 1;
1443 return nextMajorVersion + VERSION_DELIMETER + "0";
1446 private String getNextVersion(String currVersion) {
1447 String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP);
1448 Integer minorVersion = Integer.parseInt(versionParts[1]) + 1;
1449 return versionParts[0] + VERSION_DELIMETER + minorVersion;
1452 private Integer getMinorVersion(String version) {
1453 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
1454 return Integer.parseInt(versionParts[1]);
1457 private Integer getMajorVersion(String version) {
1458 String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
1459 return Integer.parseInt(versionParts[0]);
1462 private boolean isFirstCheckoutAfterCertification(String version) {
1463 if (Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[1]) == 1) {
1469 public Either<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) {
1470 Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
1471 Either<ToscaElement, StorageOperationStatus> result = null;
1472 GraphVertex toscaElement = null;
1473 GraphVertex modifier = null;
1476 Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
1477 if (getVerticesRes.isRight()) {
1478 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
1479 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
1481 if (result == null) {
1482 toscaElement = getVerticesRes.left().value().get(toscaElementId);
1483 modifier = getVerticesRes.left().value().get(modifierId);
1484 owner = getVerticesRes.left().value().get(ownerId);
1486 StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner);
1487 if (status != StorageOperationStatus.OK) {
1488 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
1491 if (result == null) {
1492 LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED;
1494 toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1495 toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, getNextCertifiedVersion(currVersion));
1497 resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
1498 if (resultUpdate.isRight()) {
1499 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
1500 result = Either.right(resultUpdate.right().value());
1503 if (result == null) {
1504 ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
1505 result = operation.getToscaElement(toscaElement.getUniqueId());
1509 } catch (Exception e) {
1510 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
1515 private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
1517 StorageOperationStatus result = null;
1518 TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
1519 if (status != TitanOperationStatus.OK) {
1520 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
1522 if (result == null) {
1523 Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
1524 properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
1525 status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
1526 if (status != TitanOperationStatus.OK) {
1527 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
1528 result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
1531 if (result == null) {
1532 result = StorageOperationStatus.OK;