Create new VSP, onboard from TOSCA file - UI
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / main / java / org / openecomp / sdc / vendorsoftwareproduct / impl / OrchestrationTemplateCandidateManagerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.vendorsoftwareproduct.impl;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.lang3.tuple.ImmutablePair;
25 import org.apache.commons.lang3.tuple.Pair;
26 import org.openecomp.core.model.dao.ServiceModelDao;
27 import org.openecomp.core.model.types.ServiceElement;
28 import org.openecomp.core.utilities.json.JsonUtil;
29 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
30 import org.openecomp.sdc.activityLog.ActivityLogManager;
31 import org.openecomp.sdc.common.errors.CoreException;
32 import org.openecomp.sdc.common.errors.Messages;
33 import org.openecomp.sdc.common.utils.SdcCommon;
34 import org.openecomp.sdc.datatypes.error.ErrorLevel;
35 import org.openecomp.sdc.datatypes.error.ErrorMessage;
36 import org.openecomp.sdc.healing.api.HealingManager;
37 import org.openecomp.sdc.healing.types.HealCode;
38 import org.openecomp.sdc.logging.api.Logger;
39 import org.openecomp.sdc.logging.api.LoggerFactory;
40 import org.openecomp.sdc.logging.api.annotations.Metrics;
41 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
42 import org.openecomp.sdc.logging.messages.AuditMessages;
43 import org.openecomp.sdc.logging.types.LoggerServiceName;
44 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
45 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
46 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao;
49 import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao;
50 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao;
51 import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao;
52 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
53 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
54 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
55 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
56 import org.openecomp.sdc.vendorsoftwareproduct.errors.OrchestrationTemplateNotFoundErrorBuilder;
57 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationTemplateFileHandler;
58 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUploadFactory;
59 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationProcessFactory;
60 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationTemplateProcessHandler;
61 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor;
62 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager;
63 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
64 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
65 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
66 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
67 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
68 import org.openecomp.sdc.versioning.dao.types.Version;
69
70 import java.io.IOException;
71 import java.io.InputStream;
72 import java.util.HashMap;
73 import java.util.List;
74 import java.util.Map;
75 import java.util.Optional;
76
77 public class OrchestrationTemplateCandidateManagerImpl
78     implements OrchestrationTemplateCandidateManager {
79   private static final Logger logger =
80       LoggerFactory.getLogger(OrchestrationTemplateCandidateManagerImpl.class);
81   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
82   private VendorSoftwareProductDao vendorSoftwareProductDao;
83   private VendorSoftwareProductInfoDao vspInfoDao;
84   private OrchestrationTemplateDao orchestrationTemplateDataDao;
85   private CandidateService candidateService;
86   private HealingManager healingManager;
87   private CompositionDataExtractor compositionDataExtractor;
88   private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao;
89   private CompositionEntityDataManager compositionEntityDataManager;
90   private NicDao nicDao;
91   private ComponentDao componentDao;
92   private ComponentArtifactDao componentArtifactDao;
93   private ActivityLogManager activityLogManager;
94   private ProcessDao processDao;
95
96   /**
97    * Instantiates a new Orchestration template candidate manager.
98    *
99    * @param vendorSoftwareProductDao     the vendor software product dao
100    * @param vspInfoDao                   the vsp info dao
101    * @param orchestrationTemplateDataDao the orchestration template data dao
102    * @param candidateService             the candidate service
103    * @param healingManager               the healing manager
104    * @param compositionDataExtractor     the composition data extractor
105    * @param serviceModelDao              the service model dao
106    * @param compositionEntityDataManager the composition entity data manager
107    * @param nicDao                       the nic dao
108    * @param componentDao                 the component dao
109    * @param componentArtifactDao                       the mib dao
110    * @param processDao                   the process dao
111    * @param activityLogManager           the activity log manager
112    */
113   public OrchestrationTemplateCandidateManagerImpl(
114       VendorSoftwareProductDao vendorSoftwareProductDao, VendorSoftwareProductInfoDao
115       vspInfoDao,
116       OrchestrationTemplateDao orchestrationTemplateDataDao,
117       CandidateService candidateService, HealingManager healingManager,
118       CompositionDataExtractor compositionDataExtractor,
119       ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao,
120       CompositionEntityDataManager compositionEntityDataManager,
121       NicDao nicDao,
122       ComponentDao componentDao,
123       ComponentArtifactDao componentArtifactDao,
124       ProcessDao processDao,
125       ActivityLogManager activityLogManager) {
126     this.vendorSoftwareProductDao = vendorSoftwareProductDao;
127     this.vspInfoDao = vspInfoDao;
128     this.orchestrationTemplateDataDao = orchestrationTemplateDataDao;
129     this.candidateService = candidateService;
130     this.healingManager = healingManager;
131     this.compositionDataExtractor = compositionDataExtractor;
132     this.serviceModelDao = serviceModelDao;
133     this.compositionEntityDataManager = compositionEntityDataManager;
134     this.nicDao = nicDao;
135     this.componentDao = componentDao;
136     this.componentArtifactDao = componentArtifactDao;
137     this.processDao = processDao;
138     this.activityLogManager = activityLogManager;
139   }
140
141   @Override
142   @Metrics
143   public UploadFileResponse upload(String vspId, Version version, InputStream fileToUpload,
144                                    String user, String filePrefix,
145                                    String networkPackageName) {
146     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
147     OrchestrationTemplateFileHandler orchestrationTemplateFileHandler =
148             OrchestrationUploadFactory.createOrchestrationTemplateFileHandler(filePrefix);
149     VspDetails vspDetails = getVspDetails(vspId, version);
150     UploadFileResponse uploadResponse = orchestrationTemplateFileHandler
151         .upload(vspId, version, fileToUpload, user, candidateService,
152             vspDetails);
153     vspDetails.setOnboardingOrigin(filePrefix);
154     vspDetails.setNetworkPackageName(networkPackageName);
155     vspInfoDao.update(vspDetails);
156
157     uploadResponse.setNetworkPackageName(networkPackageName);
158     return uploadResponse;
159   }
160
161
162
163   @Override
164   public OrchestrationTemplateActionResponse process(String vspId,
165                                                      Version version, String user) {
166     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
167     OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
168
169     Optional<OrchestrationTemplateCandidateData> candidate =
170         fetchCandidateDataEntity(vspId, version);
171     if (!candidate.isPresent()) {
172       throw new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build());
173     }
174
175     VspDetails vspDetails =
176         getVspDetails(vspId, version);
177     Optional<OrchestrationTemplateProcessHandler> processInstance =
178         OrchestrationProcessFactory.getInstance(vspDetails.getOnboardingOrigin());
179
180     if(processInstance.isPresent()){
181       response = processInstance.get().process(vspDetails, candidate.get(), user);
182     }
183
184     return response;
185   }
186
187   @Override
188   public Optional<FilesDataStructure> getFilesDataStructure(
189       String vspId, Version version, String user) {
190     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
191
192     Optional<FilesDataStructure> candidateFileDataStructure =
193         candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version);
194     if (candidateFileDataStructure.isPresent()) {
195       return candidateFileDataStructure;
196     } else {
197       Map<String, Object> healingParams = getHealingParamsAsMap(vspId, version, user);
198
199       mdcDataDebugMessage
200           .debugExitMessage("VSP id", vspId);
201       return (Optional<FilesDataStructure>) healingManager
202           .heal(HealCode.FILE_DATA_STRUCTURE_HEALER, healingParams);
203     }
204   }
205
206   @Override
207
208   public ValidationResponse updateFilesDataStructure(String vspId,
209                                                      Version version, String user,
210                                                      FilesDataStructure fileDataStructure) {
211     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
212
213     ValidationResponse response = new ValidationResponse();
214     Optional<List<ErrorMessage>> validateErrors =
215         candidateService.validateFileDataStructure(fileDataStructure);
216     if (validateErrors.isPresent()) {
217       List<ErrorMessage> errorMessages = validateErrors.get();
218       if (CollectionUtils.isNotEmpty(errorMessages)) {
219         Map<String, List<ErrorMessage>> errorsMap = new HashMap<>();
220         errorsMap.put(SdcCommon.UPLOAD_FILE, errorMessages);
221         response.setUploadDataErrors(errorsMap, LoggerServiceName.Update_Manifest,
222             LoggerTragetServiceName.VALIDATE_FILE_DATA_STRUCTURE);
223
224         mdcDataDebugMessage
225             .debugExitMessage("VSP id", vspId);
226         return response;
227       }
228     }
229     candidateService.updateOrchestrationTemplateCandidateFileDataStructure(vspId, version,
230         fileDataStructure);
231
232     mdcDataDebugMessage
233         .debugExitMessage("VSP id", vspId);
234     return response;
235   }
236
237   @Override
238
239   public Optional<Pair<String, byte[]>> get(String vspId, Version version, String user)
240       throws IOException {
241     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
242
243     VspDetails vspDetails =
244         getVspDetails(vspId, version);
245
246     Optional<OrchestrationTemplateCandidateData> candidateDataEntity =
247         fetchCandidateDataEntity(vspId, version);
248
249     if (!candidateDataEntity.isPresent()) {
250       ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
251           Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage());
252       logger.error(errorMessage.getMessage());
253
254       mdcDataDebugMessage
255           .debugExitMessage("VSP id", vspId);
256       return Optional.empty();
257     }
258     OnboardingTypesEnum type =
259         OnboardingTypesEnum.getOnboardingTypesEnum(vspDetails.getOnboardingOrigin());
260
261     if(vspDetails.getOnboardingOrigin().equals(OnboardingTypesEnum.ZIP.toString())) {
262       FilesDataStructure structure = JsonUtil
263           .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class);
264       String manifest = candidateService.createManifest(vspDetails, structure);
265
266       mdcDataDebugMessage
267           .debugExitMessage("VSP id", vspId);
268       return Optional.ofNullable(
269           new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(),candidateService
270               .replaceManifestInZip(candidateDataEntity.get().getContentData(),
271               manifest, vspId, type)));
272     }
273
274     return Optional.ofNullable(
275         new ImmutablePair<>(vspDetails.getOnboardingOrigin(),candidateDataEntity.get()
276             .getContentData().array()));
277   }
278
279   private Optional<OrchestrationTemplateCandidateData> fetchCandidateDataEntity(
280       String vspId, Version version) {
281     return Optional
282         .ofNullable(candidateService.getOrchestrationTemplateCandidate(vspId, version));
283   }
284
285
286   // todo *************************** move to reusable place! *************************
287
288   private Map<String, Object> getHealingParamsAsMap(String vspId, Version version, String user) {
289     Map<String, Object> healingParams = new HashMap<>();
290
291     healingParams.put(SdcCommon.VSP_ID, vspId);
292     healingParams.put(SdcCommon.VERSION, version);
293     healingParams.put(SdcCommon.USER, user);
294
295     return healingParams;
296   }
297
298   private VspDetails getVspDetails(String vspId, Version version) {
299     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
300     vspDetails.setValidationData(orchestrationTemplateDataDao.getValidationData(vspId, version));
301     return vspDetails;
302   }
303
304   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
305
306     errorList.forEach(errorMessage -> {
307       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
308         logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(),
309             vspId));
310       }
311     });
312   }
313
314 }