e6a6491aedd9d903db67c0793b0d7ca2f89c2b10
[sdc.git] /
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.ArtifactsBusinessLogic;
25 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
26 import org.openecomp.sdc.be.config.BeEcompErrorManager;
27 import org.openecomp.sdc.be.dao.api.ActionStatus;
28 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
29 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
30 import org.openecomp.sdc.be.impl.ComponentsUtils;
31 import org.openecomp.sdc.be.model.*;
32 import org.openecomp.sdc.be.model.category.CategoryDefinition;
33 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
34 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
35 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
36 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
37 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
38 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
39 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
40 import org.openecomp.sdc.be.user.Role;
41 import org.openecomp.sdc.common.log.wrappers.Logger;
42 import org.openecomp.sdc.exception.ResponseFormat;
43
44 import java.util.Arrays;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Optional;
48
49 public class CertificationChangeTransition extends LifeCycleTransition {
50     private static final  String ALLOTTED_CATEGORY = "Allotted Resource";
51     private static final  String DEPENDING_SRV_NAME = "depending_service_name";
52     private static final  String PROVIDING_SRV_NAME = "providing_service_name";
53     private static final  String PROVIDING_SRV_UUID = "providing_service_uuid";
54     private static final  String DEPENDING_SRV_UUID = "depending_service_uuid";
55
56     private static final Logger log = Logger.getLogger(CertificationChangeTransition.class);
57
58     private LifecycleStateEnum nextState;
59     private LifeCycleTransitionEnum name;
60     private AuditingActionEnum auditingAction;
61     private ArtifactsBusinessLogic artifactsManager;
62     private NodeTemplateOperation nodeTemplateOperation;
63
64     public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
65         super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
66
67         this.name = name;
68
69         // authorized roles
70         Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER };
71         Role[] resourceRoles = { Role.ADMIN, Role.TESTER, Role.DESIGNER};
72         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceRoles));
73         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles));
74
75         //additional authorized roles for resource type
76         switch (this.name) {
77         case CERTIFY:
78             this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE;
79             this.nextState = LifecycleStateEnum.CERTIFIED;
80             break;
81         case FAIL_CERTIFICATION:
82             this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE;
83             nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
84             break;
85         case CANCEL_CERTIFICATION:
86             this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE;
87             nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION;
88             break;
89         default:
90             break;
91         }
92
93     }
94
95     @Override
96     public LifeCycleTransitionEnum getName() {
97         return name;
98     }
99
100     @Override
101     public AuditingActionEnum getAuditingAction() {
102         return auditingAction;
103     }
104
105     public ArtifactsBusinessLogic getArtifactsManager() {
106         return artifactsManager;
107     }
108
109     public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
110         this.artifactsManager = artifactsManager;
111     }
112
113     public NodeTemplateOperation getNodeTemplateOperation() {
114         return nodeTemplateOperation;
115     }
116
117     public void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
118         this.nodeTemplateOperation = nodeTemplateOperation;
119     }
120
121     private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) {
122         BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph");
123         log.debug("certification change failed on graph");
124
125         return componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(response), component, componentType);
126     }
127
128     @Override
129     public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
130         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
131         log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
132
133         // validate user
134         Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
135         if (userValidationResponse.isRight()) {
136             log.debug("userRoleValidation failed");
137             return userValidationResponse;
138         }
139
140         if ( componentType != ComponentTypeEnum.RESOURCE ){
141             if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)  ) {
142                 log.debug("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION);
143                 ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
144                 return Either.right(error);
145             }
146     
147             if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.getUserId().equals(owner.getUserId()) && !modifier.getRole().equals(Role.ADMIN.name())) {
148                 log.debug("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE);
149                 log.debug("&& modifier({})!={}  && modifier.role({})!={}", modifier, owner, modifier.getRole(), owner.getRole());
150                 ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
151                 return Either.right(error);
152             }
153         }
154         return Either.left(true);
155     }
156
157     @Override
158     public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
159
160         log.info("start performing certification change for resource {}", component.getUniqueId());
161         Either<? extends Component, ResponseFormat> result = null;
162
163         try {
164             Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
165             if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
166                 certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
167             } else {
168                 certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState);
169             }
170
171             if (certificationChangeResult.isRight()) {
172                 ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType);
173                 result = Either.right(responseFormat);
174                 return result;
175             }
176
177             if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
178                 Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
179                         component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID());
180                 if (deleteOldComponentVersions.isRight()) {
181                     ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType);
182                     result = Either.right(responseFormat);
183                 }
184             }
185             ToscaElement certificationResult = certificationChangeResult.left().value();
186             Component componentAfterCertification = ModelConverter.convertFromToscaElement(certificationResult);
187             if ( result == null || result.isLeft() ){
188                 //update edges for allotted resource 
189                 StorageOperationStatus status = handleConnectionsForAllotted(componentAfterCertification);
190                 if ( status != StorageOperationStatus.OK){
191                     ResponseFormat responseFormat = formatCertificationError(componentAfterCertification, status, componentType);
192                     result = Either.right(responseFormat);
193                 }
194             }
195             updateCalculatedCapabilitiesRequirements(componentAfterCertification);
196             result = Either.left(componentAfterCertification);
197             return result;
198         } finally {
199             if (result == null || result.isRight()) {
200                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
201                 if ( !inTransaction ) {
202                     log.debug("operation failed. do rollback");
203                     titanDao.rollback();
204                 }
205             } else {
206                 if ( !inTransaction ) {
207                     log.debug("operation success. do commit");
208                     titanDao.commit();
209                 }
210             }
211         }
212
213     }
214
215     private void updateCalculatedCapabilitiesRequirements(Component certifiedComponent) {
216         if(certifiedComponent.getComponentType() == ComponentTypeEnum.SERVICE){
217             toscaOperationFacade.updateNamesOfCalculatedCapabilitiesRequirements(certifiedComponent.getUniqueId());
218         }
219     }
220
221     private StorageOperationStatus handleConnectionsForAllotted(Component component){
222         StorageOperationStatus status = StorageOperationStatus.OK;
223         if (component.getComponentType() == ComponentTypeEnum.RESOURCE && component.isTopologyTemplate()  ){
224             List<CategoryDefinition> categories = component.getCategories();
225             Optional<CategoryDefinition> findFirst = categories.stream().filter(c->c.getName().equals(ALLOTTED_CATEGORY)).findFirst();
226             if ( findFirst.isPresent() ){
227                 findInstanceByAllottedProperties(component);
228             }else{
229                 log.debug("Component isn't from allotted category.");
230             }
231         }
232         return status;
233     }
234
235     private void findInstanceByAllottedProperties(Component component) {
236         log.debug("Component is from alloted category. Remove all previous ALLOTTED_OF connections for all instances");
237         nodeTemplateOperation.removeAllAllotedEdges(component.getUniqueId());
238         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
239         if ( componentInstancesProperties != null ){
240             componentInstancesProperties.entrySet().forEach(e->{
241                 List<ComponentInstanceProperty> props = e.getValue();
242                 Optional<ComponentInstanceProperty> findProp = props.stream().filter(p -> p.getName().equals(DEPENDING_SRV_NAME) ||  p.getName().equals(PROVIDING_SRV_NAME)).findFirst();
243                 if ( findProp.isPresent() ){
244                     log.debug("Find specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME,PROVIDING_SRV_NAME, e.getKey()  );
245                     handleAllotedInstance(component.getUniqueId(), e.getKey(), e.getValue() );
246                 }else{
247                     log.debug("Not defined specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME,PROVIDING_SRV_NAME, e.getKey()  );
248                 }
249             });
250         }
251     }
252
253     private StorageOperationStatus handleAllotedInstance(String componentId, String instanceId, List<ComponentInstanceProperty> props) {
254         ComponentInstanceProperty serviceUUIDProp = props.stream().filter(p -> p.getName().equals(PROVIDING_SRV_UUID) ||  p.getName().equals(DEPENDING_SRV_UUID)).findFirst().get();
255         if ( serviceUUIDProp.getValue() != null && !serviceUUIDProp.getValue().contains("get_input")){
256             log.debug("Handle Allotted edge on instance {} for service UUID {} ", instanceId,  serviceUUIDProp.getValue() );
257             return  nodeTemplateOperation.createAllottedOfEdge(componentId, instanceId, serviceUUIDProp.getValue());
258         }else{
259             log.debug("An incorrectly defined service UUID for Allotted instance {} . Skip instance", instanceId,  serviceUUIDProp.getValue() );
260             return StorageOperationStatus.OK;
261         }
262     }
263 }