f155e45c061e96cd6f225024b9916749bdc960f9
[sdc.git] /
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 org.apache.commons.collections4.CollectionUtils;
20 import org.apache.commons.collections4.MapUtils;
21 import org.openecomp.core.translator.datatypes.TranslatorOutput;
22 import org.openecomp.core.utilities.file.FileContentHandler;
23 import org.openecomp.core.utilities.json.JsonUtil;
24 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
25 import org.openecomp.core.validation.util.MessageContainerUtil;
26 import org.openecomp.sdc.common.errors.Messages;
27 import org.openecomp.sdc.common.utils.SdcCommon;
28 import org.openecomp.sdc.datatypes.error.ErrorLevel;
29 import org.openecomp.sdc.datatypes.error.ErrorMessage;
30 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
31 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
32 import org.openecomp.sdc.logging.api.Logger;
33 import org.openecomp.sdc.logging.api.LoggerFactory;
34 import org.openecomp.sdc.logging.messages.AuditMessages;
35 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
36 import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil;
37 import org.openecomp.sdc.validation.util.ValidationManagerUtil;
38 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity;
39 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity;
40 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
41 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity;
42 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
43 import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory;
44 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil;
45 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
46 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
47 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
48 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
49 import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils;
50 import org.openecomp.sdc.versioning.dao.types.Version;
51
52 import java.io.ByteArrayInputStream;
53 import java.util.Collection;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Map;
57 import java.util.Optional;
58
59 import static org.openecomp.sdc.logging.messages.AuditMessages.HEAT_VALIDATION_ERROR;
60
61 public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemplateProcessHandler {
62   private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessZipHandler.class);
63   private final CandidateService candidateService =
64       CandidateServiceFactory.getInstance().createInterface();
65
66   @Override
67   public OrchestrationTemplateActionResponse process(VspDetails vspDetails,
68                                                      OrchestrationTemplateCandidateData candidateData) {
69     String vspId = vspDetails.getId();
70     Version version = vspDetails.getVersion();
71     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_VALIDATION_STARTED + vspId);
72     OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
73     UploadFileResponse uploadFileResponse = new UploadFileResponse();
74     Optional<FileContentHandler> fileContent = OrchestrationUtil
75         .getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse,
76             candidateData.getContentData().array());
77     if (!fileContent.isPresent()) {
78       response.addStructureErrors(uploadFileResponse.getErrors());
79       response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList, vspId,
80           HEAT_VALIDATION_ERROR));
81       return response;
82     }
83
84     Map<String, List<ErrorMessage>> uploadErrors = uploadFileResponse.getErrors();
85     FileContentHandler fileContentMap = fileContent.get();
86     FilesDataStructure structure =
87         JsonUtil.json2Object(candidateData.getFilesDataStructure(), FilesDataStructure.class);
88
89     if (CollectionUtils.isNotEmpty(structure.getUnassigned())) {
90       response.addErrorMessageToMap(SdcCommon.UPLOAD_FILE,
91           Messages.FOUND_UNASSIGNED_FILES.getErrorMessage(), ErrorLevel.ERROR);
92       response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList, vspId,
93           HEAT_VALIDATION_ERROR));
94       return response;
95     }
96
97
98     String manifest = candidateService.createManifest(vspDetails, structure);
99     fileContentMap.addFile(SdcCommon.MANIFEST_NAME, manifest.getBytes());
100
101     Optional<ByteArrayInputStream> zipByteArrayInputStream = candidateService
102         .fetchZipFileByteArrayInputStream(
103             vspId, candidateData, manifest, OnboardingTypesEnum.ZIP, uploadErrors);
104     if (!zipByteArrayInputStream.isPresent()) {
105       response.getErrors().values()
106           .forEach(errorList -> printAuditForErrors(errorList, vspId, HEAT_VALIDATION_ERROR));
107       return response;
108     }
109
110     HeatStructureTree tree = createAndValidateHeatTree(response, fileContentMap);
111     Map<String, List<ErrorMessage>> errors = getErrors(response);
112     if (MapUtils.isNotEmpty(errors)) {
113       response.addStructureErrors(errors);
114       candidateService.updateValidationData(vspId, version, new ValidationStructureList(tree));
115       return response;
116     }
117     Map<String, String> componentsQuestionnaire = new HashMap<>();
118     Map<String, Map<String, String>> componentNicsQuestionnaire = new HashMap<>();
119     Map<String, Collection<ComponentMonitoringUploadEntity>> componentMibList = new HashMap<>();
120     Map<String, Collection<ProcessEntity>> processes = new HashMap<>();
121     Map<String, ProcessEntity> processArtifact = new HashMap<>();
122
123     OrchestrationUtil orchestrationUtil = new OrchestrationUtil();
124     Map<String, String> vspComponentIdNameInfoBeforeProcess =
125         orchestrationUtil.getVspComponentIdNameInfo(vspId, version);
126     Collection<ComponentDependencyModelEntity> componentDependenciesBeforeDelete =
127         orchestrationUtil.getComponentDependenciesBeforeDelete(vspId, version);
128     orchestrationUtil
129         .backupComponentsQuestionnaireBeforeDelete(vspId, version, componentsQuestionnaire,
130             componentNicsQuestionnaire, componentMibList, processes, processArtifact);
131
132     orchestrationUtil.deleteUploadDataAndContent(vspId, version);
133     orchestrationUtil
134         .saveUploadData(vspDetails, candidateData, zipByteArrayInputStream.get(), fileContentMap,
135             tree);
136
137     response.getErrors().values().forEach(errorList -> printAuditForErrors(errorList, vspId,
138         HEAT_VALIDATION_ERROR));
139     if (MapUtils
140         .isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, response.getErrors()))) {
141       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_VALIDATION_COMPLETED + vspId);
142     }
143
144     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_TRANSLATION_STARTED + vspId);
145
146     TranslatorOutput translatorOutput =
147         HeatToToscaUtil.loadAndTranslateTemplateData(fileContentMap);
148
149     ToscaServiceModel toscaServiceModel = translatorOutput.getToscaServiceModel();
150     orchestrationUtil
151         .saveServiceModel(vspId, version, translatorOutput.getNonUnifiedToscaServiceModel(),
152             toscaServiceModel);
153     orchestrationUtil.retainComponentQuestionnaireData(vspId, version, componentsQuestionnaire,
154         componentNicsQuestionnaire, componentMibList, processes, processArtifact);
155     orchestrationUtil.updateVspComponentDependencies(vspId, version,
156         vspComponentIdNameInfoBeforeProcess, componentDependenciesBeforeDelete);
157
158     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.HEAT_TRANSLATION_COMPLETED + vspId);
159     uploadFileResponse.addStructureErrors(uploadErrors);
160     candidateService.deleteOrchestrationTemplateCandidate(vspId, version);
161     return response;
162   }
163
164   private Map<String, List<ErrorMessage>> getErrors(OrchestrationTemplateActionResponse
165                                                         orchestrationTemplateActionResponse) {
166     Map<String, List<ErrorMessage>> errors =
167         MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR,
168             orchestrationTemplateActionResponse.getErrors());
169     return MapUtils.isEmpty(errors) ? null : orchestrationTemplateActionResponse.getErrors();
170   }
171
172   private HeatStructureTree createAndValidateHeatTree(OrchestrationTemplateActionResponse response,
173                                                       FileContentHandler fileContentMap) {
174     VendorSoftwareProductUtils.addFileNamesToUploadFileResponse(fileContentMap, response);
175     Map<String, List<ErrorMessage>> validationErrors =
176         ValidationManagerUtil.initValidationManager(fileContentMap).validate();
177     response.getErrors().putAll(validationErrors);
178
179     return OrchestrationUtil.createHeatTree(fileContentMap, validationErrors);
180   }
181
182   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
183
184     errorList.forEach(errorMessage -> {
185       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
186         LOGGER.audit(
187             AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId));
188       }
189     });
190   }
191 }