K8sPlugin: support UAT functionality
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / k8s-connection-plugin / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / k8s / query / K8sPluginQueryApi.kt
1 package org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.query
2
3 import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration
4 import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.query.K8sQueryRestClient.Companion.getK8sQueryRestClient
5 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
6 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
7 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
8 import org.slf4j.LoggerFactory
9 import org.springframework.http.HttpMethod.GET
10
11 public class K8sPluginQueryApi(
12     private val k8sConfiguration: K8sConnectionPluginConfiguration
13 ) {
14     private val log = LoggerFactory.getLogger(K8sPluginQueryApi::class.java)!!
15
16     fun queryK8sResources(
17         cloudRegion: String,
18         kind: String,
19         apiVersion: String,
20         name: String? = null,
21         namespace: String? = null,
22         labels: Map<String, String>? = null
23     ): K8sResourceStatus? {
24         val rbQueryService = getK8sQueryRestClient(k8sConfiguration)
25         try {
26             var path: String = "?CloudRegion=$cloudRegion&ApiVersion=$apiVersion&Kind=$kind"
27             if (name != null)
28                 path = path.plus("&Name=$name")
29             if (namespace != null)
30                 path = path.plus("&Namespace=$namespace")
31             if (labels != null && labels.isNotEmpty()) {
32                 path = path.plus("&Labels=")
33                 for ((name, value) in labels)
34                     path = path.plus("$name%3D$value,")
35                 path = path.trimEnd(',')
36             }
37             val result: BlueprintWebClientService.WebClientResponse<String> = rbQueryService.exchangeResource(
38                 GET.name,
39                 path,
40                 ""
41             )
42             log.debug(result.toString())
43             return if (result.status in 200..299) {
44                 val parsedObject: K8sResourceStatus? = JacksonUtils.readValue(
45                     result.body, K8sResourceStatus::class.java
46                 )
47                 parsedObject
48             } else if (result.status == 500 && result.body.contains("Error finding master table"))
49                 null
50             else
51                 throw BluePrintProcessorException(result.body)
52         } catch (e: Exception) {
53             log.error("Caught exception trying to get k8s rb instance")
54             throw BluePrintProcessorException("${e.message}")
55         }
56     }
57 }