2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
6 * ======================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import io.swagger.v3.oas.annotations.Operation;
26 import io.swagger.v3.oas.annotations.Parameter;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.responses.ApiResponses;
31 import io.swagger.v3.oas.annotations.tags.Tag;
32 import java.lang.invoke.MethodHandles;
33 import java.time.Instant;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.List;
38 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
39 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
40 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
41 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
42 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
43 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
44 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
45 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
46 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
48 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
49 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
50 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.http.HttpStatus;
56 import org.springframework.http.MediaType;
57 import org.springframework.http.ResponseEntity;
58 import org.springframework.web.bind.annotation.DeleteMapping;
59 import org.springframework.web.bind.annotation.GetMapping;
60 import org.springframework.web.bind.annotation.PathVariable;
61 import org.springframework.web.bind.annotation.PutMapping;
62 import org.springframework.web.bind.annotation.RequestBody;
63 import org.springframework.web.bind.annotation.RequestParam;
64 import org.springframework.web.bind.annotation.RestController;
65 import org.springframework.web.reactive.function.client.WebClientException;
66 import org.springframework.web.reactive.function.client.WebClientResponseException;
67 import reactor.core.publisher.Mono;
69 @RestController("PolicyControllerV2")
71 name = PolicyController.API_NAME, //
72 description = PolicyController.API_DESCRIPTION //
74 public class PolicyController {
76 public static final String API_NAME = "A1 Policy Management";
77 public static final String API_DESCRIPTION = "";
79 public static class RejectionException extends Exception {
80 private static final long serialVersionUID = 1L;
83 private final HttpStatus status;
85 public RejectionException(String message, HttpStatus status) {
94 private PolicyTypes policyTypes;
96 private Policies policies;
98 private A1ClientFactory a1ClientFactory;
100 private Services services;
102 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
103 private static Gson gson = new GsonBuilder() //
106 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policytype_id:.+}") //
107 @Operation(summary = "Returns a policy type definition") //
108 @ApiResponses(value = { //
109 @ApiResponse(responseCode = "200", //
110 description = "Policy type", //
111 content = @Content(schema = @Schema(implementation = PolicyTypeInfo.class))), //
112 @ApiResponse(responseCode = "404", //
113 description = "Policy type is not found", //
114 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
116 public ResponseEntity<Object> getPolicyType( //
117 @PathVariable("policytype_id") String policyTypeId) throws EntityNotFoundException {
118 PolicyType type = policyTypes.getType(policyTypeId);
119 PolicyTypeInfo info = new PolicyTypeInfo(type.getSchema());
120 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
123 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
124 @Operation(summary = "Query policy type identities")
125 @ApiResponses(value = { //
126 @ApiResponse(responseCode = "200", //
127 description = "Policy type IDs", //
128 content = @Content(schema = @Schema(implementation = PolicyTypeIdList.class))), //
129 @ApiResponse(responseCode = "404", //
130 description = "Near-RT RIC is not found", //
131 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
133 public ResponseEntity<Object> getPolicyTypes( //
134 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
135 description = "Select types for the given Near-RT RIC identity.") //
136 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
138 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
139 description = "Select types with the given type name (type identity has the format <typename_version>)") //
140 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
142 @Parameter(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false, //
143 description = "Select types that are compatible with the given version. This parameter is only applicable in conjunction with "
144 + Consts.TYPE_NAME_PARAM
145 + ". As an example version 1.9.1 is compatible with 1.0.0 but not the other way around."
146 + " Matching types will be returned sorted in ascending order.") //
147 @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
149 ) throws ServiceException {
151 if (compatibleWithVersion != null && typeName == null) {
152 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
153 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
156 Collection<PolicyType> types =
157 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
159 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
160 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
163 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
164 @Operation(summary = "Returns a policy") //
165 @ApiResponses(value = { //
166 @ApiResponse(responseCode = "200", //
167 description = "Policy found", //
168 content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
169 @ApiResponse(responseCode = "404", //
170 description = "Policy is not found", //
171 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
173 public ResponseEntity<Object> getPolicy( //
174 @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
175 Policy p = policies.getPolicy(id);
176 return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
179 @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
180 @Operation(summary = "Delete a policy")
181 @ApiResponses(value = { //
182 @ApiResponse(responseCode = "200", //
183 description = "Not used", //
184 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
185 @ApiResponse(responseCode = "204", //
186 description = "Policy deleted", //
187 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
188 @ApiResponse(responseCode = "404", //
189 description = "Policy is not found", //
190 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
191 @ApiResponse(responseCode = "423", //
192 description = "Near-RT RIC is not operational", //
193 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
195 public Mono<ResponseEntity<Object>> deletePolicy( //
196 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
197 Policy policy = policies.getPolicy(policyId);
198 keepServiceAlive(policy.getOwnerServiceId());
200 return policy.getRic().getLock().lock(LockType.SHARED, "deletePolicy") //
201 .flatMap(grant -> deletePolicy(grant, policy));
204 Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
205 return assertRicStateIdle(policy.getRic()) //
206 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
207 .doOnNext(notUsed -> policies.remove(policy)) //
208 .doFinally(x -> grant.unlockBlocking()) //
209 .flatMap(client -> client.deletePolicy(policy)) //
210 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
211 .onErrorResume(this::handleException);
214 @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
215 @Operation(summary = "Create or update a policy")
216 @ApiResponses(value = { //
217 @ApiResponse(responseCode = "201", //
218 description = "Policy created", //
219 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
220 @ApiResponse(responseCode = "200", //
221 description = "Policy updated", //
222 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
223 @ApiResponse(responseCode = "423", //
224 description = "Near-RT RIC is not operational", //
225 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
226 @ApiResponse(responseCode = "404", //
227 description = "Near-RT RIC or policy type is not found", //
228 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
230 public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
232 if (!policyInfo.validate()) {
233 return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
235 String jsonString = gson.toJson(policyInfo.policyData);
236 Ric ric = rics.get(policyInfo.ricId);
237 PolicyType type = policyTypes.get(policyInfo.policyTypeId);
238 keepServiceAlive(policyInfo.serviceId);
239 if (ric == null || type == null) {
240 throw new EntityNotFoundException("Near-RT RIC or policy type not found");
242 Policy policy = Policy.builder() //
243 .id(policyInfo.policyId) //
247 .ownerServiceId(policyInfo.serviceId) //
248 .lastModified(Instant.now()) //
249 .isTransient(policyInfo.isTransient) //
250 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
253 return ric.getLock().lock(LockType.SHARED, "putPolicy") //
254 .flatMap(grant -> putPolicy(grant, policy));
257 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
258 final boolean isCreate = this.policies.get(policy.getId()) == null;
259 final Ric ric = policy.getRic();
261 return assertRicStateIdle(ric) //
262 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
263 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
264 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
265 .flatMap(client -> client.putPolicy(policy)) //
266 .doOnNext(notUsed -> policies.put(policy)) //
267 .doFinally(x -> grant.unlockBlocking()) //
268 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
269 .onErrorResume(this::handleException);
273 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
274 if (throwable instanceof WebClientResponseException) {
275 WebClientResponseException e = (WebClientResponseException) throwable;
276 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
277 } else if (throwable instanceof WebClientException) {
278 WebClientException e = (WebClientException) throwable;
279 return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
280 } else if (throwable instanceof RejectionException) {
281 RejectionException e = (RejectionException) throwable;
282 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
284 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
288 private Mono<Object> validateModifiedPolicy(Policy policy) {
289 // Check that ric is not updated
290 Policy current = this.policies.get(policy.getId());
291 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
292 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
293 ", RIC ID: " + current.getRic().id() + //
294 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
295 logger.debug("Request rejected, {}", e.getMessage());
296 return Mono.error(e);
298 return Mono.just("{}");
301 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
302 if (!ric.isSupportingType(type.getId())) {
303 logger.debug("Request rejected, type not supported, RIC: {}", ric);
304 RejectionException e = new RejectionException(
305 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
306 return Mono.error(e);
308 return Mono.just("{}");
311 private Mono<Object> assertRicStateIdle(Ric ric) {
312 if (ric.getState() == Ric.RicState.AVAILABLE) {
313 return Mono.just("{}");
315 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
316 RejectionException e = new RejectionException(
317 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
319 return Mono.error(e);
323 static final String GET_POLICIES_QUERY_DETAILS =
324 "Returns a list of A1 policies matching given search criteria. <br>" //
325 + "If several query parameters are defined, the policies matching all conditions are returned.";
327 @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
328 @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
329 @ApiResponses(value = { //
330 @ApiResponse(responseCode = "200", //
331 description = "Policies", //
332 content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
333 @ApiResponse(responseCode = "404", //
334 description = "Near-RT RIC, policy type or service not found", //
335 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
337 public ResponseEntity<Object> getPolicyInstances( //
338 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
339 description = "Select policies with a given type identity.") //
340 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
341 @Parameter(name = Consts.RIC_ID_PARAM, required = false,
342 description = "Select policies for a given Near-RT RIC identity.") //
343 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
344 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
345 description = "Select policies owned by a given service.") //
346 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
347 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
348 description = "Select policies of a given type name (type identity has the format <typename_version>)") //
349 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
350 throws EntityNotFoundException //
352 if ((typeId != null && this.policyTypes.get(typeId) == null)) {
353 throw new EntityNotFoundException("Policy type identity not found");
355 if ((ric != null && this.rics.get(ric) == null)) {
356 throw new EntityNotFoundException("Near-RT RIC not found");
359 String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
360 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
363 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
364 @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
365 @ApiResponses(value = { //
366 @ApiResponse(responseCode = "200", //
367 description = "Policy identities", //
368 content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
369 @ApiResponse(responseCode = "404", //
370 description = "Near-RT RIC or type not found", //
371 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
373 public ResponseEntity<Object> getPolicyIds( //
374 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
375 description = "Select policies of a given policy type identity.") //
376 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
377 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
378 description = "Select policies of a given Near-RT RIC identity.") //
379 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
380 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
381 description = "Select policies owned by a given service.") //
382 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
383 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
384 description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
385 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
386 throws EntityNotFoundException //
388 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
389 throw new EntityNotFoundException("Policy type not found");
391 if ((ricId != null && this.rics.get(ricId) == null)) {
392 throw new EntityNotFoundException("Near-RT RIC not found");
395 String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
396 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
399 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
400 @Operation(summary = "Returns a policy status") //
401 @ApiResponses(value = { //
402 @ApiResponse(responseCode = "200", //
403 description = "Policy status", //
404 content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
405 @ApiResponse(responseCode = "404", //
406 description = "Policy is not found", //
407 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
409 public Mono<ResponseEntity<Object>> getPolicyStatus( //
410 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
411 Policy policy = policies.getPolicy(policyId);
413 return a1ClientFactory.createA1Client(policy.getRic()) //
414 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
415 .flatMap(status -> createPolicyStatus(policy, status)) //
416 .onErrorResume(this::handleException);
420 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
421 PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
422 String str = gson.toJson(info);
423 return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
426 private void keepServiceAlive(String name) {
427 Service s = this.services.get(name);
433 private PolicyInfo toPolicyInfo(Policy p) {
434 PolicyInfo policyInfo = new PolicyInfo();
435 policyInfo.policyId = p.getId();
436 policyInfo.policyData = fromJson(p.getJson());
437 policyInfo.ricId = p.getRic().id();
438 policyInfo.policyTypeId = p.getType().getId();
439 policyInfo.serviceId = p.getOwnerServiceId();
440 policyInfo.isTransient = p.isTransient();
441 if (!p.getStatusNotificationUri().isEmpty()) {
442 policyInfo.statusNotificationUri = p.getStatusNotificationUri();
444 if (!policyInfo.validate()) {
445 logger.error("BUG, all mandatory fields must be set");
451 private String policiesToJson(Collection<Policy> policies) {
452 List<PolicyInfo> v = new ArrayList<>(policies.size());
453 for (Policy p : policies) {
454 v.add(toPolicyInfo(p));
456 PolicyInfoList list = new PolicyInfoList(v);
457 return gson.toJson(list);
460 private Object fromJson(String jsonStr) {
461 return gson.fromJson(jsonStr, Object.class);
464 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
465 List<String> v = new ArrayList<>(types.size());
466 for (PolicyType t : types) {
469 PolicyTypeIdList ids = new PolicyTypeIdList(v);
470 return gson.toJson(ids);
473 private String toPolicyIdsJson(Collection<Policy> policies) {
474 List<String> v = new ArrayList<>(policies.size());
475 for (Policy p : policies) {
478 return gson.toJson(new PolicyIdList(v));