aboutsummaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotController.kt
blob: 8b976e1c9e307c32bfa34e56d769de0266c431dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
 * Copyright © 2021 Bell Canada
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.ccsdk.cds.blueprintsprocessor.configs.api

import com.fasterxml.jackson.databind.JsonNode
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import kotlinx.coroutines.runBlocking
import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshot
import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshotService
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException
import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes
import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import java.util.Optional

/**
 * Exposes Resource Configuration Snapshot API to store and retrieve stored resource configurations.
 *
 * @author Serge Simard
 * @version 1.0
 */
@RestController
@RequestMapping("/api/v1/configs")
@Api(
    value = "Resource configuration",
    description = "Interaction with stored configurations"
)
open class ResourceConfigSnapshotController(private val resourceConfigSnapshotService: ResourceConfigSnapshotService) {

    private val JSON_MIME_TYPE = "application/json"

    @RequestMapping(
        path = ["/health-check"],
        method = [RequestMethod.GET],
        produces = [MediaType.APPLICATION_JSON_VALUE]
    )
    @ResponseBody
    @ApiOperation(value = "Health Check", hidden = true)
    fun ressCfgSnapshotControllerHealthCheck(): JsonNode = runBlocking {
        "Success".asJsonPrimitive()
    }

    @RequestMapping(
        method = [RequestMethod.GET],
        produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
    )
    @ApiOperation(
        value = "Retrieve a resource configuration snapshot",
        notes = "Retrieve a config snapshot, identified by its Resource Id and Type. " +
            "An extra 'format' parameter can be passed to tell what content-type is expected."
    )
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    fun get(
        @ApiParam(value = "Resource Type associated of the resource configuration snapshot", required = false, example = "\"PNF\"")
        @RequestParam(value = "resourceType", required = true) resourceType: String,

        @ApiParam(value = "Resource Id associated of the resource configuration snapshot", required = false, example = "\"1\"")
        @RequestParam(value = "resourceId", required = true) resourceId: String,

        @ApiParam(value = "Status of the snapshot being retrieved", defaultValue = "RUNNING", required = false)
        @RequestParam(value = "status", required = false, defaultValue = "RUNNING") status: String,

        @ApiParam(
            value = "Expected format of the snapshot being retrieved", defaultValue = MediaType.TEXT_PLAIN_VALUE,
            required = false
        )
        @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
    ):

        ResponseEntity<String> = runBlocking {

            var configSnapshot = ""

            if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
                try {
                    configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(
                        resourceId,
                        resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
                    )
                } catch (ex: NoSuchElementException) {
                    throw httpProcessorException(
                        ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
                        "Could not find configuration snapshot entry for type $resourceType and Id $resourceId",
                        ex.errorCauseOrDefault()
                    )
                } catch (ex: Exception) {
                    throw httpProcessorException(
                        ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
                        "Could not find configuration snapshot entry for type $resourceType and Id $resourceId",
                        ex.errorCauseOrDefault()
                    )
                }
            } else {
                throw httpProcessorException(
                    ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
                    "Missing param. You must specify resource-id and resource-type."
                )
            }

