Add installation mode to use snapshot image
[nonrtric/plt/rappmanager.git] / rapp-manager-acm / src / main / java / com / oransc / rappmanager / acm / service / AcmDeployer.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2023 Nordix Foundation. All rights reserved.
4  * Copyright (C) 2023 OpenInfra Foundation Europe. All rights reserved.
5  * ===============================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END========================================================================
18  */
19
20 package com.oransc.rappmanager.acm.service;
21
22 import com.google.gson.Gson;
23 import com.oransc.rappmanager.acm.configuration.ACMConfiguration;
24 import com.oransc.rappmanager.acm.rest.AutomationCompositionDefinitionApiClient;
25 import com.oransc.rappmanager.acm.rest.AutomationCompositionInstanceApiClient;
26 import com.oransc.rappmanager.dme.service.DmeAcmInterceptor;
27 import com.oransc.rappmanager.models.RappDeployer;
28 import com.oransc.rappmanager.models.csar.RappCsarConfigurationHandler;
29 import com.oransc.rappmanager.models.rapp.Rapp;
30 import com.oransc.rappmanager.models.rapp.RappEvent;
31 import com.oransc.rappmanager.models.rappinstance.RappACMInstance;
32 import com.oransc.rappmanager.models.rappinstance.RappInstance;
33 import com.oransc.rappmanager.models.statemachine.RappInstanceStateMachine;
34 import java.util.UUID;
35 import java.util.concurrent.TimeUnit;
36 import lombok.RequiredArgsConstructor;
37 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
38 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
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.messages.rest.commissioning.AcTypeStateUpdate;
42 import org.onap.policy.clamp.models.acm.messages.rest.commissioning.CommissioningResponse;
43 import org.onap.policy.clamp.models.acm.messages.rest.commissioning.PrimeOrder;
44 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.AcInstanceStateUpdate;
45 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.DeployOrder;
46 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationResponse;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.stereotype.Service;
51 import org.springframework.web.client.RestClientException;
52
53 @Service
54 @RequiredArgsConstructor
55 public class AcmDeployer implements RappDeployer {
56
57     Logger logger = LoggerFactory.getLogger(AcmDeployer.class);
58
59     private final AutomationCompositionDefinitionApiClient automationCompositionDefinitionApiClient;
60     private final AutomationCompositionInstanceApiClient automationCompositionInstanceApiClient;
61     private final RappCsarConfigurationHandler rappCsarConfigurationHandler;
62     private final RappInstanceStateMachine rappInstanceStateMachine;
63     private final ACMConfiguration acmConfiguration;
64     private final Gson gson;
65     private final DmeAcmInterceptor dmeAcmInterceptor;
66
67     void updateACMInstanceState(UUID compositionId, RappACMInstance rappACMInstance, DeployOrder deployOrder) {
68         AcInstanceStateUpdate acInstanceStateUpdate = new AcInstanceStateUpdate();
69         acInstanceStateUpdate.setDeployOrder(deployOrder);
70         automationCompositionInstanceApiClient.compositionInstanceState(compositionId,
71                 rappACMInstance.getAcmInstanceId(), acInstanceStateUpdate, UUID.randomUUID());
72     }
73
74     public void primeACMComposition(UUID compositionId, PrimeOrder primeOrder) {
75         AcTypeStateUpdate acTypeStateUpdate = new AcTypeStateUpdate();
76         acTypeStateUpdate.setPrimeOrder(primeOrder);
77         automationCompositionDefinitionApiClient.compositionDefinitionPriming(compositionId, UUID.randomUUID(),
78                 acTypeStateUpdate);
79     }
80
81     public CommissioningResponse createComposition(String compositionPayload) {
82         CommissioningResponse commissioningResponse = null;
83         try {
84             ToscaServiceTemplate toscaServiceTemplate = gson.fromJson(compositionPayload, ToscaServiceTemplate.class);
85             dmeAcmInterceptor.injectToscaServiceTemplate(toscaServiceTemplate);
86             commissioningResponse = automationCompositionDefinitionApiClient.createCompositionDefinitions(
87                     gson.toJson(toscaServiceTemplate), UUID.randomUUID());
88         } catch (Exception e) {
89             logger.warn("Error in creating composition", e);
90         }
91         return commissioningResponse;
92     }
93
94     public CommissioningResponse deleteComposition(UUID compositionId) {
95         try {
96             return automationCompositionDefinitionApiClient.deleteCompositionDefinition(compositionId,
97                     UUID.randomUUID());
98         } catch (Exception e) {
99             logger.warn("Error in deleting composition {}", compositionId, e);
100         }
101         return null;
102     }
103
104     boolean isCompositionInstanceStateEquals(UUID compositionId, UUID compositionIntanceId, DeployState deployState) {
105         return automationCompositionInstanceApiClient.getCompositionInstance(compositionId, compositionIntanceId,
106                 UUID.randomUUID()).getDeployState().equals(deployState);
107     }
108
109     boolean waitForCompositionInstanceTargetState(UUID compositionId, RappInstance rappInstance,
110             DeployState deployState) {
111         boolean targetInstanceStateTransition = false;
112         try {
113             for (int i = 0; i < acmConfiguration.getMaxRetries(); i++) {
114                 logger.debug("Composition instance state check {}", i + 1);
115                 if (isCompositionInstanceStateEquals(compositionId, rappInstance.getAcm().getAcmInstanceId(),
116                         deployState)) {
117                     sendRappInstanceStateEvent(rappInstance, deployState);
118                     logger.info("Composition instance {} state is {}", rappInstance.getAcm().getAcmInstanceId(),
119                             deployState);
120                     targetInstanceStateTransition = true;
121                     break;
122                 } else {
123                     TimeUnit.SECONDS.sleep(acmConfiguration.getRetryInterval());
124                 }
125             }
126         } catch (Exception e) {
127             logger.warn("Unable to get composition instance state for composition {}", compositionId, e);
128             Thread.currentThread().interrupt();
129         }
130         return targetInstanceStateTransition;
131     }
132
133     @Override
134     public boolean deployRappInstance(Rapp rapp, RappInstance rappInstance) {
135         try {
136             String instantiationPayload =
137                     rappCsarConfigurationHandler.getInstantiationPayload(rapp, rappInstance.getAcm(),
138                             rapp.getCompositionId());
139             AutomationComposition automationComposition =
140                     gson.fromJson(instantiationPayload, AutomationComposition.class);
141             dmeAcmInterceptor.injectAutomationComposition(automationComposition, rapp, rappInstance);
142
143             InstantiationResponse instantiationResponse =
144                     automationCompositionInstanceApiClient.createCompositionInstance(rapp.getCompositionId(),
145                             gson.toJson(automationComposition), UUID.randomUUID());
146             if (instantiationResponse.getInstanceId() != null) {
147                 rappInstance.getAcm().setAcmInstanceId(instantiationResponse.getInstanceId());
148                 updateACMInstanceState(rapp.getCompositionId(), rappInstance.getAcm(), DeployOrder.DEPLOY);
149                 return true;
150             }
151         } catch (Exception e) {
152             logger.warn("Error in deploying Rapp", e);
153         }
154         rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.ACMDEPLOYFAILED);
155         rappInstance.setReason("Unable to deploy ACM");
156         return false;
157     }
158
159     @Override
160     public boolean undeployRappInstance(Rapp rapp, RappInstance rappInstance) {
161         AutomationComposition automationComposition =
162                 automationCompositionInstanceApiClient.getCompositionInstance(rapp.getCompositionId(),
163                         rappInstance.getAcm().getAcmInstanceId(), UUID.randomUUID());
164         if (automationComposition.getDeployState().equals(DeployState.DEPLOYED) && automationComposition.getLockState()
165                                                                                            .equals(LockState.LOCKED)) {
166             updateACMInstanceState(rapp.getCompositionId(), rappInstance.getAcm(), DeployOrder.UNDEPLOY);
167             if (waitForCompositionInstanceTargetState(rapp.getCompositionId(), rappInstance, DeployState.UNDEPLOYED)) {
168                 automationCompositionInstanceApiClient.deleteCompositionInstance(
169                         automationComposition.getCompositionId(), automationComposition.getInstanceId(),
170                         UUID.randomUUID());
171                 rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.ACMUNDEPLOYED);
172                 return true;
173             }
174         }
175         rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.ACMUNDEPLOYFAILED);
176         rappInstance.setReason("Unable to undeploy ACM");
177         return false;
178     }
179
180     @Override
181     public boolean primeRapp(Rapp rapp) {
182         logger.info("Priming rapp {}", rapp.getName());
183         try {
184             String compositionPayload = rappCsarConfigurationHandler.getAcmCompositionPayload(rapp);
185             CommissioningResponse commissioningResponse = createComposition(compositionPayload);
186             if (commissioningResponse != null && commissioningResponse.getCompositionId() != null) {
187                 rapp.setCompositionId(commissioningResponse.getCompositionId());
188                 logger.info("Priming automation Composition");
189                 primeACMComposition(commissioningResponse.getCompositionId(), PrimeOrder.PRIME);
190                 return true;
191             } else {
192                 logger.warn("Failed to create automation composition");
193             }
194         } catch (Exception e) {
195             logger.warn("Error in creating automation composition", e);
196         }
197         rapp.setReason("Unable to create automation composition");
198         return false;
199     }
200
201     @Override
202     public boolean deprimeRapp(Rapp rapp) {
203         try {
204             primeACMComposition(rapp.getCompositionId(), PrimeOrder.DEPRIME);
205             if (waitForCompositionTargetState(rapp.getCompositionId(), AcTypeState.COMMISSIONED)) {
206                 CommissioningResponse commissioningResponse = deleteComposition(rapp.getCompositionId());
207                 if (commissioningResponse != null) {
208                     rapp.setCompositionId(null);
209                     return true;
210                 }
211             }
212         } catch (Exception e) {
213             logger.warn("Failed deprime automation composition", e);
214         }
215         rapp.setReason("Unable to delete automation composition");
216         return false;
217     }
218
219     boolean waitForCompositionTargetState(UUID compositionId, AcTypeState acTypeState) {
220         boolean targetCompositionStateTransition = false;
221         try {
222             for (int i = 0; i < acmConfiguration.getMaxRetries(); i++) {
223                 logger.debug("Composition state check {}", i + 1);
224                 if (isCompositionStateEquals(compositionId, acTypeState)) {
225                     logger.debug("Composition {} state is {}", compositionId, acTypeState);
226                     targetCompositionStateTransition = true;
227                     break;
228                 } else {
229                     TimeUnit.SECONDS.sleep(acmConfiguration.getRetryInterval());
230                 }
231             }
232         } catch (Exception e) {
233             logger.warn("Unable to get composition state for composition {}", compositionId, e);
234             Thread.currentThread().interrupt();
235         }
236         return targetCompositionStateTransition;
237     }
238
239     boolean isCompositionStateEquals(UUID compositionId, AcTypeState acTypeState) {
240         return automationCompositionDefinitionApiClient.getCompositionDefinition(compositionId, UUID.randomUUID())
241                        .getState().equals(acTypeState);
242     }
243
244     public void syncRappInstanceStatus(UUID compositionId, RappInstance rappInstance) {
245         if (rappInstance.getAcm().getAcmInstanceId() != null) {
246             try {
247                 AutomationComposition compositionInstance =
248                         automationCompositionInstanceApiClient.getCompositionInstance(compositionId,
249                                 rappInstance.getAcm().getAcmInstanceId(), UUID.randomUUID());
250                 sendRappInstanceStateEvent(rappInstance, compositionInstance.getDeployState());
251             } catch (RestClientException exception) {
252                 logger.warn("Unable to get the ACM details for rapp instance {}", rappInstance.getRappInstanceId());
253             }
254         }
255     }
256
257     void sendRappInstanceStateEvent(RappInstance rappInstance, DeployState deployState) {
258         if (deployState.equals(DeployState.DEPLOYED)) {
259             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.ACMDEPLOYED);
260             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.DMEDEPLOYED);
261         } else if (deployState.equals(DeployState.UNDEPLOYED)) {
262             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.ACMUNDEPLOYED);
263             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.DMEUNDEPLOYED);
264         } else if (deployState.equals(DeployState.DEPLOYING)) {
265             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.DEPLOYING);
266         } else if (deployState.equals(DeployState.UNDEPLOYING)) {
267             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.UNDEPLOYING);
268         }
269     }
270 }