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