2 // ========================LICENSE_START=================================
5 // Copyright (C) 2023-2024: OpenInfra Foundation Europe
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 publishserviceapi
30 resty "github.com/go-resty/resty/v2"
31 log "github.com/sirupsen/logrus"
33 common29122 "oransc.org/nonrtric/servicemanager/internal/common29122"
36 func (sd *ServiceAPIDescription) PrepareNewService() {
37 apiName := "api_id_" + strings.ReplaceAll(sd.ApiName, " ", "_")
41 func (sd *ServiceAPIDescription) RegisterKong(kongDomain string,
43 kongIPv4 common29122.Ipv4Addr,
44 kongDataPlanePort common29122.Port,
45 kongControlPlanePort common29122.Port,
46 apfId string) (int, error) {
48 log.Trace("entering RegisterKong")
53 kongControlPlaneURL := fmt.Sprintf("%s://%s:%d", kongProtocol, kongIPv4, kongControlPlanePort)
55 statusCode, err = sd.createKongRoutes(kongControlPlaneURL, apfId)
56 if (err != nil) || (statusCode != http.StatusCreated) {
57 return statusCode, err
60 sd.updateInterfaceDescription(kongIPv4, kongDataPlanePort, kongDomain)
62 log.Trace("exiting from RegisterKong")
63 return statusCode, nil
66 func (sd *ServiceAPIDescription) createKongRoutes(kongControlPlaneURL string, apfId string) (int, error) {
67 log.Trace("entering createKongRoutes")
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
88 return statusCode, nil
91 func (sd *ServiceAPIDescription) createKongRoute(
92 kongControlPlaneURL string,
97 apiVersion string ) (int, error) {
98 log.Trace("entering createKongRoute")
100 resourceName := resource.ResourceName
103 tags := buildTags(apfId, aefId, apiId, apiVersion, resourceName)
104 log.Debugf("createKongRoute, tags %s", tags)
106 serviceName := apiId + "_" + resourceName
107 routeName := serviceName
109 log.Debugf("createKongRoute, serviceName %s", serviceName)
110 log.Debugf("createKongRoute, routeName %s", routeName)
111 log.Debugf("createKongRoute, aefId %s", aefId)
113 uri := buildUriWithVersion(apiVersion, resource.Uri)
114 log.Debugf("createKongRoute, uri %s", uri)
116 statusCode, err := sd.createKongService(kongControlPlaneURL, serviceName, uri, tags)
117 if (err != nil) || (statusCode != http.StatusCreated) {
118 return statusCode, err
121 kongRoutesURL := kongControlPlaneURL + "/services/" + serviceName + "/routes"
123 // Define the route information for Kong
124 kongRouteInfo := map[string]interface{}{
126 "paths": []string{uri},
127 "methods": resource.Operations,
132 // Make the POST request to create the Kong service
133 resp, err := client.R().
134 SetHeader("Content-Type", "application/json").
135 SetBody(kongRouteInfo).
138 // Check for errors in the request
140 log.Debugf("createKongRoute POST Error: %v", err)
141 return resp.StatusCode(), err
144 // Check the response status code
145 if resp.StatusCode() == http.StatusCreated {
146 log.Infof("kong route %s created successfully", routeName)
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
154 return resp.StatusCode(), nil
157 func buildUriWithVersion(apiVersion string, uri string) string {
158 if apiVersion != "" {
159 if apiVersion[0] != '/' {
160 apiVersion = "/" + apiVersion
162 if apiVersion[len(apiVersion)-1] != '/' && uri[0] != '/' {
163 apiVersion = apiVersion + "/"
165 uri = apiVersion + uri
170 func buildTags(apfId string, aefId string, apiId string, apiVersion string, resourceName string) []string {
171 tagsMap := map[string]string{
175 "apiVersion": apiVersion,
176 "resourceName": resourceName,
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)
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)
193 // Define the service information for Kong
194 firstAEFProfileIpv4Addr, firstAEFProfilePort, err := sd.findFirstAEFProfile()
196 return http.StatusBadRequest, err
199 kongControlPlaneURLParsed, err := url.Parse(kongControlPlaneURL)
201 return http.StatusInternalServerError, err
203 log.Debugf("kongControlPlaneURL %s", kongControlPlaneURL)
204 log.Debugf("kongControlPlaneURLParsed.Scheme %s", kongControlPlaneURLParsed.Scheme)
206 kongServiceInfo := map[string]interface{}{
207 "host": firstAEFProfileIpv4Addr,
208 "name": kongServiceName,
209 "port": firstAEFProfilePort,
210 "protocol": kongControlPlaneURLParsed.Scheme,
211 "path": kongServiceUri,
215 // Kong admin API endpoint for creating a service
216 kongServicesURL := kongControlPlaneURL + "/services"
218 // Create a new Resty client
219 client := resty.New()
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)
227 // Check for errors in the request
229 log.Errorf("create Kong Service Request Error: %v", err)
230 return http.StatusInternalServerError, err
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
242 err = fmt.Errorf("error creating Kong service. Status code: %d", resp.StatusCode())
245 log.Errorf(err.Error())
246 log.Errorf("response body: %s", resp.Body())
249 return statusCode, err
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]
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
264 interfaceDescription := (*aefProfile.InterfaceDescriptions)[0]
265 firstIpv4Addr := *interfaceDescription.Ipv4Addr
266 firstPort := *interfaceDescription.Port
268 log.Debugf("findFirstAEFProfile firstIpv4Addr %s firstPort %d", firstIpv4Addr, firstPort)
270 return firstIpv4Addr, firstPort, nil
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{
278 Port: &kongDataPlanePort,
280 interfaceDescs := []InterfaceDescription{interfaceDesc}
282 profiles := *sd.AefProfiles
283 for i, profile := range profiles {
284 profile.DomainName = &kongDomain
285 profile.InterfaceDescriptions = &interfaceDescs
286 profiles[i] = profile
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")
297 kongControlPlaneURL := fmt.Sprintf("%s://%s:%d", kongProtocol, kongIPv4, kongControlPlanePort)
299 statusCode, err = sd.deleteKongRoutes(kongControlPlaneURL)
300 if (err != nil) || (statusCode != http.StatusNoContent) {
301 return statusCode, err
304 log.Trace("exiting from UnregisterKong")
305 return statusCode, nil
308 func (sd *ServiceAPIDescription) deleteKongRoutes(kongControlPlaneURL string) (int, error) {
309 log.Trace("entering deleteKongRoutes")
316 client := resty.New()
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
331 return statusCode, nil
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)
340 // Make the DELETE request to delete the Kong route
341 resp, err := client.R().Delete(kongRoutesURL)
343 // Check for errors in the request
345 log.Errorf("error on Kong route delete: %v", err)
346 return resp.StatusCode(), err
349 // Check the response status code
350 if resp.StatusCode() == http.StatusNoContent {
351 log.Infof("kong route %s deleted successfully", routeName)
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
358 statusCode, err := sd.deleteKongService(kongControlPlaneURL, routeName, aefId)
359 if (err != nil) || (statusCode != http.StatusNoContent) {
360 return statusCode, err
362 return statusCode, err
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
371 // Create a new Resty client
372 client := resty.New()
374 // Make the DELETE request to delete the Kong service
375 resp, err := client.R().
376 SetHeader("Content-Type", "application/json").
377 Delete(kongServicesURL)
379 // Check for errors in the request
381 log.Errorf("delete kong service request: %v", err)
382 return http.StatusInternalServerError, err
385 // Check the response status code
386 if resp.StatusCode() == http.StatusNoContent {
387 log.Infof("kong service %s deleted successfully", serviceName)
389 log.Errorf("deleting Kong service, status code: %d", resp.StatusCode())
390 log.Errorf("response body: %s", resp.Body())
392 return resp.StatusCode(), nil