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