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 / MonitoringUploadsManagerImpl.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.MapUtils;
24 import org.openecomp.core.enrichment.types.MonitoringUploadType;
25 import org.openecomp.core.utilities.CommonMethods;
26 import org.openecomp.core.utilities.file.FileContentHandler;
27 import org.openecomp.core.utilities.file.FileUtils;
28 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
29 import org.openecomp.sdc.activityLog.ActivityLogManager;
30 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
31 import org.openecomp.sdc.common.errors.CoreException;
32 import org.openecomp.sdc.common.errors.Messages;
33 import org.openecomp.sdc.common.utils.CommonUtil;
34 import org.openecomp.sdc.common.utils.SdcCommon;
35 import org.openecomp.sdc.datatypes.error.ErrorLevel;
36 import org.openecomp.sdc.datatypes.error.ErrorMessage;
37 import org.openecomp.sdc.logging.api.Logger;
38 import org.openecomp.sdc.logging.api.LoggerFactory;
39 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
40 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
41 import org.openecomp.sdc.logging.types.LoggerConstants;
42 import org.openecomp.sdc.logging.types.LoggerErrorCode;
43 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
44 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
45 import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager;
46 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
49 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity;
50 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
51 import org.openecomp.sdc.vendorsoftwareproduct.errors.MonitoringUploadErrorBuilder;
52 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringUploadStatus;
53 import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils;
54 import org.openecomp.sdc.versioning.dao.types.Version;
55 import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder;
56 import org.openecomp.sdcrests.activitylog.types.ActivityType;
57
58 import java.io.IOException;
59 import java.io.InputStream;
60 import java.nio.ByteBuffer;
61 import java.util.Collection;
62 import java.util.HashMap;
63 import java.util.List;
64 import java.util.Map;
65 import java.util.Objects;
66 import java.util.Optional;
67
68 public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager {
69   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
70   private ActivityLogManager activityLogManager;
71   private ComponentArtifactDao componentArtifactDao;
72   private VendorSoftwareProductDao vendorSoftwareProductDao;
73   private static final Logger logger =
74       LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class);
75
76   MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao,
77                                ActivityLogManager activityLogManager) {
78     this.componentArtifactDao = componentArtifactDao;
79
80     this.activityLogManager = activityLogManager;
81     componentArtifactDao.registerVersioning(
82         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
83   }
84
85   @Override
86   public void delete(String vspId, Version version, String componentId,
87                      MonitoringUploadType monitoringUploadType, String user) {
88     mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);
89
90     ComponentMonitoringUploadEntity componentMonitoringUploadEntity =
91         setValuesForComponentArtifactEntityUpload(vspId, version, null, componentId, null,
92             monitoringUploadType, null);
93     Optional<ComponentMonitoringUploadEntity> retrieved = componentArtifactDao.getByType(
94         componentMonitoringUploadEntity);
95
96     if (!retrieved.isPresent()) {
97       throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder(
98           componentMonitoringUploadEntity.getEntityType(),
99           monitoringUploadType.name(),
100           VspDetails.ENTITY_TYPE,
101           componentMonitoringUploadEntity.getFirstClassCitizenId(),
102           version).build());
103     }
104
105     componentArtifactDao.delete(retrieved.get());
106
107     mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
108   }
109
110   @Override
111   public void upload(InputStream object, String filename, String vspId,
112                      Version version, String componentId,
113                      MonitoringUploadType type,
114                      String user) {
115     mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);
116
117     if (object == null) {
118       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
119           LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
120           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type
121               .toString() + " zip file");
122       throw new CoreException(new MonitoringUploadErrorBuilder(
123           Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage()).build());
124     } else {
125       Map<String, List<ErrorMessage>> errors = new HashMap<>();
126       try {
127         byte[] uploadedFileData = FileUtils.toByteArray(object);
128         final FileContentHandler upload =
129             validateZip(vspId, version, uploadedFileData, errors);
130         if (type.equals(MonitoringUploadType.VES_EVENTS)) {
131           validateVesEventUpload(upload, errors, vspId, version);
132         }
133         if (MapUtils.isNotEmpty(errors)) {
134           MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
135               LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
136               LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type
137                   .toString() + " zip file");
138           throw new CoreException(
139               new MonitoringUploadErrorBuilder(
140                   errors.values().iterator().next().get(0).getMessage())
141                   .build());
142         }
143
144         createArtifactInDatabase(vspId, version, filename, componentId, type,
145             uploadedFileData);
146
147       } catch (Exception exception) {
148         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
149             LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
150             LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type.toString() + "zip file");
151         throw new CoreException(new MonitoringUploadErrorBuilder(exception.getMessage()).build());
152       }
153     }
154
155     ActivityLogEntity activityLogEntity =
156         new ActivityLogEntity(vspId, String.valueOf(version.getMajor() + 1),
157             ActivityType.UPLOAD_MONITORING_FILE.toString(), user, true, "", "");
158     activityLogManager.addActionLog(activityLogEntity, user);
159     logger.audit("Uploaded Monitoring File for component id:" + componentId + " ,vspId:" + vspId);
160
161
162     mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
163   }
164
165   private void validateVesEventUpload(FileContentHandler upload,
166                                       Map<String, List<ErrorMessage>> errors, String vspId,
167                                       Version version) {
168     if (!CommonUtil.validateAllFilesYml(upload)) {
169       ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors)
170           .add(new ErrorMessage(ErrorLevel.ERROR,
171               Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage()));
172       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
173           LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(),
174           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VES_FILE);
175       throw new CoreException(
176           new MonitoringUploadErrorBuilder(
177               Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage())
178               .build());
179     }
180   }
181
182   private void createArtifactInDatabase(String vspId, Version version, String filename,
183                                         String componentId,
184                                         MonitoringUploadType type,
185                                         byte[] uploadedFileData) {
186     String artifactId = CommonMethods.nextUuId();
187     ComponentMonitoringUploadEntity componentMonitoringUploadEntity =
188         setValuesForComponentArtifactEntityUpload(vspId, version, filename, componentId,
189             artifactId, type, uploadedFileData);
190     componentArtifactDao.create(componentMonitoringUploadEntity);
191   }
192
193   @Override
194   public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId,
195                                               String user) {
196     mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);
197
198     ComponentMonitoringUploadEntity current =
199         new ComponentMonitoringUploadEntity(vspId, version, componentId, null);
200
201     mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
202
203     return setMonitoringUploadStatusValues(current);
204   }
205
206
207   private MonitoringUploadStatus setMonitoringUploadStatusValues(
208       ComponentMonitoringUploadEntity componentMonitoringUploadEntity) {
209     MonitoringUploadStatus monitoringUploadStatus = new MonitoringUploadStatus();
210
211     Collection<ComponentMonitoringUploadEntity> artifactNames =
212         componentArtifactDao.list(componentMonitoringUploadEntity);
213     Map<MonitoringUploadType, String> artifactTypeToFilename =
214         VendorSoftwareProductUtils.mapArtifactsByType(artifactNames);
215
216     if (MapUtils.isNotEmpty(artifactTypeToFilename)) {
217       if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_TRAP)) {
218         monitoringUploadStatus
219             .setSnmpTrap(artifactTypeToFilename.get(MonitoringUploadType.SNMP_TRAP));
220       }
221       if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_POLL)) {
222         monitoringUploadStatus
223             .setSnmpPoll(artifactTypeToFilename.get(MonitoringUploadType.SNMP_POLL));
224       }
225       if (artifactTypeToFilename.containsKey(MonitoringUploadType.VES_EVENTS)) {
226         monitoringUploadStatus
227             .setVesEvent(artifactTypeToFilename.get(MonitoringUploadType.VES_EVENTS));
228       }
229     }
230
231     return monitoringUploadStatus;
232   }
233
234   private ComponentMonitoringUploadEntity setValuesForComponentArtifactEntityUpload(
235       String vspId, Version version, String filename, String componentId, String artifactId,
236       MonitoringUploadType monitoringUploadType, byte[] uploadedFileData) {
237
238     ComponentMonitoringUploadEntity
239         entity = new ComponentMonitoringUploadEntity();
240
241     entity.setVspId(vspId);
242     entity.setVersion(version);
243     entity.setComponentId(componentId);
244     entity.setId(artifactId);
245     entity.setType(monitoringUploadType);
246     entity.setArtifactName(filename);
247
248     if (Objects.nonNull(uploadedFileData)) {
249       entity.setArtifact(ByteBuffer.wrap(uploadedFileData));
250     }
251
252     return entity;
253   }
254
255   private FileContentHandler validateZip(String vspId, Version version, byte[] uploadedFileData,
256                                          Map<String, List<ErrorMessage>> errors) {
257     FileContentHandler contentMap;
258     try {
259       contentMap = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData);
260       VendorSoftwareProductUtils.validateContentZipData(contentMap, errors);
261     } catch (IOException exception) {
262       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
263           LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(),
264           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid Monitoring zip file");
265       throw new CoreException(
266           new MonitoringUploadErrorBuilder(vspId, version,
267               Messages.INVALID_ZIP_FILE.getErrorMessage())
268               .build());
269     }
270     return contentMap;
271   }
272 }