diff options
author | 2022-10-26 22:42:46 +0530 | |
---|---|---|
committer | 2022-10-31 18:33:22 +0530 | |
commit | a7ba8d739afc31ff1f1427bdabe935c0abc2e3ac (patch) | |
tree | d910c205cf833a43ed47de6ad3bfd11b1c21c576 /components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin | |
parent | bc0799957d1825e6cdeda60c294d6cf74281a035 (diff) |
Updated for Jakarta Release
Change to native helm, and removed generate-name capability reference.
Issue-ID: SO-3835
Change-Id: I59f4271872db1e94c189a3b375da1fe30d1089a3
Signed-off-by: sangeeta.bellara <sangeeta.bellara@t-systems.com>
Diffstat (limited to 'components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin')
3 files changed, 963 insertions, 963 deletions
diff --git a/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinDayOneConfig.kt b/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinDayOneConfig.kt index 1e13ec048..f07fad882 100644 --- a/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinDayOneConfig.kt +++ b/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinDayOneConfig.kt @@ -1,438 +1,438 @@ -/* -* Copyright © 2019 TechMahindra -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts - -import com.fasterxml.jackson.annotation.JsonIgnore -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.node.ObjectNode -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import java.io.File -import java.nio.file.Path -import java.nio.file.Paths -import org.apache.commons.io.FilenameUtils -import org.apache.commons.io.IOUtils -import org.apache.http.client.ClientProtocolException -import org.apache.http.client.entity.EntityBuilder -import org.apache.http.client.methods.HttpPost -import org.apache.http.client.methods.HttpUriRequest -import org.apache.http.entity.ContentType -import org.apache.http.message.BasicHeader -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sDefinitionRestClient -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.RestLoggerService -import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction -import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.contentFromResolvedArtifactNB -import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.storedContentFromResolvedArtifactNB -import org.slf4j.LoggerFactory -import org.springframework.http.HttpHeaders -import org.springframework.http.HttpMethod -import org.springframework.http.MediaType -import org.springframework.web.client.RestTemplate -import org.yaml.snakeyaml.Yaml -import java.util.ArrayList -import java.io.IOException - -import java.util.Base64 -import java.nio.charset.Charset -import java.nio.file.Files -import com.google.gson.Gson -import com.google.gson.reflect.TypeToken - -open class DayOneConfig : AbstractScriptComponentFunction() { - - private val log = LoggerFactory.getLogger(DayOneConfig::class.java)!! - - override fun getName(): String { - return "DayOneConfig" - } - - override suspend fun processNB(executionRequest: ExecutionServiceInput) { - log.info("DAY-1 Script excution Started") - - val prefix = "baseconfig" - - val baseK8sApiUrl = getDynamicProperties("api-access").get("url").asText() - val k8sApiUsername = getDynamicProperties("api-access").get("username").asText() - val k8sApiPassword = getDynamicProperties("api-access").get("password").asText() - - log.info("Multi-cloud params $baseK8sApiUrl") - - val aaiApiUrl = getDynamicProperties("aai-access").get("url").asText() - val aaiApiUsername = getDynamicProperties("aai-access").get("username").asText() - val aaiApiPassword = getDynamicProperties("aai-access").get("password").asText() - - - - log.info("AAI params $aaiApiUrl") - - - - - val resolution_key = getDynamicProperties("resolution-key").asText() - - val sdnc_payload:String = contentFromResolvedArtifactNB("config-deploy-sdnc") - //log.info("SDNC payload $sdnc_payload") - val sdnc_payloadObject = JacksonUtils.jsonNode(sdnc_payload) as ObjectNode - - - val aai_payload:String = contentFromResolvedArtifactNB("config-deploy-aai") - //log.info("AAI payload $aai_payload") - val aai_payloadObject = JacksonUtils.jsonNode(aai_payload) as ObjectNode - - - - - - - try { - - for (item in sdnc_payloadObject.get("vf-modules")){ - - var instanceID:String ="" - val modelTopology = item.get("vf-module-data").get("vf-module-topology") - - - - val moduleParameters = modelTopology.get("vf-module-parameters").get("param") - - val label: String? = getParamValueByName(moduleParameters, "vf-module-label") - val modelInfo = modelTopology.get("onap-model-information") - val vfModuleInvariantID = modelInfo.get("model-invariant-uuid").asText() - log.info("VF MOdule Inavriant ID $vfModuleInvariantID") - val vfModuleCustID=modelInfo.get("model-customization-uuid").asText() - val vfModuleUUID=modelInfo.get("model-uuid").asText() - val idInfo = modelTopology.get("vf-module-topology-identifier") - val vfModuleID = idInfo.get("vf-module-id").asText() - for (aai_item in aai_payloadObject.get("vf-modules")) - { - if (aai_item.get("vf-module-id").asText() == vfModuleID && aai_item.get("heat-stack-id") != null) - { - instanceID=aai_item.get("heat-stack-id").asText() - break - } - } - - - - val k8sRbProfileName: String = "profile_" + vfModuleID - - val k8sConfigTemplateName: String = "template_" + vfModuleCustID - - val api = K8sConfigTemplateApi(k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleInvariantID, vfModuleCustID, k8sConfigTemplateName) - - // Check if definition exists - if (!api.hasDefinition()) { - throw BluePrintProcessorException("K8S Definition ($vfModuleInvariantID/$vfModuleCustID) not found ") - } - val bluePrintPropertiesService: BluePrintPropertiesService =this.functionDependencyInstanceAsType("bluePrintPropertiesService") - val k8sConfiguration = K8sConnectionPluginConfiguration(bluePrintPropertiesService) - val rbDefinitionService = K8sDefinitionRestClient(k8sConfiguration,vfModuleInvariantID, vfModuleCustID) - - - val def: BlueprintWebClientService.WebClientResponse<String> = rbDefinitionService.exchangeResource(HttpMethod.GET.name,"","") - log.info(def.body.toString()) - val rbdef = JacksonUtils.jsonNode(def.body.toString()) as ObjectNode - val chartName = rbdef.get("chart-name").asText() - - log.info("Config Template name: $k8sConfigTemplateName") - - - - var configTemplate = K8sConfigTemplate() - configTemplate.templateName = k8sConfigTemplateName - configTemplate.description = " " - configTemplate.ChartName = chartName - log.info("Chart name: ${configTemplate.ChartName}") - - - - if (!api.hasConfigTemplate(configTemplate)) { - - - val configTemplateFile: Path = prepareConfigTemplateJson(k8sConfigTemplateName, vfModuleID, label) - - log.info("Config Template Upload Started") - api.createConfigTemplate(configTemplate) - api.uploadConfigTemplateContent(configTemplate, configTemplateFile) - log.info("Config Template Upload Completed") - } - } - log.info("DAY-1 Script excution completed") - - - } - catch (e: Exception) { - log.info("Caught exception during config template preparation!!") - throw BluePrintProcessorException("${e.message}") - } - } - private fun getParamValueByName(params: JsonNode, paramName: String): String? { - for (param in params) { - if (param.get("name").asText() == paramName && param.get("value").asText() != "null") { - return param.get("value").asText() - - } - } - return null - } - - fun prepareConfigTemplateJson(configTemplateName: String, vfModuleID: String, label: String?): Path { - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - val bluePrintBasePath: String = bluePrintContext.rootPath - - var profileFilePath: Path = Paths.get(bluePrintBasePath.plus(File.separator).plus("Templates").plus(File.separator).plus("k8s-profiles").plus(File.separator).plus(label +"-config-template.tar.gz")) - log.info("Reading K8s Config Template file: $profileFilePath") - - val profileFile = profileFilePath.toFile() - - if (!profileFile.exists()) - throw BluePrintProcessorException("K8s Config template file $profileFilePath does not exists") - - return profileFilePath - } - - - fun getResolvedParameter(payload: ObjectNode, keyName: String): String { - for (node in payload.get("resource-accumulator-resolved-data").elements()) { - if (node.get("param-name").asText().equals(keyName)) { - return node.get("param-value").asText() - } - } - return "" - } - override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - log.info("Recover function called!") - log.info("Execution request : $executionRequest") - log.error("Exception", runtimeException) - addError(runtimeException.message!!) - } - - - - inner class K8sConfigTemplateApi( - val username: String, - val password: String, - val baseUrl: String, - val definition: String, - val definitionVersion: String, - val configTemplateName: String - ) { - private val service: UploadConfigTemplateRestClientService // BasicAuthRestClientService - - init { - var mapOfHeaders = hashMapOf<String, String>() - mapOfHeaders.put("Accept", "application/json") - mapOfHeaders.put("Content-Type", "application/json") - mapOfHeaders.put("cache-control", " no-cache") - mapOfHeaders.put("Accept", "application/json") - var basicAuthRestClientProperties: BasicAuthRestClientProperties = BasicAuthRestClientProperties() - basicAuthRestClientProperties.username = username - basicAuthRestClientProperties.password = password - basicAuthRestClientProperties.url = "$baseUrl/v1/rb/definition/$definition/$definitionVersion" - basicAuthRestClientProperties.additionalHeaders = mapOfHeaders - - this.service = UploadConfigTemplateRestClientService(basicAuthRestClientProperties) - } - - fun hasDefinition(): Boolean { - try { - val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource(HttpMethod.GET.name, "", "") - print(result) - if (result.status >= 200 && result.status < 300) - return true - else - return false - } catch (e: Exception) { - log.info("Caught exception trying to get k8s config trmplate definition") - throw BluePrintProcessorException("${e.message}") - } - } - - fun hasConfigTemplate(profile: K8sConfigTemplate): Boolean { - try { - val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource(HttpMethod.GET.name, "/config-template/${profile.templateName}", "") - print(result) - if (result.status >= 200 && result.status < 300) { - log.info("ConfigTemplate already exists") - return true - } else - return false - } catch (e: Exception) { - log.info("Caught exception trying to get k8s config trmplate definition") - throw BluePrintProcessorException("${e.message}") - } - } - - fun createConfigTemplate(profile: K8sConfigTemplate) { - val objectMapper = ObjectMapper() - val profileJsonString: String = objectMapper.writeValueAsString(profile) - try { - val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource( - HttpMethod.POST.name, - "/config-template", - profileJsonString - ) - - if (result.status >= 200 && result.status < 300) { - log.info("Config template json info uploaded correctly") - } else if (result.status < 200 || result.status >= 300) { - log.info("Config template already exists") - } - } catch (e: Exception) { - log.info("Caught exception trying to create k8s config template ${profile.templateName} - updated") - // throw BluePrintProcessorException("${e.message}") - } - } - - fun uploadConfigTemplateContent(profile: K8sConfigTemplate, filePath: Path) { - try { - val result: BlueprintWebClientService.WebClientResponse<String> = service.uploadBinaryFile( - "/config-template/${profile.templateName}/content", - filePath - ) - if (result.status < 200 || result.status >= 300) { - throw Exception(result.body) - } - } catch (e: Exception) { - log.info("Caught exception trying to upload k8s config template ${profile.templateName}") - throw BluePrintProcessorException("${e.message}") - } - } - } -} - -class UploadConfigTemplateRestClientService( - private val restClientProperties: - BasicAuthRestClientProperties -) : BlueprintWebClientService { - - override fun defaultHeaders(): Map<String, String> { - - val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password - ) - return mapOf( - HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials" - ) - } - - override fun host(uri: String): String { - return restClientProperties.url + uri - } - - override fun convertToBasicHeaders(headers: Map<String, String>): - Array<BasicHeader> { - val customHeaders: MutableMap<String, String> = headers.toMutableMap() - // inject additionalHeaders - customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) - - if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { - val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password - ) - customHeaders[HttpHeaders.AUTHORIZATION] = - "Basic $encodedCredentials" - } - return super.convertToBasicHeaders(customHeaders) - } - - private fun setBasicAuth(username: String, password: String): String { - val credentialsString = "$username:$password" - return Base64.getEncoder().encodeToString( - credentialsString.toByteArray(Charset.defaultCharset()) - ) - } - - @Throws(IOException::class, ClientProtocolException::class) - private fun performHttpCall(httpUriRequest: HttpUriRequest): BlueprintWebClientService.WebClientResponse<String> { - val httpResponse = httpClient().execute(httpUriRequest) - val statusCode = httpResponse.statusLine.statusCode - httpResponse.entity.content.use { - val body = IOUtils.toString(it, Charset.defaultCharset()) - return BlueprintWebClientService.WebClientResponse(statusCode, body) - } - } - - fun uploadBinaryFile(path: String, filePath: Path): BlueprintWebClientService.WebClientResponse<String> { - val convertedHeaders: Array<BasicHeader> = convertToBasicHeaders(defaultHeaders()) - val httpPost = HttpPost(host(path)) - val entity = EntityBuilder.create().setBinary(Files.readAllBytes(filePath)).build() - httpPost.setEntity(entity) - RestLoggerService.httpInvoking(convertedHeaders) - httpPost.setHeaders(convertedHeaders) - return performHttpCall(httpPost) - } -} - -class K8sConfigTemplate { - @get:JsonProperty("template-name") - var templateName: String? = null - @get:JsonProperty("description") - var description: String? = null - @get:JsonProperty("ChartName") - var ChartName: String? = null - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - return true - } - - override fun hashCode(): Int { - return javaClass.hashCode() - } -} - -class K8sResources { - - var GVK: GVK? = null - lateinit var Name: String - -} - -class GVK { - - var Group: String? = null - var Version: String? = null - var Kind: String? = null - -} - -fun main(args: Array<String>) { - - val kotlin = DayOneConfig() - - - -} +/*
+* Copyright © 2019 TechMahindra
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
+
+import com.fasterxml.jackson.annotation.JsonIgnore
+import com.fasterxml.jackson.annotation.JsonProperty
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import java.io.File
+import java.nio.file.Path
+import java.nio.file.Paths
+import org.apache.commons.io.FilenameUtils
+import org.apache.commons.io.IOUtils
+import org.apache.http.client.ClientProtocolException
+import org.apache.http.client.entity.EntityBuilder
+import org.apache.http.client.methods.HttpPost
+import org.apache.http.client.methods.HttpUriRequest
+import org.apache.http.entity.ContentType
+import org.apache.http.message.BasicHeader
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
+import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sDefinitionRestClient
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.RestLoggerService
+import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.contentFromResolvedArtifactNB
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.storedContentFromResolvedArtifactNB
+import org.slf4j.LoggerFactory
+import org.springframework.http.HttpHeaders
+import org.springframework.http.HttpMethod
+import org.springframework.http.MediaType
+import org.springframework.web.client.RestTemplate
+import org.yaml.snakeyaml.Yaml
+import java.util.ArrayList
+import java.io.IOException
+
+import java.util.Base64
+import java.nio.charset.Charset
+import java.nio.file.Files
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+
+open class DayOneConfig : AbstractScriptComponentFunction() {
+
+ private val log = LoggerFactory.getLogger(DayOneConfig::class.java)!!
+
+ override fun getName(): String {
+ return "DayOneConfig"
+ }
+
+ override suspend fun processNB(executionRequest: ExecutionServiceInput) {
+ log.info("DAY-1 Script excution Started")
+
+ val prefix = "baseconfig"
+
+ val baseK8sApiUrl = getDynamicProperties("api-access").get("url").asText()
+ val k8sApiUsername = getDynamicProperties("api-access").get("username").asText()
+ val k8sApiPassword = getDynamicProperties("api-access").get("password").asText()
+
+ log.info("Multi-cloud params $baseK8sApiUrl")
+
+ val aaiApiUrl = getDynamicProperties("aai-access").get("url").asText()
+ val aaiApiUsername = getDynamicProperties("aai-access").get("username").asText()
+ val aaiApiPassword = getDynamicProperties("aai-access").get("password").asText()
+
+
+
+ log.info("AAI params $aaiApiUrl")
+
+
+
+
+ val resolution_key = getDynamicProperties("resolution-key").asText()
+
+ val sdnc_payload:String = contentFromResolvedArtifactNB("config-deploy-sdnc")
+ //log.info("SDNC payload $sdnc_payload")
+val sdnc_payloadObject = JacksonUtils.jsonNode(sdnc_payload) as ObjectNode
+
+
+ val aai_payload:String = contentFromResolvedArtifactNB("config-deploy-aai")
+ //log.info("AAI payload $aai_payload")
+val aai_payloadObject = JacksonUtils.jsonNode(aai_payload) as ObjectNode
+
+
+
+
+
+
+ try {
+
+ for (item in sdnc_payloadObject.get("vf-modules")){
+
+ var instanceID:String =""
+ val modelTopology = item.get("vf-module-data").get("vf-module-topology")
+
+
+
+ val moduleParameters = modelTopology.get("vf-module-parameters").get("param")
+
+ val label: String? = getParamValueByName(moduleParameters, "vf-module-label")
+ val modelInfo = modelTopology.get("onap-model-information")
+ val vfModuleInvariantID = modelInfo.get("model-invariant-uuid").asText()
+ log.info("VF MOdule Inavriant ID $vfModuleInvariantID")
+ val vfModuleCustID=modelInfo.get("model-customization-uuid").asText()
+ val vfModuleUUID=modelInfo.get("model-uuid").asText()
+ val idInfo = modelTopology.get("vf-module-topology-identifier")
+ val vfModuleID = idInfo.get("vf-module-id").asText()
+ for (aai_item in aai_payloadObject.get("vf-modules"))
+ {
+ if (aai_item.get("vf-module-id").asText() == vfModuleID && aai_item.get("heat-stack-id") != null)
+ {
+ instanceID=aai_item.get("heat-stack-id").asText()
+ break
+ }
+ }
+
+
+
+ val k8sRbProfileName: String = "profile_" + vfModuleID
+
+ val k8sConfigTemplateName: String = "template_" + vfModuleCustID
+
+ val api = K8sConfigTemplateApi(k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleInvariantID, vfModuleCustID, k8sConfigTemplateName)
+
+ // Check if definition exists
+ if (!api.hasDefinition()) {
+ throw BluePrintProcessorException("K8S Definition ($vfModuleInvariantID/$vfModuleCustID) not found ")
+ }
+ val bluePrintPropertiesService: BluePrintPropertiesService =this.functionDependencyInstanceAsType("bluePrintPropertiesService")
+ val k8sConfiguration = K8sConnectionPluginConfiguration(bluePrintPropertiesService)
+ val rbDefinitionService = K8sDefinitionRestClient(k8sConfiguration,vfModuleInvariantID, vfModuleCustID)
+
+
+ val def: BlueprintWebClientService.WebClientResponse<String> = rbDefinitionService.exchangeResource(HttpMethod.GET.name,"","")
+ log.info(def.body.toString())
+ val rbdef = JacksonUtils.jsonNode(def.body.toString()) as ObjectNode
+ val chartName = rbdef.get("chart-name").asText()
+
+ log.info("Config Template name: $k8sConfigTemplateName")
+
+
+
+ var configTemplate = K8sConfigTemplate()
+ configTemplate.templateName = k8sConfigTemplateName
+ configTemplate.description = " "
+ configTemplate.ChartName = chartName
+ log.info("Chart name: ${configTemplate.ChartName}")
+
+
+
+ if (!api.hasConfigTemplate(configTemplate)) {
+
+
+ val configTemplateFile: Path = prepareConfigTemplateJson(k8sConfigTemplateName, vfModuleID, label)
+
+ log.info("Config Template Upload Started")
+ api.createConfigTemplate(configTemplate)
+ api.uploadConfigTemplateContent(configTemplate, configTemplateFile)
+ log.info("Config Template Upload Completed")
+ }
+ }
+ log.info("DAY-1 Script excution completed")
+
+
+ }
+ catch (e: Exception) {
+ log.info("Caught exception during config template preparation!!")
+ throw BluePrintProcessorException("${e.message}")
+ }
+ }
+ private fun getParamValueByName(params: JsonNode, paramName: String): String? {
+ for (param in params) {
+ if (param.get("name").asText() == paramName && param.get("value").asText() != "null") {
+ return param.get("value").asText()
+
+ }
+ }
+ return null
+ }
+
+ fun prepareConfigTemplateJson(configTemplateName: String, vfModuleID: String, label: String?): Path {
+ val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
+ val bluePrintBasePath: String = bluePrintContext.rootPath
+
+ var profileFilePath: Path = Paths.get(bluePrintBasePath.plus(File.separator).plus("Templates").plus(File.separator).plus("k8s-profiles").plus(File.separator).plus(label +"-config-template.tar.gz"))
+ log.info("Reading K8s Config Template file: $profileFilePath")
+
+ val profileFile = profileFilePath.toFile()
+
+ if (!profileFile.exists())
+ throw BluePrintProcessorException("K8s Config template file $profileFilePath does not exists")
+
+ return profileFilePath
+ }
+
+
+ fun getResolvedParameter(payload: ObjectNode, keyName: String): String {
+ for (node in payload.get("resource-accumulator-resolved-data").elements()) {
+ if (node.get("param-name").asText().equals(keyName)) {
+ return node.get("param-value").asText()
+ }
+ }
+ return ""
+ }
+ override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
+ log.info("Recover function called!")
+ log.info("Execution request : $executionRequest")
+ log.error("Exception", runtimeException)
+ addError(runtimeException.message!!)
+ }
+
+
+
+ inner class K8sConfigTemplateApi(
+ val username: String,
+ val password: String,
+ val baseUrl: String,
+ val definition: String,
+ val definitionVersion: String,
+ val configTemplateName: String
+ ) {
+ private val service: UploadConfigTemplateRestClientService // BasicAuthRestClientService
+
+ init {
+ var mapOfHeaders = hashMapOf<String, String>()
+ mapOfHeaders.put("Accept", "application/json")
+ mapOfHeaders.put("Content-Type", "application/json")
+ mapOfHeaders.put("cache-control", " no-cache")
+ mapOfHeaders.put("Accept", "application/json")
+ var basicAuthRestClientProperties: BasicAuthRestClientProperties = BasicAuthRestClientProperties()
+ basicAuthRestClientProperties.username = username
+ basicAuthRestClientProperties.password = password
+ basicAuthRestClientProperties.url = "$baseUrl/v1/rb/definition/$definition/$definitionVersion"
+ basicAuthRestClientProperties.additionalHeaders = mapOfHeaders
+
+ this.service = UploadConfigTemplateRestClientService(basicAuthRestClientProperties)
+ }
+
+ fun hasDefinition(): Boolean {
+ try {
+ val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource(HttpMethod.GET.name, "", "")
+ print(result)
+ if (result.status >= 200 && result.status < 300)
+ return true
+ else
+ return false
+ } catch (e: Exception) {
+ log.info("Caught exception trying to get k8s config trmplate definition")
+ throw BluePrintProcessorException("${e.message}")
+ }
+ }
+
+ fun hasConfigTemplate(profile: K8sConfigTemplate): Boolean {
+ try {
+ val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource(HttpMethod.GET.name, "/config-template/${profile.templateName}", "")
+ print(result)
+ if (result.status >= 200 && result.status < 300) {
+ log.info("ConfigTemplate already exists")
+ return true
+ } else
+ return false
+ } catch (e: Exception) {
+ log.info("Caught exception trying to get k8s config trmplate definition")
+ throw BluePrintProcessorException("${e.message}")
+ }
+ }
+
+ fun createConfigTemplate(profile: K8sConfigTemplate) {
+ val objectMapper = ObjectMapper()
+ val profileJsonString: String = objectMapper.writeValueAsString(profile)
+ try {
+ val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource(
+ HttpMethod.POST.name,
+ "/config-template",
+ profileJsonString
+ )
+
+ if (result.status >= 200 && result.status < 300) {
+ log.info("Config template json info uploaded correctly")
+ } else if (result.status < 200 || result.status >= 300) {
+ log.info("Config template already exists")
+ }
+ } catch (e: Exception) {
+ log.info("Caught exception trying to create k8s config template ${profile.templateName} - updated")
+ // throw BluePrintProcessorException("${e.message}")
+ }
+ }
+
+ fun uploadConfigTemplateContent(profile: K8sConfigTemplate, filePath: Path) {
+ try {
+ val result: BlueprintWebClientService.WebClientResponse<String> = service.uploadBinaryFile(
+ "/config-template/${profile.templateName}/content",
+ filePath
+ )
+ if (result.status < 200 || result.status >= 300) {
+ throw Exception(result.body)
+ }
+ } catch (e: Exception) {
+ log.info("Caught exception trying to upload k8s config template ${profile.templateName}")
+ throw BluePrintProcessorException("${e.message}")
+ }
+ }
+ }
+}
+
+class UploadConfigTemplateRestClientService(
+ private val restClientProperties:
+ BasicAuthRestClientProperties
+) : BlueprintWebClientService {
+
+ override fun defaultHeaders(): Map<String, String> {
+
+ val encodedCredentials = setBasicAuth(
+ restClientProperties.username,
+ restClientProperties.password
+ )
+ return mapOf(
+ HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials"
+ )
+ }
+
+ override fun host(uri: String): String {
+ return restClientProperties.url + uri
+ }
+
+ override fun convertToBasicHeaders(headers: Map<String, String>):
+ Array<BasicHeader> {
+ val customHeaders: MutableMap<String, String> = headers.toMutableMap()
+ // inject additionalHeaders
+ customHeaders.putAll(verifyAdditionalHeaders(restClientProperties))
+
+ if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
+ val encodedCredentials = setBasicAuth(
+ restClientProperties.username,
+ restClientProperties.password
+ )
+ customHeaders[HttpHeaders.AUTHORIZATION] =
+ "Basic $encodedCredentials"
+ }
+ return super.convertToBasicHeaders(customHeaders)
+ }
+
+ private fun setBasicAuth(username: String, password: String): String {
+ val credentialsString = "$username:$password"
+ return Base64.getEncoder().encodeToString(
+ credentialsString.toByteArray(Charset.defaultCharset())
+ )
+ }
+
+ @Throws(IOException::class, ClientProtocolException::class)
+ private fun performHttpCall(httpUriRequest: HttpUriRequest): BlueprintWebClientService.WebClientResponse<String> {
+ val httpResponse = httpClient().execute(httpUriRequest)
+ val statusCode = httpResponse.statusLine.statusCode
+ httpResponse.entity.content.use {
+ val body = IOUtils.toString(it, Charset.defaultCharset())
+ return BlueprintWebClientService.WebClientResponse(statusCode, body)
+ }
+ }
+
+ fun uploadBinaryFile(path: String, filePath: Path): BlueprintWebClientService.WebClientResponse<String> {
+ val convertedHeaders: Array<BasicHeader> = convertToBasicHeaders(defaultHeaders())
+ val httpPost = HttpPost(host(path))
+ val entity = EntityBuilder.create().setBinary(Files.readAllBytes(filePath)).build()
+ httpPost.setEntity(entity)
+ RestLoggerService.httpInvoking(convertedHeaders)
+ httpPost.setHeaders(convertedHeaders)
+ return performHttpCall(httpPost)
+ }
+}
+
+class K8sConfigTemplate {
+ @get:JsonProperty("template-name")
+ var templateName: String? = null
+ @get:JsonProperty("description")
+ var description: String? = null
+ @get:JsonProperty("ChartName")
+ var ChartName: String? = null
+
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (javaClass != other?.javaClass) return false
+ return true
+ }
+
+ override fun hashCode(): Int {
+ return javaClass.hashCode()
+ }
+}
+
+class K8sResources {
+
+ var GVK: GVK? = null
+ lateinit var Name: String
+
+}
+
+class GVK {
+
+ var Group: String? = null
+ var Version: String? = null
+ var Kind: String? = null
+
+}
+
+fun main(args: Array<String>) {
+
+ val kotlin = DayOneConfig()
+
+
+
+}
diff --git a/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sProfileUpload.kt b/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sProfileUpload.kt index 55d73f318..88bcaf2eb 100644 --- a/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sProfileUpload.kt +++ b/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sProfileUpload.kt @@ -66,7 +66,7 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { for (prefix in prefixList) { if (prefix.toLowerCase().equals("vnf")) { log.info("For vnf-level resource-assignment, profile is not performed.") - + continue } val assignmentParams = getDynamicProperties("assignment-params") @@ -75,20 +75,20 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { log.info("Uploading K8S profile for template prefix $prefix") val vfModuleModelInvariantUuid: String = getResolvedParameter(payloadObject, "vf-module-model-invariant-uuid") - val vfModuleId: String = getResolvedParameter(payloadObject, "vf-module-id") - val vfModuleModelUuid: String = getResolvedParameter(payloadObject, "vf-module-model-customization-uuid") + val vfModuleId: String = getResolvedParameter(payloadObject, "vf-module-id") + val vfModuleModelCustUuid: String = getResolvedParameter(payloadObject, "vf-module-model-customization-uuid") val k8sRbProfileName: String = getResolvedParameter(payloadObject, "k8s-rb-profile-name") val k8sRbProfileNamespace: String = getResolvedParameter(payloadObject, "k8s-rb-profile-namespace") - val releaseName:String = getResolvedParameter(payloadObject, "k8s-rb-instance-release-name") - + val releaseName:String = getResolvedParameter(payloadObject, "k8s-rb-instance-release-name") + log.info("******vfModuleID************ $vfModuleId") log.info("k8sRbProfileName $k8sRbProfileName") - val api = K8sApi(k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleModelInvariantUuid, vfModuleModelUuid) + val api = K8sApi(k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleModelInvariantUuid, vfModuleModelCustUuid) if (!api.hasDefinition()) { - throw BluePrintProcessorException("K8s RB Definition ($vfModuleModelInvariantUuid/$vfModuleModelUuid) not found ") + throw BluePrintProcessorException("K8s RB Definition ($vfModuleModelInvariantUuid/$vfModuleModelCustUuid) not found ") } log.info("k8s-rb-profile-name: $k8sRbProfileName") @@ -101,15 +101,15 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { if (api.hasProfile(k8sRbProfileName)) { log.info("Profile Already Existing - skipping upload") } else { - createOverrideValues(payloadObject, vfModuleId, prefix) + createOverrideValues(payloadObject, vfModuleId, prefix) val profileFilePath: Path = prepareProfileFile(k8sRbProfileName, vfModuleId, prefix) - + var profile = K8sProfile() profile.profileName = k8sRbProfileName profile.rbName = vfModuleModelInvariantUuid - profile.rbVersion = vfModuleModelUuid + profile.rbVersion = vfModuleModelCustUuid profile.namespace = k8sRbProfileNamespace - profile.releaseName = releaseName + profile.releaseName = releaseName api.createProfile(profile) api.uploadProfileContent(profile, profileFilePath) @@ -120,9 +120,9 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { } fun prepareProfileFile(k8sRbProfileName: String, vfModuleId: String, prefix: String): Path { - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() val bluePrintBasePath: String = bluePrintContext.rootPath - var profileFilePath: Path = Paths.get(bluePrintBasePath.plus(File.separator).plus("Templates").plus(File.separator).plus("k8s-profiles").plus(File.separator).plus("$prefix-profile.tar.gz")) + var profileFilePath: Path = Paths.get(bluePrintBasePath.plus(File.separator).plus("Templates").plus(File.separator).plus("k8s-profiles").plus(File.separator).plus("$prefix-profile.tar.gz")) log.info("Reading K8s profile file: $profileFilePath") val profileFile = profileFilePath.toFile() @@ -135,9 +135,9 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { log.info("Decompressing profile to $tempProfilePath") val decompressedProfile: File = BluePrintArchiveUtils.deCompress( - profileFilePath.toFile(), - "$tempProfilePath", - ArchiveType.TarGz + profileFilePath.toFile(), + "$tempProfilePath", + ArchiveType.TarGz ) log.info("$profileFilePath decompression completed") @@ -168,8 +168,8 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { } - fun createOverrideValues(payloadObject: ObjectNode, vfModuleId: String, prefix:String): String { - // Extract supportedNssai + fun createOverrideValues(payloadObject: ObjectNode, vfModuleId: String, prefix:String): String { + // Extract supportedNssai val supportedNssaiMap = LinkedHashMap<String, Any>() val snssai: String = getResolvedParameter(payloadObject, "config.supportedNssai.sNssai.snssai") log.info("snssa1 $snssai") @@ -178,7 +178,7 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { val bluePrintContext = bluePrintRuntimeService.bluePrintContext() val bluePrintBasePath: String = bluePrintContext.rootPath val destPath: String = "/tmp/k8s-profile-" + vfModuleId - + var profileFilePath: Path = Paths.get(bluePrintBasePath.plus(File.separator).plus("Templates").plus(File.separator).plus("k8s-profiles").plus(File.separator).plus("$prefix-profile.tar.gz")) log.info("Reading K8s profile file: $profileFilePath") val profileFile = profileFilePath.toFile() @@ -190,9 +190,9 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { log.info("Decompressing profile to $destPath") val decompressedProfile: File = BluePrintArchiveUtils.deCompress( - profileFilePath.toFile(), - "$destPath", - ArchiveType.TarGz + profileFilePath.toFile(), + "$destPath", + ArchiveType.TarGz ) log.info("$profileFilePath decompression completed") @@ -285,11 +285,11 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { } inner class K8sApi( - val username: String, - val password: String, - val baseUrl: String, - val definition: String, - val definitionVersion: String + val username: String, + val password: String, + val baseUrl: String, + val definition: String, + val definitionVersion: String ) { private val service: UploadFileRestClientService // BasicAuthRestClientService @@ -325,9 +325,9 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { fun hasProfile(profileName: String): Boolean { try { val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource( - HttpMethod.GET.name, - "/profile/$profileName", - "" + HttpMethod.GET.name, + "/profile/$profileName", + "" ) if (result.status >= 200 && result.status < 300) return true @@ -346,9 +346,9 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { val profileJsonString: String = objectMapper.writeValueAsString(profile) try { val result: BlueprintWebClientService.WebClientResponse<String> = service.exchangeResource( - HttpMethod.POST.name, - "/profile", - profileJsonString + HttpMethod.POST.name, + "/profile", + profileJsonString ) if (result.status < 200 || result.status >= 300) { throw Exception(result.body) @@ -362,8 +362,8 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { fun uploadProfileContent(profile: K8sProfile, filePath: Path) { try { val result: BlueprintWebClientService.WebClientResponse<String> = service.uploadBinaryFile( - "/profile/${profile.profileName}/content", - filePath + "/profile/${profile.profileName}/content", + filePath ) if (result.status < 200 || result.status >= 300) { throw Exception(result.body) @@ -377,20 +377,20 @@ open class K8sProfileUpload : AbstractScriptComponentFunction() { } class UploadFileRestClientService( - private val restClientProperties: + private val restClientProperties: BasicAuthRestClientProperties ) : BlueprintWebClientService { override fun defaultHeaders(): Map<String, String> { val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password + restClientProperties.username, + restClientProperties.password ) return mapOf( - HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials" + HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, + HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, + HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials" ) } @@ -399,26 +399,26 @@ class UploadFileRestClientService( } override fun convertToBasicHeaders(headers: Map<String, String>): - Array<BasicHeader> { - val customHeaders: MutableMap<String, String> = headers.toMutableMap() - // inject additionalHeaders - customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) + Array<BasicHeader> { + val customHeaders: MutableMap<String, String> = headers.toMutableMap() + // inject additionalHeaders + customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) - if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { - val encodedCredentials = setBasicAuth( + if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { + val encodedCredentials = setBasicAuth( restClientProperties.username, restClientProperties.password - ) - customHeaders[HttpHeaders.AUTHORIZATION] = + ) + customHeaders[HttpHeaders.AUTHORIZATION] = "Basic $encodedCredentials" + } + return super.convertToBasicHeaders(customHeaders) } - return super.convertToBasicHeaders(customHeaders) - } private fun setBasicAuth(username: String, password: String): String { val credentialsString = "$username:$password" return Base64.getEncoder().encodeToString( - credentialsString.toByteArray(Charset.defaultCharset()) + credentialsString.toByteArray(Charset.defaultCharset()) ) } @@ -452,7 +452,7 @@ class K8sProfile { var profileName: String? = null @get:JsonProperty("namespace") var namespace: String? = "default" - @get:JsonProperty("releaseName") + @get:JsonProperty("releaseName") var releaseName: String? = null override fun toString(): String { diff --git a/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sUpdateConfig.kt b/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sUpdateConfig.kt index 937c00a4f..38a6c9a4a 100644 --- a/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sUpdateConfig.kt +++ b/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sUpdateConfig.kt @@ -1,472 +1,472 @@ -/* -* Copyright © 2019 TechMahindra -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts - -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction -import org.slf4j.LoggerFactory -import com.fasterxml.jackson.databind.node.ObjectNode -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import com.fasterxml.jackson.databind.node.ArrayNode -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException -import java.nio.file.Path -import org.springframework.http.HttpMethod -import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import org.apache.http.message.BasicHeader -import java.util.Base64 -import java.nio.charset.Charset -import java.io.IOException -import org.apache.http.client.methods.HttpUriRequest -import com.fasterxml.jackson.annotation.JsonProperty -import org.apache.commons.io.IOUtils -import org.apache.http.client.methods.HttpPost -import org.apache.http.client.entity.EntityBuilder -import java.nio.file.Files -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.RestLoggerService -import org.apache.http.client.ClientProtocolException -import com.fasterxml.jackson.databind.ObjectMapper -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sDefinitionRestClient -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.K8sConfigValueRequest -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.K8sPluginInstanceApi -import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory -import com.fasterxml.jackson.module.kotlin.convertValue - -import com.google.gson.Gson -import com.google.gson.reflect.TypeToken - -import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.storedContentFromResolvedArtifactNB -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService - -open class KotlinK8sUpdateConfig : AbstractScriptComponentFunction() { - - private val log = LoggerFactory.getLogger(KotlinK8sUpdateConfig::class.java)!! - - override fun getName(): String { - return "KotlinK8sUpdateConfig" - } - - override suspend fun processNB(executionRequest: ExecutionServiceInput) { - - println("Exeuting processNB") - log.info("Executing processNB from Kotlin script: KotlinK8sUpdateConfig ...") - val bluePrintPropertiesService: BluePrintPropertiesService =this.functionDependencyInstanceAsType("bluePrintPropertiesService") - - // read the config input - val baseK8sApiUrl = getDynamicProperties("api-access").get("url").asText() - val k8sApiUsername = getDynamicProperties("api-access").get("username").asText() - val k8sApiPassword = getDynamicProperties("api-access").get("password").asText() - - val prefix = "baseconfigput" - - val aaiApiUrl = getDynamicProperties("aai-access").get("url").asText() - val aaiApiUsername = getDynamicProperties("aai-access").get("username").asText() - val aaiApiPassword = getDynamicProperties("aai-access").get("password").asText() - - log.info("AAI params $aaiApiUrl") - - val resolution_key = getDynamicProperties("resolution-key").asText() - - val payload = storedContentFromResolvedArtifactNB(resolution_key, prefix) - - val payloadObject = JacksonUtils.jsonNode(payload) as ObjectNode - - val serviceInstanceID: String = getResolvedParameter(payloadObject, "service-instance-id") - val vnfID: String = getResolvedParameter(payloadObject, "vnf-id") - - log.info("Get serviceInstanceID $serviceInstanceID") - log.info("Get vnfID $vnfID") - - val vnfUrl = aaiApiUrl + "/aai/v19/network/generic-vnfs/generic-vnf/" + vnfID + "/vf-modules"; - - val mapOfHeaders = hashMapOf<String, String>() - mapOfHeaders.put("Accept", "application/json") - mapOfHeaders.put("Content-Type", "application/json") - mapOfHeaders.put("x-FromAppId", "SO") - mapOfHeaders.put("X-TransactionId", "get_aai_subscr") - val basicAuthRestClientProperties: BasicAuthRestClientProperties = BasicAuthRestClientProperties() - basicAuthRestClientProperties.username = aaiApiUsername - basicAuthRestClientProperties.password = aaiApiPassword - basicAuthRestClientProperties.url = vnfUrl - basicAuthRestClientProperties.additionalHeaders =mapOfHeaders - val basicAuthRestClientService: BasicAuthRestClientService= BasicAuthRestClientService(basicAuthRestClientProperties) - try { - val resultOfGet: BlueprintWebClientService.WebClientResponse<String> = basicAuthRestClientService.exchangeResource(HttpMethod.GET.name, "", "") - - val aaiBody = resultOfGet.body - val aaiPayloadObject = JacksonUtils.jsonNode(aaiBody) as ObjectNode - - log.info("aaiPayloadObject: $aaiPayloadObject") - - for (item in aaiPayloadObject.get("vf-module")) { - - log.info("item payload Deatils : $item") - - val isItBaseVfModule = item.get("is-base-vf-module").asText() - - if(isItBaseVfModule.toBoolean()) - continue - - val vfModuleID: String = item.get("vf-module-id").asText() - - log.info("AAI Vf-module ID is : $vfModuleID") - - val vfModuleModelInvariantUuid: String = item.get("model-invariant-id").asText() - - log.info("AAI Vf-module Invariant ID is : $vfModuleModelInvariantUuid") - - val vfModuleModelUuid: String = item.get("model-customization-id").asText() - - log.info("AAI Vf-module UUID is : $vfModuleModelUuid") - - val vfModuleCustUuid: String = item.get("model-customization-id").asText() - - log.info("AAI Vf-module Customization UUID is : $vfModuleCustUuid") - - - val vfModuleInstance: String = item.get("heat-stack-id").asText() - - log.info("AAI Vf-module Heat Stack ID : $vfModuleInstance") - - val profileName: String = "profile-"+ vfModuleID - val templateName: String = "template_" + vfModuleCustUuid - - //val randomString = getRandomString(6) - val configName: String = "config_"+ vfModuleID - - log.info("payloadObject: $payloadObject") - - var supportedNssai: String = getResolvedParameter(payloadObject, "supportedNssai") - - log.info("supportedNssai from SO -> "+ supportedNssai) - log.info("configName ->"+ configName) - log.info("profileName ->"+ profileName) - log.info("templateName ->"+ templateName) - - - executeK8sAPI(bluePrintPropertiesService,supportedNssai, k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleModelInvariantUuid, vfModuleCustUuid, templateName, configName, profileName, vfModuleInstance) - - } - } - catch (e: Exception) { - log.info("Caught exception trying to set config values!!") - throw BluePrintProcessorException("${e.message}") - } - } - - fun getRandomString(length: Int) : String { - val charset = "0123456789" - return (1..length) - .map { charset.random() } - .joinToString("") - } - - fun executeK8sAPI(bluePrintPropertiesService: BluePrintPropertiesService,supportedNssai: String, k8sApiUsername:String, k8sApiPassword:String, baseK8sApiUrl:String, vfModuleModelInvariantUuid:String, vfModuleCustUuid: String, templateName: String, configName:String, profileName:String, instanceId: String){ - - println("Executing executeK8sAPI ...") - - // read and convert supportedNssai parameters from string to json - val sNssaiAsJsonObj = parseSupportedNssai(supportedNssai) - - // contruct config api - val api = K8sConfigApi(k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleModelInvariantUuid, vfModuleCustUuid, instanceId, bluePrintPropertiesService) - - - // invoke config api - var config = K8sConfigPayloadJson() - config.templateName = templateName - config.configName = configName - config.values = Config() - config.values.supportedNssai = SupportedNssai() - config.values.supportedNssai.snssaiInitial = SnssaiInitial() - config.values.supportedNssai.snssaiInitial.snssaiSecond = SnssaiSecond() - config.values.supportedNssai.snssaiInitial.snssaiSecond.snssaiFinalArray = Array<SnssaiFinal>(sNssaiAsJsonObj.size){i-> SnssaiFinal()} - - val dest = buildSNssaiArray(config.values.supportedNssai.snssaiInitial.snssaiSecond.snssaiFinalArray, sNssaiAsJsonObj) - api.createOrUpdateConfig(config, profileName, instanceId, configName, templateName) - - log.info("K8s Configurations create or update Completed") - - } - - fun buildSNssaiArray(payloadSnssai: Array<SnssaiFinal>, requestSnssai: Array<SnssaiFinal>): Array<SnssaiFinal>{ - - System.arraycopy(requestSnssai, 0, payloadSnssai, 0, requestSnssai.size) - - return payloadSnssai - - } - - fun parseSupportedNssai(supportedNssai: String): Array<SnssaiFinal>{ - - log.info("parsing supportedNssai string..") - - log.info("sNssai value from input.. $supportedNssai") - - val trimmed_supportedNssai = supportedNssai.replace("\\s".toRegex(), "").replace("\\r\\n","").replace("\\","") - - val gson = Gson() - - val startInd = trimmed_supportedNssai.indexOf('[') - val endInd = trimmed_supportedNssai.indexOf(']') - - val subStr = trimmed_supportedNssai.substring(startInd, endInd+1) - - val snType = object : TypeToken<Array<SnssaiFinal>>() {}.type - - var snList: Array<SnssaiFinal> = gson.fromJson(subStr, snType) - - log.info("parsing is done.") - - return snList - - } - - fun getResolvedParameter(payload: ObjectNode, keyName: String): String { - for (node in payload.get("resource-accumulator-resolved-data").elements()) { - if (node.get("param-name").asText().equals(keyName)) { - return node.get("param-value").asText() - } - } - return "" - } - - fun getTemplatePrefixList(executionRequest: ExecutionServiceInput): ArrayList<String> { - val result = ArrayList<String>() - for (prefix in executionRequest.payload.get("resource-assignment-request").get("template-prefix").elements()) - result.add(prefix.asText()) - return result - } - - override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - log.info("Recover function called!") - log.info("Execution request : $executionRequest") - log.error("Exception", runtimeException) - addError(runtimeException.message!!) - } - - inner class K8sConfigApi( - val username: String, - val password: String, - val baseUrl: String, - val definition: String, - val definitionVersion: String, - val instanceId: String, - val bluePrintPropertiesService: BluePrintPropertiesService - - ) { - private val service: UploadFileConfigClientService // BasicAuthRestClientService - - init { - var mapOfHeaders = hashMapOf<String, String>() - mapOfHeaders.put("Accept", "application/json") - mapOfHeaders.put("Content-Type", "application/json") - mapOfHeaders.put("cache-control", " no-cache") - mapOfHeaders.put("Accept", "application/json") - var basicAuthRestClientProperties: BasicAuthRestClientProperties = BasicAuthRestClientProperties() - basicAuthRestClientProperties.username = username - basicAuthRestClientProperties.password = password - basicAuthRestClientProperties.url = "$baseUrl/v1/instance" - basicAuthRestClientProperties.additionalHeaders = mapOfHeaders - - this.service = UploadFileConfigClientService(basicAuthRestClientProperties) - } - - fun createOrUpdateConfig(configJson: K8sConfigPayloadJson, profileName: String, instanceId: String, configName: String, templateName: String) { - val objectMapper = ObjectMapper() - var obj: Any? = null - val yamlReader = ObjectMapper(YAMLFactory()) - - for(snssai in configJson.values.supportedNssai.snssaiInitial.snssaiSecond.snssaiFinalArray){ - println("snssai->" +snssai.snssai) - println("status->"+snssai.status) - - } - - val configJsonString: String = objectMapper.writeValueAsString(configJson.values) - - log.info("payload generated -> "+ configJsonString) - - val startInd = configJsonString.indexOf('[') - val endInd = configJsonString.indexOf(']') - - val snssaiArray: String = configJsonString.substring(startInd, endInd+1).replace("\"","\\\"").replace("[","\"[").replace("]","]\"") - - val finalPayload: String = configJsonString.replaceRange(startInd..endInd, snssaiArray) - - log.info("payload restructured -> "+ finalPayload) - obj = yamlReader.readValue(finalPayload, Any::class.java) - - - - val api = K8sPluginInstanceApi(K8sConnectionPluginConfiguration(bluePrintPropertiesService)) - - val configValueRequest = K8sConfigValueRequest() - configValueRequest.templateName = configJson.templateName - configValueRequest.configName = configJson.configName - configValueRequest.values = objectMapper.convertValue(obj) - if (api.hasConfigurationValues(instanceId, configName)) { - api.editConfigurationValues(configValueRequest, instanceId, configName) - } else { - api.createConfigurationValues(configValueRequest, instanceId) - } - } - - } -} - -class UploadFileConfigClientService( - private val restClientProperties: - BasicAuthRestClientProperties -) : BlueprintWebClientService { - - override fun defaultHeaders(): Map<String, String> { - - val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password - ) - return mapOf( - HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials" - ) - } - - override fun host(uri: String): String { - return restClientProperties.url + uri - } - - override fun convertToBasicHeaders(headers: Map<String, String>): - Array<BasicHeader> { - val customHeaders: MutableMap<String, String> = headers.toMutableMap() - // inject additionalHeaders - customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) - - if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { - val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password - ) - customHeaders[HttpHeaders.AUTHORIZATION] = - "Basic $encodedCredentials" - } - return super.convertToBasicHeaders(customHeaders) - } - - private fun setBasicAuth(username: String, password: String): String { - val credentialsString = "$username:$password" - return Base64.getEncoder().encodeToString( - credentialsString.toByteArray(Charset.defaultCharset()) - ) - } - - @Throws(IOException::class, ClientProtocolException::class) - private fun performHttpCall(httpUriRequest: HttpUriRequest): BlueprintWebClientService.WebClientResponse<String> { - val httpResponse = httpClient().execute(httpUriRequest) - val statusCode = httpResponse.statusLine.statusCode - httpResponse.entity.content.use { - val body = IOUtils.toString(it, Charset.defaultCharset()) - return BlueprintWebClientService.WebClientResponse(statusCode, body) - } - } - - fun uploadBinaryFile(path: String, filePath: Path): BlueprintWebClientService.WebClientResponse<String> { - val convertedHeaders: Array<BasicHeader> = convertToBasicHeaders(defaultHeaders()) - val httpPost = HttpPost(host(path)) - val entity = EntityBuilder.create().setBinary(Files.readAllBytes(filePath)).build() - httpPost.setEntity(entity) - RestLoggerService.httpInvoking(convertedHeaders) - httpPost.setHeaders(convertedHeaders) - return performHttpCall(httpPost) - } -} - - -class K8sConfigPayloadJson { - @get:JsonProperty("template-name") - var templateName: String? = null - @get:JsonProperty("config-name") - var configName: String? = null - @get:JsonProperty("values") - lateinit var values: Config - - override fun toString(): String { - return "$templateName:$configName:$values" - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - return true - } - - override fun hashCode(): Int { - return javaClass.hashCode() - } -} - -class Config{ - @get:JsonProperty("config") - lateinit var supportedNssai: SupportedNssai -} - -class SupportedNssai{ - @get:JsonProperty("supportedNssai") - lateinit var snssaiInitial: SnssaiInitial -} - -class SnssaiInitial{ - - @get:JsonProperty("sNssai") - lateinit var snssaiSecond: SnssaiSecond -} - -class SnssaiSecond{ - - @get:JsonProperty("snssai") - lateinit var snssaiFinalArray: Array<SnssaiFinal> -} - - -class SnssaiFinal{ - @get:JsonProperty("snssai") - var snssai: String? = null - - @get:JsonProperty("status") - var status: String? = null -} - - -fun main(args: Array<String>) { - - val supportedNssai = """ - - {\r\n \"sNssai\":[\r\n {\r\n \"snssai\":\"001-100001\",\r\n \"status\":\"created-modified\"\r\n },\r\n {\r\n \"snssai\":\"002-100001\",\r\n \"status\":\"activated\"\r\n },\r\n {\r\n \"snssai\":\"003-100001\",\r\n \"status\":\"de-activated\"\r\n }\r\n ]\r\n }\r\n - -""" - - val kotlin = KotlinK8sUpdateConfig() - - - -} +/*
+* Copyright © 2019 TechMahindra
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
+
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction
+import org.slf4j.LoggerFactory
+import com.fasterxml.jackson.databind.node.ObjectNode
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import com.fasterxml.jackson.databind.node.ArrayNode
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import java.nio.file.Path
+import org.springframework.http.HttpMethod
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties
+import org.springframework.http.HttpHeaders
+import org.springframework.http.MediaType
+import org.apache.http.message.BasicHeader
+import java.util.Base64
+import java.nio.charset.Charset
+import java.io.IOException
+import org.apache.http.client.methods.HttpUriRequest
+import com.fasterxml.jackson.annotation.JsonProperty
+import org.apache.commons.io.IOUtils
+import org.apache.http.client.methods.HttpPost
+import org.apache.http.client.entity.EntityBuilder
+import java.nio.file.Files
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.RestLoggerService
+import org.apache.http.client.ClientProtocolException
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sDefinitionRestClient
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.K8sConfigValueRequest
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.K8sPluginInstanceApi
+import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
+import com.fasterxml.jackson.module.kotlin.convertValue
+
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.storedContentFromResolvedArtifactNB
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService
+
+open class KotlinK8sUpdateConfig : AbstractScriptComponentFunction() {
+
+ private val log = LoggerFactory.getLogger(KotlinK8sUpdateConfig::class.java)!!
+
+ override fun getName(): String {
+ return "KotlinK8sUpdateConfig"
+ }
+
+ override suspend fun processNB(executionRequest: ExecutionServiceInput) {
+
+ println("Exeuting processNB")
+ log.info("Executing processNB from Kotlin script: KotlinK8sUpdateConfig ...")
+ val bluePrintPropertiesService: BluePrintPropertiesService =this.functionDependencyInstanceAsType("bluePrintPropertiesService")
+
+ // read the config input
+ val baseK8sApiUrl = getDynamicProperties("api-access").get("url").asText()
+ val k8sApiUsername = getDynamicProperties("api-access").get("username").asText()
+ val k8sApiPassword = getDynamicProperties("api-access").get("password").asText()
+
+ val prefix = "baseconfigput"
+
+ val aaiApiUrl = getDynamicProperties("aai-access").get("url").asText()
+ val aaiApiUsername = getDynamicProperties("aai-access").get("username").asText()
+ val aaiApiPassword = getDynamicProperties("aai-access").get("password").asText()
+
+ log.info("AAI params $aaiApiUrl")
+
+ val resolution_key = getDynamicProperties("resolution-key").asText()
+
+ val payload = storedContentFromResolvedArtifactNB(resolution_key, prefix)
+
+ val payloadObject = JacksonUtils.jsonNode(payload) as ObjectNode
+
+ val serviceInstanceID: String = getResolvedParameter(payloadObject, "service-instance-id")
+ val vnfID: String = getResolvedParameter(payloadObject, "vnf-id")
+
+ log.info("Get serviceInstanceID $serviceInstanceID")
+ log.info("Get vnfID $vnfID")
+
+ val vnfUrl = aaiApiUrl + "/aai/v19/network/generic-vnfs/generic-vnf/" + vnfID + "/vf-modules";
+
+ val mapOfHeaders = hashMapOf<String, String>()
+ mapOfHeaders.put("Accept", "application/json")
+ mapOfHeaders.put("Content-Type", "application/json")
+ mapOfHeaders.put("x-FromAppId", "SO")
+ mapOfHeaders.put("X-TransactionId", "get_aai_subscr")
+ val basicAuthRestClientProperties: BasicAuthRestClientProperties = BasicAuthRestClientProperties()
+ basicAuthRestClientProperties.username = aaiApiUsername
+ basicAuthRestClientProperties.password = aaiApiPassword
+ basicAuthRestClientProperties.url = vnfUrl
+ basicAuthRestClientProperties.additionalHeaders =mapOfHeaders
+ val basicAuthRestClientService: BasicAuthRestClientService= BasicAuthRestClientService(basicAuthRestClientProperties)
+ try {
+ val resultOfGet: BlueprintWebClientService.WebClientResponse<String> = basicAuthRestClientService.exchangeResource(HttpMethod.GET.name, "", "")
+
+ val aaiBody = resultOfGet.body
+ val aaiPayloadObject = JacksonUtils.jsonNode(aaiBody) as ObjectNode
+
+ log.info("aaiPayloadObject: $aaiPayloadObject")
+
+ for (item in aaiPayloadObject.get("vf-module")) {
+
+ log.info("item payload Deatils : $item")
+
+ val isItBaseVfModule = item.get("is-base-vf-module").asText()
+
+ if(isItBaseVfModule.toBoolean())
+ continue
+
+ val vfModuleID: String = item.get("vf-module-id").asText()
+
+ log.info("AAI Vf-module ID is : $vfModuleID")
+
+ val vfModuleModelInvariantUuid: String = item.get("model-invariant-id").asText()
+
+ log.info("AAI Vf-module Invariant ID is : $vfModuleModelInvariantUuid")
+
+ val vfModuleModelUuid: String = item.get("model-version-id").asText()
+
+ log.info("AAI Vf-module UUID is : $vfModuleModelUuid")
+
+ val vfModuleCustUuid: String = item.get("model-customization-id").asText()
+
+ log.info("AAI Vf-module Customization UUID is : $vfModuleCustUuid")
+
+
+ val vfModuleInstance: String = item.get("heat-stack-id").asText()
+
+ log.info("AAI Vf-module Heat Stack ID : $vfModuleInstance")
+
+ val profileName: String = "profile-"+ vfModuleID
+ val templateName: String = "template_" + vfModuleCustUuid
+
+ //val randomString = getRandomString(6)
+ val configName: String = "config_"+ vfModuleID
+
+ log.info("payloadObject: $payloadObject")
+
+ var supportedNssai: String = getResolvedParameter(payloadObject, "supportedNssai")
+
+ log.info("supportedNssai from SO -> "+ supportedNssai)
+ log.info("configName ->"+ configName)
+ log.info("profileName ->"+ profileName)
+ log.info("templateName ->"+ templateName)
+
+
+ executeK8sAPI(bluePrintPropertiesService,supportedNssai, k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleModelInvariantUuid, vfModuleCustUuid, templateName, configName, profileName, vfModuleInstance)
+
+ }
+ }
+ catch (e: Exception) {
+ log.info("Caught exception trying to set config values!!")
+ throw BluePrintProcessorException("${e.message}")
+ }
+ }
+
+ fun getRandomString(length: Int) : String {
+ val charset = "0123456789"
+ return (1..length)
+ .map { charset.random() }
+ .joinToString("")
+ }
+
+ fun executeK8sAPI(bluePrintPropertiesService: BluePrintPropertiesService,supportedNssai: String, k8sApiUsername:String, k8sApiPassword:String, baseK8sApiUrl:String, vfModuleModelInvariantUuid:String, vfModuleCustUuid: String, templateName: String, configName:String, profileName:String, instanceId: String){
+
+ println("Executing executeK8sAPI ...")
+
+ // read and convert supportedNssai parameters from string to json
+ val sNssaiAsJsonObj = parseSupportedNssai(supportedNssai)
+
+ // contruct config api
+ val api = K8sConfigApi(k8sApiUsername, k8sApiPassword, baseK8sApiUrl, vfModuleModelInvariantUuid, vfModuleCustUuid, instanceId, bluePrintPropertiesService)
+
+
+ // invoke config api
+ var config = K8sConfigPayloadJson()
+ config.templateName = templateName
+ config.configName = configName
+ config.values = Config()
+ config.values.supportedNssai = SupportedNssai()
+ config.values.supportedNssai.snssaiInitial = SnssaiInitial()
+ config.values.supportedNssai.snssaiInitial.snssaiSecond = SnssaiSecond()
+ config.values.supportedNssai.snssaiInitial.snssaiSecond.snssaiFinalArray = Array<SnssaiFinal>(sNssaiAsJsonObj.size){i-> SnssaiFinal()}
+
+ val dest = buildSNssaiArray(config.values.supportedNssai.snssaiInitial.snssaiSecond.snssaiFinalArray, sNssaiAsJsonObj)
+ api.createOrUpdateConfig(config, profileName, instanceId, configName, templateName)
+
+ log.info("K8s Configurations create or update Completed")
+
+ }
+
+ fun buildSNssaiArray(payloadSnssai: Array<SnssaiFinal>, requestSnssai: Array<SnssaiFinal>): Array<SnssaiFinal>{
+
+ System.arraycopy(requestSnssai, 0, payloadSnssai, 0, requestSnssai.size)
+
+ return payloadSnssai
+
+ }
+
+ fun parseSupportedNssai(supportedNssai: String): Array<SnssaiFinal>{
+
+ log.info("parsing supportedNssai string..")
+
+ log.info("sNssai value from input.. $supportedNssai")
+
+ val trimmed_supportedNssai = supportedNssai.replace("\\s".toRegex(), "").replace("\\r\\n","").replace("\\","")
+
+ val gson = Gson()
+
+ val startInd = trimmed_supportedNssai.indexOf('[')
+ val endInd = trimmed_supportedNssai.indexOf(']')
+
+ val subStr = trimmed_supportedNssai.substring(startInd, endInd+1)
+
+ val snType = object : TypeToken<Array<SnssaiFinal>>() {}.type
+
+ var snList: Array<SnssaiFinal> = gson.fromJson(subStr, snType)
+
+ log.info("parsing is done.")
+
+ return snList
+
+ }
+
+ fun getResolvedParameter(payload: ObjectNode, keyName: String): String {
+ for (node in payload.get("resource-accumulator-resolved-data").elements()) {
+ if (node.get("param-name").asText().equals(keyName)) {
+ return node.get("param-value").asText()
+ }
+ }
+ return ""
+ }
+
+ fun getTemplatePrefixList(executionRequest: ExecutionServiceInput): ArrayList<String> {
+ val result = ArrayList<String>()
+ for (prefix in executionRequest.payload.get("resource-assignment-request").get("template-prefix").elements())
+ result.add(prefix.asText())
+ return result
+ }
+
+ override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
+ log.info("Recover function called!")
+ log.info("Execution request : $executionRequest")
+ log.error("Exception", runtimeException)
+ addError(runtimeException.message!!)
+ }
+
+ inner class K8sConfigApi(
+ val username: String,
+ val password: String,
+ val baseUrl: String,
+ val definition: String,
+ val definitionVersion: String,
+ val instanceId: String,
+ val bluePrintPropertiesService: BluePrintPropertiesService
+
+ ) {
+ private val service: UploadFileConfigClientService // BasicAuthRestClientService
+
+ init {
+ var mapOfHeaders = hashMapOf<String, String>()
+ mapOfHeaders.put("Accept", "application/json")
+ mapOfHeaders.put("Content-Type", "application/json")
+ mapOfHeaders.put("cache-control", " no-cache")
+ mapOfHeaders.put("Accept", "application/json")
+ var basicAuthRestClientProperties: BasicAuthRestClientProperties = BasicAuthRestClientProperties()
+ basicAuthRestClientProperties.username = username
+ basicAuthRestClientProperties.password = password
+ basicAuthRestClientProperties.url = "$baseUrl/v1/instance"
+ basicAuthRestClientProperties.additionalHeaders = mapOfHeaders
+
+ this.service = UploadFileConfigClientService(basicAuthRestClientProperties)
+ }
+
+ fun createOrUpdateConfig(configJson: K8sConfigPayloadJson, profileName: String, instanceId: String, configName: String, templateName: String) {
+ val objectMapper = ObjectMapper()
+ var obj: Any? = null
+ val yamlReader = ObjectMapper(YAMLFactory())
+
+ for(snssai in configJson.values.supportedNssai.snssaiInitial.snssaiSecond.snssaiFinalArray){
+ println("snssai->" +snssai.snssai)
+ println("status->"+snssai.status)
+
+ }
+
+ val configJsonString: String = objectMapper.writeValueAsString(configJson.values)
+
+ log.info("payload generated -> "+ configJsonString)
+
+ val startInd = configJsonString.indexOf('[')
+ val endInd = configJsonString.indexOf(']')
+
+ val snssaiArray: String = configJsonString.substring(startInd, endInd+1).replace("\"","\\\"").replace("[","\"[").replace("]","]\"")
+
+ val finalPayload: String = configJsonString.replaceRange(startInd..endInd, snssaiArray)
+
+ log.info("payload restructured -> "+ finalPayload)
+ obj = yamlReader.readValue(finalPayload, Any::class.java)
+
+
+
+ val api = K8sPluginInstanceApi(K8sConnectionPluginConfiguration(bluePrintPropertiesService))
+
+ val configValueRequest = K8sConfigValueRequest()
+ configValueRequest.templateName = configJson.templateName
+ configValueRequest.configName = configJson.configName
+ configValueRequest.values = objectMapper.convertValue(obj)
+ if (api.hasConfigurationValues(instanceId, configName)) {
+ api.editConfigurationValues(configValueRequest, instanceId, configName)
+ } else {
+ api.createConfigurationValues(configValueRequest, instanceId)
+ }
+ }
+
+ }
+}
+
+class UploadFileConfigClientService(
+ private val restClientProperties:
+ BasicAuthRestClientProperties
+) : BlueprintWebClientService {
+
+ override fun defaultHeaders(): Map<String, String> {
+
+ val encodedCredentials = setBasicAuth(
+ restClientProperties.username,
+ restClientProperties.password
+ )
+ return mapOf(
+ HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials"
+ )
+ }
+
+ override fun host(uri: String): String {
+ return restClientProperties.url + uri
+ }
+
+ override fun convertToBasicHeaders(headers: Map<String, String>):
+ Array<BasicHeader> {
+ val customHeaders: MutableMap<String, String> = headers.toMutableMap()
+ // inject additionalHeaders
+ customHeaders.putAll(verifyAdditionalHeaders(restClientProperties))
+
+ if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
+ val encodedCredentials = setBasicAuth(
+ restClientProperties.username,
+ restClientProperties.password
+ )
+ customHeaders[HttpHeaders.AUTHORIZATION] =
+ "Basic $encodedCredentials"
+ }
+ return super.convertToBasicHeaders(customHeaders)
+ }
+
+ private fun setBasicAuth(username: String, password: String): String {
+ val credentialsString = "$username:$password"
+ return Base64.getEncoder().encodeToString(
+ credentialsString.toByteArray(Charset.defaultCharset())
+ )
+ }
+
+ @Throws(IOException::class, ClientProtocolException::class)
+ private fun performHttpCall(httpUriRequest: HttpUriRequest): BlueprintWebClientService.WebClientResponse<String> {
+ val httpResponse = httpClient().execute(httpUriRequest)
+ val statusCode = httpResponse.statusLine.statusCode
+ httpResponse.entity.content.use {
+ val body = IOUtils.toString(it, Charset.defaultCharset())
+ return BlueprintWebClientService.WebClientResponse(statusCode, body)
+ }
+ }
+
+ fun uploadBinaryFile(path: String, filePath: Path): BlueprintWebClientService.WebClientResponse<String> {
+ val convertedHeaders: Array<BasicHeader> = convertToBasicHeaders(defaultHeaders())
+ val httpPost = HttpPost(host(path))
+ val entity = EntityBuilder.create().setBinary(Files.readAllBytes(filePath)).build()
+ httpPost.setEntity(entity)
+ RestLoggerService.httpInvoking(convertedHeaders)
+ httpPost.setHeaders(convertedHeaders)
+ return performHttpCall(httpPost)
+ }
+}
+
+
+class K8sConfigPayloadJson {
+ @get:JsonProperty("template-name")
+ var templateName: String? = null
+ @get:JsonProperty("config-name")
+ var configName: String? = null
+ @get:JsonProperty("values")
+ lateinit var values: Config
+
+ override fun toString(): String {
+ return "$templateName:$configName:$values"
+ }
+
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (javaClass != other?.javaClass) return false
+ return true
+ }
+
+ override fun hashCode(): Int {
+ return javaClass.hashCode()
+ }
+}
+
+class Config{
+ @get:JsonProperty("config")
+ lateinit var supportedNssai: SupportedNssai
+}
+
+class SupportedNssai{
+ @get:JsonProperty("supportedNssai")
+ lateinit var snssaiInitial: SnssaiInitial
+}
+
+class SnssaiInitial{
+
+ @get:JsonProperty("sNssai")
+ lateinit var snssaiSecond: SnssaiSecond
+}
+
+class SnssaiSecond{
+
+ @get:JsonProperty("snssai")
+ lateinit var snssaiFinalArray: Array<SnssaiFinal>
+}
+
+
+class SnssaiFinal{
+ @get:JsonProperty("snssai")
+ var snssai: String? = null
+
+ @get:JsonProperty("status")
+ var status: String? = null
+}
+
+
+fun main(args: Array<String>) {
+
+ val supportedNssai = """
+
+ {\r\n \"sNssai\":[\r\n {\r\n \"snssai\":\"001-100001\",\r\n \"status\":\"created-modified\"\r\n },\r\n {\r\n \"snssai\":\"002-100001\",\r\n \"status\":\"activated\"\r\n },\r\n {\r\n \"snssai\":\"003-100001\",\r\n \"status\":\"de-activated\"\r\n }\r\n ]\r\n }\r\n
+
+"""
+
+ val kotlin = KotlinK8sUpdateConfig()
+
+
+
+}
|