9dd04bf95ce52b725ddd11fd91ea8cd853f853c1
[ccsdk/cds.git] /
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 kotlinx.coroutines.reactive.awaitSingle
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
26 import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.toProto
27 import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
28 import org.onap.ccsdk.cds.controllerblueprints.core.*
29 import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
30 import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
31 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
32 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService
33 import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
34 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
35 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
36 import org.slf4j.LoggerFactory
37 import org.springframework.http.codec.multipart.FilePart
38 import org.springframework.stereotype.Service
39 import java.io.File
40 import java.io.IOException
41 import java.util.*
42 import java.util.stream.Collectors
43
44 @Service
45 class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
46                               private val blueprintsProcessorCatalogService: BluePrintCatalogService,
47                               private val bluePrintWorkflowExecutionService
48                               : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput>) {
49
50     private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString())
51
52     suspend fun upload(filePart: FilePart): String {
53         val saveId = UUID.randomUUID().toString()
54         val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, saveId)
55         val blueprintWorking = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId)
56         try {
57
58             val compressedFile = normalizedFile(blueprintArchive, "cba.zip")
59             compressedFile.parentFile.reCreateNBDirs()
60             // Copy the File Part to Local File
61             copyFromFilePart(filePart, compressedFile)
62             // Save the Copied file to Database
63             return blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, true)
64         } catch (e: IOException) {
65             throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
66                 "Error in Upload CBA: ${e.message}", e)
67         } finally {
68             // Clean blueprint script cache
69             val cacheKey = BluePrintFileUtils
70                     .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath,saveId))
71             BluePrintCompileCache.cleanClassLoader(cacheKey)
72             deleteNBDir(blueprintArchive)
73             deleteNBDir(blueprintWorking)
74         }
75     }
76
77     suspend fun remove(name: String, version: String) {
78         blueprintsProcessorCatalogService.deleteFromDatabase(name, version)
79     }
80
81     suspend fun process(executionServiceInput: ExecutionServiceInput,
82                         responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>) {
83         when {
84             executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> {
85                 GlobalScope.launch(Dispatchers.Default) {
86                     val executionServiceOutput = doProcess(executionServiceInput)
87                     responseObserver.onNext(executionServiceOutput.toProto())
88                     responseObserver.onCompleted()
89                 }
90                 responseObserver.onNext(response(executionServiceInput).toProto())
91             }
92             executionServiceInput.actionIdentifiers.mode == ACTION_MODE_SYNC -> {
93                 val executionServiceOutput = doProcess(executionServiceInput)
94                 responseObserver.onNext(executionServiceOutput.toProto())
95                 responseObserver.onCompleted()
96             }
97             else -> responseObserver.onNext(response(executionServiceInput,
98                 "Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.",
99                 true).toProto());
100         }
101     }
102
103     suspend fun doProcess(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
104         val requestId = executionServiceInput.commonHeader.requestId
105         log.info("processing request id $requestId")
106         val actionIdentifiers = executionServiceInput.actionIdentifiers
107         val blueprintName = actionIdentifiers.blueprintName
108         val blueprintVersion = actionIdentifiers.blueprintVersion
109         try {
110             val basePath = blueprintsProcessorCatalogService.getFromDatabase(blueprintName, blueprintVersion)
111             log.info("blueprint base path $basePath")
112
113             val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString())
114
115             val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(blueprintRuntimeService,
116                 executionServiceInput, hashMapOf())
117
118             val errors = blueprintRuntimeService.getBluePrintError().errors
119             if (errors.isNotEmpty()) {
120                 val errorMessage = errors.stream().map { it.toString() }.collect(Collectors.joining(", "))
121                 setErrorStatus(errorMessage, output.status)
122             }
123             return output
124         } catch (e: Exception) {
125             log.error("fail processing request id $requestId", e)
126             return response(executionServiceInput, e.localizedMessage ?: e.message ?: e.toString(), true)
127         }
128     }
129
130     private suspend fun copyFromFilePart(filePart: FilePart, targetFile: File): File {
131         return filePart.transferTo(targetFile)
132             .thenReturn(targetFile)
133             .awaitSingle()
134     }
135
136     private fun setErrorStatus(errorMessage: String, status: Status) {
137         status.errorMessage = errorMessage
138         status.eventType = EventType.EVENT_COMPONENT_FAILURE.name
139         status.code = 500
140         status.message = BluePrintConstants.STATUS_FAILURE
141     }
142
143     private fun response(executionServiceInput: ExecutionServiceInput, errorMessage: String = "",
144                          failure: Boolean = false): ExecutionServiceOutput {
145         val executionServiceOutput = ExecutionServiceOutput()
146         executionServiceOutput.commonHeader = executionServiceInput.commonHeader
147         executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
148         executionServiceOutput.payload = executionServiceInput.payload
149
150         val status = Status()
151         if (failure) {
152             setErrorStatus(errorMessage, status)
153         } else {
154             status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name
155             status.code = 200
156             status.message = BluePrintConstants.STATUS_PROCESSING
157         }
158
159         executionServiceOutput.status = status
160
161         return executionServiceOutput
162     }
163
164 }