summaryrefslogtreecommitdiffstats
path: root/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImpl.java
blob: 0f4d73f8c504294b7d3e4429911233c3bf8eceff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.vendorsoftwareproduct.impl;

import org.apache.commons.collections4.MapUtils;
import org.openecomp.core.enrichment.types.MonitoringUploadType;
import org.openecomp.core.utilities.CommonMethods;
import org.openecomp.core.utilities.file.FileContentHandler;
import org.openecomp.core.utilities.file.FileUtils;
import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
import org.openecomp.sdc.activityLog.ActivityLogManager;
import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.errors.Messages;
import org.openecomp.sdc.common.utils.CommonUtil;
import org.openecomp.sdc.common.utils.SdcCommon;
import org.openecomp.sdc.datatypes.error.ErrorLevel;
import org.openecomp.sdc.datatypes.error.ErrorMessage;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
import org.openecomp.sdc.logging.types.LoggerConstants;
import org.openecomp.sdc.logging.types.LoggerErrorCode;
import org.openecomp.sdc.logging.types.LoggerErrorDescription;
import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager;
import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao;
import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
import org.openecomp.sdc.vendorsoftwareproduct.errors.MonitoringUploadErrorBuilder;
import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringUploadStatus;
import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils;
import org.openecomp.sdc.versioning.dao.types.Version;
import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder;
import org.openecomp.sdcrests.activitylog.types.ActivityType;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager {
  private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
  private ActivityLogManager activityLogManager;
  private ComponentArtifactDao componentArtifactDao;
  private VendorSoftwareProductDao vendorSoftwareProductDao;
  private static final Logger logger =
      LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class);

  private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName());

  MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao,
                               ActivityLogManager activityLogManager) {
    this.componentArtifactDao = componentArtifactDao;

    this.activityLogManager = activityLogManager;
    componentArtifactDao.registerVersioning(
        VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
  }

  @Override
  public void delete(String vspId, Version version, String componentId,
                     MonitoringUploadType monitoringUploadType, String user) {
    mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);

    ComponentMonitoringUploadEntity componentMonitoringUploadEntity =
        setValuesForComponentArtifactEntityUpload(vspId, version, null, componentId, null,
            monitoringUploadType, null);
    Optional<ComponentMonitoringUploadEntity> retrieved = componentArtifactDao.getByType(
        componentMonitoringUploadEntity);

    if (!retrieved.isPresent()) {
      throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder(
          componentMonitoringUploadEntity.getEntityType(),
          monitoringUploadType.name(),
          VspDetails.ENTITY_TYPE,
          componentMonitoringUploadEntity.getFirstClassCitizenId(),
          version).build());
    }

    componentArtifactDao.delete(retrieved.get());

    mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
  }

  @Override
  public void upload(InputStream object, String filename, String vspId,
                     Version version, String componentId,
                     MonitoringUploadType type,
                     String user) {
    mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);

    if (object == null) {
      MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
          LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
          LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type
              .toString() + " zip file");
      throw new CoreException(new MonitoringUploadErrorBuilder(
          Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage()).build());
    } else {
      Map<String, List<ErrorMessage>> errors = new HashMap<>();
      try {
        byte[] uploadedFileData = FileUtils.toByteArray(object);
        final FileContentHandler upload =
            validateZip(vspId, version, uploadedFileData, errors);
        if (type.equals(MonitoringUploadType.VES_EVENTS)) {
          validateVesEventUpload(upload, errors, vspId, version);
        }
        if (MapUtils.isNotEmpty(errors)) {
          MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
              LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
              LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type
                  .toString() + " zip file");
          throw new CoreException(
              new MonitoringUploadErrorBuilder(
                  errors.values().iterator().next().get(0).getMessage())
                  .build());
        }

        createArtifactInDatabase(vspId, version, filename, componentId, type,
            uploadedFileData);

      } catch (Exception exception) {
        log.debug("", exception);
        MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
            LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
            LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type.toString() + "zip file");
        throw new CoreException(new MonitoringUploadErrorBuilder(exception.getMessage()).build());
      }
    }

    ActivityLogEntity activityLogEntity =
        new ActivityLogEntity(vspId, String.valueOf(version.getMajor() + 1),
            ActivityType.UPLOAD_MONITORING_FILE.toString(), user, true, "", "");
    activityLogManager.addActionLog(activityLogEntity, user);
    logger.audit("Uploaded Monitoring File for component id:" + componentId + " ,vspId:" + vspId);


    mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
  }

  private void validateVesEventUpload(FileContentHandler upload,
                                      Map<String, List<ErrorMessage>> errors, String vspId,
                                      Version version) {
    if (!CommonUtil.validateAllFilesYml(upload)) {
      ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors)
          .add(new ErrorMessage(ErrorLevel.ERROR,
              Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage()));
      MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
          LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(),
          LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VES_FILE);
      throw new CoreException(
          new MonitoringUploadErrorBuilder(
              Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage())
              .build());
    }
  }

  private void createArtifactInDatabase(String vspId, Version version, String filename,
                                        String componentId,
                                        MonitoringUploadType type,
                                        byte[] uploadedFileData) {
    String artifactId = CommonMethods.nextUuId();
    ComponentMonitoringUploadEntity componentMonitoringUploadEntity =
        setValuesForComponentArtifactEntityUpload(vspId, version, filename, componentId,
            artifactId, type, uploadedFileData);
    componentArtifactDao.create(componentMonitoringUploadEntity);
  }

  @Override
  public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId,
                                              String user) {
    mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);

    ComponentMonitoringUploadEntity current =
        new ComponentMonitoringUploadEntity(vspId, version, componentId, null);

    mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);

    return setMonitoringUploadStatusValues(current);
  }


  private MonitoringUploadStatus setMonitoringUploadStatusValues(
      ComponentMonitoringUploadEntity componentMonitoringUploadEntity) {
    MonitoringUploadStatus monitoringUploadStatus = new MonitoringUploadStatus();

    Collection<ComponentMonitoringUploadEntity> artifactNames =
        componentArtifactDao.list(componentMonitoringUploadEntity);
    Map<MonitoringUploadType, String> artifactTypeToFilename =
        VendorSoftwareProductUtils.mapArtifactsByType(artifactNames);

    if (MapUtils.isNotEmpty(artifactTypeToFilename)) {
      if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_TRAP)) {
        monitoringUploadStatus
            .setSnmpTrap(artifactTypeToFilename.get(MonitoringUploadType.SNMP_TRAP));
      }
      if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_POLL)) {
        monitoringUploadStatus
            .setSnmpPoll(artifactTypeToFilename.get(MonitoringUploadType.SNMP_POLL));
      }
      if (artifactTypeToFilename.containsKey(MonitoringUploadType.VES_EVENTS)) {
        monitoringUploadStatus
            .setVesEvent(artifactTypeToFilename.get(MonitoringUploadType.VES_EVENTS));
      }
    }

    return monitoringUploadStatus;
  }

  private ComponentMonitoringUploadEntity setValuesForComponentArtifactEntityUpload(
      String vspId, Version version, String filename, String componentId, String artifactId,
      MonitoringUploadType monitoringUploadType, byte[] uploadedFileData) {

    ComponentMonitoringUploadEntity
        entity = new ComponentMonitoringUploadEntity();

    entity.setVspId(vspId);
    entity.setVersion(version);
    entity.setComponentId(componentId);
    entity.setId(artifactId);
    entity.setType(monitoringUploadType);
    entity.setArtifactName(filename);

    if (Objects.nonNull(uploadedFileData)) {
      entity.setArtifact(ByteBuffer.wrap(uploadedFileData));
    }

    return entity;
  }

  private FileContentHandler validateZip(String vspId, Version version, byte[] uploadedFileData,
                                         Map<String, List<ErrorMessage>> errors) {
    FileContentHandler contentMap;
    try {
      contentMap = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData);
      VendorSoftwareProductUtils.validateContentZipData(contentMap, errors);
    } catch (IOException exception) {
      log.debug("", exception);
      MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
          LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(),
          LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid Monitoring zip file");
      throw new CoreException(
          new MonitoringUploadErrorBuilder(vspId, version,
              Messages.INVALID_ZIP_FILE.getErrorMessage())
              .build());
    }
    return contentMap;
  }
}