05f43c1518a128205ad641cca3c172a9dc1dae3b
[ccsdk/cds.git] /
1 /*
2  * Copyright © 2019 Bell Canada
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.configs.api
18
19 import com.fasterxml.jackson.databind.JsonNode
20 import io.swagger.annotations.Api
21 import io.swagger.annotations.ApiOperation
22 import io.swagger.annotations.ApiParam
23 import kotlinx.coroutines.runBlocking
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshot
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshotService
26 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
27 import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException
28 import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes
29 import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault
30 import org.springframework.http.MediaType
31 import org.springframework.http.ResponseEntity
32 import org.springframework.security.access.prepost.PreAuthorize
33 import org.springframework.web.bind.annotation.PathVariable
34 import org.springframework.web.bind.annotation.PostMapping
35 import org.springframework.web.bind.annotation.RequestBody
36 import org.springframework.web.bind.annotation.RequestMapping
37 import org.springframework.web.bind.annotation.RequestMethod
38 import org.springframework.web.bind.annotation.RequestParam
39 import org.springframework.web.bind.annotation.ResponseBody
40 import org.springframework.web.bind.annotation.RestController
41
42 /**
43  * Exposes Resource Configuration Snapshot API to store and retrieve stored resource configurations.
44  *
45  * @author Serge Simard
46  * @version 1.0
47  */
48 @RestController
49 @RequestMapping("/api/v1/configs")
50 @Api(
51     value = "/api/v1/configs",
52     description = "Interaction with stored configurations."
53 )
54 open class ResourceConfigSnapshotController(private val resourceConfigSnapshotService: ResourceConfigSnapshotService) {
55
56     private val JSON_MIME_TYPE = "application/json"
57
58     @RequestMapping(
59         path = ["/health-check"],
60         method = [RequestMethod.GET],
61         produces = [MediaType.APPLICATION_JSON_VALUE]
62     )
63     @ResponseBody
64     @ApiOperation(value = "Health Check", hidden = true)
65     fun ressCfgSnapshotControllerHealthCheck(): JsonNode = runBlocking {
66         "Success".asJsonPrimitive()
67     }
68
69     @RequestMapping(
70         path = [""],
71         method = [RequestMethod.GET],
72         produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
73     )
74     @ApiOperation(
75         value = "Retrieve a resource configuration snapshot.",
76         notes = "Retrieve a config snapshot, identified by its Resource Id and Type. " +
77                 "An extra 'format' parameter can be passed to tell what content-type is expected."
78     )
79     @ResponseBody
80     @PreAuthorize("hasRole('USER')")
81     fun get(
82         @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
83         @RequestParam(value = "resourceType", required = true) resourceType: String,
84
85         @ApiParam(value = "Resource Id associated of the resource configuration snapshot.", required = false)
86         @RequestParam(value = "resourceId", required = true) resourceId: String,
87
88         @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = false)
89         @RequestParam(value = "status", required = false, defaultValue = "RUNNING") status: String,
90
91         @ApiParam(
92             value = "Expected format of the snapshot being retrieved.", defaultValue = MediaType.TEXT_PLAIN_VALUE,
93             required = false
94         )
95         @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
96     ):
97
98             ResponseEntity<String> = runBlocking {
99
100         var configSnapshot = ""
101
102         if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
103             try {
104                 configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(
105                     resourceId,
106                     resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
107                 )
108             } catch (ex: NoSuchElementException) {
109                 throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
110                         "Could not find configuration snapshot entry for type $resourceType and Id $resourceId",
111                         ex.errorCauseOrDefault())
112             } catch (ex: Exception) {
113                 throw httpProcessorException(ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
114                         "Could not find configuration snapshot entry for type $resourceType and Id $resourceId",
115                         ex.errorCauseOrDefault())
116             }
117         } else {
118             throw httpProcessorException(ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
119                     "Missing param. You must specify resource-id and resource-type.")
120         }
121
122         var expectedContentType = format
123         if (expectedContentType.indexOf('/') < 0) {
124             expectedContentType = "application/$expectedContentType"
125         }
126         val expectedMediaType: MediaType = MediaType.valueOf(expectedContentType)
127
128         ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshot)
129     }
130
131     @PostMapping(
132         "/{resourceType}/{resourceId}/{status}",
133         produces = [MediaType.APPLICATION_JSON_VALUE]
134     )
135     @ApiOperation(
136         value = "Store a resource configuration snapshot identified by resourceId, resourceType, status.",
137         notes = "Store a resource configuration snapshot, identified by its resourceId and resourceType, " +
138                 "and optionally its status, either RUNNING or CANDIDATE.",
139         response = ResourceConfigSnapshot::class, produces = MediaType.APPLICATION_JSON_VALUE
140     )
141     @ResponseBody
142     @PreAuthorize("hasRole('USER')")
143     fun postWithResourceIdAndResourceType(
144         @ApiParam(value = "Resource Type associated with the resolution.", required = false)
145         @PathVariable(value = "resourceType", required = true) resourceType: String,
146         @ApiParam(value = "Resource Id associated with the resolution.", required = false)
147         @PathVariable(value = "resourceId", required = true) resourceId: String,
148         @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = true)
149         @PathVariable(value = "status", required = true) status: String,
150         @ApiParam(value = "Config snapshot to store.", required = true)
151         @RequestBody snapshot: String
152     ): ResponseEntity<ResourceConfigSnapshot> = runBlocking {
153
154         val resultStored =
155             resourceConfigSnapshotService.write(
156                 snapshot, resourceId, resourceType,
157                 ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
158             )
159
160         ResponseEntity.ok().body(resultStored)
161     }
162
163     @RequestMapping(
164             path = ["/allByID"],
165             method = [RequestMethod.GET],
166             produces = [MediaType.APPLICATION_JSON_VALUE]
167     )
168     @ApiOperation(
169             value = "Retrieve all resource configuration snapshots identified by a given resource_id",
170             notes = "Retrieve all config snapshots, identified by its Resource Id, ordered by most recently created/modified date. "
171     )
172     @ResponseBody
173     @PreAuthorize("hasRole('USER')")
174     fun getAllByID(
175         @ApiParam(value = "Resource Id associated of the resource configuration snapshots.", required = false)
176         @RequestParam(value = "resourceId", required = true) resourceId: String,
177         @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "ANY", required = false)
178         @RequestParam(value = "status", required = false, defaultValue = "ANY") status: String
179     ): ResponseEntity<List<ResourceConfigSnapshot>?> = runBlocking {
180         var configSnapshots: List<ResourceConfigSnapshot>?
181
182         try {
183             if (status == "ANY") {
184                 configSnapshots = resourceConfigSnapshotService.findAllByResourceId(resourceId)
185             } else {
186                 configSnapshots = resourceConfigSnapshotService.findAllByResourceIdForStatus(
187                         resourceId, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase()))
188             }
189         } catch (ex: NoSuchElementException) {
190             throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
191                     "Could not find configuration snapshot entry for ID $resourceId",
192                     ex.errorCauseOrDefault())
193         } catch (ex: Exception) {
194             throw httpProcessorException(ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
195                     "Unexpected error while finding configuration snapshot entries for ID $resourceId",
196                     ex.errorCauseOrDefault())
197         }
198
199         val expectedMediaType: MediaType = MediaType.valueOf(JSON_MIME_TYPE)
200         ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshots)
201     }
202
203     @RequestMapping(
204             path = ["allByType"],
205             method = [RequestMethod.GET],
206             produces = [MediaType.APPLICATION_JSON_VALUE]
207     )
208     @ApiOperation(
209             value = "Retrieve all resource configuration snapshots for a given resource type.",
210             notes = "Retrieve all config snapshots matching a specified Resource Type, ordered by most recently created/modified date. "
211     )
212     @ResponseBody
213     @PreAuthorize("hasRole('USER')")
214     fun getAllByType(
215         @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
216         @RequestParam(value = "resourceType", required = true) resourceType: String,
217         @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "ANY", required = false)
218         @RequestParam(value = "status", required = false, defaultValue = "ANY") status: String
219     ): ResponseEntity<List<ResourceConfigSnapshot>?> = runBlocking {
220         var configSnapshots: List<ResourceConfigSnapshot>?
221
222         try {
223             if (status == "ANY") {
224                 configSnapshots = resourceConfigSnapshotService.findAllByResourceType(resourceType)
225             } else {
226                 configSnapshots = resourceConfigSnapshotService.findAllByResourceTypeForStatus(
227                         resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase()))
228             }
229         } catch (ex: NoSuchElementException) {
230             throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
231                     "Could not find configuration snapshot entry for ID $resourceType",
232                     ex.errorCauseOrDefault())
233         } catch (ex: Exception) {
234             throw httpProcessorException(ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
235                     "Unexpected error while finding configuration snapshot entries for type $resourceType",
236                     ex.errorCauseOrDefault())
237         }
238
239         val expectedMediaType: MediaType = MediaType.valueOf(JSON_MIME_TYPE)
240         ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshots)
241     }
242 }