Add installation mode to use snapshot image
[nonrtric/plt/rappmanager.git] / rapp-manager-sme / src / main / java / com / oransc / rappmanager / sme / service / SmeDeployer.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2023 Nordix Foundation. 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  * ============LICENSE_END========================================================================
17  */
18
19 package com.oransc.rappmanager.sme.service;
20
21 import com.fasterxml.jackson.core.type.TypeReference;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.oransc.rappmanager.models.RappDeployer;
24 import com.oransc.rappmanager.models.csar.RappCsarConfigurationHandler;
25 import com.oransc.rappmanager.models.rapp.Rapp;
26 import com.oransc.rappmanager.models.rapp.RappEvent;
27 import com.oransc.rappmanager.models.rappinstance.RappInstance;
28 import com.oransc.rappmanager.models.statemachine.RappInstanceStateMachine;
29 import com.oransc.rappmanager.sme.invoker.data.APIInvokerEnrolmentDetails;
30 import com.oransc.rappmanager.sme.provider.data.APIProviderEnrolmentDetails;
31 import com.oransc.rappmanager.sme.provider.data.APIProviderFunctionDetails;
32 import com.oransc.rappmanager.sme.provider.data.ApiProviderFuncRole;
33 import com.oransc.rappmanager.sme.provider.data.RegistrationInformation;
34 import com.oransc.rappmanager.sme.publishservice.data.ServiceAPIDescription;
35 import java.util.List;
36 import java.util.Optional;
37 import lombok.RequiredArgsConstructor;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.stereotype.Service;
41
42 @Service
43 @RequiredArgsConstructor
44 public class SmeDeployer implements RappDeployer {
45
46     Logger logger = LoggerFactory.getLogger(SmeDeployer.class);
47
48     private final com.oransc.rappmanager.sme.provider.rest.DefaultApiClient providerDefaultApiClient;
49
50
51     private final com.oransc.rappmanager.sme.publishservice.rest.DefaultApiClient publishServiceDefaultApiClient;
52
53     private final com.oransc.rappmanager.sme.invoker.rest.DefaultApiClient invokerDefaultApiClient;
54
55     private final RappCsarConfigurationHandler rappCsarConfigurationHandler;
56
57     private final ObjectMapper objectMapper;
58
59     private final RappInstanceStateMachine rappInstanceStateMachine;
60
61     private String amfRegistrationId;
62
63
64     APIProviderEnrolmentDetails createAMF() {
65         APIProviderEnrolmentDetails responseApiEnrollmentDetails = null;
66         try {
67             APIProviderFunctionDetails apiProviderFunctionDetails = new APIProviderFunctionDetails();
68             apiProviderFunctionDetails.setApiProvFuncRole(ApiProviderFuncRole.AMF);
69             apiProviderFunctionDetails.setApiProvFuncInfo("Rapp Manager as AMF");
70             apiProviderFunctionDetails.setRegInfo(new RegistrationInformation().apiProvPubKey("asd"));
71
72             APIProviderEnrolmentDetails apiProviderEnrolmentDetails = new APIProviderEnrolmentDetails();
73             apiProviderEnrolmentDetails.setRegSec("PSK");
74             apiProviderEnrolmentDetails.setApiProvDomInfo("Rapp Manager as AMF");
75             apiProviderEnrolmentDetails.setApiProvFuncs(List.of(apiProviderFunctionDetails));
76             responseApiEnrollmentDetails = providerDefaultApiClient.postRegistrations(apiProviderEnrolmentDetails);
77             amfRegistrationId = responseApiEnrollmentDetails.getApiProvDomId();
78         } catch (Exception e) {
79             logger.warn("Error in creating AMF", e);
80         }
81         return responseApiEnrollmentDetails;
82     }
83
84     void deleteAMF() {
85         deleteProviderFunc(amfRegistrationId);
86     }
87
88     @Override
89     public boolean deployRappInstance(Rapp rapp, RappInstance rappInstance) {
90         logger.debug("Deploying SME functions for RappInstance {}", rappInstance.getRappInstanceId());
91         if (createProviderDomain(rapp, rappInstance) && createPublishApi(rapp, rappInstance) && createInvoker(rapp,
92                 rappInstance)) {
93             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEDEPLOYED);
94             return true;
95         }
96         rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEDEPLOYFAILED);
97         rappInstance.setReason("Unable to deploy SME");
98         return false;
99     }
100
101     @Override
102     public boolean undeployRappInstance(Rapp rapp, RappInstance rappInstance) {
103         logger.debug("Undeploying SME functions for Rapp {}", rapp.getName());
104         try {
105             rappInstance.getSme().getInvokerIds().forEach(this::deleteInvoker);
106             rappInstance.getSme().getServiceApiIds()
107                     .forEach(s -> deletePublishApi(s, rappInstance.getSme().getApfId()));
108             rappInstance.getSme().getProviderFunctionIds().forEach(this::deleteProviderFunc);
109             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEUNDEPLOYED);
110             return true;
111         } catch (Exception e) {
112             logger.warn("Failed to Undeploy SME functions for Rapp {}", rapp.getName(), e);
113         }
114         rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEUNDEPLOYFAILED);
115         rappInstance.setReason("Unable to undeploy SME");
116         return false;
117     }
118
119     @Override
120     public boolean primeRapp(Rapp rapp) {
121         //If there is any priming operations on SME
122         return true;
123     }
124
125     @Override
126     public boolean deprimeRapp(Rapp rapp) {
127         //If there is any depriming operations
128         return true;
129     }
130
131     boolean createProviderDomain(Rapp rapp, RappInstance rappInstance) {
132         logger.debug("Creating provider domain for Rapp {}", rapp.getName());
133         try {
134             String providerDomainPayload =
135                     rappCsarConfigurationHandler.getSmeProviderDomainPayload(rapp, rappInstance.getSme());
136             logger.debug("Provider domain payload {}", providerDomainPayload);
137             if (providerDomainPayload != null) {
138                 APIProviderEnrolmentDetails apiProviderEnrolmentDetails =
139                         objectMapper.readValue(providerDomainPayload, APIProviderEnrolmentDetails.class);
140                 apiProviderEnrolmentDetails.setRegSec(
141                         apiProviderEnrolmentDetails.getRegSec() + rappInstance.getRappInstanceId());
142                 APIProviderEnrolmentDetails responseApiEnrollmentDetails =
143                         providerDefaultApiClient.postRegistrations(apiProviderEnrolmentDetails);
144                 if (responseApiEnrollmentDetails.getApiProvFuncs() != null) {
145                     rappInstance.getSme().setProviderFunctionIds(responseApiEnrollmentDetails.getApiProvFuncs().stream()
146                                                                          .map(APIProviderFunctionDetails::getApiProvFuncId)
147                                                                          .toList());
148
149                     getProviderFuncId(responseApiEnrollmentDetails.getApiProvFuncs(),
150                             ApiProviderFuncRole.APF).ifPresent(apiProviderFunctionDetails -> rappInstance.getSme()
151                                                                                                      .setApfId(
152                                                                                                              apiProviderFunctionDetails.getApiProvFuncId()));
153                     getProviderFuncId(responseApiEnrollmentDetails.getApiProvFuncs(),
154                             ApiProviderFuncRole.AEF).ifPresent(apiProviderFunctionDetails -> rappInstance.getSme()
155                                                                                                      .setAefId(
156                                                                                                              apiProviderFunctionDetails.getApiProvFuncId()));
157                     return true;
158                 }
159             }
160         } catch (Exception e) {
161             logger.warn("Error in creating provider domain", e);
162         }
163         return false;
164     }
165
166     Optional<APIProviderFunctionDetails> getProviderFuncId(List<APIProviderFunctionDetails> apiProviderFunctionDetails,
167             ApiProviderFuncRole apiProviderFuncRole) {
168         return apiProviderFunctionDetails.stream()
169                        .filter(apiProviderFunctionDetail -> apiProviderFunctionDetail.getApiProvFuncRole()
170                                                                     .equals(apiProviderFuncRole)).findFirst();
171     }
172
173     void deleteProviderFunc(String registrationId) {
174         providerDefaultApiClient.deleteRegistrationsRegistrationId(registrationId);
175     }
176
177
178     boolean createPublishApi(Rapp rapp, RappInstance rappInstance) {
179         logger.debug("Creating publish api for Rapp {}", rapp.getName());
180         try {
181             String providerApiPayload =
182                     rappCsarConfigurationHandler.getSmeProviderApiPayload(rapp, rappInstance.getSme());
183             if (providerApiPayload != null) {
184                 ServiceAPIDescription serviceAPIDescription =
185                         objectMapper.readValue(providerApiPayload, ServiceAPIDescription.class);
186                 serviceAPIDescription.getAefProfiles()
187                         .forEach(aefProfile -> aefProfile.setAefId(rappInstance.getSme().getAefId()));
188                 ServiceAPIDescription serviceAPIDescriptionResponse =
189                         publishServiceDefaultApiClient.postApfIdServiceApis(rappInstance.getSme().getApfId(),
190                                 serviceAPIDescription);
191
192                 if (serviceAPIDescriptionResponse.getAefProfiles() != null) {
193                     rappInstance.getSme().setServiceApiIds(List.of(serviceAPIDescriptionResponse.getApiId()));
194                     return true;
195                 }
196             }
197         } catch (Exception e) {
198             logger.warn("Error in creating publish api", e);
199         }
200         return false;
201     }
202
203     void deletePublishApi(String serviceApiId, String apfId) {
204         publishServiceDefaultApiClient.deleteApfIdServiceApisServiceApiId(serviceApiId, apfId);
205     }
206
207     boolean createInvoker(Rapp rapp, RappInstance rappInstance) {
208         logger.debug("Creating provider domain for Rapp {}", rapp.getName());
209         try {
210             String invokerPayload = rappCsarConfigurationHandler.getSmeInvokerPayload(rapp, rappInstance.getSme());
211             if (invokerPayload != null) {
212                 List<APIInvokerEnrolmentDetails> apiInvokerEnrolmentDetails =
213                         objectMapper.readValue(invokerPayload, new TypeReference<>() { });
214                 apiInvokerEnrolmentDetails.forEach(apiInvokerEnrolmentDetail -> {
215                     APIInvokerEnrolmentDetails apiInvokerEnrolmentDetailsResponse =
216                             invokerDefaultApiClient.postOnboardedInvokers(apiInvokerEnrolmentDetail);
217                     if (apiInvokerEnrolmentDetailsResponse.getApiList() != null) {
218                         rappInstance.getSme()
219                                 .setInvokerIds(List.of(apiInvokerEnrolmentDetailsResponse.getApiInvokerId()));
220                     }
221                 });
222                 return true;
223             }
224         } catch (Exception e) {
225             logger.warn("Error in creating invoker", e);
226         }
227         return false;
228     }
229
230     void deleteInvoker(String invokerId) {
231         invokerDefaultApiClient.deleteOnboardedInvokersOnboardingId(invokerId);
232     }
233 }