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
54 type PublishService struct {
55 publishedServices map[string][]publishapi.ServiceAPIDescription
56 serviceRegister providermanagement.ServiceRegister
57 helmManager helmmanagement.HelmManager
58 eventChannel chan<- eventsapi.EventNotification
62 // Creates a service that implements both the PublishRegister and the publishserviceapi.ServerInterface interfaces.
63 func NewPublishService(serviceRegister providermanagement.ServiceRegister, hm helmmanagement.HelmManager, eventChannel chan<- eventsapi.EventNotification) *PublishService {
64 return &PublishService{
66 publishedServices: make(map[string][]publishapi.ServiceAPIDescription),
67 serviceRegister: serviceRegister,
68 eventChannel: eventChannel,
72 func (ps *PublishService) getAllAefIds() []string {
74 defer ps.lock.Unlock()
77 for _, descriptions := range ps.publishedServices {
78 for _, description := range descriptions {
79 allIds = append(allIds, description.GetAefIds()...)
85 func (ps *PublishService) IsAPIPublished(aefId, path string) bool {
86 return slices.Contains(ps.getAllAefIds(), aefId)
89 func (ps *PublishService) GetAllPublishedServices() []publishapi.ServiceAPIDescription {
90 publishedDescriptions := []publishapi.ServiceAPIDescription{}
91 for _, descriptions := range ps.publishedServices {
92 publishedDescriptions = append(publishedDescriptions, descriptions...)
94 return publishedDescriptions
97 // Retrieve all published APIs.
98 func (ps *PublishService) GetApfIdServiceApis(ctx echo.Context, apfId string) error {
99 if !ps.serviceRegister.IsPublishingFunctionRegistered(apfId) {
100 errorMsg := fmt.Sprintf("Unable to get the service due to %s api is only available for publishers", apfId)
101 return sendCoreError(ctx, http.StatusNotFound, errorMsg)
104 serviceDescriptions := ps.publishedServices[apfId]
105 err := ctx.JSON(http.StatusOK, serviceDescriptions)
107 // Something really bad happened, tell Echo that our handler failed
113 // Publish a new API.
114 func (ps *PublishService) PostApfIdServiceApis(ctx echo.Context, apfId string) error {
115 var newServiceAPIDescription publishapi.ServiceAPIDescription
116 errorMsg := "Unable to publish the service due to %s "
117 err := ctx.Bind(&newServiceAPIDescription)
119 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, "invalid format for service "+apfId))
122 if !ps.serviceRegister.IsPublishingFunctionRegistered(apfId) {
123 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, "api is only available for publishers "+apfId))
126 if err := ps.isServicePublished(newServiceAPIDescription); err != nil {
127 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, err))
130 if err := newServiceAPIDescription.Validate(); err != nil {
131 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, err))
134 defer ps.lock.Unlock()
136 registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
137 for _, profile := range *newServiceAPIDescription.AefProfiles {
138 if !slices.Contains(registeredFuncs, profile.AefId) {
139 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf(errorMsg, fmt.Sprintf("function %s not registered", profile.AefId)))
143 newServiceAPIDescription.PrepareNewService()
145 shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
149 go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
151 _, ok := ps.publishedServices[apfId]
153 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
155 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
158 uri := ctx.Request().Host + ctx.Request().URL.String()
159 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newServiceAPIDescription.ApiId))
160 err = ctx.JSON(http.StatusCreated, newServiceAPIDescription)
162 // Something really bad happened, tell Echo that our handler failed
169 func (ps *PublishService) isServicePublished(newService publishapi.ServiceAPIDescription) error {
170 for _, services := range ps.publishedServices {
171 for _, service := range services {
172 if err := service.ValidateAlreadyPublished(newService); err != nil {
180 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
181 info := strings.Split(*newServiceAPIDescription.Description, ",")
183 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
185 return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
187 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
192 // Unpublish a published service API.
193 func (ps *PublishService) DeleteApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
194 serviceDescriptions, ok := ps.publishedServices[string(apfId)]
196 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
197 if description != nil {
198 info := strings.Split(*description.Description, ",")
200 ps.helmManager.UninstallHelmChart(info[1], info[3])
201 log.Debug("Deleted service: ", serviceApiId)
204 ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
206 go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
209 return ctx.NoContent(http.StatusNoContent)
212 // Retrieve a published service API.
213 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
215 serviceDescriptions, ok := ps.publishedServices[apfId]
219 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
220 if serviceDescription == nil {
221 return ctx.NoContent(http.StatusNotFound)
223 err := ctx.JSON(http.StatusOK, serviceDescription)
225 // Something really bad happened, tell Echo that our handler failed
231 return ctx.NoContent(http.StatusNotFound)
234 func getServiceDescription(serviceApiId string, descriptions []publishapi.ServiceAPIDescription) (int, *publishapi.ServiceAPIDescription) {
235 for pos, description := range descriptions {
236 // Check for nil as we had a failure here when running unit tests in parallel against a single Capifcore instance
237 if (description.ApiId != nil) && (serviceApiId == *description.ApiId) {
238 return pos, &description
244 func removeServiceDescription(i int, a []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
245 a[i] = a[len(a)-1] // Copy last element to index i.
246 a[len(a)-1] = publishapi.ServiceAPIDescription{} // Erase last element (write zero value).
247 a = a[:len(a)-1] // Truncate slice.
251 // Modify an existing published service API.
252 func (ps *PublishService) ModifyIndAPFPubAPI(ctx echo.Context, apfId string, serviceApiId string) error {
253 return ctx.NoContent(http.StatusNotImplemented)
256 // Update a published service API.
257 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
259 defer ps.lock.Unlock()
260 errMsg := "Unable to update service due to %s."
262 pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
264 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
267 updatedServiceDescription, err := getServiceFromRequest(ctx)
269 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
272 // Additional validation for PUT
273 if (updatedServiceDescription.ApiId == nil) || (*updatedServiceDescription.ApiId != serviceApiId) {
274 errDetail := "ServiceAPIDescription ApiId doesn't match path parameter"
275 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, errDetail))
278 err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
280 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
283 ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
285 publishedService.AefProfiles = updatedServiceDescription.AefProfiles
286 ps.publishedServices[apfId][pos] = publishedService
288 err = ctx.JSON(http.StatusOK, publishedService)
290 // Something really bad happened, tell Echo that our handler failed
296 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
297 publishedServices, ok := ps.publishedServices[apfId]
299 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
301 for pos, description := range publishedServices {
302 if *description.ApiId == serviceApiId {
303 return pos, description, nil
307 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
310 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
311 var updatedServiceDescription publishapi.ServiceAPIDescription
312 err := ctx.Bind(&updatedServiceDescription)
314 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
316 return updatedServiceDescription, nil
319 func (ps *PublishService) updateDescription(pos int, apfId string, updatedServiceDescription, publishedService *publishapi.ServiceAPIDescription) {
320 if updatedServiceDescription.Description != nil {
321 publishedService.Description = updatedServiceDescription.Description
322 go ps.sendEvent(*publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
326 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
327 apiIds := []string{*service.ApiId}
328 apis := []publishapi.ServiceAPIDescription{service}
329 event := eventsapi.EventNotification{
330 EventDetail: &eventsapi.CAPIFEventDetail{
332 ServiceAPIDescriptions: &apis,
336 ps.eventChannel <- event
339 func (ps *PublishService) checkProfilesRegistered(apfId string, updatedProfiles []publishapi.AefProfile) error {
340 registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
341 for _, profile := range updatedProfiles {
342 if !slices.Contains(registeredFuncs, profile.AefId) {
343 return fmt.Errorf("function %s not registered", profile.AefId)
349 // This function wraps sending of an error in the Error format, and
350 // handling the failure to marshal that.
351 func sendCoreError(ctx echo.Context, code int, message string) error {
352 pd := common29122.ProblemDetails{
356 err := ctx.JSON(code, pd)