            var expectedContentType = format
            if (expectedContentType.indexOf('/') < 0) {
                expectedContentType = "application/$expectedContentType"
            }
            val expectedMediaType: MediaType = MediaType.valueOf(expectedContentType)

            ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshot)
        }

    @PostMapping(
        "/{resourceType}/{resourceId}/{status}",
        produces = [MediaType.APPLICATION_JSON_VALUE]
    )
    @ApiOperation(
        value = "Store a resource configuration snapshot identified by resourceId, resourceType, status",
        notes = "Store a resource configuration snapshot, identified by its resourceId and resourceType, " +
            "and optionally its status, either RUNNING or CANDIDATE.",
        response = ResourceConfigSnapshot::class
    )
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    fun postWithResourceIdAndResourceType(
        @ApiParam(value = "Resource Type associated with the resolution", required = false, example = "\"PNF\"")
        @PathVariable(value = "resourceType", required = true) resourceType: String,
        @ApiParam(value = "Resource Id associated with the resolution", required = false, example = "\"1\"")
        @PathVariable(value = "resourceId", required = true) resourceId: String,
        @ApiParam(value = "Status of the snapshot being retrieved", defaultValue = "RUNNING", required = true)
        @PathVariable(value = "status", required = true) status: String,
        @ApiParam(value = "Config snapshot to store", required = true, example = "\"config_snapshot\"")
        @RequestBody snapshot: String
    ): ResponseEntity<ResourceConfigSnapshot> = runBlocking {

        val resultStored =
            resourceConfigSnapshotService.write(
                snapshot, resourceId, resourceType,
                ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
            )

        ResponseEntity.ok().body(resultStored)
    }

    @DeleteMapping(
        "/{resourceType}/{resourceId}/{status}",
        "/{resourceType}/{resourceId}"
    )
    @ApiOperation(
        value = "Delete a resource configuration snapshot identified by resourceId, resourceType, status.",
        notes = "Delete a resource configuration snapshot, identified by its resourceId and resourceType, " +
            "and optionally its status, either RUNNING or CANDIDATE."
    )
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    suspend fun deleteWithResourceIdAndResourceType(
        @ApiParam(value = "Resource Type associated with the resolution.", required = true)
        @PathVariable(value = "resourceType", required = true) resourceType: String,
        @ApiParam(value = "Resource Id associated with the resolution.", required = true)
        @PathVariable(value = "resourceId", required = true) resourceId: String,
        @ApiParam(value = "Status of the snapshot being deleted.", required = false)
        @PathVariable(value = "status", required = false) status: Optional<String>
    ) = mdcWebCoroutineScope {

        if (resourceId.isBlank() || resourceType.isBlank())
            throw httpProcessorException(
                ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
                "You must specify path variables resource-id and resource-type."
            )

        try {
            if (status.isPresent)
                resourceConfigSnapshotService.deleteByResourceIdAndResourceTypeAndStatus(
                    resourceId, resourceType,
                    ResourceConfigSnapshot.Status.valueOf(status.get().toUpperCase())
                )
            else {
                resourceConfigSnapshotService.deleteByResourceIdAndResourceTypeAndStatus(
                    resourceId, resourceType,
                    ResourceConfigSnapshot.Status.RUNNING
                )
                resourceConfigSnapshotService.deleteByResourceIdAndResourceTypeAndStatus(
                    resourceId, resourceType,
                    ResourceConfigSnapshot.Status.CANDIDATE
                )
            }
        } catch (ex: Exception) {
            throw httpProcessorException(
                ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
                "Could not delete configuration snapshot entry for type $resourceType and Id $resourceId",
                ex.errorCauseOrDefault()
            )
        }
    }

    @RequestMapping(
        path = ["/allByID"],
        method = [RequestMethod.GET],
        produces = [MediaType.APPLICATION_JSON_VALUE]
    )
    @ApiOperation(
        value = "Retrieve all resource configuration snapshots identified by a given resource_id",
        notes = "Retrieve all config snapshots, identified by its Resource Id, ordered by most recently created/modified date. "
    )
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    fun getAllByID(
        @ApiParam(value = "Resource Id associated of the resource configuration snapshots", required = false, example = "\"1\"")
        @RequestParam(value = "resourceId", required = true) resourceId: String,
        @ApiParam(value = "Status of the snapshot being retrieved", defaultValue = "ANY", required = false)
        @RequestParam(value = "status", required = false, defaultValue = "ANY") status: String
    ): ResponseEntity<List<ResourceConfigSnapshot>?> = runBlocking {
        var configSnapshots: List<ResourceConfigSnapshot>?

        try {
            if (status == "ANY") {
                configSnapshots = resourceConfigSnapshotService.findAllByResourceId(resourceId)
            } else {
                configSnapshots = resourceConfigSnapshotService.findAllByResourceIdForStatus(
                    resourceId, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
                )
            }
        } catch (ex: NoSuchElementException) {
            throw httpProcessorException(
                ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
                "Could not find configuration snapshot entry for ID $resourceId",
                ex.errorCauseOrDefault()
            )
        } catch (ex: Exception) {
            throw httpProcessorException(
                ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
                "Unexpected error while finding configuration snapshot entries for ID $resourceId",
                ex.errorCauseOrDefault()
            )
        }

        val expectedMediaType: MediaType = MediaType.valueOf(JSON_MIME_TYPE)
        ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshots)
    }

    @RequestMapping(
        path = ["allByType"],
        method = [RequestMethod.GET],
        produces = [MediaType.APPLICATION_JSON_VALUE]
    )
    @ApiOperation(
        value = "Retrieve all resource configuration snapshots for a given resource type",
        notes = "Retrieve all config snapshots matching a specified Resource Type, ordered by most recently created/modified date. "
    )
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    fun getAllByType(
        @ApiParam(value = "Resource Type associated of the resource configuration snapshot", required = false, example = "\"PNF\"")
        @RequestParam(value = "resourceType", required = true) resourceType: String,
        @ApiParam(value = "Status of the snapshot being retrieved", defaultValue = "ANY", required = false)
        @RequestParam(value = "status", required = false, defaultValue = "ANY") status: String
    ): ResponseEntity<List<ResourceConfigSnapshot>?> = runBlocking {
        var configSnapshots: List<ResourceConfigSnapshot>?

        try {
            if (status == "ANY") {
                configSnapshots = resourceConfigSnapshotService.findAllByResourceType(resourceType)
            } else {
                configSnapshots = resourceConfigSnapshotService.findAllByResourceTypeForStatus(
                    resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
                )
            }
        } catch (ex: NoSuchElementException) {
            throw httpProcessorException(
                ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
                "Could not find configuration snapshot entry for ID $resourceType",
                ex.errorCauseOrDefault()
            )
        } catch (ex: Exception) {
            throw httpProcessorException(
                ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
                "Unexpected error while finding configuration snapshot entries for type $resourceType",
                ex.errorCauseOrDefault()
            )
        }

        val expectedMediaType: MediaType = MediaType.valueOf(JSON_MIME_TYPE)
        ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshots)
    }
}