e3a23146c379095f9428135548373b3337986b66
[nonrtric/plt/sme.git] / capifcore / internal / publishservice / publishservice.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
6 //   %%
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
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
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===================================
19 //
20
21 package publishservice
22
23 import (
24         "fmt"
25         "net/http"
26         "path"
27         "strings"
28         "sync"
29
30         "github.com/labstack/echo/v4"
31         "k8s.io/utils/strings/slices"
32
33         "oransc.org/nonrtric/capifcore/internal/common29122"
34         "oransc.org/nonrtric/capifcore/internal/eventsapi"
35         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
36
37         "oransc.org/nonrtric/capifcore/internal/helmmanagement"
38         "oransc.org/nonrtric/capifcore/internal/providermanagement"
39
40         log "github.com/sirupsen/logrus"
41 )
42
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
54 }
55
56 type PublishService struct {
57         publishedServices map[string][]publishapi.ServiceAPIDescription
58         serviceRegister   providermanagement.ServiceRegister
59         helmManager       helmmanagement.HelmManager
60         eventChannel      chan<- eventsapi.EventNotification
61         lock              sync.Mutex
62 }
63
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{
67                 helmManager:       hm,
68                 publishedServices: make(map[string][]publishapi.ServiceAPIDescription),
69                 serviceRegister:   serviceRegister,
70                 eventChannel:      eventChannel,
71         }
72 }
73
74 func (ps *PublishService) AreAPIsPublished(serviceDescriptions *[]publishapi.ServiceAPIDescription) bool {
75
76         if serviceDescriptions != nil {
77                 registeredApis := ps.getAllAefIds()
78                 return checkNewDescriptions(*serviceDescriptions, registeredApis)
79         }
80         return true
81 }
82
83 func (ps *PublishService) getAllAefIds() []string {
84         ps.lock.Lock()
85         defer ps.lock.Unlock()
86
87         allIds := []string{}
88         for _, descriptions := range ps.publishedServices {
89                 for _, description := range descriptions {
90                         allIds = append(allIds, getIdsFromDescription(description)...)
91                 }
92         }
93         return allIds
94 }
95
96 func getIdsFromDescription(description publishapi.ServiceAPIDescription) []string {
97         allIds := []string{}
98         if description.AefProfiles != nil {
99                 for _, aefProfile := range *description.AefProfiles {
100                         allIds = append(allIds, aefProfile.AefId)
101                 }
102         }
103         return allIds
104 }
105
106 func checkNewDescriptions(newDescriptions []publishapi.ServiceAPIDescription, registeredAefIds []string) bool {
107         registered := true
108         for _, newApi := range newDescriptions {
109                 if !checkProfiles(newApi.AefProfiles, registeredAefIds) {
110                         registered = false
111                         break
112                 }
113         }
114         return registered
115 }
116
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
123                                 break
124                         }
125                 }
126         }
127         return allRegistered
128 }
129
130 func (ps *PublishService) IsAPIPublished(aefId, path string) bool {
131         return slices.Contains(ps.getAllAefIds(), aefId)
132 }
133
134 func (ps *PublishService) GetAllPublishedServices() []publishapi.ServiceAPIDescription {
135         publishedDescriptions := []publishapi.ServiceAPIDescription{}
136         for _, descriptions := range ps.publishedServices {
137                 publishedDescriptions = append(publishedDescriptions, descriptions...)
138         }
139         return publishedDescriptions
140 }
141
142 // Retrieve all published APIs.
143 func (ps *PublishService) GetApfIdServiceApis(ctx echo.Context, apfId string) error {
144         serviceDescriptions, ok := ps.publishedServices[apfId]
145         if ok {
146                 err := ctx.JSON(http.StatusOK, serviceDescriptions)
147                 if err != nil {
148                         // Something really bad happened, tell Echo that our handler failed
149                         return err
150                 }
151         } else {
152                 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("Provider %s not registered", apfId))
153         }
154
155         return nil
156 }
157
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 register the service due to: %s "
162         err := ctx.Bind(&newServiceAPIDescription)
163         if err != nil {
164                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, "invalid format for service "+apfId))
165         }
166
167         if err := newServiceAPIDescription.Validate(); err != nil {
168                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errorMsg, err))
169         }
170         ps.lock.Lock()
171         defer ps.lock.Unlock()
172
173         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
174         for _, profile := range *newServiceAPIDescription.AefProfiles {
175                 if !slices.Contains(registeredFuncs, profile.AefId) {
176                         return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf(errorMsg, fmt.Sprintf("function %s not registered", profile.AefId)))
177                 }
178         }
179
180         newId := "api_id_" + newServiceAPIDescription.ApiName
181         newServiceAPIDescription.ApiId = &newId
182
183         shouldReturn, returnValue := ps.installHelmChart(newServiceAPIDescription, ctx)
184         if shouldReturn {
185                 return returnValue
186         }
187         go ps.sendEvent(newServiceAPIDescription, eventsapi.CAPIFEventSERVICEAPIAVAILABLE)
188
189         _, ok := ps.publishedServices[apfId]
190         if ok {
191                 ps.publishedServices[apfId] = append(ps.publishedServices[apfId], newServiceAPIDescription)
192         } else {
193                 ps.publishedServices[apfId] = append([]publishapi.ServiceAPIDescription{}, newServiceAPIDescription)
194         }
195
196         uri := ctx.Request().Host + ctx.Request().URL.String()
197         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newServiceAPIDescription.ApiId))
198         err = ctx.JSON(http.StatusCreated, newServiceAPIDescription)
199         if err != nil {
200                 // Something really bad happened, tell Echo that our handler failed
201                 return err
202         }
203
204         return nil
205 }
206
207 func (ps *PublishService) installHelmChart(newServiceAPIDescription publishapi.ServiceAPIDescription, ctx echo.Context) (bool, error) {
208         info := strings.Split(*newServiceAPIDescription.Description, ",")
209         if len(info) == 5 {
210                 err := ps.helmManager.InstallHelmChart(info[1], info[2], info[3], info[4])
211                 if err != nil {
212                         return true, sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf("Unable to install Helm chart %s due to: %s", info[3], err.Error()))
213                 }
214                 log.Debug("Installed service: ", newServiceAPIDescription.ApiId)
215         }
216         return false, nil
217 }
218
219 // Unpublish a published service API.
220 func (ps *PublishService) DeleteApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
221         serviceDescriptions, ok := ps.publishedServices[string(apfId)]
222         if ok {
223                 pos, description := getServiceDescription(serviceApiId, serviceDescriptions)
224                 if description != nil {
225                         info := strings.Split(*description.Description, ",")
226                         if len(info) == 5 {
227                                 ps.helmManager.UninstallHelmChart(info[1], info[3])
228                                 log.Debug("Deleted service: ", serviceApiId)
229                         }
230                         ps.lock.Lock()
231                         ps.publishedServices[string(apfId)] = removeServiceDescription(pos, serviceDescriptions)
232                         ps.lock.Unlock()
233                         go ps.sendEvent(*description, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE)
234                 }
235         }
236         return ctx.NoContent(http.StatusNoContent)
237 }
238
239 // Retrieve a published service API.
240 func (ps *PublishService) GetApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
241         ps.lock.Lock()
242         serviceDescriptions, ok := ps.publishedServices[apfId]
243         ps.lock.Unlock()
244
245         if ok {
246                 _, serviceDescription := getServiceDescription(serviceApiId, serviceDescriptions)
247                 if serviceDescription == nil {
248                         return ctx.NoContent(http.StatusNotFound)
249                 }
250                 err := ctx.JSON(http.StatusOK, serviceDescription)
251                 if err != nil {
252                         // Something really bad happened, tell Echo that our handler failed
253                         return err
254                 }
255
256                 return nil
257         }
258         return ctx.NoContent(http.StatusNotFound)
259 }
260
261 func getServiceDescription(serviceApiId string, descriptions []publishapi.ServiceAPIDescription) (int, *publishapi.ServiceAPIDescription) {
262         for pos, description := range descriptions {
263                 if serviceApiId == *description.ApiId {
264                         return pos, &description
265                 }
266         }
267         return -1, nil
268 }
269
270 func removeServiceDescription(i int, a []publishapi.ServiceAPIDescription) []publishapi.ServiceAPIDescription {
271         a[i] = a[len(a)-1]                               // Copy last element to index i.
272         a[len(a)-1] = publishapi.ServiceAPIDescription{} // Erase last element (write zero value).
273         a = a[:len(a)-1]                                 // Truncate slice.
274         return a
275 }
276
277 // Modify an existing published service API.
278 func (ps *PublishService) ModifyIndAPFPubAPI(ctx echo.Context, apfId string, serviceApiId string) error {
279         return ctx.NoContent(http.StatusNotImplemented)
280 }
281
282 // Update a published service API.
283 func (ps *PublishService) PutApfIdServiceApisServiceApiId(ctx echo.Context, apfId string, serviceApiId string) error {
284         ps.lock.Lock()
285         defer ps.lock.Unlock()
286         errMsg := "Unable to update service due to %s."
287         pos, publishedService, err := ps.checkIfServiceIsPublished(apfId, serviceApiId, ctx)
288         if err != nil {
289                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
290         }
291         updatedServiceDescription, err := getServiceFromRequest(ctx)
292         if err != nil {
293                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
294         }
295         ps.updateDescription(pos, apfId, &updatedServiceDescription, &publishedService)
296         err = ps.checkProfilesRegistered(apfId, *updatedServiceDescription.AefProfiles)
297         if err != nil {
298                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
299         }
300         publishedService.AefProfiles = updatedServiceDescription.AefProfiles
301         ps.publishedServices[apfId][pos] = publishedService
302         err = ctx.JSON(http.StatusOK, publishedService)
303         if err != nil {
304                 // Something really bad happened, tell Echo that our handler failed
305                 return err
306         }
307         return nil
308 }
309 func (ps *PublishService) checkIfServiceIsPublished(apfId string, serviceApiId string, ctx echo.Context) (int, publishapi.ServiceAPIDescription, error) {
310         publishedServices, ok := ps.publishedServices[apfId]
311         if !ok {
312                 return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
313         } else {
314                 for pos, description := range publishedServices {
315                         if *description.ApiId == serviceApiId {
316                                 return pos, description, nil
317                         }
318                 }
319         }
320         return 0, publishapi.ServiceAPIDescription{}, fmt.Errorf("service must be published before updating it")
321 }
322 func getServiceFromRequest(ctx echo.Context) (publishapi.ServiceAPIDescription, error) {
323         var updatedServiceDescription publishapi.ServiceAPIDescription
324         err := ctx.Bind(&updatedServiceDescription)
325         if err != nil {
326                 return publishapi.ServiceAPIDescription{}, fmt.Errorf("invalid format for service")
327         }
328         return updatedServiceDescription, nil
329 }
330 func (ps *PublishService) updateDescription(pos int, apfId string, updatedServiceDescription, publishedService *publishapi.ServiceAPIDescription) {
331         if updatedServiceDescription.Description != nil {
332                 publishedService.Description = updatedServiceDescription.Description
333                 go ps.sendEvent(*publishedService, eventsapi.CAPIFEventSERVICEAPIUPDATE)
334         }
335 }
336
337 func (ps *PublishService) sendEvent(service publishapi.ServiceAPIDescription, eventType eventsapi.CAPIFEvent) {
338         apiIds := []string{*service.ApiId}
339         apis := []publishapi.ServiceAPIDescription{service}
340         event := eventsapi.EventNotification{
341                 EventDetail: &eventsapi.CAPIFEventDetail{
342                         ApiIds:                 &apiIds,
343                         ServiceAPIDescriptions: &apis,
344                 },
345                 Events: eventType,
346         }
347         ps.eventChannel <- event
348 }
349
350 func (ps *PublishService) checkProfilesRegistered(apfId string, updatedProfiles []publishapi.AefProfile) error {
351         registeredFuncs := ps.serviceRegister.GetAefsForPublisher(apfId)
352         for _, profile := range updatedProfiles {
353                 if !slices.Contains(registeredFuncs, profile.AefId) {
354                         return fmt.Errorf("function %s not registered", profile.AefId)
355                 }
356         }
357         return nil
358 }
359
360 // This function wraps sending of an error in the Error format, and
361 // handling the failure to marshal that.
362 func sendCoreError(ctx echo.Context, code int, message string) error {
363         pd := common29122.ProblemDetails{
364                 Cause:  &message,
365                 Status: &code,
366         }
367         err := ctx.JSON(code, pd)
368         return err
369 }