c1228e965323d75f4b0e82b013f59f4a7c22032b
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2024-2025 OpenInfra Foundation Europe. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.acm.participant.sim.main.handler;
22
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.UUID;
27 import java.util.concurrent.locks.LockSupport;
28 import lombok.Getter;
29 import lombok.RequiredArgsConstructor;
30 import lombok.Setter;
31 import org.onap.policy.clamp.acm.participant.intermediary.api.CompositionDto;
32 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
33 import org.onap.policy.clamp.acm.participant.sim.model.InternalData;
34 import org.onap.policy.clamp.acm.participant.sim.model.InternalDatas;
35 import org.onap.policy.clamp.acm.participant.sim.model.SimConfig;
36 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
37 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
38 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
39 import org.onap.policy.clamp.models.acm.concepts.DeployState;
40 import org.onap.policy.clamp.models.acm.concepts.LockState;
41 import org.onap.policy.clamp.models.acm.concepts.ParticipantUtils;
42 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.stereotype.Service;
47
48 /**
49  * This class handles implementation of Simulator Service.
50  */
51 @Service
52 @RequiredArgsConstructor
53 public class SimulatorService {
54
55     private final ParticipantIntermediaryApi intermediaryApi;
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(SimulatorService.class);
58     private static final String INTERNAL_STATE = "InternalState";
59     private static final String MIGRATION_PROPERTY = "stage";
60     private static final String ROLLBACK_PROPERTY = "rollbackStage";
61     private static final String PREPARE_PROPERTY = "prepareStage";
62     private static final String STAGE_MSG = "stage %d %s";
63
64     @Getter
65     @Setter
66     private SimConfig config = new SimConfig();
67
68     /**
69      * Get AutomationComposition.
70      *
71      * @return the AutomationCompositions
72      */
73     public AutomationCompositions getAutomationCompositions() {
74         var result = new AutomationCompositions();
75         result.setAutomationCompositionList(new ArrayList<>(intermediaryApi.getAutomationCompositions().values()));
76         return result;
77     }
78
79     public AutomationComposition getAutomationComposition(UUID instanceId) {
80         return intermediaryApi.getAutomationComposition(instanceId);
81     }
82
83     /**
84      * Set OutProperties.
85      *
86      * @param instanceId       the automationComposition Id
87      * @param elementId        the automationComposition Element Id
88      * @param useState         the useState
89      * @param operationalState the operationalState
90      * @param outProperties    the outProperties
91      */
92     public void setOutProperties(UUID instanceId, UUID elementId, String useState, String operationalState,
93                                  Map<String, Object> outProperties) {
94         intermediaryApi.sendAcElementInfo(instanceId, elementId, useState, operationalState,
95             outProperties);
96     }
97
98     /**
99      * Get Instance Data List.
100      *
101      * @return the InternalDatas
102      */
103     public InternalDatas getDataList() {
104         var result = new InternalDatas();
105         var map = intermediaryApi.getAutomationCompositions();
106         for (var instance : map.values()) {
107             for (var element : instance.getElements().values()) {
108                 var data = new InternalData();
109                 data.setCompositionId(instance.getCompositionId());
110                 data.setAutomationCompositionId(instance.getInstanceId());
111                 data.setAutomationCompositionElementId(element.getId());
112                 data.setIntProperties(element.getProperties());
113                 data.setOperationalState(element.getOperationalState());
114                 data.setUseState(element.getUseState());
115                 data.setOutProperties(element.getOutProperties());
116                 result.getList().add(data);
117             }
118         }
119         return result;
120     }
121
122     /**
123      * Get Composition Data List.
124      *
125      * @return the InternalDatas
126      */
127     public InternalDatas getCompositionDataList() {
128         var acElementsDefinitions = intermediaryApi.getAcElementsDefinitions();
129         var internalDatas = new InternalDatas();
130         for (var entry : acElementsDefinitions.entrySet()) {
131             for (var acElementsDefinition : entry.getValue().values()) {
132                 var internalData = new InternalData();
133                 internalData.setCompositionId(entry.getKey());
134                 internalData.setCompositionDefinitionElementId(acElementsDefinition.getAcElementDefinitionId());
135                 internalData.setIntProperties(
136                     acElementsDefinition.getAutomationCompositionElementToscaNodeTemplate().getProperties());
137                 internalData.setOutProperties(acElementsDefinition.getOutProperties());
138                 internalDatas.getList().add(internalData);
139             }
140         }
141         return internalDatas;
142     }
143
144     public void setCompositionOutProperties(UUID compositionId, ToscaConceptIdentifier compositionDefinitionElementId,
145                                             Map<String, Object> outProperties) {
146         intermediaryApi.sendAcDefinitionInfo(compositionId, compositionDefinitionElementId, outProperties);
147
148     }
149
150     protected boolean isInterrupted(int timeMs, String msg, UUID elementId) {
151         long endTime = System.nanoTime() + (timeMs * 1_000_000L);
152         while (System.nanoTime() < endTime) {
153             if (Thread.interrupted()) {
154                 LOGGER.debug(msg, elementId);
155                 return true;
156             }
157             LockSupport.parkNanos(10_000_000L);
158         }
159         return false;
160     }
161
162     private void sendAcInternalState(UUID instanceId, UUID elementId, Map<String, Object> outProperties,
163             DeployState deployState) {
164         outProperties.put(INTERNAL_STATE, deployState.name());
165         intermediaryApi.sendAcElementInfo(instanceId, elementId, null, null, outProperties);
166     }
167
168     /**
169      * Handle deploying an automation composition element.
170      *
171      * @param instanceId    the instanceId
172      * @param elementId     the elementId
173      * @param outProperties the outProperties
174      */
175     public void deploy(UUID instanceId, UUID elementId, Map<String, Object> outProperties) {
176         sendAcInternalState(instanceId, elementId, outProperties, DeployState.DEPLOYING);
177
178         if (isInterrupted(getConfig().getDeployTimerMs(),
179             "Current Thread deploy is Interrupted during execution {}", elementId)) {
180             return;
181         }
182
183         if (getConfig().isDeploySuccess()) {
184             sendAcInternalState(instanceId, elementId, outProperties, DeployState.DEPLOYED);
185
186             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
187                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
188         } else {
189             sendAcInternalState(instanceId, elementId, outProperties, DeployState.UNDEPLOYED);
190
191             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
192                 DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, "Deploy failed!");
193         }
194     }
195
196     /**
197      * Handle undeploying an automation composition element.
198      *
199      * @param instanceId    the instanceId
200      * @param elementId     the elementId
201      * @param outProperties the outProperties
202      */
203     public void undeploy(UUID instanceId, UUID elementId, Map<String, Object> outProperties) {
204         sendAcInternalState(instanceId, elementId, outProperties, DeployState.UNDEPLOYING);
205
206         if (isInterrupted(getConfig().getUndeployTimerMs(),
207             "Current Thread undeploy is Interrupted during execution {}", elementId)) {
208             return;
209         }
210
211         if (getConfig().isUndeploySuccess()) {
212             sendAcInternalState(instanceId, elementId, outProperties, DeployState.UNDEPLOYED);
213
214             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
215                 DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR, "Undeployed");
216         } else {
217             sendAcInternalState(instanceId, elementId, outProperties, DeployState.DEPLOYED);
218
219             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
220                 DeployState.DEPLOYED, null, StateChangeResult.FAILED, "Undeploy failed!");
221         }
222     }
223
224     /**
225      * Handle locking an automation composition element.
226      *
227      * @param instanceId the instanceId
228      * @param elementId  the elementId
229      */
230     public void lock(UUID instanceId, UUID elementId) {
231         if (isInterrupted(getConfig().getLockTimerMs(),
232             "Current Thread lock is Interrupted during execution {}", elementId)) {
233             return;
234         }
235
236         if (getConfig().isLockSuccess()) {
237             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
238                 null, LockState.LOCKED, StateChangeResult.NO_ERROR, "Locked");
239         } else {
240             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
241                 null, LockState.UNLOCKED, StateChangeResult.FAILED, "Lock failed!");
242         }
243     }
244
245     /**
246      * Handle unlocking an automation composition element.
247      *
248      * @param instanceId the instanceId
249      * @param elementId  the elementId
250      */
251     public void unlock(UUID instanceId, UUID elementId) {
252         if (isInterrupted(getConfig().getUnlockTimerMs(),
253             "Current Thread unlock is Interrupted during execution {}", elementId)) {
254             return;
255         }
256
257         if (getConfig().isUnlockSuccess()) {
258             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
259                 null, LockState.UNLOCKED, StateChangeResult.NO_ERROR, "Unlocked");
260         } else {
261             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
262                 null, LockState.LOCKED, StateChangeResult.FAILED, "Unlock failed!");
263         }
264     }
265
266     /**
267      * Handle deleting an automation composition element.
268      *
269      * @param instanceId the instanceId
270      * @param elementId  the elementId
271      */
272     public void delete(UUID instanceId, UUID elementId) {
273         if (isInterrupted(getConfig().getDeleteTimerMs(),
274             "Current Thread delete is Interrupted during execution {}", elementId)) {
275             return;
276         }
277
278         if (getConfig().isDeleteSuccess()) {
279             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
280                 DeployState.DELETED, null, StateChangeResult.NO_ERROR, "Deleted");
281         } else {
282             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
283                 DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, "Delete failed!");
284         }
285     }
286
287     /**
288      * Handle deleting an automation composition element in migration.
289      *
290      * @param instanceId the instanceId
291      * @param elementId  the elementId
292      */
293     public void deleteInMigration(UUID instanceId, UUID elementId) {
294         if (getConfig().isMigrateSuccess()) {
295             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
296                     DeployState.DELETED, null, StateChangeResult.NO_ERROR, "Deleted");
297         } else {
298             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
299                     DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, "Delete failed!");
300         }
301     }
302
303     /**
304      * Handle an update on an automation composition element.
305      *
306      * @param instanceId the instanceId
307      * @param elementId  the elementId
308      */
309     public void update(UUID instanceId, UUID elementId) {
310         if (isInterrupted(getConfig().getUpdateTimerMs(),
311             "Current Thread update is Interrupted during execution {}", elementId)) {
312             return;
313         }
314
315         if (getConfig().isUpdateSuccess()) {
316             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
317                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Updated");
318         } else {
319             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
320                 DeployState.DEPLOYED, null, StateChangeResult.FAILED, "Update failed!");
321         }
322     }
323
324     /**
325      * Handle a prime on an automation composition definition.
326      *
327      * @param composition the information of the Automation Composition Definition
328      */
329     public void prime(CompositionDto composition) {
330         if (isInterrupted(getConfig().getPrimeTimerMs(),
331             "Current Thread prime is Interrupted during execution {}", composition.compositionId())) {
332             return;
333         }
334
335         if (getConfig().isPrimeSuccess()) {
336             sendOutProperties(composition, AcTypeState.PRIMED.name());
337             intermediaryApi.updateCompositionState(composition.compositionId(), AcTypeState.PRIMED,
338                 StateChangeResult.NO_ERROR, "Primed");
339         } else {
340             sendOutProperties(composition, AcTypeState.COMMISSIONED.name());
341             intermediaryApi.updateCompositionState(composition.compositionId(), AcTypeState.COMMISSIONED,
342                 StateChangeResult.FAILED, "Prime failed!");
343         }
344     }
345
346     private void sendOutProperties(CompositionDto composition, String data) {
347         for (var elementEntry : composition.outPropertiesMap().entrySet()) {
348             elementEntry.getValue().put(INTERNAL_STATE, data);
349             intermediaryApi.sendAcDefinitionInfo(
350                 composition.compositionId(), elementEntry.getKey(), elementEntry.getValue());
351         }
352     }
353
354     /**
355      * Handle a deprime on an automation composition definition.
356      *
357      * @param composition the information of the Automation Composition Definition
358      */
359     public void deprime(CompositionDto composition) {
360         if (isInterrupted(getConfig().getDeprimeTimerMs(),
361             "Current Thread deprime is Interrupted during execution {}", composition.compositionId())) {
362             return;
363         }
364
365         if (getConfig().isDeprimeSuccess()) {
366             sendOutProperties(composition, AcTypeState.COMMISSIONED.name());
367             intermediaryApi.updateCompositionState(composition.compositionId(), AcTypeState.COMMISSIONED,
368                 StateChangeResult.NO_ERROR, "Deprimed");
369         } else {
370             sendOutProperties(composition, AcTypeState.PRIMED.name());
371             intermediaryApi.updateCompositionState(composition.compositionId(), AcTypeState.PRIMED,
372                 StateChangeResult.FAILED, "Deprime failed!");
373         }
374     }
375
376     /**
377      * Handle a migration on an automation composition element.
378      *
379      * @param instanceId              the instanceId
380      * @param elementId               the elementId
381      * @param stage                   the stage
382      * @param compositionInProperties in Properties from composition definition element
383      * @param instanceOutProperties   in Properties from instance element
384      */
385     public void migrate(UUID instanceId, UUID elementId, int stage, Map<String, Object> compositionInProperties,
386                         Map<String, Object> instanceOutProperties) {
387         if (isInterrupted(getConfig().getMigrateTimerMs(),
388             "Current Thread migrate is Interrupted during execution {}", elementId)) {
389             return;
390         }
391
392         if (config.isMigrateSuccess()) {
393             var stageSet = ParticipantUtils.findStageSetMigrate(compositionInProperties);
394             var nextStage = 1000;
395             for (var s : stageSet) {
396                 if (s > stage) {
397                     nextStage = Math.min(s, nextStage);
398                 }
399             }
400             instanceOutProperties.putIfAbsent(MIGRATION_PROPERTY, new ArrayList<>());
401             @SuppressWarnings("unchecked")
402             var stageList = (List<Integer>) instanceOutProperties.get(MIGRATION_PROPERTY);
403             stageList.add(stage);
404             intermediaryApi.sendAcElementInfo(instanceId, elementId, null, null, instanceOutProperties);
405             if (nextStage == 1000) {
406                 intermediaryApi.updateAutomationCompositionElementState(
407                     instanceId, elementId,
408                     DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Migrated");
409             } else {
410                 intermediaryApi.updateAutomationCompositionElementStage(
411                     instanceId, elementId,
412                     StateChangeResult.NO_ERROR, nextStage, String.format(STAGE_MSG, stage, "Migrated"));
413             }
414         } else {
415             intermediaryApi.updateAutomationCompositionElementState(
416                 instanceId, elementId,
417                 DeployState.DEPLOYED, null, StateChangeResult.FAILED, "Migrate failed!");
418         }
419     }
420
421     /**
422      * Handle a Migrate Precheck on an automation composition element.
423      *
424      * @param instanceId the instanceId
425      * @param elementId  the elementId
426      */
427     public void migratePrecheck(UUID instanceId, UUID elementId) {
428         if (isInterrupted(config.getMigratePrecheckTimerMs(),
429             "Current Thread migrate precheck is Interrupted during execution {}", elementId)) {
430             return;
431         }
432
433         if (config.isMigratePrecheck()) {
434             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
435                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Migration precheck completed");
436         } else {
437             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
438                 DeployState.DEPLOYED, null, StateChangeResult.FAILED, "Migration precheck failed");
439         }
440     }
441
442     /**
443      * Handle a Prepare on an automation composition element.
444      *
445      * @param instanceId              the instanceId
446      * @param elementId               the elementId
447      * @param stage                   the stage
448      * @param compositionInProperties in Properties from composition definition element
449      * @param instanceOutProperties   in Properties from instance element
450      */
451     public void prepare(UUID instanceId, UUID elementId, int stage, Map<String, Object> compositionInProperties,
452                         Map<String, Object> instanceOutProperties) {
453         if (isInterrupted(config.getPrepareTimerMs(),
454             "Current Thread prepare is Interrupted during execution {}", elementId)) {
455             return;
456         }
457
458         if (config.isPrepare()) {
459             var stageSet = ParticipantUtils.findStageSetPrepare(compositionInProperties);
460             var nextStage = 1000;
461             for (var s : stageSet) {
462                 if (s > stage) {
463                     nextStage = Math.min(s, nextStage);
464                 }
465             }
466             instanceOutProperties.putIfAbsent(PREPARE_PROPERTY, new ArrayList<>());
467             @SuppressWarnings("unchecked")
468             var stageList = (List<Integer>) instanceOutProperties.get(PREPARE_PROPERTY);
469             stageList.add(stage);
470             intermediaryApi.sendAcElementInfo(instanceId, elementId, null, null, instanceOutProperties);
471             if (nextStage == 1000) {
472                 intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
473                     DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR, "Prepare completed");
474             } else {
475                 intermediaryApi.updateAutomationCompositionElementStage(
476                     instanceId, elementId,
477                     StateChangeResult.NO_ERROR, nextStage, String.format(STAGE_MSG, stage, "Prepared"));
478             }
479         } else {
480             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
481                 DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, "Prepare failed");
482         }
483     }
484
485     /**
486      * Handle a Review on an automation composition element.
487      *
488      * @param instanceId the instanceId
489      * @param elementId  the elementId
490      */
491     public void review(UUID instanceId, UUID elementId) {
492         if (isInterrupted(config.getReviewTimerMs(),
493             "Current Thread review is Interrupted during execution {}", elementId)) {
494             return;
495         }
496
497         if (config.isReview()) {
498             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
499                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Review completed");
500         } else {
501             intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId,
502                 DeployState.DEPLOYED, null, StateChangeResult.FAILED, "Review failed");
503         }
504     }
505
506     /**
507      * Handle rollback of an automation composition.
508      *
509      * @param instanceId              the instanceId
510      * @param elementId               the elementId
511      * @param stage                   the stage
512      * @param compositionInProperties in Properties from composition definition element
513      * @param instanceOutProperties   in Properties from instance element
514      */
515     public void rollback(UUID instanceId, UUID elementId, int stage, Map<String, Object> compositionInProperties,
516             Map<String, Object> instanceOutProperties) {
517         if (isInterrupted(getConfig().getRollbackTimerMs(),
518             "Current Thread for rollback was Interrupted during execution {}", instanceId)) {
519             LOGGER.debug("Rollback interrupted");
520             return;
521         }
522
523         if (config.isRollback()) {
524             var stageSet = ParticipantUtils.findStageSetMigrate(compositionInProperties);
525             var nextStage = 1000;
526             for (var s : stageSet) {
527                 if (s > stage) {
528                     nextStage = Math.min(s, nextStage);
529                 }
530             }
531             instanceOutProperties.putIfAbsent(ROLLBACK_PROPERTY, new ArrayList<>());
532             @SuppressWarnings("unchecked")
533             var stageList = (List<Integer>) instanceOutProperties.get(ROLLBACK_PROPERTY);
534             stageList.add(stage);
535             intermediaryApi.sendAcElementInfo(instanceId, elementId, null, null, instanceOutProperties);
536             if (nextStage == 1000) {
537                 intermediaryApi.updateAutomationCompositionElementState(
538                         instanceId, elementId,
539                         DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Migration rollback done");
540             } else {
541                 intermediaryApi.updateAutomationCompositionElementStage(
542                         instanceId, elementId,
543                         StateChangeResult.NO_ERROR, nextStage, String.format(STAGE_MSG, stage, "Migration rollback"));
544             }
545         } else {
546             intermediaryApi.updateAutomationCompositionElementState(
547                     instanceId, elementId,
548                     DeployState.DEPLOYED, null, StateChangeResult.FAILED, "Migration rollback failed");
549         }
550     }
551 }