372b1f8ff3a397099d1d73d9c47f05e64ffa2be4
[nonrtric/plt/sme.git] / capifcore / internal / publishservice / publishservice.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022-2023: Nordix Foundation
6 //   Copyright (C) 2024: OpenInfra Foundation Europe
7 //   %%
8 //   Licensed under the Apache License, Version 2.0 (the "License");
9 //   you may not use this file except in compliance with the License.
10 //   You may obtain a copy of the License at
11 //
12 //        http://www.apache.org/licenses/LICENSE-2.0
13 //
14 //   Unless required by applicable law or agreed to in writing, software
15 //   distributed under the License is distributed on an "AS IS" BASIS,
16 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 //   See the License for the specific language governing permissions and
18 //   limitations under the License.
19 //   ========================LICENSE_END===================================
20 //
21
22 package publishservice
23
24 import (
25         "fmt"
26         "net/http"
27         "path"
28         "strings"
29         "sync"
30
31         echo "github.com/labstack/echo/v4"
32         "k8s.io/utils/strings/slices"
33
34         "oransc.org/nonrtric/capifcore/internal/common29122"
35         "oransc.org/nonrtric/capifcore/internal/eventsapi"
36         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
37
38         "oransc.org/nonrtric/capifcore/internal/helmmanagement"
39         "oransc.org/nonrtric/capifcore/internal/providermanagement"
40
41         log "github.com/sirupsen/logrus"
42 )
43
44 //go:generate mockery --name PublishRegister
45 type PublishRegister interface {
46         // Checks if the provided API is published.
47         // Returns true if the provided API has been published, false otherwise.
48         IsAPIPublished(aefId, path string) bool
49         // Gets all published APIs.
50         // Returns a list of all APIs that has been published.
51         GetAllPublishedServices() []publishapi.ServiceAPIDescription
52         GetAllowedPublishedServices(invokerApiList []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription
53 }
54
55 type PublishService struct {
56         publishedServices map[string][]publishapi.ServiceAPIDescription
57         serviceRegister   providermanagement.ServiceRegister
58         helmManager       helmmanagement.HelmManager
59         eventChannel      chan<- eventsapi.EventNotification
60         lock              sync.Mutex
61 }
62
63 // Creates a service that implements both the PublishRegister and the publishserviceapi.ServerInterface interfaces.
64 func NewPublishService(serviceRegister providermanagement.ServiceRegister, hm helmmanagement.HelmManager, eventChannel chan<- eventsapi.EventNotification) *PublishService {
65         return &PublishService{
66                 helmManager:       hm,
67                 publishedServices: make(map[string][]publishapi.ServiceAPIDescription),
68                 serviceRegister:   serviceRegister,
69                 eventChannel:      eventChannel,
70         }
71 }
72
73 func (ps *PublishService) getAllAefIds() []string {
74         ps.lock.Lock()
75         defer ps.lock.Unlock()
76
77         allIds := []string{}
78         for _, descriptions := range ps.publishedServices {
79                 for _, description := range descriptions {
80                         allIds = append(allIds, description.GetAefIds()...)
81                 }
82         }
83         return allIds
84 }
85
86 func (ps *PublishService) IsAPIPublished(aefId, path string) bool {
87         return slices.Contains(ps.getAllAefIds(), aefId)
88 }
89
90 func (ps *PublishService) GetAllPublishedServices() []publishapi.ServiceAPIDescription {
91         publishedDescriptions := []publishapi.ServiceAPIDescription{}
92         for _, descriptions := range ps.publishedServices {
93                 publishedDescriptions = append(publishedDescriptions, descriptions...)
94         }
95         return publishedDescriptions
96 }
97
98 func (ps *PublishService) GetAllowedPublishedServices(apiListRequestedServices []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
99         apiListAllPublished := ps.GetAllPublishedServices()
100         if apiListRequestedServices != nil {
101                 allowedPublishedServices := intersection(apiListAllPublished, apiListRequestedServices)
102                 return allowedPublishedServices
103         }
104         return []publishapi.ServiceAPIDescription{}
105 }
106
107 func intersection(a, b []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
108         var result []publishapi.ServiceAPIDescription
109
110         for _, itemA := range a {
111                 for _, itemB := range b {
112                         if *itemA.ApiId == *itemB.ApiId {
113                                 result = append(result, itemA)
114                                 break
115                         }
116                 }
117         }
118         return result
119 }
120
121 // Retrieve all published APIs.
122 func (ps *PublishService) GetApfIdServiceApis(ctx echo.Context, apfId string) error {
123         if !ps.serviceRegister.IsPublishingFunctionRegistered(apfId) {
124                 errorMsg := fmt.Sprintf("Unable to get the service due to %s api is only available for publishers", apfId)
125                 return sendCoreError(ctx, http.StatusNotFound, errorMsg)
126         }
127
128         serviceDescriptions := ps.publishedServices[apfId]
129         err := ctx.JSON(http.StatusOK, serviceDescriptions)
130         if err != nil {
131                 // Something really bad happened, tell Echo that our handler failed
132                 return err
133         }
134         return nil
135 }
136
137 // Publish a new API.
138 func (ps *PublishService) PostApfIdServiceApis(ctx echo.Context, apfId string) error {
139         var newServiceAPIDescription publishapi.ServiceAPIDescription
140         errorMsg := "Unable to publish the service due to %s "
141         err := ctx.Bind(&newServiceAPIDescription)
142         if err != nil {
143                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, "invalid format for service "+apfId))
144         }
145
146         if !ps.serviceRegister.IsPublishingFunctionRegistered(apfId) {
147                 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, "api is only available for publishers "+apfId))
148         }
149
150         if err := ps.isServicePublished(newServiceAPIDescription); err != nil {
151                 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, err))
152         }
153
154         if err := newServiceAPIDescription.Validate(); err != nil {
155                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, err))
156         }
157         ps.lock.Lock()
158         defer ps.lock.Unlock()
159
160         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
161         for _, profile := range *newServiceAPIDescription.AefProfiles {
162                 if !slices.Contains(registeredFuncs, profile.AefId) {
163                         return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf(errorMsg, fmt.Sprintf("function %s not registered", profile.AefId)))
164                 }
165         }
166
167         newServiceAPIDescription.PrepareNewService()
168
169         shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
170         if shouldReturn {
171                 return returnValue
172         }
173         go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
174
175         _, ok := ps.publishedServices[apfId]
176         if ok {
177                 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
178         } else {
179                 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
180         }
181
182         uri := ctx.Request().Host + ctx.Request().URL.String()
183         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newServiceAPIDescription.ApiId))
184         err = ctx.JSON(http.StatusCreated, newServiceAPIDescription)
185         if err != nil {
186                 // Something really bad happened, tell Echo that our handler failed
187                 return err
188         }
189
190         return nil
191 }
192
193 func (ps *PublishService) isServicePublished(newService publishapi.ServiceAPIDescription) error {
194         for _, services := range ps.publishedServices {
195                 for _, service := range services {
196                         if err := service.ValidateAlreadyPublished(newService); err != nil {
197                                 return err
198                         }
199                 }
200         }
201         return nil
202 }
203
204 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
205         info := strings.Split(*newServiceAPIDescription.Description, ",")
206         if len(info) == 5 {
207                 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
208                 if err != nil {
209                         return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
210                 }
211                 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
212         }
213         return false, nil
214 }
215
216 // Unpublish a published service API.
217 func (ps *PublishService) DeleteApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
218         serviceDescriptions, ok := ps.publishedServices[string(apfId)]
219         if ok {
220                 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
221                 if description != nil {
222                         info := strings.Split(*description.Description, ",")
223                         if len(info) == 5 {
224                                 ps.helmManager.UninstallHelmChart(info[1], info[3])
225                                 log.Debug("Deleted service: ", serviceApiId)
226                         }
227                         ps.lock.Lock()
228                         ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
229                         ps.lock.Unlock()
230                         go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
231                 }
232         }
233         return ctx.NoContent(http.StatusNoContent)
234 }
235
236 // Retrieve a published service API.
237 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
238         ps.lock.Lock()
239         serviceDescriptions, ok := ps.publishedServices[apfId]
240         ps.lock.Unlock()
241
242         if ok {
243                 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
244                 if serviceDescription == nil {
245                         return ctx.NoContent(http.StatusNotFound)
246                 }
247                 err := ctx.JSON(http.StatusOK, serviceDescription)
248                 if err != nil {
249                         // Something really bad happened, tell Echo that our handler failed
250                         return err
251                 }
252
253                 return nil
254         }
255         return ctx.NoContent(http.StatusNotFound)
256 }
257
258 func getServiceDescription(serviceApiId string, descriptions []publishapi.ServiceAPIDescription) (int, *publishapi.ServiceAPIDescription) {
259         for pos, description := range descriptions {
260                 // Check for nil as we had a failure here when running unit tests in parallel against a single Capifcore instance
261                 if (description.ApiId != nil) && (serviceApiId == *description.ApiId) {
262                         return pos, &description
263                 }
264         }
265         return -1, nil
266 }
267
268 func removeServiceDescription(i int, a []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
269         a[i] = a[len(a)-1]                               // Copy last element to index i.
270         a[len(a)-1] = publishapi.ServiceAPIDescription{} // Erase last element (write zero value).
271         a = a[:len(a)-1]                                 // Truncate slice.
272         return a
273 }
274
275 // Modify an existing published service API.
276 func (ps *PublishService) ModifyIndAPFPubAPI(ctx echo.Context, apfId string, serviceApiId string) error {
277         return ctx.NoContent(http.StatusNotImplemented)
278 }
279
280 // Update a published service API.
281 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
282         ps.lock.Lock()
283         defer ps.lock.Unlock()
284         errMsg := "Unable to update service due to %s."
285
286         pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
287         if err != nil {
288                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
289         }
290
291         updatedServiceDescription, err := getServiceFromRequest(ctx)
292         if err != nil {
293                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
294         }
295
296         // Additional validation for PUT
297         if (updatedServiceDescription.ApiId == nil) || (*updatedServiceDescription.ApiId != serviceApiId) {
298                 errDetail := "ServiceAPIDescription ApiId doesn't match path parameter"
299                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, errDetail))
300         }
301
302         err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
303         if err != nil {
304                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
305         }
306
307         ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
308
309         publishedService.AefProfiles = updatedServiceDescription.AefProfiles
310         ps.publishedServices[apfId][pos] = publishedService
311
312         err = ctx.JSON(http.StatusOK, publishedService)
313         if err != nil {
314                 // Something really bad happened, tell Echo that our handler failed
315                 return err
316         }
317         return nil
318 }
319
320 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
321         publishedServices, ok := ps.publishedServices[apfId]
322         if !ok {
323                 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
324         } else {
325                 for pos, description := range publishedServices {
326                         if *description.ApiId == serviceApiId {
327                                 return pos, description, nil
328                         }
329                 }
330         }
331         return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
332 }
333
334 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
335         var updatedServiceDescription publishapi.ServiceAPIDescription
336         err := ctx.Bind(&updatedServiceDescription)
337         if err != nil {
338                 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
339         }
340         return updatedServiceDescription, nil
341 }
342
343 func (ps *PublishService) updateDescription(pos int, apfId string, updatedServiceDescription, publishedService *publishapi.ServiceAPIDescription) {
344         if updatedServiceDescription.Description != nil {
345                 publishedService.Description = updatedServiceDescription.Description
346                 go ps.sendEvent(*publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
347         }
348 }
349
350 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
351         apiIds := []string{*service.ApiId}
352         apis := []publishapi.ServiceAPIDescription{service}
353         event := eventsapi.EventNotification{
354                 EventDetail: &eventsapi.CAPIFEventDetail{
355                         ApiIds:                 &apiIds,
356                         ServiceAPIDescriptions: &apis,
357                 },
358                 Events: eventType,
359         }
360         ps.eventChannel <- event
361 }
362
363 func (ps *PublishService) checkProfilesRegistered(apfId string, updatedProfiles []publishapi.AefProfile) error {
364         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
365         for _, profile := range updatedProfiles {
366                 if !slices.Contains(registeredFuncs, profile.AefId) {
367                         return fmt.Errorf("function %s not registered", profile.AefId)
368                 }
369         }
370         return nil
371 }
372
373 // This function wraps sending of an error in the Error format, and
374 // handling the failure to marshal that.
375 func sendCoreError(ctx echo.Context, code int, message string) error {
376         pd := common29122.ProblemDetails{
377                 Cause:  &message,
378                 Status: &code,
379         }
380         err := ctx.JSON(code, pd)
381         return err
382 }