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