[sdc] rebase update
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / lifecycle / CertificationRequestTransition.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 java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import java.util.Set;
31
32 import org.apache.commons.codec.binary.Base64;
33 import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
34 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
35 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
36 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
37 import org.openecomp.sdc.be.config.BeEcompErrorManager;
38 import org.openecomp.sdc.be.dao.api.ActionStatus;
39 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
40 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
41 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
42 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
43 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
44 import org.openecomp.sdc.be.impl.ComponentsUtils;
45 import org.openecomp.sdc.be.model.ArtifactDefinition;
46 import org.openecomp.sdc.be.model.CapabilityDefinition;
47 import org.openecomp.sdc.be.model.Component;
48 import org.openecomp.sdc.be.model.ComponentInstance;
49 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
50 import org.openecomp.sdc.be.model.LifecycleStateEnum;
51 import org.openecomp.sdc.be.model.Operation;
52 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
53 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
54 import org.openecomp.sdc.be.model.Resource;
55 import org.openecomp.sdc.be.model.Service;
56 import org.openecomp.sdc.be.model.User;
57 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
58 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
59 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
60 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
61 import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
62 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
63 import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
64 import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
65 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
66 import org.openecomp.sdc.be.tosca.ToscaError;
67 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
68 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
69 import org.openecomp.sdc.be.user.Role;
70 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
71 import org.openecomp.sdc.common.util.ValidationUtils;
72 import org.openecomp.sdc.exception.ResponseFormat;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 import fj.data.Either;
77
78 public class CertificationRequestTransition extends LifeCycleTransition {
79
80         private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName());
81
82         private CapabilityOperation capabilityOperation;
83         private ServiceBusinessLogic serviceBusinessLogic;
84         public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
85                         CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
86                 super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
87
88                 // authorized roles
89                 Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
90                 // Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER,
91                 // Role.PRODUCT_STRATEGIST};
92                 addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
93                 addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
94                 // TODO to be later defined for product
95                 // addAuthorizedRoles(ComponentTypeEnum.PRODUCT,
96                 // Arrays.asList(productCheckoutRoles));
97                 
98                 //additional authorized roles for resource type
99                 Role[] resourceRoles = { Role.TESTER};
100                 addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
101
102                 this.serviceBusinessLogic = serviceBusinessLogic;
103                 this.capabilityOperation = capabilityOperation;
104         }
105
106         @Override
107         public LifeCycleTransitionEnum getName() {
108                 return LifeCycleTransitionEnum.CERTIFICATION_REQUEST;
109         }
110
111         @Override
112         public AuditingActionEnum getAuditingAction() {
113                 return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE;
114         }
115
116         protected Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) {
117                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
118
119                 List<ComponentInstance> resourceInstance = component.getComponentInstances();
120                 if (resourceInstance != null) {
121                         Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny();
122                         // Uncertified Resource Found
123                         if (nonCertifiedRIOptional.isPresent()) {
124                                 ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get();
125                                 ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType());
126                                 eitherResult = Either.right(resFormat);
127                         }
128                 }
129                 return eitherResult;
130         }
131
132         private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
133
134                 ResponseFormat responseFormat;
135                 Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
136                 if (eitherResource.isRight()) {
137
138                         responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
139
140                 } else {
141                         ActionStatus actionStatus;
142                         Resource resource = eitherResource.left().value();
143                         Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
144
145                         if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
146                                 if (status.isRight() || status.left().value() == null) {
147                                         actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND;
148                                 } else {
149                                         actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
150                                 }
151                         } else {
152                                 if (status.isRight() || status.left().value() == null)
153                                         actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES;
154                                 else {
155                                         actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
156                                 }
157
158                         }
159                         String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service";
160                         responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName());
161                 }
162                 return responseFormat;
163         }
164
165         private Either<ActionStatus, Map<String, ArtifactDefinition>> validateMandatoryArtifactsSupplied(Map<String, ArtifactDefinition> artifacts) {
166
167                 if (artifacts == null || artifacts.isEmpty()) {
168                         return Either.left(ActionStatus.OK);
169                 }
170
171                 Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<>();
172                 for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
173
174                         ArtifactDefinition artifactDefinition = artifact.getValue();
175                         if (artifactDefinition.getMandatory()) {
176                                 String artifactEsId = artifactDefinition.getEsId();
177                                 if (artifactEsId == null || artifactEsId.isEmpty()) {
178                                         invalidArtifacts.put(artifact.getKey(), artifactDefinition);
179                                 }
180                         }
181                 }
182
183                 if (invalidArtifacts.isEmpty()) {
184                         return Either.left(ActionStatus.OK);
185                 } else {
186                         return Either.right(invalidArtifacts);
187                 }
188         }
189
190         @Override
191         public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
192
193                 log.debug("start performing certification request for resource {}", component.getUniqueId());
194
195                 ActionStatus actionStatus;
196                 ResponseFormat responseFormat;
197                 Either<? extends Component, ResponseFormat> result = null;
198                 try{
199                         if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
200         
201                                 Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
202                                 if (statusCert.isRight()) {
203                                         return Either.right(statusCert.right().value());
204                                 }
205         
206                                 statusCert = validateConfiguredAtomicReqCapSatisfied(component);
207                                 if (statusCert.isRight()) {
208                                         return Either.right(statusCert.right().value());
209                                 }
210                         }
211                         if (componentType == ComponentTypeEnum.SERVICE) {
212                         
213                                 Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock);
214                                                 
215                                 if (generateHeatEnvResult.isRight()) {
216                                                 return Either.right(generateHeatEnvResult.right().value());
217                                         }
218                                 Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock);
219                                 if (generateVfModuleResult.isRight()) {
220                                                 return Either.right(generateVfModuleResult.right().value());
221                                 }
222                         }
223         
224                         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
225                         if (eitherPopulated != null && eitherPopulated.isRight()) {
226                                 return Either.right(eitherPopulated.right().value());
227                         }
228         
229                         NodeTypeEnum nodeType = componentType.equals(ComponentTypeEnum.SERVICE) ? NodeTypeEnum.Service : NodeTypeEnum.Resource;
230                         
231                         
232                         Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
233                         if (certificationRequestResult.isRight()) {
234                                 log.debug("checkout failed on graph");
235                                 StorageOperationStatus response = certificationRequestResult.right().value();
236                                 actionStatus = componentUtils.convertFromStorageResponse(response);
237         
238                                 if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
239                                         actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
240                                 }
241                                 responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
242                                 result =  Either.right(responseFormat);
243                         }
244                         else {
245                                 result =  Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value()));
246                         }
247         } finally {
248                 if (result == null || result.isRight()) {
249                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
250                         if (inTransaction == false) {
251                                 log.debug("operation failed. do rollback");
252                                 titanDao.rollback();
253                         }
254                 } else {
255                         if (inTransaction == false) {
256                                 log.debug("operation success. do commit");
257                                 titanDao.commit();
258                         }
259                 }
260         }
261                 return result;
262         }
263
264         private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) {
265                 log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId());
266                 List<ComponentInstance> componentInstances = component.getComponentInstances();
267                 if (componentInstances != null) {
268                         // Prepare relationships data structures
269                         // Better make it list than set in case we need to count req/cap
270                         // occurrences in the future
271                         Map<String, List<String>> reqName2Ids = new HashMap<>();
272                         Map<String, List<String>> capName2Ids = new HashMap<>();
273                         parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids);
274                         Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert();
275                         Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert();
276                         for (ComponentInstance compInst : componentInstances) {
277                                 String compInstId = compInst.getUniqueId();
278                                 OriginTypeEnum originType = compInst.getOriginType();
279                                 if (originType == null) {
280                                         log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId());
281                                         continue;
282                                 }
283                                 String compInstType = originType.getValue();
284                                 // Validating configured requirements fulfilled
285                                 if (null != requirementsToFulfillBeforeCert) {
286                                         Set<String> reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType);
287                                         if (reqToFulfillForType != null) {
288                                                 for (String reqNameToFulfill : reqToFulfillForType) {
289                                                         List<String> reqNameList = reqName2Ids.get(reqNameToFulfill);
290                                                         if (reqNameList == null || !reqNameList.contains(compInstId)) {
291                                                                 log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType);
292                                                                 ComponentTypeEnum componentType = component.getComponentType();
293                                                                 String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
294                                                                 ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement",
295                                                                                 reqNameToFulfill, "fulfilled");
296                                                                 return Either.right(responseFormat);
297                                                         }
298                                                 }
299                                         }
300                                 }
301                                 // Validating configured capabilities consumed
302                                 if (null != capabilitiesToConsumeBeforeCert) {
303                                         Set<String> capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType);
304                                         if (capToConsumeForType != null) {
305                                                 for (String capNameToConsume : capToConsumeForType) {
306                                                         List<String> capNameList = capName2Ids.get(capNameToConsume);
307                                                         if (capNameList == null || !capNameList.contains(compInstId)) {
308                                                                 log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType);
309                                                                 ComponentTypeEnum componentType = component.getComponentType();
310                                                                 String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
311                                                                 ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability",
312                                                                                 capNameToConsume, "consumed");
313                                                                 return Either.right(responseFormat);
314                                                         }
315                                                 }
316                                         }
317                                 }
318                         }
319                 }
320                 log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId());
321                 return Either.left(true);
322         }
323
324         private Either<Boolean, ResponseFormat> parseRelationsForReqCapVerification(Component component, Map<String, List<String>> reqName2Ids, Map<String, List<String>> capName2Ids) {
325                 log.debug("Submit for testing validation - Preparing relations for inner atomic instances validation");
326                 List<RequirementCapabilityRelDef> componentInstancesRelations = component.getComponentInstancesRelations();
327                 if (componentInstancesRelations != null) {
328                         for (RequirementCapabilityRelDef reqCapRelDef : componentInstancesRelations) {
329                                 List<RequirementAndRelationshipPair> relationships = reqCapRelDef.getRelationships();
330                                 if (relationships != null) {
331                                         for (RequirementAndRelationshipPair reqRelPair : relationships) {
332                                                 String capUniqueId = reqRelPair.getCapabilityUid();
333                                                 Either<CapabilityDefinition, StorageOperationStatus> capability = capabilityOperation.getCapability(capUniqueId);
334                                                 if (capability.isRight()) {
335                                                         log.error("Couldn't fetch capability by id {}", capUniqueId);
336                                                         return Either.right(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
337                                                 }
338                                                 String reqCapType = capability.left().value().getType();
339                                                 String capabilityOwnerId = reqRelPair.getCapabilityOwnerId();
340                                                 String requirementOwnerId = reqRelPair.getRequirementOwnerId();
341                                                 // Update req
342                                                 List<String> reqIds = reqName2Ids.get(reqCapType);
343                                                 if (reqIds == null) {
344                                                         reqIds = new ArrayList<>();
345                                                         reqName2Ids.put(reqCapType, reqIds);
346                                                 }
347                                                 reqIds.add(requirementOwnerId);
348                                                 // Update cap
349                                                 List<String> capIds = capName2Ids.get(reqCapType);
350                                                 if (capIds == null) {
351                                                         capIds = new ArrayList<>();
352                                                         capName2Ids.put(reqCapType, capIds);
353                                                 }
354                                                 capIds.add(capabilityOwnerId);
355                                         }
356                                 }
357                         }
358                         log.debug("Parsed req for validation: {}, parsed cap for validation: {}", reqName2Ids, capName2Ids);
359                 } else {
360                         log.debug("There are no relations found for component {}", component.getUniqueId());
361                 }
362                 return Either.left(true);
363         }
364
365         @Override
366         public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
367                 String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
368                 log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
369
370                 // validate user
371                 Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
372                 if (userValidationResponse.isRight()) {
373                         return userValidationResponse;
374                 }
375
376                 // case of "atomic" checkin and certification request - modifier must be
377                 // the owner
378                 if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
379                         ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
380                         return Either.right(error);
381                 }
382
383                 // other states
384                 if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
385                         ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
386                         return Either.right(error);
387                 }
388                 if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
389                         ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
390                         return Either.right(error);
391                 }
392                 if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
393                         ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
394                         return Either.right(error);
395                 }
396
397                 return Either.left(true);
398         }
399 }