diff options
Diffstat (limited to 'ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org')
65 files changed, 10724 insertions, 0 deletions
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt new file mode 100644 index 000000000..9520f679c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt @@ -0,0 +1,213 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada + * + * 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.controllerblueprints.core + +/** + * BluePrintConstants + * + * @author Brinda Santh + */ +object BluePrintConstants { + + val APP_NAME = System.getProperty("APPLICATION_NAME") + ?: System.getProperty("APP_NAME") + ?: System.getProperty("APPNAME") + ?: "cds-controller-default" + + const val DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" + + const val RESPONSE_HEADER_MINOR_VERSION: String = "X-MinorVersion" + const val RESPONSE_HEADER_PATCH_VERSION: String = "X-PatchVersion" + const val RESPONSE_HEADER_LATEST_VERSION: String = "X-LatestVersion" + + const val ONAP_REQUEST_ID = "X-ONAP-RequestID" + const val ONAP_INVOCATION_ID = "X-ONAP-InvocationID" + const val ONAP_PARTNER_NAME = "X-ONAP-PartnerName" + + const val STATUS_SUCCESS: String = "success" + const val STATUS_PROCESSING: String = "processing" + const val STATUS_FAILURE: String = "failure" + + const val FLAG_Y: String = "Y" + const val FLAG_N: String = "N" + + const val TYPE_DEFAULT: String = "default" + + const val DATA_TYPE_STRING: String = "string" + const val DATA_TYPE_INTEGER: String = "integer" + const val DATA_TYPE_FLOAT: String = "float" + const val DATA_TYPE_DOUBLE: String = "double" + const val DATA_TYPE_BOOLEAN: String = "boolean" + const val DATA_TYPE_TIMESTAMP: String = "timestamp" + const val DATA_TYPE_NULL: String = "null" + const val DATA_TYPE_LIST: String = "list" + const val DATA_TYPE_MAP: String = "map" + const val DATA_TYPE_JSON: String = "json" + + const val SCRIPT_KOTLIN = "kotlin" + const val SCRIPT_JYTHON = "jython" + const val SCRIPT_INTERNAL = "internal" + + const val USER_SYSTEM: String = "System" + + const val PATH_DIVIDER: String = "/" + const val PATH_SERVICE_TEMPLATE: String = "service_template" + const val PATH_TOPOLOGY_TEMPLATE: String = "topology_template" + const val PATH_METADATA: String = "metadata" + const val PATH_NODE_TYPES: String = "node_types" + const val PATH_POLICY_TYPES: String = "policy_types" + const val PATH_RELATIONSHIP_TYPES: String = "relationship_types" + const val PATH_ARTIFACT_TYPES: String = "artifact_types" + const val PATH_DATA_TYPES: String = "data_types" + const val PATH_INPUTS: String = "inputs" + const val PATH_NODE_WORKFLOWS: String = "workflows" + const val PATH_NODE_TEMPLATES: String = "node_templates" + const val PATH_CAPABILITIES: String = "capabilities" + const val PATH_REQUIREMENTS: String = "requirements" + const val PATH_INTERFACES: String = "interfaces" + const val PATH_OPERATIONS: String = "operations" + const val PATH_OUTPUTS: String = "outputs" + const val PATH_PROPERTIES: String = "properties" + const val PATH_ATTRIBUTES: String = "attributes" + const val PATH_ARTIFACTS: String = "artifacts" + + const val MODEL_DIR_MODEL_TYPE: String = "definition-type" + + const val MODEL_DEFINITION_TYPE_NODE_TYPE: String = "node_type" + const val MODEL_DEFINITION_TYPE_ARTIFACT_TYPE: String = "artifact_type" + const val MODEL_DEFINITION_TYPE_CAPABILITY_TYPE: String = "capability_type" + const val MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE: String = "relationship_type" + const val MODEL_DEFINITION_TYPE_DATA_TYPE: String = "data_type" + + const val MODEL_TYPE_DATATYPES_ROOT: String = "tosca.datatypes.Root" + const val MODEL_TYPE_NODES_ROOT: String = "tosca.nodes.Root" + const val MODEL_TYPE_GROUPS_ROOT: String = "tosca.groups.Root" + const val MODEL_TYPE_RELATIONSHIPS_ROOT: String = "tosca.relationships.Root" + const val MODEL_TYPE_ARTIFACTS_ROOT: String = "tosca.artifacts.Root" + const val MODEL_TYPE_CAPABILITIES_ROOT: String = "tosca.capabilities.Root" + const val MODEL_TYPE_INTERFACES_ROOT: String = "tosca.interfaces.Root" + + const val MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON = "tosca.relationships.DependsOn" + const val MODEL_TYPE_RELATIONSHIPS_HOSTED_ON = "tosca.relationships.HostedOn" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO = "tosca.relationships.ConnectsTo" + const val MODEL_TYPE_RELATIONSHIPS_ATTACH_TO = "tosca.relationships.AttachesTo" + const val MODEL_TYPE_RELATIONSHIPS_ROUTES_TO = "tosca.relationships.RoutesTo" + + const val MODEL_TYPE_NODE_WORKFLOW = "tosca.nodes.Workflow" + const val MODEL_TYPE_NODE_COMPONENT = "tosca.nodes.Component" + const val MODEL_TYPE_NODE_VNF = "tosca.nodes.Vnf" + const val MODEL_TYPE_NODE_RESOURCE_SOURCE = "tosca.nodes.ResourceSource" + + const val MODEL_TYPE_NODES_COMPONENT_JAVA: String = "tosca.nodes.component.Java" + const val MODEL_TYPE_NODES_COMPONENT_BUNDLE: String = "tosca.nodes.component.Bundle" + const val MODEL_TYPE_NODES_COMPONENT_SCRIPT: String = "tosca.nodes.component.Script" + const val MODEL_TYPE_NODES_COMPONENT_PYTHON: String = "tosca.nodes.component.Python" + const val MODEL_TYPE_NODES_COMPONENT_JYTHON: String = "tosca.nodes.component.Jython" + const val MODEL_TYPE_NODES_COMPONENT_KOTLIN: String = "tosca.nodes.component.Kotlin" + const val MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT: String = "tosca.nodes.component.JavaScript" + + const val MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION = "tosca.artifacts.Implementation" + + const val MODEL_TYPE_DATA_TYPE_DYNAMIC = "tosca.datatypes.Dynamic" + + const val MODEL_TYPE_CAPABILITY_TYPE_NODE = "tosca.capabilities.Node" + const val MODEL_TYPE_CAPABILITY_TYPE_COMPUTE = "tosca.capabilities.Compute" + const val MODEL_TYPE_CAPABILITY_TYPE_NETWORK = "tosca.capabilities.Network" + const val MODEL_TYPE_CAPABILITY_TYPE_STORAGE = "tosca.capabilities.Storage" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT = "tosca.capabilities.Endpoint" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC = "tosca.capabilities.Endpoint.Public" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN = "tosca.capabilities.Endpoint.Admin" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE = "tosca.capabilities.Endpoint.Database" + const val MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT = "tosca.capabilities.Attachment" + const val MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM = "tosca.capabilities.OperatingSystem" + const val MODEL_TYPE_CAPABILITY_TYPE_BINDABLE = "tosca.capabilities.network.Bindable" + // Custom capabilities + const val MODEL_TYPE_CAPABILITY_TYPE_CONTENT = "tosca.capabilities.Content" + const val MODEL_TYPE_CAPABILITY_TYPE_MAPPING = "tosca.capabilities.Mapping" + const val MODEL_TYPE_CAPABILITY_TYPE_NETCONF = "tosca.capabilities.Netconf" + const val MODEL_TYPE_CAPABILITY_TYPE_SSH = "tosca.capabilities.Ssh" + const val MODEL_TYPE_CAPABILITY_TYPE_SFTP = "tosca.capabilities.Sftp" + + const val EXPRESSION_DSL_REFERENCE: String = "*" + const val EXPRESSION_GET_INPUT: String = "get_input" + const val EXPRESSION_GET_ATTRIBUTE: String = "get_attribute" + const val EXPRESSION_GET_ARTIFACT: String = "get_artifact" + const val EXPRESSION_GET_PROPERTY: String = "get_property" + const val EXPRESSION_GET_OPERATION_OUTPUT: String = "get_operation_output" + const val EXPRESSION_GET_NODE_OF_TYPE: String = "get_nodes_of_type" + + const val PROPERTY_BLUEPRINT_PROCESS_ID: String = "blueprint-process-id" + const val PROPERTY_BLUEPRINT_VALID: String = "blueprint-valid" + const val PROPERTY_BLUEPRINT_BASE_PATH: String = "blueprint-basePath" + const val PROPERTY_BLUEPRINT_RUNTIME: String = "blueprint-runtime" + const val PROPERTY_BLUEPRINT_INPUTS_DATA: String = "blueprint-inputs-data" + const val PROPERTY_BLUEPRINT_CONTEXT: String = "blueprint-context" + const val PROPERTY_BLUEPRINT_NAME: String = "template_name" + const val PROPERTY_BLUEPRINT_VERSION: String = "template_version" + + const val TOSCA_METADATA_DIR: String = "TOSCA-Metadata" + const val TOSCA_METADATA_ENTRY_DEFINITION_FILE: String = "TOSCA-Metadata/TOSCA.meta" + const val TOSCA_DEFINITIONS_DIR: String = "Definitions" + const val TOSCA_PLANS_DIR: String = "Plans" + const val TOSCA_SCRIPTS_DIR: String = "Scripts" + const val TOSCA_MAPPINGS_DIR: String = "Mappings" + const val TOSCA_TEMPLATES_DIR: String = "Templates" + const val TOSCA_ENVIRONMENTS_DIR: String = "Environments" + const val TOSCA_SCRIPTS_KOTLIN_DIR: String = "$TOSCA_SCRIPTS_DIR/kotlin" + const val TOSCA_SCRIPTS_JYTHON_DIR: String = "$TOSCA_SCRIPTS_DIR/python" + + const val UAT_SPECIFICATION_FILE = "Tests/uat.yaml" + + const val GRAPH_START_NODE_NAME = "START" + const val GRAPH_END_NODE_NAME = "END" + + const val PROPERTY_ENV = "ENV" + const val PROPERTY_APP = "APP" + const val PROPERTY_BPP = "BPP" + const val PROPERTY_SELF = "SELF" + + const val METADATA_TEMPLATE_NAME = "template_name" + const val METADATA_TEMPLATE_VERSION = "template_version" + const val METADATA_TEMPLATE_AUTHOR = "template_author" + const val METADATA_TEMPLATE_TAGS = "template_tags" + const val METADATA_WORKFLOW_NAME = "workflow_name" + + const val PAYLOAD_DATA = "payload-data" + const val PROPERTY_CURRENT_STEP = "current-step" + const val PROPERTY_CURRENT_NODE_TEMPLATE = "current-node-template" + const val PROPERTY_CURRENT_INTERFACE = "current-interface" + const val PROPERTY_CURRENT_OPERATION = "current-operation" + const val PROPERTY_CURRENT_TIMEOUT = "current-timeout" + const val PROPERTY_CURRENT_IMPLEMENTATION = "current-implementation" + const val PROPERTY_EXECUTION_REQUEST = "execution-request" + + const val DEFAULT_VERSION_NUMBER = "1.0.0" + const val DEFAULT_STEP_OPERATION = "process" + const val DEFAULT_STEP_INTERFACE = "ComponentInterface" + + const val ARTIFACT_VELOCITY_TYPE_NAME = "artifact-template-velocity" + const val ARTIFACT_JINJA_TYPE_NAME = "artifact-template-jinja" + + const val MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY = "artifact-template-velocity" + const val MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA = "artifact-template-jinja" + const val MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE = "artifact-mapping-resource" + const val MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON = "artifact-script-jython" + const val MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN = "artifact-script-kotlin" + const val MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH = "artifact-directed-graph" + const val MODEL_TYPE_ARTIFACT_COMPONENT_JAR = "artifact-component-jar" +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt new file mode 100644 index 000000000..66d54f52e --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt @@ -0,0 +1,29 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core + +class BluePrintError { + var errors: MutableList<String> = arrayListOf() + + fun addError(type: String, name: String, error: String) { + this.errors.add("$type : $name : $error") + } + + fun addError(error: String) { + this.errors.add(error) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt new file mode 100644 index 000000000..a2435da13 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt @@ -0,0 +1,49 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core + +/** + * + * + * @author Brinda Santh + */ +class BluePrintException : Exception { + + var code: Int = 100 + + constructor(cause: Throwable) : super(cause) + constructor(message: String) : super(message) + constructor(message: String, cause: Throwable) : super(message, cause) + constructor(cause: Throwable, message: String, vararg args: Any?) : super(String.format(message, *args), cause) + + constructor(code: Int, cause: Throwable) : super(cause) { + this.code = code + } + + constructor(code: Int, message: String) : super(message) { + this.code = code + } + + constructor(code: Int, message: String, cause: Throwable) : super(message, cause) { + this.code = code + } + + constructor(code: Int, cause: Throwable, message: String, vararg args: Any?) : + super(String.format(message, *args), cause) { + this.code = code + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt new file mode 100644 index 000000000..daf833494 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt @@ -0,0 +1,148 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core + +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.ArtifactExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.AttributeExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsConstrain +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsDataType +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsProperty +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.DSLExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.InputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.OperationOutputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyDefaultValue +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.dslExpression +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getInput +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateArtifact +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateAttribute +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateOperationOutput +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateProperty +import kotlin.reflect.KClass +import kotlin.reflect.KProperty1 +import kotlin.reflect.KType +import kotlin.reflect.full.declaredMemberProperties + +fun <T : KClass<*>> T.asBluePrintsDataTypes(): DataType { + val annotation = this.annotations.filter { it is BluePrintsDataType }.single() as BluePrintsDataType + checkNotNull(annotation) { "BluePrintsDataType annotation definition not found" } + val dataType = DataType().apply { + id = annotation.name + version = annotation.version + derivedFrom = annotation.derivedFrom + description = annotation.description + } + dataType.properties = this.asPropertyDefinitionMap() + return dataType +} + +fun <T : KClass<*>> T.asPropertyDefinitionMap(): MutableMap<String, PropertyDefinition> { + val properties: MutableMap<String, PropertyDefinition> = hashMapOf() + this.declaredMemberProperties.forEach { member -> + properties[member.name] = member.asPropertyDefinition() + } + return properties +} + +fun <T> KProperty1<T, *>.asPropertyDefinition(): PropertyDefinition { + val property = PropertyDefinition() + property.id = this.name + val getter = this.getter + property.required = !this.returnType.isMarkedNullable + property.type = this.returnType.asBluePrintsDataType(this.name) + if (this.returnType.arguments.isNotEmpty()) { + property.entrySchema = this.returnType.entitySchema() + } + this.annotations.forEach { fieldAnnotation -> + // println("Field : ${this.name} : Annotation : $fieldAnnotation") + when (fieldAnnotation) { + is BluePrintsProperty -> + property.description = fieldAnnotation.description + is PropertyDefaultValue -> + property.value = fieldAnnotation.value.asJsonType(property.type) + is BluePrintsConstrain -> { + if (property.constraints == null) property.constraints = arrayListOf() + property.constraints!!.add(fieldAnnotation.asBluePrintConstraintClause()) + } + is InputExpression -> { + property.value = getInput(fieldAnnotation.propertyName) + } + is PropertyExpression -> { + property.value = getNodeTemplateProperty( + fieldAnnotation.modelableEntityName, + fieldAnnotation.propertyName, fieldAnnotation.subPropertyName + ) + } + is AttributeExpression -> { + property.value = getNodeTemplateAttribute( + fieldAnnotation.modelableEntityName, + fieldAnnotation.attributeName, fieldAnnotation.subAttributeName + ) + } + is ArtifactExpression -> { + property.value = getNodeTemplateArtifact( + fieldAnnotation.modelableEntityName, + fieldAnnotation.artifactName + ) + } + is OperationOutputExpression -> { + property.value = getNodeTemplateOperationOutput( + fieldAnnotation.modelableEntityName, + fieldAnnotation.interfaceName, fieldAnnotation.propertyName, fieldAnnotation.subPropertyName + ) + } + is DSLExpression -> { + property.value = dslExpression(fieldAnnotation.propertyName) + } + } + } + return property +} + +internal fun BluePrintsConstrain.asBluePrintConstraintClause(): ConstraintClause { + TODO() +} + +internal fun <T : KType> T.entitySchema(): EntrySchema { + val entrySchema = EntrySchema() + if (this.arguments.size == 1) { + entrySchema.type = this.arguments[0].type!!.asBluePrintsDataType("") + } else if (this.arguments.size == 2) { + entrySchema.type = this.arguments[1].type!!.asBluePrintsDataType("") + } + return entrySchema +} + +internal fun <T : KType> T.asBluePrintsDataType(propertyName: String): String { + val simpleName = (this.classifier as? KClass<*>)?.java?.simpleName + ?: throw BluePrintException("filed to get simple name.") + return when (simpleName) { + "String", "Date" -> BluePrintConstants.DATA_TYPE_STRING + "int" -> BluePrintConstants.DATA_TYPE_INTEGER + "Boolean" -> BluePrintConstants.DATA_TYPE_BOOLEAN + "Float" -> BluePrintConstants.DATA_TYPE_FLOAT + "Double" -> BluePrintConstants.DATA_TYPE_DOUBLE + "List" -> BluePrintConstants.DATA_TYPE_LIST + "Map" -> BluePrintConstants.DATA_TYPE_MAP + "Object", "JsonNode", "ObjectNode", "ArrayNode" -> BluePrintConstants.DATA_TYPE_JSON + else -> simpleName + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt new file mode 100644 index 000000000..b0b217051 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt @@ -0,0 +1,57 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core + +/** + * + * + * @author Brinda Santh + */ +class BluePrintProcessorException : RuntimeException { + + var code: Int = 100 + + constructor(message: String, cause: Throwable) : super(message, cause) + constructor(message: String) : super(message) + constructor(cause: Throwable) : super(cause) + constructor(cause: Throwable, message: String, vararg args: Any?) : super(format(message, *args), cause) + + constructor(code: Int, cause: Throwable) : super(cause) { + this.code = code + } + + constructor(code: Int, message: String) : super(message) { + this.code = code + } + + constructor(code: Int, message: String, cause: Throwable) : super(message, cause) { + this.code = code + } + + constructor(code: Int, cause: Throwable, message: String, vararg args: Any?) : + super(String.format(message, *args), cause) { + this.code = code + } +} + +class BluePrintRetryException : RuntimeException { + constructor(message: String, cause: Throwable) : super(message, cause) + constructor(message: String) : super(message) + constructor(cause: Throwable) : super(cause) + constructor(cause: Throwable, message: String, vararg args: Any?) : super(format(message, *args), cause) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt new file mode 100644 index 000000000..0e4279a3a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt @@ -0,0 +1,164 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core + +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition + +/** + * + * + * @author Brinda Santh + */ +object BluePrintTypes { + + @JvmStatic + val validNodeTypeDerivedFroms: MutableList<String> = arrayListOf( + BluePrintConstants.MODEL_TYPE_NODES_ROOT, + BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, + BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, + BluePrintConstants.MODEL_TYPE_NODE_VNF, + BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_BUNDLE, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_SCRIPT, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_PYTHON, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JYTHON, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT + ) + + @JvmStatic + val validArtifactTypeDerivedFroms: MutableList<String> = arrayListOf( + BluePrintConstants.MODEL_TYPE_ARTIFACTS_ROOT, + BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION + ) + + @JvmStatic + val validDataTypeDerivedFroms: MutableList<String> = arrayListOf( + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, + BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC + ) + + @JvmStatic + val validRelationShipDerivedFroms: MutableList<String> = arrayListOf( + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ATTACH_TO, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROUTES_TO + ) + + @JvmStatic + val validCapabilityTypes: MutableList<String> = arrayListOf( + BluePrintConstants.MODEL_TYPE_CAPABILITIES_ROOT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NODE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_COMPUTE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETWORK, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_STORAGE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_BINDABLE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_CONTENT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_MAPPING, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETCONF, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SSH, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SFTP + ) + + @JvmStatic + fun validModelTypes(): List<String> { + val validTypes: MutableList<String> = arrayListOf() + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE) + return validTypes + } + + @JvmStatic + fun validPropertyTypes(): List<String> { + val validTypes: MutableList<String> = arrayListOf() + validTypes.addAll(validPrimitiveTypes()) + validTypes.addAll(validComplexTypes()) + validTypes.addAll(validCollectionTypes()) + return validTypes + } + + @JvmStatic + fun validPrimitiveTypes(): List<String> { + val validTypes: MutableList<String> = arrayListOf() + validTypes.add(BluePrintConstants.DATA_TYPE_STRING) + validTypes.add(BluePrintConstants.DATA_TYPE_INTEGER) + validTypes.add(BluePrintConstants.DATA_TYPE_FLOAT) + validTypes.add(BluePrintConstants.DATA_TYPE_DOUBLE) + validTypes.add(BluePrintConstants.DATA_TYPE_BOOLEAN) + validTypes.add(BluePrintConstants.DATA_TYPE_TIMESTAMP) + validTypes.add(BluePrintConstants.DATA_TYPE_NULL) + return validTypes + } + + @JvmStatic + fun validComplexTypes(): List<String> { + val validTypes: MutableList<String> = arrayListOf() + validTypes.add(BluePrintConstants.DATA_TYPE_JSON) + return validTypes + } + + @JvmStatic + fun validCollectionTypes(): List<String> { + val validTypes: MutableList<String> = arrayListOf() + validTypes.add(BluePrintConstants.DATA_TYPE_LIST) + validTypes.add(BluePrintConstants.DATA_TYPE_MAP) + return validTypes + } + + @JvmStatic + fun validPrimitiveOrCollectionPrimitive(propertyDefinition: PropertyDefinition): Boolean { + val entrySchema = propertyDefinition.entrySchema?.type ?: BluePrintConstants.DATA_TYPE_NULL + return BluePrintTypes.validPropertyTypes().contains(propertyDefinition.type) && + BluePrintTypes.validPrimitiveTypes().contains(entrySchema) + } + + @JvmStatic + fun validCommands(): List<String> { + return listOf( + BluePrintConstants.EXPRESSION_DSL_REFERENCE, + BluePrintConstants.EXPRESSION_GET_INPUT, + BluePrintConstants.EXPRESSION_GET_ATTRIBUTE, + BluePrintConstants.EXPRESSION_GET_PROPERTY, + BluePrintConstants.EXPRESSION_GET_ARTIFACT, + BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT, + BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE + ) + } + + @JvmStatic + fun rootNodeTypes(): List<String> { + return listOf(BluePrintConstants.MODEL_TYPE_NODES_ROOT) + } + + @JvmStatic + fun rootDataTypes(): List<String> { + return listOf(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/ConfigModelConstant.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/ConfigModelConstant.kt new file mode 100644 index 000000000..e8e13f2b0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/ConfigModelConstant.kt @@ -0,0 +1,30 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core + +/** + * + * + * @author Brinda Santh + */ +object ConfigModelConstant { + + const val MODEL_CONTENT_TYPE_TOSCA_JSON = "TOSCA_JSON" + const val MODEL_CONTENT_TYPE_TEMPLATE = "TEMPLATE" + const val CAPABILITY_PROPERTY_MAPPING = "mapping" +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt new file mode 100644 index 000000000..5189d0758 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt @@ -0,0 +1,333 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.BooleanNode +import com.fasterxml.jackson.databind.node.DoubleNode +import com.fasterxml.jackson.databind.node.IntNode +import com.fasterxml.jackson.databind.node.MissingNode +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import com.fasterxml.jackson.databind.node.TextNode +import org.apache.commons.lang3.ObjectUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JsonParserUtils +import org.slf4j.LoggerFactory +import org.slf4j.helpers.MessageFormatter +import java.util.UUID +import kotlin.reflect.KClass + +/** + * + * + * @author Brinda Santh + */ + +fun <T : Any> logger(clazz: T) = LoggerFactory.getLogger(clazz.javaClass)!! + +fun <T : KClass<*>> logger(clazz: T) = LoggerFactory.getLogger(clazz.java)!! + +fun <T : Any> T?.defaultToEmpty(): String { + return this?.toString() ?: "" +} + +fun <T : Any> T?.defaultToUUID(): String { + return this?.toString() ?: UUID.randomUUID().toString() +} + +fun <T : Any> T.bpClone(): T { + return ObjectUtils.clone(this) +} + +fun String.isJson(): Boolean { + return ((this.trim().startsWith("{") && this.trim().endsWith("}")) || + (this.trim().startsWith("[") && this.trim().endsWith("]"))) +} + +fun Any.asJsonString(intend: Boolean? = false): String { + return JacksonUtils.getJson(this, intend!!) +} + +fun String.asJsonPrimitive(): TextNode { + return TextNode(this) +} + +inline fun <reified T : Any> String.jsonAsType(): T { + return JacksonUtils.readValue<T>(this.trim()) +} + +// If you know the string is json content, then use the function directly +fun String.jsonAsJsonType(): JsonNode { + return JacksonUtils.jsonNode(this.trim()) +} + +fun Boolean.asJsonPrimitive(): BooleanNode { + return BooleanNode.valueOf(this) +} + +fun Int.asJsonPrimitive(): IntNode { + return IntNode.valueOf(this) +} + +fun Double.asJsonPrimitive(): DoubleNode { + return DoubleNode.valueOf(this) +} + +/** + * Utility to convert Primitive object to Json Type Primitive. + */ +fun <T : Any?> T.asJsonPrimitive(): JsonNode { + return if (this == null || this is MissingNode || this is NullNode) { + NullNode.instance + } else { + when (this) { + is String -> + this.asJsonPrimitive() + is Boolean -> + this.asJsonPrimitive() + is Int -> + this.asJsonPrimitive() + is Double -> + this.asJsonPrimitive() + else -> + throw BluePrintException("$this type is not supported") + } + } +} + +/** Based on Blueprint DataType Convert string value to JsonNode Type **/ +fun String.asJsonType(bpDataType: String): JsonNode { + return when (bpDataType.toLowerCase()) { + BluePrintConstants.DATA_TYPE_STRING -> this.asJsonPrimitive() + BluePrintConstants.DATA_TYPE_BOOLEAN -> this.toBoolean().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_INTEGER -> this.toInt().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_FLOAT -> this.toFloat().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_DOUBLE -> this.toDouble().asJsonPrimitive() + // For List, Map and Complex Types. + else -> this.jsonAsJsonType() + } +} + +/** + * Utility to convert Complex or Primitive object to Json Type. + */ +fun <T : Any?> T.asJsonType(): JsonNode { + return if (this == null || this is MissingNode || this is NullNode) { + NullNode.instance + } else { + when (this) { + is JsonNode -> + this + is String -> { + if (this.isJson()) + this.jsonAsJsonType() + else + TextNode(this) + } + is Boolean -> + BooleanNode.valueOf(this) + is Int -> + IntNode.valueOf(this.toInt()) + is Double -> + DoubleNode.valueOf(this.toDouble()) + else -> + JacksonUtils.jsonNodeFromObject(this) + } + } +} + +fun Map<String, *>.asJsonNode(): JsonNode { + return JacksonUtils.jsonNodeFromObject(this) +} + +fun Map<String, *>.asObjectNode(): ObjectNode { + return JacksonUtils.objectNodeFromObject(this) +} + +fun format(message: String, vararg args: Any?): String { + if (args != null && args.isNotEmpty()) { + return MessageFormatter.arrayFormat(message, args).message + } + return message +} + +fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? { + return if (containsKey(key)) { + get(key) as? T + } else { + null + } +} + +fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T { + if (containsKey(key)) { + return get(key) as T + } else { + throw BluePrintException("couldn't find the key $key") + } +} + +fun ArrayNode.asListOfString(): List<String> { + return JacksonUtils.getListFromJsonNode(this, String::class.java) +} + +fun <T> JsonNode.asType(clazzType: Class<T>): T { + return JacksonUtils.readValue(this, clazzType) + ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType") +} + +fun JsonNode.asListOfString(): List<String> { + check(this is ArrayNode) { "JsonNode is not of type ArrayNode" } + return this.asListOfString() +} + +fun <T : JsonNode> T?.returnNullIfMissing(): JsonNode? { + return if (this == null || this is NullNode || this is MissingNode) { + null + } else this +} + +fun <T : JsonNode> T?.isNullOrMissing(): Boolean { + return this == null || this is NullNode || this is MissingNode +} + +/** + * Convert Json to map of json node, the root fields will be map keys + */ +fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> { + if (this is ObjectNode) { + val propertyMap: MutableMap<String, JsonNode> = linkedMapOf() + this.fields().forEach { + propertyMap[it.key] = it.value + } + return propertyMap + } else { + throw BluePrintException("json node should be Object Node Type") + } +} + +fun JsonNode.removeNullNode() { + val it = this.iterator() + while (it.hasNext()) { + val child = it.next() + if (child.isNull) { + it.remove() + } else { + child.removeNullNode() + } + } +} + +fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) { + val convertedValue = value.asJsonType() + this[key] = convertedValue +} + +fun Map<String, JsonNode>.getAsString(key: String): String { + return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)") +} + +fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean { + return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)") +} + +fun Map<String, JsonNode>.getAsInt(key: String): Int { + return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)") +} + +fun Map<String, JsonNode>.getAsDouble(key: String): Double { + return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)") +} + +fun Map<String, JsonNode>.getOptionalAsString(key: String): String? { + return if (this.containsKey(key)) this[key]!!.asText() else null +} + +fun Map<String, JsonNode>.getOptionalAsBoolean(key: String): Boolean? { + return if (this.containsKey(key)) this[key]!!.asBoolean() else null +} + +fun Map<String, JsonNode>.getOptionalAsInt(key: String): Int? { + return if (this.containsKey(key)) this[key]!!.asInt() else null +} + +fun Map<String, JsonNode>.getOptionalAsDouble(key: String): Double? { + return if (this.containsKey(key)) this[key]!!.asDouble() else null +} + +// Checks + +inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean { + if (value1.equals(value2, ignoreCase = true)) { + return true + } else { + throw BluePrintException(lazyMessage().toString()) + } +} + +inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String { + if (value == null || value.isEmpty()) { + val message = lazyMessage() + throw IllegalStateException(message.toString()) + } else { + return value + } +} + +inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String { + if (value == null || value.isBlank()) { + val message = lazyMessage() + throw IllegalStateException(message.toString()) + } else { + return value + } +} + +fun isNotEmpty(value: String?): Boolean { + return value != null && value.isNotEmpty() +} + +fun isNotBlank(value: String?): Boolean { + return value != null && value.isNotBlank() +} + +fun <T : String> T?.emptyTONull(): String? { + return if (this == null || this.isEmpty()) null else this +} + +fun nullToEmpty(value: String?): String { + return if (isNotEmpty(value)) value!! else "" +} + +inline fun <reified T : JsonNode> T.isComplexType(): Boolean { + return this is ObjectNode || this is ArrayNode +} + +// Json Parsing Extensions +fun JsonNode.jsonPathParse(expression: String): JsonNode { + check(this.isComplexType()) { "$this is not complex or array node to apply expression" } + return JsonParserUtils.parse(this, expression) +} + +// Json Path Extensions +fun JsonNode.jsonPaths(expression: String): List<String> { + check(this.isComplexType()) { "$this is not complex or array node to apply expression" } + return JsonParserUtils.paths(this, expression) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt new file mode 100644 index 000000000..518e9b236 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt @@ -0,0 +1,108 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.apache.commons.io.FileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils +import java.io.File +import java.io.InputStream +import java.nio.charset.Charset +import java.nio.file.Path +import java.nio.file.Paths + +fun InputStream.toFile(path: String): File { + val file = File(path) + file.outputStream().use { this.copyTo(it) } + return file +} + +fun File.reCreateDirs(): File { + if (this.exists()) { + this.deleteRecursively() + } + // this.mkdirs() + FileUtils.forceMkdir(this) + check(this.exists()) { + throw BluePrintException("failed to re create dir(${this.absolutePath})") + } + return this +} + +fun File.compress(targetZipFileName: String): File { + return this.compress(Paths.get(targetZipFileName).toFile()) +} + +/** + * Compress the current Dir to the target zip file and return the target zip file + */ +fun File.compress(targetZipFile: File): File { + BluePrintArchiveUtils.compress(this, targetZipFile) + return targetZipFile +} + +fun File.deCompress(targetFileName: String): File { + return this.deCompress(Paths.get(targetFileName).toFile()) +} + +/** + * De-Compress the current zip file to the target file and return the target file + */ +fun File.deCompress(targetFile: File): File { + BluePrintArchiveUtils.deCompress(this, targetFile.path) + return targetFile +} + +fun deleteDir(path: String, vararg more: String?) { + normalizedFile(path, *more).deleteRecursively() +} + +fun checkFileExists(file: File, lazyMessage: () -> Any) { + if (!file.exists()) { + val message = lazyMessage() + throw IllegalStateException(message.toString()) + } +} + +fun normalizedFile(path: String, vararg more: String?): File { + return Paths.get(path, *more).toFile().normalize() +} + +fun normalizedPath(path: String, vararg more: String?): Path { + return Paths.get(path, *more).toAbsolutePath().normalize() +} + +fun normalizedPathName(path: String, vararg more: String?): String { + return normalizedPath(path, *more).toString() +} + +suspend fun File.reCreateNBDirs(): File = withContext(Dispatchers.IO) { + reCreateDirs() +} + +suspend fun deleteNBDir(path: String, vararg more: String?): Boolean = withContext(Dispatchers.IO) { + normalizedFile(path, *more).deleteRecursively() +} + +suspend fun File.readNBText(): String = withContext(Dispatchers.IO) { + readText(Charset.defaultCharset()) +} + +suspend fun File.readNBLines(): List<String> = withContext(Dispatchers.IO) { + readLines(Charset.defaultCharset()) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt new file mode 100644 index 000000000..5995a8a9e --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core + +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel +import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.utils.WorkflowGraphUtils +import java.util.regex.Pattern + +private val graphTokenSeparators = Pattern.compile("[->/]") + +/** Convert Blueprint workflow to graph data structure */ +fun Workflow.asGraph(): Graph { + return WorkflowGraphUtils.workFlowToGraph(this) +} + +fun String.toGraph(): Graph { + if (!startsWith('[') || !endsWith(']')) { + throw IllegalArgumentException("Expected string starting '[' and ending with ']' but it was '$") + } + val tokens = substring(1, length - 1).split(", ").map { it.split(graphTokenSeparators) } + val nodes = tokens.flatMap { it.take(2) }.toCollection(LinkedHashSet()) + val edges = tokens.filter { it.size == 3 }.map { Graph.TermForm.Term(it[0], it[1], EdgeLabel.valueOf(it[2])) } + return Graph.labeledDirectedTerms(Graph.TermForm(nodes, edges)) +} + +fun Graph.toAdjacencyList(): Graph.AdjacencyList<String, EdgeLabel> { + val entries = nodes.values.map { node -> + val links = node.edges.map { Graph.AdjacencyList.Link(it.target(node).id, it.label) } + Graph.AdjacencyList.Entry(node = node.id, links = links) + } + return Graph.AdjacencyList(entries) +} + +fun Graph.findAllPaths(from: String, to: String, path: List<String> = emptyList()): List<List<String>> { + if (from == to) return listOf(path + to) + return nodes[from]!!.neighbors() + .filter { !path.contains(it.id) } + .flatMap { findAllPaths(it.id, to, path + from) } +} + +fun Graph.findCycles(node: String): List<List<String>> { + fun findCycles(path: List<String>): List<List<String>> { + if (path.size > 3 && path.first() == path.last()) return listOf(path) + return nodes[path.last()]!!.neighbors() + .filterNot { path.tail().contains(it.id) } + .flatMap { findCycles(path + it.id) } + } + return findCycles(listOf(node)) +} + +fun Graph.startNodes() = this.nodes.values.filter { + val incomingEdges = incomingEdges(it.id) + incomingEdges.isEmpty() +} + +fun Graph.endNodes(): Set<Graph.Node> = this.nodes.values.filter { + outgoingEdges(it.id).isEmpty() +}.toSet() + +fun Graph.node(node: String) = this.nodes[node] + +fun Graph.edge(label: EdgeLabel) = + this.edges.filter { it.label == label } + +fun Graph.incomingEdges(node: String) = + this.edges.filter { it.target.id == node } + +fun Graph.incomingNodes(node: String) = + this.incomingEdges(node).map { it.source } + +fun Graph.outgoingEdges(node: String) = + this.edges.filter { it.source.id == node } + +fun Graph.outgoingNodes(node: String) = + this.outgoingEdges(node).map { it.target } + +fun Graph.outgoingEdges(node: String, label: EdgeLabel) = + this.edges.filter { it.source.id == node && it.label == label } + +fun Graph.outgoingNodes(node: String, label: EdgeLabel) = + this.outgoingEdges(node, label).map { it.target } + +fun Graph.outgoingNodesNotInEdgeLabels(node: String, labels: List<EdgeLabel>) = + this.outgoingEdgesNotInLabels(node, labels).map { it.target } + +fun Graph.outgoingEdges(node: String, labels: List<EdgeLabel>) = + this.edges.filter { it.source.id == node && labels.contains(it.label) } + +fun Graph.outgoingEdgesNotInLabels(node: String, labels: List<EdgeLabel>) = + this.edges.filter { it.source.id == node && !labels.contains(it.label) } + +fun Graph.outgoingNodes(node: String, labels: List<EdgeLabel>) = + this.outgoingEdges(node, labels).map { it.target } + +fun Graph.isEndNode(node: Graph.Node): Boolean { + return this.endNodes().contains(node) +} + +fun <T> List<T>.tail(): List<T> = drop(1) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt new file mode 100644 index 000000000..9d81f13e3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt @@ -0,0 +1,51 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * 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.controllerblueprints.core + +import kotlinx.coroutines.ThreadContextElement +import org.slf4j.MDC +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext + +typealias MDCContextMap = Map<String, String>? + +class MDCContext(private val contextMap: MDCContextMap = MDC.getCopyOfContextMap()) : + ThreadContextElement<MDCContextMap>, AbstractCoroutineContextElement(Key) { + + /** + * Key of [MDCContext] in [CoroutineContext]. + */ + companion object Key : CoroutineContext.Key<MDCContext> + + override fun updateThreadContext(context: CoroutineContext): MDCContextMap { + val oldState = MDC.getCopyOfContextMap() + setCurrent(contextMap) + return oldState + } + + override fun restoreThreadContext(context: CoroutineContext, oldState: MDCContextMap) { + setCurrent(oldState) + } + + private fun setCurrent(contextMap: MDCContextMap) { + if (contextMap == null) { + MDC.clear() + } else { + MDC.setContextMap(contextMap) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt new file mode 100644 index 000000000..c39442976 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt @@ -0,0 +1,100 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.annotations + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import kotlin.reflect.KClass + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsDataType( + val name: String, + val version: String = BluePrintConstants.DEFAULT_VERSION_NUMBER, + val description: String, + val derivedFrom: String = "tosca.datatypes.root" +) + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsWorkflowInput + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsWorkflowOutput + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsNodeType( + val propertiesType: KClass<*>, + val attributesType: KClass<*>, + val inputsType: KClass<*>, + val outputsType: KClass<*> +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class BluePrintsProperty( + val name: String = "", + val description: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +@Repeatable +annotation class BluePrintsConstrain() + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class PropertyDefaultValue(val value: String) + +annotation class PropertyValidValue(val value: String) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class InputExpression( + val propertyName: String +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class PropertyExpression( + val modelableEntityName: String = "SELF", + val reqOrCapEntityName: String = "", + val propertyName: String, + val subPropertyName: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class AttributeExpression( + val modelableEntityName: String = "SELF", + val reqOrCapEntityName: String = "", + val attributeName: String, + val subAttributeName: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class ArtifactExpression( + val modelableEntityName: String = "SELF", + val artifactName: String, + val location: String = "LOCAL_FILE", + val remove: Boolean = false +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class OperationOutputExpression( + val modelableEntityName: String = "SELF", + val interfaceName: String, + val operationName: String, + val propertyName: String, + val subPropertyName: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class DSLExpression( + val propertyName: String +) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt new file mode 100644 index 000000000..66bc3b3cb --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt @@ -0,0 +1,23 @@ +/* + * Copyright © 2019 Bell Canada + * + * 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.controllerblueprints.core.common + +object ApplicationConstants { + const val ACTIVE_Y = "Y" + const val ACTIVE_N = "N" + const val ASDC_ARTIFACT_TYPE_SDNC_MODEL = "SDNC_MODEL" +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt new file mode 100644 index 000000000..0128f64a5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt @@ -0,0 +1,28 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.config + +open class BluePrintLoadConfiguration { + lateinit var blueprintDeployPath: String + lateinit var blueprintArchivePath: String + lateinit var blueprintWorkingPath: String + + var loadBluePrintPaths: String? = null + var loadModeTypePaths: String? = null + var loadResourceDictionaryPaths: String? = null +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt new file mode 100644 index 000000000..37c128714 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt @@ -0,0 +1,77 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. + * + * 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. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.controllerblueprints.core.data + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ObjectNode + +/** + * + * + * @author Brinda Santh + */ +data class ExpressionData( + var isExpression: Boolean = false, + var valueNode: JsonNode, + var expressionNode: ObjectNode? = null, + var dslExpression: DSLExpression? = null, + var inputExpression: InputExpression? = null, + var propertyExpression: PropertyExpression? = null, + var attributeExpression: AttributeExpression? = null, + var artifactExpression: ArtifactExpression? = null, + var operationOutputExpression: OperationOutputExpression? = null, + var command: String? = null +) + +data class InputExpression( + var propertyName: String +) + +data class PropertyExpression( + var modelableEntityName: String = "SELF", + var reqOrCapEntityName: String? = null, + var propertyName: String, + var subPropertyName: String? = null +) + +data class AttributeExpression( + var modelableEntityName: String = "SELF", + var reqOrCapEntityName: String? = null, + var attributeName: String, + var subAttributeName: String? = null +) + +data class ArtifactExpression( + val modelableEntityName: String = "SELF", + val artifactName: String, + val location: String? = "LOCAL_FILE", + val remove: Boolean? = false +) + +data class OperationOutputExpression( + val modelableEntityName: String = "SELF", + val interfaceName: String, + val operationName: String, + val propertyName: String, + var subPropertyName: String? = null +) + +data class DSLExpression( + val propertyName: String +) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt new file mode 100644 index 000000000..9c9b1f9bf --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt @@ -0,0 +1,180 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.data + +enum class EdgeLabel(val id: String) { + SUCCESS("success"), + FAILURE("failure"), + DEFAULT("*") +} + +enum class EdgeStatus(val id: String) { + NOT_STARTED("not_started"), + EXECUTED("executed"), + SKIPPED("skipped") +} + +enum class NodeStatus(val id: String) { + NOT_STARTED("not_started"), + READY("ready"), + EXECUTING("executing"), + EXECUTED("executed"), + SKIPPED("skipped"), + TERMINATED("terminated") +} + +class Graph { + val nodes: MutableMap<String, Node> = hashMapOf() + val edges: MutableSet<Edge> = mutableSetOf() + + fun addNode(value: String): Node { + val node = Node(value) + nodes[value] = node + return node + } + + fun addEdge(source: String, destination: String, label: EdgeLabel) { + if (!nodes.containsKey(source)) { + addNode(source) + } + if (!nodes.containsKey(destination)) { + addNode(destination) + } + val edge = Edge(nodes[source]!!, nodes[destination]!!, label) + if (!edges.contains(edge)) { + edges.add(edge) + nodes[source]!!.edges.add(edge) + } + } + + override fun toString(): String { + val standaloneNodes = nodes.values.filter { node -> edges.all { it.source != node && it.target != node } } + val s = (edges.map { it.toString() } + standaloneNodes.map { it.toString() }).joinToString() + return "[$s]" + } + + fun print(): String { + val buffer = StringBuffer("Nodes :") + nodes.values.forEach { + buffer.append("\n\t$it") + } + buffer.append("\nEdges :") + edges.forEach { + buffer.append("\n\t$it") + } + return buffer.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other?.javaClass != javaClass) return false + other as Graph + return nodes == other.nodes && edges == other.edges + } + + override fun hashCode() = 31 * nodes.hashCode() + edges.hashCode() + + fun equivalentTo(other: Graph): Boolean { + return nodes == other.nodes && edges.all { edge -> other.edges.any { it.equivalentTo(edge) } } + } + + data class Node(val id: String, var status: NodeStatus = NodeStatus.NOT_STARTED) { + val edges: MutableList<Edge> = ArrayList() + + fun neighbors(): List<Node> = edges.map { edge -> edge.target(this) } + + fun neighbors(label: EdgeLabel): List<Node> = edges.filter { it.label == label } + .map { edge -> edge.target(this) } + + fun labelEdges(label: EdgeLabel): List<Edge> = edges.filter { it.label == label } + + override fun toString() = "$id, Status($status)" + } + + data class Edge( + val source: Node, + val target: Node, + val label: EdgeLabel, + var status: EdgeStatus = EdgeStatus.NOT_STARTED + ) { + + fun target(node: Node): Node = target + + fun equivalentTo(other: Edge) = + (source == other.source && target == other.target) || + (source == other.target && target == other.source) + + override fun toString() = + "${source.id}>${target.id}/$label($status)" + } + + data class TermForm(val nodes: Collection<String>, val edges: List<Term>) { + + data class Term(val source: String, val target: String, val label: EdgeLabel) { + override fun toString() = "Term($source, $target, $label)" + } + } + + data class AdjacencyList<String, out EdgeLabel>(val entries: List<Entry<String, EdgeLabel>>) { + constructor(vararg entries: Entry<String, EdgeLabel>) : this(entries.asList()) + + override fun toString() = "AdjacencyList(${entries.joinToString()})" + + data class Entry<out String, out EdgeLabel>(val node: String, val links: List<Link<String, EdgeLabel>> = emptyList<Nothing>()) { + constructor(node: String, vararg links: Link<String, EdgeLabel>) : this(node, links.asList()) + + override fun toString() = "Entry($node, links[${links.joinToString()}])" + } + + data class Link<out String, out EdgeLabel>(val node: String, val label: EdgeLabel) { + override fun toString() = if (label == null) "$node" else "$node/$label" + } + } + + companion object { + + fun labeledDirectedTerms(termForm: TermForm): Graph = + createFromTerms(termForm) { graph, n1, n2, value -> graph.addEdge(n1, n2, value) } + + fun labeledDirectedAdjacent(adjacencyList: AdjacencyList<String, EdgeLabel>): Graph = + fromAdjacencyList(adjacencyList) { graph, n1, n2, value -> + graph.addEdge(n1, n2, value) + } + + private fun createFromTerms( + termForm: TermForm, + addFunction: (Graph, String, String, EdgeLabel) -> Unit + ): Graph { + val graph = Graph() + termForm.nodes.forEach { graph.addNode(it) } + termForm.edges.forEach { addFunction(graph, it.source, it.target, it.label) } + return graph + } + + private fun fromAdjacencyList( + adjacencyList: AdjacencyList<String, EdgeLabel>, + addFunction: (Graph, String, String, EdgeLabel) -> Unit + ): Graph { + val graph = Graph() + adjacencyList.entries.forEach { graph.addNode(it.node) } + adjacencyList.entries.forEach { (node, links) -> + links.forEach { addFunction(graph, node, it.node, it.label) } + } + return graph + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt new file mode 100644 index 000000000..71a31dcca --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt @@ -0,0 +1,652 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * 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. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.controllerblueprints.core.data + +import com.fasterxml.jackson.annotation.JsonIgnore +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonPropertyOrder +import com.fasterxml.jackson.databind.JsonNode +import io.swagger.annotations.ApiModelProperty +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants + +/** + * + * + * @author Brinda Santh + */ +open class EntityType { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var version: String = "1.0.0" + var metadata: MutableMap<String, String>? = null + @get:JsonProperty("derived_from") + lateinit var derivedFrom: String + var attributes: MutableMap<String, AttributeDefinition>? = null + var properties: MutableMap<String, PropertyDefinition>? = null +} + +/* + 5.3.2 tosca.datatypes.Credential + The Credential type is a complex TOSCA data Type used when describing + authorization credentials used to access network accessible resources. + */ +class Credential { + + @get:JsonIgnore + var id: String? = null + var protocol: String? = null + @get:JsonProperty("token_type") + lateinit var tokenType: String + lateinit var token: String + var keys: MutableMap<String, String>? = null + lateinit var user: String +} + +/* +3.5.2 Constraint clause +A constraint clause defines an operation along with one or more compatible values that can be used to define a constraint on a property or parameter’s allowed values when it is defined in a TOSCA Service Template or one of its entities. + */ +class ConstraintClause { + + var equal: JsonNode? = null + @get:JsonProperty("greater_than") + var greaterThan: JsonNode? = null + @get:JsonProperty("greater_or_equal") + var greaterOrEqual: JsonNode? = null + @get:JsonProperty("less_than") + var lessThan: JsonNode? = null + @get:JsonProperty("less_or_equal") + var lessOrEqual: JsonNode? = null + @get:JsonProperty("in_range") + var inRange: MutableList<JsonNode>? = null + @get:JsonProperty("valid_values") + var validValues: MutableList<JsonNode>? = null + var length: JsonNode? = null + @get:JsonProperty("min_length") + var minLength: JsonNode? = null + @get:JsonProperty("max_length") + var maxLength: JsonNode? = null + var pattern: String? = null + var schema: String? = null +} + +/* +3.5.4 Node Filter definition +A node filter definition defines criteria for selection of a TOSCA Node Template based upon the template’s property values, capabilities and capability properties. + */ + +class NodeFilterDefinition { + var properties: MutableMap<String, PropertyDefinition>? = null + var capabilities: MutableList<String>? = null +} + +/* +3.5.5 Repository definition + A repository definition defines a named external repository which contains deployment + and implementation artifacts that are referenced within the TOSCA Service Template. +*/ +class RepositoryDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + lateinit var url: String + var credential: Credential? = null +} + +/* +3.5.6 Artifact definition +An artifact definition defines a named, typed file that can be associated with Node Type +or Node Template and used by orchestration engine to facilitate deployment and implementation of interface operations. + */ +class ArtifactDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + lateinit var file: String + var repository: String? = null + var description: String? = null + @get:JsonProperty("deploy_Path") + var deployPath: String? = null + var properties: MutableMap<String, JsonNode>? = null +} + +/* +3.5.7 Import definition +An import definition is used within a TOSCA Service Template to locate and uniquely name +another TOSCA Service Template file which has type and template definitions to be imported (included) +and referenced within another Service Template. + */ +class ImportDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var file: String + var repository: String? = null + @get:JsonProperty("namespace_uri") + var namespaceUri: String? = null + @get:JsonProperty("namespace_prefix") + var namespacePrefix: String? = null +} + +/* +3.5.8 Property definition A property definition defines a named, typed value and related data that can be associated with an +entity defined in this specification (e.g., Node Types, Relationship Types, Capability Types, etc.). +Properties are used by template authors to provide input values to TOSCA entities which indicate their “desired state” when they are +instantiated. The value of a property can be retrieved using the get_property function within TOSCA Service Templates. + */ +class PropertyDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var required: Boolean? = null + lateinit var type: String + @get:JsonProperty("default") + var defaultValue: JsonNode? = null + var status: String? = null + var constraints: MutableList<ConstraintClause>? = null + @get:JsonProperty("entry_schema") + var entrySchema: EntrySchema? = null + @get:JsonProperty("external-schema") + var externalSchema: String? = null + var metadata: MutableMap<String, String>? = null + // Mainly used in Workflow Outputs + @get:ApiModelProperty(notes = "Property Value, It may be Expression or Json type values") + var value: JsonNode? = null +} + +/* +3.5.10 Attribute definition + +An attribute definition defines a named, typed value that can be associated with an entity defined in this +specification (e.g., a Node, Relationship or Capability Type). Specifically, it is used to expose the +“actual state” of some property of a TOSCA entity after it has been deployed and instantiated +(as set by the TOSCA orchestrator). Attribute values can be retrieved via the get_attribute function +from the instance model and used as values to other entities within TOSCA Service Templates. + */ + +class AttributeDefinition { + @get:JsonIgnore + var id: String? = null + var description: String? = null + var required: Boolean? = null + lateinit var type: String + @JsonProperty("default") + var defaultValue: JsonNode? = null + var status: String? = null + var constraints: MutableList<ConstraintClause>? = null + @JsonProperty("entry_schema") + var entrySchema: EntrySchema? = null + // Mainly used in DSL definitions + @get:ApiModelProperty(notes = "Attribute Value, It may be Expression or Json type values") + var value: JsonNode? = null +} + +/* +3.5.13 Operation definition +An operation definition defines a named function or procedure that can be bound to an implementation artifact (e.g., a script). + */ +class OperationDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var implementation: Implementation? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null +} + +class Implementation { + var primary: String? = null + var dependencies: MutableList<String>? = null + @get:JsonProperty("operation_host") + var operationHost: String = BluePrintConstants.PROPERTY_SELF + // Timeout value in seconds + var timeout: Int = 180 +} + +/* +3.5.14 Interface definition +An interface definition defines a named interface that can be associated with a Node or Relationship Type + */ +class InterfaceDefinition { + + @get:JsonIgnore + var id: String? = null + var type: String? = null + var operations: MutableMap<String, OperationDefinition>? = null + var inputs: MutableMap<String, PropertyDefinition>? = null +} + +/* +3.5.15 Event Filter definition +An event filter definition defines criteria for selection of an attribute, for the purpose of monitoring it, within a TOSCA entity, or one its capabilities. + */ +class EventFilterDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var node: String + var requirement: String? = null + var capability: String? = null +} + +/* +3.5.16 Trigger definition TODO +A trigger definition defines the event, condition and action that is used to “trigger” a policy it is associated with. + */ +class TriggerDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + @get:JsonProperty("event_type") + lateinit var eventType: String + @get:JsonProperty("target_filter") + var targetFilter: EventFilterDefinition? = null + var condition: ConditionClause? = null + var constraint: ConditionClause? = null + var method: String? = null + lateinit var action: String +} + +/* + 3.5.17 Workflow activity definition + A workflow activity defines an operation to be performed in a TOSCA workflow. Activities allows to: + · Delegate the workflow for a node expected to be provided by the orchestrator + · Set the state of a node + · Call an operation defined on a TOSCA interface of a node, relationship or group + · Inline another workflow defined in the topology (to allow reusability) + */ +class Activity { + + var delegate: String? = null + @get:JsonProperty("set_state") + var setState: String? = null + @get:JsonProperty("call_operation") + var callOperation: String? = null + var inlines: ArrayList<String>? = null +} + +/* +3.5.20 Workflow precondition definition +A workflow condition can be used as a filter or precondition to check if a workflow can be processed or not based on the state of the instances of a TOSCA topology deployment. When not met, the workflow will not be triggered. + */ +class PreConditionDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var target: String + @get:JsonProperty("target_relationship") + lateinit var targetRelationship: String + lateinit var condition: ArrayList<ConditionClause> +} + +/* +3.5.21 Workflow step definition +A workflow step allows to define one or multiple sequenced activities in a workflow and how they are connected to other steps in the workflow. They are the building blocks of a declarative workflow. + */ +class Step { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var target: String? = null + @JsonProperty("target_relationship") + var targetRelationship: String? = null + @JsonProperty("operation_host") + var operationHost: String? = null + var activities: ArrayList<Activity>? = null + @get:JsonProperty("on_success") + var onSuccess: ArrayList<String>? = null + @get:JsonProperty("on_failure") + var onFailure: ArrayList<String>? = null +} + +/* +3.6.2 Capability definition +A capability definition defines a named, typed set of data that can be associated with Node Type or Node Template to describe a transparent capability or feature of the software component the node describes. + */ + +class CapabilityDefinition { + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var properties: MutableMap<String, PropertyDefinition>? = null + @get:JsonProperty("valid_source_types") + var validSourceTypes: MutableList<String>? = null + var occurrences: MutableList<Any>? = null +} + +/* +3.6.3 Requirement definition +The Requirement definition describes a named requirement (dependencies) of a TOSCA Node Type or Node template which needs to be fulfilled by a matching Capability definition declared by another TOSCA modelable entity. The requirement definition may itself include the specific name of the fulfilling entity (explicitly) or provide an abstract type, along with additional filtering characteristics, that a TOSCA orchestrator can use to fulfill the capability at runtime (implicitly). + */ +class RequirementDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var capability: String? = null + var node: String? = null + var relationship: String? = null + var occurrences: MutableList<Any>? = null +} + +/* +3.6.4 Artifact Type +An Artifact Type is a reusable entity that defines the type of one or more files that are used to define implementation or deployment artifacts that are referenced by nodes or relationships on their operations. + */ +class ArtifactType : EntityType() { + + @get:JsonProperty("mime_type") + var mimeType: String? = null + @get:JsonProperty("file_ext") + var fileExt: MutableList<String>? = null +} + +/* +3.6.6 Data Type +A Data Type definition defines the schema for new named datatypes in TOSCA. + */ + +class DataType : EntityType() { + var constraints: MutableList<ConstraintClause>? = null +} + +/* +3.6.9 Node Type +A Node Type is a reusable entity that defines the type of one or more Node Templates. As such, a Node Type defines the structure of observable properties via a Properties Definition, the Requirements and Capabilities of the node as well as its supported interfaces. + + */ + +class NodeType : EntityType() { + var capabilities: MutableMap<String, CapabilityDefinition>? = null + var requirements: MutableMap<String, RequirementDefinition>? = null + var interfaces: MutableMap<String, InterfaceDefinition>? = null + var artifacts: MutableMap<String, ArtifactDefinition>? = null +} + +/* +3.6.8 Requirement Type +A Requirement Type is a reusable entity that describes a kind of requirement that a Node Type can declare to expose. +The TOSCA Simple Profile seeks to simplify the need for declaring specific Requirement Types +from nodes and instead rely upon nodes declaring their features sets using TOSCA Capability Types +along with a named Feature notation. + */ + +class RequirementType : EntityType() { + var requirements: MutableMap<String, RequirementDefinition>? = null + var capabilities: MutableMap<String, CapabilityDefinition>? = null + var interfaces: MutableMap<String, InterfaceDefinition>? = null + var artifacts: MutableMap<String, ArtifactDefinition>? = null +} + +/* +3.6.10 Relationship Type +A Relationship Type is a reusable entity that defines the type of one or more relationships between Node Types or Node Templates. +*/ + +class RelationshipType : EntityType() { + var interfaces: MutableMap<String, InterfaceDefinition>? = null + @get:JsonProperty("valid_target_types") + var validTargetTypes: MutableList<String>? = null +} + +/* +3.6.11 Group Type +A Group Type defines logical grouping types for nodes, typically for different management purposes. +Groups can effectively be viewed as logical nodes that are not part of the physical deployment topology + of an application, yet can have capabilities and the ability to attach policies and interfaces + that can be applied (depending on the group type) to its member nodes. + */ + +class GroupType : EntityType() { + var members: MutableList<String>? = null + var requirements: ArrayList<RequirementDefinition>? = null + var capabilities: MutableMap<String, CapabilityDefinition>? = null + var interfaces: MutableMap<String, InterfaceDefinition>? = null +} + +/* + 3.6.12 Policy Type + A Policy Type defines a type of requirement that affects or governs an application or service’s + topology at some stage of its lifecycle, but is not explicitly part of the topology itself + (i.e., it does not prevent the application or service from being deployed or run if it did not exist). + */ +class PolicyType : EntityType() { + + lateinit var targets: MutableList<String> +} + +/* +3.7.1 Capability assignment +A capability assignment allows node template authors to assign values to properties and attributes for a named capability definition that is part of a Node Template’s type definition. + */ +class CapabilityAssignment { + + @get:JsonIgnore + var id: String? = null + var attributes: MutableMap<String, JsonNode>? = null + var properties: MutableMap<String, JsonNode>? = null +} + +/* +3.7.4 Relationship Template +A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations. + */ +class GroupDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var metadata: MutableMap<String, String>? = null + var properties: MutableMap<String, JsonNode>? = null + var members = ArrayList<String>() + var interfaces: MutableMap<String, InterfaceDefinition>? = null +} + +/* +3.7.6 Policy definition +A policy definition defines a policy that can be associated with a TOSCA topology or top-level entity definition (e.g., group definition, node template, etc.). + */ +class PolicyDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var metadata: MutableMap<String, String>? = null + var properties: MutableMap<String, JsonNode>? = null + var targets: MutableList<String>? = null +} + +/* +3.8 Topology Template definition +This section defines the topology template of a cloud application. The main ingredients of the topology template are node templates representing components of the application and relationship templates representing links between the components. These elements are defined in the nested node_templates section and the nested relationship_templates sections, respectively. Furthermore, a topology template allows for defining input parameters, output parameters as well as grouping of node templates. + */ +class TopologyTemplate { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + @get:JsonProperty("node_templates") + var nodeTemplates: MutableMap<String, NodeTemplate>? = null + @get:JsonProperty("relationship_templates") + var relationshipTemplates: MutableMap<String, RelationshipTemplate>? = null + var policies: MutableMap<String, PolicyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null + @get:JsonProperty("substitution_mappings") + var substitutionMappings: Any? = null + var workflows: MutableMap<String, Workflow>? = null +} + +class SubstitutionMapping { + @get:JsonProperty("node_type") + lateinit var nodeType: String + lateinit var capabilities: ArrayList<String> + lateinit var requirements: ArrayList<String> +} + +class EntrySchema { + lateinit var type: String + var constraints: MutableList<ConstraintClause>? = null +} + +class InterfaceAssignment { + @get:JsonIgnore + var id: String? = null + var operations: MutableMap<String, OperationAssignment>? = null + var inputs: MutableMap<String, JsonNode>? = null +} + +/* +3.7.3 Node Template +A Node Template specifies the occurrence of a manageable software component as part of an application’s topology model which is defined in a TOSCA Service Template. A Node template is an instance of a specified Node Type and can provide customized properties, constraints or operations which override the defaults provided by its Node Type and its implementations. + */ + +open class NodeTemplate { + @get:JsonIgnore + var id: String? = null + var description: String? = null + lateinit var type: String + var metadata: MutableMap<String, String>? = null + var directives: MutableList<String>? = null + // @get:JsonSerialize(using = PropertyDefinitionValueSerializer::class) + var properties: MutableMap<String, JsonNode>? = null + var attributes: MutableMap<String, JsonNode>? = null + var capabilities: MutableMap<String, CapabilityAssignment>? = null + var requirements: MutableMap<String, RequirementAssignment>? = null + var interfaces: MutableMap<String, InterfaceAssignment>? = null + var artifacts: MutableMap<String, ArtifactDefinition>? = null + @get:JsonProperty("node_filter") + var nodeFilter: NodeFilterDefinition? = null + var copy: String? = null +} + +class OperationAssignment { + @get:JsonIgnore + var id: String? = null + var description: String? = null + var implementation: Implementation? = null + var inputs: MutableMap<String, JsonNode>? = null + var outputs: MutableMap<String, JsonNode>? = null +} + +/* +3.7.4 Relationship Template +A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations. + */ + +class RelationshipTemplate { + var type: String? = null + var description: String? = null + var metadata: MutableMap<String, String>? = null + var properties: MutableMap<String, PropertyDefinition>? = null + var attributes: MutableMap<String, JsonNode>? = null + var interfaces: MutableMap<String, InterfaceDefinition>? = null + var copy: String? = null +} + +/* +3.7.2 Requirement assignment +A Requirement assignment allows template authors to provide either concrete names of TOSCA templates or provide abstract selection criteria for providers to use to find matching TOSCA templates that are used to fulfill a named requirement’s declared TOSCA Node Type. + */ + +class RequirementAssignment { + @get:JsonIgnore + var id: String? = null + var capability: String? = null + var node: String? = null + // Relationship Type or Relationship Template + var relationship: String? = null +} + +class Workflow { + @get:JsonIgnore + var id: String? = null + var description: String? = null + var steps: MutableMap<String, Step>? = null + var preconditions: ArrayList<PreConditionDefinition>? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null +} + +class ConditionClause { + var and: ArrayList<MutableMap<String, Any>>? = null + var or: ArrayList<MutableMap<String, Any>>? = null + @get:JsonProperty("assert") + var assertConditions: ArrayList<MutableMap<String, Any>>? = null +} + +/* +3.9 Service Template definition +A TOSCA Service Template (YAML) document contains element definitions of building blocks for cloud application, or complete models of cloud applications. This section describes the top-level structural elements (TOSCA keynames) along with their grammars, which are allowed to appear in a TOSCA Service Template document. + */ + +@JsonPropertyOrder( + value = ["toscaDefinitionsVersion", "description", "metadata", "imports", "dsl_definitions", + "topologyTemplate"] +) +class ServiceTemplate : Cloneable { + + @get:JsonIgnore + var id: String? = null + @get:JsonProperty("tosca_definitions_version") + var toscaDefinitionsVersion: String = "controller_blueprint_1_0_0" + var metadata: MutableMap<String, String>? = null + var description: String? = null + @get:JsonProperty("dsl_definitions") + var dslDefinitions: MutableMap<String, JsonNode>? = null + var repositories: MutableMap<String, RepositoryDefinition>? = null + var imports: MutableList<ImportDefinition>? = null + @get:JsonProperty("artifact_types") + var artifactTypes: MutableMap<String, ArtifactType>? = null + @get:JsonProperty("data_types") + var dataTypes: MutableMap<String, DataType>? = null + @get:JsonProperty("relationship_types") + var relationshipTypes: MutableMap<String, RelationshipType>? = null + @get:JsonProperty("node_types") + var nodeTypes: MutableMap<String, NodeType>? = null + @get:JsonProperty("policy_types") + var policyTypes: MutableMap<String, PolicyType>? = null + @get:JsonProperty("topology_template") + var topologyTemplate: TopologyTemplate? = null + + public override fun clone(): ServiceTemplate { + return super.clone() as ServiceTemplate + } +} + +class ToscaMetaData { + lateinit var toscaMetaFileVersion: String + lateinit var csarVersion: String + lateinit var createdBy: String + lateinit var entityDefinitions: String + var templateName: String? = null + var templateVersion: String? = null + var templateTags: String? = null +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt new file mode 100644 index 000000000..8bdedd429 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt @@ -0,0 +1,103 @@ +/* + * Copyright © 2018-2019 Bell Canada Intellectual Property. + * + * 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.controllerblueprints.core.data + +import java.util.HashMap + +/** + * ErrorCode.java Purpose: Maintain a list of HTTP status codes + * + * @author Steve Siani + * @version 1.0 + */ +enum class ErrorCode(val value: Int, val httpCode: Int) { + + // / TODO: Add more attribute for each needed application protocol + // TODO: Example: INVALID_FILE_EXTENSION(2, 415, 25) + GENERIC_FAILURE(1, 500) { + + override fun message(detailMsg: String): String { + return "Generic failure. Details : {$detailMsg}" + } + }, + INVALID_FILE_EXTENSION(2, 415) { + override fun message(detailMsg: String): String { + return "Unexpected file extension. Details : {$detailMsg}" + } + }, + BLUEPRINT_PATH_MISSING(3, 503) { + override fun message(detailMsg: String): String { + return "Blueprint path missing or wrong. Details : {$detailMsg}" + } + }, + BLUEPRINT_WRITING_FAIL(4, 503) { + override fun message(detailMsg: String): String { + return "Fail to write blueprint files. Details : {$detailMsg}" + } + }, + IO_FILE_INTERRUPT(5, 503) { + override fun message(detailMsg: String): String { + return "IO file system interruption. Details : {$detailMsg}" + } + }, + INVALID_REQUEST_FORMAT(6, 400) { + override fun message(detailMsg: String): String { + return "Bad request. Details : {$detailMsg}" + } + }, + UNAUTHORIZED_REQUEST(7, 401) { + override fun message(detailMsg: String): String { + return "The request requires user authentication. Details : {$detailMsg}" + } + }, + REQUEST_NOT_FOUND(8, 404) { + override fun message(detailMsg: String): String { + return "Request mapping doesn't exist. Details : {$detailMsg}" + } + }, + RESOURCE_NOT_FOUND(9, 404) { + override fun message(detailMsg: String): String { + return "No response was found for this request in the server. Details : {$detailMsg}" + } + }, + CONFLICT_ADDING_RESOURCE(10, 409) { + override fun message(detailMsg: String): String { + return "Duplicated entry while saving Blueprint. Details : {$detailMsg}" + } + }, + DUPLICATE_DATA(11, 409) { + override fun message(detailMsg: String): String { + return "Duplicated data - was expecting one result, got more than one. Details : {$detailMsg}" + } + }; + + abstract fun message(detailMsg: String): String + + companion object { + + private val map = HashMap<Int, ErrorCode>() + + init { + for (errorCode in ErrorCode.values()) { + map[errorCode.value] = errorCode + } + } + + fun valueOf(value: Int): ErrorCode? { + return if (map.containsKey(value)) map[value] else map[1] + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.kt new file mode 100644 index 000000000..13e9f0e5a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.kt @@ -0,0 +1,41 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +abstract class AbstractNodeTemplateOperationImplBuilder<Prop : PropertiesAssignmentBuilder, + In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder>( + id: String, + type: String, + private val interfaceName: String, + description: String + ) : AbstractNodeTemplatePropertyImplBuilder<Prop>(id, type, description) { + + open fun definedOperation(description: String, block: OperationAssignmentBuilder<In, Out>.() -> Unit) { + typedOperation<In, Out>(interfaceName, description, block) + } +} + +abstract class AbstractNodeTemplatePropertyImplBuilder<Prop : PropertiesAssignmentBuilder>( + id: String, + type: String, + description: String +) : NodeTemplateBuilder(id, type, description) { + + open fun definedProperties(block: Prop.() -> Unit) { + typedProperties<Prop>(block) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt new file mode 100644 index 000000000..9964687a6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt @@ -0,0 +1,313 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType + +// CDS DSLs +fun blueprint( + name: String, + version: String, + author: String, + tags: String, + block: DSLBluePrintBuilder.() -> Unit +): DSLBluePrint { + return DSLBluePrintBuilder(name, version, author, tags).apply(block).build() +} + +// TOSCA DSLs +fun serviceTemplate( + name: String, + version: String, + author: String, + tags: String, + block: BluePrintServiceDSLBuilder.() -> Unit +): ServiceTemplate { + return BluePrintServiceDSLBuilder(name, version, author, tags).apply(block).build() +} + +fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit): Workflow { + return WorkflowBuilder(id, description).apply(block).build() +} + +fun nodeTemplate( + id: String, + type: String, + description: String, + block: NodeTemplateBuilder.() -> Unit +): NodeTemplate { + return NodeTemplateBuilder(id, type, description).apply(block).build() +} + +fun nodeType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: NodeTypeBuilder.() -> Unit +): NodeType { + return NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +fun dataType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: DataTypeBuilder.() -> Unit +): DataType { + return DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +fun artifactType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: ArtifactTypeBuilder.() -> Unit +): ArtifactType { + return ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +fun relationshipType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: RelationshipTypeBuilder.() -> Unit +): RelationshipType { + return RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +// DSL Function +fun dslExpression(key: String): JsonNode { + return ("*$key").asJsonPrimitive() +} +// Input Function + +fun getInput(inputKey: String, jsonPath: String? = null): JsonNode { + return """{"get_input": "$inputKey"}""".jsonAsJsonType() +} + +fun getAttribute(attributeId: String, jsonPath: String? = null): JsonNode { + return getNodeTemplateAttribute("SELF", attributeId, jsonPath) +} + +fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String): JsonNode { + return getNodeTemplateAttribute(nodeTemplateId, attributeId, null) +} + +fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String, jsonPath: String?): JsonNode { + return if (jsonPath.isNullOrEmpty() || jsonPath.isNullOrBlank()) { + """{"get_attribute": ["$nodeTemplateId", "$attributeId"]}""".jsonAsJsonType() + } else { + """{"get_attribute": ["$nodeTemplateId", "$attributeId", "$jsonPath"]}""".jsonAsJsonType() + } +} + +// Property Function + +fun getProperty(propertyId: String, jsonPath: String? = null): JsonNode { + return getNodeTemplateProperty("SELF", propertyId, jsonPath) +} + +fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String): JsonNode { + return getNodeTemplateProperty(nodeTemplateName, propertyId, null) +} + +fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String, jsonPath: String?): JsonNode { + return if (jsonPath.isNullOrEmpty() || jsonPath.isNullOrBlank()) { + """{"get_property": ["$nodeTemplateName", "$propertyId"]}""".jsonAsJsonType() + } else { + """{"get_property": ["$nodeTemplateName", "$propertyId", "$jsonPath"]}""".jsonAsJsonType() + } +} + +// Artifact Function + +fun getArtifact(artifactId: String): JsonNode { + return getNodeTemplateArtifact("SELF", artifactId) +} + +fun getNodeTemplateArtifact(nodeTemplateName: String, artifactId: String): JsonNode { + return """{"get_artifact": ["$nodeTemplateName", "$artifactId"]}""".jsonAsJsonType() +} + +// Operation Function + +fun getNodeTemplateOperationOutput( + nodeTemplateName: String, + interfaceName: String, + propertyId: String, + jsonPath: String? = null +): JsonNode { + return """{"get_operation_output": ["$nodeTemplateName", "$interfaceName", "process","$propertyId","$jsonPath" ]}""".trimMargin().jsonAsJsonType() +} + +/** Blueprint Type Extensions */ + +fun BluePrintTypes.nodeTypeComponent(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default Component Node" + ) { + } +} + +fun BluePrintTypes.nodeTypeWorkflow(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default Workflow Node" + ) { + } +} + +fun BluePrintTypes.nodeTypeVnf(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_VNF, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default VNF Node" + ) { + } +} + +fun BluePrintTypes.nodeTypeResourceSource(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default Resource Source Node" + ) { + } +} + +/** Artifacts */ + +fun BluePrintTypes.artifactTypeTemplateVelocity(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Velocity Artifact" + ) { + fileExt("vtl") + } +} + +fun BluePrintTypes.artifactTypeTempleJinja(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Jinja Artifact" + ) { + fileExt("jinja") + } +} + +fun BluePrintTypes.artifactTypeMappingResource(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Mapping Resource Artifact" + ) { + fileExt("json") + } +} + +fun BluePrintTypes.artifactTypeScriptJython(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Jython Script Artifact" + ) { + fileExt("py") + } +} + +fun BluePrintTypes.artifactTypeScriptKotlin(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Kotlin Script Artifact" + ) { + fileExt("kts") + } +} + +fun BluePrintTypes.artifactTypeDirectedGraph(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Directed Graph Artifact" + ) { + fileExt("xml", "json") + } +} + +fun BluePrintTypes.artifactTypeComponentJar(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_COMPONENT_JAR, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Component Artifact" + ) { + fileExt("jar") + } +} + +/** Relationship Types */ + +fun BluePrintTypes.relationshipTypeConnectsTo(): RelationshipType { + return relationshipType( + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + description = "Relationship connects to" + ) { + } +} + +fun BluePrintTypes.relationshipTypeDependsOn(): RelationshipType { + return relationshipType( + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + description = "Relationship depends on" + ) { + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt new file mode 100644 index 000000000..f2e964a1d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt @@ -0,0 +1,477 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step + +/** + * @author Brinda Santh + */ +class DSLBluePrintBuilder( + private val name: String, + private val version: String, + private val author: String, + private val tags: String +) { + + private var dslBluePrint = DSLBluePrint() + private var metadata: MutableMap<String, String> = hashMapOf() + var properties: MutableMap<String, JsonNode>? = null + var dataTypes: MutableMap<String, DataType> = hashMapOf() + var artifactTypes: MutableMap<String, ArtifactType> = hashMapOf() + var components: MutableMap<String, DSLComponent> = hashMapOf() + private var registryComponents: MutableMap<String, DSLRegistryComponent> = hashMapOf() + var workflows: MutableMap<String, DSLWorkflow> = hashMapOf() + + private fun initMetaData() { + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = name + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = version + metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] = author + metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] = tags + } + + fun metadata(id: String, value: String) { + metadata[id] = value + } + + fun property(id: String, expression: Any) { + if (properties == null) + properties = hashMapOf() + properties!![id] = expression.asJsonType() + } + + fun dataType(dataType: DataType) { + dataTypes[dataType.id!!] = dataType + } + + fun dataType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: DataTypeBuilder.() -> Unit + ) { + dataTypes[id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun artifactType(artifactType: ArtifactType) { + artifactTypes[artifactType.id!!] = artifactType + } + + fun artifactType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: ArtifactTypeBuilder.() -> Unit + ) { + artifactTypes[id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun component( + id: String, + type: String, + version: String, + description: String, + block: DSLComponentBuilder.() -> Unit + ) { + components[id] = DSLComponentBuilder(id, type, version, description).apply(block).build() + } + + fun registryComponent( + id: String, + type: String, + version: String, + interfaceName: String, + description: String, + block: DSLRegistryComponentBuilder.() -> Unit + ) { + registryComponents[id] = DSLRegistryComponentBuilder(id, type, version, interfaceName, description) + .apply(block).build() + } + + fun workflow(id: String, description: String, block: DSLWorkflowBuilder.() -> Unit) { + workflows[id] = DSLWorkflowBuilder(id, description).apply(block).build() + } + + fun build(): DSLBluePrint { + initMetaData() + dslBluePrint.metadata = metadata + dslBluePrint.properties = properties + dslBluePrint.dataTypes = dataTypes + dslBluePrint.artifactTypes = artifactTypes + dslBluePrint.components = components + dslBluePrint.registryComponents = registryComponents + dslBluePrint.workflows = workflows + return dslBluePrint + } +} + +class DSLComponentBuilder( + private val id: String, + private val type: String, + private val version: String, + private val description: String +) { + + private val dslComponent = DSLComponent() + var properties: MutableMap<String, PropertyDefinition>? = null + var attributes: MutableMap<String, AttributeDefinition>? = null + + var artifacts: MutableMap<String, ArtifactDefinition>? = null + var implementation: Implementation? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null + + fun attribute(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (attributes == null) + attributes = hashMapOf() + val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description).build() + attributes!![id] = attribute + } + + fun attribute( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLAttributeDefinitionBuilder.() -> Unit + ) { + if (attributes == null) + attributes = hashMapOf() + val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + attributes!![id] = attribute + } + + fun property(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (properties == null) + properties = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description).build() + properties!![id] = property + } + + fun property( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (properties == null) + properties = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + properties!![id] = property + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() + } + + fun input(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (inputs == null) + inputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + inputs!![id] = property.build() + } + + fun input( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (inputs == null) + inputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + inputs!![id] = property + } + + fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + outputs!![id] = property.build() + } + + fun output( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + outputs!![id] = property + } + + fun build(): DSLComponent { + dslComponent.id = id + dslComponent.type = type + dslComponent.version = version + dslComponent.description = description + dslComponent.attributes = attributes + dslComponent.properties = properties + dslComponent.implementation = implementation + dslComponent.artifacts = artifacts + dslComponent.inputs = inputs + dslComponent.outputs = outputs + + return dslComponent + } +} + +class DSLRegistryComponentBuilder( + private val id: String, + private val type: String, + private val version: String, + private val interfaceName: String, + private val description: String +) { + + private val dslComponent = DSLRegistryComponent() + var properties: MutableMap<String, JsonNode>? = null + + var artifacts: MutableMap<String, ArtifactDefinition>? = null + var implementation: Implementation? = null + var inputs: MutableMap<String, JsonNode>? = null + var outputs: MutableMap<String, JsonNode>? = null + + fun property(id: String, expression: Any) { + if (properties == null) + properties = hashMapOf() + properties!![id] = expression.asJsonType() + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() + } + + fun input(id: String, expression: Any) { + if (inputs == null) + inputs = hashMapOf() + inputs!![id] = expression.asJsonType() + } + + fun output(id: String, expression: Any) { + if (outputs == null) + outputs = hashMapOf() + outputs!![id] = expression.asJsonType() + } + + fun build(): DSLRegistryComponent { + dslComponent.id = id + dslComponent.type = type + dslComponent.version = version + dslComponent.interfaceName = interfaceName + dslComponent.description = description + dslComponent.properties = properties + dslComponent.implementation = implementation + dslComponent.artifacts = artifacts + dslComponent.inputs = inputs + dslComponent.outputs = outputs + return dslComponent + } +} + +class DSLWorkflowBuilder(private val actionName: String, private val description: String) { + private val dslWorkflow = DSLWorkflow() + private var steps: MutableMap<String, Step>? = null + private var inputs: MutableMap<String, PropertyDefinition>? = null + private var outputs: MutableMap<String, PropertyDefinition>? = null + + fun input(id: String, type: String, required: Boolean, description: String? = "") { + if (inputs == null) + inputs = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description) + inputs!![id] = property.build() + } + + fun input( + id: String, + type: String, + required: Boolean, + description: String, + defaultValue: Any?, + block: PropertyDefinitionBuilder.() -> Unit + ) { + if (inputs == null) + inputs = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() + if (defaultValue != null) + property.defaultValue = defaultValue.asJsonType() + inputs!![id] = property + } + + fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + outputs!![id] = property.build() + } + + fun output( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + outputs!![id] = property + } + + fun step(id: String, target: String, description: String) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).build() + } + + fun step(id: String, target: String, description: String, block: StepBuilder.() -> Unit) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).apply(block).build() + } + + fun build(): DSLWorkflow { + dslWorkflow.actionName = actionName + dslWorkflow.description = description + dslWorkflow.inputs = inputs + dslWorkflow.outputs = outputs + dslWorkflow.steps = steps!! + return dslWorkflow + } +} + +class DSLAttributeDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val expression: JsonNode, + private val description: String? = "" +) { + + private var attributeDefinition = AttributeDefinition() + + fun entrySchema(entrySchemaType: String) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + // TODO("Constrains") + + fun defaultValue(defaultValue: JsonNode) { + attributeDefinition.defaultValue = defaultValue + } + + fun build(): AttributeDefinition { + attributeDefinition.id = id + attributeDefinition.type = type!! + attributeDefinition.required = required + attributeDefinition.value = expression + attributeDefinition.description = description + return attributeDefinition + } +} + +class DSLPropertyDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val expression: JsonNode, + private val description: String? = "" +) { + + private var propertyDefinition: PropertyDefinition = PropertyDefinition() + + fun entrySchema(entrySchemaType: String) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + // TODO("Constrains") + + fun defaultValue(defaultValue: JsonNode) { + propertyDefinition.defaultValue = defaultValue + } + + fun build(): PropertyDefinition { + propertyDefinition.id = id + propertyDefinition.type = type!! + propertyDefinition.required = required + propertyDefinition.value = expression + propertyDefinition.description = description + return propertyDefinition + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt new file mode 100644 index 000000000..8b5c4151a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt @@ -0,0 +1,80 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.annotation.JsonIgnore +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step + +/** + * This is simplified version of DSL, which is used for generating the Service template + * @author Brinda Santh + */ + +class DSLBluePrint { + + var metadata: MutableMap<String, String> = hashMapOf() + var properties: MutableMap<String, JsonNode>? = null + var dataTypes: MutableMap<String, DataType> = hashMapOf() + var artifactTypes: MutableMap<String, ArtifactType> = hashMapOf() + var components: MutableMap<String, DSLComponent> = hashMapOf() + var registryComponents: MutableMap<String, DSLRegistryComponent> = hashMapOf() + var workflows: MutableMap<String, DSLWorkflow> = hashMapOf() +} + +class DSLWorkflow { + @get:JsonIgnore + var id: String? = null + lateinit var description: String + lateinit var actionName: String + lateinit var steps: MutableMap<String, Step> + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null +} + +class DSLComponent { + @get:JsonIgnore + lateinit var id: String + lateinit var type: String + lateinit var version: String + lateinit var description: String + var implementation: Implementation? = null + var attributes: MutableMap<String, AttributeDefinition>? = null + var properties: MutableMap<String, PropertyDefinition>? = null + var artifacts: MutableMap<String, ArtifactDefinition>? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null +} + +class DSLRegistryComponent { + lateinit var id: String + lateinit var type: String + lateinit var version: String + lateinit var interfaceName: String + lateinit var description: String + var implementation: Implementation? = null + var properties: MutableMap<String, JsonNode>? = null + var artifacts: MutableMap<String, ArtifactDefinition>? = null + var inputs: MutableMap<String, JsonNode>? = null + var outputs: MutableMap<String, JsonNode>? = null +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt new file mode 100644 index 000000000..ca4d56338 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt @@ -0,0 +1,232 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asBluePrintsDataTypes +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import kotlin.reflect.KClass + +class BluePrintServiceDSLBuilder( + private val name: String, + private val version: String, + private val author: String, + private val tags: String +) { + + private var serviceTemplate = ServiceTemplate() + private var topologyTemplate: TopologyTemplate? = null + private var metadata: MutableMap<String, String> = hashMapOf() + private var dslDefinitions: MutableMap<String, JsonNode>? = null + private var imports: MutableList<ImportDefinition> = mutableListOf() + private var nodeTypes: MutableMap<String, NodeType>? = null + private var artifactTypes: MutableMap<String, ArtifactType>? = null + private var dataTypes: MutableMap<String, DataType>? = null + private var relationshipTypes: MutableMap<String, RelationshipType>? = null + private var policyTypes: MutableMap<String, PolicyType>? = null + + private fun initMetaData() { + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = name + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = version + metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] = author + metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] = tags + } + + fun metadata(id: String, value: String) { + metadata[id] = value + } + + fun import(file: String) { + val importDefinition = ImportDefinition().apply { + this.file = file + } + imports.add(importDefinition) + } + + fun dsl(id: String, kclass: KClass<*>) { + dsl(id, kclass.asPropertyDefinitionMap().asJsonNode()) + } + + fun dataType(dataType: KClass<*>) { + dataType(dataType.asBluePrintsDataTypes()) + } + + fun dsl(id: String, content: Any) { + dsl(id, content.asJsonType()) + } + + fun dsl(id: String, json: JsonNode) { + if (dslDefinitions == null) + dslDefinitions = hashMapOf() + dslDefinitions!![id] = json + } + + fun dataTypes(dataTypes: MutableMap<String, DataType>) { + if (this.dataTypes == null) + this.dataTypes = hashMapOf() + + this.dataTypes!!.putAll(dataTypes) + } + + fun artifactTypes(artifactTypes: MutableMap<String, ArtifactType>) { + if (this.artifactTypes == null) + this.artifactTypes = hashMapOf() + + this.artifactTypes!!.putAll(artifactTypes) + } + + fun relationshipTypes(relationshipTypes: MutableMap<String, RelationshipType>) { + if (this.relationshipTypes == null) + this.relationshipTypes = hashMapOf() + + this.relationshipTypes!!.putAll(relationshipTypes) + } + + fun policyTypes(policyTypes: MutableMap<String, PolicyType>) { + if (this.policyTypes == null) + this.policyTypes = hashMapOf() + + this.policyTypes!!.putAll(policyTypes) + } + + fun nodeType(nodeTypes: MutableMap<String, NodeType>) { + if (this.nodeTypes == null) + this.nodeTypes = hashMapOf() + + this.nodeTypes!!.putAll(nodeTypes) + } + + fun dataType(dataType: DataType) { + if (dataTypes == null) + dataTypes = hashMapOf() + dataTypes!![dataType.id!!] = dataType + } + + fun artifactType(artifactType: ArtifactType) { + if (artifactTypes == null) + artifactTypes = hashMapOf() + artifactTypes!![artifactType.id!!] = artifactType + } + + fun relationshipType(relationshipType: RelationshipType) { + if (relationshipTypes == null) + relationshipTypes = hashMapOf() + relationshipTypes!![relationshipType.id!!] = relationshipType + } + + fun policyType(policyType: PolicyType) { + if (policyTypes == null) + policyTypes = hashMapOf() + + policyTypes!![policyType.id!!] = policyType + } + + fun nodeType(nodeType: NodeType) { + if (nodeTypes == null) + nodeTypes = hashMapOf() + nodeTypes!![nodeType.id!!] = nodeType + } + + fun dataType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: DataTypeBuilder.() -> Unit + ) { + if (dataTypes == null) + dataTypes = hashMapOf() + dataTypes!![id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun artifactType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: ArtifactTypeBuilder.() -> Unit + ) { + if (artifactTypes == null) + artifactTypes = hashMapOf() + artifactTypes!![id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun relationshipType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: RelationshipTypeBuilder.() -> Unit + ) { + if (relationshipTypes == null) + relationshipTypes = hashMapOf() + relationshipTypes!![id] = RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun policyType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: PolicyTypeBuilder.() -> Unit + ) { + if (policyTypes == null) + policyTypes = hashMapOf() + policyTypes!![id] = PolicyTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun nodeType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: NodeTypeBuilder.() -> Unit + ) { + if (nodeTypes == null) + nodeTypes = hashMapOf() + nodeTypes!![id] = NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun topologyTemplate(block: TopologyTemplateBuilder.() -> Unit) { + topologyTemplate = TopologyTemplateBuilder().apply(block).build() + } + + fun build(): ServiceTemplate { + initMetaData() + serviceTemplate.metadata = metadata + serviceTemplate.imports = imports + serviceTemplate.dslDefinitions = dslDefinitions + serviceTemplate.nodeTypes = nodeTypes + serviceTemplate.artifactTypes = artifactTypes + serviceTemplate.dataTypes = dataTypes + serviceTemplate.relationshipTypes = relationshipTypes + serviceTemplate.policyTypes = policyTypes + serviceTemplate.topologyTemplate = topologyTemplate + return serviceTemplate + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt new file mode 100644 index 000000000..d07fc9c71 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt @@ -0,0 +1,211 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.bpClone +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow + +/** + * Generate Service Template for the simplified DSL. + * @author Brinda Santh + */ +class BluePrintServiceTemplateGenerator(private val dslBluePrint: DSLBluePrint) { + + private var serviceTemplate = ServiceTemplate() + + private val nodeTypes: MutableMap<String, NodeType> = hashMapOf() + private val artifactTypes: MutableMap<String, ArtifactType> = hashMapOf() + private val dataTypes: MutableMap<String, DataType> = hashMapOf() + + fun serviceTemplate(): ServiceTemplate { + serviceTemplate.metadata = dslBluePrint.metadata + serviceTemplate.dslDefinitions = dslBluePrint.properties + + dataTypes.putAll(dslBluePrint.dataTypes) + artifactTypes.putAll(dslBluePrint.artifactTypes) + + serviceTemplate.dataTypes = dataTypes + serviceTemplate.artifactTypes = artifactTypes + serviceTemplate.nodeTypes = nodeTypes + + serviceTemplate.topologyTemplate = populateTopologyTemplate() + + return serviceTemplate + } + + private fun populateTopologyTemplate(): TopologyTemplate { + val topologyTemplate = TopologyTemplate() + topologyTemplate.nodeTemplates = populateNodeTemplates() + topologyTemplate.workflows = populateWorkflow() + return topologyTemplate + } + + private fun populateNodeTemplates(): MutableMap<String, NodeTemplate> { + + val nodeTemplates: MutableMap<String, NodeTemplate> = hashMapOf() + + // For New or Dynamic Components + val components = dslBluePrint.components + components.forEach { (dslCompName, dslComp) -> + val nodeTemplate = NodeTemplate() + nodeTemplate.type = dslComp.type + nodeTemplate.properties = propertyAssignments(dslComp.properties) + nodeTemplate.artifacts = dslComp.artifacts + nodeTemplate.interfaces = populateInterfaceAssignments(dslComp) + nodeTemplates[dslCompName] = nodeTemplate + + /** Populate Type **/ + nodeTypes[dslComp.type] = populateNodeType(dslComp) + } + + // For Registry Components + val registryComponents = dslBluePrint.registryComponents + registryComponents.forEach { (dslCompName, dslComp) -> + val nodeTemplate = NodeTemplate() + nodeTemplate.type = dslComp.type + nodeTemplate.properties = dslComp.properties + nodeTemplate.artifacts = dslComp.artifacts + nodeTemplate.interfaces = populateInterfaceAssignments(dslComp) + nodeTemplates[dslCompName] = nodeTemplate + } + return nodeTemplates + } + + private fun populateWorkflow(): MutableMap<String, Workflow>? { + var workflows: MutableMap<String, Workflow>? = null + if (dslBluePrint.workflows.isNotEmpty()) { + workflows = hashMapOf() + + dslBluePrint.workflows.forEach { (dslWorkflowName, dslWorkflow) -> + val workflow = Workflow() + workflow.description = dslWorkflow.description + workflow.steps = dslWorkflow.steps + workflow.inputs = dslWorkflow.inputs + workflow.outputs = dslWorkflow.outputs + workflows[dslWorkflowName] = workflow + } + } + return workflows + } + + private fun populateNodeType(dslComponent: DSLComponent): NodeType { + val nodeType = NodeType() + nodeType.derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT + nodeType.version = dslComponent.version + nodeType.description = dslComponent.description + nodeType.interfaces = populateInterfaceDefinitions(dslComponent, nodeType) + return nodeType + } + + private fun populateInterfaceDefinitions(dslComponent: DSLComponent, nodeType: NodeType): MutableMap<String, InterfaceDefinition> { + + // Populate Node Type Attribute + nodeType.attributes = attributeDefinitions(dslComponent.attributes) + + val operationDefinition = OperationDefinition() + operationDefinition.inputs = propertyDefinitions(dslComponent.inputs) + operationDefinition.outputs = propertyDefinitions(dslComponent.outputs) + + val operations: MutableMap<String, OperationDefinition> = hashMapOf() + operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationDefinition + + val interfaceDefinition = InterfaceDefinition() + interfaceDefinition.operations = operations + + val interfaces: MutableMap<String, InterfaceDefinition> = hashMapOf() + interfaces[BluePrintConstants.DEFAULT_STEP_INTERFACE] = interfaceDefinition + return interfaces + } + + private fun populateInterfaceAssignments(dslComponent: DSLRegistryComponent): MutableMap<String, InterfaceAssignment> { + val operationAssignment = OperationAssignment() + operationAssignment.implementation = dslComponent.implementation + operationAssignment.inputs = dslComponent.inputs + operationAssignment.outputs = dslComponent.outputs + + val operations: MutableMap<String, OperationAssignment> = hashMapOf() + operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationAssignment + + val interfaceAssignment = InterfaceAssignment() + interfaceAssignment.operations = operations + + val interfaces: MutableMap<String, InterfaceAssignment> = hashMapOf() + interfaces[dslComponent.interfaceName] = interfaceAssignment + return interfaces + } + + private fun populateInterfaceAssignments(dslComponent: DSLComponent): MutableMap<String, InterfaceAssignment> { + val operationAssignment = OperationAssignment() + operationAssignment.implementation = dslComponent.implementation + operationAssignment.inputs = propertyAssignments(dslComponent.inputs) + operationAssignment.outputs = propertyAssignments(dslComponent.outputs) + + val operations: MutableMap<String, OperationAssignment> = hashMapOf() + operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationAssignment + + val interfaceAssignment = InterfaceAssignment() + interfaceAssignment.operations = operations + + val interfaces: MutableMap<String, InterfaceAssignment> = hashMapOf() + interfaces[BluePrintConstants.DEFAULT_STEP_INTERFACE] = interfaceAssignment + return interfaces + } + + private fun propertyDefinitions(propertyDefinitions: Map<String, PropertyDefinition>?): MutableMap<String, PropertyDefinition>? { + val definitions: MutableMap<String, PropertyDefinition>? = propertyDefinitions?.bpClone()?.toMutableMap() + + definitions?.forEach { (_, prop) -> + prop.value = null + } + return definitions + } + + private fun attributeDefinitions(attributeDefinitions: Map<String, AttributeDefinition>?): MutableMap<String, AttributeDefinition>? { + val definitions: MutableMap<String, AttributeDefinition>? = attributeDefinitions?.bpClone()?.toMutableMap() + + definitions?.forEach { (_, prop) -> + prop.value = null + } + return definitions + } + + private fun propertyAssignments(propertyDefinitions: Map<String, PropertyDefinition>?): MutableMap<String, JsonNode>? { + var assignments: MutableMap<String, JsonNode>? = null + if (propertyDefinitions != null) { + assignments = hashMapOf() + propertyDefinitions.forEach { (propertyName, property) -> + assignments[propertyName] = property.value ?: NullNode.instance + } + } + return assignments + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt new file mode 100644 index 000000000..df4d2d849 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt @@ -0,0 +1,408 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import kotlin.reflect.KClass +import kotlin.reflect.full.createInstance +import kotlin.reflect.jvm.reflect + +class TopologyTemplateBuilder { + private var topologyTemplate = TopologyTemplate() + private var nodeTemplates: MutableMap<String, NodeTemplate>? = null + private var workflows: MutableMap<String, Workflow>? = null + + fun nodeTemplate(id: String, type: String, description: String, block: NodeTemplateBuilder.() -> Unit) { + if (nodeTemplates == null) + nodeTemplates = hashMapOf() + nodeTemplates!![id] = NodeTemplateBuilder(id, type, description).apply(block).build() + } + + fun nodeTemplate(nodeTemplate: NodeTemplate) { + if (nodeTemplates == null) + nodeTemplates = hashMapOf() + nodeTemplates!![nodeTemplate.id!!] = nodeTemplate + } + + fun nodeTemplateOperation( + nodeTemplateName: String, + type: String, + interfaceName: String, + description: String, + operationBlock: OperationAssignmentBuilder<PropertiesAssignmentBuilder, + PropertiesAssignmentBuilder>.() -> Unit + ) { + if (nodeTemplates == null) + nodeTemplates = hashMapOf() + + val nodeTemplateBuilder = NodeTemplateBuilder(nodeTemplateName, type, description) + nodeTemplateBuilder.operation(interfaceName, "$description operation", operationBlock) + nodeTemplates!![nodeTemplateName] = nodeTemplateBuilder.build() + } + + fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit) { + if (workflows == null) + workflows = hashMapOf() + workflows!![id] = WorkflowBuilder(id, description).apply(block).build() + } + + fun workflow(workflow: Workflow) { + if (workflows == null) + workflows = hashMapOf() + workflows!![workflow.id!!] = workflow + } + + // TODO("populate inputs, outputs") + fun workflowNodeTemplate( + actionName: String, + nodeTemplateType: String, + description: String, + block: NodeTemplateBuilder.() -> Unit + ) { + if (nodeTemplates == null) + nodeTemplates = hashMapOf() + + if (workflows == null) + workflows = hashMapOf() + + val workflowBuilder = WorkflowBuilder(actionName, description) + workflowBuilder.nodeTemplateStep(actionName, description) + // Workflow name is NodeTemplate name + workflows!![actionName] = workflowBuilder.build() + + nodeTemplates!![actionName] = NodeTemplateBuilder(actionName, nodeTemplateType, description).apply(block).build() + } + + fun build(): TopologyTemplate { + topologyTemplate.nodeTemplates = nodeTemplates + topologyTemplate.workflows = workflows + return topologyTemplate + } +} + +open class NodeTemplateBuilder( + private val id: String, + private val type: String, + private val description: String? = "" +) { + + private var nodeTemplate: NodeTemplate = NodeTemplate() + private var properties: MutableMap<String, JsonNode>? = null + private var interfaces: MutableMap<String, InterfaceAssignment>? = null + private var artifacts: MutableMap<String, ArtifactDefinition>? = null + private var capabilities: MutableMap<String, CapabilityAssignment>? = null + private var requirements: MutableMap<String, RequirementAssignment>? = null + + fun properties(properties: MutableMap<String, JsonNode>?) { + this.properties = properties + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) + properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + open fun <Prop : PropertiesAssignmentBuilder> typedProperties(block: Prop.() -> Unit) { + if (properties == null) + properties = hashMapOf() + val instance: Prop = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass<Prop>).createInstance() + properties = instance.apply(block).build() + } + + open fun <In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder> typedOperation( + interfaceName: String, + description: String = "", + block: OperationAssignmentBuilder<In, Out>.() -> Unit + ) { + if (interfaces == null) + interfaces = hashMapOf() + + val interfaceAssignment = InterfaceAssignment() + val defaultOperationName = BluePrintConstants.DEFAULT_STEP_OPERATION + interfaceAssignment.operations = hashMapOf() + interfaceAssignment.operations!![defaultOperationName] = + OperationAssignmentBuilder<In, Out>(defaultOperationName, description).apply(block).build() + interfaces!![interfaceName] = interfaceAssignment + } + + fun operation( + interfaceName: String, + description: String, + block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit + ) { + typedOperation<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>(interfaceName, description, block) + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() + } + + fun artifacts(artifacts: MutableMap<String, ArtifactDefinition>?) { + this.artifacts = artifacts + } + + fun capability(id: String, block: CapabilityAssignmentBuilder.() -> Unit) { + if (capabilities == null) + capabilities = hashMapOf() + capabilities!![id] = CapabilityAssignmentBuilder(id).apply(block).build() + } + + fun capabilities(capabilities: MutableMap<String, CapabilityAssignment>?) { + this.capabilities = capabilities + } + + fun requirement(id: String, capability: String, node: String, relationship: String) { + if (requirements == null) + requirements = hashMapOf() + requirements!![id] = RequirementAssignmentBuilder(id, capability, node, relationship).build() + } + + fun requirements(requirements: MutableMap<String, RequirementAssignment>?) { + this.requirements = requirements + } + + fun build(): NodeTemplate { + nodeTemplate.id = id + nodeTemplate.type = type + nodeTemplate.description = description + nodeTemplate.properties = properties + nodeTemplate.interfaces = interfaces + nodeTemplate.artifacts = artifacts + nodeTemplate.capabilities = capabilities + nodeTemplate.requirements = requirements + return nodeTemplate + } +} + +class ArtifactDefinitionBuilder(private val id: String, private val type: String, private val file: String) { + + private var artifactDefinition: ArtifactDefinition = ArtifactDefinition() + private var properties: MutableMap<String, JsonNode>? = null + + fun repository(repository: String) { + artifactDefinition.repository = repository + } + + fun deployPath(deployPath: String) { + artifactDefinition.deployPath = deployPath + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) + properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + fun build(): ArtifactDefinition { + artifactDefinition.id = id + artifactDefinition.type = type + artifactDefinition.file = file + artifactDefinition.properties = properties + return artifactDefinition + } +} + +open class CapabilityAssignmentBuilder(private val id: String) { + var capabilityAssignment: CapabilityAssignment = CapabilityAssignment() + var attributes: MutableMap<String, JsonNode>? = null + var properties: MutableMap<String, JsonNode>? = null + + fun attributes(block: AttributesAssignmentBuilder.() -> Unit) { + if (attributes == null) + attributes = hashMapOf() + attributes = AttributesAssignmentBuilder().apply(block).build() + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) + properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + fun build(): CapabilityAssignment { + capabilityAssignment.properties = properties + capabilityAssignment.attributes = attributes + return capabilityAssignment + } +} + +open class RequirementAssignmentBuilder( + private val id: String, + private val capability: String, + private val node: String, + private val relationship: String +) { + + private var requirementAssignment: RequirementAssignment = RequirementAssignment() + + fun build(): RequirementAssignment { + requirementAssignment.id = id + requirementAssignment.capability = capability + requirementAssignment.node = node + requirementAssignment.relationship = relationship + return requirementAssignment + } +} + +class InterfaceAssignmentBuilder(private val id: String) { + + private var interfaceAssignment: InterfaceAssignment = InterfaceAssignment() + private var operations: MutableMap<String, OperationAssignment>? = null + + fun operation( + id: String, + description: String? = "", + block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit + ) { + if (operations == null) + operations = hashMapOf() + operations!![id] = OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>( + id, description + ).apply(block).build() + } + + fun build(): InterfaceAssignment { + interfaceAssignment.id = id + interfaceAssignment.operations = operations + return interfaceAssignment + } +} + +class OperationAssignmentBuilder<In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder>( + private val id: String, + private val description: String? = "" +) { + + private var operationAssignment: OperationAssignment = OperationAssignment() + + fun implementation(implementation: Implementation?) { + operationAssignment.implementation = implementation + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + operationAssignment.implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun implementation( + timeout: Int, + operationHost: String? = BluePrintConstants.PROPERTY_SELF, + block: ImplementationBuilder.() -> Unit + ) { + operationAssignment.implementation = ImplementationBuilder(timeout, operationHost!!).apply(block).build() + } + + fun inputs(inputs: MutableMap<String, JsonNode>?) { + operationAssignment.inputs = inputs + } + + fun inputs(block: In.() -> Unit) { + val instance: In = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass<In>).createInstance() + operationAssignment.inputs = instance.apply(block).build() + } + + fun outputs(outputs: MutableMap<String, JsonNode>?) { + operationAssignment.outputs = outputs + } + + fun outputs(block: Out.() -> Unit) { + val instance: Out = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass<Out>).createInstance() + operationAssignment.outputs = instance.apply(block).build() + } + + fun build(): OperationAssignment { + operationAssignment.id = id + operationAssignment.description = description + return operationAssignment + } +} + +class ImplementationBuilder(private val timeout: Int, private val operationHost: String) { + private val implementation = Implementation() + + fun primary(primary: String) { + implementation.primary = primary + } + + fun dependencies(vararg dependencies: String) { + if (implementation.dependencies == null) + implementation.dependencies = arrayListOf() + dependencies.forEach { + implementation.dependencies!!.add(it) + } + } + + fun build(): Implementation { + implementation.timeout = timeout + implementation.operationHost = operationHost + return implementation + } +} + +open class PropertiesAssignmentBuilder { + var properties: MutableMap<String, JsonNode> = hashMapOf() + + fun property(id: String, value: Any) { + property(id, value.asJsonType()) + } + + fun property(id: String, value: JsonNode) { + properties[id] = value + } + + open fun build(): MutableMap<String, JsonNode> { + return properties + } +} + +open class AttributesAssignmentBuilder { + var attributes: MutableMap<String, JsonNode> = hashMapOf() + + fun attribute(id: String, value: String) { + attribute(id, value.asJsonType()) + } + + fun attribute(id: String, value: JsonNode) { + attributes[id] = value + } + + fun build(): MutableMap<String, JsonNode> { + return attributes + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt new file mode 100644 index 000000000..e183b8090 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt @@ -0,0 +1,581 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.asListOfString +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType +import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType + +open class EntityTypeBuilder( + private val id: String, + private val version: String, + private val derivedFrom: String, + private val description: String? = "" +) { + + var metadata: MutableMap<String, String>? = null + var properties: MutableMap<String, PropertyDefinition>? = null + var attributes: MutableMap<String, AttributeDefinition>? = null + + fun metadata(key: String, value: String) { + if (metadata == null) + metadata = hashMapOf() + metadata!![key] = value + } + + fun attribute(id: String, type: String, required: Boolean, description: String? = "") { + if (attributes == null) + attributes = hashMapOf() + val attribute = AttributeDefinitionBuilder(id, type, required, description).build() + attributes!![id] = attribute + } + + fun attribute( + id: String, + type: String, + required: Boolean, + description: String? = "", + block: AttributeDefinitionBuilder.() -> Unit + ) { + if (attributes == null) + attributes = hashMapOf() + val attribute = AttributeDefinitionBuilder(id, type, required, description).apply(block).build() + attributes!![id] = attribute + } + + fun property(id: String, type: String, required: Boolean, description: String? = "") { + if (properties == null) + properties = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description).build() + properties!![id] = property + } + + fun property( + id: String, + type: String, + required: Boolean, + description: String? = "", + block: PropertyDefinitionBuilder.() -> Unit + ) { + if (properties == null) + properties = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() + properties!![id] = property + } + + fun buildEntityType(entity: EntityType) { + entity.id = id + entity.description = description + entity.version = version + entity.derivedFrom = derivedFrom + entity.metadata = metadata + entity.properties = properties + entity.attributes = attributes + } +} + +class NodeTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var nodeType = NodeType() + private var capabilities: MutableMap<String, CapabilityDefinition>? = null + private var requirements: MutableMap<String, RequirementDefinition>? = null + private var interfaces: MutableMap<String, InterfaceDefinition>? = null + private var artifacts: MutableMap<String, ArtifactDefinition>? = null + + fun capability(id: String, type: String, description: String, block: CapabilityDefinitionBuilder.() -> Unit) { + if (capabilities == null) + capabilities = hashMapOf() + capabilities!![id] = CapabilityDefinitionBuilder(id, type, description).apply(block).build() + } + + fun requirement(id: String, capability: String, node: String, relationship: String, description: String) { + if (requirements == null) + requirements = hashMapOf() + requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description).build() + } + + fun requirement( + id: String, + capability: String, + node: String, + relationship: String, + description: String, + block: RequirementDefinitionBuilder.() -> Unit + ) { + if (requirements == null) + requirements = hashMapOf() + requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description) + .apply(block).build() + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + private fun nodeInterface(id: String, block: InterfaceDefinitionBuilder.() -> Unit) { + if (interfaces == null) + interfaces = hashMapOf() + interfaces!![id] = InterfaceDefinitionBuilder(id).apply(block).build() + } + + fun operation(interfaceName: String, description: String?, block: OperationDefinitionBuilder.() -> Unit) { + if (interfaces == null) + interfaces = hashMapOf() + + val interfaceDefinition = InterfaceDefinition() + val defaultOperationName = "process" + interfaceDefinition.operations = hashMapOf() + interfaceDefinition.operations!![defaultOperationName] = + OperationDefinitionBuilder(defaultOperationName, description).apply(block).build() + interfaces!![interfaceName] = interfaceDefinition + } + + fun build(): NodeType { + buildEntityType(nodeType) + nodeType.capabilities = capabilities + nodeType.requirements = requirements + nodeType.interfaces = interfaces + nodeType.artifacts = artifacts + return nodeType + } +} + +class ArtifactTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var artifactType = ArtifactType() + private var fileExt: MutableList<String>? = null + + fun fileExt(vararg fileExts: String) { + if (fileExt == null) + fileExt = arrayListOf() + fileExts.forEach { + fileExt!!.add(it) + } + } + + fun build(): ArtifactType { + buildEntityType(artifactType) + artifactType.fileExt = fileExt + return artifactType + } +} + +class PolicyTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var policyType = PolicyType() + + fun targets(targetsStr: String) { + val arrayNode = targetsStr.jsonAsJsonType() as ArrayNode + targets(arrayNode.asListOfString()) + } + + fun targets(target: List<String>) { + policyType.targets = target.toMutableList() + } + + fun build(): PolicyType { + buildEntityType(policyType) + return policyType + } +} + +class RelationshipTypeBuilder( + private val id: String, + private val version: String, + derivedFrom: String, + private val description: String? +) : + EntityTypeBuilder(id, version, derivedFrom, description) { + + private var relationshipType = RelationshipType() + + fun validTargetTypes(validTargetTypesStr: String) { + val arrayNode = validTargetTypesStr.jsonAsJsonType() as ArrayNode + validTargetTypes(arrayNode.asListOfString()) + } + + fun validTargetTypes(validTargetTypes: List<String>) { + relationshipType.validTargetTypes = validTargetTypes.toMutableList() + } + + fun build(): RelationshipType { + buildEntityType(relationshipType) + relationshipType.id = id + relationshipType.version = version + relationshipType.description = description + return relationshipType + } +} + +class DataTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var dataType = DataType() + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (dataType.constraints == null) { + dataType.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + dataType.constraints!!.add(constraintClause) + } + + fun build(): DataType { + buildEntityType(dataType) + return dataType + } +} + +class CapabilityDefinitionBuilder(private val id: String, private val type: String, private val description: String? = "") { + + private var capabilityDefinition = CapabilityDefinition() + private val properties: MutableMap<String, PropertyDefinition> = hashMapOf() + + fun property(id: String, type: String? = BluePrintConstants.DATA_TYPE_STRING, required: Boolean? = false, description: String? = "") { + val property = PropertyDefinitionBuilder(id, type, required, description).build() + properties[id] = property + } + + fun build(): CapabilityDefinition { + capabilityDefinition.id = id + capabilityDefinition.description = description + capabilityDefinition.type = type + capabilityDefinition.properties = properties + return capabilityDefinition + } +} + +class RequirementDefinitionBuilder( + private val id: String, + private val capability: String, + private val node: String, + private val relationship: String, + private val description: String? = "" +) { + + private var requirementDefinition = RequirementDefinition() + + fun build(): RequirementDefinition { + requirementDefinition.id = id + requirementDefinition.description = description + requirementDefinition.capability = capability + requirementDefinition.node = node + requirementDefinition.relationship = relationship + return requirementDefinition + } +} + +class InterfaceDefinitionBuilder(private val id: String) { + + private var interfaceDefinition: InterfaceDefinition = InterfaceDefinition() + private var operations: MutableMap<String, OperationDefinition>? = null + + fun operation(id: String, description: String? = "", block: OperationDefinitionBuilder.() -> Unit) { + if (operations == null) + operations = hashMapOf() + operations!![id] = OperationDefinitionBuilder(id, description).apply(block).build() + } + + fun build(): InterfaceDefinition { + interfaceDefinition.id = id + interfaceDefinition.operations = operations + return interfaceDefinition + } +} + +class OperationDefinitionBuilder( + private val id: String, + private val description: String? = "" +) { + + private var operationDefinition: OperationDefinition = OperationDefinition() + + fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) { + operationDefinition.inputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun outputs(block: PropertiesDefinitionBuilder.() -> Unit) { + operationDefinition.outputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun build(): OperationDefinition { + operationDefinition.id = id + operationDefinition.description = description + return operationDefinition + } +} + +class AttributeDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val description: String? = "" +) { + + private var attributeDefinition: AttributeDefinition = AttributeDefinition() + + fun entrySchema(entrySchemaType: String) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (attributeDefinition.constraints == null) { + attributeDefinition.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + attributeDefinition.constraints!!.add(constraintClause) + } + + fun defaultValue(defaultValue: Any) { + defaultValue(defaultValue.asJsonType()) + } + + fun defaultValue(defaultValue: JsonNode) { + attributeDefinition.defaultValue = defaultValue + } + + fun build(): AttributeDefinition { + attributeDefinition.id = id + attributeDefinition.type = type!! + attributeDefinition.required = required + attributeDefinition.description = description + return attributeDefinition + } +} + +class PropertiesDefinitionBuilder { + private val properties: MutableMap<String, PropertyDefinition> = hashMapOf() + + fun property(id: String, property: PropertyDefinition) { + properties[id] = property + } + + fun property(id: String, type: String?, required: Boolean?, description: String? = "") { + val property = PropertyDefinitionBuilder(id, type, required, description).build() + properties[id] = property + } + + fun property( + id: String, + type: String?, + required: Boolean?, + description: String? = "", + block: PropertyDefinitionBuilder.() -> Unit + ) { + val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() + properties[id] = property + } + + fun build(): MutableMap<String, PropertyDefinition> { + return properties + } +} + +class PropertyDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val description: String? = "" +) { + + private var propertyDefinition: PropertyDefinition = PropertyDefinition() + + fun entrySchema(entrySchemaType: String) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (propertyDefinition.constraints == null) { + propertyDefinition.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + propertyDefinition.constraints!!.add(constraintClause) + } + + fun defaultValue(defaultValue: Any) { + defaultValue(defaultValue.asJsonType()) + } + + fun defaultValue(defaultValue: JsonNode) { + propertyDefinition.defaultValue = defaultValue + } + + fun metadata(name: String, value: String) { + if (propertyDefinition.metadata == null) { + propertyDefinition.metadata = hashMapOf() + } + propertyDefinition.metadata!![name] = value + } + + fun value(value: Any) { + value(value.asJsonType()) + } + + fun value(value: JsonNode) { + propertyDefinition.value = value + } + + fun build(): PropertyDefinition { + propertyDefinition.id = id + propertyDefinition.type = type!! + propertyDefinition.required = required + propertyDefinition.description = description + return propertyDefinition + } +} + +class ConstraintsClauseBuilder { + val constraints: MutableList<ConstraintClause> = mutableListOf() + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + val constraintClause = ConstraintClauseBuilder().apply(block).build() + constraints.add(constraintClause) + } + + fun build(): MutableList<ConstraintClause> { + return constraints + } +} + +class ConstraintClauseBuilder { + private val constraintClause = ConstraintClause() + + fun equal(equal: Any) = equal(equal.asJsonType()) + + fun equal(equal: JsonNode) { + constraintClause.equal = equal + } + + fun greaterOrEqual(greaterOrEqual: Any) { + constraintClause.greaterOrEqual = greaterOrEqual.asJsonPrimitive() + } + + fun greaterThan(greaterThan: Any) { + constraintClause.greaterThan = greaterThan.asJsonPrimitive() + } + + fun lessOrEqual(lessOrEqual: Any) { + constraintClause.lessOrEqual = lessOrEqual.asJsonPrimitive() + } + + fun lessThan(lessThan: Any) { + constraintClause.lessThan = lessThan.asJsonPrimitive() + } + + fun inRange(inRangeStr: String) = inRange(inRangeStr.jsonAsJsonType() as ArrayNode) + + fun inRange(inRangeNode: ArrayNode) { + constraintClause.inRange = inRangeNode.toMutableList() + } + + fun validValues(validValuesStr: String) = validValues(validValuesStr.jsonAsJsonType() as ArrayNode) + + fun validValues(validValuesNode: ArrayNode) = validValues(validValuesNode.toMutableList()) + + fun validValues(validValues: List<JsonNode>) { + constraintClause.validValues = validValues.toMutableList() + } + + fun length(length: Any) { + constraintClause.length = length.asJsonPrimitive() + } + + fun minLength(minLength: Any) { + constraintClause.minLength = minLength.asJsonPrimitive() + } + + fun maxLength(maxLength: Any) { + constraintClause.maxLength = maxLength.asJsonPrimitive() + } + + fun pattern(pattern: String) { + constraintClause.pattern = pattern + } + + fun schema(schema: String) { + constraintClause.schema = schema + } + + fun build(): ConstraintClause { + return constraintClause + } +} + +class EntrySchemaBuilder(private val type: String) { + private var entrySchema: EntrySchema = EntrySchema() + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (entrySchema.constraints == null) { + entrySchema.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + entrySchema.constraints!!.add(constraintClause) + } + + fun build(): EntrySchema { + entrySchema.type = type + return entrySchema + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt new file mode 100644 index 000000000..8a1a9d63c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt @@ -0,0 +1,121 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.dsl + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap +import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import kotlin.reflect.KClass + +class WorkflowBuilder(private val id: String, private val description: String) { + + private var workflow = Workflow() + private var steps: MutableMap<String, Step>? = null + private var inputs: MutableMap<String, PropertyDefinition>? = null + private var outputs: MutableMap<String, PropertyDefinition>? = null + + // Used Internally + fun nodeTemplateStep(nodeTemplateName: String, description: String) { + step(nodeTemplateName, nodeTemplateName, "$description step") + } + + fun step(id: String, target: String, description: String) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).build() + } + + fun step(id: String, target: String, description: String, block: StepBuilder.() -> Unit) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).apply(block).build() + } + + fun inputs(kClazz: KClass<*>) { + inputs = kClazz.asPropertyDefinitionMap() + } + + fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) { + inputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun outputs(block: PropertiesDefinitionBuilder.() -> Unit) { + outputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun outputs(kClazz: KClass<*>) { + outputs = kClazz.asPropertyDefinitionMap() + } + + fun build(): Workflow { + workflow.id = id + workflow.description = description + workflow.steps = steps + workflow.inputs = inputs + workflow.outputs = outputs + return workflow + } +} + +class StepBuilder( + private val id: String, + private val target: String, + private val description: String +) { + + private var step = Step() + private var activities: ArrayList<Activity> = arrayListOf() + private var onSuccess: ArrayList<String>? = null + private var onFailure: ArrayList<String>? = null + + fun activity(callOperation: String) { + val activity = Activity() + activity.callOperation = callOperation + activities.add(activity) + } + + fun success(vararg successTargets: String) { + if (onSuccess == null) + onSuccess = arrayListOf() + successTargets.forEach { + onSuccess!!.add(it) + } + } + + fun failure(vararg failureTargets: String) { + if (onFailure == null) + onFailure = arrayListOf() + failureTargets.forEach { + onFailure!!.add(it) + } + } + + fun build(): Step { + step.id = id + step.target = target + // Add Default Activity, Assumption is only one Operation + activity(".${BluePrintConstants.DEFAULT_STEP_OPERATION}") + step.description = description + step.activities = activities + step.onSuccess = onSuccess + step.onFailure = onFailure + return step + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt new file mode 100755 index 000000000..bd45bed06 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt @@ -0,0 +1,57 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import java.io.File +import java.nio.file.Path + +interface BluePrintCatalogService { + + /** + * Save the CBA to database. + * @param processingId Processing Id + * @param blueprintFile Either a directory, or an archive + * @param validate whether to validate blueprint content. Default true. + * @return The unique blueprint identifier + * @throws BluePrintException if process failed + */ + @Throws(BluePrintException::class) + suspend fun saveToDatabase(processingId: String, blueprintFile: File, validate: Boolean = true): String + + /** + * Retrieve the CBA from database either archived or extracted. + * @param name Name of the blueprint + * @param version Version of the blueprint + * @param extract true to extract the content, false for archived content. Default to true + * @return Path where CBA is located + * @throws BluePrintException if process failed + */ + + @Throws(BluePrintException::class) + suspend fun getFromDatabase(name: String, version: String, extract: Boolean = true): Path + + /** + * Delete the CBA from database. + * @param name Name of the blueprint + * @param version Version of the blueprint + * @throws BluePrintException if process failed + */ + + @Throws(BluePrintException::class) + suspend fun deleteFromDatabase(name: String, version: String) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt new file mode 100644 index 000000000..fcc9bf2d7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt @@ -0,0 +1,60 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate + +interface BluePrintDefinitions { + + /** Define the service Template Model */ + fun serviceTemplate(): ServiceTemplate + + /** Load Custom Definitions that may used during runtime **/ + fun loadOtherDefinitions() + + /** Utility Method to add the definition */ + fun addOtherDefinition(key: String, definition: Any) + + /** Utility method to get the definition */ + fun <T : Any> otherDefinition(key: String): T + + fun otherDefinitions(): MutableMap<String, Any> +} + +abstract class AbstractBluePrintDefinitions : BluePrintDefinitions { + + private val otherDefinitionMap: MutableMap<String, Any> = hashMapOf() + + constructor() { + loadOtherDefinitions() + } + + override fun loadOtherDefinitions() { + } + + override fun <T : Any> otherDefinition(key: String): T { + return otherDefinitionMap[key] as T + } + + override fun addOtherDefinition(key: String, definition: Any) { + otherDefinitionMap[key] = definition + } + + override fun otherDefinitions(): MutableMap<String, Any> { + return otherDefinitionMap + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt new file mode 100644 index 000000000..80c91ca28 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt @@ -0,0 +1,154 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +interface BluePrintEnhancer<T> { + fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T) +} + +interface BluePrintServiceTemplateEnhancer : BluePrintEnhancer<ServiceTemplate> + +interface BluePrintTopologyTemplateEnhancer : BluePrintEnhancer<TopologyTemplate> + +interface BluePrintWorkflowEnhancer : BluePrintEnhancer<Workflow> + +interface BluePrintNodeTemplateEnhancer : BluePrintEnhancer<NodeTemplate> + +interface BluePrintNodeTypeEnhancer : BluePrintEnhancer<NodeType> + +interface BluePrintArtifactDefinitionEnhancer : BluePrintEnhancer<ArtifactDefinition> + +interface BluePrintPolicyTypeEnhancer : BluePrintEnhancer<PolicyType> + +interface BluePrintPropertyDefinitionEnhancer : BluePrintEnhancer<PropertyDefinition> + +interface BluePrintAttributeDefinitionEnhancer : BluePrintEnhancer<AttributeDefinition> + +interface BluePrintEnhancerService { + + @Throws(BluePrintException::class) + suspend fun enhance(basePath: String, enrichedBasePath: String): BluePrintContext + + @Throws(BluePrintException::class) + suspend fun enhance(basePath: String): BluePrintContext +} + +interface BluePrintTypeEnhancerService { + + fun getServiceTemplateEnhancers(): List<BluePrintServiceTemplateEnhancer> + + fun getTopologyTemplateEnhancers(): List<BluePrintTopologyTemplateEnhancer> + + fun getWorkflowEnhancers(): List<BluePrintWorkflowEnhancer> + + fun getNodeTemplateEnhancers(): List<BluePrintNodeTemplateEnhancer> + + fun getNodeTypeEnhancers(): List<BluePrintNodeTypeEnhancer> + + fun getArtifactDefinitionEnhancers(): List<BluePrintArtifactDefinitionEnhancer> + + fun getPolicyTypeEnhancers(): List<BluePrintPolicyTypeEnhancer> + + fun getPropertyDefinitionEnhancers(): List<BluePrintPropertyDefinitionEnhancer> + + fun getAttributeDefinitionEnhancers(): List<BluePrintAttributeDefinitionEnhancer> + + fun enhanceServiceTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) { + val enhancers = getServiceTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, serviceTemplate, enhancers) + } + + fun enhanceTopologyTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) { + val enhancers = getTopologyTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, topologyTemplate, enhancers) + } + + fun enhanceWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) { + val enhancers = getWorkflowEnhancers() + doEnhancement(bluePrintRuntimeService, name, workflow, enhancers) + } + + fun enhanceNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { + val enhancers = getNodeTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, nodeTemplate, enhancers) + } + + fun enhanceNodeType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) { + val enhancers = getNodeTypeEnhancers() + doEnhancement(bluePrintRuntimeService, name, nodeType, enhancers) + } + + fun enhanceArtifactDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) { + val enhancers = getArtifactDefinitionEnhancers() + doEnhancement(bluePrintRuntimeService, name, artifactDefinition, enhancers) + } + + fun enhancePolicyType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, policyType: PolicyType) { + val enhancers = getPolicyTypeEnhancers() + doEnhancement(bluePrintRuntimeService, name, policyType, enhancers) + } + + fun enhancePropertyDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, properties: MutableMap<String, PropertyDefinition>) { + properties.forEach { propertyName, propertyDefinition -> + enhancePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition) + } + } + + fun enhancePropertyDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { + val enhancers = getPropertyDefinitionEnhancers() + doEnhancement(bluePrintRuntimeService, name, propertyDefinition, enhancers) + } + + fun enhanceAttributeDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, attributes: MutableMap<String, AttributeDefinition>) { + attributes.forEach { attributeName, attributeDefinition -> + enhanceAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition) + } + } + + fun enhanceAttributeDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { + val enhancers = getAttributeDefinitionEnhancers() + doEnhancement(bluePrintRuntimeService, name, attributeDefinition, enhancers) + } + + @Suppress("UNCHECKED_CAST") + private fun <T> doEnhancement( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + definition: Any, + enhancers: List<BluePrintEnhancer<T>> + ) { + if (enhancers.isNotEmpty()) { + enhancers.forEach { + it.enhance(bluePrintRuntimeService, name, definition as T) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt new file mode 100644 index 000000000..8d04e5489 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt @@ -0,0 +1,50 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import java.io.Serializable + +/** + * BluePrintRepoFileService + * @author Brinda Santh + * + */ + +interface BluePrintRepoService : Serializable { + + @Throws(BluePrintException::class) + fun getNodeType(nodeTypeName: String): NodeType + + @Throws(BluePrintException::class) + fun getDataType(dataTypeName: String): DataType + + @Throws(BluePrintException::class) + fun getArtifactType(artifactTypeName: String): ArtifactType + + @Throws(BluePrintException::class) + fun getRelationshipType(relationshipTypeName: String): RelationshipType + + @Throws(BluePrintException::class) + fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt new file mode 100644 index 000000000..aa61b0c4d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt @@ -0,0 +1,39 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintSourceCode + +interface BluePrintScriptsService { + + suspend fun <T> scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T + + suspend fun <T> scriptInstance( + blueprintBasePath: String, + artifactName: String, + artifactVersion: String, + scriptClassName: String, + reCompile: Boolean + ): T + + suspend fun <T> scriptInstance(blueprintBasePath: String, scriptClassName: String, reCompile: Boolean): T + + suspend fun <T> scriptInstance(cacheKey: String, scriptClassName: String): T + + suspend fun <T> scriptInstance(scriptClassName: String): T +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt new file mode 100644 index 000000000..70c797326 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt @@ -0,0 +1,28 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +interface BluePrintWorkflowExecutionService<Input, Output> { + + suspend fun executeBluePrintWorkflow( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + executionServiceInput: Input, + properties: MutableMap<String, Any> = hashMapOf() + ): Output +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt new file mode 100644 index 000000000..b56fac541 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt @@ -0,0 +1,72 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.interfaces + +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import java.util.function.Function + +interface BlueprintFunctionNode<T, R> : Function<T, R> { + + fun getName(): String + + @Throws(BluePrintProcessorException::class) + fun prepareRequest(executionRequest: T): T = runBlocking { + prepareRequestNB(executionRequest) + } + + @Throws(BluePrintProcessorException::class) + fun process(executionRequest: T) = runBlocking { + processNB(executionRequest) + } + + @Throws(BluePrintProcessorException::class) + fun recover(runtimeException: RuntimeException, executionRequest: T) = runBlocking { + recoverNB(runtimeException, executionRequest) + } + + @Throws(BluePrintProcessorException::class) + fun prepareResponse(): R = runBlocking { + prepareResponseNB() + } + + override fun apply(executionServiceInput: T): R { + try { + prepareRequest(executionServiceInput) + process(executionServiceInput) + } catch (runtimeException: RuntimeException) { + recover(runtimeException, executionServiceInput) + } + return prepareResponse() + } + + @Throws(BluePrintProcessorException::class) + suspend fun prepareRequestNB(executionRequest: T): T + + @Throws(BluePrintProcessorException::class) + suspend fun processNB(executionRequest: T) + + @Throws(BluePrintProcessorException::class) + suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: T) + + @Throws(BluePrintProcessorException::class) + suspend fun prepareResponseNB(): R + + @Throws(BluePrintProcessorException::class) + suspend fun applyNB(t: T): R +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt new file mode 100644 index 000000000..6f6979772 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt @@ -0,0 +1,65 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.interfaces + +import com.fasterxml.jackson.core.io.CharTypes +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import com.fasterxml.jackson.databind.node.TextNode +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +interface BlueprintTemplateService { + + /** + * Generate dynamique content using Velocity Template or Jinja template + * + * @param bluePrintRuntimeService blueprint runtime + * @param nodeTemplateName node template + * @param artifactName Artifact Name + * @param jsonData json string data content to mash + * @param ignoreJsonNull Ignore Null value in the JSON content + * @param additionalContext (Key, value) mutable map for additional variables + * @return Content result + * + **/ + suspend fun generateContent( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + nodeTemplateName: String, + artifactName: String, + jsonData: String = "", + ignoreJsonNull: Boolean = false, + additionalContext: MutableMap<String, Any> = mutableMapOf() + ): String +} + +/** + * Customise JsonNodeFactory and TextNode, Since it introduces quotes for string data. + */ +open class BluePrintJsonNodeFactory : JsonNodeFactory() { + + override fun textNode(text: String): TextNode { + return BluePrintTextNode(text) + } +} + +open class BluePrintTextNode(v: String) : TextNode(v) { + override fun toString(): String { + var len = this._value.length + len = len + 2 + (len shr 4) + val sb = StringBuilder(len) + CharTypes.appendQuoted(sb, this._value) + return sb.toString() + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt new file mode 100644 index 000000000..c6339f449 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt @@ -0,0 +1,175 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +interface BluePrintValidator<T> { + + fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T) +} + +interface BluePrintServiceTemplateValidator : BluePrintValidator<ServiceTemplate> + +interface BluePrintTopologyTemplateValidator : BluePrintValidator<TopologyTemplate> + +interface BluePrintArtifactTypeValidator : BluePrintValidator<ArtifactType> + +interface BluePrintArtifactDefinitionValidator : BluePrintValidator<ArtifactDefinition> + +interface BluePrintDataTypeValidator : BluePrintValidator<DataType> + +interface BluePrintNodeTypeValidator : BluePrintValidator<NodeType> + +interface BluePrintNodeTemplateValidator : BluePrintValidator<NodeTemplate> + +interface BluePrintWorkflowValidator : BluePrintValidator<Workflow> + +interface BluePrintPropertyDefinitionValidator : BluePrintValidator<PropertyDefinition> + +interface BluePrintAttributeDefinitionValidator : BluePrintValidator<AttributeDefinition> + +/** + * Blueprint Validation Interface. + */ +interface BluePrintValidatorService { + + @Throws(BluePrintException::class) + fun validateBluePrints(basePath: String): Boolean + + @Throws(BluePrintException::class) + fun validateBluePrints(bluePrintRuntimeService: BluePrintRuntimeService<*>): Boolean +} + +interface BluePrintTypeValidatorService { + + fun <T : BluePrintValidator<*>> bluePrintValidator(referenceName: String, classType: Class<T>): T? + + fun <T : BluePrintValidator<*>> bluePrintValidators(referenceNamePrefix: String, classType: Class<T>): List<T>? + + fun <T : BluePrintValidator<*>> bluePrintValidators(classType: Class<T>): List<T>? + + fun getServiceTemplateValidators(): List<BluePrintServiceTemplateValidator> + + fun getDataTypeValidators(): List<BluePrintDataTypeValidator> + + fun getArtifactTypeValidators(): List<BluePrintArtifactTypeValidator> + + fun getArtifactDefinitionsValidators(): List<BluePrintArtifactDefinitionValidator> + + fun getNodeTypeValidators(): List<BluePrintNodeTypeValidator> + + fun getTopologyTemplateValidators(): List<BluePrintTopologyTemplateValidator> + + fun getNodeTemplateValidators(): List<BluePrintNodeTemplateValidator> + + fun getWorkflowValidators(): List<BluePrintWorkflowValidator> + + fun getPropertyDefinitionValidators(): List<BluePrintPropertyDefinitionValidator> + + fun getAttributeDefinitionValidators(): List<BluePrintAttributeDefinitionValidator> + + fun validateServiceTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) { + val validators = getServiceTemplateValidators() + doValidation(bluePrintRuntimeService, name, serviceTemplate, validators) + } + + fun validateArtifactType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactType: ArtifactType) { + val validators = getArtifactTypeValidators() + doValidation(bluePrintRuntimeService, name, artifactType, validators) + } + + fun validateArtifactDefinition( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + artifactDefinition: ArtifactDefinition + ) { + val validators = getArtifactDefinitionsValidators() + doValidation(bluePrintRuntimeService, name, artifactDefinition, validators) + } + + fun validateDataType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, dataType: DataType) { + val validators = getDataTypeValidators() + doValidation(bluePrintRuntimeService, name, dataType, validators) + } + + fun validateNodeType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) { + val validators = getNodeTypeValidators() + doValidation(bluePrintRuntimeService, name, nodeType, validators) + } + + fun validateTopologyTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) { + val validators = getTopologyTemplateValidators() + doValidation(bluePrintRuntimeService, name, topologyTemplate, validators) + } + + fun validateNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { + val validators = getNodeTemplateValidators() + doValidation(bluePrintRuntimeService, name, nodeTemplate, validators) + } + + fun validateWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) { + val validators = getWorkflowValidators() + doValidation(bluePrintRuntimeService, name, workflow, validators) + } + + fun validatePropertyDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, properties: MutableMap<String, PropertyDefinition>) { + properties.forEach { propertyName, propertyDefinition -> + validatePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition) + } + } + + fun validatePropertyDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { + val validators = getPropertyDefinitionValidators() + doValidation(bluePrintRuntimeService, name, propertyDefinition, validators) + } + + fun validateAttributeDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, attributes: MutableMap<String, AttributeDefinition>) { + attributes.forEach { attributeName, attributeDefinition -> + validateAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition) + } + } + + fun validateAttributeDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { + val validators = getAttributeDefinitionValidators() + doValidation(bluePrintRuntimeService, name, attributeDefinition, validators) + } + + @Suppress("UNCHECKED_CAST") + private fun <T> doValidation( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + definition: Any, + validators: List<BluePrintValidator<T>> + ) { + validators.forEach { + it.validate(bluePrintRuntimeService, name, definition as T) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt new file mode 100644 index 000000000..b2857c6ce --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt @@ -0,0 +1,178 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.scripts + +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import org.jetbrains.kotlin.cli.common.ExitCode +import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler +import org.jetbrains.kotlin.config.Services +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import java.io.File +import java.net.URLClassLoader +import java.util.ArrayList +import kotlin.script.experimental.api.SourceCode +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.system.measureTimeMillis + +open class BluePrintCompileService { + val log = logger(BluePrintCompileService::class) + + companion object { + val classPaths = classpathFromClasspathProperty()?.joinToString(File.pathSeparator) { + it.absolutePath + } + } + + /** Compile the [bluePrintSourceCode] and get the [kClassName] instance for the constructor [args] */ + suspend fun <T> eval( + bluePrintSourceCode: BluePrintSourceCode, + kClassName: String, + args: ArrayList<Any?>? + ): T { + /** Compile the source code */ + compile(bluePrintSourceCode) + /** Get the class loader with compiled jar */ + val classLoaderWithDependencies = BluePrintCompileCache.classLoader(bluePrintSourceCode.cacheKey) + /* Create the instance from the class loader */ + return instance(classLoaderWithDependencies, kClassName, args) + } + + /** Compile [bluePrintSourceCode] and put into cache */ + suspend fun compile(bluePrintSourceCode: BluePrintSourceCode) { + // TODO("Include Multiple folders") + val sourcePath = bluePrintSourceCode.blueprintKotlinSources.first() + val compiledJarFile = bluePrintSourceCode.targetJarFile + + /** Check cache is present for the blueprint scripts */ + val hasCompiledCache = BluePrintCompileCache.hasClassLoader(bluePrintSourceCode.cacheKey) + + log.debug( + "Jar Exists : ${compiledJarFile.exists()}, Regenerate : ${bluePrintSourceCode.regenerate}," + + " Compiled hash(${bluePrintSourceCode.cacheKey}) : $hasCompiledCache" + ) + + if (!compiledJarFile.exists() || bluePrintSourceCode.regenerate || !hasCompiledCache) { + log.info("compiling for cache key(${bluePrintSourceCode.cacheKey})") + coroutineScope { + val timeTaken = measureTimeMillis { + /** Create compile arguments */ + val args = mutableListOf<String>().apply { + add("-no-stdlib") + add("-no-reflect") + add("-module-name") + add(bluePrintSourceCode.moduleName) + add("-cp") + add(classPaths!!) + add(sourcePath) + add("-d") + add(compiledJarFile.absolutePath) + } + val deferredCompile = async { + val k2jvmCompiler = K2JVMCompiler() + /** Construct Arguments */ + val arguments = k2jvmCompiler.createArguments() + parseCommandLineArguments(args, arguments) + val messageCollector = CompilationMessageCollector() + /** Compile with arguments */ + val exitCode: ExitCode = k2jvmCompiler.exec(messageCollector, Services.EMPTY, arguments) + when (exitCode) { + ExitCode.OK -> { + checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" } + } + else -> { + throw BluePrintException("$exitCode :${messageCollector.errors().joinToString("\n")}") + } + } + } + deferredCompile.await() + } + log.info("compiled in ($timeTaken)mSec for cache key(${bluePrintSourceCode.cacheKey})") + } + } + } + + /** create class [kClassName] instance from [classLoader] */ + fun <T> instance(classLoader: URLClassLoader, kClassName: String, args: ArrayList<Any?>? = arrayListOf()): T { + val kClazz = classLoader.loadClass(kClassName) + ?: throw BluePrintException("failed to load class($kClassName) from current class loader.") + + val instance = if (args.isNullOrEmpty()) { + kClazz.newInstance() + } else { + kClazz.constructors + .single().newInstance(*args.toArray()) + } ?: throw BluePrintException("failed to create class($kClassName) instance for constructor argument($args).") + return instance as T + } +} + +/** Compile source code information */ +open class BluePrintSourceCode : SourceCode { + + lateinit var blueprintKotlinSources: MutableList<String> + lateinit var moduleName: String + lateinit var targetJarFile: File + lateinit var cacheKey: String + var regenerate: Boolean = false + + override val text: String + get() = "" + + override val locationId: String? = null + + override val name: String? + get() = moduleName +} + +/** Class to collect compilation Data */ +data class CompiledMessageData( + val severity: CompilerMessageSeverity, + val message: String, + val location: CompilerMessageLocation? +) + +/** Class to collect compilation results */ +class CompilationMessageCollector : MessageCollector { + + private val compiledMessages: MutableList<CompiledMessageData> = arrayListOf() + + override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) { + synchronized(compiledMessages) { + compiledMessages.add(CompiledMessageData(severity, message, location)) + } + } + + override fun hasErrors() = + synchronized(compiledMessages) { + compiledMessages.any { it.severity.isError } + } + + override fun clear() { + synchronized(compiledMessages) { + compiledMessages.clear() + } + } + + fun errors(): List<CompiledMessageData> = compiledMessages.filter { it.severity == CompilerMessageSeverity.ERROR } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt new file mode 100644 index 000000000..fbfcfb94f --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt @@ -0,0 +1,76 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.scripts + +import com.google.common.cache.CacheBuilder +import com.google.common.cache.CacheLoader +import com.google.common.cache.LoadingCache +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import java.net.URL +import java.net.URLClassLoader + +object BluePrintCompileCache { + val log = logger(BluePrintCompileCache::class) + + private val classLoaderCache: LoadingCache<String, URLClassLoader> = CacheBuilder.newBuilder() + .maximumSize(50) + .build(BluePrintClassLoader) + + fun classLoader(key: String): URLClassLoader { + return classLoaderCache.get(key) + } + + fun cleanClassLoader(key: String) { + if (hasClassLoader(key)) { + // Make sure to close all classloader loaded resources before we let go of it. + // This fixes a Delete failure message on filesystem that keeps locks on opened jars; + // like Windows and NFS. + classLoaderCache.get(key).close() + classLoaderCache.invalidate(key) + log.info("Cleaned compiled cache($key)") + } else { + log.warn("No compiled cache($key) present to clean.") + } + } + + fun hasClassLoader(key: String): Boolean { + return classLoaderCache.asMap().containsKey(key) + } +} + +object BluePrintClassLoader : CacheLoader<String, URLClassLoader>() { + + val log = logger(BluePrintClassLoader::class) + + override fun load(key: String): URLClassLoader { + log.info("loading compiled cache($key)") + val keyPath = normalizedFile(key) + if (!keyPath.exists()) { + throw BluePrintException("failed to load cache($key), missing files.") + } + val urls = arrayListOf<URL>() + keyPath.walkTopDown() + .filter { it.name.endsWith("cba-kts.jar") } + .forEach { + log.debug("Adding (${it.absolutePath}) to cache($key)") + urls.add(it.toURI().toURL()) + } + return URLClassLoader(urls.toTypedArray(), this.javaClass.classLoader) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt new file mode 100644 index 000000000..f3eb1a2b9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt @@ -0,0 +1,82 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core.scripts + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintScriptsService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import java.util.ArrayList + +open class BluePrintScriptsServiceImpl : BluePrintScriptsService { + + val log = logger(BluePrintScriptsServiceImpl::class) + + override suspend fun <T> scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T { + val bluePrintCompileService = BluePrintCompileService() + return bluePrintCompileService.eval(bluePrintSourceCode, scriptClassName, null) + } + + override suspend fun <T> scriptInstance( + blueprintBasePath: String, + artifactName: String, + artifactVersion: String, + scriptClassName: String, + reCompile: Boolean + ): T { + + val sources: MutableList<String> = arrayListOf() + sources.add(normalizedPathName(blueprintBasePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR)) + + val scriptSource = BluePrintSourceCode() + scriptSource.blueprintKotlinSources = sources + scriptSource.moduleName = "$artifactName-$artifactVersion-cba-kts" + scriptSource.cacheKey = BluePrintFileUtils.compileCacheKey(blueprintBasePath) + scriptSource.targetJarFile = BluePrintFileUtils.compileJarFile(blueprintBasePath, artifactName, artifactVersion) + scriptSource.regenerate = reCompile + return scriptInstance(scriptSource, scriptClassName) + } + + override suspend fun <T> scriptInstance( + blueprintBasePath: String, + scriptClassName: String, + reCompile: Boolean + ): T { + val toscaMetaData = BluePrintMetadataUtils.toscaMetaData(blueprintBasePath) + checkNotNull(toscaMetaData.templateName) { "couldn't find 'Template-Name' key in TOSCA.meta" } + checkNotNull(toscaMetaData.templateVersion) { "couldn't find 'Template-Version' key in TOSCA.meta" } + return scriptInstance( + blueprintBasePath, toscaMetaData.templateName!!, toscaMetaData.templateVersion!!, + scriptClassName, reCompile + ) + } + + override suspend fun <T> scriptInstance(cacheKey: String, scriptClassName: String): T { + val args = ArrayList<Any?>() + return BluePrintCompileCache.classLoader(cacheKey).loadClass(scriptClassName).constructors + .single().newInstance(*args.toArray()) as T + } + + override suspend fun <T> scriptInstance(scriptClassName: String): T { + val args = ArrayList<Any?>() + return Thread.currentThread().contextClassLoader.loadClass(scriptClassName).constructors + .single().newInstance(*args.toArray()) as T + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt new file mode 100644 index 000000000..7d85963dc --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt @@ -0,0 +1,125 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition + +/** + * + * + * @author Brinda Santh + */ +class BluePrintChainedService { + + var bpc: BluePrintContext + + constructor(bpc: BluePrintContext) { + this.bpc = bpc + } + + fun nodeTypeChained(nodeTypeName: String): NodeType { + + val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName) + val attributes = hashMapOf<String, AttributeDefinition>() + val properties = hashMapOf<String, PropertyDefinition>() + val requirements = hashMapOf<String, RequirementDefinition>() + val capabilities = hashMapOf<String, CapabilityDefinition>() + val interfaces = hashMapOf<String, InterfaceDefinition>() + val artifacts = hashMapOf<String, ArtifactDefinition>() + + recNodeTypesChained(nodeTypeName).forEach { nodeType -> + + val subAttributes = bpc.nodeTypeByName(nodeType.id!!).attributes + if (subAttributes != null) { + attributes.putAll(subAttributes) + } + + val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties + if (subProperties != null) { + properties.putAll(subProperties) + } + + val subRequirements = bpc.nodeTypeByName(nodeType.id!!).requirements + if (subRequirements != null) { + requirements.putAll(subRequirements) + } + val subCapabilities = bpc.nodeTypeByName(nodeType.id!!).capabilities + if (subCapabilities != null) { + capabilities.putAll(subCapabilities) + } + val subInterfaces = bpc.nodeTypeByName(nodeType.id!!).interfaces + if (subInterfaces != null) { + interfaces.putAll(subInterfaces) + } + + val subArtifacts = bpc.nodeTypeByName(nodeType.id!!).artifacts + if (subArtifacts != null) { + artifacts.putAll(subArtifacts) + } + } + nodeType.attributes = attributes + nodeType.properties = properties + nodeType.requirements = requirements + nodeType.capabilities = capabilities + nodeType.interfaces = interfaces + nodeType.artifacts = artifacts + return nodeType + } + + fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? { + val nodeType = bpc.nodeTypeByName(nodeTypeName) + val properties = hashMapOf<String, PropertyDefinition>() + + recNodeTypesChained(nodeTypeName).forEach { nodeType -> + val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties + if (subProperties != null) { + properties.putAll(subProperties) + } + } + return properties + } + + private fun recNodeTypesChained(nodeTypeName: String, nodeTypes: MutableList<NodeType>? = arrayListOf()): MutableList<NodeType> { + val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName) + nodeType.id = nodeTypeName + val derivedFrom: String = nodeType.derivedFrom + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + recNodeTypesChained(derivedFrom, nodeTypes) + } + nodeTypes!!.add(nodeType) + return nodeTypes + } + + private fun recDataTypesChained(dataTypeName: String, dataTypes: MutableList<DataType>? = arrayListOf()): MutableList<DataType> { + val dataType: DataType = bpc.dataTypeByName(dataTypeName)!! + dataType.id = dataTypeName + val derivedFrom: String = dataType.derivedFrom + if (!BluePrintTypes.rootDataTypes().contains(derivedFrom)) { + recDataTypesChained(derivedFrom, dataTypes) + } + dataTypes!!.add(dataType) + return dataTypes + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt new file mode 100644 index 000000000..47cd62ea1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt @@ -0,0 +1,296 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +class BluePrintContext(val serviceTemplate: ServiceTemplate) { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + /** + * Blueprint CBA extracted file location + */ + var rootPath = "." + /** + * Root Definition file path + */ + var entryDefinition = "" + + /** Other definitions along with model, It may Resource Definition, Resource Assignments, Configurations etc..*/ + var otherDefinitions: MutableMap<String, Any> = hashMapOf() + + fun <T> otherDefinition(key: String) = otherDefinitions[key] as T + + fun checkOtherDefinition(key: String) = otherDefinitions.containsKey(key) + + fun imports(): List<ImportDefinition>? = serviceTemplate.imports + + fun dslDefinitions() = serviceTemplate.dslDefinitions + + val metadata: MutableMap<String, String>? = serviceTemplate.metadata + + fun dataTypes(): MutableMap<String, DataType>? = serviceTemplate.dataTypes + + fun inputs(): MutableMap<String, PropertyDefinition>? = serviceTemplate.topologyTemplate?.inputs + + fun blueprintJson(pretty: Boolean = false): String = print("json", pretty) + + private fun print(type: String? = "json", pretty: Boolean = false): String { + return JacksonUtils.getJson(serviceTemplate, pretty) + } + + fun name(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_NAME) + ?: throw BluePrintException("could't get template name from meta data") + + fun version(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_VERSION) + ?: throw BluePrintException("could't get template version from meta data") + + fun author(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_AUTHOR) + ?: throw BluePrintException("could't get template author from meta data") + + // Workflow + fun workflows(): MutableMap<String, Workflow>? = serviceTemplate.topologyTemplate?.workflows + + fun workflowByName(workFlowName: String): Workflow = workflows()?.get(workFlowName) + ?: throw BluePrintException("could't get workflow($workFlowName)") + + fun workflowInputs(workFlowName: String) = workflowByName(workFlowName).inputs + + fun workflowStepByName(workFlowName: String, stepName: String): Step { + return workflowByName(workFlowName).steps?.get(stepName) + ?: throw BluePrintException("could't get step($stepName) for workflow($workFlowName)") + } + + fun workflowStepNodeTemplate(workFlowName: String, stepName: String): String { + return workflowStepByName(workFlowName, stepName).target + ?: throw BluePrintException("could't get node template name for workflow($workFlowName)'s step($stepName)") + } + + fun workflowFirstStepNodeTemplate(workFlowName: String): String { + val firstStepName = workflowByName(workFlowName).steps?.keys?.first() + ?: throw BluePrintException("could't get first step for workflow($workFlowName)") + return workflowStepNodeTemplate(workFlowName, firstStepName) + } + + fun workflowStepFirstCallOperation(workFlowName: String, stepName: String): String { + return workflowStepByName(workFlowName, stepName).activities?.filter { it.callOperation != null }?.single()?.callOperation + ?: throw BluePrintException("couldn't get first callOperation for WorkFlow($workFlowName) ") + } + + // DSL + fun dslPropertiesByName(name: String): JsonNode = dslDefinitions()?.get(name) + ?: throw BluePrintException("couldn't get policy type for the dsl($name)") + + // Data Type + fun dataTypeByName(name: String): DataType? = dataTypes()?.get(name) + + // Artifact Type + fun artifactTypes(): MutableMap<String, ArtifactType>? = serviceTemplate.artifactTypes + + // Policy Types + fun policyTypes(): MutableMap<String, PolicyType>? = serviceTemplate.policyTypes + + fun policyTypeByName(policyName: String) = policyTypes()?.get(policyName) + ?: throw BluePrintException("could't get policy type for the name($policyName)") + + fun policyTypesDerivedFrom(name: String): MutableMap<String, PolicyType>? { + return policyTypes()?.filterValues { policyType -> policyType.derivedFrom == name }?.toMutableMap() + } + + fun policyTypesTarget(target: String): MutableMap<String, PolicyType>? { + return policyTypes()?.filterValues { it.targets.contains(target) }?.toMutableMap() + } + + fun policyTypesTargetNDerivedFrom(target: String, derivedFrom: String): MutableMap<String, PolicyType>? { + return policyTypesDerivedFrom(derivedFrom)?.filterValues { + it.targets.contains(target) + }?.toMutableMap() + } + + // Node Type Methods + fun nodeTypes(): MutableMap<String, NodeType>? = serviceTemplate.nodeTypes + + fun nodeTypeByName(name: String): NodeType = + nodeTypes()?.get(name) + ?: throw BluePrintException("could't get node type for the name($name)") + + fun nodeTypeDerivedFrom(name: String): MutableMap<String, NodeType>? { + return nodeTypes()?.filterValues { nodeType -> nodeType.derivedFrom == name }?.toMutableMap() + } + + fun nodeTypeInterface(nodeTypeName: String, interfaceName: String): InterfaceDefinition { + return nodeTypeByName(nodeTypeName).interfaces?.get(interfaceName) + ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName)") + } + + fun nodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, operationName: String): OperationDefinition { + return nodeTypeInterface(nodeTypeName, interfaceName).operations?.get(operationName) + ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName) operation definition($operationName)") + } + + fun interfaceNameForNodeType(nodeTypeName: String): String { + return nodeTypeByName(nodeTypeName).interfaces?.keys?.first() + ?: throw BluePrintException("could't get NodeType($nodeTypeName)'s first InterfaceDefinition name") + } + + fun nodeTypeInterfaceOperationInputs( + nodeTypeName: String, + interfaceName: String, + operationName: String + ): MutableMap<String, PropertyDefinition>? { + return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).inputs + } + + fun nodeTypeInterfaceOperationOutputs( + nodeTypeName: String, + interfaceName: String, + operationName: String + ): MutableMap<String, PropertyDefinition>? { + return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).outputs + } + + // Node Template Methods + fun nodeTemplates(): MutableMap<String, NodeTemplate>? = serviceTemplate.topologyTemplate?.nodeTemplates + + fun nodeTemplateByName(name: String): NodeTemplate = + nodeTemplates()?.get(name) ?: throw BluePrintException("could't get node template for the name($name)") + + fun nodeTemplateForNodeType(name: String): MutableMap<String, NodeTemplate>? { + return nodeTemplates()?.filterValues { nodeTemplate -> nodeTemplate.type == name }?.toMutableMap() + } + + fun nodeTemplateNodeType(nodeTemplateName: String): NodeType { + val nodeTemplateType: String = nodeTemplateByName(nodeTemplateName).type + return nodeTypeByName(nodeTemplateType) + } + + fun nodeTemplateProperty(nodeTemplateName: String, propertyName: String): Any? { + return nodeTemplateByName(nodeTemplateName).properties?.get(propertyName) + } + + fun nodeTemplateArtifacts(nodeTemplateName: String): MutableMap<String, ArtifactDefinition>? { + return nodeTemplateByName(nodeTemplateName).artifacts + } + + fun nodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition { + return nodeTemplateArtifacts(nodeTemplateName)?.get(artifactName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s ArtifactDefinition($artifactName)") + } + + fun nodeTemplateArtifactForArtifactType(nodeTemplateName: String, artifactType: String): ArtifactDefinition { + return nodeTemplateArtifacts(nodeTemplateName)?.filter { it.value.type == artifactType }?.map { it.value }?.get(0) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s Artifact Type($artifactType)") + } + + fun nodeTemplateFirstInterface(nodeTemplateName: String): InterfaceAssignment { + return nodeTemplateByName(nodeTemplateName).interfaces?.values?.first() + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment") + } + + fun nodeTemplateFirstInterfaceName(nodeTemplateName: String): String { + return nodeTemplateByName(nodeTemplateName).interfaces?.keys?.first() + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment name") + } + + fun nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName: String): String { + return nodeTemplateFirstInterface(nodeTemplateName).operations?.keys?.first() + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment's first OperationAssignment name") + } + + fun nodeTemplateOperationImplementation(nodeTemplateName: String, interfaceName: String, operationName: String): + Implementation? { + return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).implementation + } + + fun nodeTemplateInterfaceOperationInputs(nodeTemplateName: String, interfaceName: String, operationName: String): MutableMap<String, JsonNode>? { + return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).inputs + } + + fun nodeTemplateInterfaceOperationOutputs(nodeTemplateName: String, interfaceName: String, operationName: String): MutableMap<String, JsonNode>? { + return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).outputs + } + + fun nodeTemplateInterface(nodeTemplateName: String, interfaceName: String): InterfaceAssignment { + return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName)") + } + + fun nodeTemplateInterfaceOperation(nodeTemplateName: String, interfaceName: String, operationName: String): OperationAssignment { + return nodeTemplateInterface(nodeTemplateName, interfaceName).operations?.get(operationName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName) OperationAssignment($operationName)") + } + + fun nodeTemplateCapability(nodeTemplateName: String, capabilityName: String): CapabilityAssignment { + return nodeTemplateByName(nodeTemplateName).capabilities?.get(capabilityName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s CapabilityAssignment($capabilityName)") + } + + fun nodeTemplateRequirement(nodeTemplateName: String, requirementName: String): RequirementAssignment { + return nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first RequirementAssignment($requirementName)") + } + + fun nodeTemplateRequirementNode(nodeTemplateName: String, requirementName: String): NodeTemplate { + val filteredNodeTemplateName: String = nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)?.node + ?: throw BluePrintException("could't NodeTemplate for NodeTemplate's($nodeTemplateName) requirement's ($requirementName) ") + return nodeTemplateByName(filteredNodeTemplateName) + } + + fun nodeTemplateCapabilityProperty(nodeTemplateName: String, capabilityName: String, propertyName: String): Any? { + return nodeTemplateCapability(nodeTemplateName, capabilityName).properties?.get(propertyName) + } + + // Chained Functions + + fun nodeTypeChained(nodeTypeName: String): NodeType { + return BluePrintChainedService(this).nodeTypeChained(nodeTypeName) + } + + fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? { + return BluePrintChainedService(this).nodeTypeChainedProperties(nodeTypeName) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt new file mode 100644 index 000000000..df3bde1b4 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt @@ -0,0 +1,53 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.springframework.context.ApplicationContext +import kotlin.reflect.KClass + +/** + * Generic Bluepring Dependency Service, which will be used mainly in scripts. + * This will be initialised only once during the Application startup. + * Function modules, shall add their own dependency function names as an extension function. + * + * @author Brinda Santh + */ + +object BluePrintDependencyService { + + lateinit var applicationContext: ApplicationContext + + fun inject(applicationContext: ApplicationContext) { + BluePrintDependencyService.applicationContext = applicationContext + } + + inline fun <reified T> instance(name: String): T { + return applicationContext.getBean(name) as? T + ?: throw BluePrintProcessorException("failed to get instance($name)") + } + + inline fun <reified T> instance(type: Class<T>): T { + return applicationContext.getBean(type) + ?: throw BluePrintProcessorException("failed to get instance($type)") + } + + inline fun <reified T> instance(type: KClass<*>): T { + return applicationContext.getBean(type.java) as? T + ?: throw BluePrintProcessorException("failed to get instance($type)") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt new file mode 100644 index 000000000..6a3c64650 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt @@ -0,0 +1,230 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.ObjectNode +import com.fasterxml.jackson.databind.node.TextNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.DSLExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData +import org.onap.ccsdk.cds.controllerblueprints.core.data.InputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +object BluePrintExpressionService { + + val log = LoggerFactory.getLogger(this::class.toString()) + + @JvmStatic + fun checkContainsExpression(propertyAssignmentNode: JsonNode): Boolean { + val json = propertyAssignmentNode.toString() + // FIXME("Check if any Optimisation needed") + return (json.contains(BluePrintConstants.EXPRESSION_GET_INPUT) || + json.contains(BluePrintConstants.EXPRESSION_GET_ATTRIBUTE) || + json.contains(BluePrintConstants.EXPRESSION_GET_PROPERTY)) + } + + @JvmStatic + fun getExpressionData(propertyAssignmentNode: JsonNode): ExpressionData { + log.trace("Assignment Data/Expression : {}", propertyAssignmentNode) + val expressionData = ExpressionData(valueNode = propertyAssignmentNode) + if (propertyAssignmentNode is ObjectNode) { + val commands: Set<String> = propertyAssignmentNode.fieldNames().asSequence().toList().intersect(BluePrintTypes.validCommands()) + if (commands.isNotEmpty()) { + expressionData.isExpression = true + expressionData.command = commands.first() + expressionData.expressionNode = propertyAssignmentNode + + when (expressionData.command) { + BluePrintConstants.EXPRESSION_GET_INPUT -> { + expressionData.inputExpression = populateInputExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_ATTRIBUTE -> { + expressionData.attributeExpression = populateAttributeExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_PROPERTY -> { + expressionData.propertyExpression = populatePropertyExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> { + expressionData.operationOutputExpression = populateOperationOutputExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_ARTIFACT -> { + expressionData.artifactExpression = populateArtifactExpression(propertyAssignmentNode) + } + } + } + } else if (propertyAssignmentNode is TextNode && + propertyAssignmentNode.textValue().startsWith(BluePrintConstants.EXPRESSION_DSL_REFERENCE) + ) { + expressionData.isExpression = true + expressionData.command = BluePrintConstants.EXPRESSION_DSL_REFERENCE + expressionData.dslExpression = populateDSLExpression(propertyAssignmentNode) + } + return expressionData + } + + @JvmStatic + fun populateDSLExpression(jsonNode: TextNode): DSLExpression { + return DSLExpression( + propertyName = jsonNode.textValue() + .removePrefix(BluePrintConstants.EXPRESSION_DSL_REFERENCE) + ) + } + + @JvmStatic + fun populateInputExpression(jsonNode: JsonNode): InputExpression { + return InputExpression(propertyName = jsonNode.first().textValue()) + } + + @JvmStatic + fun populatePropertyExpression(jsonNode: JsonNode): PropertyExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + check(arrayNode.size() >= 2) { + throw BluePrintException( + String.format( + "missing property expression, " + + "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, " + + "<nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] , but present {}", jsonNode + ) + ) + } + var reqOrCapEntityName: String? = null + var propertyName = "" + var subProperty: String? = null + when { + arrayNode.size() == 2 -> propertyName = arrayNode[1].textValue() + arrayNode.size() == 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + propertyName = arrayNode[2].textValue() + } + arrayNode.size() > 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + propertyName = arrayNode[2].textValue() + val propertyPaths: List<String> = arrayNode.filterIndexed { index, _ -> + index >= 3 + }.map { it.textValue() } + subProperty = propertyPaths.joinToString("/") + } + } + + return PropertyExpression( + modelableEntityName = arrayNode[0].asText(), + reqOrCapEntityName = reqOrCapEntityName, + propertyName = propertyName, + subPropertyName = subProperty + ) + } + + @JvmStatic + fun populateAttributeExpression(jsonNode: JsonNode): AttributeExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + check(arrayNode.size() >= 2) { + throw BluePrintException( + String.format( + "missing attribute expression, " + + "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <attribute_name>," + + " <nested_attribute_name_or_index_1>, ..., <nested_attribute_name_or_index_n> ] , but present {}", jsonNode + ) + ) + } + + var reqOrCapEntityName: String? = null + var attributeName = "" + var subAttributeName: String? = null + when { + arrayNode.size() == 2 -> attributeName = arrayNode[1].textValue() + arrayNode.size() == 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + attributeName = arrayNode[2].textValue() + } + arrayNode.size() > 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + attributeName = arrayNode[2].textValue() + val propertyPaths: List<String> = arrayNode.filterIndexed { index, _ -> + index >= 3 + }.map { it.textValue() } + subAttributeName = propertyPaths.joinToString("/") + } + } + return AttributeExpression( + modelableEntityName = arrayNode[0].asText(), + reqOrCapEntityName = reqOrCapEntityName, + attributeName = attributeName, + subAttributeName = subAttributeName + ) + } + + @JvmStatic + fun populateOperationOutputExpression(jsonNode: JsonNode): OperationOutputExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + + check(arrayNode.size() >= 4) { + throw BluePrintException( + String.format( + "missing operation output expression, " + + "it should be (<modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>) , but present {}", + jsonNode + ) + ) + } + + var subPropertyName: String? = null + if (arrayNode.size() == 5) + subPropertyName = arrayNode[4].asText() + + return OperationOutputExpression( + modelableEntityName = arrayNode[0].asText(), + interfaceName = arrayNode[1].asText(), + operationName = arrayNode[2].asText(), + propertyName = arrayNode[3].asText(), + subPropertyName = subPropertyName + ) + } + + @JvmStatic + fun populateArtifactExpression(jsonNode: JsonNode): ArtifactExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + + check(arrayNode.size() >= 2) { + throw BluePrintException( + String.format( + "missing artifact expression, " + + "it should be [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ] , but present {}", jsonNode + ) + ) + } + return ArtifactExpression( + modelableEntityName = arrayNode[0].asText(), + artifactName = arrayNode[1].asText(), + location = arrayNode[2]?.asText() ?: "LOCAL_FILE", + remove = arrayNode[3]?.asBoolean() ?: false + ) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt new file mode 100644 index 000000000..24b7e261c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt @@ -0,0 +1,94 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.utils.ServiceTemplateUtils +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import java.io.File +import java.net.URL +import java.net.URLDecoder +import java.nio.charset.Charset + +class BluePrintImportService(private val parentServiceTemplate: ServiceTemplate, private val blueprintBasePath: String) { + companion object { + private const val PARENT_SERVICE_TEMPLATE: String = "parent" + } + + private val log: Logger = LoggerFactory.getLogger(this::class.toString()) + + private var importServiceTemplateMap: MutableMap<String, ServiceTemplate> = hashMapOf() + + suspend fun getImportResolvedServiceTemplate(): ServiceTemplate { + // Populate Imported Service Templates + traverseSchema(PARENT_SERVICE_TEMPLATE, parentServiceTemplate) + + importServiceTemplateMap.forEach { key, serviceTemplate -> + ServiceTemplateUtils.merge(parentServiceTemplate, serviceTemplate) + log.debug("merged service template $key") + } + return parentServiceTemplate + } + + private suspend fun traverseSchema(key: String, serviceTemplate: ServiceTemplate) { + if (key != PARENT_SERVICE_TEMPLATE) { + importServiceTemplateMap[key] = serviceTemplate + } + val imports: List<ImportDefinition>? = serviceTemplate.imports + + imports?.let { + serviceTemplate.imports?.forEach { importDefinition -> + val childServiceTemplate = resolveImportDefinition(importDefinition) + val keyName: String = importDefinition.file + traverseSchema(keyName, childServiceTemplate) + } + } + } + + private suspend fun resolveImportDefinition(importDefinition: ImportDefinition): ServiceTemplate { + var serviceTemplate: ServiceTemplate? = null + val file: String = importDefinition.file + val decodedSystemId: String = URLDecoder.decode(file, Charset.defaultCharset().toString()) + log.trace("file ({}), decodedSystemId ({}) ", file, decodedSystemId) + try { + if (decodedSystemId.startsWith("http", true) || + decodedSystemId.startsWith("https", true) + ) { + val givenUrl: String = URL(decodedSystemId).toString() + val systemUrl: String = File(".").toURI().toURL().toString() + log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl) + if (givenUrl.startsWith(systemUrl)) { + } + } else { + if (!decodedSystemId.startsWith("/")) { + importDefinition.file = StringBuilder().append(blueprintBasePath).append(File.separator).append(file).toString() + } + serviceTemplate = ServiceTemplateUtils.getServiceTemplate(importDefinition.file) + } + } catch (e: Exception) { + throw BluePrintException("failed to populate service template for ${importDefinition.file} original error: ${e.message}", e) + } + if (serviceTemplate == null) { + throw BluePrintException("failed to populate service template for : ${importDefinition.file}") + } + return serviceTemplate + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt new file mode 100644 index 000000000..fdc348bf7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.service + +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import com.hubspot.jinjava.Jinjava +import com.hubspot.jinjava.JinjavaConfig +import com.hubspot.jinjava.interpret.JinjavaInterpreter +import com.hubspot.jinjava.loader.ResourceLocator +import com.hubspot.jinjava.loader.ResourceNotFoundException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode +import java.io.IOException +import java.nio.charset.Charset +import java.nio.file.Files.readAllBytes +import java.nio.file.Paths + +object BluePrintJinjaTemplateService { + + /** + * To enable inheritance within CBA, we need Jinja runtime to know where to load the templates. + */ + class BlueprintRelatedTemplateLocator( + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val artifactName: String, + private val artifactVersion: String + ) : ResourceLocator { + + @Throws(IOException::class) + override fun getString(fullName: String, encoding: Charset, interpreter: JinjavaInterpreter): String { + try { + val deployFile = + normalizedPathName( + bluePrintLoadConfiguration.blueprintDeployPath, + artifactName, + artifactVersion, + fullName + ) + + return String(readAllBytes(Paths.get(deployFile))) + } catch (var5: IllegalArgumentException) { + throw ResourceNotFoundException("Couldn't find resource: $fullName") + } + } + } + + fun generateContent( + template: String, + json: String, + ignoreJsonNull: Boolean, + additionalContext: MutableMap<String, Any>, + bluePrintLoadConfiguration: BluePrintLoadConfiguration, + artifactName: String, + artifactVersion: String + ): String { + + return generateContent( + template, + json, + ignoreJsonNull, + additionalContext, + BlueprintRelatedTemplateLocator(bluePrintLoadConfiguration, artifactName, artifactVersion) + ) + } + + fun generateContent( + template: String, + json: String, + ignoreJsonNull: Boolean, + additionalContext: MutableMap<String, Any>, + resourceLocator: ResourceLocator? = null + ): String { + val jinJava = Jinjava(JinjavaConfig()) + if (resourceLocator != null) { + jinJava.resourceLocator = resourceLocator + } + + val mapper = ObjectMapper() + val nodeFactory = BluePrintJsonNodeFactory() + mapper.nodeFactory = nodeFactory + + // Add the JSON Data to the context + if (json.isNotEmpty()) { + val jsonNode = mapper.readValue<JsonNode>(json, JsonNode::class.java) + ?: throw BluePrintProcessorException("couldn't get json node from json") + if (ignoreJsonNull) { + jsonNode.removeNullNode() + } + + val jsonMap: Map<String, Any> = mapper.readValue(json, object : TypeReference<Map<String, Any>>() {}) + additionalContext.putAll(jsonMap) + } + + return jinJava.render(template, additionalContext) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt new file mode 100644 index 000000000..1f71495a3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt @@ -0,0 +1,76 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory + +open class BluePrintRepoFileService(modelTypePath: String) : BluePrintRepoService { + + private val log = LoggerFactory.getLogger(BluePrintRepoFileService::class.toString()) + + private val dataTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + private val nodeTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE) + private val artifactTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE) + private val capabilityTypePath = + modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE) + private val relationshipTypePath = + modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE) + private val extension = ".json" + + override fun getDataType(dataTypeName: String): DataType { + val fileName = dataTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(dataTypeName).plus(extension) + return getModelType(fileName, DataType::class.java) + } + + override fun getNodeType(nodeTypeName: String): NodeType { + val fileName = nodeTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(nodeTypeName).plus(extension) + return getModelType(fileName, NodeType::class.java) + } + + override fun getArtifactType(artifactTypeName: String): ArtifactType { + val fileName = artifactTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(artifactTypeName).plus(extension) + return getModelType(fileName, ArtifactType::class.java) + } + + override fun getRelationshipType(relationshipTypeName: String): RelationshipType { + val fileName = relationshipTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(relationshipTypeName).plus(extension) + return getModelType(fileName, RelationshipType::class.java) + } + + override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { + val fileName = capabilityTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(capabilityDefinitionName).plus(extension) + return getModelType(fileName, CapabilityDefinition::class.java) + } + + private fun <T> getModelType(fileName: String, valueType: Class<T>): T { + return JacksonUtils.readValueFromFile(fileName, valueType) + ?: throw BluePrintException("couldn't get file($fileName) for type(${valueType.name}") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt new file mode 100644 index 000000000..a6d2de476 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt @@ -0,0 +1,649 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing +import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.slf4j.LoggerFactory +import java.io.File + +interface BluePrintRuntimeService<T> { + + fun id(): String + + fun bluePrintContext(): BluePrintContext + + fun getExecutionContext(): T + + fun setExecutionContext(executionContext: T) + + fun put(key: String, value: JsonNode) + + fun get(key: String): JsonNode? + + fun check(key: String): Boolean + + fun cleanRuntime() + + fun getAsString(key: String): String? + + fun getAsBoolean(key: String): Boolean? + + fun getAsInt(key: String): Int? + + fun getAsDouble(key: String): Double? + + fun getBluePrintError(): BluePrintError + + fun setBluePrintError(bluePrintError: BluePrintError) + + fun loadEnvironments(type: String, fileName: String) + + fun resolveNodeTemplatePropertyAssignments( + nodeTemplateName: String, + propertyDefinitions: MutableMap<String, PropertyDefinition>, + propertyAssignments: MutableMap<String, JsonNode> + ): MutableMap<String, JsonNode> + + fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>): + MutableMap<String, JsonNode> + + fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>): + MutableMap<String, JsonNode> + + fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap<String, JsonNode> + + fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): MutableMap<String, + JsonNode> + + fun resolveNodeTemplateInterfaceOperationInputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap<String, JsonNode> + + fun resolveNodeTemplateInterfaceOperationOutputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap<String, JsonNode> + + fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String + + fun resolveNodeTemplateArtifactDefinition(nodeTemplateName: String, artifactName: String): ArtifactDefinition + + fun resolveDSLExpression(dslPropertyName: String): JsonNode + + fun setInputValue(propertyName: String, value: JsonNode) + + fun setWorkflowInputValue( + workflowName: String, + propertyName: String, + propertyDefinition: PropertyDefinition, + value: JsonNode + ) + + fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode) + + fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode) + + fun setNodeTemplateOperationPropertyValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) + + fun setNodeTemplateOperationInputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) + + fun setNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) + + fun getInputValue(propertyName: String): JsonNode + + fun getNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String + ): JsonNode + + fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode? + + fun getNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String): JsonNode? + + fun assignInputs(jsonNode: JsonNode) + + fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) + + fun resolveWorkflowOutputs(workflowName: String): MutableMap<String, JsonNode> + + fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List<String>): JsonNode +} + +/** + * + * + * @author Brinda Santh + */ +open class DefaultBluePrintRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) : + BluePrintRuntimeService<MutableMap<String, JsonNode>> { + + @Transient + private val log = LoggerFactory.getLogger(BluePrintRuntimeService::class.toString()) + + private var store: MutableMap<String, JsonNode> = hashMapOf() + + private var bluePrintError = BluePrintError() + + init { + /** + * Load Blueprint Environments Properties + */ + val absoluteEnvFilePath = bluePrintContext.rootPath.plus(File.separator) + .plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR) + loadEnvironments(BluePrintConstants.PROPERTY_BPP, absoluteEnvFilePath) + } + + override fun id(): String { + return id + } + + override fun bluePrintContext(): BluePrintContext { + return bluePrintContext + } + + override fun getExecutionContext(): MutableMap<String, JsonNode> { + return store + } + + @Suppress("UNCHECKED_CAST") + override fun setExecutionContext(executionContext: MutableMap<String, JsonNode>) { + this.store = executionContext + } + + override fun put(key: String, value: JsonNode) { + store[key] = value + } + + override fun get(key: String): JsonNode { + return store[key] ?: throw BluePrintProcessorException("failed to get execution property($key)") + } + + override fun check(key: String): Boolean { + return store.containsKey(key) + } + + override fun cleanRuntime() { + store.clear() + } + + private fun getJsonNode(key: String): JsonNode { + return get(key) + } + + override fun getAsString(key: String): String? { + return get(key).asText() + } + + override fun getAsBoolean(key: String): Boolean? { + return get(key).asBoolean() + } + + override fun getAsInt(key: String): Int? { + return get(key).asInt() + } + + override fun getAsDouble(key: String): Double? { + return get(key).asDouble() + } + + override fun getBluePrintError(): BluePrintError { + return this.bluePrintError + } + + override fun setBluePrintError(bluePrintError: BluePrintError) { + this.bluePrintError = bluePrintError + } + + override fun loadEnvironments(type: String, fileName: String) { + BluePrintMetadataUtils.environmentFileProperties(fileName).forEach { key, value -> + setNodeTemplateAttributeValue(type, key.toString(), value.asJsonType()) + } + } + + /** + * Resolve any property assignments for the node + */ + override fun resolveNodeTemplatePropertyAssignments( + nodeTemplateName: String, + propertyDefinitions: MutableMap<String, PropertyDefinition>, + propertyAssignments: MutableMap<String, JsonNode> + ): + MutableMap<String, JsonNode> { + + val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf() + + propertyDefinitions.forEach { (nodeTypePropertyName, nodeTypeProperty) -> + // Get the Express or Value for the Node Template + val propertyAssignment: JsonNode? = propertyAssignments[nodeTypePropertyName] + + var resolvedValue: JsonNode = NullNode.getInstance() + if (propertyAssignment != null) { + // Resolve the Expressing + val propertyAssignmentExpression = PropertyAssignmentService(this) + resolvedValue = propertyAssignmentExpression.resolveAssignmentExpression( + nodeTemplateName, nodeTypePropertyName, propertyAssignment + ) + } + + // Set default value if null + if (resolvedValue is NullNode) { + nodeTypeProperty.defaultValue?.let { resolvedValue = nodeTypeProperty.defaultValue!! } + } + + // Set for Return of method + propertyAssignmentValue[nodeTypePropertyName] = resolvedValue + } + return propertyAssignmentValue + } + + override fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>): + MutableMap<String, JsonNode> { + val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf() + + propertyDefinitions.forEach { propertyName, propertyDefinition -> + val propertyAssignmentExpression = PropertyAssignmentService(this) + val expression = propertyDefinition.value ?: propertyDefinition.defaultValue + if (expression != null) { + propertyAssignmentValue[propertyName] = + propertyAssignmentExpression.resolveAssignmentExpression(name, propertyName, expression) + } + } + return propertyAssignmentValue + } + + override fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>): + MutableMap<String, JsonNode> { + val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf() + + propertyAssignments.forEach { (propertyName, propertyExpression) -> + val propertyAssignmentExpression = PropertyAssignmentService(this) + propertyAssignmentValue[propertyName] = + propertyAssignmentExpression.resolveAssignmentExpression(name, propertyName, propertyExpression) + } + return propertyAssignmentValue + } + + override fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap<String, JsonNode> { + log.info("resolveNodeTemplatePropertyValues for node template ({})", nodeTemplateName) + + val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + val propertyAssignments: MutableMap<String, JsonNode> = nodeTemplate.properties!! + + // Get the Node Type Definitions + val nodeTypePropertiesDefinitions: MutableMap<String, PropertyDefinition> = bluePrintContext + .nodeTypeChainedProperties(nodeTemplate.type)!! + + /** + * Resolve the NodeTemplate Property Assignment Values. + */ + return resolveNodeTemplatePropertyAssignments(nodeTemplateName, nodeTypePropertiesDefinitions, propertyAssignments) + } + + override fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): + MutableMap<String, JsonNode> { + log.info("resolveNodeTemplateCapabilityProperties for node template($nodeTemplateName) capability($capabilityName)") + val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + val propertyAssignments = nodeTemplate.capabilities?.get(capabilityName)?.properties ?: hashMapOf() + + val propertyDefinitions = bluePrintContext.nodeTemplateNodeType(nodeTemplateName) + .capabilities?.get(capabilityName)?.properties ?: hashMapOf() + + /** + * Resolve the Capability Property Assignment Values. + */ + return resolveNodeTemplatePropertyAssignments(nodeTemplateName, propertyDefinitions, propertyAssignments) + } + + override fun resolveNodeTemplateInterfaceOperationInputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap<String, JsonNode> { + log.info( + "resolveNodeTemplateInterfaceOperationInputs for node template ($nodeTemplateName), " + + "interface name($interfaceName), operationName($operationName)" + ) + + val propertyAssignments: MutableMap<String, JsonNode> = + bluePrintContext.nodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName) + ?: hashMapOf() + + val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type + + val nodeTypeInterfaceOperationInputs: MutableMap<String, PropertyDefinition> = + bluePrintContext.nodeTypeInterfaceOperationInputs(nodeTypeName, interfaceName, operationName) + ?: hashMapOf() + + log.info("input definition for node template ($nodeTemplateName), values ($propertyAssignments)") + + /** + * Resolve the Property Input Assignment Values. + */ + return resolveNodeTemplatePropertyAssignments(nodeTemplateName, nodeTypeInterfaceOperationInputs, propertyAssignments) + } + + override fun resolveNodeTemplateInterfaceOperationOutputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap<String, JsonNode> { + log.info( + "resolveNodeTemplateInterfaceOperationOutputs for node template ($nodeTemplateName),interface name " + + "($interfaceName), operationName($operationName)" + ) + + val propertyAssignments: MutableMap<String, JsonNode> = + bluePrintContext.nodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName) + ?: hashMapOf() + + val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type + + val nodeTypeInterfaceOperationOutputs: MutableMap<String, PropertyDefinition> = + bluePrintContext.nodeTypeInterfaceOperationOutputs(nodeTypeName, interfaceName, operationName) + ?: hashMapOf() + /** + * Resolve the Property Output Assignment Values. + */ + val propertyAssignmentValue = + resolveNodeTemplatePropertyAssignments(nodeTemplateName, nodeTypeInterfaceOperationOutputs, propertyAssignments) + + // Store operation output values into context + propertyAssignmentValue.forEach { (key, value) -> + setNodeTemplateOperationOutputValue(nodeTemplateName, interfaceName, operationName, key, value) + } + return propertyAssignmentValue + } + + override fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String { + val artifactDefinition: ArtifactDefinition = + resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) + val propertyAssignmentExpression = PropertyAssignmentService(this) + return propertyAssignmentExpression.artifactContent(artifactDefinition) + } + + override fun resolveNodeTemplateArtifactDefinition( + nodeTemplateName: String, + artifactName: String + ): ArtifactDefinition { + val nodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + return nodeTemplate.artifacts?.get(artifactName) + ?: throw BluePrintProcessorException( + "failed to get artifact definition($artifactName) from the node template" + ) + } + + /** + * Read the DSL Property reference, If there is any expression, then resolve those expression and return as Json + * Type + */ + override fun resolveDSLExpression(dslPropertyName: String): JsonNode { + val propertyAssignments = bluePrintContext.dslPropertiesByName(dslPropertyName) + return if (BluePrintExpressionService.checkContainsExpression(propertyAssignments) && + propertyAssignments is ObjectNode + ) { + + val rootKeyMap = propertyAssignments.rootFieldsToMap() + val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf() + rootKeyMap.forEach { (propertyName, propertyValue) -> + val propertyAssignmentExpression = PropertyAssignmentService(this) + propertyAssignmentValue[propertyName] = propertyAssignmentExpression + .resolveAssignmentExpression("DSL", propertyName, propertyValue) + } + propertyAssignmentValue.asJsonNode() + } else { + propertyAssignments + } + } + + override fun setInputValue(propertyName: String, value: JsonNode) { + val path = """${BluePrintConstants.PATH_INPUTS}${BluePrintConstants.PATH_DIVIDER}$propertyName""" + log.trace("setting input path ({}), values ({})", path, value) + put(path, value) + } + + override fun setWorkflowInputValue( + workflowName: String, + propertyName: String, + propertyDefinition: PropertyDefinition, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_WORKFLOWS) + .append(BluePrintConstants.PATH_DIVIDER).append(workflowName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).append(attributeName).toString() + put(path, value) + } + + override fun setNodeTemplateOperationPropertyValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + log.trace("setting operation property path ({}), values ({})", path, value) + put(path, value) + } + + override fun setNodeTemplateOperationInputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun setNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OUTPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun getInputValue(propertyName: String): JsonNode { + val path = StringBuilder(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String + ): JsonNode { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OUTPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String): JsonNode { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).append(attributeName).toString() + return getJsonNode(path) + } + + override fun assignInputs(jsonNode: JsonNode) { + log.info("assignInputs from input JSON ({})", jsonNode.toString()) + bluePrintContext.inputs()?.forEach { propertyName, property -> + val valueNode: JsonNode = jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName) + ?: property.defaultValue + ?: NullNode.getInstance() + setInputValue(propertyName, valueNode) + } + } + + override fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) { + log.info("For workflow ($workflowName) driving input data from ($jsonNode)") + val dynamicInputPropertiesName = "$workflowName-properties" + + bluePrintContext.workflowByName(workflowName).inputs + ?.forEach { propertyName, property -> + if (propertyName != dynamicInputPropertiesName) { + val valueNode: JsonNode = + jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing() + ?: property.defaultValue + ?: NullNode.getInstance() + log.trace("Setting input data - attribute:($propertyName) value:($valueNode)") + setInputValue(propertyName, valueNode) + } + } + // Load Dynamic data Types + jsonNode.get(dynamicInputPropertiesName)?.let { + bluePrintContext.dataTypeByName("dt-$dynamicInputPropertiesName")?.properties + ?.forEach { propertyName, property -> + val valueNode: JsonNode = + it.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing() + ?: property.defaultValue + ?: NullNode.getInstance() + log.trace("Setting input data - attribute:($propertyName) value:($valueNode)") + setInputValue(propertyName, valueNode) + } + } + } + + override fun resolveWorkflowOutputs(workflowName: String): MutableMap<String, JsonNode> { + log.info("resolveWorkflowOutputs for workflow($workflowName)") + val outputs = bluePrintContext.workflowByName(workflowName).outputs ?: mutableMapOf() + return resolvePropertyDefinitions("WORKFLOW", outputs) + } + + override fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List<String>): JsonNode { + + val jsonNode: ObjectNode = jacksonObjectMapper().createObjectNode() + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).toString() + store.keys.filter { + it.startsWith(path) + }.map { + val key = it.replace(path, "") + if (keys.contains(key)) { + val value = store[it] as JsonNode + jsonNode.set(key, value) + } + } + return jsonNode + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt new file mode 100644 index 000000000..db733bda1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt @@ -0,0 +1,65 @@ +/* + * Copyright © 2019 IBM, Bell Canada + * + * 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.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTemplateService +import org.springframework.stereotype.Service + +@Service +class BluePrintTemplateService(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration) : + BlueprintTemplateService { + + override suspend fun generateContent( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + nodeTemplateName: String, + artifactName: String, + jsonData: String, + ignoreJsonNull: Boolean, + additionalContext: MutableMap<String, Any> + ): String { + + val artifactDefinition = + bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) + val templateType = artifactDefinition.type + val template = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) + + return when (templateType) { + BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME -> { + BluePrintJinjaTemplateService.generateContent( + template, + jsonData, + ignoreJsonNull, + additionalContext, + bluePrintLoadConfiguration, + bluePrintRuntimeService.bluePrintContext().name(), + bluePrintRuntimeService.bluePrintContext().version() + ) + } + BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME -> { + BluePrintVelocityTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext) + } + else -> { + throw BluePrintProcessorException( + "Unknown Artifact type, expecting ${BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME}" + + "or ${BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME}" + ) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt new file mode 100644 index 000000000..f492c2bc6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt @@ -0,0 +1,706 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.google.common.base.Preconditions +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.format +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import java.io.Serializable + +/** + * + * + * @author Brinda Santh + */ +interface BluePrintValidatorService : Serializable { + + @Throws(BluePrintException::class) + fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap<String, Any>) + + @Throws(BluePrintException::class) + fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap<String, Any>) +} + +@Deprecated("Decomposed implementation moved to blueprint-validation module") +open class BluePrintValidatorDefaultService : BluePrintValidatorService { + + val log = LoggerFactory.getLogger(BluePrintValidatorDefaultService::class.toString()) + + lateinit var bluePrintContext: BluePrintContext + lateinit var serviceTemplate: ServiceTemplate + lateinit var properties: MutableMap<String, Any> + var message: StringBuilder = StringBuilder() + private val separator: String = BluePrintConstants.PATH_DIVIDER + var paths: MutableList<String> = arrayListOf() + + @Throws(BluePrintException::class) + override fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap<String, Any>) { + validateBlueprint(bluePrintContext.serviceTemplate, properties) + } + + @Throws(BluePrintException::class) + override fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap<String, Any>) { + this.bluePrintContext = BluePrintContext(serviceTemplate) + this.serviceTemplate = serviceTemplate + this.properties = properties + try { + message.appendln("-> Config Blueprint") + serviceTemplate.metadata?.let { validateMetadata(serviceTemplate.metadata!!) } + serviceTemplate.artifactTypes?.let { validateArtifactTypes(serviceTemplate.artifactTypes!!) } + serviceTemplate.dataTypes?.let { validateDataTypes(serviceTemplate.dataTypes!!) } + serviceTemplate.nodeTypes?.let { validateNodeTypes(serviceTemplate.nodeTypes!!) } + serviceTemplate.topologyTemplate?.let { validateTopologyTemplate(serviceTemplate.topologyTemplate!!) } + } catch (e: Exception) { + log.error("validation failed in the path : {}", paths.joinToString(separator), e) + log.error("validation trace message :{} ", message) + throw BluePrintException( + e, + format("failed to validate blueprint on path ({}) with message {}", paths.joinToString(separator), e.message) + ) + } + } + + @Throws(BluePrintException::class) + open fun validateMetadata(metaDataMap: MutableMap<String, String>) { + paths.add("metadata") + + val templateName = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_NAME] + val templateVersion = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_VERSION] + val templateTags = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_TAGS] + val templateAuthor = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] + + Preconditions.checkArgument(StringUtils.isNotBlank(templateName), "failed to get template name metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateVersion), "failed to get template version metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateTags), "failed to get template tags metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateAuthor), "failed to get template author metadata") + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateArtifactTypes(artifactTypes: MutableMap<String, ArtifactType>) { + paths.add("artifact_types") + artifactTypes.forEach { artifactName, artifactType -> + paths.add(artifactName) + message.appendln("--> Artifact Type :" + paths.joinToString(separator)) + artifactType.properties?.let { validatePropertyDefinitions(artifactType.properties!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateDataTypes(dataTypes: MutableMap<String, DataType>) { + paths.add("dataTypes") + dataTypes.forEach { dataTypeName, dataType -> + paths.add(dataTypeName) + message.appendln("--> DataType :" + paths.joinToString(separator)) + dataType.properties?.let { validatePropertyDefinitions(dataType.properties!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeTypes(nodeTypes: MutableMap<String, NodeType>) { + paths.add("nodeTypes") + nodeTypes.forEach { nodeTypeName, nodeType -> + // Validate Single Node Type + validateNodeType(nodeTypeName, nodeType) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeType(nodeTypeName: String, nodeType: NodeType) { + paths.add(nodeTypeName) + message.appendln("--> Node Type :" + paths.joinToString(separator)) + val derivedFrom: String = nodeType.derivedFrom + // Check Derived From + checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom) + + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + serviceTemplate.nodeTypes?.get(derivedFrom) + ?: throw BluePrintException( + format( + "Failed to get derivedFrom NodeType({})'s for NodeType({}) ", + derivedFrom, nodeTypeName + ) + ) + } + + nodeType.properties?.let { validatePropertyDefinitions(nodeType.properties!!) } + nodeType.capabilities?.let { validateCapabilityDefinitions(nodeTypeName, nodeType) } + nodeType.requirements?.let { validateRequirementDefinitions(nodeTypeName, nodeType) } + nodeType.interfaces?.let { validateInterfaceDefinitions(nodeType.interfaces!!) } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun checkValidNodeTypesDerivedFrom(nodeTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validNodeTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get node type ({})'s derivedFrom({}) definition ", nodeTypeName, derivedFrom)) + } + } + + @Throws(BluePrintException::class) + open fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) { + paths.add("topology") + message.appendln("--> Topology Template") + topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) } + topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) } + topologyTemplate.workflows?.let { validateWorkFlows(topologyTemplate.workflows!!) } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateInputs(inputs: MutableMap<String, PropertyDefinition>) { + paths.add("inputs") + message.appendln("---> Input :" + paths.joinToString(separator)) + validatePropertyDefinitions(inputs) + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeTemplates(nodeTemplates: MutableMap<String, NodeTemplate>) { + paths.add("nodeTemplates") + nodeTemplates.forEach { nodeTemplateName, nodeTemplate -> + validateNodeTemplate(nodeTemplateName, nodeTemplate) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeTemplate(nodeTemplateName: String, nodeTemplate: NodeTemplate) { + paths.add(nodeTemplateName) + message.appendln("---> NodeTemplate :" + paths.joinToString(separator)) + val type: String = nodeTemplate.type + + val nodeType: NodeType = serviceTemplate.nodeTypes?.get(type) + ?: throw BluePrintException(format("Failed to get NodeType({}) definition for NodeTemplate({})", type, nodeTemplateName)) + + nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) } + nodeTemplate.properties?.let { validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) } + nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeType, nodeTemplateName, nodeTemplate) } + nodeTemplate.requirements?.let { validateRequirementAssignments(nodeType, nodeTemplateName, nodeTemplate) } + nodeTemplate.interfaces?.let { validateInterfaceAssignments(nodeType, nodeTemplateName, nodeTemplate) } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateArtifactDefinitions(artifacts: MutableMap<String, ArtifactDefinition>) { + paths.add("artifacts") + artifacts.forEach { artifactDefinitionName, artifactDefinition -> + paths.add(artifactDefinitionName) + message.appendln("Validating artifact " + paths.joinToString(separator)) + val type: String = artifactDefinition.type + ?: throw BluePrintException(format("type is missing for ArtifactDefinition({})", artifactDefinitionName)) + // Check Artifact Type + checkValidArtifactType(artifactDefinitionName, type) + + val file: String = artifactDefinition.file + ?: throw BluePrintException(format("file is missing for ArtifactDefinition({})", artifactDefinitionName)) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateWorkFlows(workflows: MutableMap<String, Workflow>) { + paths.add("workflows") + workflows.forEach { workflowName, workflow -> + + // Validate Single workflow + validateWorkFlow(workflowName, workflow) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateWorkFlow(workflowName: String, workflow: Workflow) { + paths.add(workflowName) + message.appendln("---> Workflow :" + paths.joinToString(separator)) + // Step Validation Start + paths.add("steps") + workflow.steps?.forEach { stepName, _ -> + paths.add(stepName) + message.appendln("----> Steps :" + paths.joinToString(separator)) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + // Step Validation Ends + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validatePropertyDefinitions(properties: MutableMap<String, PropertyDefinition>) { + paths.add("properties") + properties.forEach { propertyName, propertyDefinition -> + paths.add(propertyName) + val dataType: String = propertyDefinition.type + when { + BluePrintTypes.validPrimitiveTypes().contains(dataType) -> { + // Do Nothing + } + BluePrintTypes.validCollectionTypes().contains(dataType) -> { + val entrySchemaType: String = propertyDefinition.entrySchema?.type + ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, propertyName)) + checkPrimitiveOrComplex(entrySchemaType, propertyName) + } + else -> checkPropertyDataType(dataType, propertyName) + } + message.appendln("property " + paths.joinToString(separator) + " of type " + dataType) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validatePropertyAssignments( + nodeTypeProperties: MutableMap<String, PropertyDefinition>, + properties: MutableMap<String, JsonNode> + ) { + properties.forEach { propertyName, propertyAssignment -> + val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName] + ?: throw BluePrintException(format("failed to get definition for the property ({})", propertyName)) + + validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + } + + @Throws(BluePrintException::class) + open fun validatePropertyAssignment( + propertyName: String, + propertyDefinition: PropertyDefinition, + propertyAssignment: JsonNode + ) { + // Check and Validate if Expression Node + val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment) + if (!expressionData.isExpression) { + checkPropertyValue(propertyName, propertyDefinition, propertyAssignment) + } + } + + @Throws(BluePrintException::class) + open fun validateCapabilityAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + val capabilities = nodeTemplate.capabilities + paths.add("capabilities") + capabilities?.forEach { capabilityName, capabilityAssignment -> + paths.add(capabilityName) + + val capabilityDefinition = nodeType.capabilities?.get(capabilityName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) capability definition ({}) " + + "from NodeType({}) ", nodeTemplateName, capabilityName, nodeTemplate.type + ) + ) + + validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateCapabilityAssignment( + nodeTemplateName: String, + capabilityName: String, + capabilityDefinition: CapabilityDefinition, + capabilityAssignment: CapabilityAssignment + ) { + + capabilityAssignment.properties?.let { validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!) } + } + + @Throws(BluePrintException::class) + open fun validateRequirementAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + val requirements = nodeTemplate.requirements + paths.add("requirements") + requirements?.forEach { requirementName, requirementAssignment -> + paths.add(requirementName) + val requirementDefinition = nodeType.requirements?.get(requirementName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) requirement definition ({}) from" + + " NodeType({}) ", nodeTemplateName, requirementName, nodeTemplate.type + ) + ) + // Validate Requirement Assignment + validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateRequirementAssignment( + nodeTemplateName: String, + requirementAssignmentName: String, + requirementDefinition: RequirementDefinition, + requirementAssignment: RequirementAssignment + ) { + log.info("Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName, requirementAssignmentName) + val requirementNodeTemplateName = requirementAssignment.node!! + val capabilityName = requirementAssignment.capability + val relationship = requirementAssignment.relationship!! + + check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) { + throw BluePrintException( + format( + "Failed to get relationship type ({}) for NodeTemplate({})'s requirement({}) ", + relationship, nodeTemplateName, requirementAssignmentName + ) + ) + } + + val relationShipNodeTemplate = serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeTemplate({})'s for NodeTemplate({}) requirement({}) ", + requirementNodeTemplateName, nodeTemplateName, requirementAssignmentName + ) + ) + + relationShipNodeTemplate.capabilities?.get(capabilityName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeTemplate({})'s capability({}) for NodeTemplate ({})'s requirement({}) ", + requirementNodeTemplateName, capabilityName, nodeTemplateName, requirementAssignmentName + ) + ) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + + val interfaces = nodeTemplate.interfaces + paths.add("interfaces") + interfaces?.forEach { interfaceAssignmentName, interfaceAssignment -> + paths.add(interfaceAssignmentName) + val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) interface definition ({}) from" + + " NodeType({}) ", nodeTemplateName, interfaceAssignmentName, nodeTemplate.type + ) + ) + + validateInterfaceAssignment( + nodeTemplateName, interfaceAssignmentName, interfaceDefinition, + interfaceAssignment + ) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceAssignment( + nodeTemplateName: String, + interfaceAssignmentName: String, + interfaceDefinition: InterfaceDefinition, + interfaceAssignment: InterfaceAssignment + ) { + + val operations = interfaceAssignment.operations + operations?.let { + validateInterfaceOperationsAssignment( + nodeTemplateName, interfaceAssignmentName, interfaceDefinition, + interfaceAssignment + ) + } + } + + @Throws(BluePrintException::class) + open fun validateInterfaceOperationsAssignment( + nodeTemplateName: String, + interfaceAssignmentName: String, + interfaceDefinition: InterfaceDefinition, + interfaceAssignment: InterfaceAssignment + ) { + + val operations = interfaceAssignment.operations + operations?.let { + it.forEach { operationAssignmentName, operationAssignments -> + + val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) operation definition ({}) ", + nodeTemplateName, operationAssignmentName + ) + ) + + log.info( + "Validation NodeTemplate({}) Interface({}) Operation ({})", nodeTemplateName, + interfaceAssignmentName, operationAssignmentName + ) + + val inputs = operationAssignments.inputs + val outputs = operationAssignments.outputs + + inputs?.forEach { propertyName, propertyAssignment -> + val propertyDefinition = operationDefinition.inputs?.get(propertyName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) operation definition ({}) " + + "property definition({})", nodeTemplateName, operationAssignmentName, propertyName + ) + ) + // Check the property values with property definition + validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + + outputs?.forEach { propertyName, propertyAssignment -> + val propertyDefinition = operationDefinition.outputs?.get(propertyName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) operation definition ({}) " + + "output property definition({})", nodeTemplateName, operationAssignmentName, + propertyName + ) + ) + // Check the property values with property definition + validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + } + } + } + + @Throws(BluePrintException::class) + open fun validateCapabilityDefinitions(nodeTypeName: String, nodeType: NodeType) { + val capabilities = nodeType.capabilities + paths.add("capabilities") + capabilities?.forEach { capabilityName, capabilityDefinition -> + paths.add(capabilityName) + + validateCapabilityDefinition(nodeTypeName, nodeType, capabilityName, capabilityDefinition) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateCapabilityDefinition( + nodeTypeName: String, + nodeType: NodeType, + capabilityName: String, + capabilityDefinition: CapabilityDefinition + ) { + val capabilityType = capabilityDefinition.type + check(BluePrintTypes.validCapabilityTypes.contains(capabilityType)) { + throw BluePrintException( + format( + "Failed to get CapabilityType({}) for NodeType({})", + capabilityType, nodeTypeName + ) + ) + } + } + + @Throws(BluePrintException::class) + open fun validateRequirementDefinitions(nodeName: String, nodeType: NodeType) { + paths.add("requirements") + val requirements = nodeType.requirements + + requirements?.forEach { requirementDefinitionName, requirementDefinition -> + paths.add(requirementDefinitionName) + message.appendln("Validating : " + paths.joinToString(separator)) + validateRequirementDefinition(nodeName, nodeType, requirementDefinitionName, requirementDefinition) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateRequirementDefinition( + nodeTypeName: String, + nodeType: NodeType, + requirementDefinitionName: String, + requirementDefinition: RequirementDefinition + ) { + + log.info("Validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName) + val requirementNodeTypeName = requirementDefinition.node!! + val capabilityName = requirementDefinition.capability + val relationship = requirementDefinition.relationship!! + + check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) { + throw BluePrintException( + format( + "Failed to get relationship({}) for NodeType({})'s requirement({}) ", + relationship, nodeTypeName, requirementDefinitionName + ) + ) + } + + val relationShipNodeType = serviceTemplate.nodeTypes?.get(requirementNodeTypeName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeType({})'s for requirement({}) ", + requirementNodeTypeName, requirementDefinitionName + ) + ) + + relationShipNodeType.capabilities?.get(capabilityName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeType({})'s capability({}) for NodeType ({})'s requirement({}) ", + requirementNodeTypeName, capabilityName, nodeTypeName, requirementDefinitionName + ) + ) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceDefinitions(interfaces: MutableMap<String, InterfaceDefinition>) { + paths.add("interfaces") + interfaces.forEach { interfaceName, interfaceDefinition -> + paths.add(interfaceName) + message.appendln("Validating : " + paths.joinToString(separator)) + interfaceDefinition.operations?.let { validateOperationDefinitions(interfaceDefinition.operations!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateOperationDefinitions(operations: MutableMap<String, OperationDefinition>) { + paths.add("operations") + operations.forEach { opertaionName, operationDefinition -> + paths.add(opertaionName) + message.appendln("Validating : " + paths.joinToString(separator)) + operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) } + operationDefinition.inputs?.let { validatePropertyDefinitions(operationDefinition.inputs!!) } + operationDefinition.outputs?.let { validatePropertyDefinitions(operationDefinition.outputs!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateImplementation(implementation: Implementation) { + checkNotEmpty(implementation.primary) { "couldn't get implementation" } + } + + @Throws(BluePrintException::class) + open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) { + + val artifactType = serviceTemplate.artifactTypes?.get(artifactTypeName) + ?: throw BluePrintException("failed to artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)") + + checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom) + } + + @Throws(BluePrintException::class) + open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition") + } + } + + @Throws(BluePrintException::class) + open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom)) + } + } + + @Throws(BluePrintException::class) + open fun checkValidRelationshipTypeDerivedFrom(relationshipTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validRelationShipDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get relationship type ({})'s derivedFrom({}) definition ", relationshipTypeName, derivedFrom)) + } + } + + open fun checkPropertyValue(propertyName: String, propertyDefinition: PropertyDefinition, propertyAssignment: JsonNode) { + val propertyType = propertyDefinition.type + val isValid: Boolean + + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) { + isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment) + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { + + val entrySchemaType = propertyDefinition.entrySchema?.type + ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName)) + + if (!BluePrintTypes.validPropertyTypes().contains(entrySchemaType)) { + checkPropertyDataType(entrySchemaType, propertyName) + } + isValid = JacksonUtils.checkJsonNodeValueOfCollectionType(propertyType, propertyAssignment) + } else { + checkPropertyDataType(propertyType, propertyName) + isValid = true + } + + check(isValid) { + throw BluePrintException( + format( + "property({}) defined of type({}) is not comptable with the value ({})", + propertyName, propertyType, propertyAssignment + ) + ) + } + } + + private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { + + val dataType = serviceTemplate.dataTypes?.get(dataTypeName) + ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) + + checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) + } + + private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { + if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { + return true + } else { + throw BluePrintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName)) + } + } + + private fun checkDataType(key: String): Boolean { + return serviceTemplate.dataTypes?.containsKey(key) ?: false + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt new file mode 100644 index 000000000..43e27d047 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt @@ -0,0 +1,99 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Modifications Copyright © 2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import org.apache.commons.lang3.BooleanUtils +import org.apache.commons.lang3.StringUtils +import org.apache.velocity.VelocityContext +import org.apache.velocity.app.VelocityEngine +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory +import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode +import java.io.StringWriter + +object BluePrintVelocityTemplateService { + + /** + * Generate Content from Velocity Template and JSON Content with injected API + */ + fun generateContent( + template: String, + json: String, + ignoreJsonNull: Boolean = false, + additionalContext: MutableMap<String, Any> = mutableMapOf() + ): String { + + // Customized Object Mapper to remove String double quotes + val mapper = ObjectMapper() + val nodeFactory = BluePrintJsonNodeFactory() + mapper.nodeFactory = nodeFactory + + val jsonNode: JsonNode? = if (json.isNotEmpty()) { + mapper.readValue(json, JsonNode::class.java) + ?: throw BluePrintProcessorException("couldn't get json node from json") + } else { + null + } + return generateContent(template, jsonNode, ignoreJsonNull, additionalContext) + } + + /** + * Generate Content from Velocity Template and JSON Node with injected API + */ + fun generateContent( + template: String, + jsonNode: JsonNode?, + ignoreJsonNull: Boolean = false, + additionalContext: MutableMap<String, Any> = mutableMapOf() + ): String { + + /* + * create a new instance of the velocity engine + */ + val velocity = VelocityEngine() + + /* + * initialize the engine + */ + velocity.init() + + val velocityContext = VelocityContext() + velocityContext.put("StringUtils", StringUtils::class.java) + velocityContext.put("BooleanUtils", BooleanUtils::class.java) + + // Add the Custom Velocity Context API + additionalContext.forEach { (name, value) -> velocityContext.put(name, value) } + + // Add the JSON Data to the context + if (jsonNode != null) { + if (ignoreJsonNull) + jsonNode.removeNullNode() + jsonNode.fields().forEach { entry -> + velocityContext.put(entry.key, entry.value) + } + } + + val stringWriter = StringWriter() + velocity.evaluate(velocityContext, stringWriter, "TemplateData", template) + stringWriter.flush() + return stringWriter.toString() + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt new file mode 100644 index 000000000..98e5e5aec --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt @@ -0,0 +1,353 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.service + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.actor +import kotlinx.coroutines.channels.consumeEach +import kotlinx.coroutines.launch +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeStatus +import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeStatus +import org.onap.ccsdk.cds.controllerblueprints.core.incomingEdges +import org.onap.ccsdk.cds.controllerblueprints.core.isEndNode +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdges +import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdgesNotInLabels +import org.onap.ccsdk.cds.controllerblueprints.core.startNodes +import kotlin.coroutines.CoroutineContext + +interface BluePrintWorkFlowService<In, Out> { + + /** Executes imperative workflow graph [graph] for the bluePrintRuntimeService [bluePrintRuntimeService] + * and workflow input [input]*/ + suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BluePrintRuntimeService<*>, input: In): Out + + suspend fun initializeWorkflow(input: In): EdgeLabel + + suspend fun prepareWorkflowOutput(): Out + + /** Prepare the message for the Node */ + suspend fun prepareNodeExecutionMessage(node: Graph.Node): NodeExecuteMessage<In, Out> + + suspend fun prepareNodeSkipMessage(node: Graph.Node): NodeSkipMessage<In, Out> + + suspend fun executeNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel + + suspend fun skipNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel + + suspend fun cancelNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel + + suspend fun restartNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel +} + +/** Workflow Message Types */ +sealed class WorkflowMessage<In, Out> + +class WorkflowExecuteMessage<In, Out>(val input: In, val output: CompletableDeferred<Out>) : WorkflowMessage<In, Out>() + +class WorkflowCancelMessage<In, Out>(val input: In, val output: CompletableDeferred<Out>) : WorkflowMessage<In, Out>() + +class WorkflowRestartMessage<In, Out>(val input: In, val output: CompletableDeferred<Out>) : WorkflowMessage<In, Out>() + +/** Node Message Types */ +sealed class NodeMessage<In, Out> + +class NodeReadyMessage<In, Out>(val fromEdge: Graph.Edge, val edgeAction: EdgeAction) : NodeMessage<In, Out>() + +class NodeExecuteMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>() + +class NodeRestartMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>() + +class NodeSkipMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>() + +class NodeCancelMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>() + +enum class EdgeAction(val id: String) { + EXECUTE("execute"), + SKIP("skip") +} + +/** Abstract workflow service implementation */ +abstract class AbstractBluePrintWorkFlowService<In, Out> : CoroutineScope, BluePrintWorkFlowService<In, Out> { + + lateinit var graph: Graph + + private val log = logger(AbstractBluePrintWorkFlowService::class) + + private val job = Job() + + lateinit var workflowId: String + + var exceptions: MutableList<Exception> = arrayListOf() + + final override val coroutineContext: CoroutineContext + get() = job + CoroutineName("Wf") + + fun cancel() { + log.info("Received workflow($workflowId) cancel request") + job.cancel() + throw CancellationException("Workflow($workflowId) cancelled as requested") + } + + suspend fun workflowActor() = actor<WorkflowMessage<In, Out>>(coroutineContext, Channel.UNLIMITED) { + /** Process the workflow execution message */ + suspend fun executeMessageActor(workflowExecuteMessage: WorkflowExecuteMessage<In, Out>) { + + val nodeActor = nodeActor() + // Prepare Workflow and Populate the Initial store + initializeWorkflow(workflowExecuteMessage.input) + + val startNode = graph.startNodes().first() + // Prepare first node message and Send NodeExecuteMessage + // Start node doesn't wait for any nodes, so we can pass Execute message directly + val nodeExecuteMessage = prepareNodeExecutionMessage(startNode) + /** Send message from workflow actor to node actor */ + launch { + nodeActor.send(nodeExecuteMessage) + } + // Wait for workflow completion or Error + nodeActor.invokeOnClose { exception -> + launch { + if (exception != null) exceptions.add(BluePrintProcessorException(exception)) + log.info("workflow($workflowId) nodes completed with (${exceptions.size})exceptions") + val workflowOutput = prepareWorkflowOutput() + workflowExecuteMessage.output.complete(workflowOutput) + channel.close() + } + } + } + + /** Process each actor message received based on type */ + consumeEach { message -> + when (message) { + is WorkflowExecuteMessage<In, Out> -> { + launch { + try { + executeMessageActor(message) + } catch (e: Exception) { + exceptions.add(e) + } + } + } + is WorkflowRestartMessage<In, Out> -> { + launch { + TODO("") + } + } + is WorkflowCancelMessage<In, Out> -> { + launch { + TODO("") + } + } + } + } + } + + private suspend fun nodeActor() = actor<NodeMessage<In, Out>>(coroutineContext, Channel.UNLIMITED) { + + /** Send message to process from one state to other state */ + fun sendNodeMessage(nodeMessage: NodeMessage<In, Out>) = launch { + channel.send(nodeMessage) + } + + /** Process the cascade node processing, based on the previous state of the node */ + fun processNextNodes(node: Graph.Node, nodeState: EdgeLabel) { + // Process only Next Success Node + val stateEdges = graph.outgoingEdges(node.id, arrayListOf(nodeState)) + if (stateEdges.isNotEmpty()) { + stateEdges.forEach { stateEdge -> + // Prepare next node ready message and Send NodeReadyMessage + val nodeReadyMessage = NodeReadyMessage<In, Out>(stateEdge, EdgeAction.EXECUTE) + sendNodeMessage(nodeReadyMessage) + } + } + } + + suspend fun triggerToExecuteOrSkip(message: NodeReadyMessage<In, Out>) { + val edge = message.fromEdge + val node = edge.target + // Check if current edge action is Skip or Execute + when (message.edgeAction) { + EdgeAction.SKIP -> { + val skipMessage = prepareNodeSkipMessage(node) + sendNodeMessage(skipMessage) + } + EdgeAction.EXECUTE -> { + val nodeExecuteMessage = prepareNodeExecutionMessage(node) + sendNodeMessage(nodeExecuteMessage) + } + } + } + + suspend fun readyNodeWorker(message: NodeReadyMessage<In, Out>) { + val edge = message.fromEdge + val node = edge.target + log.debug("@@@@@ Ready workflow($workflowId), node($node) from edge($edge) for action(${message.edgeAction}) @@@@@") + // Update the current incoming edge status to executed or skipped + when (message.edgeAction) { + EdgeAction.SKIP -> message.fromEdge.status = EdgeStatus.SKIPPED + EdgeAction.EXECUTE -> message.fromEdge.status = EdgeStatus.EXECUTED + } + val incomingEdges = graph.incomingEdges(node.id) + if (incomingEdges.size > 1) { + // Check all incoming edges executed or skipped + val notCompletedEdges = incomingEdges.filter { it.status == EdgeStatus.NOT_STARTED } + if (notCompletedEdges.isEmpty()) { + // Possibility of skip edge action performed at last, but other edges have execute action. + val executePresent = incomingEdges.filter { it.status == EdgeStatus.EXECUTED } + val newMessage = if (executePresent.isNotEmpty()) { + NodeReadyMessage(message.fromEdge, EdgeAction.EXECUTE) + } else { + message + } + triggerToExecuteOrSkip(newMessage) + } else { + log.info("node(${node.id}) is waiting for incoming edges($notCompletedEdges)") + } + } else { + triggerToExecuteOrSkip(message) + } + } + + suspend fun executeNodeWorker(message: NodeExecuteMessage<In, Out>) { + val node = message.node + node.status = NodeStatus.EXECUTING + val nodeState = if (node.id == BluePrintConstants.GRAPH_START_NODE_NAME || + node.id == BluePrintConstants.GRAPH_END_NODE_NAME + ) { + EdgeLabel.SUCCESS + } else { + log.debug("##### Processing workflow($workflowId) node($node) #####") + // Call the Extension function and get the next Edge state. + executeNode(node, message.nodeInput, message.nodeOutput) + } + // Update Node Completed + node.status = NodeStatus.EXECUTED + log.info("Execute node(${node.id}) -> executed state($nodeState)") + // Check if the Node status edge is there, If not close processing + val edgePresent = graph.outgoingEdges(node.id, nodeState).isNotEmpty() + + // If End Node, Send End Message + if (graph.isEndNode(node)) { + // Close the current channel + channel.close() + } else if (!edgePresent) { + throw BluePrintProcessorException("node(${node.id}) outgoing edge($nodeState) is missing.") + } else { + val skippingEdges = graph.outgoingEdgesNotInLabels(node.id, arrayListOf(nodeState)) + log.debug("Skipping node($node)'s outgoing edges($skippingEdges)") + // Process Skip Edges + skippingEdges.forEach { skippingEdge -> + // Prepare next node ready message and Send NodeReadyMessage + val nodeReadyMessage = NodeReadyMessage<In, Out>(skippingEdge, EdgeAction.SKIP) + sendNodeMessage(nodeReadyMessage) + } + // Process Success Node + processNextNodes(node, nodeState) + } + } + + suspend fun skipNodeWorker(message: NodeSkipMessage<In, Out>) { + val node = message.node + val incomingEdges = graph.incomingEdges(node.id) + // Check All Incoming Nodes Skipped + val nonSkippedEdges = incomingEdges.filter { + it.status == EdgeStatus.NOT_STARTED + } + log.debug("Node($node) incoming edges ($incomingEdges), not skipped incoming edges ($nonSkippedEdges)") + + if (nonSkippedEdges.isEmpty()) { + log.debug("$$$$$ Skipping workflow($workflowId) node($node) $$$$$") + // Call the Extension Function + val nodeState = skipNode(node, message.nodeInput, message.nodeOutput) + log.info("Skip node(${node.id}) -> executed state($nodeState)") + // Mark the Current node as Skipped + node.status = NodeStatus.SKIPPED + // Look for next possible skip nodes + graph.outgoingEdges(node.id).forEach { outgoingEdge -> + val nodeReadyMessage = NodeReadyMessage<In, Out>(outgoingEdge, EdgeAction.SKIP) + sendNodeMessage(nodeReadyMessage) + } + } + } + + fun restartNodeWorker(message: NodeRestartMessage<In, Out>) = launch { + TODO() + } + + fun cancelNodeWorker(messageWorkflow: WorkflowCancelMessage<In, Out>) = launch { + channel.close() + throw CancellationException("Workflow($workflowId) actor cancelled as requested.") + } + + /** Process each actor message received based on type **/ + consumeEach { nodeMessage -> + when (nodeMessage) { + is NodeReadyMessage<In, Out> -> { + // Blocking call + try { + readyNodeWorker(nodeMessage) + } catch (e: Exception) { + exceptions.add(e) + channel.close() + } + } + is NodeExecuteMessage<In, Out> -> { + launch { + try { + executeNodeWorker(nodeMessage) + } catch (e: Exception) { + nodeMessage.node.status = NodeStatus.TERMINATED + exceptions.add(e) + channel.close() + } + } + } + is NodeSkipMessage<In, Out> -> { + launch { + try { + skipNodeWorker(nodeMessage) + } catch (e: Exception) { + nodeMessage.node.status = NodeStatus.TERMINATED + exceptions.add(e) + channel.close() + } + } + } + is NodeRestartMessage<In, Out> -> { + launch { + try { + restartNodeWorker(nodeMessage) + } catch (e: Exception) { + exceptions.add(e) + channel.close() + } + } + } + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt new file mode 100644 index 000000000..2dc8b5cf7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt @@ -0,0 +1,259 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression +import org.onap.ccsdk.cds.controllerblueprints.core.format +import org.onap.ccsdk.cds.controllerblueprints.core.isComplexType +import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.ResourceResolverUtils +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +class PropertyAssignmentService(var bluePrintRuntimeService: BluePrintRuntimeService<MutableMap<String, JsonNode>>) { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + private var bluePrintContext: BluePrintContext = bluePrintRuntimeService.bluePrintContext() + + /* + + If Property Assignment is Expression. + Get the Expression + Recursively resolve the expression + */ + + fun resolveAssignmentExpression( + nodeTemplateName: String, + assignmentName: String, + assignment: JsonNode + ): JsonNode { + val valueNode: JsonNode + log.trace("Assignment ({})", assignment) + val expressionData = BluePrintExpressionService.getExpressionData(assignment) + + if (expressionData.isExpression) { + valueNode = resolveExpression(nodeTemplateName, assignmentName, expressionData) + } else { + valueNode = expressionData.valueNode + } + return valueNode + } + + fun resolveExpression(nodeTemplateName: String, propName: String, expressionData: ExpressionData): JsonNode { + + var valueNode: JsonNode = NullNode.getInstance() + + if (expressionData.isExpression) { + val command = expressionData.command!! + + when (command) { + BluePrintConstants.EXPRESSION_GET_INPUT -> { + valueNode = bluePrintRuntimeService.getInputValue(expressionData.inputExpression?.propertyName!!) + } + BluePrintConstants.EXPRESSION_GET_ATTRIBUTE -> { + valueNode = resolveAttributeExpression(nodeTemplateName, expressionData.attributeExpression!!) + } + BluePrintConstants.EXPRESSION_GET_PROPERTY -> { + valueNode = resolvePropertyExpression(nodeTemplateName, expressionData.propertyExpression!!) + } + BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> { + valueNode = resolveOperationOutputExpression(nodeTemplateName, expressionData.operationOutputExpression!!) + } + BluePrintConstants.EXPRESSION_GET_ARTIFACT -> { + valueNode = resolveArtifactExpression(nodeTemplateName, expressionData.artifactExpression!!) + } + BluePrintConstants.EXPRESSION_DSL_REFERENCE -> { + valueNode = bluePrintRuntimeService.resolveDSLExpression(expressionData.dslExpression!!.propertyName) + } + BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE -> { + } + else -> { + throw BluePrintException(format("for property ({}), command ({}) is not supported ", propName, command)) + } + } + } + return valueNode + } + + /* + get_attribute: [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, + <nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] + */ + fun resolveAttributeExpression(nodeTemplateName: String, attributeExpression: AttributeExpression): JsonNode { + var valueNode: JsonNode + + val attributeName = attributeExpression.attributeName + val subAttributeName: String? = attributeExpression.subAttributeName + + var attributeNodeTemplateName = nodeTemplateName + /** + * Attributes are dynamic runtime properties information. There are multiple types of Attributes, + * ENV : Environment Variables + * APP : Application properties ( ie Spring resolved properties ) + * BPP : Blueprint Properties, Specific to Blue Print execution. + * SELF : Current Node Template properties. + */ + when (attributeExpression.modelableEntityName) { + BluePrintConstants.PROPERTY_ENV -> { + val environmentValue = System.getProperty(attributeName) + valueNode = environmentValue.asJsonPrimitive() + } + BluePrintConstants.PROPERTY_APP -> { + TODO("Get property from application properties") + } + BluePrintConstants.PROPERTY_BPP -> { + valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue(BluePrintConstants.PROPERTY_BPP, attributeName) + ?: throw BluePrintException("failed to get env attribute name ($attributeName) ") + } + else -> { + if (!attributeExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) { + attributeNodeTemplateName = attributeExpression.modelableEntityName + } + + var attributeDefinition: AttributeDefinition = bluePrintContext + .nodeTemplateNodeType(attributeNodeTemplateName).attributes?.get(attributeName) + ?: throw BluePrintException("failed to get attribute definitions for node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ") + + valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue(attributeNodeTemplateName, attributeName) + ?: throw BluePrintException("failed to get node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ") + } + } + if (subAttributeName != null) { + if (valueNode.isComplexType()) + valueNode = valueNode.jsonPathParse(subAttributeName) + } + return valueNode + } + + /* + get_property: [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, + <nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] + */ + fun resolvePropertyExpression(nodeTemplateName: String, propertyExpression: PropertyExpression): JsonNode { + var valueNode: JsonNode + + val propertyName = propertyExpression.propertyName + val subPropertyName: String? = propertyExpression.subPropertyName + + var propertyNodeTemplateName = nodeTemplateName + + if (!propertyExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) { + propertyNodeTemplateName = propertyExpression.modelableEntityName + } + + val nodeTemplatePropertyExpression = bluePrintContext.nodeTemplateByName(propertyNodeTemplateName).properties?.get(propertyName) + ?: throw BluePrintException( + format( + "failed to get property definitions for node template ({})'s property name ({}) ", + nodeTemplateName, + propertyName + ) + ) + + var propertyDefinition: PropertyDefinition = bluePrintContext.nodeTemplateNodeType(propertyNodeTemplateName).properties?.get(propertyName)!! + + log.info( + "node template name ({}), property Name ({}) resolved value ({})", + propertyNodeTemplateName, + propertyName, + nodeTemplatePropertyExpression + ) + + // Check it it is a nested expression + valueNode = resolveAssignmentExpression(propertyNodeTemplateName, propertyName, nodeTemplatePropertyExpression) + + if (subPropertyName != null) { + if (valueNode.isComplexType()) + valueNode = valueNode.jsonPathParse(subPropertyName) + } + return valueNode + } + + /* + get_operation_output: <modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name> + */ + fun resolveOperationOutputExpression(nodeTemplateName: String, operationOutputExpression: OperationOutputExpression): JsonNode { + var outputNodeTemplateName = nodeTemplateName + if (!operationOutputExpression.modelableEntityName.equals("SELF", true)) { + outputNodeTemplateName = operationOutputExpression.modelableEntityName + } + + var valueNode = bluePrintRuntimeService.getNodeTemplateOperationOutputValue( + outputNodeTemplateName, + operationOutputExpression.interfaceName, operationOutputExpression.operationName, + operationOutputExpression.propertyName + ) + + val subPropertyName: String? = operationOutputExpression.subPropertyName + if (subPropertyName != null) { + if (valueNode.isComplexType()) + valueNode = valueNode.jsonPathParse(subPropertyName) + } + return valueNode + } + + /* + get_artifact: [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ] + */ + fun resolveArtifactExpression(nodeTemplateName: String, artifactExpression: ArtifactExpression): JsonNode { + + var artifactNodeTemplateName = nodeTemplateName + if (!artifactExpression.modelableEntityName.equals("SELF", true)) { + artifactNodeTemplateName = artifactExpression.modelableEntityName + } + val artifactDefinition: ArtifactDefinition = bluePrintContext.nodeTemplateByName(artifactNodeTemplateName) + .artifacts?.get(artifactExpression.artifactName) + ?: throw BluePrintException( + format( + "failed to get artifact definitions for node template ({})'s " + + "artifact name ({}) ", nodeTemplateName, artifactExpression.artifactName + ) + ) + + return JacksonUtils.jsonNodeFromObject(artifactContent(artifactDefinition)) + } + + fun artifactContent(artifactDefinition: ArtifactDefinition): String { + val bluePrintBasePath: String = bluePrintContext.rootPath + + if (artifactDefinition.repository != null) { + TODO() + } else if (artifactDefinition.file != null) { + return ResourceResolverUtils.getFileContent(artifactDefinition.file, bluePrintBasePath) + } + return "" + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt new file mode 100755 index 000000000..9ccf856b5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt @@ -0,0 +1,158 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 Nordix Foundation. + * + * 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.controllerblueprints.core.utils + +import com.google.common.base.Predicates +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.slf4j.LoggerFactory +import java.io.BufferedInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import java.nio.charset.Charset +import java.nio.file.FileVisitResult +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes +import java.util.function.Predicate +import java.util.zip.Deflater +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream + +class BluePrintArchiveUtils { + + companion object { + private val log = LoggerFactory.getLogger(BluePrintArchiveUtils::class.java) + + /** + * Create a new Zip from a root directory + * + * @param source the base directory + * @param destination the output filename + * @return True if OK + */ + fun compress(source: File, destination: File): Boolean { + try { + if (!destination.parentFile.exists()) { + destination.parentFile.mkdirs() + } + destination.createNewFile() + val ignoreZipFiles = Predicate<Path> { path -> !path.endsWith(".zip") && !path.endsWith(".ZIP") } + FileOutputStream(destination).use { out -> + compressFolder(source.toPath(), out, pathFilter = ignoreZipFiles) + } + } catch (e: Exception) { + log.error("Fail to compress folder($source) to path(${destination.path})", e) + return false + } + return true + } + + /** + * In-memory compress an entire folder. + */ + fun compressToBytes(baseDir: Path, compressionLevel: Int = Deflater.NO_COMPRESSION): ByteArray { + return compressFolder(baseDir, ByteArrayOutputStream(), compressionLevel = compressionLevel) + .toByteArray() + } + + /** + * Compress an entire folder. + * + * @param baseDir path of base folder to be packaged. + * @param output the output stream + * @param pathFilter filter to ignore files based on its path. + * @param compressionLevel the wanted compression level. + * @param fixedModificationTime to force every entry to have this modification time. + * Useful for reproducible operations, like tests, for example. + */ + private fun <T> compressFolder( + baseDir: Path, + output: T, + pathFilter: Predicate<Path> = Predicates.alwaysTrue(), + compressionLevel: Int = Deflater.DEFAULT_COMPRESSION, + fixedModificationTime: Long? = null + ): T + where T : OutputStream { + ZipOutputStream(output) + .apply { setLevel(compressionLevel) } + .use { zos -> + Files.walkFileTree(baseDir, object : SimpleFileVisitor<Path>() { + @Throws(IOException::class) + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + if (pathFilter.test(file)) { + val zipEntry = ZipEntry(baseDir.relativize(file).toString()) + fixedModificationTime?.let { + zipEntry.time = it + } + zipEntry.time = 0 + zos.putNextEntry(zipEntry) + Files.copy(file, zos) + zos.closeEntry() + } + return FileVisitResult.CONTINUE + } + + @Throws(IOException::class) + override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { + val zipEntry = ZipEntry(baseDir.relativize(dir).toString() + "/") + fixedModificationTime?.let { + zipEntry.time = it + } + zos.putNextEntry(zipEntry) + zos.closeEntry() + return FileVisitResult.CONTINUE + } + }) + } + return output + } + + fun deCompress(zipFile: File, targetPath: String): File { + val zip = ZipFile(zipFile, Charset.defaultCharset()) + val enumeration = zip.entries() + while (enumeration.hasMoreElements()) { + val entry = enumeration.nextElement() + val destFilePath = File(targetPath, entry.name) + destFilePath.parentFile.mkdirs() + + if (entry.isDirectory) + continue + + val bufferedIs = BufferedInputStream(zip.getInputStream(entry)) + bufferedIs.use { + destFilePath.outputStream().buffered(1024).use { bos -> + bufferedIs.copyTo(bos) + } + } + } + + val destinationDir = File(targetPath) + check(destinationDir.isDirectory && destinationDir.exists()) { + throw BluePrintProcessorException("failed to decompress blueprint(${zipFile.absolutePath}) to ($targetPath) ") + } + + return destinationDir + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt new file mode 100755 index 000000000..6605e8eca --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt @@ -0,0 +1,292 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +import kotlinx.coroutines.runBlocking +import org.apache.commons.io.FileUtils +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.slf4j.LoggerFactory +import java.io.File +import java.io.FileFilter +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.nio.file.StandardOpenOption + +class BluePrintFileUtils { + companion object { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + fun createEmptyBluePrint(basePath: String) { + + val blueprintDir = File(basePath) + FileUtils.deleteDirectory(blueprintDir) + + Files.createDirectories(blueprintDir.toPath()) + + val metaDataDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_METADATA_DIR)) + Files.createDirectories(metaDataDir.toPath()) + + val metaFile = File( + blueprintDir.absolutePath.plus(File.separator).plus( + BluePrintConstants + .TOSCA_METADATA_ENTRY_DEFINITION_FILE + ) + ) + Files.write(metaFile.toPath(), getMetaDataContent().toByteArray(), StandardOpenOption.CREATE_NEW) + + val definitionsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR)) + Files.createDirectories(definitionsDir.toPath()) + + val scriptsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_SCRIPTS_DIR)) + Files.createDirectories(scriptsDir.toPath()) + + val plansDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_PLANS_DIR)) + Files.createDirectories(plansDir.toPath()) + + val templatesDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_TEMPLATES_DIR)) + Files.createDirectories(templatesDir.toPath()) + } + + fun copyBluePrint(sourcePath: String, targetPath: String) { + val sourceFile = File(sourcePath) + val targetFile = File(targetPath) + sourceFile.copyRecursively(targetFile, true) + } + + fun deleteBluePrintTypes(basePath: String) { + val definitionPath = basePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR) + log.info("deleting definition types under : $definitionPath") + + val definitionDir = File(definitionPath) + // Find the Type Definitions + val fileFilter = FileFilter { pathname -> pathname.absolutePath.endsWith("_types.json") } + // Delete the Type Files + definitionDir.listFiles(fileFilter).forEach { + Files.deleteIfExists(it.toPath()) + } + } + + fun writeEnhancedBluePrint(blueprintContext: BluePrintContext) { + + // Write Blueprint Types + writeBluePrintTypes(blueprintContext) + // Re Populate the Imports + populateDefaultImports(blueprintContext) + // Rewrite the Entry Definition Files + writeEntryDefinitionFile(blueprintContext) + } + + fun writeBluePrintTypes(blueprintContext: BluePrintContext) { + + val basePath = blueprintContext.rootPath + val definitionPath = basePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR) + val definitionDir = File(definitionPath) + + check(definitionDir.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get definition file under " + + "path(${definitionDir.absolutePath})" + ) + } + + blueprintContext.serviceTemplate.dataTypes?.let { + val dataTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_DATA_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_DATA_TYPES, dataTypesContent) + } + + blueprintContext.serviceTemplate.relationshipTypes?.let { + val nodeTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_RELATIONSHIP_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_RELATIONSHIP_TYPES, nodeTypesContent) + } + + blueprintContext.serviceTemplate.artifactTypes?.let { + val artifactTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_ARTIFACT_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_ARTIFACT_TYPES, artifactTypesContent) + } + + blueprintContext.serviceTemplate.nodeTypes?.let { + val nodeTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_NODE_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_NODE_TYPES, nodeTypesContent) + } + + blueprintContext.serviceTemplate.policyTypes?.let { + val nodeTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_POLICY_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_POLICY_TYPES, nodeTypesContent) + } + } + + private fun populateDefaultImports(blueprintContext: BluePrintContext) { + // Get the Default Types + val types = arrayListOf( + BluePrintConstants.PATH_DATA_TYPES, BluePrintConstants.PATH_RELATIONSHIP_TYPES, + BluePrintConstants.PATH_ARTIFACT_TYPES, BluePrintConstants.PATH_NODE_TYPES, + BluePrintConstants.PATH_POLICY_TYPES + ) + + // Clean Type Imports + cleanImportTypes(blueprintContext.serviceTemplate) + + val imports = mutableListOf<ImportDefinition>() + types.forEach { typeName -> + val import = ImportDefinition() + import.file = BluePrintConstants.TOSCA_DEFINITIONS_DIR.plus("/$typeName.json") + imports.add(import) + } + + blueprintContext.serviceTemplate.imports = imports + } + + fun cleanImportTypes(serviceTemplate: ServiceTemplate) { + // Clean the Type imports + val toDeleteTypes = serviceTemplate.imports?.filter { + it.file.endsWith("_types.json") + } + + if (toDeleteTypes != null && toDeleteTypes.isNotEmpty()) { + serviceTemplate.imports?.removeAll(toDeleteTypes) + } + } + + /** + * Re Generate the Blueprint Service Template Definition file based on BluePrint Context. + */ + private fun writeEntryDefinitionFile(blueprintContext: BluePrintContext) { + + val absoluteEntryDefinitionFile = blueprintContext.rootPath.plus(File.separator).plus(blueprintContext.entryDefinition) + + val serviceTemplate = blueprintContext.serviceTemplate + + // Clone the Service Template + val writeServiceTemplate = serviceTemplate.clone() + writeServiceTemplate.dataTypes = null + writeServiceTemplate.artifactTypes = null + writeServiceTemplate.policyTypes = null + writeServiceTemplate.relationshipTypes = null + writeServiceTemplate.nodeTypes = null + + // Write the Service Template + writeDefinitionFile(absoluteEntryDefinitionFile, JacksonUtils.getJson(writeServiceTemplate, true)) + } + + fun writeDefinitionFile(definitionFileName: String, content: String) = runBlocking { + val definitionFile = File(definitionFileName) + // Delete the File If exists + Files.deleteIfExists(definitionFile.toPath()) + + Files.write(definitionFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW) + check(definitionFile.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_WRITING_FAIL.value, "couldn't write definition file under " + + "path(${definitionFile.absolutePath})" + ) + } + } + + private fun writeTypeFile(definitionPath: String, type: String, content: String) = runBlocking { + val typeFile = File(definitionPath.plus(File.separator).plus("$type.json")) + + Files.write(typeFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW) + check(typeFile.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_WRITING_FAIL.value, "couldn't write $type.json file under " + + "path(${typeFile.absolutePath})" + ) + } + } + + private fun getMetaDataContent(): String { + return "TOSCA-Meta-File-Version: 1.0.0" + + "\nCSAR-Version: <VERSION>" + + "\nCreated-By: <AUTHOR NAME>" + + "\nEntry-Definitions: Definitions/<BLUEPRINT_NAME>.json" + + "\nTemplate-Name: <BLUEPRINT_NAME>" + + "\nTemplate-Tags: <BLUEPRINT_VERSION>" + + "\nTemplate-Tags: <TAGS>" + } + + fun getBluePrintFile(fileName: String, targetPath: Path): File { + val filePath = targetPath.resolve(fileName).toString() + val file = File(filePath) + check(file.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get definition file under " + + "path(${file.absolutePath})" + ) + } + return file + } + + fun getCbaStorageDirectory(path: String): Path { + check(StringUtils.isNotBlank(path)) { + throw BluePrintException( + ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get " + + "Blueprint folder under path($path)" + ) + } + + val fileStorageLocation = Paths.get(path).toAbsolutePath().normalize() + + if (!Files.exists(fileStorageLocation)) + Files.createDirectories(fileStorageLocation) + + return fileStorageLocation + } + + fun compileCacheKey(basePath: String): String { + return normalizedPathName(basePath) + } + + private fun compileJarFileName(artifactName: String, artifactVersion: String): String { + return "$artifactName-$artifactVersion-cba-kts.jar" + } + + fun compileJarFilePathName(basePath: String, artifactName: String, artifactVersion: String): String { + return normalizedPathName( + basePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR, + compileJarFileName(artifactName, artifactVersion) + ) + } + + fun compileJarFile(basePath: String, artifactName: String, artifactVersion: String): File { + return normalizedFile( + compileJarFilePathName( + basePath, + artifactName, artifactVersion + ) + ) + } + + fun stripFileExtension(fileName: String): String { + val dotIndexe = fileName.lastIndexOf('.') + + // In case dot is in first position, we are dealing with a hidden file rather than an extension + return if (dotIndexe > 0) fileName.substring(0, dotIndexe) else fileName + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt new file mode 100644 index 000000000..d29fed0d9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt @@ -0,0 +1,41 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +object BluePrintIOUtils { + + suspend fun <T> retry( + times: Int = 1, + initialDelay: Long = 0, + delay: Long = 1000, + block: suspend (Int) -> T, + exceptionBlock: (e: Exception) -> Unit + ): T { + var currentDelay = initialDelay + val currentTimes = times - 1 + repeat(currentTimes) { count -> + try { + return block(count) + } catch (e: Exception) { + exceptionBlock(e) + } + kotlinx.coroutines.delay(currentDelay) + currentDelay = delay + } + return block(currentTimes) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt new file mode 100644 index 000000000..4d7647f47 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt @@ -0,0 +1,213 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * 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.controllerblueprints.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDefinitions +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintScriptsServiceImpl +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintImportService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService +import org.slf4j.LoggerFactory +import java.io.File +import java.util.Properties + +class BluePrintMetadataUtils { + companion object { + private val log = LoggerFactory.getLogger(this::class.toString()) + + suspend fun toscaMetaData(basePath: String): ToscaMetaData { + val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE) + return toscaMetaDataFromMetaFile(toscaMetaPath) + } + + suspend fun entryDefinitionFile(basePath: String): String { + val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE) + return toscaMetaDataFromMetaFile(toscaMetaPath).entityDefinitions + } + + fun bluePrintEnvProperties(basePath: String): Properties { + val blueprintsEnvFilePath = basePath.plus(File.separator) + .plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR) + return environmentFileProperties(blueprintsEnvFilePath) + } + + fun environmentFileProperties(pathName: String): Properties { + val properties = Properties() + val envDir = normalizedFile(pathName) + // Verify if the environment directory exists + if (envDir.exists() && envDir.isDirectory) { + // Find all available environment files + envDir.listFiles()!! + .filter { it.name.endsWith(".properties") } + .forEach { + val istream = it.inputStream() + properties.load(istream) + istream.close() + } + } + return properties + } + + private suspend fun toscaMetaDataFromMetaFile(metaFilePath: String): ToscaMetaData { + val toscaMetaData = ToscaMetaData() + val lines = normalizedFile(metaFilePath).readNBLines() + lines.forEach { line -> + if (line.contains(":")) { + val keyValue = line.split(":") + if (keyValue.size == 2) { + val value: String = keyValue[1].trim() + when (keyValue[0]) { + "TOSCA-Meta-File-Version" -> toscaMetaData.toscaMetaFileVersion = value + "CSAR-Version" -> toscaMetaData.csarVersion = value + "Created-By" -> toscaMetaData.createdBy = value + "Entry-Definitions" -> toscaMetaData.entityDefinitions = value + "Template-Name" -> toscaMetaData.templateName = value + "Template-Version" -> toscaMetaData.templateVersion = value + "Template-Tags" -> toscaMetaData.templateTags = value + } + } + } + } + return toscaMetaData + } + + fun getBluePrintRuntime(id: String, blueprintBasePath: String): + BluePrintRuntimeService<MutableMap<String, JsonNode>> { + val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath) + return getBluePrintRuntime(id, bluePrintContext) + } + + fun getBluePrintRuntime(id: String, bluePrintContext: BluePrintContext): + BluePrintRuntimeService<MutableMap<String, JsonNode>> { + checkNotEmpty(bluePrintContext.rootPath) { "blueprint context root path is missing." } + checkNotEmpty(bluePrintContext.entryDefinition) { "blueprint context entry definition is missing." } + val blueprintBasePath = bluePrintContext.rootPath + val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext) + bluePrintRuntimeService.put(BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH, blueprintBasePath.asJsonPrimitive()) + bluePrintRuntimeService.put(BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID, id.asJsonPrimitive()) + return bluePrintRuntimeService + } + + suspend fun getBaseEnhancementBluePrintRuntime(id: String, blueprintBasePath: String): + BluePrintRuntimeService<MutableMap<String, JsonNode>> { + + val bluePrintContext: BluePrintContext = getBaseEnhancementBluePrintContext(blueprintBasePath) + + val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext) + bluePrintRuntimeService.put(BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH, blueprintBasePath.asJsonPrimitive()) + bluePrintRuntimeService.put(BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID, id.asJsonPrimitive()) + + return bluePrintRuntimeService + } + + fun getBluePrintRuntime(id: String, blueprintBasePath: String, executionContext: MutableMap<String, JsonNode>): + BluePrintRuntimeService<MutableMap<String, JsonNode>> { + val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath) + val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext) + executionContext.forEach { + bluePrintRuntimeService.put(it.key, it.value) + } + + bluePrintRuntimeService.setExecutionContext(executionContext) + return bluePrintRuntimeService + } + + fun getBluePrintContext(blueprintBasePath: String): BluePrintContext = runBlocking { + + val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath) + + log.info("Reading blueprint path($blueprintBasePath) and entry definition file (${toscaMetaData.entityDefinitions})") + + // If the EntryDefinition is Kotlin file, compile and get Service Template + if (toscaMetaData.entityDefinitions.endsWith("kt")) { + readBlueprintKotlinFile(toscaMetaData, blueprintBasePath) + } else { + readBlueprintFile(toscaMetaData.entityDefinitions, blueprintBasePath) + } + } + + private suspend fun getBaseEnhancementBluePrintContext(blueprintBasePath: String): BluePrintContext { + val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath) + // Clean Type files + BluePrintFileUtils.deleteBluePrintTypes(blueprintBasePath) + val rootFilePath: String = blueprintBasePath.plus(File.separator).plus(toscaMetaData.entityDefinitions) + val rootServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath) + + // Clean the Import Definitions + BluePrintFileUtils.cleanImportTypes(rootServiceTemplate) + + val blueprintContext = BluePrintContext(rootServiceTemplate) + blueprintContext.rootPath = blueprintBasePath + blueprintContext.entryDefinition = toscaMetaData.entityDefinitions + return blueprintContext + } + + private suspend fun readBlueprintFile(entityDefinitions: String, basePath: String): BluePrintContext { + val normalizedBasePath = normalizedPathName(basePath) + val rootFilePath = normalizedPathName(normalizedBasePath, entityDefinitions) + val rootServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath) + // Recursively Import Template files + val schemaImportResolverUtils = BluePrintImportService(rootServiceTemplate, normalizedBasePath) + val completeServiceTemplate = schemaImportResolverUtils.getImportResolvedServiceTemplate() + val blueprintContext = BluePrintContext(completeServiceTemplate) + blueprintContext.rootPath = normalizedBasePath + blueprintContext.entryDefinition = entityDefinitions + return blueprintContext + } + + /** Reade the Service Template Definitions from the Kotlin file */ + private suspend fun readBlueprintKotlinFile(toscaMetaData: ToscaMetaData, basePath: String): BluePrintContext { + + checkNotNull(toscaMetaData.templateName) { "couldn't find 'Template-Name' key in TOSCA.meta" } + checkNotNull(toscaMetaData.templateVersion) { "couldn't find 'Template-Version' key in TOSCA.meta" } + + val definitionClassName = toscaMetaData.entityDefinitions.removeSuffix(".kt") + val normalizedBasePath = normalizedPathName(basePath) + + val bluePrintScriptsService = BluePrintScriptsServiceImpl() + val bluePrintDefinitions = bluePrintScriptsService + .scriptInstance<BluePrintDefinitions>( + normalizedBasePath, toscaMetaData.templateName!!, + toscaMetaData.templateVersion!!, definitionClassName, false + ) + // Get the Service Template + val serviceTemplate = bluePrintDefinitions.serviceTemplate() + + // Clean the Default type import Definitions + BluePrintFileUtils.cleanImportTypes(serviceTemplate) + + val blueprintContext = BluePrintContext(serviceTemplate) + blueprintContext.rootPath = normalizedBasePath + blueprintContext.entryDefinition = toscaMetaData.entityDefinitions + blueprintContext.otherDefinitions = bluePrintDefinitions.otherDefinitions() + return blueprintContext + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt new file mode 100644 index 000000000..c44355070 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt @@ -0,0 +1,64 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +object BluePrintRuntimeUtils { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + fun assignInputsFromFile(bluePrintContext: BluePrintContext, fileName: String, context: MutableMap<String, JsonNode>) { + val jsonNode: JsonNode = JacksonUtils.jsonNodeFromFile(fileName) + return assignInputs(bluePrintContext, jsonNode, context) + } + + fun assignInputsFromClassPathFile( + bluePrintContext: BluePrintContext, + fileName: String, + context: MutableMap<String, + JsonNode> + ) { + val jsonNode = JacksonUtils.jsonNodeFromClassPathFile(fileName) + return assignInputs(bluePrintContext, jsonNode, context) + } + + fun assignInputsFromContent(bluePrintContext: BluePrintContext, content: String, context: MutableMap<String, JsonNode>) { + val jsonNode: JsonNode = JacksonUtils.jsonNode(content) + return assignInputs(bluePrintContext, jsonNode, context) + } + + fun assignInputs(bluePrintContext: BluePrintContext, jsonNode: JsonNode, context: MutableMap<String, JsonNode>) { + log.info("assignInputs from input JSON ({})", jsonNode.toString()) + bluePrintContext.inputs()?.forEach { propertyName, _ -> + val valueNode: JsonNode = jsonNode.at("/".plus(propertyName)) ?: NullNode.getInstance() + + val path = BluePrintConstants.PATH_INPUTS.plus(BluePrintConstants.PATH_DIVIDER).plus(propertyName) + log.trace("setting input path ({}), values ({})", path, valueNode) + context[path] = valueNode + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt new file mode 100644 index 000000000..4fd907a5a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt @@ -0,0 +1,47 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import java.text.SimpleDateFormat +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Date + +fun controllerDate(): Date { + val localDateTime = LocalDateTime.now(ZoneId.systemDefault()) + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()) +} + +fun currentTimestamp(): String { + val localDateTime = LocalDateTime.now(ZoneId.systemDefault()) + val formatter = DateTimeFormatter.ofPattern(BluePrintConstants.DATE_TIME_PATTERN) + return formatter.format(localDateTime) +} + +/** Parse string date in CDS string format */ +fun String.toControllerDate(): Date { + val formatter = SimpleDateFormat(BluePrintConstants.DATE_TIME_PATTERN) + return formatter.parse(this) +} + +/** Return date to CDS string format */ +fun Date.currentTimestamp(): String { + val formatter = SimpleDateFormat(BluePrintConstants.DATE_TIME_PATTERN) + return formatter.format(this) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtils.kt new file mode 100644 index 000000000..6645ff7b4 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtils.kt @@ -0,0 +1,92 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.apache.commons.io.IOUtils +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.slf4j.LoggerFactory +import java.io.File +import java.nio.charset.Charset + +class JacksonReactorUtils { + companion object { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + suspend fun getContent(fileName: String): String { + // log.info("Reading File($fileName)") + return getContent(normalizedFile(fileName)) + } + + suspend fun getContent(file: File): String = withContext(Dispatchers.IO) { + // log.info("Reading File(${file.absolutePath})") + file.readText(Charsets.UTF_8) + } + + suspend fun getClassPathFileContent(fileName: String): String = withContext(Dispatchers.IO) { + // log.trace("Reading Classpath File($fileName)") + IOUtils.toString( + JacksonUtils::class.java.classLoader + .getResourceAsStream(fileName), Charset.defaultCharset() + ) + } + + suspend fun <T> readValueFromFile(fileName: String, valueType: Class<T>): T? { + val content: String = getContent(fileName) + return JacksonUtils.readValue(content, valueType) + } + + suspend fun <T> readValueFromClassPathFile(fileName: String, valueType: Class<T>): T? { + val content: String = getClassPathFileContent(fileName) + return JacksonUtils.readValue(content, valueType) + } + + suspend fun jsonNodeFromClassPathFile(fileName: String): JsonNode { + val content: String = getClassPathFileContent(fileName) + return JacksonUtils.jsonNode(content) + } + + suspend fun jsonNodeFromFile(fileName: String): JsonNode { + val content: String = getContent(fileName) + return JacksonUtils.jsonNode(content) + } + + suspend fun <T> getListFromFile(fileName: String, valueType: Class<T>): List<T> { + val content: String = getContent(fileName) + return JacksonUtils.getListFromJson(content, valueType) + } + + suspend fun <T> getListFromClassPathFile(fileName: String, valueType: Class<T>): List<T> { + val content: String = getClassPathFileContent(fileName) + return JacksonUtils.getListFromJson(content, valueType) + } + + suspend fun <T> getMapFromFile(file: File, valueType: Class<T>): MutableMap<String, T> { + val content: String = getContent(file) + return JacksonUtils.getMapFromJson(content, valueType) + } + + suspend fun <T> getMapFromClassPathFile(fileName: String, valueType: Class<T>): MutableMap<String, T> { + val content: String = getClassPathFileContent(fileName) + return JacksonUtils.getMapFromJson(content, valueType) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt new file mode 100644 index 000000000..945f300af --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt @@ -0,0 +1,327 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * 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.controllerblueprints.core.utils + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.BooleanNode +import com.fasterxml.jackson.databind.node.DoubleNode +import com.fasterxml.jackson.databind.node.FloatNode +import com.fasterxml.jackson.databind.node.IntNode +import com.fasterxml.jackson.databind.node.MissingNode +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import com.fasterxml.jackson.databind.node.TextNode +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import org.apache.commons.io.IOUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.readNBText +import java.io.File +import java.io.InputStream +import java.nio.charset.Charset + +/** + * + * + * @author Brinda Santh + */ +class JacksonUtils { + + companion object { + + val objectMapper = jacksonObjectMapper() + + inline fun <reified T : Any> readValue(content: String): T = + objectMapper.readValue(content, T::class.java) + + inline fun <reified T : Any> readValue(stream: InputStream): T = + objectMapper.readValue(stream, T::class.java) + + fun <T> readValue(content: String, valueType: Class<T>): T? { + return objectMapper.readValue(content, valueType) + } + + fun <T> readValue(stream: InputStream, valueType: Class<T>): T? { + return objectMapper.readValue(stream, valueType) + } + + fun <T> readValue(node: JsonNode, valueType: Class<T>): T? { + return objectMapper.treeToValue(node, valueType) + } + + fun getContent(fileName: String): String = runBlocking { + try { + normalizedFile(fileName).readNBText() + } catch (e: Exception) { + throw BluePrintException("couldn't get file ($fileName) content : ${e.message}") + } + } + + fun getClassPathFileContent(fileName: String): String { + return runBlocking { + withContext(Dispatchers.Default) { + IOUtils.toString( + JacksonUtils::class.java.classLoader + .getResourceAsStream(fileName), Charset.defaultCharset() + ) + } + } + } + + fun <T> readValueFromFile(fileName: String, valueType: Class<T>): T? { + val content: String = getContent(fileName) + return readValue(content, valueType) + } + + fun <T> readValueFromClassPathFile(fileName: String, valueType: Class<T>): T? { + val content: String = getClassPathFileContent(fileName) + return readValue(content, valueType) + } + + fun objectNodeFromObject(from: kotlin.Any): ObjectNode { + return objectMapper.convertValue(from, ObjectNode::class.java) + } + + fun jsonNodeFromObject(from: kotlin.Any): JsonNode { + return objectMapper.convertValue(from, JsonNode::class.java) + } + + fun jsonNodeFromClassPathFile(fileName: String): JsonNode { + val content: String = getClassPathFileContent(fileName) + return jsonNode(content) + } + + fun jsonNodeFromFile(fileName: String): JsonNode { + val content: String = getContent(fileName) + return jsonNode(content) + } + + fun jsonNode(content: String): JsonNode { + return jacksonObjectMapper().readTree(content) + } + + fun getJson(any: kotlin.Any): String { + return getJson(any, false) + } + + fun getWrappedJson(wrapper: String, any: kotlin.Any, pretty: Boolean = false): String { + val wrapperMap = hashMapOf<String, Any>() + wrapperMap[wrapper] = any + return getJson(wrapperMap, pretty) + } + + fun getJson(any: kotlin.Any, pretty: Boolean = false): String { + val objectMapper = jacksonObjectMapper() + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) + if (pretty) { + objectMapper.enable(SerializationFeature.INDENT_OUTPUT) + } + return objectMapper.writeValueAsString(any) + } + + fun getJsonNode(any: kotlin.Any?, pretty: Boolean = false): JsonNode { + val objectMapper = jacksonObjectMapper() + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) + if (pretty) { + objectMapper.enable(SerializationFeature.INDENT_OUTPUT) + } + return objectMapper.valueToTree(any) + } + + fun <T> getListFromJsonNode(node: JsonNode, valueType: Class<T>): List<T> { + return getListFromJson(node.toString(), valueType) + } + + fun <T> getListFromJson(content: String, valueType: Class<T>): List<T> { + val objectMapper = jacksonObjectMapper() + val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, valueType) + return objectMapper.readValue<List<T>>(content, javaType) + } + + fun <T> getListFromFile(fileName: String, valueType: Class<T>): List<T> { + val content: String = getContent(fileName) + return getListFromJson(content, valueType) + } + + fun <T> getListFromClassPathFile(fileName: String, valueType: Class<T>): List<T> { + val content: String = getClassPathFileContent(fileName) + return getListFromJson(content, valueType) + } + + fun <T> getMapFromJson(content: String, valueType: Class<T>): MutableMap<String, T> { + val objectMapper = jacksonObjectMapper() + val mapType = objectMapper.typeFactory.constructMapType(Map::class.java, String::class.java, valueType) + return objectMapper.readValue(content, mapType) + } + + fun <T> getMapFromFile(file: File, valueType: Class<T>): MutableMap<String, T> = runBlocking { + val content: String = file.readNBText() + getMapFromJson(content, valueType) + } + + fun <T> getMapFromFile(fileName: String, valueType: Class<T>): MutableMap<String, T> = getMapFromFile(File(fileName), valueType) + + fun <T> getInstanceFromMap(properties: MutableMap<String, JsonNode>, classType: Class<T>): T { + return readValue(getJson(properties), classType) + ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)") + } + + fun checkJsonNodeValueOfType(type: String, jsonNode: JsonNode): Boolean { + if (BluePrintTypes.validPrimitiveTypes().contains(type.toLowerCase())) { + return checkJsonNodeValueOfPrimitiveType(type, jsonNode) + } else if (BluePrintTypes.validCollectionTypes().contains(type)) { + return checkJsonNodeValueOfCollectionType(type, jsonNode) + } + return false + } + + fun checkIfPrimitiveType(primitiveType: String): Boolean { + return when (primitiveType.toLowerCase()) { + BluePrintConstants.DATA_TYPE_STRING -> true + BluePrintConstants.DATA_TYPE_BOOLEAN -> true + BluePrintConstants.DATA_TYPE_INTEGER -> true + BluePrintConstants.DATA_TYPE_FLOAT -> true + BluePrintConstants.DATA_TYPE_DOUBLE -> true + BluePrintConstants.DATA_TYPE_TIMESTAMP -> true + else -> false + } + } + + fun checkJsonNodeValueOfPrimitiveType(primitiveType: String, jsonNode: JsonNode): Boolean { + return when (primitiveType.toLowerCase()) { + BluePrintConstants.DATA_TYPE_STRING -> jsonNode.isTextual + BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNode.isBoolean + BluePrintConstants.DATA_TYPE_INTEGER -> jsonNode.isInt + BluePrintConstants.DATA_TYPE_FLOAT -> jsonNode.isDouble + BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNode.isDouble + BluePrintConstants.DATA_TYPE_TIMESTAMP -> jsonNode.isTextual + else -> false + } + } + + fun checkJsonNodeValueOfCollectionType(type: String, jsonNode: JsonNode): Boolean { + return when (type.toLowerCase()) { + BluePrintConstants.DATA_TYPE_LIST -> jsonNode.isArray + BluePrintConstants.DATA_TYPE_MAP -> jsonNode.isContainerNode + else -> false + } + } + + fun getValue(value: JsonNode): Any { + return when (value) { + is BooleanNode -> value.booleanValue() + is IntNode -> value.intValue() + is FloatNode -> value.floatValue() + is DoubleNode -> value.doubleValue() + is TextNode -> value.textValue() + else -> value + } + } + + fun getValue(value: Any, type: String): Any { + return when (type.toLowerCase()) { + BluePrintConstants.DATA_TYPE_BOOLEAN -> (value as BooleanNode).booleanValue() + BluePrintConstants.DATA_TYPE_INTEGER -> (value as IntNode).intValue() + BluePrintConstants.DATA_TYPE_FLOAT -> (value as FloatNode).floatValue() + BluePrintConstants.DATA_TYPE_DOUBLE -> (value as DoubleNode).doubleValue() + BluePrintConstants.DATA_TYPE_STRING -> (value as TextNode).textValue() + else -> (value as JsonNode) + } + } + + fun populatePrimitiveValues(key: String, value: JsonNode, primitiveType: String, objectNode: ObjectNode) { + when (primitiveType.toLowerCase()) { + BluePrintConstants.DATA_TYPE_BOOLEAN, + BluePrintConstants.DATA_TYPE_INTEGER, + BluePrintConstants.DATA_TYPE_FLOAT, + BluePrintConstants.DATA_TYPE_DOUBLE, + BluePrintConstants.DATA_TYPE_TIMESTAMP, + BluePrintConstants.DATA_TYPE_STRING, + BluePrintConstants.DATA_TYPE_NULL -> + objectNode.set(key, value) + else -> throw BluePrintException("populatePrimitiveValues expected only primitive values! Received: ($value)") + } + } + + fun populatePrimitiveValues(value: JsonNode, primitiveType: String, arrayNode: ArrayNode) { + when (primitiveType.toLowerCase()) { + BluePrintConstants.DATA_TYPE_BOOLEAN, + BluePrintConstants.DATA_TYPE_INTEGER, + BluePrintConstants.DATA_TYPE_FLOAT, + BluePrintConstants.DATA_TYPE_DOUBLE, + BluePrintConstants.DATA_TYPE_TIMESTAMP, + BluePrintConstants.DATA_TYPE_STRING, + BluePrintConstants.DATA_TYPE_NULL -> + arrayNode.add(value) + else -> throw BluePrintException("populatePrimitiveValues expected only primitive values! Received: ($value)") + } + } + + fun populatePrimitiveDefaultValues(key: String, primitiveType: String, objectNode: ObjectNode) { + val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType) + ?: throw BluePrintException("populatePrimitiveDefaultValues expected only primitive values! Received type ($primitiveType)") + objectNode.set(key, defaultValue) + } + + fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) { + val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType) + ?: throw BluePrintException("populatePrimitiveDefaultValuesForArrayNode expected only primitive values! Received type ($primitiveType)") + arrayNode.add(defaultValue) + } + + private fun getDefaultValueOfPrimitiveAsJsonNode(primitiveType: String): JsonNode? { + return when (primitiveType.toLowerCase()) { + BluePrintConstants.DATA_TYPE_BOOLEAN -> BooleanNode.valueOf(false) + BluePrintConstants.DATA_TYPE_INTEGER -> IntNode.valueOf(0) + BluePrintConstants.DATA_TYPE_FLOAT -> FloatNode.valueOf(0.0f) + BluePrintConstants.DATA_TYPE_DOUBLE -> DoubleNode.valueOf(0.0) + BluePrintConstants.DATA_TYPE_STRING -> MissingNode.getInstance() + else -> null + } + } + + fun populateJsonNodeValues(key: String, nodeValue: JsonNode?, type: String, objectNode: ObjectNode) { + if (nodeValue == null || nodeValue is NullNode) { + objectNode.set(key, nodeValue) + } else if (BluePrintTypes.validPrimitiveTypes().contains(type)) { + populatePrimitiveValues(key, nodeValue, type, objectNode) + } else { + objectNode.set(key, nodeValue) + } + } + + fun convertPrimitiveResourceValue(type: String, value: String): JsonNode { + return when (type.toLowerCase()) { + BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNodeFromObject(value.toBoolean()) + BluePrintConstants.DATA_TYPE_INTEGER -> jsonNodeFromObject(value.toInt()) + BluePrintConstants.DATA_TYPE_FLOAT -> jsonNodeFromObject(value.toFloat()) + BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNodeFromObject(value.toDouble()) + BluePrintConstants.DATA_TYPE_STRING -> jsonNodeFromObject(value) + else -> getJsonNode(value) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt new file mode 100644 index 000000000..0e3d4f93d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt @@ -0,0 +1,62 @@ +/* + * Copyright © 2018 IBM. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. + * + * 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.controllerblueprints.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import com.jayway.jsonpath.Configuration +import com.jayway.jsonpath.JsonPath +import com.jayway.jsonpath.Option +import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider +import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString + +class JsonParserUtils { + companion object { + + // TODO("Optimise this") + val JACKSON_JSON_NODE_CONFIGURATION = Configuration.builder() + .mappingProvider(JacksonMappingProvider()).jsonProvider(JacksonJsonNodeJsonProvider()).build() + + val PATH_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST).build() + + fun paths(jsonContent: String, expression: String): List<String> { + return JsonPath.using(PATH_CONFIGURATION).parse(jsonContent).read(expression) + } + + fun paths(jsonNode: JsonNode, expression: String): List<String> { + return paths(jsonNode.asJsonString(), expression) + } + + fun parse(jsonContent: String, expression: String): JsonNode { + return JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).read(expression) + } + + fun parse(jsonNode: JsonNode, expression: String): JsonNode { + return parse(jsonNode.asJsonString(), expression) + } + + fun parseNSet(jsonContent: String, expression: String, value: JsonNode): JsonNode { + return JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).set(expression, value).json() + } + + fun parseNSet(jsonNode: JsonNode, expression: String, valueNode: JsonNode): JsonNode { + + return parseNSet(jsonNode.asJsonString(), expression, valueNode) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt new file mode 100644 index 000000000..c0204af8d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt @@ -0,0 +1,62 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty +import org.slf4j.LoggerFactory +import java.io.File +import java.net.URL + +/** + * + * + * @author Brinda Santh + */ +object ResourceResolverUtils { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + fun getFileContent(filename: String, basePath: String?): String { + log.trace("file ({}), basePath ({}) ", filename, basePath) + try { + var resolvedFileName: String = filename + if (filename.startsWith("http", true) || + filename.startsWith("https", true) + ) { + val givenUrl: String = URL(filename).toString() + val systemUrl: String = File(".").toURI().toURL().toString() + log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl) + if (givenUrl.startsWith(systemUrl)) { + } + } else { + if (!filename.startsWith("/")) { + if (isNotEmpty(basePath)) { + resolvedFileName = basePath.plus(File.separator).plus(filename) + } else { + resolvedFileName = javaClass.classLoader.getResource(".").path.plus(filename) + } + } + } + // FIXME("Convert into reactive") + return JacksonUtils.getContent(resolvedFileName) + } catch (e: Exception) { + throw BluePrintException(e, "failed to file (%s), basePath (%s) ", filename, basePath) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ServiceTemplateUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ServiceTemplateUtils.kt new file mode 100644 index 000000000..a74722f31 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ServiceTemplateUtils.kt @@ -0,0 +1,108 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate + +/** + * + * + * @author Brinda Santh + */ +object ServiceTemplateUtils { + + suspend fun getServiceTemplate(fileName: String): ServiceTemplate { + val content: String = JacksonReactorUtils.getContent(fileName) + return getServiceTemplateFromContent(content) + } + + fun getServiceTemplateFromContent(content: String): ServiceTemplate { + return JacksonUtils.readValue(content) + } + + fun merge(parentServiceTemplate: ServiceTemplate, toMerge: ServiceTemplate, removeImports: Boolean? = true): ServiceTemplate { + if (removeImports!!) { + parentServiceTemplate.imports = null + toMerge.imports = null + } + + toMerge.metadata?.let { + parentServiceTemplate.metadata = parentServiceTemplate.metadata ?: hashMapOf() + parentServiceTemplate.metadata?.putAll(toMerge.metadata as MutableMap) + } + + toMerge.dslDefinitions?.let { + parentServiceTemplate.dslDefinitions = parentServiceTemplate.dslDefinitions ?: hashMapOf() + parentServiceTemplate.dslDefinitions?.putAll(toMerge.dslDefinitions as MutableMap) + } + + toMerge.dataTypes?.let { + parentServiceTemplate.dataTypes = parentServiceTemplate.dataTypes ?: hashMapOf() + parentServiceTemplate.dataTypes?.putAll(toMerge.dataTypes as MutableMap) + } + + toMerge.nodeTypes?.let { + parentServiceTemplate.nodeTypes = parentServiceTemplate.nodeTypes ?: hashMapOf() + parentServiceTemplate.nodeTypes?.putAll(toMerge.nodeTypes as MutableMap) + } + + toMerge.artifactTypes?.let { + parentServiceTemplate.artifactTypes = parentServiceTemplate.artifactTypes ?: hashMapOf() + parentServiceTemplate.artifactTypes?.putAll(toMerge.artifactTypes as MutableMap) + } + + toMerge.repositories?.let { + parentServiceTemplate.repositories = parentServiceTemplate.repositories ?: hashMapOf() + parentServiceTemplate.repositories?.putAll(toMerge.repositories as MutableMap) + } + + parentServiceTemplate.topologyTemplate = parentServiceTemplate.topologyTemplate ?: TopologyTemplate() + + toMerge.topologyTemplate?.inputs?.let { + parentServiceTemplate.topologyTemplate?.inputs = parentServiceTemplate.topologyTemplate?.inputs + ?: hashMapOf() + parentServiceTemplate.topologyTemplate?.inputs?.putAll(parentServiceTemplate.topologyTemplate?.inputs as MutableMap) + } + + toMerge.topologyTemplate?.nodeTemplates?.let { + parentServiceTemplate.topologyTemplate?.nodeTemplates = parentServiceTemplate.topologyTemplate?.nodeTemplates + ?: hashMapOf() + parentServiceTemplate.topologyTemplate?.nodeTemplates?.putAll(parentServiceTemplate.topologyTemplate?.nodeTemplates as MutableMap) + } + + toMerge.topologyTemplate?.relationshipTemplates?.let { + parentServiceTemplate.topologyTemplate?.relationshipTemplates = parentServiceTemplate.topologyTemplate?.relationshipTemplates + ?: hashMapOf() + parentServiceTemplate.topologyTemplate?.relationshipTemplates?.putAll(parentServiceTemplate.topologyTemplate?.relationshipTemplates as MutableMap) + } + + toMerge.topologyTemplate?.policies?.let { + parentServiceTemplate.topologyTemplate?.policies = parentServiceTemplate.topologyTemplate?.policies + ?: hashMapOf() + parentServiceTemplate.topologyTemplate?.policies?.putAll(parentServiceTemplate.topologyTemplate?.policies as MutableMap) + } + + toMerge.topologyTemplate?.workflows?.let { + parentServiceTemplate.topologyTemplate?.workflows = parentServiceTemplate.topologyTemplate?.workflows + ?: hashMapOf() + parentServiceTemplate.topologyTemplate?.workflows?.putAll(parentServiceTemplate.topologyTemplate?.workflows as MutableMap) + } + return parentServiceTemplate + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt new file mode 100644 index 000000000..fb990c486 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt @@ -0,0 +1,132 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.controllerblueprints.core.utils + +import java.util.ArrayList +import java.util.HashMap +import java.util.LinkedList +import java.util.Stack + +/** + * + * + * @author Brinda Santh + */ +class TopologicalSortingUtils<V> { + + private val neighbors: MutableMap<V, MutableList<V>> = hashMapOf() + + val isDag: Boolean + get() = topSort() != null + + override fun toString(): String { + val s = StringBuffer() + for (v in neighbors.keys) + s.append("\n " + v + " -> " + neighbors[v]) + return s.toString() + } + + fun getNeighbors(): Map<V, List<V>> { + return neighbors + } + + fun add(vertex: V) { + if (neighbors.containsKey(vertex)) + return + neighbors[vertex] = arrayListOf() + } + + operator fun contains(vertex: V): Boolean { + return neighbors.containsKey(vertex) + } + + fun add(from: V, to: V) { + this.add(from) + this.add(to) + neighbors[from]?.add(to) + } + + fun remove(from: V, to: V) { + if (!(this.contains(from) && this.contains(to))) + throw IllegalArgumentException("Nonexistent vertex") + neighbors[from]?.remove(to) + } + + fun outDegree(): Map<V, Int> { + val result: MutableMap<V, Int> = hashMapOf() + for (v in neighbors.keys) + result[v] = neighbors[v]!!.size + return result + } + + fun inDegree(): MutableMap<V, Int> { + val result = HashMap<V, Int>() + for (v in neighbors.keys) + result[v] = 0 // All in-degrees are 0 + for (from in neighbors.keys) { + for (to in neighbors[from]!!) { + result[to] = result[to]!! + 1 // Increment in-degree + } + } + return result + } + + fun topSort(): List<V>? { + val degree = inDegree() + // Determine all vertices with zero in-degree + val zeroVerts = Stack<V>() // Stack as good as any here + for (v in degree.keys) { + if (degree[v] == 0) zeroVerts.push(v) + } + // Determine the topological order + val result = ArrayList<V>() + while (!zeroVerts.isEmpty()) { + val v = zeroVerts.pop() // Choose a vertex with zero in-degree + result.add(v) // Vertex v is next in topol order + // "Remove" vertex v by updating its neighbors + for (neighbor in neighbors[v]!!) { + degree[neighbor] = degree[neighbor]!! - 1 + // Remember any vertices that now have zero in-degree + if (degree[neighbor] == 0) zeroVerts.push(neighbor) + } + } + // Check that we have used the entire graph (if not, there was a cycle) + return if (result.size != neighbors.size) null else result + } + + fun bfsDistance(start: V): Map<*, *> { + val distance: MutableMap<V, Int> = hashMapOf() + // Initially, all distance are infinity, except start node + for (v in neighbors.keys) + distance[v] = -1 + distance[start] = 0 + // Process nodes in queue order + val queue = LinkedList<V>() + queue.offer(start) // Place start node in queue + while (!queue.isEmpty()) { + val v = queue.remove() + val vDist = distance[v]!! + // Update neighbors + for (neighbor in neighbors[v]!!) { + if (distance[neighbor] != null) continue // Ignore if already done + distance[neighbor] = vDist + 1 + queue.offer(neighbor) + } + } + return distance + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt new file mode 100644 index 000000000..fea637f61 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt @@ -0,0 +1,46 @@ +/* + * Copyright © 2019 IBM. + * + * 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.controllerblueprints.core.utils + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel +import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.endNodes +import org.onap.ccsdk.cds.controllerblueprints.core.startNodes + +object WorkflowGraphUtils { + + fun workFlowToGraph(workflow: Workflow): Graph { + val graph = Graph() + workflow.steps?.forEach { (stepName, step) -> + step.onSuccess?.forEach { successTarget -> + graph.addEdge(stepName, successTarget, EdgeLabel.SUCCESS) + } + step.onFailure?.forEach { failureTarget -> + graph.addEdge(stepName, failureTarget, EdgeLabel.FAILURE) + } + } + graph.startNodes().forEach { rootNode -> + graph.addEdge(BluePrintConstants.GRAPH_START_NODE_NAME, rootNode.id, EdgeLabel.SUCCESS) + } + graph.endNodes().forEach { endNode -> + graph.addEdge(endNode.id, BluePrintConstants.GRAPH_END_NODE_NAME, EdgeLabel.SUCCESS) + } + return graph + } +} |