0116680cf861210bfbe14fcc7b2b7133c3cfd989
[ccsdk/cds.git] /
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2019 Bell Canada.
4  * Modifications Copyright © 2019 IBM.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api
20
21 import io.grpc.StatusException
22 import io.grpc.stub.StreamObserver
23 import kotlinx.coroutines.runBlocking
24 import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.currentTimestamp
25 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
26 import org.onap.ccsdk.cds.controllerblueprints.common.api.Status
27 import org.onap.ccsdk.cds.controllerblueprints.core.*
28 import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
29 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
30 import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
31 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
32 import org.onap.ccsdk.cds.controllerblueprints.management.api.*
33 import org.slf4j.LoggerFactory
34 import org.springframework.security.access.prepost.PreAuthorize
35 import org.springframework.stereotype.Service
36 import java.io.File
37 import java.util.*
38
39 // TODO("move to management-api or designer-api module")
40 @Service
41 open class BluePrintManagementGRPCHandler(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
42                                           private val blueprintsProcessorCatalogService: BluePrintCatalogService)
43     : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() {
44
45     private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java)
46
47     @PreAuthorize("hasRole('USER')")
48     override fun uploadBlueprint(request: BluePrintUploadInput, responseObserver:
49     StreamObserver<BluePrintManagementOutput>) {
50         runBlocking {
51
52             log.info("request(${request.commonHeader.requestId})")
53             val uploadId = UUID.randomUUID().toString()
54             val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, uploadId)
55             val blueprintWorking = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, uploadId)
56             try {
57                 val cbaFile = normalizedFile(blueprintArchive, "cba.zip")
58
59                 saveToDisk(request, cbaFile)
60
61                 val uploadAction = request.actionIdentifiers?.actionName.emptyTONull()
62                         ?: UploadAction.DRAFT.toString()
63
64                 when (uploadAction) {
65                     UploadAction.DRAFT.toString() -> {
66                         val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(uploadId, cbaFile, false)
67                         responseObserver.onNext(successStatus("Successfully uploaded CBA($blueprintId)...",
68                                 request.commonHeader))
69                     }
70                     UploadAction.PUBLISH.toString() -> {
71                         val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(uploadId, cbaFile, true)
72                         responseObserver.onNext(successStatus("Successfully uploaded CBA($blueprintId)...",
73                                 request.commonHeader))
74                     }
75                     UploadAction.VALIDATE.toString() -> {
76                         //TODO("Not Implemented")
77                         responseObserver.onError(failStatus("Not Implemented",
78                                 BluePrintProcessorException("Not Implemented")))
79                     }
80                     UploadAction.ENRICH.toString() -> {
81                         //TODO("Not Implemented")
82                         responseObserver.onError(failStatus("Not Implemented",
83                                 BluePrintProcessorException("Not Implemented")))
84                     }
85                 }
86                 responseObserver.onCompleted()
87             } catch (e: Exception) {
88                 responseObserver.onError(failStatus("request(${request.commonHeader.requestId}): Failed to upload CBA", e))
89             } finally {
90                 // Clean blueprint script cache
91                 val cacheKey = BluePrintFileUtils
92                         .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, uploadId))
93                 BluePrintCompileCache.cleanClassLoader(cacheKey)
94                 deleteNBDir(blueprintArchive)
95                 deleteNBDir(blueprintWorking)
96             }
97         }
98     }
99
100     @PreAuthorize("hasRole('USER')")
101     override fun removeBlueprint(request: BluePrintRemoveInput, responseObserver:
102     StreamObserver<BluePrintManagementOutput>) {
103
104         runBlocking {
105             val blueprintName = request.blueprintName
106             val blueprintVersion = request.blueprintVersion
107             val blueprint = "blueprint $blueprintName:$blueprintVersion"
108
109             log.info("request(${request.commonHeader.requestId}): Received delete $blueprint")
110
111
112             try {
113                 blueprintsProcessorCatalogService.deleteFromDatabase(blueprintName, blueprintVersion)
114                 responseObserver.onNext(successStatus("Successfully deleted $blueprint", request.commonHeader))
115                 responseObserver.onCompleted()
116             } catch (e: Exception) {
117                 responseObserver.onError(failStatus("request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
118             }
119         }
120     }
121
122     private fun saveToDisk(request: BluePrintUploadInput, cbaFile: File) {
123         log.info("request(${request.commonHeader.requestId}): Writing CBA File under :${cbaFile.absolutePath}")
124
125         // Recreate Folder
126         cbaFile.parentFile.reCreateDirs()
127
128         // Write the File
129         cbaFile.writeBytes(request.fileChunk.chunk.toByteArray()).apply {
130             log.info("request(${request.commonHeader.requestId}): CBA file(${cbaFile.absolutePath} written successfully")
131         }
132
133     }
134
135     private fun successStatus(message: String, header: CommonHeader): BluePrintManagementOutput =
136             BluePrintManagementOutput.newBuilder()
137                     .setCommonHeader(header)
138                     .setStatus(Status.newBuilder()
139                             .setTimestamp(currentTimestamp())
140                             .setMessage(message)
141                             .setCode(200)
142                             .build())
143                     .build()
144
145     private fun failStatus(message: String, e: Exception): StatusException {
146         log.error(message, e)
147         return io.grpc.Status.INTERNAL
148                 .withDescription(message)
149                 .withCause(e)
150                 .asException()
151     }
152 }