2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022-2023: Nordix Foundation
6 // Copyright (C) 2024: OpenInfra Foundation Europe
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
12 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
22 package publishservice
31 echo "github.com/labstack/echo/v4"
32 "k8s.io/utils/strings/slices"
34 "oransc.org/nonrtric/capifcore/internal/common29122"
35 "oransc.org/nonrtric/capifcore/internal/eventsapi"
36 publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
38 "oransc.org/nonrtric/capifcore/internal/helmmanagement"
39 "oransc.org/nonrtric/capifcore/internal/providermanagement"
41 log "github.com/sirupsen/logrus"
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
55 type PublishService struct {
56 publishedServices map[string][]publishapi.ServiceAPIDescription
57 serviceRegister providermanagement.ServiceRegister
58 helmManager helmmanagement.HelmManager
59 eventChannel chan<- eventsapi.EventNotification
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{
67 publishedServices: make(map[string][]publishapi.ServiceAPIDescription),
68 serviceRegister: serviceRegister,
69 eventChannel: eventChannel,
73 func (ps *PublishService) getAllAefIds() []string {
75 defer ps.lock.Unlock()
78 for _, descriptions := range ps.publishedServices {
79 for _, description := range descriptions {
80 allIds = append(allIds, description.GetAefIds()...)
86 func (ps *PublishService) IsAPIPublished(aefId, path string) bool {
87 return slices.Contains(ps.getAllAefIds(), aefId)
90 func (ps *PublishService) GetAllPublishedServices() []publishapi.ServiceAPIDescription {
91 publishedDescriptions := []publishapi.ServiceAPIDescription{}
92 for _, descriptions := range ps.publishedServices {
93 publishedDescriptions = append(publishedDescriptions, descriptions...)
95 return publishedDescriptions
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
104 return []publishapi.ServiceAPIDescription{}
107 func intersection(a, b []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
108 var result []publishapi.ServiceAPIDescription
110 for _, itemA := range a {
111 for _, itemB := range b {
112 if *itemA.ApiId == *itemB.ApiId {
113 result = append(result, itemA)
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)
128 serviceDescriptions := ps.publishedServices[apfId]
129 err := ctx.JSON(http.StatusOK, serviceDescriptions)
131 // Something really bad happened, tell Echo that our handler failed
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)
143 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, "invalid format for service "+apfId))
146 if !ps.serviceRegister.IsPublishingFunctionRegistered(apfId) {
147 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, "api is only available for publishers "+apfId))
150 if err := ps.isServicePublished(newServiceAPIDescription); err != nil {
151 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, err))
154 if err := newServiceAPIDescription.Validate(); err != nil {
155 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, err))
158 defer ps.lock.Unlock()
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)))
167 newServiceAPIDescription.PrepareNewService()
169 shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
173 go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
175 _, ok := ps.publishedServices[apfId]
177 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
179 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
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)
186 // Something really bad happened, tell Echo that our handler failed
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 {
204 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
205 info := strings.Split(*newServiceAPIDescription.Description, ",")
207 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
209 return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
211 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
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)]
220 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
221 if description != nil {
222 info := strings.Split(*description.Description, ",")
224 ps.helmManager.UninstallHelmChart(info[1], info[3])
225 log.Debug("Deleted service: ", serviceApiId)
228 ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
230 go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
233 return ctx.NoContent(http.StatusNoContent)
236 // Retrieve a published service API.
237 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
239 serviceDescriptions, ok := ps.publishedServices[apfId]
243 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
244 if serviceDescription == nil {
245 return ctx.NoContent(http.StatusNotFound)
247 err := ctx.JSON(http.StatusOK, serviceDescription)
249 // Something really bad happened, tell Echo that our handler failed
255 return ctx.NoContent(http.StatusNotFound)
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
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.
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)
280 // Update a published service API.
281 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
283 defer ps.lock.Unlock()
284 errMsg := "Unable to update service due to %s."
286 pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
288 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
291 updatedServiceDescription, err := getServiceFromRequest(ctx)
293 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
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))
302 err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
304 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
307 ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
309 publishedService.AefProfiles = updatedServiceDescription.AefProfiles
310 ps.publishedServices[apfId][pos] = publishedService
312 err = ctx.JSON(http.StatusOK, publishedService)
314 // Something really bad happened, tell Echo that our handler failed
320 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
321 publishedServices, ok := ps.publishedServices[apfId]
323 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
325 for pos, description := range publishedServices {
326 if *description.ApiId == serviceApiId {
327 return pos, description, nil
331 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
334 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
335 var updatedServiceDescription publishapi.ServiceAPIDescription
336 err := ctx.Bind(&updatedServiceDescription)
338 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
340 return updatedServiceDescription, nil
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)
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{
356 ServiceAPIDescriptions: &apis,
360 ps.eventChannel <- event
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)
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{
380 err := ctx.JSON(code, pd)