Improve locking
[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                 pm.deleteProvider(registrationId)
130         }
131
132         return ctx.NoContent(http.StatusNoContent)
133 }
134
135 func (pm *ProviderManager) deleteProvider(registrationId string) {
136         log.Debug("Deleting provider", registrationId)
137         pm.lock.Lock()
138         defer pm.lock.Unlock()
139         delete(pm.onboardedProviders, registrationId)
140 }
141
142 func (pm *ProviderManager) PutRegistrationsRegistrationId(ctx echo.Context, registrationId string) error {
143         pm.lock.Lock()
144         defer pm.lock.Unlock()
145
146         errMsg := "Unable to update provider due to %s."
147         registeredProvider, err := pm.checkIfProviderIsRegistered(registrationId, ctx)
148         if err != nil {
149                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
150         }
151
152         updatedProvider, err := getProviderFromRequest(ctx)
153         if err != nil {
154                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
155         }
156
157         updateDomainInfo(&updatedProvider, registeredProvider)
158
159         registeredProvider.ApiProvFuncs, err = updateFuncs(updatedProvider.ApiProvFuncs, registeredProvider.ApiProvFuncs)
160         if err != nil {
161                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
162         }
163
164         pm.onboardedProviders[*registeredProvider.ApiProvDomId] = *registeredProvider
165         err = ctx.JSON(http.StatusOK, *registeredProvider)
166         if err != nil {
167                 // Something really bad happened, tell Echo that our handler failed
168                 return err
169         }
170
171         return nil
172 }
173
174 func (pm *ProviderManager) checkIfProviderIsRegistered(registrationId string, ctx echo.Context) (*provapi.APIProviderEnrolmentDetails, error) {
175         registeredProvider, ok := pm.onboardedProviders[registrationId]
176         if !ok {
177                 return nil, fmt.Errorf("provider not onboarded")
178         }
179         return &registeredProvider, nil
180 }
181
182 func getProviderFromRequest(ctx echo.Context) (provapi.APIProviderEnrolmentDetails, error) {
183         var updatedProvider provapi.APIProviderEnrolmentDetails
184         err := ctx.Bind(&updatedProvider)
185         if err != nil {
186                 return provapi.APIProviderEnrolmentDetails{}, fmt.Errorf("invalid format for provider")
187         }
188         return updatedProvider, nil
189 }
190
191 func updateDomainInfo(updatedProvider, registeredProvider *provapi.APIProviderEnrolmentDetails) {
192         if updatedProvider.ApiProvDomInfo != nil {
193                 registeredProvider.ApiProvDomInfo = updatedProvider.ApiProvDomInfo
194         }
195 }
196
197 func updateFuncs(updatedFuncs, registeredFuncs *[]provapi.APIProviderFunctionDetails) (*[]provapi.APIProviderFunctionDetails, error) {
198         addedFuncs := []provapi.APIProviderFunctionDetails{}
199         changedFuncs := []provapi.APIProviderFunctionDetails{}
200         for _, function := range *updatedFuncs {
201                 if function.ApiProvFuncId == nil {
202                         function.ApiProvFuncId = getFuncId(function.ApiProvFuncRole, function.ApiProvFuncInfo)
203                         addedFuncs = append(addedFuncs, function)
204                 } else {
205                         registeredFunction, ok := getApiFunc(*function.ApiProvFuncId, registeredFuncs)
206                         if !ok {
207                                 return nil, fmt.Errorf("function with ID %s is not registered for the provider", *function.ApiProvFuncId)
208                         }
209                         if function.ApiProvFuncInfo != nil {
210                                 registeredFunction.ApiProvFuncInfo = function.ApiProvFuncInfo
211                         }
212                         changedFuncs = append(changedFuncs, function)
213                 }
214         }
215         modifiedFuncs := append(changedFuncs, addedFuncs...)
216         return &modifiedFuncs, nil
217 }
218
219 func getApiFunc(funcId string, apiFunctions *[]provapi.APIProviderFunctionDetails) (provapi.APIProviderFunctionDetails, bool) {
220         for _, function := range *apiFunctions {
221                 if *function.ApiProvFuncId == funcId {
222                         return function, true
223                 }
224         }
225         return provapi.APIProviderFunctionDetails{}, false
226 }
227
228 func (pm *ProviderManager) ModifyIndApiProviderEnrolment(ctx echo.Context, registrationId string) error {
229         return ctx.NoContent(http.StatusNotImplemented)
230 }
231
232 func (pm *ProviderManager) registerFunctions(provFuncs *[]provapi.APIProviderFunctionDetails) {
233         if provFuncs == nil {
234                 return
235         }
236         for i, provFunc := range *provFuncs {
237                 (*provFuncs)[i].ApiProvFuncId = getFuncId(provFunc.ApiProvFuncRole, provFunc.ApiProvFuncInfo)
238         }
239 }
240
241 func (pm *ProviderManager) getDomainId(domainInfo *string) *string {
242         idAsString := "domain_id_" + strings.ReplaceAll(*domainInfo, " ", "_")
243         return &idAsString
244 }
245
246 func getFuncId(role provapi.ApiProviderFuncRole, funcInfo *string) *string {
247         var idPrefix string
248         switch role {
249         case provapi.ApiProviderFuncRoleAPF:
250                 idPrefix = "APF_id_"
251         case provapi.ApiProviderFuncRoleAMF:
252                 idPrefix = "AMF_id_"
253         case provapi.ApiProviderFuncRoleAEF:
254                 idPrefix = "AEF_id_"
255         default:
256                 idPrefix = "function_id_"
257         }
258         idAsString := idPrefix + strings.ReplaceAll(*funcInfo, " ", "_")
259         return &idAsString
260 }
261
262 // This function wraps sending of an error in the Error format, and
263 // handling the failure to marshal that.
264 func sendCoreError(ctx echo.Context, code int, message string) error {
265         pd := common29122.ProblemDetails{
266                 Cause:  &message,
267                 Status: &code,
268         }
269         err := ctx.JSON(code, pd)
270         return err
271 }