re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / lifecycle / CheckoutTransition.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.be.components.lifecycle;
22
23 import fj.data.Either;
24 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
25 import org.openecomp.sdc.be.config.BeEcompErrorManager;
26 import org.openecomp.sdc.be.dao.api.ActionStatus;
27 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
28 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
29 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
30 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
31 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
32 import org.openecomp.sdc.be.impl.ComponentsUtils;
33 import org.openecomp.sdc.be.model.*;
34 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
35 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
36 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
37 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
38 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
39 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
40 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
41 import org.openecomp.sdc.be.tosca.ToscaUtils;
42 import org.openecomp.sdc.be.user.Role;
43 import org.openecomp.sdc.common.log.wrappers.Logger;
44 import org.openecomp.sdc.exception.ResponseFormat;
45
46 import java.util.Arrays;
47 import java.util.List;
48
49 public class CheckoutTransition extends LifeCycleTransition {
50
51     private static final Logger log = Logger.getLogger(CheckoutTransition.class);
52
53     CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
54         super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
55
56         // authorized roles
57         Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
58         Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
59         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
60         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
61         addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
62
63     }
64
65     @Override
66     public LifeCycleTransitionEnum getName() {
67         return LifeCycleTransitionEnum.CHECKOUT;
68     }
69
70     @Override
71     public AuditingActionEnum getAuditingAction() {
72         return AuditingActionEnum.CHECKOUT_RESOURCE;
73     }
74
75     @Override
76     public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
77
78         log.debug("start performing {} for resource {}", getName(), component.getUniqueId());
79
80         Either<? extends Component, ResponseFormat> result = null;
81         try {
82
83             Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
84
85             if (checkoutResourceResult.isRight()) {
86                 log.debug("checkout failed on graph");
87                 StorageOperationStatus response = checkoutResourceResult.right().value();
88                 ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
89
90                 if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
91                     actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
92                 }
93                 ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
94                 result = Either.right(responseFormat);
95             } else {
96
97                 Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value());
98                 if(componentType == ComponentTypeEnum.SERVICE) {
99                     Service service = (Service)clonedComponent;
100                     service.validateAndSetInstantiationType();
101                 }
102                 if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NODE_TYPE ){
103                     Either<Component, ActionStatus> upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent);
104                     if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){
105                         result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value()));
106                         return result;
107                     }
108                     if ( upgradeToLatestDerived.isLeft() ){
109                         //get resource after update derived
110                         clonedComponent = upgradeToLatestDerived.left().value();
111                     }
112                 }
113                 result = Either.left(clonedComponent);
114                 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent);
115                 if (upgradeToLatestGeneric.isRight()) {
116                     result = Either.right(upgradeToLatestGeneric.right().value());
117                 } else if (upgradeToLatestGeneric.left().value()  ) {
118                     StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent);
119                     if (StorageOperationStatus.OK != response) {
120                         ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
121                         ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
122                         result = Either.right(responseFormat);
123                     }
124                 }
125                 handleCalculatedCapabilitiesRequirements(clonedComponent);
126             }
127
128         } finally {
129             if (result == null || result.isRight()) {
130                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
131                 if (!inTransaction) {
132                     log.debug("operation failed. do rollback");
133                     titanDao.rollback();
134                 }
135             } else {
136                 if (!inTransaction) {
137                     log.debug("operation success. do commit");
138                     titanDao.commit();
139                 }
140             }
141         }
142         return result;
143     }
144
145     private void handleCalculatedCapabilitiesRequirements(Component clonedComponent) {
146         if(clonedComponent.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(clonedComponent)){
147             toscaOperationFacade.revertNamesOfCalculatedCapabilitiesRequirements(clonedComponent.getUniqueId());
148         }
149     }
150
151     private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
152
153         StorageOperationStatus updateStatus = StorageOperationStatus.OK;
154         Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent);
155         if (updateEither.isRight()) {
156             updateStatus = updateEither.right().value();
157         } else if (clonedComponent.shouldGenerateInputs()) {
158             List<InputDefinition> newInputs = clonedComponent.getInputs();
159             updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME);
160         }
161         return updateStatus;
162     }
163
164     @Override
165     public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
166         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
167         log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
168
169         // validate user
170         Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
171         if (userValidationResponse.isRight()) {
172             return userValidationResponse;
173         }
174
175         // check resource is not locked by another user
176         if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
177             ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
178             return Either.right(error);
179         }
180
181         if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
182             ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
183             return Either.right(error);
184         }
185
186         if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
187             if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) {
188                 ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
189                 return Either.right(error);
190             }
191         }
192         return Either.left(true);
193     }
194
195 }