6c62aae886456f7a1e4b9a477ab61c34a368f34c
[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     private val publishAuditService: PublishAuditService
49 ) {
50
51     private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString())
52
53     suspend fun process(
54         executionServiceInput: ExecutionServiceInput,
55         responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>
56     ) {
57         when {
58             executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> {
59                 GlobalScope.launch(Dispatchers.Default) {
60                     val executionServiceOutput = doProcess(executionServiceInput)
61                     responseObserver.onNext(executionServiceOutput.toProto())
62                     responseObserver.onCompleted()
63                 }
64                 responseObserver.onNext(response(executionServiceInput).toProto())
65             }
66             executionServiceInput.actionIdentifiers.mode == ACTION_MODE_SYNC -> {
67                 val executionServiceOutput = doProcess(executionServiceInput)
68                 responseObserver.onNext(executionServiceOutput.toProto())
69                 responseObserver.onCompleted()
70             }
71             else -> {
72                 publishAuditService.publishExecutionInput(executionServiceInput)
73                 val executionServiceOutput = response(
74                         executionServiceInput,
75                         "Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.",
76                         true
77                 )
78                 publishAuditService.publishExecutionOutput(executionServiceInput.correlationUUID, executionServiceOutput)
79                 responseObserver.onNext(
80                         executionServiceOutput.toProto()
81                 )
82             }
83         }
84     }
85
86     suspend fun doProcess(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
87         val requestId = executionServiceInput.commonHeader.requestId
88         val actionIdentifiers = executionServiceInput.actionIdentifiers
89         val blueprintName = actionIdentifiers.blueprintName
90         val blueprintVersion = actionIdentifiers.blueprintVersion
91
92         lateinit var executionServiceOutput: ExecutionServiceOutput
93
94         log.info("processing request id $requestId")
95
96         publishAuditService.publishExecutionInput(executionServiceInput)
97
98         try {
99             /** Check Blueprint is needed for this request */
100             if (checkServiceFunction(executionServiceInput)) {
101                 executionServiceOutput = executeServiceFunction(executionServiceInput)
102             } else {
103                 val basePath = blueprintsProcessorCatalogService.getFromDatabase(blueprintName, blueprintVersion)
104                 log.info("blueprint base path $basePath")
105
106                 val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString())
107
108                 executionServiceOutput = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(
109                     blueprintRuntimeService,
110                     executionServiceInput, hashMapOf()
111                 )
112
113                 val errors = blueprintRuntimeService.getBluePrintError().errors
114                 if (errors.isNotEmpty()) {
115                     val errorMessage = errors.stream().map { it.toString() }.collect(Collectors.joining(", "))
116                     setErrorStatus(errorMessage, executionServiceOutput.status)
117                 }
118             }
119         } catch (e: Exception) {
120             log.error("fail processing request id $requestId", e)
121             executionServiceOutput = response(executionServiceInput, e.localizedMessage ?: e.message ?: e.toString(), true)
122         }
123
124         publishAuditService.publishExecutionOutput(executionServiceInput.correlationUUID, executionServiceOutput)
125         return executionServiceOutput
126     }
127
128     /** If the blueprint name is default, It means no blueprint is needed for the execution */
129     fun checkServiceFunction(executionServiceInput: ExecutionServiceInput): Boolean {
130         return executionServiceInput.actionIdentifiers.blueprintName == "default"
131     }
132
133     /** If no blueprint is needed, then get the Service function instance mapping to the action name and execute it */
134     suspend fun executeServiceFunction(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
135         val actionName = executionServiceInput.actionIdentifiers.actionName
136         val instance = BluePrintDependencyService.instance<AbstractServiceFunction>(actionName)
137         checkNotNull(instance) { "failed to initialize service function($actionName)" }
138         instance.actionName = actionName
139         return instance.applyNB(executionServiceInput)
140     }
141
142     private fun setErrorStatus(errorMessage: String, status: Status) {
143         status.errorMessage = errorMessage
144         status.eventType = EventType.EVENT_COMPONENT_FAILURE.name
145         status.code = 500
146         status.message = BluePrintConstants.STATUS_FAILURE
147     }
148
149     private fun response(
150         executionServiceInput: ExecutionServiceInput,
151         errorMessage: String = "",
152         failure: Boolean = false
153     ): ExecutionServiceOutput {
154         val executionServiceOutput = ExecutionServiceOutput()
155         executionServiceOutput.commonHeader = executionServiceInput.commonHeader
156         executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
157         executionServiceOutput.payload = executionServiceInput.payload
158
159         val status = Status()
160         if (failure) {
161             setErrorStatus(errorMessage, status)
162         } else {
163             status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name
164             status.code = 200
165             status.message = BluePrintConstants.STATUS_PROCESSING
166         }
167
168         executionServiceOutput.status = status
169
170         return executionServiceOutput
171     }
172 }