aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java
blob: e1807bafad4c49be215a9700a731b15a9261bc13 (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
 * Copyright © 2018 European Support Limited
 *
 * 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.
 */

package org.openecomp.sdc.healing.healers;

import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element;
import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo;
import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement;
import com.amdocs.zusammen.datatypes.Id;
import com.amdocs.zusammen.datatypes.SessionContext;
import com.amdocs.zusammen.datatypes.item.Action;
import com.amdocs.zusammen.datatypes.item.ElementContext;
import com.amdocs.zusammen.utils.fileutils.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.openecomp.core.utilities.file.FileContentHandler;
import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
import org.openecomp.core.zusammen.api.ZusammenAdaptor;
import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.errors.ErrorCode;
import org.openecomp.sdc.common.utils.CommonUtil;
import org.openecomp.sdc.datatypes.error.ErrorLevel;
import org.openecomp.sdc.datatypes.model.ElementType;
import org.openecomp.sdc.healing.interfaces.Healer;
import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory;
import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateEntityBuilder;
import org.openecomp.sdc.versioning.dao.types.Version;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Objects;

import static org.openecomp.core.zusammen.api.ZusammenUtil.*;

public class NetworkPackageHealer implements Healer {

  private static final byte[] EMPTY_DATA_BYTES = "{}".getBytes();
  private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR =
      "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidate";
  private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR =
      "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidateContent"
          + " under OrchestrationTemplateCandidate";

  private static final String MISSING_VSP_MODEL_ERROR =
      "Vsp with invalid structure: does not contain element VspModel";
  private static final String MISSING_ORCHESTRATION_TEMPLATE_ERROR =
      "Vsp with invalid structure: does not contain element OrchestrationTemplate"
          + " under VspModel element";
  private static final String MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR =
      "Vsp with invalid structure: does not contain element OrchestrationTemplateValidationData"
          + " under OrchestrationTemplate element";

  private final VendorSoftwareProductInfoDao vspInfoDao;
  private final ZusammenAdaptor zusammenAdaptor;
  private final CandidateService candidateService;

  public NetworkPackageHealer() {
    this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(),
        ZusammenAdaptorFactory.getInstance().createInterface(), CandidateServiceFactory
            .getInstance().createInterface());
  }

  public NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao,
                              ZusammenAdaptor zusammenAdaptor,
                              CandidateService candidateService) {
    this.vspInfoDao = vspInfoDao;
    this.zusammenAdaptor = zusammenAdaptor;
    this.candidateService = candidateService;
  }

  @Override
  public boolean isHealingNeeded(String itemId, Version version) {
    return OnboardingMethod.NetworkPackage.name()
        .equals(vspInfoDao.get(new VspDetails(itemId, version)).getOnboardingMethod()) &&
        isVspMissingAddedElements(itemId, version);
  }

  @Override
  public void heal(String itemId, Version version) throws Exception {
    SessionContext context = createSessionContext();
    ElementContext elementContext = new ElementContext(itemId, version.getId());

    Element candidateElement =
        getElement(context, elementContext, null, ElementType.OrchestrationTemplateCandidate,
            MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR);

    Collection<Element> candidateSubs =
        zusammenAdaptor.listElementData(context, elementContext, candidateElement.getElementId());

    Id candidateValidationElementId =
        creatIfAbsentCandidateValidationElementId(candidateSubs, context,
        elementContext, candidateElement);

    Element orchestrationTemplateElement = getOrchestrationTemplateElement(context, elementContext);

    Collection<Element> orchestrationTemplateSubs = zusammenAdaptor
        .listElementData(context, elementContext, orchestrationTemplateElement.getElementId());

    Id structureElementId = createIfAbsentStructureElementId(orchestrationTemplateSubs, context,
        elementContext, orchestrationTemplateElement);

    Element orchestrationTemplateValidationElement = getOrchestrationTemplateValidationElement
        (orchestrationTemplateSubs);

    OrchestrationTemplateEntity orchestrationTemplateEntity =
        getOrchestrationTemplateEntity(orchestrationTemplateElement,
            orchestrationTemplateValidationElement);

    if (StringUtils.isEmpty(orchestrationTemplateEntity.getFileSuffix())) {
      return;
    }

    Element candidateContentElement = getCandidateContentElement(candidateSubs);

    VspDetails vspDetails = vspInfoDao.get(new VspDetails(itemId, version));
    if (isEqual(orchestrationTemplateEntity,
        getCandidateData(candidateElement, candidateContentElement))) {

      if (isProcessedEntityValid(orchestrationTemplateEntity)) {
        emptyStructureElementAndSub(context, elementContext, candidateElement.getElementId(),
            ElementType.OrchestrationTemplateCandidate, candidateContentElement.getElementId(),
            ElementType.OrchestrationTemplateCandidateContent);

        populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(),
            structureElementId, vspDetails, context, elementContext);
      } else {
        emptyStructureElementAndSub(context, elementContext,
            orchestrationTemplateElement.getElementId(), ElementType.OrchestrationTemplate,
            orchestrationTemplateValidationElement.getElementId(),
            ElementType.OrchestrationTemplateValidationData);

        populateCandidateValidationData(context, elementContext, candidateValidationElementId,
            orchestrationTemplateEntity.getValidationData());
      }
    } else {
      populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(),
          structureElementId, vspDetails, context, elementContext);
    }
  }

  private boolean isVspMissingAddedElements(String vspId, Version version) {
    SessionContext context = createSessionContext();
    ElementContext elementContext = new ElementContext(vspId, version.getId());

    return zusammenAdaptor.listElementsByName(context, elementContext, null,
        ElementType.OrchestrationTemplateCandidate.name()).stream()
        .noneMatch(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name()
            .equals(candidateSub.getInfo().getName()));
  }

  private boolean isEqual(OrchestrationTemplateEntity orchestrationTemplateEntity,
                          OrchestrationTemplateCandidateData orchestrationTemplateCandidateData) {
    return orchestrationTemplateEntity.getFileName()
        .equals(orchestrationTemplateCandidateData.getFileName()) &&
        orchestrationTemplateEntity.getFileSuffix()
            .equals(orchestrationTemplateCandidateData.getFileSuffix());
  }

  private boolean isProcessedEntityValid(OrchestrationTemplateEntity orchestrationTemplateEntity) {
    return !orchestrationTemplateEntity.getValidationData().contains(ErrorLevel.ERROR.name());
  }

  private void populateCandidateValidationData(SessionContext context,
                                               ElementContext elementContext,
                                               Id candidateValidationElementId,
                                               String validationData) {
    ZusammenElement candidateValidationElement =
        buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData,
            Action.UPDATE);
    candidateValidationElement.setElementId(candidateValidationElementId);
    candidateValidationElement.setData(new ByteArrayInputStream(validationData.getBytes()));

    zusammenAdaptor.saveElement(context, elementContext, candidateValidationElement,
        "Healed Orchestration Template Candidate Validation data");
  }

  private void populateOrchestrationTemplateStructure(InputStream processedFile,
                                                      Id structureElementId, VspDetails vspDetails,
                                                      SessionContext context,
                                                      ElementContext elementContext)
      throws Exception {
    byte[] byteData = FileUtils.toByteArray(processedFile);
    FileContentHandler contentMap =
        CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteData);
    OrchestrationTemplateCandidateData orchestrationTemplateEntityData =
        new CandidateEntityBuilder(candidateService)
            .buildCandidateEntityFromZip(vspDetails, byteData, contentMap, null);
    String fileDataStructure = orchestrationTemplateEntityData.getFilesDataStructure();

    ZusammenElement orchestrationTemplateStructure =
        buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.UPDATE);
    orchestrationTemplateStructure.setElementId(structureElementId);
    orchestrationTemplateStructure.setData(new ByteArrayInputStream(fileDataStructure.getBytes()));

    zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateStructure,
        "Healed Orchestration Template Structure");
  }

  private Element getOrchestrationTemplateElement(SessionContext context,
                                                  ElementContext elementContext) {
    ElementInfo vspModelElement = zusammenAdaptor
        .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name())
        .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder()
            .withMessage(MISSING_VSP_MODEL_ERROR).build()));

    return getElement(context, elementContext, vspModelElement.getId(),
        ElementType.OrchestrationTemplate, MISSING_ORCHESTRATION_TEMPLATE_ERROR);
  }

  private Element getOrchestrationTemplateValidationElement(
      Collection<Element> orchestrationTemplateSubs) {
    return orchestrationTemplateSubs.stream()
        .filter(orchestrationTemplateSub -> ElementType.OrchestrationTemplateValidationData.name()
            .equals(orchestrationTemplateSub.getInfo().getName()))
        .findFirst()
        .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder()
            .withMessage(MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR).build()));

  }

  private Element getCandidateContentElement(Collection<Element> candidateSubs) {
    return candidateSubs.stream()
        .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateContent.name()
            .equals(candidateSub.getInfo().getName()))
        .findFirst()
        .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder()
            .withMessage(MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR).build()));
  }

  private Id createIfAbsentStructureElementId(Collection<Element> orchestrationTemplateSubs,
                                              SessionContext context, ElementContext elementContext,
                                              Element orchestrationTemplateElement) {
    return orchestrationTemplateSubs.stream()
        .filter(orchestrationTemplateSub -> ElementType.OrchestrationTemplateStructure.name()
            .equals(orchestrationTemplateSub.getInfo().getName()))
        .findFirst().map(Element::getElementId)
        .orElse(addStructureSubElement(context, elementContext,
            ElementType.OrchestrationTemplateStructure,
            orchestrationTemplateElement.getElementId()));
  }

  private Id creatIfAbsentCandidateValidationElementId(Collection<Element> candidateSubs,
                                                       SessionContext context, ElementContext
                                                 elementContext, Element candidateElement) {
    return candidateSubs.stream()
        .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name()
            .equals(candidateSub.getInfo().getName()))
        .findFirst().map(Element::getElementId)
        .orElse(addStructureSubElement(context, elementContext,
            ElementType.OrchestrationTemplateCandidateValidationData,
            candidateElement.getElementId()));
  }

  private Element getElement(SessionContext context, ElementContext elementContext,
                             Id parentElementId, ElementType elementType, String errorMessage) {
    return zusammenAdaptor
        .getElementByName(context, elementContext, parentElementId, elementType.name())
        .orElseThrow(() -> new CoreException(
            new ErrorCode.ErrorCodeBuilder().withMessage(errorMessage).build()));
  }

  private OrchestrationTemplateEntity getOrchestrationTemplateEntity(
      Element orchestrationTemplateElement, Element validationDataElement) {
    OrchestrationTemplateEntity orchestrationTemplateEntity = new OrchestrationTemplateEntity();

    if (isNotEmpty(orchestrationTemplateElement.getData())) {
      orchestrationTemplateEntity.setContentData(
          ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData())));
    }
    orchestrationTemplateEntity.setFileSuffix(
        validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal()));
    orchestrationTemplateEntity.setFileName(
        validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal()));
    if (isNotEmpty(validationDataElement.getData())) {
      orchestrationTemplateEntity
          .setValidationData(new String(FileUtils.toByteArray(validationDataElement.getData())));
    }
    return orchestrationTemplateEntity;
  }

  private OrchestrationTemplateCandidateData getCandidateData(Element candidateElement,
                                                              Element candidateContentElement) {
    OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData();
    candidateData
        .setFilesDataStructure(new String(FileUtils.toByteArray(candidateElement.getData())));
    candidateData
        .setContentData(ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.getData())));
    candidateData.setFileSuffix(
        candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal()));
    candidateData.setFileName(
        candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal()));
    return candidateData;
  }

  private Id addStructureSubElement(SessionContext context, ElementContext elementContext,
                                    ElementType elementType, Id parentElementId) {
    ZusammenElement newElement = buildStructuralElement(elementType, Action.CREATE);

    ZusammenElement parentElement = buildElement(parentElementId, Action.IGNORE);
    parentElement.addSubElement(newElement);

    return zusammenAdaptor.saveElement(context, elementContext, parentElement,
        String.format("Add element %s under element id %s", elementType.name(), parentElementId))
        .getSubElements().iterator().next().getElementId();
  }

  private void emptyStructureElementAndSub(SessionContext context, ElementContext elementContext,
                                           Id elementId, ElementType elementType, Id subElementId,
                                           ElementType subElementType) {
    ZusammenElement subElement = buildStructuralElement(subElementType, Action.UPDATE);
    subElement.setElementId(subElementId);
    subElement.setData(new ByteArrayInputStream(EMPTY_DATA_BYTES));

    ZusammenElement element = buildStructuralElement(elementType, Action.UPDATE);
    element.setElementId(elementId);
    element.setData(new ByteArrayInputStream(EMPTY_DATA_BYTES));
    element.addSubElement(subElement);

    zusammenAdaptor.saveElement(context, elementContext, element,
        String.format("Empty element %s and its sub element %s", elementType.name(),
            subElementType.name()));
  }

  public enum InfoPropertyName {
    FILE_SUFFIX("fileSuffix"),
    FILE_NAME("fileName");

    private String val;

    InfoPropertyName(String val) {
      this.val = val;
    }

    private String getVal() {
      return val;
    }
  }

  private boolean isNotEmpty(InputStream elementData) {
    byte[] byteElementData;
    if (Objects.isNull(elementData)) {
      return false;
    }
    try {
      byteElementData = IOUtils.toByteArray(elementData);
    } catch (IOException e) {
      return true;
    }
    return !ArrayUtils.isEmpty(byteElementData);
  }
}