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