451f54b1034dfe9c270c262f48944530ee0630df
[nonrtric/plt/sme.git] / servicemanager / internal / publishserviceapi / typeupdate.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2023-2024: OpenInfra Foundation Europe
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 publishserviceapi
22
23 import (
24         "errors"
25         "fmt"
26         "net/http"
27         "net/url"
28         "strings"
29
30         resty "github.com/go-resty/resty/v2"
31         log "github.com/sirupsen/logrus"
32
33         common29122 "oransc.org/nonrtric/servicemanager/internal/common29122"
34 )
35
36 func (sd *ServiceAPIDescription) PrepareNewService() {
37         apiName := "api_id_" + strings.ReplaceAll(sd.ApiName, " ", "_")
38         sd.ApiId = &apiName
39 }
40
41 func (sd *ServiceAPIDescription) RegisterKong(kongDomain string,
42                 kongProtocol string,
43                 kongIPv4 common29122.Ipv4Addr,
44                 kongDataPlanePort common29122.Port,
45                 kongControlPlanePort common29122.Port,
46                 apfId string) (int, error) {
47
48         log.Trace("entering RegisterKong")
49         var (
50                 statusCode int
51                 err        error
52         )
53         kongControlPlaneURL := fmt.Sprintf("%s://%s:%d", kongProtocol, kongIPv4, kongControlPlanePort)
54
55         statusCode, err = sd.createKongRoutes(kongControlPlaneURL, apfId)
56         if (err != nil) || (statusCode != http.StatusCreated) {
57                 return statusCode, err
58         }
59
60         sd.updateInterfaceDescription(kongIPv4, kongDataPlanePort, kongDomain)
61
62         log.Trace("exiting from RegisterKong")
63         return statusCode, nil
64 }
65
66 func (sd *ServiceAPIDescription) createKongRoutes(kongControlPlaneURL string, apfId string) (int, error) {
67         log.Trace("entering createKongRoutes")
68         var (
69                 statusCode int
70                 err        error
71         )
72
73         client := resty.New()
74
75         profiles := *sd.AefProfiles
76         for _, profile := range profiles {
77                 log.Debugf("createKongRoutes, AefId %s", profile.AefId)
78                 for _, version := range profile.Versions {
79                         log.Debugf("createKongRoutes, apiVersion \"%s\"", version.ApiVersion)
80                         for _, resource := range *version.Resources {
81                                 statusCode, err = sd.createKongRoute(kongControlPlaneURL, client, resource, apfId, profile.AefId, version.ApiVersion)
82                                 if (err != nil) || (statusCode != http.StatusCreated) {
83                                         return statusCode, err
84                                 }
85                         }
86                 }
87         }
88         return statusCode, nil
89 }
90
91 func (sd *ServiceAPIDescription) createKongRoute(
92                 kongControlPlaneURL string,
93                 client *resty.Client,
94                 resource Resource,
95                 apfId string,
96                 aefId string,
97                 apiVersion string ) (int, error) {
98         log.Trace("entering createKongRoute")
99
100         resourceName := resource.ResourceName
101         apiId := *sd.ApiId
102
103         tags := buildTags(apfId, aefId, apiId, apiVersion, resourceName)
104         log.Debugf("createKongRoute, tags %s", tags)
105
106         serviceName := apiId + "_" + resourceName
107         routeName := serviceName
108
109         log.Debugf("createKongRoute, serviceName %s", serviceName)
110         log.Debugf("createKongRoute, routeName %s", routeName)
111         log.Debugf("createKongRoute, aefId %s", aefId)
112
113         uri := buildUriWithVersion(apiVersion, resource.Uri)
114         log.Debugf("createKongRoute, uri %s", uri)
115
116         statusCode, err := sd.createKongService(kongControlPlaneURL, serviceName, uri, tags)
117         if (err != nil) || (statusCode != http.StatusCreated) {
118                 return statusCode, err
119         }
120
121         kongRoutesURL := kongControlPlaneURL + "/services/" + serviceName + "/routes"
122
123         // Define the route information for Kong
124         kongRouteInfo := map[string]interface{}{
125                 "name":       routeName,
126                 "paths":      []string{uri},
127                 "methods":    resource.Operations,
128                 "tags":       tags,
129                 "strip_path": true,
130         }
131
132         // Make the POST request to create the Kong service
133         resp, err := client.R().
134                 SetHeader("Content-Type", "application/json").
135                 SetBody(kongRouteInfo).
136                 Post(kongRoutesURL)
137
138         // Check for errors in the request
139         if err != nil {
140                 log.Debugf("createKongRoute POST Error: %v", err)
141                 return resp.StatusCode(), err
142         }
143
144         // Check the response status code
145         if resp.StatusCode() == http.StatusCreated {
146                 log.Infof("kong route %s created successfully", routeName)
147         } else {
148                 err = fmt.Errorf("the Kong service already exists. Status code: %d", resp.StatusCode())
149                 log.Error(err.Error())
150                 log.Errorf("response body: %s", resp.Body())
151                 return resp.StatusCode(), err
152         }
153
154         return resp.StatusCode(), nil
155 }
156
157 func buildUriWithVersion(apiVersion string, uri string) string {
158         if apiVersion != "" {
159                 if apiVersion[0] != '/' {
160                         apiVersion = "/" + apiVersion
161                 }
162                 if apiVersion[len(apiVersion)-1] != '/' && uri[0] != '/' {
163                         apiVersion = apiVersion + "/"
164                 }
165                 uri = apiVersion + uri
166         }
167         return uri
168 }
169
170 func buildTags(apfId string, aefId string, apiId string, apiVersion string, resourceName string) []string  {
171         tagsMap := map[string]string{
172                 "apfId": apfId,
173                 "aefId": aefId,
174                 "apiId": apiId,
175                 "apiVersion": apiVersion,
176                 "resourceName": resourceName,
177         }
178
179         // Convert the map to a slice of strings
180         var tagsSlice []string
181         for key, value := range tagsMap {
182                 str := fmt.Sprintf("%s: %s", key, value)
183                 tagsSlice = append(tagsSlice, str)
184         }
185
186         return tagsSlice
187 }
188
189 func (sd *ServiceAPIDescription) createKongService(kongControlPlaneURL string, kongServiceName string, kongServiceUri string, tags []string) (int, error) {
190         log.Tracef("entering createKongService")
191         log.Tracef("createKongService, kongServiceName %s", kongServiceName)
192
193         // Define the service information for Kong
194         firstAEFProfileIpv4Addr, firstAEFProfilePort, err := sd.findFirstAEFProfile()
195         if err != nil {
196                 return http.StatusBadRequest, err
197         }
198
199         kongControlPlaneURLParsed, err := url.Parse(kongControlPlaneURL)
200         if err != nil {
201                 return http.StatusInternalServerError, err
202         }
203         log.Debugf("kongControlPlaneURL %s", kongControlPlaneURL)
204         log.Debugf("kongControlPlaneURLParsed.Scheme %s", kongControlPlaneURLParsed.Scheme)
205
206         kongServiceInfo := map[string]interface{}{
207                 "host":     firstAEFProfileIpv4Addr,
208                 "name":     kongServiceName,
209                 "port":     firstAEFProfilePort,
210                 "protocol": kongControlPlaneURLParsed.Scheme,
211                 "path":     kongServiceUri,
212                 "tags":     tags,
213         }
214
215         // Kong admin API endpoint for creating a service
216         kongServicesURL := kongControlPlaneURL + "/services"
217
218         // Create a new Resty client
219         client := resty.New()
220
221         // Make the POST request to create the Kong service
222         resp, err := client.R().
223                 SetHeader("Content-Type", "application/json").
224                 SetBody(kongServiceInfo).
225                 Post(kongServicesURL)
226
227         // Check for errors in the request
228         if err != nil {
229                 log.Errorf("create Kong Service Request Error: %v", err)
230                 return http.StatusInternalServerError, err
231         }
232
233         // Check the response status code
234         statusCode := resp.StatusCode()
235         if statusCode == http.StatusCreated {
236                 log.Infof("kong service %s created successfully", kongServiceName)
237         } else if resp.StatusCode() == http.StatusConflict {
238                 log.Errorf("kong service already exists. Status code: %d", resp.StatusCode())
239                 err = fmt.Errorf("service with identical apiName is already published") // for compatibilty with Capif error message on a duplicate service
240                 statusCode = http.StatusForbidden // for compatibilty with the spec, TS29222_CAPIF_Publish_Service_API
241         } else {
242                 err = fmt.Errorf("error creating Kong service. Status code: %d", resp.StatusCode())
243         }
244         if err != nil {
245                 log.Errorf(err.Error())
246                 log.Errorf("response body: %s", resp.Body())
247         }
248
249         return statusCode, err
250 }
251
252 func (sd *ServiceAPIDescription) findFirstAEFProfile() (common29122.Ipv4Addr, common29122.Port, error) {
253         log.Tracef("entering findFirstAEFProfile")
254         var aefProfile AefProfile
255         if *sd.AefProfiles != nil {
256                 aefProfile = (*sd.AefProfiles)[0]
257         }
258         if (*sd.AefProfiles == nil) || (aefProfile.InterfaceDescriptions == nil) {
259                 err := errors.New("cannot read interfaceDescription")
260                 log.Errorf(err.Error())
261                 return "", common29122.Port(0), err
262         }
263
264         interfaceDescription := (*aefProfile.InterfaceDescriptions)[0]
265         firstIpv4Addr := *interfaceDescription.Ipv4Addr
266         firstPort := *interfaceDescription.Port
267
268         log.Debugf("findFirstAEFProfile firstIpv4Addr %s firstPort %d", firstIpv4Addr, firstPort)
269
270         return firstIpv4Addr, firstPort, nil
271 }
272
273 // Update our exposures to point to Kong by replacing in incoming interface description with Kong interface descriptions.
274 func (sd *ServiceAPIDescription) updateInterfaceDescription(kongIPv4 common29122.Ipv4Addr, kongDataPlanePort common29122.Port, kongDomain string) {
275         log.Trace("updating InterfaceDescriptions")
276         interfaceDesc := InterfaceDescription{
277                 Ipv4Addr: &kongIPv4,
278                 Port:     &kongDataPlanePort,
279         }
280         interfaceDescs := []InterfaceDescription{interfaceDesc}
281
282         profiles := *sd.AefProfiles
283         for i, profile := range profiles {
284                 profile.DomainName = &kongDomain
285                 profile.InterfaceDescriptions = &interfaceDescs
286                 profiles[i] = profile
287         }
288 }
289
290 func (sd *ServiceAPIDescription) UnregisterKong(kongDomain string, kongProtocol string, kongIPv4 common29122.Ipv4Addr, kongDataPlanePort common29122.Port, kongControlPlanePort common29122.Port) (int, error) {
291         log.Trace("entering UnregisterKong")
292
293         var (
294                 statusCode int
295                 err        error
296         )
297         kongControlPlaneURL := fmt.Sprintf("%s://%s:%d", kongProtocol, kongIPv4, kongControlPlanePort)
298
299         statusCode, err = sd.deleteKongRoutes(kongControlPlaneURL)
300         if (err != nil) || (statusCode != http.StatusNoContent) {
301                 return statusCode, err
302         }
303
304         log.Trace("exiting from UnregisterKong")
305         return statusCode, nil
306 }
307
308 func (sd *ServiceAPIDescription) deleteKongRoutes(kongControlPlaneURL string) (int, error) {
309         log.Trace("entering deleteKongRoutes")
310
311         var (
312                 statusCode int
313                 err        error
314         )
315
316         client := resty.New()
317
318         profiles := *sd.AefProfiles
319         for _, profile := range profiles {
320                 log.Debugf("deleteKongRoutes, AefId %s", profile.AefId)
321                 for _, version := range profile.Versions {
322                         log.Debugf("deleteKongRoutes, apiVersion \"%s\"", version.ApiVersion)
323                         for _, resource := range *version.Resources {
324                                 statusCode, err = sd.deleteKongRoute(kongControlPlaneURL, client, resource, profile.AefId, version.ApiVersion)
325                                 if (err != nil) || (statusCode != http.StatusNoContent) {
326                                         return statusCode, err
327                                 }
328                         }
329                 }
330         }
331         return statusCode, nil
332 }
333
334 func (sd *ServiceAPIDescription) deleteKongRoute(kongControlPlaneURL string, client *resty.Client, resource Resource, aefId string, apiVersion string) (int, error) {
335         log.Trace("entering deleteKongRoute")
336         routeName := *sd.ApiId + "_" + resource.ResourceName
337         kongRoutesURL := kongControlPlaneURL + "/routes/" + routeName + "?tags=" + aefId
338         log.Debugf("deleteKongRoute, routeName %s, tag %s", routeName, aefId)
339
340         // Make the DELETE request to delete the Kong route
341         resp, err := client.R().Delete(kongRoutesURL)
342
343         // Check for errors in the request
344         if err != nil {
345                 log.Errorf("error on Kong route delete: %v", err)
346                 return resp.StatusCode(), err
347         }
348
349         // Check the response status code
350         if resp.StatusCode() == http.StatusNoContent {
351                 log.Infof("kong route %s deleted successfully", routeName)
352         } else {
353                 log.Errorf("error deleting Kong route. Status code: %d", resp.StatusCode())
354                 log.Errorf("response body: %s", resp.Body())
355                 return resp.StatusCode(), err
356         }
357
358         statusCode, err := sd.deleteKongService(kongControlPlaneURL, routeName, aefId)
359         if (err != nil) || (statusCode != http.StatusNoContent) {
360                 return statusCode, err
361         }
362         return statusCode, err
363 }
364
365 func (sd *ServiceAPIDescription) deleteKongService(kongControlPlaneURL string, serviceName string, aefId string) (int, error) {
366         log.Trace("entering deleteKongService")
367         // Define the service information for Kong
368         // Kong admin API endpoint for deleting a service
369         kongServicesURL := kongControlPlaneURL + "/services/" + serviceName + "?tags=" + aefId
370
371         // Create a new Resty client
372         client := resty.New()
373
374         // Make the DELETE request to delete the Kong service
375         resp, err := client.R().
376                 SetHeader("Content-Type", "application/json").
377                 Delete(kongServicesURL)
378
379         // Check for errors in the request
380         if err != nil {
381                 log.Errorf("delete kong service request: %v", err)
382                 return http.StatusInternalServerError, err
383         }
384
385         // Check the response status code
386         if resp.StatusCode() == http.StatusNoContent {
387                 log.Infof("kong service %s deleted successfully", serviceName)
388         } else {
389                 log.Errorf("deleting Kong service, status code: %d", resp.StatusCode())
390                 log.Errorf("response body: %s", resp.Body())
391         }
392         return resp.StatusCode(), nil
393 }