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 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
56 type PublishService struct {
57 publishedServices map[string][]publishapi.ServiceAPIDescription
58 serviceRegister providermanagement.ServiceRegister
59 helmManager helmmanagement.HelmManager
60 eventChannel chan<- eventsapi.EventNotification
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{
68 publishedServices: make(map[string][]publishapi.ServiceAPIDescription),
69 serviceRegister: serviceRegister,
70 eventChannel: eventChannel,
74 func (ps *PublishService) AreAPIsPublished(serviceDescriptions *[]publishapi.ServiceAPIDescription) bool {
76 if serviceDescriptions != nil {
77 registeredApis := ps.getAllAefIds()
78 return checkNewDescriptions(*serviceDescriptions, registeredApis)
83 func (ps *PublishService) getAllAefIds() []string {
85 defer ps.lock.Unlock()
88 for _, descriptions := range ps.publishedServices {
89 for _, description := range descriptions {
90 allIds = append(allIds, getIdsFromDescription(description)...)
96 func getIdsFromDescription(description publishapi.ServiceAPIDescription) []string {
98 if description.AefProfiles != nil {
99 for _, aefProfile := range *description.AefProfiles {
100 allIds = append(allIds, aefProfile.AefId)
106 func checkNewDescriptions(newDescriptions []publishapi.ServiceAPIDescription, registeredAefIds []string) bool {
108 for _, newApi := range newDescriptions {
109 if !checkProfiles(newApi.AefProfiles, registeredAefIds) {
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
130 func (ps *PublishService) IsAPIPublished(aefId, path string) bool {
131 return slices.Contains(ps.getAllAefIds(), aefId)
134 func (ps *PublishService) GetAllPublishedServices() []publishapi.ServiceAPIDescription {
135 publishedDescriptions := []publishapi.ServiceAPIDescription{}
136 for _, descriptions := range ps.publishedServices {
137 publishedDescriptions = append(publishedDescriptions, descriptions...)
139 return publishedDescriptions
142 // Retrieve all published APIs.
143 func (ps *PublishService) GetApfIdServiceApis(ctx echo.Context, apfId string) error {
144 serviceDescriptions, ok := ps.publishedServices[apfId]
146 err := ctx.JSON(http.StatusOK, serviceDescriptions)
148 // Something really bad happened, tell Echo that our handler failed
152 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("Provider %s not registered", apfId))
158 // Publish a new API.
159 func (ps *PublishService) PostApfIdServiceApis(ctx echo.Context, apfId string) error {
160 var newServiceAPIDescription publishapi.ServiceAPIDescription
161 errorMsg := "Unable to publish the service due to %s "
162 err := ctx.Bind(&newServiceAPIDescription)
164 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, "invalid format for service "+apfId))
167 if ps.isServicePublished(newServiceAPIDescription) {
168 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errorMsg, "service already published"))
171 if err := newServiceAPIDescription.Validate(); err != nil {
172 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, err))
175 defer ps.lock.Unlock()
177 registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
178 for _, profile := range *newServiceAPIDescription.AefProfiles {
179 if !slices.Contains(registeredFuncs, profile.AefId) {
180 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf(errorMsg, fmt.Sprintf("function %s not registered", profile.AefId)))
184 newId := "api_id_" + newServiceAPIDescription.ApiName
185 newServiceAPIDescription.ApiId = &newId
187 shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
191 go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
193 _, ok := ps.publishedServices[apfId]
195 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
197 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
200 uri := ctx.Request().Host + ctx.Request().URL.String()
201 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newServiceAPIDescription.ApiId))
202 err = ctx.JSON(http.StatusCreated, newServiceAPIDescription)
204 // Something really bad happened, tell Echo that our handler failed
211 func (ps *PublishService) isServicePublished(newService publishapi.ServiceAPIDescription) bool {
212 for _, services := range ps.publishedServices {
213 for _, service := range services {
214 if newService.ApiName == service.ApiName {
222 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
223 info := strings.Split(*newServiceAPIDescription.Description, ",")
225 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
227 return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
229 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
234 // Unpublish a published service API.
235 func (ps *PublishService) DeleteApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
236 serviceDescriptions, ok := ps.publishedServices[string(apfId)]
238 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
239 if description != nil {
240 info := strings.Split(*description.Description, ",")
242 ps.helmManager.UninstallHelmChart(info[1], info[3])
243 log.Debug("Deleted service: ", serviceApiId)
246 ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
248 go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
251 return ctx.NoContent(http.StatusNoContent)
254 // Retrieve a published service API.
255 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
257 serviceDescriptions, ok := ps.publishedServices[apfId]
261 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
262 if serviceDescription == nil {
263 return ctx.NoContent(http.StatusNotFound)
265 err := ctx.JSON(http.StatusOK, serviceDescription)
267 // Something really bad happened, tell Echo that our handler failed
273 return ctx.NoContent(http.StatusNotFound)
276 func getServiceDescription(serviceApiId string, descriptions []publishapi.ServiceAPIDescription) (int, *publishapi.ServiceAPIDescription) {
277 for pos, description := range descriptions {
278 if serviceApiId == *description.ApiId {
279 return pos, &description
285 func removeServiceDescription(i int, a []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
286 a[i] = a[len(a)-1] // Copy last element to index i.
287 a[len(a)-1] = publishapi.ServiceAPIDescription{} // Erase last element (write zero value).
288 a = a[:len(a)-1] // Truncate slice.
292 // Modify an existing published service API.
293 func (ps *PublishService) ModifyIndAPFPubAPI(ctx echo.Context, apfId string, serviceApiId string) error {
294 return ctx.NoContent(http.StatusNotImplemented)
297 // Update a published service API.
298 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
300 defer ps.lock.Unlock()
301 errMsg := "Unable to update service due to %s."
302 pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
304 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
306 updatedServiceDescription, err := getServiceFromRequest(ctx)
308 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
310 ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
311 err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
313 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
315 publishedService.AefProfiles = updatedServiceDescription.AefProfiles
316 ps.publishedServices[apfId][pos] = publishedService
317 err = ctx.JSON(http.StatusOK, publishedService)
319 // Something really bad happened, tell Echo that our handler failed
324 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
325 publishedServices, ok := ps.publishedServices[apfId]
327 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
329 for pos, description := range publishedServices {
330 if *description.ApiId == serviceApiId {
331 return pos, description, nil
335 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
337 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
338 var updatedServiceDescription publishapi.ServiceAPIDescription
339 err := ctx.Bind(&updatedServiceDescription)
341 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
343 return updatedServiceDescription, nil
345 func (ps *PublishService) updateDescription(pos int, apfId string, updatedServiceDescription, publishedService *publishapi.ServiceAPIDescription) {
346 if updatedServiceDescription.Description != nil {
347 publishedService.Description = updatedServiceDescription.Description
348 go ps.sendEvent(*publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
352 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
353 apiIds := []string{*service.ApiId}
354 apis := []publishapi.ServiceAPIDescription{service}
355 event := eventsapi.EventNotification{
356 EventDetail: &eventsapi.CAPIFEventDetail{
358 ServiceAPIDescriptions: &apis,
362 ps.eventChannel <- event
365 func (ps *PublishService) checkProfilesRegistered(apfId string, updatedProfiles []publishapi.AefProfile) error {
366 registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
367 for _, profile := range updatedProfiles {
368 if !slices.Contains(registeredFuncs, profile.AefId) {
369 return fmt.Errorf("function %s not registered", profile.AefId)
375 // This function wraps sending of an error in the Error format, and
376 // handling the failure to marshal that.
377 func sendCoreError(ctx echo.Context, code int, message string) error {
378 pd := common29122.ProblemDetails{
382 err := ctx.JSON(code, pd)