f2781471fc1fa6e128de52833104fb4087c5f8b4
[nonrtric/plt/sme.git] / capifcore / internal / providermanagement / providermanagement.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package providermanagement
22
23 import (
24         "fmt"
25         "net/http"
26         "path"
27         "strings"
28         "sync"
29
30         "github.com/labstack/echo/v4"
31
32         "oransc.org/nonrtric/capifcore/internal/common29122"
33         provapi "oransc.org/nonrtric/capifcore/internal/providermanagementapi"
34
35         log "github.com/sirupsen/logrus"
36 )
37
38 //go:generate mockery --name ServiceRegister
39 type ServiceRegister interface {
40         IsFunctionRegistered(functionId string) bool
41         GetAefsForPublisher(apfId string) []string
42 }
43
44 type ProviderManager struct {
45         onboardedProviders map[string]provapi.APIProviderEnrolmentDetails
46         lock               sync.Mutex
47 }
48
49 func NewProviderManager() *ProviderManager {
50         return &ProviderManager{
51                 onboardedProviders: make(map[string]provapi.APIProviderEnrolmentDetails),
52         }
53 }
54
55 func (pm *ProviderManager) IsFunctionRegistered(functionId string) bool {
56         registered := false
57 out:
58         for _, provider := range pm.onboardedProviders {
59                 for _, registeredFunc := range *provider.ApiProvFuncs {
60                         if *registeredFunc.ApiProvFuncId == functionId {
61                                 registered = true
62                                 break out
63                         }
64                 }
65         }
66
67         return registered
68 }
69
70 func (pm *ProviderManager) GetAefsForPublisher(apfId string) []string {
71         for _, provider := range pm.onboardedProviders {
72                 for _, registeredFunc := range *provider.ApiProvFuncs {
73                         if *registeredFunc.ApiProvFuncId == apfId && registeredFunc.ApiProvFuncRole == provapi.ApiProviderFuncRoleAPF {
74                                 return getExposedFuncs(provider.ApiProvFuncs)
75                         }
76                 }
77         }
78         return nil
79 }
80
81 func getExposedFuncs(providerFuncs *[]provapi.APIProviderFunctionDetails) []string {
82         exposedFuncs := []string{}
83         for _, registeredFunc := range *providerFuncs {
84                 if registeredFunc.ApiProvFuncRole == provapi.ApiProviderFuncRoleAEF {
85                         exposedFuncs = append(exposedFuncs, *registeredFunc.ApiProvFuncId)
86                 }
87         }
88         return exposedFuncs
89 }
90
91 func (pm *ProviderManager) PostRegistrations(ctx echo.Context) error {
92         var newProvider provapi.APIProviderEnrolmentDetails
93         err := ctx.Bind(&newProvider)
94         if err != nil {
95                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for provider")
96         }
97
98         if newProvider.ApiProvDomInfo == nil || *newProvider.ApiProvDomInfo == "" {
99                 return sendCoreError(ctx, http.StatusBadRequest, "Provider missing required ApiProvDomInfo")
100         }
101
102         pm.prepareNewProvider(&newProvider)
103
104         uri := ctx.Request().Host + ctx.Request().URL.String()
105         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newProvider.ApiProvDomId))
106         err = ctx.JSON(http.StatusCreated, newProvider)
107         if err != nil {
108                 // Something really bad happened, tell Echo that our handler failed
109                 return err
110         }
111
112         return nil
113 }
114
115 func (pm *ProviderManager) prepareNewProvider(newProvider *provapi.APIProviderEnrolmentDetails) {
116         pm.lock.Lock()
117         defer pm.lock.Unlock()
118
119         newProvider.ApiProvDomId = pm.getDomainId(newProvider.ApiProvDomInfo)
120
121         pm.registerFunctions(newProvider.ApiProvFuncs)
122         pm.onboardedProviders[*newProvider.ApiProvDomId] = *newProvider
123 }
124
125 func (pm *ProviderManager) DeleteRegistrationsRegistrationId(ctx echo.Context, registrationId string) error {
126
127         log.Debug(pm.onboardedProviders)
128         if _, ok := pm.onboardedProviders[registrationId]; ok {
129                 log.Debug("Deleting provider", registrationId)
130                 pm.lock.Lock()
131                 delete(pm.onboardedProviders, registrationId)
132                 pm.lock.Unlock()
133         }
134
135         return ctx.NoContent(http.StatusNoContent)
136 }
137
138 func (pm *ProviderManager) PutRegistrationsRegistrationId(ctx echo.Context, registrationId string) error {
139         pm.lock.Lock()
140         defer pm.lock.Unlock()
141
142         errMsg := "Unable to update provider due to %s."
143         registeredProvider, err := pm.checkIfProviderIsRegistered(registrationId, ctx)
144         if err != nil {
145                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
146         }
147
148         updatedProvider, err := getProviderFromRequest(ctx)
149         if err != nil {
150                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
151         }
152
153         updateDomainInfo(&updatedProvider, registeredProvider)
154
155         registeredProvider.ApiProvFuncs, err = updateFuncs(updatedProvider.ApiProvFuncs, registeredProvider.ApiProvFuncs)
156         if err != nil {
157                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
158         }
159
160         pm.onboardedProviders[*registeredProvider.ApiProvDomId] = *registeredProvider
161         err = ctx.JSON(http.StatusOK, *registeredProvider)
162         if err != nil {
163                 // Something really bad happened, tell Echo that our handler failed
164                 return err
165         }
166
167         return nil
168 }
169
170 func (pm *ProviderManager) checkIfProviderIsRegistered(registrationId string, ctx echo.Context) (*provapi.APIProviderEnrolmentDetails, error) {
171         registeredProvider, ok := pm.onboardedProviders[registrationId]
172         if !ok {
173                 return nil, fmt.Errorf("provider not onboarded")
174         }
175         return &registeredProvider, nil
176 }
177
178 func getProviderFromRequest(ctx echo.Context) (provapi.APIProviderEnrolmentDetails, error) {
179         var updatedProvider provapi.APIProviderEnrolmentDetails
180         err := ctx.Bind(&updatedProvider)
181         if err != nil {
182                 return provapi.APIProviderEnrolmentDetails{}, fmt.Errorf("invalid format for provider")
183         }
184         return updatedProvider, nil
185 }
186
187 func updateDomainInfo(updatedProvider, registeredProvider *provapi.APIProviderEnrolmentDetails) {
188         if updatedProvider.ApiProvDomInfo != nil {
189                 registeredProvider.ApiProvDomInfo = updatedProvider.ApiProvDomInfo
190         }
191 }
192
193 func updateFuncs(updatedFuncs, registeredFuncs *[]provapi.APIProviderFunctionDetails) (*[]provapi.APIProviderFunctionDetails, error) {
194         addedFuncs := []provapi.APIProviderFunctionDetails{}
195         changedFuncs := []provapi.APIProviderFunctionDetails{}
196         for _, function := range *updatedFuncs {
197                 if function.ApiProvFuncId == nil {
198                         function.ApiProvFuncId = getFuncId(function.ApiProvFuncRole, function.ApiProvFuncInfo)
199                         addedFuncs = append(addedFuncs, function)
200                 } else {
201                         registeredFunction, ok := getApiFunc(*function.ApiProvFuncId, registeredFuncs)
202                         if !ok {
203                                 return nil, fmt.Errorf("function with ID %s is not registered for the provider", *function.ApiProvFuncId)
204                         }
205                         if function.ApiProvFuncInfo != nil {
206                                 registeredFunction.ApiProvFuncInfo = function.ApiProvFuncInfo
207                         }
208                         changedFuncs = append(changedFuncs, function)
209                 }
210         }
211         modifiedFuncs := append(changedFuncs, addedFuncs...)
212         return &modifiedFuncs, nil
213 }
214
215 func getApiFunc(funcId string, apiFunctions *[]provapi.APIProviderFunctionDetails) (provapi.APIProviderFunctionDetails, bool) {
216         for _, function := range *apiFunctions {
217                 if *function.ApiProvFuncId == funcId {
218                         return function, true
219                 }
220         }
221         return provapi.APIProviderFunctionDetails{}, false
222 }
223
224 func (pm *ProviderManager) ModifyIndApiProviderEnrolment(ctx echo.Context, registrationId string) error {
225         return ctx.NoContent(http.StatusNotImplemented)
226 }
227
228 func (pm *ProviderManager) registerFunctions(provFuncs *[]provapi.APIProviderFunctionDetails) {
229         if provFuncs == nil {
230                 return
231         }
232         for i, provFunc := range *provFuncs {
233                 (*provFuncs)[i].ApiProvFuncId = getFuncId(provFunc.ApiProvFuncRole, provFunc.ApiProvFuncInfo)
234         }
235 }
236
237 func (pm *ProviderManager) getDomainId(domainInfo *string) *string {
238         idAsString := "domain_id_" + strings.ReplaceAll(*domainInfo, " ", "_")
239         return &idAsString
240 }
241
242 func getFuncId(role provapi.ApiProviderFuncRole, funcInfo *string) *string {
243         var idPrefix string
244         switch role {
245         case provapi.ApiProviderFuncRoleAPF:
246                 idPrefix = "APF_id_"
247         case provapi.ApiProviderFuncRoleAMF:
248                 idPrefix = "AMF_id_"
249         case provapi.ApiProviderFuncRoleAEF:
250                 idPrefix = "AEF_id_"
251         default:
252                 idPrefix = "function_id_"
253         }
254         idAsString := idPrefix + strings.ReplaceAll(*funcInfo, " ", "_")
255         return &idAsString
256 }
257
258 // This function wraps sending of an error in the Error format, and
259 // handling the failure to marshal that.
260 func sendCoreError(ctx echo.Context, code int, message string) error {
261         pd := common29122.ProblemDetails{
262                 Cause:  &message,
263                 Status: &code,
264         }
265         err := ctx.JSON(code, pd)
266         return err
267 }