Formatting Code base with ktlint
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / inbounds / selfservice-api / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / selfservice / api / ExecutionServiceHandler.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2019 IBM.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api
19
20 import io.grpc.stub.StreamObserver
21 import kotlinx.coroutines.Dispatchers
22 import kotlinx.coroutines.GlobalScope
23 import kotlinx.coroutines.launch
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
29 import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toProto
30 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractServiceFunction
31 import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
32 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
33 import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
34 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
35 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService
36 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
37 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
38 import org.slf4j.LoggerFactory
39 import org.springframework.stereotype.Service
40 import java.util.stream.Collectors
41
42 @Service
43 class ExecutionServiceHandler(
44     private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
45     private val blueprintsProcessorCatalogService: BluePrintCatalogService,
46     private val bluePrintWorkflowExecutionService:
47     BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput>
48 ) {
49
50     private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString())
51
52     suspend fun process(
53         executionServiceInput: ExecutionServiceInput,
54         responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>
55     ) {
56         when {
57             executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> {
58                 GlobalScope.launch(Dispatchers.Default) {
59                     val executionServiceOutput = doProcess(executionServiceInput)
60                     responseObserver.onNext(executionServiceOutput.toProto())
61                     responseObserver.onCompleted()
62                 }
63                 responseObserver.onNext(response(executionServiceInput).toProto())
64             }
65             executionServiceInput.actionIdentifiers.mode == ACTION_MODE_SYNC -> {
66                 val executionServiceOutput = doProcess(executionServiceInput)
67                 responseObserver.onNext(executionServiceOutput.toProto())
68                 responseObserver.onCompleted()
69             }
70             else -> responseObserver.onNext(
71                 response(
72                     executionServiceInput,
73                     "Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.",
74                     true
75                 ).toProto()
76             )
77         }
78     }
79
80     suspend fun doProcess(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
81         val requestId = executionServiceInput.commonHeader.requestId
82         log.info("processing request id $requestId")
83         val actionIdentifiers = executionServiceInput.actionIdentifiers
84         val blueprintName = actionIdentifiers.blueprintName
85         val blueprintVersion = actionIdentifiers.blueprintVersion
86         try {
87             /** Check Blueprint is needed for this request */
88             if (checkServiceFunction(executionServiceInput)) {
89                 return executeServiceFunction(executionServiceInput)
90             } else {
91                 val basePath = blueprintsProcessorCatalogService.getFromDatabase(blueprintName, blueprintVersion)
92                 log.info("blueprint base path $basePath")
93
94                 val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString())
95
96                 val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(
97                     blueprintRuntimeService,
98                     executionServiceInput, hashMapOf()
99                 )
100
101                 val errors = blueprintRuntimeService.getBluePrintError().errors
102                 if (errors.isNotEmpty()) {
103                     val errorMessage = errors.stream().map { it.toString() }.collect(Collectors.joining(", "))
104                     setErrorStatus(errorMessage, output.status)
105                 }
106                 return output
107             }
108         } catch (e: Exception) {
109             log.error("fail processing request id $requestId", e)
110             return response(executionServiceInput, e.localizedMessage ?: e.message ?: e.toString(), true)
111         }
112     }
113
114     /** If the blueprint name is default, It means no blueprint is needed for the execution */
115     fun checkServiceFunction(executionServiceInput: ExecutionServiceInput): Boolean {
116         return executionServiceInput.actionIdentifiers.blueprintName == "default"
117     }
118
119     /** If no blueprint is needed, then get the Service function instance mapping to the action name and execute it */
120     suspend fun executeServiceFunction(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
121         val actionName = executionServiceInput.actionIdentifiers.actionName
122         val instance = BluePrintDependencyService.instance<AbstractServiceFunction>(actionName)
123         checkNotNull(instance) { "failed to initialize service function($actionName)" }
124         instance.actionName = actionName
125         return instance.applyNB(executionServiceInput)
126     }
127
128     private fun setErrorStatus(errorMessage: String, status: Status) {
129         status.errorMessage = errorMessage
130         status.eventType = EventType.EVENT_COMPONENT_FAILURE.name
131         status.code = 500
132         status.message = BluePrintConstants.STATUS_FAILURE
133     }
134
135     private fun response(
136         executionServiceInput: ExecutionServiceInput,
137         errorMessage: String = "",
138         failure: Boolean = false
139     ): ExecutionServiceOutput {
140         val executionServiceOutput = ExecutionServiceOutput()
141         executionServiceOutput.commonHeader = executionServiceInput.commonHeader
142         executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
143         executionServiceOutput.payload = executionServiceInput.payload
144
145         val status = Status()
146         if (failure) {
147             setErrorStatus(errorMessage, status)
148         } else {
149             status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name
150             status.code = 200
151             status.message = BluePrintConstants.STATUS_PROCESSING
152         }
153
154         executionServiceOutput.status = status
155
156         return executionServiceOutput
157     }
158 }