Refactor providermaagement
[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         "sync"
28
29         "github.com/labstack/echo/v4"
30
31         "oransc.org/nonrtric/capifcore/internal/common29122"
32         provapi "oransc.org/nonrtric/capifcore/internal/providermanagementapi"
33
34         log "github.com/sirupsen/logrus"
35 )
36
37 //go:generate mockery --name ServiceRegister
38 type ServiceRegister interface {
39         IsFunctionRegistered(functionId string) bool
40         GetAefsForPublisher(apfId string) []string
41 }
42
43 type ProviderManager struct {
44         registeredProviders map[string]provapi.APIProviderEnrolmentDetails
45         lock                sync.Mutex
46 }
47
48 func NewProviderManager() *ProviderManager {
49         return &ProviderManager{
50                 registeredProviders: make(map[string]provapi.APIProviderEnrolmentDetails),
51         }
52 }
53
54 func (pm *ProviderManager) IsFunctionRegistered(functionId string) bool {
55         for _, provider := range pm.registeredProviders {
56                 if provider.IsFunctionRegistered(functionId) {
57                         return true
58                 }
59         }
60         return false
61 }
62
63 func (pm *ProviderManager) GetAefsForPublisher(apfId string) []string {
64         for _, provider := range pm.registeredProviders {
65                 if aefs := provider.GetExposingFunctionIdsForPublisher(apfId); aefs != nil {
66                         return aefs
67                 }
68         }
69         return nil
70 }
71
72 func (pm *ProviderManager) PostRegistrations(ctx echo.Context) error {
73         var newProvider provapi.APIProviderEnrolmentDetails
74         if err := ctx.Bind(&newProvider); err != nil {
75                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for provider")
76         }
77
78         if err := newProvider.Validate(); err != nil {
79                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Provider not valid due to %s", err))
80         }
81
82         pm.prepareNewProvider(&newProvider)
83
84         uri := ctx.Request().Host + ctx.Request().URL.String()
85         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newProvider.ApiProvDomId))
86         if err := ctx.JSON(http.StatusCreated, newProvider); err != nil {
87                 // Something really bad happened, tell Echo that our handler failed
88                 return err
89         }
90         return nil
91 }
92
93 func (pm *ProviderManager) prepareNewProvider(newProvider *provapi.APIProviderEnrolmentDetails) {
94         pm.lock.Lock()
95         defer pm.lock.Unlock()
96
97         newProvider.PrepareNewProvider()
98         pm.registeredProviders[*newProvider.ApiProvDomId] = *newProvider
99 }
100
101 func (pm *ProviderManager) DeleteRegistrationsRegistrationId(ctx echo.Context, registrationId string) error {
102         log.Debug(pm.registeredProviders)
103         if _, ok := pm.registeredProviders[registrationId]; ok {
104                 pm.deleteProvider(registrationId)
105         }
106         return ctx.NoContent(http.StatusNoContent)
107 }
108
109 func (pm *ProviderManager) deleteProvider(registrationId string) {
110         log.Debug("Deleting provider", registrationId)
111         pm.lock.Lock()
112         defer pm.lock.Unlock()
113         delete(pm.registeredProviders, registrationId)
114 }
115
116 func (pm *ProviderManager) PutRegistrationsRegistrationId(ctx echo.Context, registrationId string) error {
117         errMsg := "Unable to update provider due to %s."
118         registeredProvider, err := pm.checkIfProviderIsRegistered(registrationId, ctx)
119         if err != nil {
120                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
121         }
122
123         updatedProvider, err := getProviderFromRequest(ctx)
124         if err != nil {
125                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
126         }
127
128         if updatedProvider.Validate() != nil {
129                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
130         }
131
132         if err = pm.updateProvider(updatedProvider, registeredProvider); err != nil {
133                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
134         }
135
136         if err = ctx.JSON(http.StatusOK, updatedProvider); err != nil {
137                 // Something really bad happened, tell Echo that our handler failed
138                 return err
139         }
140         return nil
141 }
142
143 func (pm *ProviderManager) ModifyIndApiProviderEnrolment(ctx echo.Context, registrationId string) error {
144         return ctx.NoContent(http.StatusNotImplemented)
145 }
146
147 func (pm *ProviderManager) checkIfProviderIsRegistered(registrationId string, ctx echo.Context) (*provapi.APIProviderEnrolmentDetails, error) {
148         registeredProvider, ok := pm.registeredProviders[registrationId]
149         if !ok {
150                 return nil, fmt.Errorf("provider not onboarded")
151         }
152         return &registeredProvider, nil
153 }
154
155 func getProviderFromRequest(ctx echo.Context) (provapi.APIProviderEnrolmentDetails, error) {
156         var updatedProvider provapi.APIProviderEnrolmentDetails
157         err := ctx.Bind(&updatedProvider)
158         if err != nil {
159                 return provapi.APIProviderEnrolmentDetails{}, fmt.Errorf("invalid format for provider")
160         }
161         return updatedProvider, nil
162 }
163
164 func (pm *ProviderManager) updateProvider(updatedProvider provapi.APIProviderEnrolmentDetails, registeredProvider *provapi.APIProviderEnrolmentDetails) error {
165         pm.lock.Lock()
166         defer pm.lock.Unlock()
167
168         if err := updatedProvider.UpdateFuncs(*registeredProvider); err == nil {
169                 pm.registeredProviders[*updatedProvider.ApiProvDomId] = updatedProvider
170                 return nil
171         } else {
172                 return err
173         }
174 }
175
176 // This function wraps sending of an error in the Error format, and
177 // handling the failure to marshal that.
178 func sendCoreError(ctx echo.Context, code int, message string) error {
179         pd := common29122.ProblemDetails{
180                 Cause:  &message,
181                 Status: &code,
182         }
183         err := ctx.JSON(code, pd)
184         return err
185 }