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 err := ctx.Bind(&newServiceAPIDescription)
163 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for service "+apfId)
167 defer ps.lock.Unlock()
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))
176 newId := "api_id_" + newServiceAPIDescription.ApiName
177 newServiceAPIDescription.ApiId = &newId
179 shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
183 go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
185 _, ok := ps.publishedServices[apfId]
187 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
189 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
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)
196 // Something really bad happened, tell Echo that our handler failed
203 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
204 info := strings.Split(*newServiceAPIDescription.Description, ",")
206 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
208 return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
210 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
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)]
219 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
220 if description != nil {
221 info := strings.Split(*description.Description, ",")
223 ps.helmManager.UninstallHelmChart(info[1], info[3])
224 log.Debug("Deleted service: ", serviceApiId)
227 defer ps.lock.Unlock()
228 ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
229 go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
232 return ctx.NoContent(http.StatusNoContent)
235 // Retrieve a published service API.
236 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
238 defer ps.lock.Unlock()
240 serviceDescriptions, ok := ps.publishedServices[apfId]
242 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
243 if serviceDescription == nil {
244 return ctx.NoContent(http.StatusNotFound)
246 err := ctx.JSON(http.StatusOK, serviceDescription)
248 // Something really bad happened, tell Echo that our handler failed
254 return ctx.NoContent(http.StatusNotFound)
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
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.
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)
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)
285 updatedServiceDescription, shouldReturn, returnValue := getServiceFromRequest(ctx)
290 if updatedServiceDescription.Description != nil {
292 defer ps.lock.Unlock()
294 publishedService.Description = updatedServiceDescription.Description
295 ps.publishedServices[apfId][pos] = publishedService
296 go ps.sendEvent(publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
299 err := ctx.JSON(http.StatusOK, ps.publishedServices[apfId][pos])
301 // Something really bad happened, tell Echo that our handler failed
307 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, bool, error) {
308 publishedServices, ok := ps.publishedServices[apfId]
310 return 0, publishapi.ServiceAPIDescription{}, true, sendCoreError(ctx, http.StatusBadRequest, "Service must be published before updating it")
312 for pos, description := range publishedServices {
313 if *description.ApiId == serviceApiId {
314 return pos, description, false, nil
321 return 0, publishapi.ServiceAPIDescription{}, true, sendCoreError(ctx, http.StatusBadRequest, "Service must be published before updating it")
324 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, bool, error) {
325 var updatedServiceDescription publishapi.ServiceAPIDescription
326 err := ctx.Bind(&updatedServiceDescription)
328 return publishapi.ServiceAPIDescription{}, true, sendCoreError(ctx, http.StatusBadRequest, "Invalid format for service")
330 return updatedServiceDescription, false, nil
333 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
334 apiIds := []string{*service.ApiId}
335 apis := []publishapi.ServiceAPIDescription{service}
336 event := eventsapi.EventNotification{
337 EventDetail: &eventsapi.CAPIFEventDetail{
339 ServiceAPIDescriptions: &apis,
343 ps.eventChannel <- event
346 // This function wraps sending of an error in the Error format, and
347 // handling the failure to marshal that.
348 func sendCoreError(ctx echo.Context, code int, message string) error {
349 pd := common29122.ProblemDetails{
353 err := ctx.JSON(code, pd)