dfd7beeaf1fa18adcff084952e4a9539d694bee2
[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.distribution.engine.ServiceDistributionArtifactsBuilder;
25 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
26 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
27 import org.openecomp.sdc.be.config.BeEcompErrorManager;
28 import org.openecomp.sdc.be.dao.api.ActionStatus;
29 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
30 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
31 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
32 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
33 import org.openecomp.sdc.be.impl.ComponentsUtils;
34 import org.openecomp.sdc.be.model.*;
35 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
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.model.operations.impl.CapabilityOperation;
41 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
42 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
43 import org.openecomp.sdc.be.user.Role;
44 import org.openecomp.sdc.common.util.ValidationUtils;
45 import org.openecomp.sdc.exception.ResponseFormat;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import java.util.*;
50
51 public class CertificationRequestTransition extends LifeCycleTransition {
52
53     private static final Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class);
54
55     private CapabilityOperation capabilityOperation;
56     private ServiceBusinessLogic serviceBusinessLogic;
57     public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
58             CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
59         super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
60
61         // authorized roles
62         Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
63         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
64         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
65         // TODO to be later defined for product
66         // addAuthorizedRoles(ComponentTypeEnum.PRODUCT,
67         // Arrays.asList(productCheckoutRoles));
68
69         //additional authorized roles for resource type
70         Role[] resourceRoles = { Role.TESTER};
71         addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
72
73         this.serviceBusinessLogic = serviceBusinessLogic;
74         this.capabilityOperation = capabilityOperation;
75     }
76
77     @Override
78     public LifeCycleTransitionEnum getName() {
79         return LifeCycleTransitionEnum.CERTIFICATION_REQUEST;
80     }
81
82     @Override
83     public AuditingActionEnum getAuditingAction() {
84         return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE;
85     }
86
87     protected Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) {
88         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
89
90         List<ComponentInstance> resourceInstance = component.getComponentInstances();
91         if (resourceInstance != null) {
92             Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny();
93             // Uncertified Resource Found
94             if (nonCertifiedRIOptional.isPresent()) {
95                 ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get();
96                 ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType());
97                 eitherResult = Either.right(resFormat);
98             }
99         }
100         return eitherResult;
101     }
102
103     private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
104
105         ResponseFormat responseFormat;
106         Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
107         if (eitherResource.isRight()) {
108
109             responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
110
111         } else {
112             ActionStatus actionStatus;
113             Resource resource = eitherResource.left().value();
114             Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
115
116             if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
117                 if (status.isRight() || status.left().value() == null) {
118                     actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND;
119                 } else {
120                     actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
121                 }
122             } else {
123                 if (status.isRight() || status.left().value() == null)
124                     actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES;
125                 else {
126                     actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
127                 }
128
129             }
130             String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service";
131             responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName());
132         }
133         return responseFormat;
134     }
135
136     @Override
137     public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
138
139         log.debug("start performing certification request for resource {}", component.getUniqueId());
140
141         ActionStatus actionStatus;
142         ResponseFormat responseFormat;
143         Either<? extends Component, ResponseFormat> result = null;
144         try{
145             if (component.isTopologyTemplate()) {
146
147                 Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
148                 if (statusCert.isRight()) {
149                     return Either.right(statusCert.right().value());
150                 }
151
152                 statusCert = validateConfiguredAtomicReqCapSatisfied(component);
153                 if (statusCert.isRight()) {
154                     return Either.right(statusCert.right().value());
155                 }
156             }
157             if (componentType == ComponentTypeEnum.SERVICE) {
158
159                 Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction);
160
161                 if (generateHeatEnvResult.isRight()) {
162                         return Either.right(generateHeatEnvResult.right().value());
163                     }
164                 Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction);
165                 if (generateVfModuleResult.isRight()) {
166                         return Either.right(generateVfModuleResult.right().value());
167                 }
168                 component = generateVfModuleResult.left().value();
169
170             }
171
172             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
173             if (eitherPopulated != null && eitherPopulated.isRight()) {
174                 return Either.right(eitherPopulated.right().value());
175             }
176
177             Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
178             if (certificationRequestResult.isRight()) {
179                 log.debug("checkout failed on graph");
180                 StorageOperationStatus response = certificationRequestResult.right().value();
181                 actionStatus = componentUtils.convertFromStorageResponse(response);
182
183                 if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
184                     actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
185                 }
186                 responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
187                 result =  Either.right(responseFormat);
188             }
189             else {
190                 result =  Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value()));
191             }
192     } finally {
193         if (result == null || result.isRight()) {
194             BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
195             if (!inTransaction) {
196                 log.debug("operation failed. do rollback");
197                 titanDao.rollback();
198             }
199         } else {
200             if (!inTransaction) {
201                 log.debug("operation success. do commit");
202                 titanDao.commit();
203             }
204         }
205     }
206         return result;
207     }
208
209     private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) {
210         log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId());
211         List<ComponentInstance> componentInstances = component.getComponentInstances();
212         if (componentInstances != null) {
213             // Prepare relationships data structures
214             // Better make it list than set in case we need to count req/cap
215             // occurrences in the future
216             Map<String, List<String>> reqName2Ids = new HashMap<>();
217             Map<String, List<String>> capName2Ids = new HashMap<>();
218             Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert();
219             Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert();
220             for (ComponentInstance compInst : componentInstances) {
221                 String compInstId = compInst.getUniqueId();
222                 OriginTypeEnum originType = compInst.getOriginType();
223                 if (originType == null) {
224                     log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId());
225                     continue;
226                 }
227                 String compInstType = originType.getValue();
228                 // Validating configured requirements fulfilled
229                 if (null != requirementsToFulfillBeforeCert) {
230                     Set<String> reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType);
231                     if (reqToFulfillForType != null) {
232                         for (String reqNameToFulfill : reqToFulfillForType) {
233                             List<String> reqNameList = reqName2Ids.get(reqNameToFulfill);
234                             if (reqNameList == null || !reqNameList.contains(compInstId)) {
235                                 log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType);
236                                 ComponentTypeEnum componentType = component.getComponentType();
237                                 String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
238                                 ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement",
239                                         reqNameToFulfill, "fulfilled");
240                                 return Either.right(responseFormat);
241                             }
242                         }
243                     }
244                 }
245                 // Validating configured capabilities consumed
246                 if (null != capabilitiesToConsumeBeforeCert) {
247                     Set<String> capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType);
248                     if (capToConsumeForType != null) {
249                         for (String capNameToConsume : capToConsumeForType) {
250                             List<String> capNameList = capName2Ids.get(capNameToConsume);
251                             if (capNameList == null || !capNameList.contains(compInstId)) {
252                                 log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType);
253                                 ComponentTypeEnum componentType = component.getComponentType();
254                                 String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
255                                 ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability",
256                                         capNameToConsume, "consumed");
257                                 return Either.right(responseFormat);
258                             }
259                         }
260                     }
261                 }
262             }
263         }
264         log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId());
265         return Either.left(true);
266     }
267
268     @Override
269     public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
270         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
271         log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
272
273         // validate user
274         Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
275         if (userValidationResponse.isRight()) {
276             return userValidationResponse;
277         }
278
279         // case of "atomic" checkin and certification request - modifier must be
280         // the owner
281         if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
282             ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
283             return Either.right(error);
284         }
285
286         // other states
287         if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
288             ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
289             return Either.right(error);
290         }
291         if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
292             ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
293             return Either.right(error);
294         }
295         if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
296             ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
297             return Either.right(error);
298         }
299
300         return Either.left(true);
301     }
302 }