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;
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.Content;
29 import io.swagger.v3.oas.annotations.media.Schema;
30 import io.swagger.v3.oas.annotations.responses.ApiResponse;
31 import io.swagger.v3.oas.annotations.responses.ApiResponses;
32 import io.swagger.v3.oas.annotations.tags.Tag;
34 import java.lang.invoke.MethodHandles;
35 import java.time.Instant;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.List;
42 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
43 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
44 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
45 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
46 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
48 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
49 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
50 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.MediaType;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.web.bind.annotation.DeleteMapping;
63 import org.springframework.web.bind.annotation.GetMapping;
64 import org.springframework.web.bind.annotation.PathVariable;
65 import org.springframework.web.bind.annotation.PutMapping;
66 import org.springframework.web.bind.annotation.RequestBody;
67 import org.springframework.web.bind.annotation.RequestParam;
68 import org.springframework.web.bind.annotation.RestController;
69 import org.springframework.web.reactive.function.client.WebClientException;
70 import org.springframework.web.reactive.function.client.WebClientResponseException;
71 import reactor.core.publisher.Mono;
73 @RestController("PolicyControllerV2")
75 name = PolicyController.API_NAME, //
76 description = PolicyController.API_DESCRIPTION //
78 public class PolicyController {
80 public static final String API_NAME = "A1 Policy Management";
81 public static final String API_DESCRIPTION = "";
83 public static class RejectionException extends Exception {
84 private static final long serialVersionUID = 1L;
87 private final HttpStatus status;
89 public RejectionException(String message, HttpStatus status) {
98 private PolicyTypes policyTypes;
100 private Policies policies;
102 private A1ClientFactory a1ClientFactory;
104 private Services services;
106 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
107 private static Gson gson = new GsonBuilder() //
110 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policytype_id:.+}") //
111 @Operation(summary = "Returns a policy type definition") //
112 @ApiResponses(value = { //
113 @ApiResponse(responseCode = "200", //
114 description = "Policy type", //
115 content = @Content(schema = @Schema(implementation = PolicyTypeInfo.class))), //
116 @ApiResponse(responseCode = "404", //
117 description = "Policy type is not found", //
118 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
120 public ResponseEntity<Object> getPolicyType( //
121 @PathVariable("policytype_id") String policyTypeId) throws EntityNotFoundException {
122 PolicyType type = policyTypes.getType(policyTypeId);
123 PolicyTypeInfo info = new PolicyTypeInfo(type.getSchema());
124 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
127 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
128 @Operation(summary = "Query policy type identities")
129 @ApiResponses(value = { //
130 @ApiResponse(responseCode = "200", //
131 description = "Policy type IDs", //
132 content = @Content(schema = @Schema(implementation = PolicyTypeIdList.class))), //
133 @ApiResponse(responseCode = "404", //
134 description = "Near-RT RIC is not found", //
135 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
137 public ResponseEntity<Object> getPolicyTypes( //
138 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
139 description = "Select types for the given Near-RT RIC identity.") //
140 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
142 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
143 description = "Select types with the given type name (type identity has the format <typename_version>)") //
144 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
146 @Parameter(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false, //
147 description = "Select types that are compatible with the given version. This parameter is only applicable in conjunction with "
148 + Consts.TYPE_NAME_PARAM
149 + ". As an example version 1.9.1 is compatible with 1.0.0 but not the other way around."
150 + " Matching types will be returned sorted in ascending order.") //
151 @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
153 ) throws ServiceException {
155 if (compatibleWithVersion != null && typeName == null) {
156 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
157 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
160 Collection<PolicyType> types =
161 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
163 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
164 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
167 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
168 @Operation(summary = "Returns a policy") //
169 @ApiResponses(value = { //
170 @ApiResponse(responseCode = "200", //
171 description = "Policy found", //
172 content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
173 @ApiResponse(responseCode = "404", //
174 description = "Policy is not found", //
175 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
177 public ResponseEntity<Object> getPolicy( //
178 @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
179 Policy p = policies.getPolicy(id);
180 return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
183 @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
184 @Operation(summary = "Delete a policy")
185 @ApiResponses(value = { //
186 @ApiResponse(responseCode = "200", //
187 description = "Not used", //
188 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
189 @ApiResponse(responseCode = "204", //
190 description = "Policy deleted", //
191 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
192 @ApiResponse(responseCode = "404", //
193 description = "Policy is not found", //
194 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
195 @ApiResponse(responseCode = "423", //
196 description = "Near-RT RIC is not operational", //
197 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
199 public Mono<ResponseEntity<Object>> deletePolicy( //
200 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
201 Policy policy = policies.getPolicy(policyId);
202 keepServiceAlive(policy.getOwnerServiceId());
204 return policy.getRic().getLock().lock(LockType.SHARED, "deletePolicy") //
205 .flatMap(grant -> deletePolicy(grant, policy));
208 Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
209 return assertRicStateIdle(policy.getRic()) //
210 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
211 .doOnNext(notUsed -> policies.remove(policy)) //
212 .doFinally(x -> grant.unlockBlocking()) //
213 .flatMap(client -> client.deletePolicy(policy)) //
214 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
215 .onErrorResume(this::handleException);
218 @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
219 @Operation(summary = "Create or update a policy")
220 @ApiResponses(value = { //
221 @ApiResponse(responseCode = "201", //
222 description = "Policy created", //
223 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
224 @ApiResponse(responseCode = "200", //
225 description = "Policy updated", //
226 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
227 @ApiResponse(responseCode = "423", //
228 description = "Near-RT RIC is not operational", //
229 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
230 @ApiResponse(responseCode = "404", //
231 description = "Near-RT RIC or policy type is not found", //
232 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
234 public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
236 if (!policyInfo.validate()) {
237 return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
239 String jsonString = gson.toJson(policyInfo.policyData);
240 Ric ric = rics.get(policyInfo.ricId);
241 PolicyType type = policyTypes.get(policyInfo.policyTypeId);
242 keepServiceAlive(policyInfo.serviceId);
243 if (ric == null || type == null) {
244 throw new EntityNotFoundException("Near-RT RIC or policy type not found");
246 Policy policy = Policy.builder() //
247 .id(policyInfo.policyId) //
251 .ownerServiceId(policyInfo.serviceId) //
252 .lastModified(Instant.now()) //
253 .isTransient(policyInfo.isTransient) //
254 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
257 return ric.getLock().lock(LockType.SHARED, "putPolicy") //
258 .flatMap(grant -> putPolicy(grant, policy));
261 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
262 final boolean isCreate = this.policies.get(policy.getId()) == null;
263 final Ric ric = policy.getRic();
265 return assertRicStateIdle(ric) //
266 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
267 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
268 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
269 .flatMap(client -> client.putPolicy(policy)) //
270 .doOnNext(notUsed -> policies.put(policy)) //
271 .doFinally(x -> grant.unlockBlocking()) //
272 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
273 .onErrorResume(this::handleException);
277 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
278 if (throwable instanceof WebClientResponseException) {
279 WebClientResponseException e = (WebClientResponseException) throwable;
280 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
281 } else if (throwable instanceof WebClientException) {
282 WebClientException e = (WebClientException) throwable;
283 return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
284 } else if (throwable instanceof RejectionException) {
285 RejectionException e = (RejectionException) throwable;
286 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
288 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
292 private Mono<Object> validateModifiedPolicy(Policy policy) {
293 // Check that ric is not updated
294 Policy current = this.policies.get(policy.getId());
295 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
296 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
297 ", RIC ID: " + current.getRic().id() + //
298 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
299 logger.debug("Request rejected, {}", e.getMessage());
300 return Mono.error(e);
302 return Mono.just("{}");
305 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
306 if (!ric.isSupportingType(type.getId())) {
307 logger.debug("Request rejected, type not supported, RIC: {}", ric);
308 RejectionException e = new RejectionException(
309 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
310 return Mono.error(e);
312 return Mono.just("{}");
315 private Mono<Object> assertRicStateIdle(Ric ric) {
316 if (ric.getState() == Ric.RicState.AVAILABLE) {
317 return Mono.just("{}");
319 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
320 RejectionException e = new RejectionException(
321 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
323 return Mono.error(e);
327 static final String GET_POLICIES_QUERY_DETAILS =
328 "Returns a list of A1 policies matching given search criteria. <br>" //
329 + "If several query parameters are defined, the policies matching all conditions are returned.";
331 @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
332 @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
333 @ApiResponses(value = { //
334 @ApiResponse(responseCode = "200", //
335 description = "Policies", //
336 content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
337 @ApiResponse(responseCode = "404", //
338 description = "Near-RT RIC, policy type or service not found", //
339 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
341 public ResponseEntity<Object> getPolicyInstances( //
342 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
343 description = "Select policies with a given type identity.") //
344 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
345 @Parameter(name = Consts.RIC_ID_PARAM, required = false,
346 description = "Select policies for a given Near-RT RIC identity.") //
347 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
348 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
349 description = "Select policies owned by a given service.") //
350 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
351 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
352 description = "Select policies of a given type name (type identity has the format <typename_version>)") //
353 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
354 throws EntityNotFoundException //
356 if ((typeId != null && this.policyTypes.get(typeId) == null)) {
357 throw new EntityNotFoundException("Policy type identity not found");
359 if ((ric != null && this.rics.get(ric) == null)) {
360 throw new EntityNotFoundException("Near-RT RIC not found");
363 String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
364 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
367 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
368 @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
369 @ApiResponses(value = { //
370 @ApiResponse(responseCode = "200", //
371 description = "Policy identities", //
372 content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
373 @ApiResponse(responseCode = "404", //
374 description = "Near-RT RIC or type not found", //
375 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
377 public ResponseEntity<Object> getPolicyIds( //
378 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
379 description = "Select policies of a given policy type identity.") //
380 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
381 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
382 description = "Select policies of a given Near-RT RIC identity.") //
383 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
384 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
385 description = "Select policies owned by a given service.") //
386 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
387 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
388 description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
389 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
390 throws EntityNotFoundException //
392 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
393 throw new EntityNotFoundException("Policy type not found");
395 if ((ricId != null && this.rics.get(ricId) == null)) {
396 throw new EntityNotFoundException("Near-RT RIC not found");
399 String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
400 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
403 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
404 @Operation(summary = "Returns a policy status") //
405 @ApiResponses(value = { //
406 @ApiResponse(responseCode = "200", //
407 description = "Policy status", //
408 content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
409 @ApiResponse(responseCode = "404", //
410 description = "Policy is not found", //
411 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
413 public Mono<ResponseEntity<Object>> getPolicyStatus( //
414 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
415 Policy policy = policies.getPolicy(policyId);
417 return a1ClientFactory.createA1Client(policy.getRic()) //
418 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
419 .flatMap(status -> createPolicyStatus(policy, status)) //
420 .onErrorResume(this::handleException);
424 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
425 PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
426 String str = gson.toJson(info);
427 return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
430 private void keepServiceAlive(String name) {
431 Service s = this.services.get(name);
437 private PolicyInfo toPolicyInfo(Policy p) {
438 PolicyInfo policyInfo = new PolicyInfo();
439 policyInfo.policyId = p.getId();
440 policyInfo.policyData = fromJson(p.getJson());
441 policyInfo.ricId = p.getRic().id();
442 policyInfo.policyTypeId = p.getType().getId();
443 policyInfo.serviceId = p.getOwnerServiceId();
444 policyInfo.isTransient = p.isTransient();
445 if (!p.getStatusNotificationUri().isEmpty()) {
446 policyInfo.statusNotificationUri = p.getStatusNotificationUri();
448 if (!policyInfo.validate()) {
449 logger.error("BUG, all mandatory fields must be set");
455 private String policiesToJson(Collection<Policy> policies) {
456 List<PolicyInfo> v = new ArrayList<>(policies.size());
457 for (Policy p : policies) {
458 v.add(toPolicyInfo(p));
460 PolicyInfoList list = new PolicyInfoList(v);
461 return gson.toJson(list);
464 private Object fromJson(String jsonStr) {
465 return gson.fromJson(jsonStr, Object.class);
468 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
469 List<String> v = new ArrayList<>(types.size());
470 for (PolicyType t : types) {
473 PolicyTypeIdList ids = new PolicyTypeIdList(v);
474 return gson.toJson(ids);
477 private String toPolicyIdsJson(Collection<Policy> policies) {
478 List<String> v = new ArrayList<>(policies.size());
479 for (Policy p : policies) {
482 return gson.toJson(new PolicyIdList(v));