3898a804535b29529e8c06eaf0ef4cf981b98910
[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         err := ctx.Bind(&newServiceAPIDescription)
162         if err != nil {
163                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for service "+apfId)
164         }
165
166         ps.lock.Lock()
167         defer ps.lock.Unlock()
168
169         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
170         for _, profile := range *newServiceAPIDescription.AefProfiles {
171                 if !slices.Contains(registeredFuncs, profile.AefId) {
172                         return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("Function %s not registered", profile.AefId))
173                 }
174         }
175
176         newId := "api_id_" + newServiceAPIDescription.ApiName
177         newServiceAPIDescription.ApiId = &newId
178
179         shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
180         if shouldReturn {
181                 return returnValue
182         }
183         go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
184
185         _, ok := ps.publishedServices[apfId]
186         if ok {
187                 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
188         } else {
189                 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
190         }
191
192         uri := ctx.Request().Host + ctx.Request().URL.String()
193         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newServiceAPIDescription.ApiId))
194         err = ctx.JSON(http.StatusCreated, newServiceAPIDescription)
195         if err != nil {
196                 // Something really bad happened, tell Echo that our handler failed
197                 return err
198         }
199
200         return nil
201 }
202
203 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
204         info := strings.Split(*newServiceAPIDescription.Description, ",")
205         if len(info) == 5 {
206                 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
207                 if err != nil {
208                         return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
209                 }
210                 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
211         }
212         return false, nil
213 }
214
215 // Unpublish a published service API.
216 func (ps *PublishService) DeleteApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
217         serviceDescriptions, ok := ps.publishedServices[string(apfId)]
218         if ok {
219                 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
220                 if description != nil {
221                         info := strings.Split(*description.Description, ",")
222                         if len(info) == 5 {
223                                 ps.helmManager.UninstallHelmChart(info[1], info[3])
224                                 log.Debug("Deleted service: ", serviceApiId)
225                         }
226                         ps.lock.Lock()
227                         ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
228                         ps.lock.Unlock()
229                         go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
230                 }
231         }
232         return ctx.NoContent(http.StatusNoContent)
233 }
234
235 // Retrieve a published service API.
236 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
237         ps.lock.Lock()
238         serviceDescriptions, ok := ps.publishedServices[apfId]
239         ps.lock.Unlock()
240
241         if ok {
242                 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
243                 if serviceDescription == nil {
244                         return ctx.NoContent(http.StatusNotFound)
245                 }
246                 err := ctx.JSON(http.StatusOK, serviceDescription)
247                 if err != nil {
248                         // Something really bad happened, tell Echo that our handler failed
249                         return err
250                 }
251
252                 return nil
253         }
254         return ctx.NoContent(http.StatusNotFound)
255 }
256
257 func getServiceDescription(serviceApiId string, descriptions []publishapi.ServiceAPIDescription) (int, *publishapi.ServiceAPIDescription) {
258         for pos, description := range descriptions {
259                 if serviceApiId == *description.ApiId {
260                         return pos, &description
261                 }
262         }
263         return -1, nil
264 }
265
266 func removeServiceDescription(i int, a []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
267         a[i] = a[len(a)-1]                               // Copy last element to index i.
268         a[len(a)-1] = publishapi.ServiceAPIDescription{} // Erase last element (write zero value).
269         a = a[:len(a)-1]                                 // Truncate slice.
270         return a
271 }
272
273 // Modify an existing published service API.
274 func (ps *PublishService) ModifyIndAPFPubAPI(ctx echo.Context, apfId string, serviceApiId string) error {
275         return ctx.NoContent(http.StatusNotImplemented)
276 }
277
278 // Update a published service API.
279 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
280         ps.lock.Lock()
281         defer ps.lock.Unlock()
282         errMsg := "Unable to update service due to %s."
283         pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
284         if err != nil {
285                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
286         }
287         updatedServiceDescription, err := getServiceFromRequest(ctx)
288         if err != nil {
289                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
290         }
291         ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
292         err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
293         if err != nil {
294                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
295         }
296         publishedService.AefProfiles = updatedServiceDescription.AefProfiles
297         ps.publishedServices[apfId][pos] = publishedService
298         err = ctx.JSON(http.StatusOK, publishedService)
299         if err != nil {
300                 // Something really bad happened, tell Echo that our handler failed
301                 return err
302         }
303         return nil
304 }
305 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
306         publishedServices, ok := ps.publishedServices[apfId]
307         if !ok {
308                 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
309         } else {
310                 for pos, description := range publishedServices {
311                         if *description.ApiId == serviceApiId {
312                                 return pos, description, nil
313                         }
314                 }
315         }
316         return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
317 }
318 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
319         var updatedServiceDescription publishapi.ServiceAPIDescription
320         err := ctx.Bind(&updatedServiceDescription)
321         if err != nil {
322                 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
323         }
324         return updatedServiceDescription, nil
325 }
326 func (ps *PublishService) updateDescription(pos int, apfId string, updatedServiceDescription, publishedService *publishapi.ServiceAPIDescription) {
327         if updatedServiceDescription.Description != nil {
328                 publishedService.Description = updatedServiceDescription.Description
329                 go ps.sendEvent(*publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
330         }
331 }
332
333 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
334         apiIds := []string{*service.ApiId}
335         apis := []publishapi.ServiceAPIDescription{service}
336         event := eventsapi.EventNotification{
337                 EventDetail: &eventsapi.CAPIFEventDetail{
338                         ApiIds:                 &apiIds,
339                         ServiceAPIDescriptions: &apis,
340                 },
341                 Events: eventType,
342         }
343         ps.eventChannel <- event
344 }
345
346 func (ps *PublishService) checkProfilesRegistered(apfId string, updatedProfiles []publishapi.AefProfile) error {
347
348         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
349         for _, profile := range updatedProfiles {
350                 if !slices.Contains(registeredFuncs, profile.AefId) {
351                         return fmt.Errorf("function %s not registered", profile.AefId)
352                 }
353         }
354         return nil
355
356 }
357
358 // This function wraps sending of an error in the Error format, and
359 // handling the failure to marshal that.
360 func sendCoreError(ctx echo.Context, code int, message string) error {
361         pd := common29122.ProblemDetails{
362                 Cause:  &message,
363                 Status: &code,
364         }
365         err := ctx.JSON(code, pd)
366         return err
367 }