ac7a1510c76775f3411388fdc756a9c21eaf9934
[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.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/ONBOARDED_PACKAGE/";
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,
68                                   OrchestrationTemplateCandidateData candidateData) {
69
70
71     UploadFileResponse uploadFileResponse = new UploadFileResponse();
72     Optional<FileContentHandler> fileContent = OrchestrationUtil
73         .getFileContentMap(OnboardingTypesEnum.CSAR, uploadFileResponse,
74             candidateData.getContentData().array());
75
76     OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
77     if (fileContent.isPresent()) {
78       try {
79         FileContentHandler fileContentHandler = fileContent.get();
80         processCsar(vspDetails, fileContentHandler, candidateData, response);
81       } catch (CoreException e) {
82         LOGGER.error(e.getMessage(), e);
83         response.addErrorMessageToMap(e.code().id(), e.code().message(),ErrorLevel.ERROR);
84       }catch (IOException e){
85         LOGGER.error(e.getMessage(), e);
86         response.addErrorMessageToMap(SdcCommon.PROCESS_FILE, e.getMessage(), ErrorLevel.ERROR);
87       }
88     } else {
89       if (!uploadFileResponse.getErrors().isEmpty()) {
90         response.addStructureErrors(uploadFileResponse.getErrors());
91       }
92     }
93     return response;
94   }
95
96   private void processCsar(VspDetails vspDetails,
97                            FileContentHandler fileContentHandler,
98                            OrchestrationTemplateCandidateData candidateData,
99                            OrchestrationTemplateActionResponse response) throws IOException{
100     response.setFileNames(new ArrayList<>(fileContentHandler.getFileList()));
101     Map<String, List<ErrorMessage>> errors = validateCsar(fileContentHandler);
102     toscaTreeManager.createTree();
103
104     if (!isValid(errors)) {
105       response.addStructureErrors(errors);
106       toscaTreeManager.addErrors(errors);
107       candidateService.updateValidationData(vspDetails.getId(), vspDetails.getVersion(),
108           new ValidationStructureList(toscaTreeManager.getTree()));
109       return;
110     }
111
112     HeatStructureTree tree = toscaTreeManager.getTree();
113
114     Map<String, String> componentsQuestionnaire = new HashMap<>();
115     Map<String, Map<String, String>> componentNicsQuestionnaire = new HashMap<>();
116     Map<String, Collection<ComponentMonitoringUploadEntity>> componentMibList = new HashMap<>();
117     Map<String, Collection<ProcessEntity>> processes = new HashMap<>();
118     Map<String, ProcessEntity> processArtifact = new HashMap<>();
119     OrchestrationUtil orchestrationUtil = new OrchestrationUtil();
120     orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspDetails.getId(),
121         vspDetails.getVersion(), componentsQuestionnaire,
122         componentNicsQuestionnaire, componentMibList, processes, processArtifact);
123
124     Optional<ByteArrayInputStream> zipByteArrayInputStream = candidateService
125         .fetchZipFileByteArrayInputStream(vspDetails.getId(), candidateData, null,
126             OnboardingTypesEnum.CSAR, errors);
127
128     orchestrationUtil.deleteUploadDataAndContent(vspDetails.getId(), vspDetails.getVersion());
129     zipByteArrayInputStream.ifPresent(byteArrayInputStream -> orchestrationUtil
130             .saveUploadData(vspDetails, candidateData, byteArrayInputStream,
131             fileContentHandler, tree));
132
133     ETSIService etsiService = new ETSIServiceImpl();
134     ToscaServiceModel toscaServiceModel;
135     if (etsiService.isSol004WithToscaMetaDirectory(fileContentHandler)) {
136       if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(candidateData.getFileSuffix())) {
137         fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getOriginalFileName() +
138             EXT_SEPARATOR + candidateData.getOriginalFileSuffix(), candidateData.getOriginalFileContentData().array());
139       } else {
140         fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getFileName() +
141             EXT_SEPARATOR + candidateData.getFileSuffix(), candidateData.getContentData().array());
142       }
143       final ResourceTypeEnum resourceType = etsiService.getResourceType(fileContentHandler);
144       toscaServiceModel = instantiateToscaConverterFor(resourceType).convert(fileContentHandler);
145     } else {
146       toscaServiceModel = new ToscaConverterImpl().convert(fileContentHandler);
147     }
148     orchestrationUtil.saveServiceModel(vspDetails.getId(),
149             vspDetails.getVersion(), toscaServiceModel,
150         toscaServiceModel);
151     candidateService
152         .deleteOrchestrationTemplateCandidate(vspDetails.getId(), vspDetails.getVersion());
153   }
154
155   private AbstractToscaSolConverter instantiateToscaConverterFor(ResourceTypeEnum resourceType) {
156     if (resourceType == ResourceTypeEnum.PNF) {
157       return new ToscaSolModelDrivenConverterPnf();
158     }
159     // default is VF
160     return new ToscaSolConverterVnf();
161   }
162
163   private void addFiles(FileContentHandler fileContentHandler) {
164     for (Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
165       toscaTreeManager.addFile(fileEntry.getKey(), fileEntry.getValue());
166     }
167   }
168
169   private Map<String, List<ErrorMessage>> validateCsar(FileContentHandler fileContentHandler) {
170     Map<String, List<ErrorMessage>> errors = new HashMap<>();
171     addFiles(fileContentHandler);
172     toscaTreeManager.createTree();
173     toscaTreeManager.addErrors(errors);
174     //todo - add tosca validation here to the existing validation framework
175     return errors;
176   }
177
178   private boolean isValid(Map<String, List<ErrorMessage>> errors) {
179     return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors));
180   }
181 }