Add event handling to invokermanagement
[nonrtric/plt/sme.git] / capifcore / internal / invokermanagement / invokermanagement.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 invokermanagement
22
23 import (
24         "net/http"
25         "path"
26         "strconv"
27         "strings"
28         "sync"
29
30         "oransc.org/nonrtric/capifcore/internal/eventsapi"
31         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
32
33         "oransc.org/nonrtric/capifcore/internal/common29122"
34         invokerapi "oransc.org/nonrtric/capifcore/internal/invokermanagementapi"
35
36         "oransc.org/nonrtric/capifcore/internal/publishservice"
37
38         "github.com/labstack/echo/v4"
39 )
40
41 //go:generate mockery --name InvokerRegister
42 type InvokerRegister interface {
43         // Checks if the invoker is registered.
44         // Returns true of the provided invoker is registered, false otherwise.
45         IsInvokerRegistered(invokerId string) bool
46         // Verifies that the provided secret is the invoker's registered secret.
47         // Returns true if the provided secret is the registered invoker's secret, false otherwise.
48         VerifyInvokerSecret(invokerId, secret string) bool
49         // Gets the provided invoker's registered APIs.
50         // Returns a list of all the invoker's registered APIs.
51         GetInvokerApiList(invokerId string) *invokerapi.APIList
52 }
53
54 type InvokerManager struct {
55         onboardedInvokers map[string]invokerapi.APIInvokerEnrolmentDetails
56         publishRegister   publishservice.PublishRegister
57         nextId            int64
58         eventChannel      chan<- eventsapi.EventNotification
59         lock              sync.Mutex
60 }
61
62 // Creates a manager that implements both the InvokerRegister and the invokermanagementapi.ServerInterface interfaces.
63 func NewInvokerManager(publishRegister publishservice.PublishRegister, eventChannel chan<- eventsapi.EventNotification) *InvokerManager {
64         return &InvokerManager{
65                 onboardedInvokers: make(map[string]invokerapi.APIInvokerEnrolmentDetails),
66                 publishRegister:   publishRegister,
67                 nextId:            1000,
68                 eventChannel:      eventChannel,
69         }
70 }
71
72 func (im *InvokerManager) IsInvokerRegistered(invokerId string) bool {
73         im.lock.Lock()
74         defer im.lock.Unlock()
75
76         _, registered := im.onboardedInvokers[invokerId]
77         return registered
78 }
79
80 func (im *InvokerManager) VerifyInvokerSecret(invokerId, secret string) bool {
81         im.lock.Lock()
82         defer im.lock.Unlock()
83
84         verified := false
85         if invoker, registered := im.onboardedInvokers[invokerId]; registered {
86                 verified = *invoker.OnboardingInformation.OnboardingSecret == secret
87         }
88         return verified
89 }
90
91 func (im *InvokerManager) GetInvokerApiList(invokerId string) *invokerapi.APIList {
92         invoker, ok := im.onboardedInvokers[invokerId]
93         if ok {
94                 var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
95                 im.lock.Lock()
96                 defer im.lock.Unlock()
97                 invoker.ApiList = &apiList
98                 return &apiList
99         }
100         return nil
101 }
102
103 // Creates a new individual API Invoker profile.
104 func (im *InvokerManager) PostOnboardedInvokers(ctx echo.Context) error {
105         var newInvoker invokerapi.APIInvokerEnrolmentDetails
106         err := ctx.Bind(&newInvoker)
107         if err != nil {
108                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for invoker")
109         }
110
111         shouldReturn, coreError := im.validateInvoker(newInvoker, ctx)
112         if shouldReturn {
113                 return coreError
114         }
115
116         im.lock.Lock()
117         defer im.lock.Unlock()
118
119         newInvoker.ApiInvokerId = im.getId(newInvoker.ApiInvokerInformation)
120         onboardingSecret := "onboarding_secret_"
121         if newInvoker.ApiInvokerInformation != nil {
122                 onboardingSecret = onboardingSecret + strings.ReplaceAll(*newInvoker.ApiInvokerInformation, " ", "_")
123         } else {
124                 onboardingSecret = onboardingSecret + *newInvoker.ApiInvokerId
125         }
126         newInvoker.OnboardingInformation.OnboardingSecret = &onboardingSecret
127
128         var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
129         newInvoker.ApiList = &apiList
130
131         im.onboardedInvokers[*newInvoker.ApiInvokerId] = newInvoker
132         go im.sendEvent(*newInvoker.ApiInvokerId, eventsapi.CAPIFEventAPIINVOKERONBOARDED)
133
134         uri := ctx.Request().Host + ctx.Request().URL.String()
135         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newInvoker.ApiInvokerId))
136         err = ctx.JSON(http.StatusCreated, newInvoker)
137         if err != nil {
138                 // Something really bad happened, tell Echo that our handler failed
139                 return err
140         }
141
142         return nil
143 }
144
145 // Deletes an individual API Invoker.
146 func (im *InvokerManager) DeleteOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
147         im.lock.Lock()
148         defer im.lock.Unlock()
149
150         delete(im.onboardedInvokers, onboardingId)
151         go im.sendEvent(onboardingId, eventsapi.CAPIFEventAPIINVOKEROFFBOARDED)
152
153         return ctx.NoContent(http.StatusNoContent)
154 }
155
156 // Updates an individual API invoker details.
157 func (im *InvokerManager) PutOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
158         var invoker invokerapi.APIInvokerEnrolmentDetails
159         err := ctx.Bind(&invoker)
160         if err != nil {
161                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for invoker")
162         }
163
164         if onboardingId != *invoker.ApiInvokerId {
165                 return sendCoreError(ctx, http.StatusBadRequest, "Invoker ApiInvokerId not matching")
166         }
167
168         shouldReturn, coreError := im.validateInvoker(invoker, ctx)
169         if shouldReturn {
170                 return coreError
171         }
172
173         im.lock.Lock()
174         defer im.lock.Unlock()
175
176         if _, ok := im.onboardedInvokers[onboardingId]; ok {
177                 im.onboardedInvokers[*invoker.ApiInvokerId] = invoker
178         } else {
179                 return sendCoreError(ctx, http.StatusNotFound, "The invoker to update has not been onboarded")
180         }
181
182         err = ctx.JSON(http.StatusOK, invoker)
183         if err != nil {
184                 // Something really bad happened, tell Echo that our handler failed
185                 return err
186         }
187
188         return nil
189 }
190
191 func (im *InvokerManager) ModifyIndApiInvokeEnrolment(ctx echo.Context, onboardingId string) error {
192         return ctx.NoContent(http.StatusNotImplemented)
193 }
194
195 func (im *InvokerManager) validateInvoker(invoker invokerapi.APIInvokerEnrolmentDetails, ctx echo.Context) (bool, error) {
196         if invoker.NotificationDestination == "" {
197                 return true, sendCoreError(ctx, http.StatusBadRequest, "Invoker missing required NotificationDestination")
198         }
199
200         if invoker.OnboardingInformation.ApiInvokerPublicKey == "" {
201                 return true, sendCoreError(ctx, http.StatusBadRequest, "Invoker missing required OnboardingInformation.ApiInvokerPublicKey")
202         }
203
204         if !im.areAPIsPublished(invoker.ApiList) {
205                 return true, sendCoreError(ctx, http.StatusBadRequest, "Some APIs needed by invoker are not registered")
206         }
207
208         return false, nil
209 }
210
211 func (im *InvokerManager) areAPIsPublished(apis *invokerapi.APIList) bool {
212         if apis == nil {
213                 return true
214         }
215         return im.publishRegister.AreAPIsPublished((*[]publishapi.ServiceAPIDescription)(apis))
216 }
217
218 func (im *InvokerManager) getId(invokerInfo *string) *string {
219         idAsString := "api_invoker_id_"
220         if invokerInfo != nil {
221                 idAsString = idAsString + strings.ReplaceAll(*invokerInfo, " ", "_")
222         } else {
223                 idAsString = idAsString + strconv.FormatInt(im.nextId, 10)
224                 im.nextId = im.nextId + 1
225         }
226         return &idAsString
227 }
228
229 func (im *InvokerManager) sendEvent(invokerId string, eventType eventsapi.CAPIFEvent) {
230         invokerIds := []string{invokerId}
231         event := eventsapi.EventNotification{
232                 EventDetail: &eventsapi.CAPIFEventDetail{
233                         ApiInvokerIds: &invokerIds,
234                 },
235                 Events: eventType,
236         }
237         im.eventChannel <- event
238 }
239
240 // This function wraps sending of an error in the Error format, and
241 // handling the failure to marshal that.
242 func sendCoreError(ctx echo.Context, code int, message string) error {
243         pd := common29122.ProblemDetails{
244                 Cause:  &message,
245                 Status: &code,
246         }
247         err := ctx.JSON(code, pd)
248         return err
249 }