diff options
44 files changed, 766 insertions, 255 deletions
diff --git a/cds-ui/client/src/app/app.component.html b/cds-ui/client/src/app/app.component.html index 88446ca84..945db342e 100644 --- a/cds-ui/client/src/app/app.component.html +++ b/cds-ui/client/src/app/app.component.html @@ -20,4 +20,10 @@ limitations under the License. --> +<mat-progress-bar mode="indeterminate" *ngIf="loaderStatus === true"></mat-progress-bar> +<div [ngClass]="{'overlay': loaderStatus === true}"> <router-outlet></router-outlet> +<div class="notification-container"> + <app-notification></app-notification> +</div> +</div> diff --git a/cds-ui/client/src/app/app.component.scss b/cds-ui/client/src/app/app.component.scss index bf7a36c2e..8dc7dd0af 100644 --- a/cds-ui/client/src/app/app.component.scss +++ b/cds-ui/client/src/app/app.component.scss @@ -32,4 +32,17 @@ limitations under the License. height: 200px; overflow: auto; border: 1px solid #555; + } + + .overlay { + opacity: 0.5; + pointer-events: none; + } + + .notification-container{ + position: fixed; + top: 1em; + z-index: 1; + right: 1em; + overflow: auto; }
\ No newline at end of file diff --git a/cds-ui/client/src/app/app.component.ts b/cds-ui/client/src/app/app.component.ts index 106417958..d6499cc35 100644 --- a/cds-ui/client/src/app/app.component.ts +++ b/cds-ui/client/src/app/app.component.ts @@ -23,13 +23,22 @@ import { Router } from '@angular/router'; import { Observable} from 'rxjs'; import { Store } from '@ngrx/store'; +import { LoaderService } from './common/core/services/loader.service'; + @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { + loaderStatus: boolean = false; + constructor(private router: Router, + private loaderService: LoaderService + ) { - constructor(private router: Router) { + this.loaderService.subject.subscribe(data=>{ + console.log(data); + this.loaderStatus = data; + }) } } diff --git a/cds-ui/client/src/app/common/core/core.module.ts b/cds-ui/client/src/app/common/core/core.module.ts index 807065ebc..7207178a9 100644 --- a/cds-ui/client/src/app/common/core/core.module.ts +++ b/cds-ui/client/src/app/common/core/core.module.ts @@ -30,6 +30,8 @@ import { appReducers } from './store/reducers/app.reducer'; import { BlueprintEffects } from './store/effects/blueprint.effects'; import { ResourcesEffects } from './store/effects/resources.effects'; import { ApiService } from './services/api.service'; +import { NotificationHandlerService } from './services/notification-handler.service'; +import { LoaderService } from './services/loader.service'; // import { BlueprintService } from './services/blueprint.service'; @NgModule({ @@ -38,10 +40,13 @@ import { ApiService } from './services/api.service'; imports: [ CommonModule, StoreModule.forRoot(appReducers), - EffectsModule.forRoot([BlueprintEffects,ResourcesEffects]), - StoreRouterConnectingModule.forRoot({stateKey: 'router'}), + EffectsModule.forRoot([BlueprintEffects, ResourcesEffects]), + StoreRouterConnectingModule.forRoot({ stateKey: 'router' }), HttpClientModule ], - providers : [ ApiService ] + providers: [ApiService, + NotificationHandlerService, + LoaderService + ] }) export class CoreModule { } diff --git a/cds-ui/client/src/app/common/core/services/notification-handler.service.ts b/cds-ui/client/src/app/common/core/services/notification-handler.service.ts index 296b71e53..b64f2fa0f 100644 --- a/cds-ui/client/src/app/common/core/services/notification-handler.service.ts +++ b/cds-ui/client/src/app/common/core/services/notification-handler.service.ts @@ -23,22 +23,22 @@ limitations under the License. import { Injectable } from '@angular/core'; -// import { NotificationService } from '../../shared/components/notification/notification.service'; +import { NotificationService } from '../../shared/components/notification/notification.service'; @Injectable() export class NotificationHandlerService { constructor( - // private alert: NotificationService + private alert: NotificationService ) { } success(message: string) { - // this.alert.success(message); + this.alert.success(message); } error(message: string) { - // this.alert.error(message); + this.alert.error(message); } info(message: string) { diff --git a/cds-ui/client/src/app/common/shared/shared.module.ts b/cds-ui/client/src/app/common/shared/shared.module.ts index b036f5967..39e4e433f 100644 --- a/cds-ui/client/src/app/common/shared/shared.module.ts +++ b/cds-ui/client/src/app/common/shared/shared.module.ts @@ -30,6 +30,8 @@ import { SearchPipe } from './pipes/search.pipe'; import { SearchDialog } from './components/search-dialog/search-dialog.component'; import { AppMaterialModule } from '../modules/app-material.module'; import { SortPipe } from './pipes/sort.pipe'; +import { NotificationComponent } from './components/notification/notification.component'; +import { NotificationService } from './components/notification/notification.service'; @NgModule({ declarations: [ @@ -37,14 +39,16 @@ import { SortPipe } from './pipes/sort.pipe'; CBAWizardComponent, SearchPipe, SearchDialog, - SortPipe + SortPipe, + NotificationComponent ], exports: [ HomeComponent, CBAWizardComponent, SearchPipe, SearchDialog, - SortPipe + SortPipe, + NotificationComponent ], imports: [ AppMaterialModule, @@ -68,6 +72,7 @@ import { SortPipe } from './pipes/sort.pipe'; MatStepperModule, RouterModule ], + providers: [NotificationService], entryComponents: [SearchDialog] }) export class SharedModule { }
\ No newline at end of file diff --git a/cds-ui/client/src/app/feature-modules/blueprint/modify-template/editor/editor.component.ts b/cds-ui/client/src/app/feature-modules/blueprint/modify-template/editor/editor.component.ts index b982fa29f..0a3a8d2ef 100644 --- a/cds-ui/client/src/app/feature-modules/blueprint/modify-template/editor/editor.component.ts +++ b/cds-ui/client/src/app/feature-modules/blueprint/modify-template/editor/editor.component.ts @@ -39,6 +39,9 @@ import { ApiService } from 'src/app/common/core/services/api.service'; import { IMetaData } from 'src/app/common/core/store/models/metadata.model'; import { EditorService } from './editor.service'; import { SortPipe } from '../../../../common/shared/pipes/sort.pipe'; +import { NotificationHandlerService } from 'src/app/common/core/services/notification-handler.service'; +import { LoaderService } from 'src/app/common/core/services/loader.service'; + interface Node { name: string; @@ -107,6 +110,7 @@ export class EditorComponent implements OnInit { private tocsaMetadaData: any; metadata: IMetaData; uploadedFileName: string; + entryDefinition: string; private transformer = (node: Node, level: number) => { return { @@ -126,7 +130,10 @@ export class EditorComponent implements OnInit { artifactName: any; artifactVersion: any; - constructor(private store: Store<IAppState>, private apiservice: EditorService) { + constructor(private store: Store<IAppState>, private apiservice: EditorService, + private alertService: NotificationHandlerService, private loader: LoaderService + ) + { this.dataSource.data = TREE_DATA; this.bpState = this.store.select('blueprint'); // this.dataSource.data = TREE_DATA; @@ -162,6 +169,7 @@ export class EditorComponent implements OnInit { this.dataSource.data = this.filesTree; this.blueprintName = blueprintdata.name; this.uploadedFileName = blueprintdata.uploadedFileName; + this.entryDefinition = blueprintdata.entryDefinition; let blueprint = []; for (let key in this.blueprintdata) { if (this.blueprintdata.hasOwnProperty(key)) { @@ -206,10 +214,10 @@ export class EditorComponent implements OnInit { name: this.blueprintName, files: this.filesTree, filesData: this.filesData, - uploadedFileName: this.uploadedFileName + uploadedFileName: this.uploadedFileName, + entryDefinition: this.entryDefinition } this.store.dispatch(new SetBlueprintState(blueprintState)); - // console.log(this.text); } selectFileToView(file) { @@ -227,7 +235,6 @@ export class EditorComponent implements OnInit { } }) this.fileExtension = this.selectedFile.substr(this.selectedFile.lastIndexOf('.') + 1); - // console.log(this.fileExtension); this.setEditorMode(); } @@ -248,7 +255,10 @@ export class EditorComponent implements OnInit { console.log("processed"); } }); - window.alert('Blueprint enriched successfully'); + this.alertService.success('Blueprint enriched successfully'); + }, + (error)=>{ + this.alertService.error('Enrich:' + error.message); }); }); } @@ -264,8 +274,9 @@ export class EditorComponent implements OnInit { this.apiservice.post("/create-blueprint/", formData) .subscribe( data => { - // console.log(data); - window.alert('Success:' + JSON.stringify(data)); + this.alertService.success('Success:' + JSON.stringify(data)); + }, error=>{ + this.alertService.error('Save -' +error.message); }); }); @@ -280,8 +291,9 @@ export class EditorComponent implements OnInit { formData.append("file", blob); this.apiservice.deployPost("/deploy-blueprint/", formData) .subscribe(data => { - // console.log(data); - window.alert('Saved Successfully:' + JSON.stringify(data)); + this.alertService.success('Saved Successfully:' + JSON.stringify(data)); + }, error=>{ + this.alertService.error('Deploy - ' + error.message); }); }); @@ -295,8 +307,9 @@ export class EditorComponent implements OnInit { formData.append("file", blob); this.apiservice.post("/publish/", formData) .subscribe(data => { - // console.log(data); - window.alert('Published:' + JSON.stringify(data)); + this.alertService.success('Published:' + JSON.stringify(data)) + }, error=>{ + this.alertService.error('Publish - ' + error.message); }); }); @@ -580,6 +593,7 @@ export class EditorComponent implements OnInit { } saveEditedChanges() { + this.loader.showLoader(); this.filesData.forEach(fileNode => { if (this.selectedFile && fileNode.name.includes(this.blueprintName.trim()) && fileNode.name.includes(this.selectedFile.trim())) { fileNode.data = this.text; @@ -596,5 +610,6 @@ export class EditorComponent implements OnInit { } this.updateBlueprint(); + this.loader.hideLoader(); } } diff --git a/cds-ui/client/src/app/feature-modules/blueprint/select-template/metadata/metadata.component.ts b/cds-ui/client/src/app/feature-modules/blueprint/select-template/metadata/metadata.component.ts index 609aacae7..cefe0fd93 100644 --- a/cds-ui/client/src/app/feature-modules/blueprint/select-template/metadata/metadata.component.ts +++ b/cds-ui/client/src/app/feature-modules/blueprint/select-template/metadata/metadata.component.ts @@ -29,6 +29,7 @@ import { IBlueprintState } from 'src/app/common/core/store/models/blueprintState import { IBlueprint } from 'src/app/common/core/store/models/blueprint.model'; import { IMetaData } from '../../../../common/core/store/models/metadata.model'; import { SetBlueprintState } from 'src/app/common/core/store/actions/blueprint.action'; +import { LoaderService } from '../../../../common/core/services/loader.service'; @Component({ selector: 'app-metadata', @@ -48,7 +49,7 @@ export class MetadataComponent implements OnInit { uploadedFileName: string; entryDefinition: string; - constructor(private formBuilder: FormBuilder, private store: Store<IAppState>) { + constructor(private formBuilder: FormBuilder, private store: Store<IAppState>, private loader: LoaderService) { this.bpState = this.store.select('blueprint'); this.CBAMetadataForm = this.formBuilder.group({ template_author: ['', Validators.required], @@ -96,9 +97,16 @@ export class MetadataComponent implements OnInit { } UploadMetadata() { + this.loader.showLoader(); this.metadata = Object.assign({}, this.CBAMetadataForm.value); this.blueprint.metadata = this.metadata; - + if( this.blueprint && + this.blueprint['topology_template'] && + this.blueprint['topology_template'].workflows && + this.blueprint['topology_template'].workflows['resource-assignment'] && + this.blueprint['topology_template'].workflows['resource-assignment'].name) { + delete this.blueprint['topology_template'].workflows['resource-assignment'].name; + } this.filesData.forEach((fileNode) => { if (fileNode.name.includes(this.blueprintName) && fileNode.name == this.entryDefinition) { fileNode.data = JSON.stringify(this.blueprint, null, "\t"); @@ -113,6 +121,6 @@ export class MetadataComponent implements OnInit { entryDefinition: this.entryDefinition } this.store.dispatch(new SetBlueprintState(blueprintState)); + this.loader.hideLoader(); } - }
\ No newline at end of file diff --git a/cds-ui/client/src/app/feature-modules/blueprint/select-template/search-template/search-template.component.ts b/cds-ui/client/src/app/feature-modules/blueprint/select-template/search-template/search-template.component.ts index 92003c919..1221e8f2b 100644 --- a/cds-ui/client/src/app/feature-modules/blueprint/select-template/search-template/search-template.component.ts +++ b/cds-ui/client/src/app/feature-modules/blueprint/select-template/search-template/search-template.component.ts @@ -30,6 +30,7 @@ import { IAppState } from '../../../../common/core/store/state/app.state'; import { LoadBlueprintSuccess, SET_BLUEPRINT_STATE, SetBlueprintState } from '../../../../common/core/store/actions/blueprint.action'; import { json } from 'd3'; import { SortPipe } from '../../../../common/shared/pipes/sort.pipe'; +import { LoaderService } from '../../../../common/core/services/loader.service'; @Component({ selector: 'app-search-template', @@ -56,7 +57,7 @@ export class SearchTemplateComponent implements OnInit { private blueprintName: string; private entryDefinition: string; - constructor(private store: Store<IAppState>) { } + constructor(private store: Store<IAppState>, private loader: LoaderService) { } ngOnInit() { } @@ -68,7 +69,8 @@ export class SearchTemplateComponent implements OnInit { this.zipFile.files = {}; this.zipFile.loadAsync(this.file) .then((zip) => { - if(zip) { + if(zip) { + this.loader.showLoader(); this.buildFileViewData(zip); } }); @@ -157,8 +159,8 @@ export class SearchTemplateComponent implements OnInit { } } }); - }); - console.log('tree', tree); + }); + this.loader.hideLoader(); return tree; } diff --git a/cds-ui/client/src/app/feature-modules/resource-definition/resource-edit/resource-edit.component.ts b/cds-ui/client/src/app/feature-modules/resource-definition/resource-edit/resource-edit.component.ts index 4603c529f..2da1287ba 100644 --- a/cds-ui/client/src/app/feature-modules/resource-definition/resource-edit/resource-edit.component.ts +++ b/cds-ui/client/src/app/feature-modules/resource-definition/resource-edit/resource-edit.component.ts @@ -30,6 +30,7 @@ import { JsonEditorComponent, JsonEditorOptions } from 'ang-jsoneditor'; import { Observable } from 'rxjs'; import { A11yModule } from '@angular/cdk/a11y'; import { ResourceEditService } from './resource-edit.service'; +import { NotificationHandlerService } from 'src/app/common/core/services/notification-handler.service'; @Component({ selector: 'app-resource-edit', @@ -47,7 +48,7 @@ export class ResourceEditComponent implements OnInit { @ViewChild(JsonEditorComponent) editor: JsonEditorComponent; options = new JsonEditorOptions(); - constructor(private store: Store<IAppState>, private resourceEditService: ResourceEditService) { + constructor(private store: Store<IAppState>, private resourceEditService: ResourceEditService, private alertService: NotificationHandlerService) { this.rdState = this.store.select('resources'); this.options.mode = 'text'; this.options.modes = [ 'text', 'tree', 'view']; @@ -100,10 +101,10 @@ export class ResourceEditComponent implements OnInit { saveToBackend() { this.resourceEditService.saveResource(this.data) .subscribe(response=>{ - window.alert("save success"); + this.alertService.success("save success") }, error=>{ - window.alert('Error saving resources'); + this.alertService.error('Error saving resources'); }) } } diff --git a/components/model-catalog/blueprint-model/test-blueprint/remote_scripts/Definitions/node_types.json b/components/model-catalog/blueprint-model/test-blueprint/remote_scripts/Definitions/node_types.json index ddbccac93..4945da889 100644 --- a/components/model-catalog/blueprint-model/test-blueprint/remote_scripts/Definitions/node_types.json +++ b/components/model-catalog/blueprint-model/test-blueprint/remote_scripts/Definitions/node_types.json @@ -8,9 +8,12 @@ "required" : false, "type" : "string" }, - "execute-command-logs" : { - "required" : false, - "type" : "string" + "execute-command-logs": { + "required": false, + "type": "list", + "entry_schema": { + "type": "string" + } } }, "capabilities" : { @@ -179,4 +182,4 @@ "derived_from" : "tosca.nodes.Root" } } -}
\ No newline at end of file +} diff --git a/components/model-catalog/definition-type/starter-type/node_type/component-remote-python-executor.json b/components/model-catalog/definition-type/starter-type/node_type/component-remote-python-executor.json index e14b63e58..caab5f7ac 100644 --- a/components/model-catalog/definition-type/starter-type/node_type/component-remote-python-executor.json +++ b/components/model-catalog/definition-type/starter-type/node_type/component-remote-python-executor.json @@ -8,7 +8,10 @@ }, "execute-command-logs": { "required": false, - "type": "string" + "type": "list", + "entry_schema": { + "type": "string" + } } }, "capabilities": { @@ -56,4 +59,4 @@ } }, "derived_from": "tosca.nodes.Component" -}
\ No newline at end of file +} diff --git a/components/model-catalog/proto-definition/proto/CommandExecutor.proto b/components/model-catalog/proto-definition/proto/CommandExecutor.proto index bc175dbc1..fd2d4f305 100644 --- a/components/model-catalog/proto-definition/proto/CommandExecutor.proto +++ b/components/model-catalog/proto-definition/proto/CommandExecutor.proto @@ -37,7 +37,7 @@ message Identifiers { message ExecutionOutput { string requestId = 1; - string response = 2; + repeated string response = 2; ResponseStatus status = 3; google.protobuf.Timestamp timestamp = 4; } diff --git a/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml b/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml index 6af268cb0..10cf29d99 100755 --- a/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml +++ b/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml @@ -29,6 +29,7 @@ <outputFileNameMapping>${artifact.groupId}-${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}</outputFileNameMapping> <excludes> <exclude>org.slf4j:slf4j-simple</exclude> + <exclude>org.apache.karaf.*</exclude> </excludes> </dependencySet> </dependencySets> diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliComponentFunction.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliComponentFunction.kt index c7f35f7c8..1b84964e8 100644 --- a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliComponentFunction.kt +++ b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliComponentFunction.kt @@ -41,12 +41,6 @@ abstract class CliComponentFunction : AbstractScriptComponentFunction() { return file.readNBLines() } - suspend fun generateMessage(artifactName: String, json: String): String { - val templateService = BluePrintTemplateService() - return templateService.generateContent(bluePrintRuntimeService, nodeTemplateName, artifactName, json, true) - } - - fun generateMessage(artifactName: String): String { return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) } diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/scripts/InternalSimpleCli.cba.kts b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/scripts/InternalSimpleCli.cba.kts index 18d4a4797..0955ace79 100644 --- a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/scripts/InternalSimpleCli.cba.kts +++ b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/scripts/InternalSimpleCli.cba.kts @@ -20,6 +20,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.CliComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.ComponentCliExecutor import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService import org.slf4j.LoggerFactory open class TestCliScriptFunction : CliComponentFunction() { diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt index 4ef1cfbb3..2de22424e 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt @@ -22,6 +22,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServic import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService import org.onap.ccsdk.cds.controllerblueprints.core.* import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.config.ConfigurableBeanFactory import org.springframework.boot.autoconfigure.condition.ConditionalOnBean @@ -96,7 +97,7 @@ open class ComponentRemotePythonExecutor(private val remoteScriptExecutionServic ) val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput) log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}") - setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, prepareEnvOutput.response.asJsonPrimitive()) + setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)) setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive()) check(prepareEnvOutput.status == StatusType.SUCCESS) { "failed to get prepare remote env response status for requestId(${prepareEnvInput.requestId})" @@ -112,7 +113,7 @@ open class ComponentRemotePythonExecutor(private val remoteScriptExecutionServic properties = properties) val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput) log.info("$ATTRIBUTE_EXEC_CMD_LOG - ${remoteExecutionOutput.response}") - setAttribute(ATTRIBUTE_EXEC_CMD_LOG, remoteExecutionOutput.response.asJsonPrimitive()) + setAttribute(ATTRIBUTE_EXEC_CMD_LOG, JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)) check(remoteExecutionOutput.status == StatusType.SUCCESS) { "failed to get prepare remote command response status for requestId(${remoteExecutionOutput.requestId})" } @@ -128,4 +129,4 @@ open class ComponentRemotePythonExecutor(private val remoteScriptExecutionServic bluePrintRuntimeService.getBluePrintError() .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}") } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt index 896d9a648..166d7b136 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt @@ -189,7 +189,7 @@ class MockRemoteScriptExecutionService : RemoteScriptExecutionService { assertNotNull(prepareEnvInput.packages, "failed to get packages") val remoteScriptExecutionOutput = mockk<RemoteScriptExecutionOutput>() - every { remoteScriptExecutionOutput.response } returns "prepared successfully" + every { remoteScriptExecutionOutput.response } returns listOf("prepared successfully") every { remoteScriptExecutionOutput.status } returns StatusType.SUCCESS return remoteScriptExecutionOutput } @@ -198,7 +198,7 @@ class MockRemoteScriptExecutionService : RemoteScriptExecutionService { assertEquals(remoteExecutionInput.requestId, "123456-1000", "failed to match request id") val remoteScriptExecutionOutput = mockk<RemoteScriptExecutionOutput>() - every { remoteScriptExecutionOutput.response } returns "processed successfully" + every { remoteScriptExecutionOutput.response } returns listOf("processed successfully") every { remoteScriptExecutionOutput.status } returns StatusType.SUCCESS return remoteScriptExecutionOutput } @@ -206,4 +206,4 @@ class MockRemoteScriptExecutionService : RemoteScriptExecutionService { override suspend fun close() { } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt index ebff47899..fe5906220 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt @@ -59,7 +59,8 @@ interface ResourceResolutionService { @Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext, - private var resolutionResultService: ResourceResolutionResultService) : + private var resolutionResultService: ResourceResolutionResultService, + private var blueprintTemplateService: BluePrintTemplateService) : ResourceResolutionService { private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java) @@ -137,7 +138,6 @@ open class ResourceResolutionServiceImpl(private var applicationContext: Applica // Check Template is there if (artifactTemplate != null) { - val blueprintTemplateService = BluePrintTemplateService() resolvedContent = blueprintTemplateService.generateContent(bluePrintRuntimeService, nodeTemplateName, artifactTemplate, resolvedParamJsonContent) @@ -189,6 +189,7 @@ open class ResourceResolutionServiceImpl(private var applicationContext: Applica // Set errors from RA blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError()) } catch (e: RuntimeException) { + log.error("Fail in processing ${resourceAssignment.name}", e) throw BluePrintProcessorException(e) } } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt index 2e91eb93f..242739067 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt @@ -15,8 +15,11 @@ */ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.TextNode +import io.mockk.every +import io.mockk.spyk import kotlinx.coroutines.runBlocking -import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService @@ -28,7 +31,7 @@ import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertNotNull +import kotlin.test.assertTrue @RunWith(SpringRunner::class) @ContextConfiguration(classes = [InputResourceResolutionProcessor::class]) @@ -38,20 +41,21 @@ class InputResourceResolutionProcessorTest { @Autowired lateinit var inputResourceResolutionProcessor: InputResourceResolutionProcessor - @Ignore @Test - fun `test input resource resolution`() { + fun `InputResourceResolutionProcessor should be able to resolve a value for an input parameter`() { runBlocking { + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext) + val resourceAssignmentRuntimeService = spyk(ResourceAssignmentRuntimeService("1234", bluePrintContext)) - inputResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService - inputResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils - .resourceDefinitions(bluePrintContext.rootPath) + // mocking input for resource resolution + val textNode: JsonNode = TextNode("any value") + every {resourceAssignmentRuntimeService.getInputValue("rr-name") } returns textNode - //TODO ("Mock the input Values") + inputResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService + inputResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils.resourceDefinitions(bluePrintContext.rootPath) val resourceAssignment = ResourceAssignment().apply { name = "rr-name" @@ -62,9 +66,8 @@ class InputResourceResolutionProcessorTest { } } - val processorName = inputResourceResolutionProcessor.applyNB(resourceAssignment) - assertNotNull(processorName, "couldn't get Input resource assignment processor name") - println(processorName) + val operationOutcome = inputResourceResolutionProcessor.applyNB(resourceAssignment) + assertTrue(operationOutcome, "An error occurred while trying to test the InputResourceResolutionProcessor") } } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt index 83254cecc..2f9ea4a25 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt @@ -37,7 +37,7 @@ data class RemoteScriptExecutionInput(var requestId: String, data class RemoteScriptExecutionOutput(var requestId: String, - var response: String, + var response: List<String>, var status: StatusType = StatusType.SUCCESS, var timestamp: Date = Date()) @@ -46,4 +46,4 @@ data class PrepareRemoteEnvInput(var requestId: String, var remoteIdentifier: RemoteIdentifier? = null, var packages: JsonNode, var timeOut: Long = 120, - var properties: MutableMap<String, JsonNode> = hashMapOf())
\ No newline at end of file + var properties: MutableMap<String, JsonNode> = hashMapOf()) diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt index 7aee95e11..3af57a22b 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt @@ -148,9 +148,9 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi fun ExecutionOutput.asJavaData(): RemoteScriptExecutionOutput { return RemoteScriptExecutionOutput( requestId = this.requestId, - response = this.response, + response = this.responseList, status = StatusType.valueOf(this.status.name) ) } -}
\ No newline at end of file +} diff --git a/ms/command-executor/src/main/python/command_executor_handler.py b/ms/command-executor/src/main/python/command_executor_handler.py index a5951fdb3..365c00188 100644 --- a/ms/command-executor/src/main/python/command_executor_handler.py +++ b/ms/command-executor/src/main/python/command_executor_handler.py @@ -19,6 +19,7 @@ from subprocess import CalledProcessError, PIPE import logging import os import subprocess +import sys import virtualenv import venv import utils @@ -37,10 +38,7 @@ class CommandExecutorHandler(): self.installed = self.venv_home + '/.installed' def is_installed(self): - if os.path.exists(self.installed): - return True - else: - return False + return os.path.exists(self.installed) def prepare_env(self, request, results): if not self.is_installed(): @@ -78,7 +76,16 @@ class CommandExecutorHandler(): self.logger.info("Command: {}".format(cmd)) try: - results.append(os.popen(cmd).read()) + with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + shell=True, bufsize=1, universal_newlines=True) as newProcess: + while True: + output = newProcess.stdout.readline() + if output == '' and newProcess.poll() is not None: + break + if output: + self.logger.info(output.strip()) + results.append(output.strip()) + rc = newProcess.poll() except Exception as e: self.logger.info("{} - Failed to execute command. Error: {}".format(self.blueprint_id, e)) results.append(e) diff --git a/ms/command-executor/src/main/python/proto/CommandExecutor_pb2.py b/ms/command-executor/src/main/python/proto/CommandExecutor_pb2.py index 3afeb35fc..478e00959 100644 --- a/ms/command-executor/src/main/python/proto/CommandExecutor_pb2.py +++ b/ms/command-executor/src/main/python/proto/CommandExecutor_pb2.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: CommandExecutor.proto @@ -22,7 +23,7 @@ DESCRIPTOR = _descriptor.FileDescriptor( package='org.onap.ccsdk.cds.controllerblueprints.command.api', syntax='proto3', serialized_options=_b('P\001'), - serialized_pb=_b('\n\x15\x43ommandExecutor.proto\x12\x33org.onap.ccsdk.cds.controllerblueprints.command.api\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x8f\x02\n\x0e\x45xecutionInput\x12\x11\n\trequestId\x18\x01 \x01(\t\x12\x15\n\rcorrelationId\x18\x02 \x01(\t\x12U\n\x0bidentifiers\x18\x03 \x01(\x0b\x32@.org.onap.ccsdk.cds.controllerblueprints.command.api.Identifiers\x12\x0f\n\x07\x63ommand\x18\x04 \x01(\t\x12\x0f\n\x07timeOut\x18\x05 \x01(\x05\x12+\n\nproperties\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12-\n\ttimestamp\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xd0\x02\n\x0fPrepareEnvInput\x12U\n\x0bidentifiers\x18\x01 \x01(\x0b\x32@.org.onap.ccsdk.cds.controllerblueprints.command.api.Identifiers\x12\x11\n\trequestId\x18\x02 \x01(\t\x12\x15\n\rcorrelationId\x18\x03 \x01(\t\x12O\n\x08packages\x18\x04 \x03(\x0b\x32=.org.onap.ccsdk.cds.controllerblueprints.command.api.Packages\x12\x0f\n\x07timeOut\x18\x05 \x01(\x05\x12+\n\nproperties\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12-\n\ttimestamp\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\">\n\x0bIdentifiers\x12\x15\n\rblueprintName\x18\x01 \x01(\t\x12\x18\n\x10\x62lueprintVersion\x18\x02 \x01(\t\"\xba\x01\n\x0f\x45xecutionOutput\x12\x11\n\trequestId\x18\x01 \x01(\t\x12\x10\n\x08response\x18\x02 \x01(\t\x12S\n\x06status\x18\x03 \x01(\x0e\x32\x43.org.onap.ccsdk.cds.controllerblueprints.command.api.ResponseStatus\x12-\n\ttimestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"k\n\x08Packages\x12N\n\x04type\x18\x01 \x01(\x0e\x32@.org.onap.ccsdk.cds.controllerblueprints.command.api.PackageType\x12\x0f\n\x07package\x18\x02 \x03(\t**\n\x0eResponseStatus\x12\x0b\n\x07SUCCESS\x10\x00\x12\x0b\n\x07\x46\x41ILURE\x10\x01**\n\x0bPackageType\x12\x07\n\x03pip\x10\x00\x12\x12\n\x0e\x61nsible_galaxy\x10\x01\x32\xd1\x02\n\x16\x43ommandExecutorService\x12\x98\x01\n\nprepareEnv\x12\x44.org.onap.ccsdk.cds.controllerblueprints.command.api.PrepareEnvInput\x1a\x44.org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutput\x12\x9b\x01\n\x0e\x65xecuteCommand\x12\x43.org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionInput\x1a\x44.org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutputB\x02P\x01\x62\x06proto3') + serialized_pb=_b('\n\x15\x43ommandExecutor.proto\x12\x33org.onap.ccsdk.cds.controllerblueprints.command.api\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x8f\x02\n\x0e\x45xecutionInput\x12\x11\n\trequestId\x18\x01 \x01(\t\x12\x15\n\rcorrelationId\x18\x02 \x01(\t\x12U\n\x0bidentifiers\x18\x03 \x01(\x0b\x32@.org.onap.ccsdk.cds.controllerblueprints.command.api.Identifiers\x12\x0f\n\x07\x63ommand\x18\x04 \x01(\t\x12\x0f\n\x07timeOut\x18\x05 \x01(\x05\x12+\n\nproperties\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12-\n\ttimestamp\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xd0\x02\n\x0fPrepareEnvInput\x12U\n\x0bidentifiers\x18\x01 \x01(\x0b\x32@.org.onap.ccsdk.cds.controllerblueprints.command.api.Identifiers\x12\x11\n\trequestId\x18\x02 \x01(\t\x12\x15\n\rcorrelationId\x18\x03 \x01(\t\x12O\n\x08packages\x18\x04 \x03(\x0b\x32=.org.onap.ccsdk.cds.controllerblueprints.command.api.Packages\x12\x0f\n\x07timeOut\x18\x05 \x01(\x05\x12+\n\nproperties\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12-\n\ttimestamp\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\">\n\x0bIdentifiers\x12\x15\n\rblueprintName\x18\x01 \x01(\t\x12\x18\n\x10\x62lueprintVersion\x18\x02 \x01(\t\"\xba\x01\n\x0f\x45xecutionOutput\x12\x11\n\trequestId\x18\x01 \x01(\t\x12\x10\n\x08response\x18\x02 \x03(\t\x12S\n\x06status\x18\x03 \x01(\x0e\x32\x43.org.onap.ccsdk.cds.controllerblueprints.command.api.ResponseStatus\x12-\n\ttimestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"k\n\x08Packages\x12N\n\x04type\x18\x01 \x01(\x0e\x32@.org.onap.ccsdk.cds.controllerblueprints.command.api.PackageType\x12\x0f\n\x07package\x18\x02 \x03(\t**\n\x0eResponseStatus\x12\x0b\n\x07SUCCESS\x10\x00\x12\x0b\n\x07\x46\x41ILURE\x10\x01**\n\x0bPackageType\x12\x07\n\x03pip\x10\x00\x12\x12\n\x0e\x61nsible_galaxy\x10\x01\x32\xd1\x02\n\x16\x43ommandExecutorService\x12\x98\x01\n\nprepareEnv\x12\x44.org.onap.ccsdk.cds.controllerblueprints.command.api.PrepareEnvInput\x1a\x44.org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutput\x12\x9b\x01\n\x0e\x65xecuteCommand\x12\x43.org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionInput\x1a\x44.org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutputB\x02P\x01\x62\x06proto3') , dependencies=[google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) @@ -279,8 +280,8 @@ _EXECUTIONOUTPUT = _descriptor.Descriptor( serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='response', full_name='org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutput.response', index=1, - number=2, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), diff --git a/ms/command-executor/src/main/python/utils.py b/ms/command-executor/src/main/python/utils.py index 6260997f3..dc5d0089f 100644 --- a/ms/command-executor/src/main/python/utils.py +++ b/ms/command-executor/src/main/python/utils.py @@ -17,7 +17,6 @@ from google.protobuf.timestamp_pb2 import Timestamp import proto.CommandExecutor_pb2 as CommandExecutor_pb2 - def get_blueprint_id(request): blueprint_name = request.identifiers.blueprintName blueprint_version = request.identifiers.blueprintVersion @@ -32,6 +31,5 @@ def build_response(request, results, is_success=True): timestamp = Timestamp() timestamp.GetCurrentTime() - - return CommandExecutor_pb2.ExecutionOutput(requestId=request.requestId, response="".join(results), status=status, + return CommandExecutor_pb2.ExecutionOutput(requestId=request.requestId, response=results, status=status, timestamp=timestamp) diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt index 9a652fb92..786bcd3a5 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt @@ -180,6 +180,8 @@ object BluePrintConstants { const val PROPERTY_CURRENT_IMPLEMENTATION = "current-implementation" const val PROPERTY_EXECUTION_REQUEST = "execution-request" + const val DEFAULT_STEP_OPERATION = "process" + const val ARTIFACT_VELOCITY_TYPE_NAME = "artifact-template-velocity" const val ARTIFACT_JINJA_TYPE_NAME = "artifact-template-jinja" }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt index 4f2b7a121..a508c8fbc 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt @@ -34,6 +34,10 @@ fun String.isJson(): Boolean { || (this.startsWith("[") && this.endsWith("]"))) } +fun Any.asJsonString(intend: Boolean? = false): String { + return JacksonUtils.getJson(this, true) +} + fun String.asJsonPrimitive(): TextNode { return TextNode(this) } diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt index 745671ac9..9e934c7c7 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt @@ -192,6 +192,9 @@ class AttributeDefinition { 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 } /* diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt index 4878cb696..95303ea23 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt @@ -17,60 +17,91 @@ package org.onap.ccsdk.cds.controllerblueprints.core.dsl import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.* 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: ServiceTemplateBuilder.() -> Unit): ServiceTemplate { return ServiceTemplateBuilder(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() +} + // Input Function fun getInput(inputKey: String): JsonNode { return """{"get_input": "$inputKey"}""".jsonAsJsonType() } -fun getAttribute(attributeName: String): JsonNode { - return """{"get_attribute": ["SELF", "$attributeName"]}""".jsonAsJsonType() +fun getAttribute(attributeId: String): JsonNode { + return """{"get_attribute": ["SELF", "$attributeId"]}""".jsonAsJsonType() } -fun getAttribute(attributeName: String, jsonPath: String): JsonNode { - return """{"get_attribute": ["SELF", "$attributeName", "$jsonPath"]}""".jsonAsJsonType() +fun getAttribute(attributeId: String, jsonPath: String): JsonNode { + return """{"get_attribute": ["SELF", "$attributeId", "$jsonPath"]}""".jsonAsJsonType() } -fun getNodeTemplateAttribute(nodeTemplateName: String, attributeName: String): JsonNode { - return """{"get_attribute": ["$nodeTemplateName", "$attributeName"]}""".jsonAsJsonType() +fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String): JsonNode { + return """{"get_attribute": ["$nodeTemplateId", "$attributeId"]}""".jsonAsJsonType() } -fun getNodeTemplateAttribute(nodeTemplateName: String, attributeName: String, jsonPath: String): JsonNode { - return """{"get_attribute": ["$nodeTemplateName", "$attributeName", "$jsonPath]}""".jsonAsJsonType() +fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String, jsonPath: String): JsonNode { + return """{"get_attribute": ["$nodeTemplateId", "$attributeId", "$jsonPath]}""".jsonAsJsonType() } // Property Function -fun getProperty(propertyName: String): JsonNode { - return """{"get_property": ["SELF", "$propertyName"]}""".jsonAsJsonType() +fun getProperty(propertyId: String): JsonNode { + return """{"get_property": ["SELF", "$propertyId"]}""".jsonAsJsonType() } -fun getProperty(propertyName: String, jsonPath: String): JsonNode { - return """{"get_property": ["SELF", "$propertyName", "$jsonPath"]}""".jsonAsJsonType() +fun getProperty(propertyId: String, jsonPath: String): JsonNode { + return """{"get_property": ["SELF", "$propertyId", "$jsonPath"]}""".jsonAsJsonType() } -fun getNodeTemplateProperty(nodeTemplateName: String, propertyName: String): JsonNode { - return """{"get_property": ["$nodeTemplateName", "$propertyName"]}""".jsonAsJsonType() +fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String): JsonNode { + return """{"get_property": ["$nodeTemplateName", "$propertyId"]}""".jsonAsJsonType() } -fun getNodeTemplateProperty(nodeTemplateName: String, propertyName: String, jsonPath: String): JsonNode { - return """{"get_property": ["$nodeTemplateName", "$propertyName", "$jsonPath]}""".jsonAsJsonType() +fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String, jsonPath: String): JsonNode { + return """{"get_property": ["$nodeTemplateName", "$propertyId", "$jsonPath]}""".jsonAsJsonType() } // Artifact Function -fun getArtifact(artifactName: String): JsonNode { - return """{"get_artifact": ["SELF", "$artifactName"]}""".jsonAsJsonType() +fun getArtifact(artifactId: String): JsonNode { + return """{"get_artifact": ["SELF", "$artifactId"]}""".jsonAsJsonType() } -fun getNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): JsonNode { - return """{"get_artifact": ["$nodeTemplateName", "$artifactName"]}""".jsonAsJsonType() +fun getNodeTemplateArtifact(nodeTemplateName: String, artifactId: String): JsonNode { + return """{"get_artifact": ["$nodeTemplateName", "$artifactId"]}""".jsonAsJsonType() }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt new file mode 100644 index 000000000..8cfa90b15 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt @@ -0,0 +1,342 @@ +/* + * 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.* + +/** + * @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 dataType: MutableMap<String, DataType> = hashMapOf() + var artifacts: MutableMap<String, ArtifactDefinition> = hashMapOf() + var components: MutableMap<String, DSLComponent> = 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(id: String, version: String, derivedFrom: String, description: String, + block: DataTypeBuilder.() -> Unit) { + dataType[id] = DataTypeBuilder(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 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.dataType = dataType + dslBluePrint.components = components + 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 + + // For already registered components + private var assignProperties: MutableMap<String, JsonNode>? = null + + var artifacts: MutableMap<String, ArtifactDefinition>? = null + var implementation: Implementation? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null + + // For already registered components + private var assignInputs: MutableMap<String, JsonNode>? = null + private var assignOutputs: MutableMap<String, JsonNode>? = 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 assignProperty(id: String, expression: Any) { + if (assignProperties == null) + assignProperties = hashMapOf() + assignProperties!![id] = expression.asJsonType() + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun artifacts(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifacts(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 assignInput(id: String, expression: Any) { + if (assignInputs == null) + assignInputs = hashMapOf() + assignInputs!![id] = expression.asJsonType() + } + + 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 assignOutput(id: String, expression: Any) { + if (assignOutputs == null) + assignOutputs = hashMapOf() + assignOutputs!![id] = expression.asJsonType() + } + + fun build(): DSLComponent { + dslComponent.id = id + dslComponent.type = type + dslComponent.version = version + dslComponent.description = description + dslComponent.attributes = attributes + dslComponent.properties = properties + dslComponent.assignProperties = assignProperties + dslComponent.implementation = implementation + dslComponent.artifacts = artifacts + dslComponent.inputs = inputs + dslComponent.outputs = outputs + dslComponent.assignInputs = assignInputs + dslComponent.assignOutputs = assignOutputs + 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 + } +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt new file mode 100644 index 000000000..12428a90c --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt @@ -0,0 +1,61 @@ +/* + * 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.* + +/** + * 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 dataType: MutableMap<String, DataType> = hashMapOf() + var components: MutableMap<String, DSLComponent> = 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 assignProperties: MutableMap<String, JsonNode>? = null + var artifacts: MutableMap<String, ArtifactDefinition>? = null + var inputs: MutableMap<String, PropertyDefinition>? = null + var outputs: MutableMap<String, PropertyDefinition>? = null + var assignInputs: MutableMap<String, JsonNode>? = null + var assignOutputs: MutableMap<String, JsonNode>? = null +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt index 7973293ae..f19ae8eb8 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt @@ -87,7 +87,7 @@ class NodeTemplateBuilder(private val id: String, interfaces = hashMapOf() val interfaceAssignment = InterfaceAssignment() - val defaultOperationName = "process" + val defaultOperationName = BluePrintConstants.DEFAULT_STEP_OPERATION interfaceAssignment.operations = hashMapOf() interfaceAssignment.operations!![defaultOperationName] = OperationAssignmentBuilder(defaultOperationName, description).apply(block).build() diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt index 5ec3df160..f98cf58d3 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt @@ -16,6 +16,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.dsl +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants 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 @@ -30,7 +31,7 @@ class WorkflowBuilder(private val id: String, private val description: String) { // Used Internally fun nodeTemplateStep(nodeTemplateName: String, description: String) { - step(nodeTemplateName, nodeTemplateName, "") + step(nodeTemplateName, nodeTemplateName, "$description step") } fun step(id: String, target: String, description: String) { @@ -98,7 +99,7 @@ class StepBuilder(private val id: String, private val target: String, step.id = id step.target = target // Add Default Activity, Assumption is only one Operation - activity(".process") + activity(".${BluePrintConstants.DEFAULT_STEP_OPERATION}") step.description = description step.activities = activities step.onSuccess = onSuccess diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt index 86bf3ff56..98abf8987 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt @@ -40,21 +40,6 @@ interface BlueprintTemplateService { jsonData: String = "", ignoreJsonNull: Boolean = false, additionalContext: MutableMap<String, Any> = mutableMapOf()): String - - - /** - * Generate dynamique content using Velocity Template or Jinja template - * - * @param template template string content - * @param templateType template type - * @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(template: String, templateType: String, jsonData: String = "", ignoreJsonNull: Boolean = false, - additionalContext: MutableMap<String, Any> = mutableMapOf()): String } /** diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt index 912667e0a..baddd6a12 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt @@ -16,20 +16,76 @@ 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.google.common.io.Resources import com.hubspot.jinjava.Jinjava +import com.hubspot.jinjava.interpret.Context +import com.hubspot.jinjava.interpret.JinjavaInterpreter +import com.hubspot.jinjava.loader.ClasspathResourceLocator +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.config.BluePrintPathConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode - +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service +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 bluePrintPathConfiguration: BluePrintPathConfiguration, + 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(bluePrintPathConfiguration.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>): String { - // Load template + additionalContext: MutableMap<String, Any>, + bluePrintPathConfiguration: BluePrintPathConfiguration, artifactName: String, + artifactVersion: String): String { + + + return generateContent(template, + json, + ignoreJsonNull, + additionalContext, + BlueprintRelatedTemplateLocator(bluePrintPathConfiguration, artifactName, artifactVersion)) + } + + fun generateContent(template: String, json: String, ignoreJsonNull: Boolean, + additionalContext: MutableMap<String, Any>, resourceLocator: ResourceLocator? = null): String { val jinJava = Jinjava() + if (resourceLocator != null) { + jinJava.resourceLocator = resourceLocator + } + val mapper = ObjectMapper() val nodeFactory = BluePrintJsonNodeFactory() mapper.nodeFactory = nodeFactory @@ -37,15 +93,16 @@ object BluePrintJinjaTemplateService { // 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) + ?: throw BluePrintProcessorException("couldn't get json node from json") + if (ignoreJsonNull) { jsonNode.removeNullNode() - jsonNode.fields().forEach { entry -> - additionalContext[entry.key] = entry.value } + + val jsonMap: Map<String, Any> = mapper.readValue(json, object : TypeReference<Map<String, Any>>() {}) + additionalContext.putAll(jsonMap) } - return jinJava.render(template, additionalContext.toMap()) + return jinJava.render(template, additionalContext) } } diff --git a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt index 45e2678ed..af97d6691 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt @@ -17,26 +17,33 @@ 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.BluePrintPathConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTemplateService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service -class BluePrintTemplateService : BlueprintTemplateService { +@Service +class BluePrintTemplateService(private val bluePrintPathConfiguration: BluePrintPathConfiguration) : + 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 artifactDefinition = + bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) val templateType = artifactDefinition.type val template = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) - return generateContent(template, templateType, jsonData, ignoreJsonNull, additionalContext) - } - override suspend fun generateContent(template: String, templateType: String, jsonData: String, ignoreJsonNull: Boolean, - additionalContext: MutableMap<String, Any>): String { return when (templateType) { BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME -> { - BluePrintJinjaTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext) + BluePrintJinjaTemplateService.generateContent(template, + jsonData, + ignoreJsonNull, + additionalContext, + bluePrintPathConfiguration, + bluePrintRuntimeService.bluePrintContext().name(), + bluePrintRuntimeService.bluePrintContext().version()) } BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME -> { BluePrintVelocityTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext) @@ -47,12 +54,4 @@ class BluePrintTemplateService : BlueprintTemplateService { } } } - - suspend fun generateContentFromFiles(templatePath: String, templateType: String, jsonPath: String, - ignoreJsonNull: Boolean, - additionalContext: MutableMap<String, Any>): String { - val json = JacksonUtils.getClassPathFileContent(jsonPath) - val template = JacksonUtils.getClassPathFileContent(templatePath) - return generateContent(template, templateType, json, ignoreJsonNull, additionalContext) - } }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt index dff0f943f..e7f24d629 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt @@ -21,6 +21,44 @@ import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType import kotlin.test.assertNotNull class BluePrintDSLTest { + + @Test + fun testOperationDSLWorkflow() { + + val blueprint = blueprint("sample-bp", "1.0.0", + "brindasanth@onap.com", "sample, blueprints") { + + // For New Component Definition + component("resource-resolution", "component-resource-resolution", "1.0.0", + "Resource Resolution Call") { + implementation(180) + // Attributes ( Properties which will be set during execution) + attribute("template1-data", "string", true, "") + + // Properties + property("string-value1", "string", true, "sample") + property("string-value2", "string", true, getInput("key-1")) + // Inputs + input("json-content", "json", true, """{ "name" : "cds"}""") + input("template-content", "string", true, getArtifact("template1")) + // Outputs + output("self-attribute-expression", "json", true, getAttribute("template1-data")) + // Artifacts + artifacts("template1", "artifact-velocity", "Templates/template1.vtl") + } + + workflow("resource-resolution-process", "") { + input("json-content", "json", true, "") + input("key-1", "string", true, "") + output("status", "string", true, "success") + step("resource-resolution-call", "resource-resolution", "Resource Resolution component invoke") + } + } + assertNotNull(blueprint.components, "failed to get components") + assertNotNull(blueprint.workflows, "failed to get workflows") + //println(blueprint.asJsonString(true)) + } + @Test fun testServiceTemplate() { val serviceTemplate = serviceTemplate("sample-bp", "1.0.0", @@ -88,7 +126,7 @@ class BluePrintDSLTest { assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template") assertNotNull(serviceTemplate.topologyTemplate?.nodeTemplates, "failed to get nodeTypes") assertNotNull(serviceTemplate.topologyTemplate?.nodeTemplates!!["activate"], "failed to get nodeTypes(activate)") - //println(JacksonUtils.getJson(serviceTemplate, true)) + //println(serviceTemplate.asJsonString(true)) } @Test @@ -107,7 +145,7 @@ class BluePrintDSLTest { } assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template") assertNotNull(serviceTemplate.topologyTemplate?.workflows?.get("activate"), "failed to get workflow(activate)") - //println(JacksonUtils.getJson(serviceTemplate, true)) + //println(serviceTemplate.asJsonString(true)) } } diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt index 6f961c8ed..63c8ad74e 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt @@ -36,7 +36,8 @@ class BluePrintTemplateServiceTest { @BeforeTest fun setup() { - val blueprintBasePath: String = ("./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + val blueprintBasePath: String = + ("./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") blueprintRuntime = BluePrintMetadataUtils.getBluePrintRuntime("1234", blueprintBasePath) } @@ -55,11 +56,12 @@ class BluePrintTemplateServiceTest { @Test fun testJinjaGeneratedContent() { runBlocking { - val template = JacksonUtils.getClassPathFileContent("templates/base-config-jinja-template.jinja") + val template = JacksonUtils.getClassPathFileContent("templates/master.jinja") val json = JacksonUtils.getClassPathFileContent("templates/base-config-data-jinja.json") var element: MutableMap<String, Any> = mutableMapOf() - element["additional_array"] = arrayListOf(hashMapOf("name" to "Element1", "location" to "Region0"), hashMapOf("name" to "Element2", "location" to "Region1")) + element["additional_array"] = arrayListOf(hashMapOf("name" to "Element1", "location" to "Region0"), + hashMapOf("name" to "Element2", "location" to "Region1")) val content = BluePrintJinjaTemplateService.generateContent(template, json, false, element) assertNotNull(content, "failed to generate content for velocity template") @@ -67,42 +69,12 @@ class BluePrintTemplateServiceTest { } - @Test - fun testVelocityGeneratedContentFromFiles() { - runBlocking { - val bluePrintTemplateService = BluePrintTemplateService() - val templateFile = "templates/base-config-velocity-template.vtl" - val jsonFile = "templates/base-config-data-velocity.json" - - val content = bluePrintTemplateService.generateContentFromFiles( - templateFile, BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME, jsonFile, false, mutableMapOf()) - assertNotNull(content, "failed to generate content for velocity template") - } - - } - - @Test - fun testJinjaGeneratedContentFromFiles() { - runBlocking { - var element: MutableMap<String, Any> = mutableMapOf() - element["additional_array"] = arrayListOf(hashMapOf("name" to "Element1", "location" to "Region0"), hashMapOf("name" to "Element2", "location" to "Region1")) - - val bluePrintTemplateService = BluePrintTemplateService() - - val templateFile = "templates/base-config-jinja-template.jinja" - val jsonFile = "templates/base-config-data-jinja.json" - - val content = bluePrintTemplateService.generateContentFromFiles( - templateFile, BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME, - jsonFile, false, element) - assertNotNull(content, "failed to generate content for velocity template") - } - } @Test fun `no value variable should evaluate to default value - standalone template mesh test`() { runBlocking { - val template = JacksonUtils.getClassPathFileContent("templates/default-variable-value-velocity-template.vtl") + val template = + JacksonUtils.getClassPathFileContent("templates/default-variable-value-velocity-template.vtl") val json = JacksonUtils.getClassPathFileContent("templates/default-variable-value-data.json") val content = BluePrintVelocityTemplateService.generateContent(template, json) @@ -113,24 +85,5 @@ class BluePrintTemplateServiceTest { } } - @Test - fun `no value variable should evaluate to default value - blueprint processing test`() { - runBlocking { - val bluePrintTemplateService = BluePrintTemplateService() - - val templateFile = "templates/default-variable-value-velocity-template.vtl" - val jsonFile = "templates/default-variable-value-data.json" - - val content = bluePrintTemplateService.generateContentFromFiles(templateFile, - BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME, jsonFile, false, mutableMapOf()) - - //first line represents a variable whose value was successfully retrieved, second line contains a variable - // whose value could not be evaluated - val expected = "sample-hostname\n\${node0_backup_router_address}" - assertEquals(expected, content, "No value variable should use default value") - } - - } - } diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-data-jinja.json b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-data-jinja.json index bbfb38d80..ab7abf3d4 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-data-jinja.json +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-data-jinja.json @@ -1,16 +1,3 @@ { - "node_hostname": "sdnc-host", - "node_backup_router_address": "2001:1890:1253::192:168:100:1", - "node_backup_router_d_address": "2011:1090:1253::112:158:100:1", - "servers": [ - "Server1", - "Server2", - "Server3" - ], - "classes": [ - "superuser-class", - "tacacs-adv-class", - "tacacs-base-class" - ], - "system_password": "teamops-system-password" + "occurrence": 2 }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-jinja-template.jinja b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-jinja-template.jinja deleted file mode 100755 index db900bc8b..000000000 --- a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/base-config-jinja-template.jinja +++ /dev/null @@ -1,42 +0,0 @@ -<configuration xmlns="http://xml.juniper.net/xnm/1.1/xnm" -xmlns:a="http://xml.juniper.net/junos/15.1X49/junos"> - <version>15.1X49-D50.3</version> - <groups> - <name>node0</name> - <system> - {%- for server in servers %} - <server-host-name>{{ server }}</server-host-name> - {%- endfor %} - </system> - <system> - <host-name>{{ node_hostname }}</host-name> - <backup-router> - <address>{{ node_backup_router_address }}</address> - <destination>{{ node_backup_router_d_address }}</destination> - </backup-router> - <login> - <message>ONAP information assets</message> - {%- for class in classes %} - <class> - {{ class }} - </class> - {%- endfor %} - <user> - <name>readwrite</name> - <full-name>Read - Write Account Access</full-name> - <uid>1002</uid> - <class>tacacs-adv-class</class> - <authentication> - <encrypted-password>{{ system_password }}</encrypted-password> - </authentication> - </user> - </login> - {%- for element in additional_array %} - <additionalArray> - <name>{{ element.name }}</name> - <location>{{ element.location }}</location> - </additionalArray> - {%- endfor %} - </system> - </groups> -</configuration>
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/interface.jinja b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/interface.jinja new file mode 100755 index 000000000..93114d90a --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/interface.jinja @@ -0,0 +1,3 @@ + <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg"> +blo + </interface-configurations>
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/isis.jinja b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/isis.jinja new file mode 100644 index 000000000..f46d91330 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/isis.jinja @@ -0,0 +1,3 @@ + <isis xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-clns-isis-cfg"> +blah + </isis>
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/master.jinja b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/master.jinja new file mode 100644 index 000000000..1137b2595 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/resources/templates/master.jinja @@ -0,0 +1,7 @@ +{%- for i in range(occurrence) %} +<config> +{% include "templates/isis.jinja" %} +{% include "templates/interface.jinja" %} +</config> +{{ "]]>]]" if not loop.last }} +{%- endfor %}
\ No newline at end of file @@ -19,7 +19,7 @@ limitations under the License. <parent> <groupId>org.onap.ccsdk.parent</groupId> - <artifactId>odlparent-lite</artifactId> + <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.0-SNAPSHOT</version> <relativePath/> </parent> |