2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package publishservice
30 "github.com/labstack/echo/v4"
31 "k8s.io/utils/strings/slices"
33 "oransc.org/nonrtric/capifcore/internal/common29122"
34 "oransc.org/nonrtric/capifcore/internal/eventsapi"
35 publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
37 "oransc.org/nonrtric/capifcore/internal/helmmanagement"
38 "oransc.org/nonrtric/capifcore/internal/providermanagement"
40 log "github.com/sirupsen/logrus"
43 //go:generate mockery --name PublishRegister
44 type PublishRegister interface {
45 // Checks if the provided API is published.
46 // Returns true if the provided API has been published, false otherwise.
47 IsAPIPublished(aefId, path string) bool
48 // Gets all published APIs.
49 // Returns a list of all APIs that has been published.
50 GetAllPublishedServices() []publishapi.ServiceAPIDescription
53 type PublishService struct {
54 publishedServices map[string][]publishapi.ServiceAPIDescription
55 serviceRegister providermanagement.ServiceRegister
56 helmManager helmmanagement.HelmManager
57 eventChannel chan<- eventsapi.EventNotification
61 // Creates a service that implements both the PublishRegister and the publishserviceapi.ServerInterface interfaces.
62 func NewPublishService(serviceRegister providermanagement.ServiceRegister, hm helmmanagement.HelmManager, eventChannel chan<- eventsapi.EventNotification) *PublishService {
63 return &PublishService{
65 publishedServices: make(map[string][]publishapi.ServiceAPIDescription),
66 serviceRegister: serviceRegister,
67 eventChannel: eventChannel,
71 func (ps *PublishService) getAllAefIds() []string {
73 defer ps.lock.Unlock()
76 for _, descriptions := range ps.publishedServices {
77 for _, description := range descriptions {
78 allIds = append(allIds, description.GetAefIds()...)
84 func (ps *PublishService) IsAPIPublished(aefId, path string) bool {
85 return slices.Contains(ps.getAllAefIds(), aefId)
88 func (ps *PublishService) GetAllPublishedServices() []publishapi.ServiceAPIDescription {
89 publishedDescriptions := []publishapi.ServiceAPIDescription{}
90 for _, descriptions := range ps.publishedServices {
91 publishedDescriptions = append(publishedDescriptions, descriptions...)
93 return publishedDescriptions
96 // Retrieve all published APIs.
97 func (ps *PublishService) GetApfIdServiceApis(ctx echo.Context, apfId string) error {
98 serviceDescriptions, ok := ps.publishedServices[apfId]
100 err := ctx.JSON(http.StatusOK, serviceDescriptions)
102 // Something really bad happened, tell Echo that our handler failed
106 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("Provider %s not registered", apfId))
112 // Publish a new API.
113 func (ps *PublishService) PostApfIdServiceApis(ctx echo.Context, apfId string) error {
114 var newServiceAPIDescription publishapi.ServiceAPIDescription
115 errorMsg := "Unable to publish the service due to %s "
116 err := ctx.Bind(&newServiceAPIDescription)
118 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, "invalid format for service "+apfId))
121 if !ps.serviceRegister.IsPublishingFunctionRegistered(apfId) {
122 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, "api is only available for publishers "+apfId))
125 if err := ps.isServicePublished(newServiceAPIDescription); err != nil {
126 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, err))
129 if err := newServiceAPIDescription.Validate(); err != nil {
130 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, err))
133 defer ps.lock.Unlock()
135 registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
136 for _, profile := range *newServiceAPIDescription.AefProfiles {
137 if !slices.Contains(registeredFuncs, profile.AefId) {
138 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf(errorMsg, fmt.Sprintf("function %s not registered", profile.AefId)))
142 newServiceAPIDescription.PrepareNewService()
144 shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
148 go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
150 _, ok := ps.publishedServices[apfId]
152 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
154 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
157 uri := ctx.Request().Host + ctx.Request().URL.String()
158 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newServiceAPIDescription.ApiId))
159 err = ctx.JSON(http.StatusCreated, newServiceAPIDescription)
161 // Something really bad happened, tell Echo that our handler failed
168 func (ps *PublishService) isServicePublished(newService publishapi.ServiceAPIDescription) error {
169 for _, services := range ps.publishedServices {
170 for _, service := range services {
171 if err := service.ValidateAlreadyPublished(newService); err != nil {
179 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
180 info := strings.Split(*newServiceAPIDescription.Description, ",")
182 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
184 return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
186 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
191 // Unpublish a published service API.
192 func (ps *PublishService) DeleteApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
193 serviceDescriptions, ok := ps.publishedServices[string(apfId)]
195 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
196 if description != nil {
197 info := strings.Split(*description.Description, ",")
199 ps.helmManager.UninstallHelmChart(info[1], info[3])
200 log.Debug("Deleted service: ", serviceApiId)
203 ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
205 go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
208 return ctx.NoContent(http.StatusNoContent)
211 // Retrieve a published service API.
212 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
214 serviceDescriptions, ok := ps.publishedServices[apfId]
218 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
219 if serviceDescription == nil {
220 return ctx.NoContent(http.StatusNotFound)
222 err := ctx.JSON(http.StatusOK, serviceDescription)
224 // Something really bad happened, tell Echo that our handler failed
230 return ctx.NoContent(http.StatusNotFound)
233 func getServiceDescription(serviceApiId string, descriptions []publishapi.ServiceAPIDescription) (int, *publishapi.ServiceAPIDescription) {
234 for pos, description := range descriptions {
235 if serviceApiId == *description.ApiId {
236 return pos, &description
242 func removeServiceDescription(i int, a []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
243 a[i] = a[len(a)-1] // Copy last element to index i.
244 a[len(a)-1] = publishapi.ServiceAPIDescription{} // Erase last element (write zero value).
245 a = a[:len(a)-1] // Truncate slice.
249 // Modify an existing published service API.
250 func (ps *PublishService) ModifyIndAPFPubAPI(ctx echo.Context, apfId string, serviceApiId string) error {
251 return ctx.NoContent(http.StatusNotImplemented)
254 // Update a published service API.
255 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
257 defer ps.lock.Unlock()
258 errMsg := "Unable to update service due to %s."
259 pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
261 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
263 updatedServiceDescription, err := getServiceFromRequest(ctx)
265 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
267 err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
269 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
271 ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
272 publishedService.AefProfiles = updatedServiceDescription.AefProfiles
273 ps.publishedServices[apfId][pos] = publishedService
274 err = ctx.JSON(http.StatusOK, publishedService)
276 // Something really bad happened, tell Echo that our handler failed
281 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
282 publishedServices, ok := ps.publishedServices[apfId]
284 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
286 for pos, description := range publishedServices {
287 if *description.ApiId == serviceApiId {
288 return pos, description, nil
292 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
294 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
295 var updatedServiceDescription publishapi.ServiceAPIDescription
296 err := ctx.Bind(&updatedServiceDescription)
298 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
300 return updatedServiceDescription, nil
302 func (ps *PublishService) updateDescription(pos int, apfId string, updatedServiceDescription, publishedService *publishapi.ServiceAPIDescription) {
303 if updatedServiceDescription.Description != nil {
304 publishedService.Description = updatedServiceDescription.Description
305 go ps.sendEvent(*publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
309 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
310 apiIds := []string{*service.ApiId}
311 apis := []publishapi.ServiceAPIDescription{service}
312 event := eventsapi.EventNotification{
313 EventDetail: &eventsapi.CAPIFEventDetail{
315 ServiceAPIDescriptions: &apis,
319 ps.eventChannel <- event
322 func (ps *PublishService) checkProfilesRegistered(apfId string, updatedProfiles []publishapi.AefProfile) error {
323 registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
324 for _, profile := range updatedProfiles {
325 if !slices.Contains(registeredFuncs, profile.AefId) {
326 return fmt.Errorf("function %s not registered", profile.AefId)
332 // This function wraps sending of an error in the Error format, and
333 // handling the failure to marshal that.
334 func sendCoreError(ctx echo.Context, code int, message string) error {
335 pd := common29122.ProblemDetails{
339 err := ctx.JSON(code, pd)