aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
blob: c38b3d8f9927b3d052558fed09835f7d926d1f89 (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
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2021, Nordix Foundation. 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.be.components.impl;

import fj.data.Either;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.jetbrains.annotations.NotNull;
import org.openecomp.sdc.be.components.attribute.AttributeDeclarationOrchestrator;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstOutputsMap;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceAttribOutput;
import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
import org.openecomp.sdc.be.model.ComponentInstanceOutput;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.OutputDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.common.log.elements.LoggerSupportability;
import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
import org.openecomp.sdc.common.log.enums.StatusCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

@org.springframework.stereotype.Component("outputsBusinessLogic")
public class OutputsBusinessLogic extends BaseBusinessLogic {

    private static final String CREATE_OUTPUT = "CreateOutput";
    private static final Logger log = Logger.getLogger(OutputsBusinessLogic.class);
    private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
    private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_OUTPUTS = "Going to execute rollback on create outputs.";
    private static final String GOING_TO_EXECUTE_COMMIT_ON_CREATE_OUTPUTS = "Going to execute commit on create outputs.";
    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(OutputsBusinessLogic.class);
    private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID =
        "Failed to found component instance outputs componentInstanceId: {}";
    private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR = "Failed to found component instance outputs {}, error: {}";
    private final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator;

    @Autowired
    public OutputsBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
                                final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
                                final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
                                final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator,
                                final ArtifactsOperations artifactToscaOperation) {
        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
            artifactToscaOperation);
        this.attributeDeclarationOrchestrator = attributeDeclarationOrchestrator;
    }

    public Either<List<ComponentInstanceOutput>, ResponseFormat> getComponentInstanceOutputs(final String userId, final String componentId,
                                                                                             final String componentInstanceId) {
        validateUserExists(userId);
        final ComponentParametersView filters = new ComponentParametersView();
        filters.disableAll();
        filters.setIgnoreOutputs(false);
        filters.setIgnoreComponentInstances(false);
        filters.setIgnoreComponentInstancesOutputs(false);
        final Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
        if (getComponentEither.isRight()) {
            ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
            log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        final Component component = getComponentEither.left().value();
        if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) {
            final ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
            log.debug(FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR, componentInstanceId, actionStatus);
            loggerSupportability.log(LoggerSupportabilityActions.CREATE_OUTPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
                FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId);
            return Either.right(componentsUtils.getResponseFormat(actionStatus));
        }
        final Map<String, List<ComponentInstanceOutput>> ciOutputs = Optional.ofNullable(component.getComponentInstancesOutputs())
            .orElse(Collections.emptyMap());
        return Either.left(ciOutputs.getOrDefault(componentInstanceId, Collections.emptyList()));
    }

    @Override
    public Either<List<OutputDefinition>, ResponseFormat> declareAttributes(final String userId, final String componentId,
                                                                            final ComponentTypeEnum componentTypeEnum,
                                                                            final ComponentInstOutputsMap componentInstOutputsMap) {
        return createMultipleOutputs(userId, componentId, componentTypeEnum, componentInstOutputsMap, true, false);
    }

    private Either<List<OutputDefinition>, ResponseFormat> createMultipleOutputs(final String userId, final String componentId,
                                                                                 final ComponentTypeEnum componentType,
                                                                                 final ComponentInstOutputsMap componentInstOutputsMapUi,
                                                                                 final boolean shouldLockComp, final boolean inTransaction) {
        Either<List<OutputDefinition>, ResponseFormat> result = Either.right(new ResponseFormat(HttpStatus.BAD_REQUEST.value()));
        org.openecomp.sdc.be.model.Component component = null;
        try {
            validateUserExists(userId);
            component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);
            ImmutablePair<StorageOperationStatus, String> status = validateOutputName(component, componentInstOutputsMapUi);
            if (status.getLeft() != StorageOperationStatus.OK) {
                throw new ByResponseFormatComponentException(
                    componentsUtils.getResponseFormat(ActionStatus.OUTPUT_NAME_ALREADY_EXIST, status.getRight()));
            }
            result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi)
                .left().bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate))
                .right().map(componentsUtils::getResponseFormat);
            return result;
        } catch (final ByResponseFormatComponentException e) {
            log.error("#createMultipleOutputs: Exception thrown: ", e);
            result = Either.right(e.getResponseFormat());
            return result;
        } finally {
            if (!inTransaction) {
                if (result.isRight()) {
                    log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_OUTPUTS);
                    janusGraphDao.rollback();
                } else {
                    log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_OUTPUTS);
                    janusGraphDao.commit();
                }
            }
            // unlock resource
            if (shouldLockComp && component != null) {
                graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
            }
        }
    }

    private ImmutablePair<StorageOperationStatus, String> validateOutputName(final Component component,
                                                                             final ComponentInstOutputsMap componentInstOutputsMapUi) {
        final Map<String, List<ComponentInstanceAttribOutput>> outputDeclaredProperties = new HashMap<>();
        if (MapUtils.isNotEmpty(componentInstOutputsMapUi.getComponentInstanceOutputsMap())) {
            outputDeclaredProperties.putAll(componentInstOutputsMapUi.getComponentInstanceOutputsMap());
        } else if (MapUtils.isNotEmpty(componentInstOutputsMapUi.getComponentInstanceAttributes())) {
            outputDeclaredProperties.putAll(componentInstOutputsMapUi.getComponentInstanceAttributes());
        }
        if (MapUtils.isNotEmpty(outputDeclaredProperties) && CollectionUtils.isNotEmpty(component.getOutputs())) {
            for (final List<ComponentInstanceAttribOutput> componentInstancePropOutputs : outputDeclaredProperties.values()) {
                for (final ComponentInstanceAttribOutput componentInstancePropOutput : componentInstancePropOutputs) {
                    final Optional<OutputDefinition> outputDefinition = component.getOutputs().stream()
                        .filter(output -> output.getName().equals(componentInstancePropOutput.getOutputName())
                            || output.getName().equals(componentInstancePropOutput.getName())).findAny();
                    if (outputDefinition.isPresent()) {
                        return new ImmutablePair<>(StorageOperationStatus.INVALID_VALUE, outputDefinition.get().getName());
                    }
                }
            }
        }
        return new ImmutablePair<>(StorageOperationStatus.OK, StringUtils.EMPTY);
    }

    private Component getAndValidateComponentForCreate(final String userId, final String componentId,
                                                       final ComponentTypeEnum componentType,
                                                       final boolean shouldLockComp) {
        final ComponentParametersView componentParametersView = getBaseComponentParametersView();
        final Component component = validateComponentExists(componentId, componentType, componentParametersView);
        if (shouldLockComp) {
            // lock the component
            lockComponent(component, CREATE_OUTPUT);
        }
        validateCanWorkOnComponent(component, userId);
        return component;
    }

    private Either<List<OutputDefinition>, StorageOperationStatus> prepareOutputsForCreation(final String userId, final String cmptId,
                                                                                             final List<OutputDefinition> outputsToCreate) {
        final Map<String, OutputDefinition> outputsToPersist = MapUtil.toMap(outputsToCreate, OutputDefinition::getName);
        assignOwnerIdToOutputs(userId, outputsToPersist);
        final var statusEither = toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId);
        if (statusEither.isRight()) {
            return statusEither;
        }
        return statusEither.left().map(persistedOutputs -> outputsToCreate);
    }

    private void assignOwnerIdToOutputs(final String userId, final Map<String, OutputDefinition> outputsToCreate) {
        outputsToCreate.values().forEach(outputDefinition -> outputDefinition.setOwnerId(userId));
    }

    private ComponentParametersView getBaseComponentParametersView() {
        final ComponentParametersView componentParametersView = new ComponentParametersView();
        componentParametersView.disableAll();
        componentParametersView.setIgnoreOutputs(false);
        componentParametersView.setIgnoreAttributes(false);
        componentParametersView.setIgnoreComponentInstances(false);
        componentParametersView.setIgnoreComponentInstancesOutputs(false);
        componentParametersView.setIgnoreComponentInstancesAttributes(false);
        componentParametersView.setIgnoreComponentInstancesProperties(false);
        componentParametersView.setIgnoreUsers(false);
        return componentParametersView;
    }

    /**
     * Delete output from component
     *
     * @param componentId
     * @param userId
     * @param outputId
     * @return
     */
    public OutputDefinition deleteOutput(final String componentId, final String userId, final String outputId) {
        if (log.isDebugEnabled()) {
            log.debug("Going to delete output id: {}", outputId);
        }
        validateUserExists(userId);
        final ComponentParametersView componentParametersView = getBaseComponentParametersView();
        componentParametersView.setIgnoreAttributes(false);
        final Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade
            .getToscaElement(componentId, componentParametersView);
        if (componentEither.isRight()) {
            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value()));
        }
        final org.openecomp.sdc.be.model.Component component = componentEither.left().value();
        // Validate outputId is child of the component
        final Optional<OutputDefinition> optionalOutput = component.getOutputs().stream().
            // filter by ID
                filter(output -> output.getUniqueId().equals(outputId)).
            // Get the output
                findAny();
        if (!optionalOutput.isPresent()) {
            throw new ByActionStatusComponentException(ActionStatus.OUTPUT_IS_NOT_CHILD_OF_COMPONENT, outputId, componentId);
        }
        final OutputDefinition outputForDelete = optionalOutput.get();
        // Lock component
        lockComponent(componentId, component, "deleteOutput");
        // Delete output operations
        boolean failed = false;
        try {
            final StorageOperationStatus status = toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName());
            if (status != StorageOperationStatus.OK) {
                log.debug("Component id: {} delete output id: {} failed", componentId, outputId);
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName());
            }
            final StorageOperationStatus storageOperationStatus = attributeDeclarationOrchestrator
                .unDeclareAttributesAsOutputs(component, outputForDelete);
            if (storageOperationStatus != StorageOperationStatus.OK) {
                log.debug("Component id: {} update attributes declared as output for outputId: {} failed", componentId, outputId);
                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName());
            }
            return outputForDelete;
        } catch (final ComponentException e) {
            failed = true;
            throw e;
        } finally {
            unlockComponent(failed, component);
        }
    }

    public Either<List<OutputDefinition>, ResponseFormat> createOutputsInGraph(final Map<String, OutputDefinition> outputs,
                                                                               final Component component,
                                                                               final String userId) {

        final List<OutputDefinition> result = new ArrayList<>();
        for (final Map.Entry<String, OutputDefinition> outputDefinition : outputs.entrySet()) {
            final var outputDefinitionValue = outputDefinition.getValue();
            outputDefinitionValue.setName(outputDefinition.getKey());

            final String value = outputDefinitionValue.getValue();
            if (value != null) {
                final List<String> getAttribute = (List<String>) ImportUtils.loadYamlAsStrictMap(value)
                    .get(ToscaGetFunctionType.GET_ATTRIBUTE.getFunctionName());
                if (getAttribute.size() == 2) {
                    final var optionalComponentInstance = component.getComponentInstanceByName(getAttribute.get(0));
                    if (optionalComponentInstance.isPresent()) {
                        final var createdOutputs
                            = createOutputs(component.getUniqueId(), userId, getAttribute.get(1), optionalComponentInstance.get(),
                            outputDefinitionValue.getName());
                        if (createdOutputs.isRight()) {
                            return Either.right((createdOutputs.right().value()));
                        }
                        result.addAll(createdOutputs.left().value());
                    } else {
                        // From SELF
                        outputDefinitionValue.setInstanceUniqueId(component.getUniqueId());
                    }
                }
            }
        }
        return Either.left(result);

    }

    private Either<List<OutputDefinition>, ResponseFormat> createOutputs(final String componentUniqueId, final String userId,
                                                                         final String attributeName,
                                                                         final ComponentInstance componentInstance,
                                                                         final String outputName) {
        // From Instance
        final var componentInstanceAttributes = componentInstance.getAttributes();
        if (CollectionUtils.isNotEmpty(componentInstanceAttributes)) {
            final var componentInstanceAttributeOptional = componentInstanceAttributes.stream()
                .filter(ad -> ad.getName().equals(attributeName)).map(ComponentInstanceAttribute::new).findFirst();
            if (componentInstanceAttributeOptional.isPresent()) {
                final var componentInstOutputsMap = new ComponentInstOutputsMap();
                componentInstOutputsMap.setComponentInstanceAttributes(Collections.singletonMap(componentInstance.getUniqueId(),
                    Collections.singletonList(new ComponentInstanceAttribOutput(componentInstanceAttributeOptional.get(), outputName))));
                return createMultipleOutputs(userId, componentUniqueId, ComponentTypeEnum.SERVICE,
                    componentInstOutputsMap, true, false);
            }
        }
        final List<PropertyDefinition> componentInstanceProperties = componentInstance.getProperties();
        if (CollectionUtils.isNotEmpty(componentInstanceProperties)) {
            final Optional<PropertyDefinition> componentInstancePropertyOptional = componentInstanceProperties.stream()
                .filter(prop -> prop.getName().equals(attributeName)).findFirst();
            if (componentInstancePropertyOptional.isPresent()) {
                PropertyDefinition propertyDefinition = componentInstancePropertyOptional.get();
                final ComponentInstOutputsMap componentInstOutputsMap = new ComponentInstOutputsMap();
                ComponentInstanceAttribOutput attribute = getComponentInstanceAttribOutput(propertyDefinition);
                componentInstOutputsMap.setComponentInstanceAttributes(Collections.singletonMap(componentInstance.getUniqueId(),
                    Collections.singletonList(new ComponentInstanceAttribOutput(attribute, outputName))));
                return createMultipleOutputs(userId, componentUniqueId, ComponentTypeEnum.SERVICE, componentInstOutputsMap, true, false);
            }
        }
        return Either.left(new ArrayList<>());
    }

    @NotNull
    private ComponentInstanceAttribOutput getComponentInstanceAttribOutput(PropertyDefinition propertyDefinition) {
        ComponentInstanceAttribOutput attribute = new ComponentInstanceAttribOutput();
        attribute.setParentUniqueId(propertyDefinition.getParentUniqueId());
        attribute.setName(propertyDefinition.getName());
        attribute.setOwnerId(propertyDefinition.getOwnerId());
        attribute.setType(propertyDefinition.getType());
        attribute.setSchema(propertyDefinition.getSchema());
        attribute.setUniqueId(propertyDefinition.getUniqueId());
        return attribute;
    }

}