Update more functionality to publish service
[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                         defer ps.lock.Unlock()
228                         ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
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         defer ps.lock.Unlock()
239
240         serviceDescriptions, ok := ps.publishedServices[apfId]
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         pos, publishedService, shouldReturn, returnValue := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
281         if shouldReturn {
282                 return returnValue
283         }
284
285         updatedServiceDescription, shouldReturn, returnValue := getServiceFromRequest(ctx)
286         if shouldReturn {
287                 return returnValue
288         }
289
290         if updatedServiceDescription.Description != nil {
291                 ps.lock.Lock()
292                 defer ps.lock.Unlock()
293
294                 publishedService.Description = updatedServiceDescription.Description
295                 ps.publishedServices[apfId][pos] = publishedService
296                 go ps.sendEvent(publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
297         }
298
299         pos, shouldReturn, returnValue = ps.updateProfiles(pos, apfId, updatedServiceDescription, publishedService, ctx)
300         if shouldReturn {
301                 return returnValue
302         }
303
304         err := ctx.JSON(http.StatusOK, ps.publishedServices[apfId][pos])
305         if err != nil {
306                 // Something really bad happened, tell Echo that our handler failed
307                 return err
308         }
309         return nil
310 }
311
312 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, bool, error) {
313         publishedServices, ok := ps.publishedServices[apfId]
314         if !ok {
315                 return 0, publishapi.ServiceAPIDescription{}, true, sendCoreError(ctx, http.StatusBadRequest, "Service must be published before updating it")
316         } else {
317                 for pos, description := range publishedServices {
318                         if *description.ApiId == serviceApiId {
319                                 return pos, description, false, nil
320
321                         }
322
323                 }
324
325         }
326         return 0, publishapi.ServiceAPIDescription{}, true, sendCoreError(ctx, http.StatusBadRequest, "Service must be published before updating it")
327 }
328
329 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, bool, error) {
330         var updatedServiceDescription publishapi.ServiceAPIDescription
331         err := ctx.Bind(&updatedServiceDescription)
332         if err != nil {
333                 return publishapi.ServiceAPIDescription{}, true, sendCoreError(ctx, http.StatusBadRequest, "Invalid format for service")
334         }
335         return updatedServiceDescription, false, nil
336 }
337
338 func (ps *PublishService) updateProfiles(pos int, apfId string, updatedServiceDescription publishapi.ServiceAPIDescription, publishedService publishapi.ServiceAPIDescription, ctx echo.Context) (int, bool, error) {
339         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
340         for _, profile := range *updatedServiceDescription.AefProfiles {
341                 if !slices.Contains(registeredFuncs, profile.AefId) {
342                         return 0, false, sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("Function %s not registered", profile.AefId))
343                 }
344                 if ps.checkIfProfileIsNew(profile.AefId, *publishedService.AefProfiles) {
345
346                         publishedService.AefProfiles = ps.addProfile(profile, publishedService)
347                         ps.publishedServices[apfId][pos] = publishedService
348
349                 } else {
350                         pos, shouldReturn, returnValue := ps.updateProfile(profile, publishedService, ctx)
351                         if shouldReturn {
352                                 return pos, true, returnValue
353                         }
354                 }
355
356         }
357         return 0, false, nil
358 }
359
360 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
361         apiIds := []string{*service.ApiId}
362         apis := []publishapi.ServiceAPIDescription{service}
363         event := eventsapi.EventNotification{
364                 EventDetail: &eventsapi.CAPIFEventDetail{
365                         ApiIds:                 &apiIds,
366                         ServiceAPIDescriptions: &apis,
367                 },
368                 Events: eventType,
369         }
370         ps.eventChannel <- event
371 }
372
373 func (ps *PublishService) checkIfProfileIsNew(aefId string, publishedPofiles []publishapi.AefProfile) bool {
374         for _, profile := range publishedPofiles {
375                 if profile.AefId == aefId {
376                         return false
377                 }
378         }
379         return true
380 }
381 func (ps *PublishService) addProfile(profile publishapi.AefProfile, publishedService publishapi.ServiceAPIDescription) *[]publishapi.AefProfile {
382         registeredProfiles := *publishedService.AefProfiles
383         newProfiles := append(registeredProfiles, profile)
384         publishedService.AefProfiles = &newProfiles
385         return &newProfiles
386
387 }
388
389 func (*PublishService) updateProfile(profile publishapi.AefProfile, publishedService publishapi.ServiceAPIDescription, ctx echo.Context) (int, bool, error) {
390         pos, registeredProfile, err := getProfile(profile.AefId, publishedService.AefProfiles)
391         if err != nil {
392                 return pos, true, sendCoreError(ctx, http.StatusBadRequest, "Unable to update service due to: "+err.Error())
393         }
394         if profile.DomainName != nil {
395                 registeredProfile.DomainName = profile.DomainName
396                 (*publishedService.AefProfiles)[pos] = registeredProfile
397         }
398         return -1, false, nil
399 }
400
401 func getProfile(profileId string, apiProfiles *[]publishapi.AefProfile) (int, publishapi.AefProfile, error) {
402         for pos, profile := range *apiProfiles {
403                 if profile.AefId == profileId {
404                         return pos, profile, nil
405                 }
406         }
407         return 0, publishapi.AefProfile{}, fmt.Errorf("profile with ID %s is not registered for the service", profileId)
408 }
409
410 // This function wraps sending of an error in the Error format, and
411 // handling the failure to marshal that.
412 func sendCoreError(ctx echo.Context, code int, message string) error {
413         pd := common29122.ProblemDetails{
414                 Cause:  &message,
415                 Status: &code,
416         }
417         err := ctx.JSON(code, pd)
418         return err
419 }