aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java
blob: 385a0fb0f5b2b93d292976eee029877abddf4c87 (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
/*-
 * ============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.translator.services.heattotosca.impl.resourcetranslation;

import org.apache.commons.collections4.CollectionUtils;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.datatypes.error.ErrorLevel;
import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
import org.openecomp.sdc.heat.datatypes.model.Resource;
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.tosca.datatypes.ToscaCapabilityType;
import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType;
import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements;
import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment;
import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
import org.openecomp.sdc.tosca.services.DataModelUtil;
import org.openecomp.sdc.tosca.services.ToscaConstants;
import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext;
import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo;
import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil;
import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType;
import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil;
import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory;
import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public abstract class ResourceTranslationBase {

  protected static Logger logger = (Logger) LoggerFactory.getLogger(ResourceTranslationBase.class);
  protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();

  protected abstract void translate(TranslateTo translateTo);

  /**
   * Translate resource.
   *
   * @param heatFileName              the heat file name
   * @param serviceTemplate           the service template
   * @param heatOrchestrationTemplate the heat orchestration template
   * @param resource                  the resource
   * @param resourceId                the resource id
   * @param context                   the context
   * @return the translated id if this resource is supported, or empty value if not supported
   */
  public Optional<String> translateResource(String heatFileName, ServiceTemplate serviceTemplate,
                                            HeatOrchestrationTemplate heatOrchestrationTemplate,
                                            Resource resource, String resourceId,
                                            TranslationContext context) {

    mdcDataDebugMessage.debugEntryMessage("file, resource", heatFileName, resourceId);
    Optional<String> translatedId =
        getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context);
    context.getTranslatedResources().putIfAbsent(heatFileName, new HashSet<>());
    if (context.getTranslatedResources().get(heatFileName).contains(resourceId)) {
      return translatedId;
    }
    if (!translatedId.isPresent()) {
      return Optional.empty();
    }
    logger.debug("Translate- file:" + heatFileName + " resource Id:" + resourceId
        + " translated resource id:" + translatedId.get());
    TranslateTo translateTo = new TranslateTo(heatFileName, serviceTemplate,
        heatOrchestrationTemplate, resource, resourceId, translatedId.get(), context);
    translate(translateTo);
    context.getTranslatedResources().get(heatFileName).add(resourceId);

    if (DataModelUtil.isNodeTemplate(translatedId.get(), serviceTemplate)) {
      if (!context.getHeatStackGroupMembers().containsKey(heatFileName)) {
        context.getHeatStackGroupMembers().put(heatFileName, new HashSet<>());
      }
      context.getHeatStackGroupMembers().get(heatFileName).add(translatedId.get());
      updateResourceDependency(translateTo);
    }

    mdcDataDebugMessage.debugExitMessage("file, resource", heatFileName, resourceId);
    return translatedId;
  }

  /**
   * Gets resource translated id.
   *
   * @param heatFileName              the heat file name
   * @param heatOrchestrationTemplate the heat orchestration template
   * @param resourceId                the resource id
   * @param context                   the context
   * @return the resource translated id
   */
  public static Optional<String> getResourceTranslatedId(String heatFileName,
                                                         HeatOrchestrationTemplate
                                                             heatOrchestrationTemplate,
                                                         String resourceId,
                                                         TranslationContext context) {


    mdcDataDebugMessage.debugEntryMessage(null, null);

    if (!context.getTranslatedIds().containsKey(heatFileName)) {
      context.getTranslatedIds().put(heatFileName, new HashMap<>());
    }

    Map<String, String> translatedIdsPerFile = context.getTranslatedIds().get(heatFileName);
    String translatedId = translatedIdsPerFile.get(resourceId);
    if (translatedId != null) {
      return Optional.of(translatedId);
    }

    Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
    if (resource == null) {
      MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
          LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(),
          LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT);
      throw new CoreException(
          new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
    }
    TranslateTo translateTo =
        generateTranslationTo(heatFileName, null, heatOrchestrationTemplate, resource, resourceId,
            null, context);
    translatedId =
        ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo);
    if (translatedId != null) {
      context.getTranslatedIds().get(heatFileName).put(resourceId, translatedId);
    }

    mdcDataDebugMessage.debugExitMessage(null, null);
    return Optional.ofNullable(translatedId);
  }


  /**
   * Gets resource translated element template.
   *
   * @param heatFileName              the heat file name
   * @param heatOrchestrationTemplate the heat orchestration template
   * @param resourceId                the resource id
   * @param context                   the context
   * @return the resource translated element template
   */
  public static Optional<ToscaTopologyTemplateElements> getResourceTranslatedElementTemplate(
      String heatFileName,
      HeatOrchestrationTemplate heatOrchestrationTemplate,
      String resourceId, TranslationContext context) {

    mdcDataDebugMessage.debugEntryMessage(null, null);

    Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
    if (resource == null) {
      MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
          LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(),
          LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT);
      throw new CoreException(
          new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
    }
    TranslateTo translateTo =
        generateTranslationTo(heatFileName, null, heatOrchestrationTemplate, resource, resourceId,
            null, context);

    Optional<ToscaTopologyTemplateElements> translatedElementTemplate =
        ResourceTranslationFactory.getInstance(resource)
            .getTranslatedToscaTopologyElement(translateTo);

    mdcDataDebugMessage.debugExitMessage(null, null);
    return translatedElementTemplate;
  }

  protected String generateTranslatedId(TranslateTo translateTo) {
    if (isEssentialRequirementsValid(translateTo)) {
      return translateTo.getResourceId();
    } else {
      return null;
    }

  }

  protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(
      TranslateTo translateTo) {
    if (isEssentialRequirementsValid(translateTo)) {
      return Optional.of(ToscaTopologyTemplateElements.NODE_TEMPLATE);
    } else {
      return Optional.empty();
    }
  }

  protected boolean isEssentialRequirementsValid(TranslateTo translateTo) {
    return true;
  }

  private static TranslateTo generateTranslationTo(String heatFileName,
                                                   ServiceTemplate serviceTemplate,
                                                   HeatOrchestrationTemplate
                                                       heatOrchestrationTemplate,
                                                   Resource resource, String resourceId,
                                                   String translatedId,
                                                   TranslationContext context) {
    TranslateTo to = new TranslateTo();
    to.setHeatFileName(heatFileName);
    to.setServiceTemplate(serviceTemplate);
    to.setHeatOrchestrationTemplate(heatOrchestrationTemplate);
    to.setResource(resource);
    to.setResourceId(resourceId);
    to.setTranslatedId(translatedId);
    to.setContext(context);
    return to;
  }

  private void updateResourceDependency(TranslateTo translateTo) {

    String heatFileName = translateTo.getHeatFileName();
    mdcDataDebugMessage.debugEntryMessage("file", heatFileName);

    Resource resource = translateTo.getResource();
    HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo
        .getHeatOrchestrationTemplate();
    String translatedId = translateTo.getTranslatedId();
    ServiceTemplate serviceTemplate = translateTo.getServiceTemplate();
    TranslationContext context = translateTo.getContext();
    if (resource.getDepends_on() == null) {
      return;
    }

    if (resource.getDepends_on() instanceof List) {
      List<String> dependsOnList = (List<String>) resource.getDepends_on();
      for (String dependsOnResourceId : dependsOnList) {
        addDependOnRequirement(dependsOnResourceId, translateTo);
      }
    } else {
      String dependsOnResourceId = (String) resource.getDepends_on();
      addDependOnRequirement(dependsOnResourceId, translateTo);
    }

    mdcDataDebugMessage.debugExitMessage("file", heatFileName);
  }

  private void addDependOnRequirement(String dependsOnResourceId, TranslateTo translateTo) {

    mdcDataDebugMessage.debugEntryMessage(null, null);
    String nodeTemplateId = translateTo.getTranslatedId();
    ServiceTemplate serviceTemplate = translateTo.getServiceTemplate();
    String heatFileName = translateTo.getHeatFileName();
    HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo
        .getHeatOrchestrationTemplate();
    TranslationContext context = translateTo.getContext();
    RequirementAssignment requirementAssignment = new RequirementAssignment();
    Optional<String> resourceTranslatedId =
        getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId,
            context);

    Optional<ToscaTopologyTemplateElements> resourceTranslatedElementTemplate =
        getResourceTranslatedElementTemplate(heatFileName, heatOrchestrationTemplate,
            dependsOnResourceId, context);

    if (resourceTranslatedId.isPresent()
        && (resourceTranslatedElementTemplate.isPresent() && resourceTranslatedElementTemplate
        .get() == ToscaTopologyTemplateElements.NODE_TEMPLATE)) {
      Resource sourceResource = translateTo.getResource();
      Resource targetResource = HeatToToscaUtil
          .getResource(heatOrchestrationTemplate, dependsOnResourceId,
              translateTo.getHeatFileName());
      if (HeatToToscaUtil
          .isValidDependsOnCandidate(heatOrchestrationTemplate, sourceResource, targetResource,
              ConsolidationEntityType.OTHER, translateTo.getContext())) {
        requirementAssignment.setNode(resourceTranslatedId.get());
        requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NODE);
        requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_DEPENDS_ON);
        DataModelUtil.addRequirementAssignment(
            serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId),
            ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment);
        Resource dependsOnResource = targetResource;
        ConsolidationDataUtil
            .updateNodesConnectedData(translateTo, dependsOnResourceId, dependsOnResource,
                sourceResource, nodeTemplateId, ToscaConstants.DEPENDS_ON_REQUIREMENT_ID,
                requirementAssignment);
      }
    }
    mdcDataDebugMessage.debugExitMessage(null, null);
  }

  Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId(
      String heatFileName,
      HeatOrchestrationTemplate heatOrchestrationTemplate,
      String translatedResourceId,
      TranslateTo translateTo,
      String heatResourceType) {
    mdcDataDebugMessage.debugEntryMessage(null, null);
    List<Map.Entry<String, Resource>> list = heatOrchestrationTemplate.getResources().entrySet()
        .stream()
        .filter(entry -> getPredicatesForTranslatedIdToResourceId(heatFileName,
            heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(),
            heatResourceType)
            .stream()
            .allMatch(p -> p.test(entry)))
        .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(list)) {
      mdcDataDebugMessage.debugExitMessage(null, null);
      return Optional.empty();
    } else {
      mdcDataDebugMessage.debugExitMessage(null, null);
      return Optional.of(list);
    }
  }

  private List<Predicate<Map.Entry<String, Resource>>> getPredicatesForTranslatedIdToResourceId(
      String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate,
      String translatedResourceId, TranslationContext context, String heatResourceType) {
    List<Predicate<Map.Entry<String, Resource>>> list = new ArrayList<>();
    list.add(entry ->
        entry.getValue().getType().equals(heatResourceType));
    list.add(entry -> {
      Optional<String> resourceTranslatedId =
          getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context);
      return resourceTranslatedId.isPresent()
          && resourceTranslatedId.get().equals(translatedResourceId);
    });
    return list;
  }

  boolean isResourceTypeSupported(Resource resource, List<String> supporteTypes) {
    return Objects.nonNull(resource) && supporteTypes.contains(resource.getType());
  }

}