Identify SOL004 packages
[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.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Optional;
25 import org.apache.commons.collections4.CollectionUtils;
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.ToscaModelConverter;
30 import org.openecomp.core.impl.ToscaSolConverterVnf;
31 import org.openecomp.core.impl.ToscaSolModelDrivenConverterPnf;
32 import org.openecomp.core.utilities.file.FileContentHandler;
33 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
34 import org.openecomp.core.validation.util.MessageContainerUtil;
35 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
36 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
37 import org.openecomp.sdc.common.errors.CoreException;
38 import org.openecomp.sdc.common.utils.SdcCommon;
39 import org.openecomp.sdc.datatypes.error.ErrorLevel;
40 import org.openecomp.sdc.datatypes.error.ErrorMessage;
41 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
42 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
43 import org.openecomp.sdc.heat.services.tree.ToscaTreeManager;
44 import org.openecomp.sdc.logging.api.Logger;
45 import org.openecomp.sdc.logging.api.LoggerFactory;
46 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
49 import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory;
50 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil;
51 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
52 import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIService;
53 import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIServiceImpl;
54 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
55 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
56
57 public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTemplateProcessHandler {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessCsarHandler.class);
60     private static final String SDC_ONBOARDED_PACKAGE_DIR = "Deployment/" + ArtifactTypeEnum.ETSI_PACKAGE.getType() + "/";
61     private static final String EXT_SEPARATOR = ".";
62     private final CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface();
63     private final ToscaTreeManager toscaTreeManager = new ToscaTreeManager();
64     private final ETSIService etsiService;
65
66     public OrchestrationTemplateProcessCsarHandler() {
67         etsiService = new ETSIServiceImpl();
68     }
69
70     @Override
71     public OrchestrationTemplateActionResponse process(VspDetails vspDetails, OrchestrationTemplateCandidateData candidateData) {
72         UploadFileResponse uploadFileResponse = new UploadFileResponse();
73         Optional<FileContentHandler> fileContent = OrchestrationUtil
74             .getFileContentMap(OnboardingTypesEnum.CSAR, uploadFileResponse, candidateData.getContentData().array());
75         OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
76         if (fileContent.isPresent()) {
77             try {
78                 FileContentHandler fileContentHandler = fileContent.get();
79                 processCsar(vspDetails, fileContentHandler, candidateData, response);
80             } catch (CoreException e) {
81                 LOGGER.error(e.getMessage(), e);
82                 response.addErrorMessageToMap(e.code().id(), e.code().message(), ErrorLevel.ERROR);
83             } catch (IOException e) {
84                 LOGGER.error(e.getMessage(), e);
85                 response.addErrorMessageToMap(SdcCommon.PROCESS_FILE, e.getMessage(), ErrorLevel.ERROR);
86             }
87         } else {
88             if (!uploadFileResponse.getErrors().isEmpty()) {
89                 response.addStructureErrors(uploadFileResponse.getErrors());
90             }
91         }
92         return response;
93     }
94
95     private void processCsar(VspDetails vspDetails, FileContentHandler fileContentHandler, OrchestrationTemplateCandidateData candidateData,
96                              OrchestrationTemplateActionResponse response) throws IOException {
97         response.setFileNames(new ArrayList<>(fileContentHandler.getFileList()));
98         Map<String, List<ErrorMessage>> errors = validateCsar(fileContentHandler);
99         toscaTreeManager.createTree();
100         if (!isValid(errors)) {
101             response.addStructureErrors(errors);
102             toscaTreeManager.addErrors(errors);
103             candidateService
104                 .updateValidationData(vspDetails.getId(), vspDetails.getVersion(), new ValidationStructureList(toscaTreeManager.getTree()));
105             return;
106         }
107         HeatStructureTree tree = toscaTreeManager.getTree();
108         final var orchestrationUtil = new OrchestrationUtil();
109         orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspDetails.getId(), vspDetails.getVersion(),
110             new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>());
111         Optional<ByteArrayInputStream> zipByteArrayInputStream = candidateService
112             .fetchZipFileByteArrayInputStream(vspDetails.getId(), candidateData, null, OnboardingTypesEnum.CSAR, errors);
113         orchestrationUtil.deleteUploadDataAndContent(vspDetails.getId(), vspDetails.getVersion());
114         zipByteArrayInputStream.ifPresent(
115             byteArrayInputStream -> orchestrationUtil.saveUploadData(vspDetails, candidateData, byteArrayInputStream, fileContentHandler, tree));
116         final var toscaServiceModel = convertToToscaServiceModel(vspDetails.getModelIdList(), fileContentHandler, candidateData);
117         orchestrationUtil
118             .saveServiceModel(vspDetails.getId(), vspDetails.getVersion(), toscaServiceModel, toscaServiceModel);
119         candidateService.deleteOrchestrationTemplateCandidate(vspDetails.getId(), vspDetails.getVersion());
120     }
121
122     private ToscaServiceModel convertToToscaServiceModel(final List<String> modelList, final FileContentHandler fileContentHandler,
123                                                          final OrchestrationTemplateCandidateData candidateData) throws IOException {
124         if (CollectionUtils.isNotEmpty(modelList)) {
125             return handleToscaModelConversion(modelList, fileContentHandler, candidateData);
126         }
127         if (etsiService.isEtsiPackage(fileContentHandler)) {
128             return getToscaServiceModelSol004(fileContentHandler, candidateData);
129         }
130         return new ToscaConverterImpl().convert(fileContentHandler);
131     }
132
133     private ToscaServiceModel handleToscaModelConversion(final List<String> modelList, final FileContentHandler fileContentHandler,
134                                                          final OrchestrationTemplateCandidateData candidateData) throws IOException {
135         addOriginalOnboardedPackage(fileContentHandler, candidateData);
136         final var toscaServiceModel = new ToscaModelConverter().convert(fileContentHandler);
137         toscaServiceModel.setModelList(modelList);
138         return toscaServiceModel;
139     }
140
141     private ToscaServiceModel getToscaServiceModelSol004(final FileContentHandler fileContentHandler,
142                                                          final OrchestrationTemplateCandidateData candidateData) throws IOException {
143         addOriginalOnboardedPackage(fileContentHandler, candidateData);
144         final ResourceTypeEnum resourceType = etsiService.getResourceType(fileContentHandler);
145         return instantiateToscaConverterFor(resourceType).convert(fileContentHandler);
146     }
147
148     private void addOriginalOnboardedPackage(final FileContentHandler fileContentHandler, final OrchestrationTemplateCandidateData candidateData) {
149         if (OnboardingTypesEnum.CSAR.getType().equalsIgnoreCase(candidateData.getFileSuffix())) {
150             fileContentHandler
151                 .addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getOriginalFileName() + EXT_SEPARATOR + candidateData.getOriginalFileSuffix(),
152                     candidateData.getOriginalFileContentData().array());
153         } else {
154             fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getFileName() + EXT_SEPARATOR + candidateData.getFileSuffix(),
155                 candidateData.getContentData().array());
156         }
157     }
158
159     private AbstractToscaSolConverter instantiateToscaConverterFor(ResourceTypeEnum resourceType) {
160         if (resourceType == ResourceTypeEnum.PNF) {
161             return new ToscaSolModelDrivenConverterPnf();
162         }
163         // default is VF
164         return new ToscaSolConverterVnf();
165     }
166
167     private void addFiles(FileContentHandler fileContentHandler) {
168         for (Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
169             toscaTreeManager.addFile(fileEntry.getKey(), fileEntry.getValue());
170         }
171     }
172
173     private Map<String, List<ErrorMessage>> validateCsar(FileContentHandler fileContentHandler) {
174         Map<String, List<ErrorMessage>> errors = new HashMap<>();
175         addFiles(fileContentHandler);
176         toscaTreeManager.createTree();
177         toscaTreeManager.addErrors(errors);
178         //todo - add tosca validation here to the existing validation framework
179         return errors;
180     }
181
182     private boolean isValid(Map<String, List<ErrorMessage>> errors) {
183         return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors));
184     }
185 }