Reformat openecomp-be
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / main / java / org / openecomp / sdc / vendorsoftwareproduct / impl / orchestration / process / OrchestrationTemplateProcessCsarHandler.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Optional;
26 import org.apache.commons.collections4.MapUtils;
27 import org.openecomp.core.impl.AbstractToscaSolConverter;
28 import org.openecomp.core.impl.ToscaConverterImpl;
29 import org.openecomp.core.impl.ToscaSolConverterVnf;
30 import org.openecomp.core.impl.ToscaSolModelDrivenConverterPnf;
31 import org.openecomp.core.utilities.file.FileContentHandler;
32 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
33 import org.openecomp.core.validation.util.MessageContainerUtil;
34 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
35 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
36 import org.openecomp.sdc.common.errors.CoreException;
37 import org.openecomp.sdc.common.utils.SdcCommon;
38 import org.openecomp.sdc.datatypes.error.ErrorLevel;
39 import org.openecomp.sdc.datatypes.error.ErrorMessage;
40 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
41 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
42 import org.openecomp.sdc.heat.services.tree.ToscaTreeManager;
43 import org.openecomp.sdc.logging.api.Logger;
44 import org.openecomp.sdc.logging.api.LoggerFactory;
45 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
46 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity;
49 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
50 import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory;
51 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil;
52 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
53 import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIService;
54 import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIServiceImpl;
55 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
57
58 public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTemplateProcessHandler {
59
60     private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessCsarHandler.class);
61     private static final String SDC_ONBOARDED_PACKAGE_DIR = "Deployment/" + ArtifactTypeEnum.ETSI_PACKAGE.getType() + "/";
62     private static final String EXT_SEPARATOR = ".";
63     private final CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface();
64     private final ToscaTreeManager toscaTreeManager = new ToscaTreeManager();
65
66     @Override
67     public OrchestrationTemplateActionResponse process(VspDetails vspDetails, OrchestrationTemplateCandidateData candidateData) {
68         UploadFileResponse uploadFileResponse = new UploadFileResponse();
69         Optional<FileContentHandler> fileContent = OrchestrationUtil
70             .getFileContentMap(OnboardingTypesEnum.CSAR, uploadFileResponse, candidateData.getContentData().array());
71         OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
72         if (fileContent.isPresent()) {
73             try {
74                 FileContentHandler fileContentHandler = fileContent.get();
75                 processCsar(vspDetails, fileContentHandler, candidateData, response);
76             } catch (CoreException e) {
77                 LOGGER.error(e.getMessage(), e);
78                 response.addErrorMessageToMap(e.code().id(), e.code().message(), ErrorLevel.ERROR);
79             } catch (IOException e) {
80                 LOGGER.error(e.getMessage(), e);
81                 response.addErrorMessageToMap(SdcCommon.PROCESS_FILE, e.getMessage(), ErrorLevel.ERROR);
82             }
83         } else {
84             if (!uploadFileResponse.getErrors().isEmpty()) {
85                 response.addStructureErrors(uploadFileResponse.getErrors());
86             }
87         }
88         return response;
89     }
90
91     private void processCsar(VspDetails vspDetails, FileContentHandler fileContentHandler, OrchestrationTemplateCandidateData candidateData,
92                              OrchestrationTemplateActionResponse response) throws IOException {
93         response.setFileNames(new ArrayList<>(fileContentHandler.getFileList()));
94         Map<String, List<ErrorMessage>> errors = validateCsar(fileContentHandler);
95         toscaTreeManager.createTree();
96         if (!isValid(errors)) {
97             response.addStructureErrors(errors);
98             toscaTreeManager.addErrors(errors);
99             candidateService
100                 .updateValidationData(vspDetails.getId(), vspDetails.getVersion(), new ValidationStructureList(toscaTreeManager.getTree()));
101             return;
102         }
103         HeatStructureTree tree = toscaTreeManager.getTree();
104         Map<String, String> componentsQuestionnaire = new HashMap<>();
105         Map<String, Map<String, String>> componentNicsQuestionnaire = new HashMap<>();
106         Map<String, Collection<ComponentMonitoringUploadEntity>> componentMibList = new HashMap<>();
107         Map<String, Collection<ProcessEntity>> processes = new HashMap<>();
108         Map<String, ProcessEntity> processArtifact = new HashMap<>();
109         OrchestrationUtil orchestrationUtil = new OrchestrationUtil();
110         orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspDetails.getId(), vspDetails.getVersion(), componentsQuestionnaire,
111             componentNicsQuestionnaire, componentMibList, processes, processArtifact);
112         Optional<ByteArrayInputStream> zipByteArrayInputStream = candidateService
113             .fetchZipFileByteArrayInputStream(vspDetails.getId(), candidateData, null, OnboardingTypesEnum.CSAR, errors);
114         orchestrationUtil.deleteUploadDataAndContent(vspDetails.getId(), vspDetails.getVersion());
115         zipByteArrayInputStream.ifPresent(
116             byteArrayInputStream -> orchestrationUtil.saveUploadData(vspDetails, candidateData, byteArrayInputStream, fileContentHandler, tree));
117         ETSIService etsiService = new ETSIServiceImpl();
118         ToscaServiceModel toscaServiceModel;
119         if (etsiService.isSol004WithToscaMetaDirectory(fileContentHandler)) {
120             if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(candidateData.getFileSuffix())) {
121                 fileContentHandler
122                     .addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getOriginalFileName() + EXT_SEPARATOR + candidateData.getOriginalFileSuffix(),
123                         candidateData.getOriginalFileContentData().array());
124             } else {
125                 fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getFileName() + EXT_SEPARATOR + candidateData.getFileSuffix(),
126                     candidateData.getContentData().array());
127             }
128             final ResourceTypeEnum resourceType = etsiService.getResourceType(fileContentHandler);
129             toscaServiceModel = instantiateToscaConverterFor(resourceType).convert(fileContentHandler);
130         } else {
131             toscaServiceModel = new ToscaConverterImpl().convert(fileContentHandler);
132         }
133         orchestrationUtil.saveServiceModel(vspDetails.getId(), vspDetails.getVersion(), toscaServiceModel, toscaServiceModel);
134         candidateService.deleteOrchestrationTemplateCandidate(vspDetails.getId(), vspDetails.getVersion());
135     }
136
137     private AbstractToscaSolConverter instantiateToscaConverterFor(ResourceTypeEnum resourceType) {
138         if (resourceType == ResourceTypeEnum.PNF) {
139             return new ToscaSolModelDrivenConverterPnf();
140         }
141         // default is VF
142         return new ToscaSolConverterVnf();
143     }
144
145     private void addFiles(FileContentHandler fileContentHandler) {
146         for (Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
147             toscaTreeManager.addFile(fileEntry.getKey(), fileEntry.getValue());
148         }
149     }
150
151     private Map<String, List<ErrorMessage>> validateCsar(FileContentHandler fileContentHandler) {
152         Map<String, List<ErrorMessage>> errors = new HashMap<>();
153         addFiles(fileContentHandler);
154         toscaTreeManager.createTree();
155         toscaTreeManager.addErrors(errors);
156         //todo - add tosca validation here to the existing validation framework
157         return errors;
158     }
159
160     private boolean isValid(Map<String, List<ErrorMessage>> errors) {
161         return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors));
162     }
163 }