aboutsummaryrefslogtreecommitdiffstats
path: root/components/model-catalog/blueprint-model/service-blueprint/5GC_Simulator_CNF_CDS/Scripts/kotlin/KotlinK8sUpdateConfig.kt
blob: 38a6c9a4a8c83e6b90d5f7697cfc4e53b01d2f6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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-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()

   

}