aboutsummaryrefslogtreecommitdiffstats
path: root/runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/instantiation/AutomationCompositionInstantiationProvider.java
blob: 220636b9d05e96a0befbb305dc96aab60efa2c5c (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
/*-
 * ============LICENSE_START=======================================================
 * Copyright (C) 2021-2024 Nordix Foundation.
 * Modifications Copyright (C) 2021 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.clamp.acm.runtime.instantiation;

import jakarta.validation.Valid;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.onap.policy.clamp.acm.runtime.main.parameters.AcRuntimeParameterGroup;
import org.onap.policy.clamp.acm.runtime.participants.AcmParticipantProvider;
import org.onap.policy.clamp.acm.runtime.supervision.SupervisionAcHandler;
import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
import org.onap.policy.clamp.models.acm.concepts.DeployState;
import org.onap.policy.clamp.models.acm.concepts.LockState;
import org.onap.policy.clamp.models.acm.concepts.NodeTemplateState;
import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
import org.onap.policy.clamp.models.acm.messages.rest.instantiation.AcInstanceStateUpdate;
import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationResponse;
import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
import org.onap.policy.clamp.models.acm.persistence.provider.AcInstanceStateResolver;
import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
import org.onap.policy.clamp.models.acm.utils.AcmUtils;
import org.onap.policy.common.parameters.BeanValidationResult;
import org.onap.policy.common.parameters.ObjectValidationResult;
import org.onap.policy.common.parameters.ValidationStatus;
import org.onap.policy.models.base.PfKey;
import org.onap.policy.models.base.PfModelRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * This class is dedicated to the Instantiation of Commissioned automation composition.
 */
@Service
@Transactional
@RequiredArgsConstructor
public class AutomationCompositionInstantiationProvider {
    private static final String DO_NOT_MATCH = " do not match with ";

    private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionInstantiationProvider.class);

    private final AutomationCompositionProvider automationCompositionProvider;
    private final AcDefinitionProvider acDefinitionProvider;
    private final AcInstanceStateResolver acInstanceStateResolver;
    private final SupervisionAcHandler supervisionAcHandler;
    private final AcmParticipantProvider acmParticipantProvider;
    private final AcRuntimeParameterGroup acRuntimeParameterGroup;

    /**
     * Create automation composition.
     *
     * @param compositionId The UUID of the automation composition definition
     * @param automationComposition the automation composition
     * @return the result of the instantiation operation
     */
    public InstantiationResponse createAutomationComposition(UUID compositionId,
            AutomationComposition automationComposition) {
        if (!compositionId.equals(automationComposition.getCompositionId())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
        }
        var checkAutomationCompositionOpt =
                automationCompositionProvider.findAutomationComposition(automationComposition.getKey().asIdentifier());
        if (checkAutomationCompositionOpt.isPresent()) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    automationComposition.getKey().asIdentifier() + " already defined");
        }

        var validationResult = validateAutomationComposition(automationComposition);
        if (!validationResult.isValid()) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult());
        }
        automationComposition = automationCompositionProvider.createAutomationComposition(automationComposition);

        return createInstantiationResponse(automationComposition);
    }

    private InstantiationResponse createInstantiationResponse(AutomationComposition automationComposition) {
        var response = new InstantiationResponse();
        response.setInstanceId(automationComposition.getInstanceId());
        response.setAffectedAutomationComposition(automationComposition.getKey().asIdentifier());
        return response;
    }

    /**
     * Update automation composition.
     *
     * @param compositionId The UUID of the automation composition definition
     * @param automationComposition the automation composition
     * @return the result of the update
     */
    public InstantiationResponse updateAutomationComposition(UUID compositionId,
            AutomationComposition automationComposition) {
        var instanceId = automationComposition.getInstanceId();
        var acToUpdate = automationCompositionProvider.getAutomationComposition(instanceId);
        if (!compositionId.equals(acToUpdate.getCompositionId())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
        }
        if (DeployState.UNDEPLOYED.equals(acToUpdate.getDeployState())) {
            acToUpdate.setElements(automationComposition.getElements());
            acToUpdate.setName(automationComposition.getName());
            acToUpdate.setVersion(automationComposition.getVersion());
            acToUpdate.setDescription(automationComposition.getDescription());
            acToUpdate.setDerivedFrom(automationComposition.getDerivedFrom());
            var validationResult = validateAutomationComposition(acToUpdate);
            if (!validationResult.isValid()) {
                throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult());
            }
            automationComposition = automationCompositionProvider.updateAutomationComposition(acToUpdate);
            return createInstantiationResponse(automationComposition);

        } else if ((DeployState.DEPLOYED.equals(acToUpdate.getDeployState())
                || DeployState.UPDATING.equals(acToUpdate.getDeployState()))
                && LockState.LOCKED.equals(acToUpdate.getLockState())) {
            if (automationComposition.getCompositionTargetId() != null) {
                return  migrateAutomationComposition(automationComposition, acToUpdate);
            } else {
                return updateDeployedAutomationComposition(automationComposition, acToUpdate);
            }
        }
        throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                "Not allowed to update in the state " + acToUpdate.getDeployState());
    }

    /**
     * Update deployed AC Element properties.
     *
     * @param automationComposition the automation composition
     * @param acToBeUpdated the composition to be updated
     * @return the result of the update
     */
    private InstantiationResponse updateDeployedAutomationComposition(
            AutomationComposition automationComposition, AutomationComposition acToBeUpdated) {

        // Iterate and update the element property values
        for (var element : automationComposition.getElements().entrySet()) {
            var elementId = element.getKey();
            var dbAcElement = acToBeUpdated.getElements().get(elementId);
            if (dbAcElement == null) {
                throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Element id not present " + elementId);
            }
            AcmUtils.recursiveMerge(dbAcElement.getProperties(), element.getValue().getProperties());
        }
        if (automationComposition.getRestarting() != null) {
            throw new PfModelRuntimeException(Status.BAD_REQUEST, "There is a restarting process, Update not allowed");
        }

        var validationResult = validateAutomationComposition(acToBeUpdated);
        if (!validationResult.isValid()) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult());
        }
        // Publish property update event to the participants
        supervisionAcHandler.update(acToBeUpdated);

        automationComposition = automationCompositionProvider.updateAutomationComposition(acToBeUpdated);
        return createInstantiationResponse(automationComposition);
    }

    private InstantiationResponse migrateAutomationComposition(
        AutomationComposition automationComposition, AutomationComposition acToBeUpdated) {

        if (!DeployState.DEPLOYED.equals(acToBeUpdated.getDeployState())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                "Not allowed to migrate in the state " + acToBeUpdated.getDeployState());
        }
        if (automationComposition.getRestarting() != null) {
            throw new PfModelRuntimeException(Status.BAD_REQUEST, "There is a restarting process, Migrate not allowed");
        }

        // Iterate and update the element property values
        for (var element : automationComposition.getElements().entrySet()) {
            var elementId = element.getKey();
            var dbAcElement = acToBeUpdated.getElements().get(elementId);
            if (dbAcElement == null) {
                throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Element id not present " + elementId);
            }
            AcmUtils.recursiveMerge(dbAcElement.getProperties(), element.getValue().getProperties());
            var newDefinition = element.getValue().getDefinition();
            var compatibility =
                newDefinition.asConceptKey().getCompatibility(dbAcElement.getDefinition().asConceptKey());
            if (PfKey.Compatibility.DIFFERENT.equals(compatibility)) {
                throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    dbAcElement.getDefinition() + " is not compatible with " + newDefinition);
            }
            if (PfKey.Compatibility.MAJOR.equals(compatibility) || PfKey.Compatibility.MINOR.equals(compatibility)) {
                LOGGER.warn("Migrate {}: Version {} has {} compatibility with {} ",
                    automationComposition.getInstanceId(), newDefinition, compatibility, dbAcElement.getDefinition());
            }
            dbAcElement.setDefinition(element.getValue().getDefinition());
        }

        var validationResult =
            validateAutomationComposition(acToBeUpdated, automationComposition.getCompositionTargetId());
        if (!validationResult.isValid()) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult());
        }
        acToBeUpdated.setCompositionTargetId(automationComposition.getCompositionTargetId());

        // Publish migrate event to the participants
        supervisionAcHandler.migrate(acToBeUpdated, automationComposition.getCompositionTargetId());

        automationComposition = automationCompositionProvider.updateAutomationComposition(acToBeUpdated);
        return createInstantiationResponse(automationComposition);
    }

    private BeanValidationResult validateAutomationComposition(AutomationComposition automationComposition) {
        return validateAutomationComposition(automationComposition, automationComposition.getCompositionId());
    }

    /**
     * Validate AutomationComposition.
     *
     * @param automationComposition AutomationComposition to validate
     * @param compositionId the composition id
     * @return the result of validation
     */
    private BeanValidationResult validateAutomationComposition(AutomationComposition automationComposition,
            UUID compositionId) {

        var result = new BeanValidationResult("AutomationComposition", automationComposition);
        var acDefinitionOpt = acDefinitionProvider.findAcDefinition(compositionId);
        if (acDefinitionOpt.isEmpty()) {
            result.addResult(new ObjectValidationResult("ServiceTemplate", compositionId, ValidationStatus.INVALID,
                    "Commissioned automation composition definition not found"));
            return result;
        }
        if (!AcTypeState.PRIMED.equals(acDefinitionOpt.get().getState())) {
            result.addResult(new ObjectValidationResult("ServiceTemplate.state", acDefinitionOpt.get().getState(),
                    ValidationStatus.INVALID, "Commissioned automation composition definition not primed"));
            return result;
        }
        if (acDefinitionOpt.get().getRestarting() != null) {
            result.addResult(
                    new ObjectValidationResult("ServiceTemplate.restarting", acDefinitionOpt.get().getRestarting(),
                            ValidationStatus.INVALID, "There is a restarting process in composition"));
            return result;
        }
        var participantIds = acDefinitionOpt.get().getElementStateMap().values().stream()
                .map(NodeTemplateState::getParticipantId).collect(Collectors.toSet());

        acmParticipantProvider.verifyParticipantState(participantIds);

        result.addResult(AcmUtils.validateAutomationComposition(automationComposition,
                acDefinitionOpt.get().getServiceTemplate(),
                acRuntimeParameterGroup.getAcmParameters().getToscaCompositionName()));

        result.addResult(automationCompositionProvider.validateElementIds(automationComposition));

        if (result.isValid()) {
            for (var element : automationComposition.getElements().values()) {
                var name = element.getDefinition().getName();
                var participantId = acDefinitionOpt.get().getElementStateMap().get(name).getParticipantId();
                element.setParticipantId(participantId);
            }
        }

        return result;
    }

    /**
     * Get Automation Composition.
     *
     * @param compositionId The UUID of the automation composition definition
     * @param instanceId The UUID of the automation composition instance
     * @return the Automation Composition
     */
    @Transactional(readOnly = true)
    public AutomationComposition getAutomationComposition(@NonNull UUID compositionId, UUID instanceId) {
        var automationComposition = automationCompositionProvider.getAutomationComposition(instanceId);
        if (!compositionId.equals(automationComposition.getCompositionId())
                        && !compositionId.equals(automationComposition.getCompositionTargetId())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
        }
        return automationComposition;
    }

    /**
     * Delete the automation composition with the given name and version.
     *
     * @param compositionId The UUID of the automation composition definition
     * @param instanceId The UUID of the automation composition instance
     * @return the result of the deletion
     */
    public InstantiationResponse deleteAutomationComposition(UUID compositionId, UUID instanceId) {
        var automationComposition = automationCompositionProvider.getAutomationComposition(instanceId);
        if (!compositionId.equals(automationComposition.getCompositionId())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
        }
        if (!DeployState.UNDEPLOYED.equals(automationComposition.getDeployState())
                && !DeployState.DELETING.equals(automationComposition.getDeployState())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    "Automation composition state is still " + automationComposition.getDeployState());
        }
        if (DeployState.DELETING.equals(automationComposition.getDeployState())
                && StateChangeResult.NO_ERROR.equals(automationComposition.getStateChangeResult())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    "Automation composition state is still " + automationComposition.getDeployState());
        }
        if (automationComposition.getRestarting() != null) {
            throw new PfModelRuntimeException(Status.BAD_REQUEST, "There is a restarting process, Delete not allowed");
        }
        var acDefinition = acDefinitionProvider.getAcDefinition(automationComposition.getCompositionId());
        var participantIds = acDefinition.getElementStateMap().values().stream()
            .map(NodeTemplateState::getParticipantId).collect(Collectors.toSet());
        acmParticipantProvider.verifyParticipantState(participantIds);
        supervisionAcHandler.delete(automationComposition, acDefinition);
        var response = new InstantiationResponse();
        response.setInstanceId(automationComposition.getInstanceId());
        response.setAffectedAutomationComposition(automationComposition.getKey().asIdentifier());
        return response;
    }

    /**
     * Get the requested automation compositions.
     *
     * @param name the name of the automation composition to get, null for all automation compositions
     * @param version the version of the automation composition to get, null for all automation compositions
     * @return the automation compositions
     */
    @Transactional(readOnly = true)
    public AutomationCompositions getAutomationCompositions(UUID compositionId, String name, String version) {
        var automationCompositions = new AutomationCompositions();
        automationCompositions.setAutomationCompositionList(
                automationCompositionProvider.getAutomationCompositions(compositionId, name, version));

        return automationCompositions;
    }

    /**
     * Handle Composition Instance State.
     *
     * @param compositionId the compositionId
     * @param instanceId the instanceId
     * @param acInstanceStateUpdate the AcInstanceStateUpdate
     */
    public void compositionInstanceState(UUID compositionId, UUID instanceId,
            @Valid AcInstanceStateUpdate acInstanceStateUpdate) {
        var automationComposition = automationCompositionProvider.getAutomationComposition(instanceId);
        if (!compositionId.equals(automationComposition.getCompositionId())) {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
                    automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
        }
        var acDefinition = acDefinitionProvider.getAcDefinition(automationComposition.getCompositionId());

        var participantIds = acDefinition.getElementStateMap().values().stream()
                .map(NodeTemplateState::getParticipantId).collect(Collectors.toSet());

        acmParticipantProvider.verifyParticipantState(participantIds);
        var result = acInstanceStateResolver.resolve(acInstanceStateUpdate.getDeployOrder(),
                acInstanceStateUpdate.getLockOrder(), automationComposition.getDeployState(),
                automationComposition.getLockState(), automationComposition.getStateChangeResult());
        switch (result) {
            case "DEPLOY":
                supervisionAcHandler.deploy(automationComposition, acDefinition);
                break;

            case "UNDEPLOY":
                supervisionAcHandler.undeploy(automationComposition, acDefinition);
                break;

            case "LOCK":
                supervisionAcHandler.lock(automationComposition, acDefinition);
                break;

            case "UNLOCK":
                supervisionAcHandler.unlock(automationComposition, acDefinition);
                break;

            default:
                throw new PfModelRuntimeException(Status.BAD_REQUEST, "Not valid " + acInstanceStateUpdate);
        }
    }
}