aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java
blob: a11bff4b6a74c2dde31102761decbf1231059cc8 (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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*-
 * ============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.tosca.services.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.openecomp.core.utilities.CommonMethods;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType;
import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
import org.openecomp.sdc.tosca.datatypes.model.CapabilityType;
import org.openecomp.sdc.tosca.datatypes.model.Import;
import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate;
import org.openecomp.sdc.tosca.datatypes.model.NodeType;
import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment;
import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
import org.openecomp.sdc.tosca.errors.ToscaInvalidEntryNotFoundErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstitutionServiceTemplateErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaNodeTypeNotFoundErrorBuilder;
import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
import org.openecomp.sdc.tosca.services.ToscaConstants;
import org.openecomp.sdc.tosca.services.yamlutil.ToscaExtensionYamlUtil;

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.Set;

public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService {
  /*
  node template with type equal to node type or derived from node type.
   */
  @Override
  public Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate,
                                                          String nodeType,
                                                          ToscaServiceModel toscaServiceModel) {
    Map<String, NodeTemplate> nodeTemplates = new HashMap<>();

    if (Objects.nonNull(serviceTemplate.getTopology_template())
        && MapUtils.isNotEmpty(serviceTemplate.getTopology_template().getNode_templates())) {
      for (Map.Entry<String, NodeTemplate> nodeTemplateEntry : serviceTemplate
          .getTopology_template().getNode_templates().entrySet()) {
        if (isTypeOf(nodeTemplateEntry.getValue(), nodeType, serviceTemplate, toscaServiceModel)) {
          nodeTemplates.put(nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue());
        }

      }
    }
    return nodeTemplates;
  }

  @Override
  public boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType,
                          ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
    if (nodeTemplate == null) {
      return false;
    }

    if (isNodeTemplateOfTypeNodeType(nodeTemplate, nodeType)) {
      return true;
    }

    Optional<Boolean> nodeTypeExistInServiceTemplateHierarchy =
        isNodeTypeExistInServiceTemplateHierarchy(nodeType, nodeTemplate.getType(), serviceTemplate,
            toscaServiceModel, null);
    return nodeTypeExistInServiceTemplateHierarchy.orElseThrow(() -> new CoreException(
        new ToscaNodeTypeNotFoundErrorBuilder(nodeTemplate.getType()).build()));
  }


  private Optional<Boolean> isNodeTypeExistInServiceTemplateHierarchy(String nodeTypeToMatch,
                                                               String nodeTypeToSearch,
                                                               ServiceTemplate serviceTemplate,
                                                               ToscaServiceModel toscaServiceModel,
                                                               Set<String> analyzedImportFiles) {
    Map<String, NodeType> searchableNodeTypes = serviceTemplate.getNode_types();
    if (!MapUtils.isEmpty(searchableNodeTypes)) {
      NodeType nodeType = searchableNodeTypes.get(nodeTypeToSearch);
      if (Objects.nonNull(nodeType)) {
        if (Objects.equals(nodeType.getDerived_from(), nodeTypeToMatch)) {
          return Optional.of(true);
        } else if (isNodeTypeIsToscaRoot(nodeType)) {
          return Optional.of(false);
        } else {
          return isNodeTypeExistInServiceTemplateHierarchy(nodeTypeToMatch,
              nodeType.getDerived_from(), serviceTemplate, toscaServiceModel, null);
        }
      } else {
        return isNodeTypeExistInImports(nodeTypeToMatch, nodeTypeToSearch, serviceTemplate,
            toscaServiceModel, analyzedImportFiles);
      }
    }
    return isNodeTypeExistInImports(nodeTypeToMatch, nodeTypeToSearch, serviceTemplate,
        toscaServiceModel, analyzedImportFiles);

  }

  private Optional<Boolean> isNodeTypeExistInImports(String nodeTypeToMatch,
                                                     String nodeTypeToSearch,
                                                     ServiceTemplate serviceTemplate,
                                                     ToscaServiceModel toscaServiceModel,
                                                     Set<String> analyzedImportFiles) {
    Map<String, Import> imports = serviceTemplate.getImports();
    if (imports == null) {
      return Optional.empty();
    }

    analyzedImportFiles = createAnalyzedImportFilesSet(analyzedImportFiles);
    for (Import anImport : imports.values()) {
      if (Objects.isNull(anImport) || Objects.isNull(anImport.getFile())) {
        throw new RuntimeException("import without file entry");
      }
      String importFile = anImport.getFile();
      if (analyzedImportFiles.contains(importFile)) {
        continue;
      }
      addImportFileToAnalyzedImportFilesSet(analyzedImportFiles, importFile);
      ServiceTemplate template = toscaServiceModel.getServiceTemplates().get(importFile);
      Optional<Boolean> nodeTypeExistInServiceTemplateHierarchy =
          isNodeTypeExistInServiceTemplateHierarchy(nodeTypeToMatch, nodeTypeToSearch, template,
              toscaServiceModel, analyzedImportFiles);
      if (nodeTypeExistInServiceTemplateHierarchy.isPresent()) {
        if (nodeTypeExistInServiceTemplateHierarchy.get()) {
          return Optional.of(true);
        }
      }
    }
    return Optional.of(false);
  }

  private Set<String> addImportFileToAnalyzedImportFilesSet(Set<String> analyzedImportFiles,
                                                            String importFile) {
    analyzedImportFiles.add(importFile);
    return analyzedImportFiles;
  }

  private Set<String> createAnalyzedImportFilesSet(Set<String> analyzedImportFiles) {
    if (Objects.isNull(analyzedImportFiles)) {
      analyzedImportFiles = new HashSet<>();
    }
    return analyzedImportFiles;
  }

  private boolean isNodeTypeIsToscaRoot(NodeType stNodeType) {
    return Objects.equals(stNodeType.getDerived_from(), ToscaNodeType.ROOT.getDisplayName());
  }

  private boolean isNodeTemplateOfTypeNodeType(NodeTemplate nodeTemplate, String nodeType) {
    return Objects.equals(nodeTemplate.getType(), nodeType);
  }

  @Override
  public List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate,
                                                     String requirementId) {
    List<RequirementAssignment> requirements = new ArrayList<>();
    List<Map<String, RequirementAssignment>> requirementList = nodeTemplate.getRequirements();
    if (requirementList != null) {
      requirementList.stream().filter(reqMap -> reqMap.get(requirementId) != null)
          .forEach(reqMap -> {
            ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
            RequirementAssignment reqAssignment = toscaExtensionYamlUtil
                .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqMap.get(requirementId)),
                    RequirementAssignment.class);
            requirements.add(reqAssignment);
          });
    }
    return requirements;
  }

  @Override
  public Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate,
                                                    String nodeTemplateId) {
    if ((serviceTemplate.getTopology_template() != null)
        && (serviceTemplate.getTopology_template().getNode_templates() != null)
        && (serviceTemplate.getTopology_template().getNode_templates()
        .get(nodeTemplateId) != null)) {
      return Optional
          .of(serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId));
    }
    return Optional.empty();
  }

  @Override
  public Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId,
                                                           NodeTemplate substitutableNodeTemplate) {
    if (!isSubstitutableNodeTemplate(substitutableNodeTemplate)) {
      return Optional.empty();
    }

    if (substitutableNodeTemplate.getProperties() != null
        && substitutableNodeTemplate.getProperties()
            .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) != null) {
      Object serviceTemplateFilter = substitutableNodeTemplate.getProperties()
          .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
      if (serviceTemplateFilter != null && serviceTemplateFilter instanceof Map) {
        Object substituteServiceTemplate = ((Map) serviceTemplateFilter)
            .get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
        if (substituteServiceTemplate == null) {
          throw new CoreException(
              new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId)
                  .build());
        }
        return Optional.of(substituteServiceTemplate.toString());
      }
    }
    throw new CoreException(
        new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId)
            .build());
  }

  @Override
  public Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate) {
    Map<String, NodeTemplate> substitutableNodeTemplates = new HashMap<>();

    if (serviceTemplate == null
        || serviceTemplate.getTopology_template() == null
        || serviceTemplate.getTopology_template().getNode_templates() == null) {
      return substitutableNodeTemplates;
    }

    Map<String, NodeTemplate> nodeTemplates =
        serviceTemplate.getTopology_template().getNode_templates();
    for (String nodeTemplateId : nodeTemplates.keySet()) {
      NodeTemplate nodeTemplate = nodeTemplates.get(nodeTemplateId);
      if (isSubstitutableNodeTemplate(nodeTemplate)) {
        substitutableNodeTemplates.put(nodeTemplateId, nodeTemplate);
      }
    }

    return substitutableNodeTemplates;
  }

  private boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate) {
    return nodeTemplate.getDirectives() != null
        && nodeTemplate.getDirectives().contains(ToscaConstants
        .NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
  }

  private boolean isSubstitutionServiceTemplate(String substituteServiceTemplateFileName,
                                                ServiceTemplate substituteServiceTemplate) {
    if (substituteServiceTemplate != null
        && substituteServiceTemplate.getTopology_template() != null
        && substituteServiceTemplate.getTopology_template().getSubstitution_mappings() != null) {
      if (substituteServiceTemplate.getTopology_template().getSubstitution_mappings()
          .getNode_type() == null) {
        throw new CoreException(new ToscaInvalidSubstitutionServiceTemplateErrorBuilder(
            substituteServiceTemplateFileName).build());
      }
      return true;
    }
    return false;

  }

  @Override
  public Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq(
      String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate,
      String requirementId) {
    if (isSubstitutionServiceTemplate(substituteServiceTemplateFileName,
        substituteServiceTemplate)) {
      Map<String, List<String>> substitutionMappingRequirements =
          substituteServiceTemplate.getTopology_template().getSubstitution_mappings()
              .getRequirements();
      if (substitutionMappingRequirements != null) {
        List<String> requirementMapping = substitutionMappingRequirements.get(requirementId);
        if (requirementMapping != null && !requirementMapping.isEmpty()) {
          String mappedNodeTemplateId = requirementMapping.get(0);
          Optional<NodeTemplate> mappedNodeTemplate =
              getNodeTemplateById(substituteServiceTemplate, mappedNodeTemplateId);
          mappedNodeTemplate.orElseThrow(() -> new CoreException(
              new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", mappedNodeTemplateId)
                  .build()));
          Map.Entry<String, NodeTemplate> mappedNodeTemplateEntry =
              new Map.Entry<String, NodeTemplate>() {
                @Override
                public String getKey() {
                  return mappedNodeTemplateId;
                }

                @Override
                public NodeTemplate getValue() {
                  return mappedNodeTemplate.get();
                }

                @Override
                public NodeTemplate setValue(NodeTemplate value) {
                  return null;
                }
              };
          return Optional.of(mappedNodeTemplateEntry);
        }
      }
    }
    return Optional.empty();
  }


  /*
  match only for the input which is not null
   */
  @Override
  public boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment,
                                                String capability, String node,
                                                String relationship) {
    if (capability != null) {
      if (requirementAssignment.getCapability() == null
          || !requirementAssignment.getCapability().equals(capability)) {
        return false;
      }
    }

    if (node != null) {
      if (requirementAssignment.getNode() == null
          || !requirementAssignment.getNode().equals(node)) {
        return false;
      }
    }

    if (relationship != null) {
      if (requirementAssignment.getRelationship() == null
          || !requirementAssignment.getRelationship().equals(relationship)) {
        return false;
      }
    }

    return !(capability == null && node == null && relationship == null);

  }

  @Override
  public Object getFlatEntity(ToscaElementTypes elementType, String typeId,
                              ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel) {
    Object returnEntity;

    switch (elementType) {
      case CAPABILITY_TYPE:
        returnEntity = new CapabilityType();
        break;
      default:
        throw new RuntimeException(
            "Entity[" + elementType + "] id[" + typeId + "] flat not supported");
    }

    scanAnFlatEntity(elementType, typeId, returnEntity, serviceTemplate, toscaModel);


    return returnEntity;
  }

  private void scanAnFlatEntity(ToscaElementTypes elementType, String typeId, Object entity,
                                ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel) {


    boolean entityFound =
        enrichEntityFromCurrentServiceTemplate(elementType, typeId, entity, serviceTemplate,
            toscaModel);
    if (!entityFound) {
      Map<String, Import> imports = serviceTemplate.getImports();
      if (MapUtils.isEmpty(imports)) {
        return;
      }
      for (Import importServiceTemplate : imports.values()) {
        ServiceTemplate template =
            toscaModel.getServiceTemplates().get(importServiceTemplate.getFile());
        scanAnFlatEntity(elementType, typeId, entity, template, toscaModel);
      }
    }


  }

  private boolean enrichEntityFromCurrentServiceTemplate(ToscaElementTypes elementType,
                                                         String typeId, Object entity,
                                                         ServiceTemplate serviceTemplate,
                                                         ToscaServiceModel toscaModel) {
    String derivedFrom;
    switch (elementType) {
      case CAPABILITY_TYPE:
        if (serviceTemplate.getCapability_types() != null
            && serviceTemplate.getCapability_types().containsKey(typeId)) {

          CapabilityType targetCapabilityType = ((CapabilityType) entity);
          CapabilityType sourceCapabilityType = serviceTemplate.getCapability_types().get(typeId);
          derivedFrom = sourceCapabilityType.getDerived_from();
          if (derivedFrom != null
              && !ToscaCapabilityType.NFV_METRIC.getDisplayName().equals(derivedFrom)) {
            scanAnFlatEntity(elementType, derivedFrom, entity, serviceTemplate, toscaModel);
          }
          combineCapabilityTypeInfo(sourceCapabilityType, targetCapabilityType);
        } else {
          return false;
        }
        break;
      default:
        throw new RuntimeException(
            "Entity[" + elementType + "] id[" + typeId + "] flat not supported");
    }

    return true;


  }

  private void combineCapabilityTypeInfo(CapabilityType sourceCapabilityType,
                                         CapabilityType targetCapabilityType) {
    if (MapUtils.isNotEmpty(sourceCapabilityType.getAttributes())) {
      if (targetCapabilityType.getAttributes() == null) {
        targetCapabilityType.setAttributes(new HashMap<>());
      }
      targetCapabilityType.getAttributes().putAll(sourceCapabilityType.getAttributes());
    }

    if (MapUtils.isNotEmpty(sourceCapabilityType.getProperties())) {
      if (targetCapabilityType.getProperties() == null) {
        targetCapabilityType.setProperties(new HashMap<>());
      }
      targetCapabilityType.getProperties().putAll(sourceCapabilityType.getProperties());
    }

    if (CollectionUtils.isNotEmpty(sourceCapabilityType.getValid_source_types())) {
      if (targetCapabilityType.getValid_source_types() == null) {
        targetCapabilityType.setValid_source_types(new ArrayList<>());
      }
      targetCapabilityType.getValid_source_types()
          .addAll(sourceCapabilityType.getValid_source_types());
    }

    if (CommonMethods.isEmpty(sourceCapabilityType.getDerived_from())) {
      targetCapabilityType.setDerived_from(sourceCapabilityType.getDerived_from());
    }
    if (CommonMethods.isEmpty(sourceCapabilityType.getDescription())) {
      targetCapabilityType.setDescription(sourceCapabilityType.getDescription());
    }
    if (CommonMethods.isEmpty(sourceCapabilityType.getVersion())) {
      targetCapabilityType.setVersion(sourceCapabilityType.getVersion());
    }


  }


}