Support for optional rApp and rApp instance parameters
[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 (rappInstance.isSMEEnabled()) {
92             if (createProviderDomain(rapp, rappInstance) && createPublishApi(rapp, rappInstance) && createInvoker(rapp,
93                     rappInstance)) {
94                 rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEDEPLOYED);
95                 return true;
96             }
97             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEDEPLOYFAILED);
98             rappInstance.setReason("Unable to deploy SME");
99             return false;
100         }
101         return true;
102     }
103
104     @Override
105     public boolean undeployRappInstance(Rapp rapp, RappInstance rappInstance) {
106         logger.debug("Undeploying SME functions for Rapp {}", rapp.getName());
107         if (rappInstance.isSMEEnabled()) {
108             try {
109                 rappInstance.getSme().getInvokerIds().forEach(this::deleteInvoker);
110                 rappInstance.getSme().getServiceApiIds()
111                         .forEach(s -> deletePublishApi(s, rappInstance.getSme().getApfId()));
112                 rappInstance.getSme().getProviderFunctionIds().forEach(this::deleteProviderFunc);
113                 rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEUNDEPLOYED);
114                 return true;
115             } catch (Exception e) {
116                 logger.warn("Failed to Undeploy SME functions for Rapp {}", rapp.getName(), e);
117             }
118             rappInstanceStateMachine.sendRappInstanceEvent(rappInstance, RappEvent.SMEUNDEPLOYFAILED);
119             rappInstance.setReason("Unable to undeploy SME");
120             return false;
121         }
122         return true;
123     }
124
125     @Override
126     public boolean primeRapp(Rapp rapp) {
127         //If there is any priming operations on SME
128         return true;
129     }
130
131     @Override
132     public boolean deprimeRapp(Rapp rapp) {
133         //If there is any depriming operations
134         return true;
135     }
136
137     boolean createProviderDomain(Rapp rapp, RappInstance rappInstance) {
138         logger.debug("Creating provider domain for Rapp {}", rapp.getName());
139         try {
140             String providerDomainPayload =
141                     rappCsarConfigurationHandler.getSmeProviderDomainPayload(rapp, rappInstance.getSme());
142             logger.debug("Provider domain payload {}", providerDomainPayload);
143             if (providerDomainPayload != null) {
144                 APIProviderEnrolmentDetails apiProviderEnrolmentDetails =
145                         objectMapper.readValue(providerDomainPayload, APIProviderEnrolmentDetails.class);
146                 apiProviderEnrolmentDetails.setRegSec(
147                         apiProviderEnrolmentDetails.getRegSec() + rappInstance.getRappInstanceId());
148                 APIProviderEnrolmentDetails responseApiEnrollmentDetails =
149                         providerDefaultApiClient.postRegistrations(apiProviderEnrolmentDetails);
150                 if (responseApiEnrollmentDetails.getApiProvFuncs() != null) {
151                     rappInstance.getSme().setProviderFunctionIds(responseApiEnrollmentDetails.getApiProvFuncs().stream()
152                                                                          .map(APIProviderFunctionDetails::getApiProvFuncId)
153                                                                          .toList());
154
155                     getProviderFuncId(responseApiEnrollmentDetails.getApiProvFuncs(),
156                             ApiProviderFuncRole.APF).ifPresent(apiProviderFunctionDetails -> rappInstance.getSme()
157                                                                                                      .setApfId(
158                                                                                                              apiProviderFunctionDetails.getApiProvFuncId()));
159                     getProviderFuncId(responseApiEnrollmentDetails.getApiProvFuncs(),
160                             ApiProviderFuncRole.AEF).ifPresent(apiProviderFunctionDetails -> rappInstance.getSme()
161                                                                                                      .setAefId(
162                                                                                                              apiProviderFunctionDetails.getApiProvFuncId()));
163                     return true;
164                 }
165             }
166         } catch (Exception e) {
167             logger.warn("Error in creating provider domain", e);
168         }
169         return false;
170     }
171
172     Optional<APIProviderFunctionDetails> getProviderFuncId(List<APIProviderFunctionDetails> apiProviderFunctionDetails,
173             ApiProviderFuncRole apiProviderFuncRole) {
174         return apiProviderFunctionDetails.stream()
175                        .filter(apiProviderFunctionDetail -> apiProviderFunctionDetail.getApiProvFuncRole()
176                                                                     .equals(apiProviderFuncRole)).findFirst();
177     }
178
179     void deleteProviderFunc(String registrationId) {
180         providerDefaultApiClient.deleteRegistrationsRegistrationId(registrationId);
181     }
182
183
184     boolean createPublishApi(Rapp rapp, RappInstance rappInstance) {
185         logger.debug("Creating publish api for Rapp {}", rapp.getName());
186         try {
187             String providerApiPayload =
188                     rappCsarConfigurationHandler.getSmeProviderApiPayload(rapp, rappInstance.getSme());
189             if (providerApiPayload != null) {
190                 ServiceAPIDescription serviceAPIDescription =
191                         objectMapper.readValue(providerApiPayload, ServiceAPIDescription.class);
192                 serviceAPIDescription.getAefProfiles()
193                         .forEach(aefProfile -> aefProfile.setAefId(rappInstance.getSme().getAefId()));
194                 ServiceAPIDescription serviceAPIDescriptionResponse =
195                         publishServiceDefaultApiClient.postApfIdServiceApis(rappInstance.getSme().getApfId(),
196                                 serviceAPIDescription);
197
198                 if (serviceAPIDescriptionResponse.getAefProfiles() != null) {
199                     rappInstance.getSme().setServiceApiIds(List.of(serviceAPIDescriptionResponse.getApiId()));
200                     return true;
201                 }
202             }
203         } catch (Exception e) {
204             logger.warn("Error in creating publish api", e);
205         }
206         return false;
207     }
208
209     void deletePublishApi(String serviceApiId, String apfId) {
210         publishServiceDefaultApiClient.deleteApfIdServiceApisServiceApiId(serviceApiId, apfId);
211     }
212
213     boolean createInvoker(Rapp rapp, RappInstance rappInstance) {
214         logger.debug("Creating provider domain for Rapp {}", rapp.getName());
215         try {
216             String invokerPayload = rappCsarConfigurationHandler.getSmeInvokerPayload(rapp, rappInstance.getSme());
217             if (invokerPayload != null) {
218                 List<APIInvokerEnrolmentDetails> apiInvokerEnrolmentDetails =
219                         objectMapper.readValue(invokerPayload, new TypeReference<>() { });
220                 apiInvokerEnrolmentDetails.forEach(apiInvokerEnrolmentDetail -> {
221                     APIInvokerEnrolmentDetails apiInvokerEnrolmentDetailsResponse =
222                             invokerDefaultApiClient.postOnboardedInvokers(apiInvokerEnrolmentDetail);
223                     if (apiInvokerEnrolmentDetailsResponse.getApiList() != null) {
224                         rappInstance.getSme()
225                                 .setInvokerIds(List.of(apiInvokerEnrolmentDetailsResponse.getApiInvokerId()));
226                     }
227                 });
228                 return true;
229             }
230         } catch (Exception e) {
231             logger.warn("Error in creating invoker", e);
232         }
233         return false;
234     }
235
236     void deleteInvoker(String invokerId) {
237         invokerDefaultApiClient.deleteOnboardedInvokersOnboardingId(invokerId);
238     }
239 }