From c99c15f6f91fb296f2b44c6406795ac0583d632d Mon Sep 17 00:00:00 2001 From: Lukasz Rajewski Date: Wed, 10 Feb 2021 22:07:29 +0100 Subject: K8sPlugin Instance API Handlers Issue-ID: CCSDK-3146 Signed-off-by: Lukasz Rajewski Change-Id: I404957d5e782b8943bbe0d8bc501bbe88d524483 --- .../functions/k8s/K8sAbstractRestClientService.kt | 38 ++- .../functions/k8s/K8sDefinitionRestClient.kt | 33 -- .../functions/k8s/K8sPluginApi.kt | 32 +- .../k8s/K8sUploadFileRestClientService.kt | 62 ---- .../k8s/definition/K8sDefinitionRestClient.kt | 34 ++ .../definition/K8sUploadFileRestClientService.kt | 61 ++++ .../functions/k8s/definition/profile/K8sProfile.kt | 51 +++ .../profile/K8sProfileUploadComponent.kt | 359 ++++++++++++++++++++ .../functions/k8s/instance/K8sPluginInstanceApi.kt | 136 ++++++++ .../functions/k8s/instance/K8sRbInstance.kt | 77 +++++ .../functions/k8s/instance/K8sRbInstanceGvk.kt | 48 +++ .../functions/k8s/instance/K8sRbInstanceRequest.kt | 56 ++++ .../k8s/instance/K8sRbInstanceRestClient.kt | 36 ++ .../functions/k8s/instance/K8sRbInstanceStatus.kt | 73 +++++ .../functions/k8s/profile/upload/K8sProfile.kt | 51 --- .../profile/upload/K8sProfileUploadComponent.kt | 363 --------------------- 16 files changed, 978 insertions(+), 532 deletions(-) delete mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sDefinitionRestClient.kt delete mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sUploadFileRestClientService.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sDefinitionRestClient.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sUploadFileRestClientService.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfile.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstance.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceGvk.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRequest.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRestClient.kt create mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceStatus.kt delete mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfile.kt delete mode 100644 ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfileUploadComponent.kt diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sAbstractRestClientService.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sAbstractRestClientService.kt index 69f647387..14f14f61b 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sAbstractRestClientService.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sAbstractRestClientService.kt @@ -1,7 +1,7 @@ /* * Copyright © 2017-2018 AT&T Intellectual Property. * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2021 Orange. * Modifications Copyright © 2020 Deutsche Telekom AG. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,17 +29,25 @@ import org.springframework.http.MediaType.APPLICATION_JSON_VALUE import java.nio.charset.Charset import java.util.Base64 -abstract class K8sAbstractRestClientService(val username: String, val password: String) : BlueprintWebClientService { +abstract class K8sAbstractRestClientService( + private val k8sConfiguration: K8sConnectionPluginConfiguration +) : BlueprintWebClientService { - private val restClientProperties: BasicAuthRestClientProperties = getBasicAuthRestClientProperties() + protected val baseUrl: String = k8sConfiguration.getProperties().url + private var restClientProperties: BasicAuthRestClientProperties? = null private fun getBasicAuthRestClientProperties(): BasicAuthRestClientProperties { - val basicAuthRestClientProperties = BasicAuthRestClientProperties() - basicAuthRestClientProperties.username = username - basicAuthRestClientProperties.password = password - basicAuthRestClientProperties.url = apiUrl() - basicAuthRestClientProperties.additionalHeaders = getHeaders() - return basicAuthRestClientProperties + return if (restClientProperties != null) + restClientProperties!! + else { + val basicAuthRestClientProperties = BasicAuthRestClientProperties() + basicAuthRestClientProperties.username = k8sConfiguration.getProperties().username + basicAuthRestClientProperties.password = k8sConfiguration.getProperties().password + basicAuthRestClientProperties.url = apiUrl() + basicAuthRestClientProperties.additionalHeaders = getHeaders() + restClientProperties = basicAuthRestClientProperties + return basicAuthRestClientProperties + } } private fun getHeaders(): HashMap { @@ -58,8 +66,8 @@ abstract class K8sAbstractRestClientService(val username: String, val password: override fun defaultHeaders(): Map { val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password + getBasicAuthRestClientProperties().username, + getBasicAuthRestClientProperties().password ) return mapOf( CONTENT_TYPE to APPLICATION_JSON_VALUE, @@ -69,18 +77,18 @@ abstract class K8sAbstractRestClientService(val username: String, val password: } override fun host(uri: String): String { - return restClientProperties.url + uri + return getBasicAuthRestClientProperties().url + uri } override fun convertToBasicHeaders(headers: Map): Array { val customHeaders: MutableMap = headers.toMutableMap() // inject additionalHeaders - customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) + customHeaders.putAll(verifyAdditionalHeaders(getBasicAuthRestClientProperties())) if (!headers.containsKey(AUTHORIZATION)) { val encodedCredentials = setBasicAuth( - restClientProperties.username, - restClientProperties.password + getBasicAuthRestClientProperties().username, + getBasicAuthRestClientProperties().password ) customHeaders[AUTHORIZATION] = "Basic $encodedCredentials" } diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sDefinitionRestClient.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sDefinitionRestClient.kt deleted file mode 100644 index 0daa276ec..000000000 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sDefinitionRestClient.kt +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2020 Orange. - * Modifications Copyright © 2020 Deutsche Telekom AG. - * - * 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.functions.k8s - -open class K8sDefinitionRestClient( - username: String, - password: String, - private val baseUrl: String, - private val definition: String, - private val definitionVersion: String -) : K8sAbstractRestClientService(username, password) { - - override fun apiUrl(): String { - return "$baseUrl/v1/rb/definition/$definition/$definitionVersion" - } -} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sPluginApi.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sPluginApi.kt index 2c58645c8..211bc5abe 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sPluginApi.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sPluginApi.kt @@ -20,7 +20,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s import com.fasterxml.jackson.databind.ObjectMapper -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.profile.upload.K8sProfile +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sDefinitionRestClient +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sUploadFileRestClientService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.profile.K8sProfile import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException import org.slf4j.LoggerFactory @@ -29,15 +31,17 @@ import org.springframework.http.HttpMethod.POST import java.nio.file.Path class K8sPluginApi( - private val username: String, - private val password: String, - private val baseUrl: String + private val k8sConfiguration: K8sConnectionPluginConfiguration ) { private val log = LoggerFactory.getLogger(K8sPluginApi::class.java)!! private val objectMapper = ObjectMapper() fun hasDefinition(definition: String, definitionVersion: String): Boolean { - val rbDefinitionService = K8sDefinitionRestClient(username, password, baseUrl, definition, definitionVersion) + val rbDefinitionService = K8sDefinitionRestClient( + k8sConfiguration, + definition, + definitionVersion + ) try { val result: BlueprintWebClientService.WebClientResponse = rbDefinitionService.exchangeResource( GET.name, @@ -53,7 +57,11 @@ class K8sPluginApi( } fun hasProfile(definition: String, definitionVersion: String, profileName: String): Boolean { - val rbDefinitionService = K8sDefinitionRestClient(username, password, baseUrl, definition, definitionVersion) + val rbDefinitionService = K8sDefinitionRestClient( + k8sConfiguration, + definition, + definitionVersion + ) try { val result: BlueprintWebClientService.WebClientResponse = rbDefinitionService.exchangeResource( GET.name, @@ -69,7 +77,11 @@ class K8sPluginApi( } fun createProfile(definition: String, definitionVersion: String, profile: K8sProfile) { - val rbDefinitionService = K8sDefinitionRestClient(username, password, baseUrl, definition, definitionVersion) + val rbDefinitionService = K8sDefinitionRestClient( + k8sConfiguration, + definition, + definitionVersion + ) val profileJsonString: String = objectMapper.writeValueAsString(profile) try { val result: BlueprintWebClientService.WebClientResponse = rbDefinitionService.exchangeResource( @@ -87,7 +99,11 @@ class K8sPluginApi( } fun uploadProfileContent(definition: String, definitionVersion: String, profile: K8sProfile, filePath: Path) { - val fileUploadService = K8sUploadFileRestClientService(username, password, baseUrl, definition, definitionVersion) + val fileUploadService = K8sUploadFileRestClientService( + k8sConfiguration, + definition, + definitionVersion + ) try { val result: BlueprintWebClientService.WebClientResponse = fileUploadService.uploadBinaryFile( "/profile/${profile.profileName}/content", diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sUploadFileRestClientService.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sUploadFileRestClientService.kt deleted file mode 100644 index ac545cfe5..000000000 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sUploadFileRestClientService.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2020 Orange. - * Modifications Copyright © 2020 Deutsche Telekom AG. - * - * 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.functions.k8s - -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.message.BasicHeader -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.RestLoggerService -import java.io.IOException -import java.nio.charset.Charset -import java.nio.file.Files -import java.nio.file.Path - -class K8sUploadFileRestClientService( - username: String, - password: String, - baseUrl: String, - definition: String, - definitionVersion: String -) : K8sDefinitionRestClient(username, password, baseUrl, definition, definitionVersion) { - - @Throws(IOException::class, ClientProtocolException::class) - private fun performHttpCall(httpUriRequest: HttpUriRequest): BlueprintWebClientService.WebClientResponse { - 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 { - val convertedHeaders: Array = 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) - } -} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sDefinitionRestClient.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sDefinitionRestClient.kt new file mode 100644 index 000000000..0c95fe3b6 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sDefinitionRestClient.kt @@ -0,0 +1,34 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2021 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.definition + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sAbstractRestClientService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration + +open class K8sDefinitionRestClient( + k8sConfiguration: K8sConnectionPluginConfiguration, + private val definition: String, + private val definitionVersion: String +) : K8sAbstractRestClientService(k8sConfiguration) { + + override fun apiUrl(): String { + return "$baseUrl/v1/rb/definition/$definition/$definitionVersion" + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sUploadFileRestClientService.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sUploadFileRestClientService.kt new file mode 100644 index 000000000..e44c4eb04 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sUploadFileRestClientService.kt @@ -0,0 +1,61 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.definition + +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.message.BasicHeader +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.RestLoggerService +import java.io.IOException +import java.nio.charset.Charset +import java.nio.file.Files +import java.nio.file.Path + +class K8sUploadFileRestClientService( + k8sConfiguration: K8sConnectionPluginConfiguration, + definition: String, + definitionVersion: String +) : K8sDefinitionRestClient(k8sConfiguration, definition, definitionVersion) { + + @Throws(IOException::class, ClientProtocolException::class) + private fun performHttpCall(httpUriRequest: HttpUriRequest): BlueprintWebClientService.WebClientResponse { + 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 { + val convertedHeaders: Array = 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) + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfile.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfile.kt new file mode 100644 index 000000000..dcaf48710 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfile.kt @@ -0,0 +1,51 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.definition.profile + +import com.fasterxml.jackson.annotation.JsonProperty + +class K8sProfile { + + @get:JsonProperty("rb-name") + var rbName: String? = null + + @get:JsonProperty("rb-version") + var rbVersion: String? = null + + @get:JsonProperty("profile-name") + var profileName: String? = null + + @get:JsonProperty("namespace") + var namespace: String? = "default" + + override fun toString(): String { + return "$rbName:$rbVersion:$profileName" + } + + 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() + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt new file mode 100644 index 000000000..47fe6d957 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt @@ -0,0 +1,359 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.definition.profile + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.ObjectNode +import org.apache.commons.io.FileUtils +import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sPluginApi +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing +import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +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.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Component +import org.yaml.snakeyaml.Yaml +import java.io.File +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths + +@Component("component-k8s-profile-upload") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class K8sProfileUploadComponent( + private var bluePrintPropertiesService: BlueprintPropertiesService, + private val resourceResolutionService: ResourceResolutionService +) : + + AbstractComponentFunction() { + + companion object { + + const val INPUT_K8S_PROFILE_NAME = "k8s-rb-profile-name" + const val INPUT_K8S_DEFINITION_NAME = "k8s-rb-definition-name" + const val INPUT_K8S_DEFINITION_VERSION = "k8s-rb-definition-version" + const val INPUT_K8S_PROFILE_NAMESPACE = "k8s-rb-profile-namespace" + const val INPUT_K8S_PROFILE_SOURCE = "k8s-rb-profile-source" + const val INPUT_RESOURCE_ASSIGNMENT_MAP = "resource-assignment-map" + const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names" + + const val OUTPUT_STATUSES = "statuses" + const val OUTPUT_SKIPPED = "skipped" + const val OUTPUT_UPLOADED = "uploaded" + const val OUTPUT_ERROR = "error" + } + + private val log = LoggerFactory.getLogger(K8sProfileUploadComponent::class.java)!! + + override suspend fun processNB(executionRequest: ExecutionServiceInput) { + log.info("Triggering K8s Profile Upload component logic.") + + val inputParameterNames = arrayOf( + INPUT_K8S_PROFILE_NAME, + INPUT_K8S_DEFINITION_NAME, + INPUT_K8S_DEFINITION_VERSION, + INPUT_K8S_PROFILE_NAMESPACE, + INPUT_K8S_PROFILE_SOURCE, + INPUT_ARTIFACT_PREFIX_NAMES + ) + var outputPrefixStatuses = mutableMapOf() + var inputParamsMap = mutableMapOf() + + inputParameterNames.forEach { + inputParamsMap[it] = getOptionalOperationInput(it)?.returnNullIfMissing() + } + + log.info("Getting the template prefixes") + val prefixList: ArrayList = getTemplatePrefixList(inputParamsMap[INPUT_ARTIFACT_PREFIX_NAMES]) + + log.info("Iterating over prefixes in resource assignment map.") + for (prefix in prefixList) { + // Prefilling prefix sucess status + outputPrefixStatuses.put(prefix, OUTPUT_SKIPPED) + // Resource assignment map is organized by prefixes, in each iteraton we work only + // on one section of resource assignment map + val prefixNode: JsonNode = operationInputs[INPUT_RESOURCE_ASSIGNMENT_MAP]?.get(prefix) ?: continue + val assignmentMapPrefix = JacksonUtils.jsonNode(prefixNode.toPrettyString()) as ObjectNode + + // We are copying the map because for each prefix it might be completed with a different data + var prefixInputParamsMap = inputParamsMap.toMutableMap() + prefixInputParamsMap.forEach { (inputParamName, value) -> + if (value == null) { + val mapValue = assignmentMapPrefix?.get(inputParamName) + log.debug("$inputParamName value was $value so we fetch $mapValue") + prefixInputParamsMap[inputParamName] = mapValue + } + } + + // For clarity we pull out the required fields + val profileName: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAME]?.returnNullIfMissing()?.asText() + val definitionName: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_NAME]?.returnNullIfMissing()?.asText() + val definitionVersion: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_VERSION]?.returnNullIfMissing()?.asText() + + val k8sProfileUploadConfiguration = K8sConnectionPluginConfiguration(bluePrintPropertiesService) + + // Creating API connector + var api = K8sPluginApi(k8sProfileUploadConfiguration) + + if ((profileName == null) || (definitionName == null) || (definitionVersion == null)) { + log.warn("Prefix $prefix does not have required data for us to continue.") + } else if (!api.hasDefinition(definitionName, definitionVersion)) { + log.warn("K8s RB Definition ($definitionName/$definitionVersion) not found ") + } else if (profileName == "") { + log.warn("K8s rb profile name is empty! Either define profile name to use or choose default") + } else if (api.hasProfile(definitionName, definitionVersion, profileName)) { + log.info("Profile Already Existing - skipping upload") + } else { + log.info("Uploading K8s Profile..") + outputPrefixStatuses.put(prefix, OUTPUT_ERROR) + val profileNamespace: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAMESPACE]?.returnNullIfMissing()?.asText() + var profileSource: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_SOURCE]?.returnNullIfMissing()?.asText() + if (profileNamespace == null) + throw BlueprintProcessorException("Profile $profileName namespace is missing") + if (profileSource == null) { + profileSource = profileName + log.info("Profile name used instead of profile source") + } + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, profileSource) + if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE) + throw BlueprintProcessorException( + "Unexpected profile artifact type for profile source " + + "$profileSource. Expecting: $artifact.type" + ) + var profile = K8sProfile() + profile.profileName = profileName + profile.rbName = definitionName + profile.rbVersion = definitionVersion + profile.namespace = profileNamespace + val profileFilePath: Path = prepareProfileFile(profileName, profileSource, artifact.file) + api.createProfile(definitionName, definitionVersion, profile) + api.uploadProfileContent(definitionName, definitionVersion, profile, profileFilePath) + + log.info("K8s Profile Upload Completed") + outputPrefixStatuses.put(prefix, OUTPUT_UPLOADED) + } + } + bluePrintRuntimeService.setNodeTemplateAttributeValue( + nodeTemplateName, + OUTPUT_STATUSES, + outputPrefixStatuses.asJsonNode() + ) + } + + override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + bluePrintRuntimeService.getBlueprintError().addError(runtimeException.message!!) + } + + private fun getTemplatePrefixList(node: JsonNode?): ArrayList { + var result = ArrayList() + when (node) { + is ArrayNode -> { + val arrayNode = node.toList() + for (prefixNode in arrayNode) + result.add(prefixNode.asText()) + } + is ObjectNode -> { + result.add(node.asText()) + } + } + return result + } + + private suspend fun prepareProfileFile(k8sRbProfileName: String, ks8ProfileSource: String, ks8ProfileLocation: String): Path { + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + val bluePrintBasePath: String = bluePrintContext.rootPath + val profileSourceFileFolderPath: Path = Paths.get( + bluePrintBasePath.plus(File.separator).plus(ks8ProfileLocation) + ) + + if (profileSourceFileFolderPath.toFile().exists() && !profileSourceFileFolderPath.toFile().isDirectory) + return profileSourceFileFolderPath + else if (profileSourceFileFolderPath.toFile().exists()) { + log.info("Profile building started from source $ks8ProfileSource") + val properties: MutableMap = mutableMapOf() + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = false + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] = "" + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] = "" + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] = "" + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] = 1 + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY] = false + val resolutionResult: Pair> = resourceResolutionService.resolveResources( + bluePrintRuntimeService, + nodeTemplateName, + ks8ProfileSource, + properties + ) + val tempMainPath: File = createTempDir("k8s-profile-", "") + val tempProfilePath: File = createTempDir("content-", "", tempMainPath) + + val resolvedJsonContent = resolutionResult.second + .associateBy({ it.name }, { it.property?.value }) + .asJsonNode() + + try { + val manifestFiles: ArrayList? = readManifestFiles( + profileSourceFileFolderPath.toFile(), + tempProfilePath + ) + if (manifestFiles != null) { + templateLocation( + profileSourceFileFolderPath.toFile(), resolvedJsonContent, + tempProfilePath, manifestFiles + ) + } else + throw BlueprintProcessorException("Manifest file is missing") + // Preparation of the final profile content + val finalProfileFilePath = Paths.get( + tempMainPath.toString().plus(File.separator).plus( + "$k8sRbProfileName.tar.gz" + ) + ) + if (!BlueprintArchiveUtils.compress( + tempProfilePath, finalProfileFilePath.toFile(), + ArchiveType.TarGz + ) + ) { + throw BlueprintProcessorException("Profile compression has failed") + } + FileUtils.deleteDirectory(tempProfilePath) + + return finalProfileFilePath + } catch (t: Throwable) { + FileUtils.deleteDirectory(tempMainPath) + throw t + } + } else + throw BlueprintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder") + } + + private fun readManifestFiles(profileSource: File, destinationFolder: File): ArrayList? { + val directoryListing: Array? = profileSource.listFiles() + var result: ArrayList? = null + if (directoryListing != null) { + for (child in directoryListing) { + if (!child.isDirectory && child.name.toLowerCase() == "manifest.yaml") { + child.bufferedReader().use { inr -> + val manifestYaml = Yaml() + val manifestObject: Map = manifestYaml.load(inr) + val typeObject: MutableMap? = manifestObject["type"] as MutableMap? + if (typeObject != null) { + result = ArrayList() + val valuesObject = typeObject["values"] + if (valuesObject != null) { + result!!.add(File(destinationFolder.toString().plus(File.separator).plus(valuesObject))) + result!!.add(File(destinationFolder.toString().plus(File.separator).plus(child.name))) + } + (typeObject["configresource"] as ArrayList<*>?)?.forEach { item -> + val fileInfo: Map = item as Map + val filePath = fileInfo["filepath"] + val chartPath = fileInfo["chartpath"] + if (filePath == null || chartPath == null) + log.error("One configresource in manifest was skipped because of the wrong format") + else { + result!!.add(File(destinationFolder.toString().plus(File.separator).plus(filePath))) + } + } + } + } + break + } + } + } + return result + } + + private fun templateLocation( + location: File, + params: JsonNode, + destinationFolder: File, + manifestFiles: ArrayList + ) { + val directoryListing: Array? = location.listFiles() + if (directoryListing != null) { + for (child in directoryListing) { + var newDestinationFolder = destinationFolder.toPath() + if (child.isDirectory) + newDestinationFolder = Paths.get(destinationFolder.toString().plus(File.separator).plus(child.name)) + + templateLocation(child, params, newDestinationFolder.toFile(), manifestFiles) + } + } else if (!location.isDirectory) { + if (location.extension.toLowerCase() == "vtl") { + templateFile(location, params, destinationFolder, manifestFiles) + } else { + val finalFilePath = Paths.get( + destinationFolder.path.plus(File.separator) + .plus(location.name) + ).toFile() + if (isFileInTheManifestFiles(finalFilePath, manifestFiles)) { + if (!destinationFolder.exists()) + Files.createDirectories(destinationFolder.toPath()) + FileUtils.copyFile(location, finalFilePath) + } + } + } + } + + private fun isFileInTheManifestFiles(file: File, manifestFiles: ArrayList): Boolean { + manifestFiles.forEach { fileFromManifest -> + if (fileFromManifest.toString().toLowerCase() == file.toString().toLowerCase()) + return true + } + return false + } + + private fun templateFile( + templatedFile: File, + params: JsonNode, + destinationFolder: File, + manifestFiles: ArrayList + ) { + val finalFile = File( + destinationFolder.path.plus(File.separator) + .plus(templatedFile.nameWithoutExtension) + ) + if (!isFileInTheManifestFiles(finalFile, manifestFiles)) + return + val fileContent = templatedFile.bufferedReader().readText() + val finalFileContent = BlueprintVelocityTemplateService.generateContent( + fileContent, + params, true + ) + if (!destinationFolder.exists()) + Files.createDirectories(destinationFolder.toPath()) + finalFile.bufferedWriter().use { out -> out.write(finalFileContent) } + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt new file mode 100644 index 000000000..3faaac00d --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt @@ -0,0 +1,136 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2021 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.instance + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService +import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import org.springframework.http.HttpMethod.GET + +class K8sPluginInstanceApi( + private val k8sConfiguration: K8sConnectionPluginConfiguration +) { + private val log = LoggerFactory.getLogger(K8sPluginInstanceApi::class.java)!! + + fun getAllInstances(): List? { + val rbInstanceService = K8sRbInstanceRestClient(k8sConfiguration) + try { + val result: BlueprintWebClientService.WebClientResponse = rbInstanceService.exchangeResource( + GET.name, + "", + "" + ) + log.debug(result.toString()) + return if (result.status in 200..299) { + val parsedObject: List = JacksonUtils.readValue(result.body) + parsedObject + } else if (result.status == 500 && result.body.contains("Did not find any objects with tag")) + null + else + throw BlueprintProcessorException(result.body) + } catch (e: Exception) { + log.error("Caught exception trying to get k8s rb instance") + throw BlueprintProcessorException("${e.message}") + } + } + + fun getInstanceById(instanceId: String): K8sRbInstance? { + val rbInstanceService = K8sRbInstanceRestClient(k8sConfiguration, instanceId) + try { + val result: BlueprintWebClientService.WebClientResponse = rbInstanceService.exchangeResource( + GET.name, + "", + "" + ) + log.debug(result.toString()) + return if (result.status in 200..299) { + val instance: JsonNode = JacksonUtils.jsonNode(result.body) + val parsedObject: K8sRbInstance? = JacksonUtils.readValue(result.body, K8sRbInstance::class.java) + parsedObject + } else if (result.status == 500 && result.body.contains("Error finding master table")) + null + else + throw BlueprintProcessorException(result.body) + } catch (e: Exception) { + log.error("Caught exception trying to get k8s rb instance") + throw BlueprintProcessorException("${e.message}") + } + } + + fun getInstanceByRequestProperties( + rbDefinitionName: String, + rbDefinitionVersion: String, + rbProfileName: String + ): K8sRbInstance? { + val rbInstanceService = K8sRbInstanceRestClient(k8sConfiguration) + try { + val result: BlueprintWebClientService.WebClientResponse = rbInstanceService.exchangeResource( + GET.name, + "", + "" + ) + log.debug(result.toString()) + return if (result.status in 200..299) { + val parsedObject: List = JacksonUtils.readValue(result.body) + var instance: K8sRbInstance? = null + parsedObject.forEach { + if (it.request?.rbName == rbDefinitionName && it.request?.rbVersion == rbDefinitionVersion && + it.request?.profileName == rbProfileName + ) + instance = it + } + instance + } else if (result.status == 500 && result.body.contains("Did not find any objects with tag")) + null + else + throw BlueprintProcessorException(result.body) + } catch (e: Exception) { + log.error("Caught exception trying to get k8s rb instance") + throw BlueprintProcessorException("${e.message}") + } + } + + fun getInstanceStatus(instanceId: String): K8sRbInstanceStatus? { + val rbInstanceService = K8sRbInstanceRestClient(k8sConfiguration, instanceId) + try { + val result: BlueprintWebClientService.WebClientResponse = rbInstanceService.exchangeResource( + GET.name, + "/status", + "" + ) + log.debug(result.toString()) + return if (result.status in 200..299) { + val parsedObject: K8sRbInstanceStatus? = JacksonUtils.readValue( + result.body, K8sRbInstanceStatus::class.java + ) + parsedObject + } else if (result.status == 500 && result.body.contains("Error finding master table")) + null + else + throw BlueprintProcessorException(result.body) + } catch (e: Exception) { + log.error("Caught exception trying to get k8s rb instance") + throw BlueprintProcessorException("${e.message}") + } + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstance.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstance.kt new file mode 100644 index 000000000..d3acde015 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstance.kt @@ -0,0 +1,77 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2021 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.instance + +import com.fasterxml.jackson.annotation.JsonProperty + +class K8sRbInstance { + + @get:JsonProperty("id") + var id: String? = null + + @get:JsonProperty("namespace") + var namespace: String? = "default" + + @get:JsonProperty("request") + var request: K8sRbInstanceRequest? = null + + @get:JsonProperty("release-name") + var releaseName: String? = null + + @get:JsonProperty("resources") + var resources: List? = null + + override fun toString(): String { + return "$id:$releaseName:$namespace" + } + + 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 K8sRbInstanceResource { + + @get:JsonProperty("Name") + var name: String? = null + + @get:JsonProperty("GVK") + var gvk: K8sRbInstanceGvk? = null + + override fun toString(): String { + return "$name" + } + + 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() + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceGvk.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceGvk.kt new file mode 100644 index 000000000..8bfe5f241 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceGvk.kt @@ -0,0 +1,48 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.instance + +import com.fasterxml.jackson.annotation.JsonProperty + +class K8sRbInstanceGvk { + + @get:JsonProperty("Group") + var group: String? = null + + @get:JsonProperty("Kind") + var kind: String? = null + + @get:JsonProperty("Version") + var version: String? = null + + override fun toString(): String { + return "$group:$kind:$version" + } + + 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() + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRequest.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRequest.kt new file mode 100644 index 000000000..388d5e33b --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRequest.kt @@ -0,0 +1,56 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.instance + +import com.fasterxml.jackson.annotation.JsonProperty + +class K8sRbInstanceRequest { + + @get:JsonProperty("labels") + var labels: Map? = null + + @get:JsonProperty("cloud-region") + var cloudRegion: String? = null + + @get:JsonProperty("override-values") + var overrideValues: Map? = null + + @get:JsonProperty("release-name") + var releaseName: String? = null + + @get:JsonProperty("rb-name") + var rbName: String? = null + + @get:JsonProperty("rb-version") + var rbVersion: String? = null + + @get:JsonProperty("profile-name") + var profileName: 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() + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRestClient.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRestClient.kt new file mode 100644 index 000000000..4c4da6200 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceRestClient.kt @@ -0,0 +1,36 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.instance + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sAbstractRestClientService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration + +open class K8sRbInstanceRestClient( + k8sConfiguration: K8sConnectionPluginConfiguration, + private val instanceId: String = "" +) : K8sAbstractRestClientService(k8sConfiguration) { + + override fun apiUrl(): String { + return if (instanceId != "") + "$baseUrl/v1/instance/$instanceId" + else + "$baseUrl/v1/instance" + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceStatus.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceStatus.kt new file mode 100644 index 000000000..e61868984 --- /dev/null +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sRbInstanceStatus.kt @@ -0,0 +1,73 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2020 Orange. + * Modifications Copyright © 2020 Deutsche Telekom AG. + * + * 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.functions.k8s.instance + +import com.fasterxml.jackson.annotation.JsonProperty + +class K8sRbInstanceStatus { + + @get:JsonProperty("request") + var request: K8sRbInstanceRequest? = null + + @get:JsonProperty("resourceCount") + var resourceCount: Int = 0 + + @get:JsonProperty("ready") + var ready: Boolean = false + + @get:JsonProperty("resourcesStatus") + var resourcesStatus: List? = 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 K8sRbInstanceResourceStatus { + + @get:JsonProperty("name") + var name: String? = null + + @get:JsonProperty("GVK") + var gvk: K8sRbInstanceGvk? = null + + @get:JsonProperty("status") + var status: Map? = null + + override fun toString(): String { + return "$name" + } + + 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() + } +} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfile.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfile.kt deleted file mode 100644 index c9ddf4846..000000000 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfile.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2020 Orange. - * Modifications Copyright © 2020 Deutsche Telekom AG. - * - * 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.functions.k8s.profile.upload - -import com.fasterxml.jackson.annotation.JsonProperty - -class K8sProfile { - - @get:JsonProperty("rb-name") - var rbName: String? = null - - @get:JsonProperty("rb-version") - var rbVersion: String? = null - - @get:JsonProperty("profile-name") - var profileName: String? = null - - @get:JsonProperty("namespace") - var namespace: String? = "default" - - override fun toString(): String { - return "$rbName:$rbVersion:$profileName" - } - - 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() - } -} diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfileUploadComponent.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfileUploadComponent.kt deleted file mode 100644 index fb42fa7c5..000000000 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/profile/upload/K8sProfileUploadComponent.kt +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2020 Orange. - * Modifications Copyright © 2020 Deutsche Telekom AG. - * - * 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.functions.k8s.profile.upload - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ArrayNode -import com.fasterxml.jackson.databind.node.ObjectNode -import org.apache.commons.io.FileUtils -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sPluginApi -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService -import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService -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.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Component -import org.yaml.snakeyaml.Yaml -import java.io.File -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -@Component("component-k8s-profile-upload") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class K8sProfileUploadComponent( - private var bluePrintPropertiesService: BlueprintPropertiesService, - private val resourceResolutionService: ResourceResolutionService -) : - - AbstractComponentFunction() { - - companion object { - - const val INPUT_K8S_PROFILE_NAME = "k8s-rb-profile-name" - const val INPUT_K8S_DEFINITION_NAME = "k8s-rb-definition-name" - const val INPUT_K8S_DEFINITION_VERSION = "k8s-rb-definition-version" - const val INPUT_K8S_PROFILE_NAMESPACE = "k8s-rb-profile-namespace" - const val INPUT_K8S_PROFILE_SOURCE = "k8s-rb-profile-source" - const val INPUT_RESOURCE_ASSIGNMENT_MAP = "resource-assignment-map" - const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names" - - const val OUTPUT_STATUSES = "statuses" - const val OUTPUT_SKIPPED = "skipped" - const val OUTPUT_UPLOADED = "uploaded" - const val OUTPUT_ERROR = "error" - } - - private val log = LoggerFactory.getLogger(K8sProfileUploadComponent::class.java)!! - - override suspend fun processNB(executionRequest: ExecutionServiceInput) { - log.info("Triggering K8s Profile Upload component logic.") - - val inputParameterNames = arrayOf( - INPUT_K8S_PROFILE_NAME, - INPUT_K8S_DEFINITION_NAME, - INPUT_K8S_DEFINITION_VERSION, - INPUT_K8S_PROFILE_NAMESPACE, - INPUT_K8S_PROFILE_SOURCE, - INPUT_ARTIFACT_PREFIX_NAMES - ) - var outputPrefixStatuses = mutableMapOf() - var inputParamsMap = mutableMapOf() - - inputParameterNames.forEach { - inputParamsMap[it] = getOptionalOperationInput(it)?.returnNullIfMissing() - } - - log.info("Getting the template prefixes") - val prefixList: ArrayList = getTemplatePrefixList(inputParamsMap[INPUT_ARTIFACT_PREFIX_NAMES]) - - log.info("Iterating over prefixes in resource assignment map.") - for (prefix in prefixList) { - // Prefilling prefix sucess status - outputPrefixStatuses.put(prefix, OUTPUT_SKIPPED) - // Resource assignment map is organized by prefixes, in each iteraton we work only - // on one section of resource assignment map - val prefixNode: JsonNode = operationInputs[INPUT_RESOURCE_ASSIGNMENT_MAP]?.get(prefix) ?: continue - val assignmentMapPrefix = JacksonUtils.jsonNode(prefixNode.toPrettyString()) as ObjectNode - - // We are copying the map because for each prefix it might be completed with a different data - var prefixInputParamsMap = inputParamsMap.toMutableMap() - prefixInputParamsMap.forEach { (inputParamName, value) -> - if (value == null) { - val mapValue = assignmentMapPrefix?.get(inputParamName) - log.debug("$inputParamName value was $value so we fetch $mapValue") - prefixInputParamsMap[inputParamName] = mapValue - } - } - - // For clarity we pull out the required fields - val profileName: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAME]?.returnNullIfMissing()?.asText() - val definitionName: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_NAME]?.returnNullIfMissing()?.asText() - val definitionVersion: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_VERSION]?.returnNullIfMissing()?.asText() - - val k8sProfileUploadConfiguration = K8sConnectionPluginConfiguration(bluePrintPropertiesService) - - // Creating API connector - var api = K8sPluginApi( - k8sProfileUploadConfiguration.getProperties().username, - k8sProfileUploadConfiguration.getProperties().password, - k8sProfileUploadConfiguration.getProperties().url - ) - - if ((profileName == null) || (definitionName == null) || (definitionVersion == null)) { - log.warn("Prefix $prefix does not have required data for us to continue.") - } else if (!api.hasDefinition(definitionName, definitionVersion)) { - log.warn("K8s RB Definition ($definitionName/$definitionVersion) not found ") - } else if (profileName == "") { - log.warn("K8s rb profile name is empty! Either define profile name to use or choose default") - } else if (api.hasProfile(definitionName, definitionVersion, profileName)) { - log.info("Profile Already Existing - skipping upload") - } else { - log.info("Uploading K8s Profile..") - outputPrefixStatuses.put(prefix, OUTPUT_ERROR) - val profileNamespace: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAMESPACE]?.returnNullIfMissing()?.asText() - var profileSource: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_SOURCE]?.returnNullIfMissing()?.asText() - if (profileNamespace == null) - throw BlueprintProcessorException("Profile $profileName namespace is missing") - if (profileSource == null) { - profileSource = profileName - log.info("Profile name used instead of profile source") - } - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, profileSource) - if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE) - throw BlueprintProcessorException( - "Unexpected profile artifact type for profile source " + - "$profileSource. Expecting: $artifact.type" - ) - var profile = K8sProfile() - profile.profileName = profileName - profile.rbName = definitionName - profile.rbVersion = definitionVersion - profile.namespace = profileNamespace - val profileFilePath: Path = prepareProfileFile(profileName, profileSource, artifact.file) - api.createProfile(definitionName, definitionVersion, profile) - api.uploadProfileContent(definitionName, definitionVersion, profile, profileFilePath) - - log.info("K8s Profile Upload Completed") - outputPrefixStatuses.put(prefix, OUTPUT_UPLOADED) - } - } - bluePrintRuntimeService.setNodeTemplateAttributeValue( - nodeTemplateName, - OUTPUT_STATUSES, - outputPrefixStatuses.asJsonNode() - ) - } - - override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - bluePrintRuntimeService.getBlueprintError().addError(runtimeException.message!!) - } - - private fun getTemplatePrefixList(node: JsonNode?): ArrayList { - var result = ArrayList() - when (node) { - is ArrayNode -> { - val arrayNode = node.toList() - for (prefixNode in arrayNode) - result.add(prefixNode.asText()) - } - is ObjectNode -> { - result.add(node.asText()) - } - } - return result - } - - private suspend fun prepareProfileFile(k8sRbProfileName: String, ks8ProfileSource: String, ks8ProfileLocation: String): Path { - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - val bluePrintBasePath: String = bluePrintContext.rootPath - val profileSourceFileFolderPath: Path = Paths.get( - bluePrintBasePath.plus(File.separator).plus(ks8ProfileLocation) - ) - - if (profileSourceFileFolderPath.toFile().exists() && !profileSourceFileFolderPath.toFile().isDirectory) - return profileSourceFileFolderPath - else if (profileSourceFileFolderPath.toFile().exists()) { - log.info("Profile building started from source $ks8ProfileSource") - val properties: MutableMap = mutableMapOf() - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = false - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] = "" - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] = "" - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] = "" - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] = 1 - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY] = false - val resolutionResult: Pair> = resourceResolutionService.resolveResources( - bluePrintRuntimeService, - nodeTemplateName, - ks8ProfileSource, - properties - ) - val tempMainPath: File = createTempDir("k8s-profile-", "") - val tempProfilePath: File = createTempDir("content-", "", tempMainPath) - - val resolvedJsonContent = resolutionResult.second - .associateBy({ it.name }, { it.property?.value }) - .asJsonNode() - - try { - val manifestFiles: ArrayList? = readManifestFiles( - profileSourceFileFolderPath.toFile(), - tempProfilePath - ) - if (manifestFiles != null) { - templateLocation( - profileSourceFileFolderPath.toFile(), resolvedJsonContent, - tempProfilePath, manifestFiles - ) - } else - throw BlueprintProcessorException("Manifest file is missing") - // Preparation of the final profile content - val finalProfileFilePath = Paths.get( - tempMainPath.toString().plus(File.separator).plus( - "$k8sRbProfileName.tar.gz" - ) - ) - if (!BlueprintArchiveUtils.compress( - tempProfilePath, finalProfileFilePath.toFile(), - ArchiveType.TarGz - ) - ) { - throw BlueprintProcessorException("Profile compression has failed") - } - FileUtils.deleteDirectory(tempProfilePath) - - return finalProfileFilePath - } catch (t: Throwable) { - FileUtils.deleteDirectory(tempMainPath) - throw t - } - } else - throw BlueprintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder") - } - - private fun readManifestFiles(profileSource: File, destinationFolder: File): ArrayList? { - val directoryListing: Array? = profileSource.listFiles() - var result: ArrayList? = null - if (directoryListing != null) { - for (child in directoryListing) { - if (!child.isDirectory && child.name.toLowerCase() == "manifest.yaml") { - child.bufferedReader().use { inr -> - val manifestYaml = Yaml() - val manifestObject: Map = manifestYaml.load(inr) - val typeObject: MutableMap? = manifestObject["type"] as MutableMap? - if (typeObject != null) { - result = ArrayList() - val valuesObject = typeObject["values"] - if (valuesObject != null) { - result!!.add(File(destinationFolder.toString().plus(File.separator).plus(valuesObject))) - result!!.add(File(destinationFolder.toString().plus(File.separator).plus(child.name))) - } - (typeObject["configresource"] as ArrayList<*>?)?.forEach { item -> - val fileInfo: Map = item as Map - val filePath = fileInfo["filepath"] - val chartPath = fileInfo["chartpath"] - if (filePath == null || chartPath == null) - log.error("One configresource in manifest was skipped because of the wrong format") - else { - result!!.add(File(destinationFolder.toString().plus(File.separator).plus(filePath))) - } - } - } - } - break - } - } - } - return result - } - - private fun templateLocation( - location: File, - params: JsonNode, - destinationFolder: File, - manifestFiles: ArrayList - ) { - val directoryListing: Array? = location.listFiles() - if (directoryListing != null) { - for (child in directoryListing) { - var newDestinationFolder = destinationFolder.toPath() - if (child.isDirectory) - newDestinationFolder = Paths.get(destinationFolder.toString().plus(File.separator).plus(child.name)) - - templateLocation(child, params, newDestinationFolder.toFile(), manifestFiles) - } - } else if (!location.isDirectory) { - if (location.extension.toLowerCase() == "vtl") { - templateFile(location, params, destinationFolder, manifestFiles) - } else { - val finalFilePath = Paths.get( - destinationFolder.path.plus(File.separator) - .plus(location.name) - ).toFile() - if (isFileInTheManifestFiles(finalFilePath, manifestFiles)) { - if (!destinationFolder.exists()) - Files.createDirectories(destinationFolder.toPath()) - FileUtils.copyFile(location, finalFilePath) - } - } - } - } - - private fun isFileInTheManifestFiles(file: File, manifestFiles: ArrayList): Boolean { - manifestFiles.forEach { fileFromManifest -> - if (fileFromManifest.toString().toLowerCase() == file.toString().toLowerCase()) - return true - } - return false - } - - private fun templateFile( - templatedFile: File, - params: JsonNode, - destinationFolder: File, - manifestFiles: ArrayList - ) { - val finalFile = File( - destinationFolder.path.plus(File.separator) - .plus(templatedFile.nameWithoutExtension) - ) - if (!isFileInTheManifestFiles(finalFile, manifestFiles)) - return - val fileContent = templatedFile.bufferedReader().readText() - val finalFileContent = BlueprintVelocityTemplateService.generateContent( - fileContent, - params, true - ) - if (!destinationFolder.exists()) - Files.createDirectories(destinationFolder.toPath()) - finalFile.bufferedWriter().use { out -> out.write(finalFileContent) } - } -} -- cgit 1.2.3-korg