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.HttpStatusCode;
61 import org.springframework.http.MediaType;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.web.bind.annotation.DeleteMapping;
64 import org.springframework.web.bind.annotation.GetMapping;
65 import org.springframework.web.bind.annotation.PathVariable;
66 import org.springframework.web.bind.annotation.PutMapping;
67 import org.springframework.web.bind.annotation.RequestBody;
68 import org.springframework.web.bind.annotation.RequestParam;
69 import org.springframework.web.bind.annotation.RestController;
70 import org.springframework.web.reactive.function.client.WebClientException;
71 import org.springframework.web.reactive.function.client.WebClientResponseException;
72 import reactor.core.publisher.Mono;
74 @RestController("PolicyControllerV2")
76 name = PolicyController.API_NAME, //
77 description = PolicyController.API_DESCRIPTION //
79 public class PolicyController {
81 public static final String API_NAME = "A1 Policy Management";
82 public static final String API_DESCRIPTION = "";
84 public static class RejectionException extends Exception {
85 private static final long serialVersionUID = 1L;
88 private final HttpStatus status;
90 public RejectionException(String message, HttpStatus status) {
99 private PolicyTypes policyTypes;
101 private Policies policies;
103 private A1ClientFactory a1ClientFactory;
105 private Services services;
107 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
108 private static Gson gson = new GsonBuilder() //
111 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policytype_id:.+}") //
112 @Operation(summary = "Returns a policy type definition") //
113 @ApiResponses(value = { //
114 @ApiResponse(responseCode = "200", //
115 description = "Policy type", //
116 content = @Content(schema = @Schema(implementation = PolicyTypeInfo.class))), //
117 @ApiResponse(responseCode = "404", //
118 description = "Policy type is not found", //
119 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
121 public ResponseEntity<Object> getPolicyType( //
122 @PathVariable("policytype_id") String policyTypeId) throws EntityNotFoundException {
123 PolicyType type = policyTypes.getType(policyTypeId);
124 PolicyTypeInfo info = new PolicyTypeInfo(type.getSchema());
125 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
128 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
129 @Operation(summary = "Query policy type identities")
130 @ApiResponses(value = { //
131 @ApiResponse(responseCode = "200", //
132 description = "Policy type IDs", //
133 content = @Content(schema = @Schema(implementation = PolicyTypeIdList.class))), //
134 @ApiResponse(responseCode = "404", //
135 description = "Near-RT RIC is not found", //
136 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
138 public ResponseEntity<Object> getPolicyTypes( //
139 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
140 description = "Select types for the given Near-RT RIC identity.") //
141 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
143 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
144 description = "Select types with the given type name (type identity has the format <typename_version>)") //
145 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
147 @Parameter(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false, //
148 description = "Select types that are compatible with the given version. This parameter is only applicable in conjunction with "
149 + Consts.TYPE_NAME_PARAM
150 + ". As an example version 1.9.1 is compatible with 1.0.0 but not the other way around."
151 + " Matching types will be returned sorted in ascending order.") //
152 @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
154 ) throws ServiceException {
156 if (compatibleWithVersion != null && typeName == null) {
157 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
158 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
161 Collection<PolicyType> types =
162 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
164 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
165 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
168 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
169 @Operation(summary = "Returns a policy") //
170 @ApiResponses(value = { //
171 @ApiResponse(responseCode = "200", //
172 description = "Policy found", //
173 content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
174 @ApiResponse(responseCode = "404", //
175 description = "Policy is not found", //
176 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
178 public ResponseEntity<Object> getPolicy( //
179 @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
180 Policy p = policies.getPolicy(id);
181 return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
184 @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
185 @Operation(summary = "Delete a policy")
186 @ApiResponses(value = { //
187 @ApiResponse(responseCode = "200", //
188 description = "Not used", //
189 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
190 @ApiResponse(responseCode = "204", //
191 description = "Policy deleted", //
192 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
193 @ApiResponse(responseCode = "404", //
194 description = "Policy is not found", //
195 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
196 @ApiResponse(responseCode = "423", //
197 description = "Near-RT RIC is not operational", //
198 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
200 public Mono<ResponseEntity<Object>> deletePolicy( //
201 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
202 Policy policy = policies.getPolicy(policyId);
203 keepServiceAlive(policy.getOwnerServiceId());
205 return policy.getRic().getLock().lock(LockType.SHARED, "deletePolicy") //
206 .flatMap(grant -> deletePolicy(grant, policy));
209 Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
210 return assertRicStateIdle(policy.getRic()) //
211 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
212 .doOnNext(notUsed -> policies.remove(policy)) //
213 .doFinally(x -> grant.unlockBlocking()) //
214 .flatMap(client -> client.deletePolicy(policy)) //
215 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
216 .onErrorResume(this::handleException);
219 @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
220 @Operation(summary = "Create or update a policy")
221 @ApiResponses(value = { //
222 @ApiResponse(responseCode = "201", //
223 description = "Policy created", //
224 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
225 @ApiResponse(responseCode = "200", //
226 description = "Policy updated", //
227 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
228 @ApiResponse(responseCode = "423", //
229 description = "Near-RT RIC is not operational", //
230 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
231 @ApiResponse(responseCode = "404", //
232 description = "Near-RT RIC or policy type is not found", //
233 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
235 public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
237 if (!policyInfo.validate()) {
238 return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
240 String jsonString = gson.toJson(policyInfo.policyData);
241 Ric ric = rics.get(policyInfo.ricId);
242 PolicyType type = policyTypes.get(policyInfo.policyTypeId);
243 keepServiceAlive(policyInfo.serviceId);
244 if (ric == null || type == null) {
245 throw new EntityNotFoundException("Near-RT RIC or policy type not found");
247 Policy policy = Policy.builder() //
248 .id(policyInfo.policyId) //
252 .ownerServiceId(policyInfo.serviceId) //
253 .lastModified(Instant.now()) //
254 .isTransient(policyInfo.isTransient) //
255 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
258 return ric.getLock().lock(LockType.SHARED, "putPolicy") //
259 .flatMap(grant -> putPolicy(grant, policy));
262 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
263 final boolean isCreate = this.policies.get(policy.getId()) == null;
264 final Ric ric = policy.getRic();
266 return assertRicStateIdle(ric) //
267 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
268 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
269 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
270 .flatMap(client -> client.putPolicy(policy)) //
271 .doOnNext(notUsed -> policies.put(policy)) //
272 .doFinally(x -> grant.unlockBlocking()) //
273 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
274 .onErrorResume(this::handleException);
278 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
279 if (throwable instanceof WebClientResponseException) {
280 WebClientResponseException e = (WebClientResponseException) throwable;
281 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
282 } else if (throwable instanceof WebClientException) {
283 WebClientException e = (WebClientException) throwable;
284 return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
285 } else if (throwable instanceof RejectionException) {
286 RejectionException e = (RejectionException) throwable;
287 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
289 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
293 private Mono<Object> validateModifiedPolicy(Policy policy) {
294 // Check that ric is not updated
295 Policy current = this.policies.get(policy.getId());
296 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
297 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
298 ", RIC ID: " + current.getRic().id() + //
299 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
300 logger.debug("Request rejected, {}", e.getMessage());
301 return Mono.error(e);
303 return Mono.just("{}");
306 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
307 if (!ric.isSupportingType(type.getId())) {
308 logger.debug("Request rejected, type not supported, RIC: {}", ric);
309 RejectionException e = new RejectionException(
310 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
311 return Mono.error(e);
313 return Mono.just("{}");
316 private Mono<Object> assertRicStateIdle(Ric ric) {
317 if (ric.getState() == Ric.RicState.AVAILABLE) {
318 return Mono.just("{}");
320 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
321 RejectionException e = new RejectionException(
322 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
324 return Mono.error(e);
328 static final String GET_POLICIES_QUERY_DETAILS =
329 "Returns a list of A1 policies matching given search criteria. <br>" //
330 + "If several query parameters are defined, the policies matching all conditions are returned.";
332 @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
333 @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
334 @ApiResponses(value = { //
335 @ApiResponse(responseCode = "200", //
336 description = "Policies", //
337 content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
338 @ApiResponse(responseCode = "404", //
339 description = "Near-RT RIC, policy type or service not found", //
340 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
342 public ResponseEntity<Object> getPolicyInstances( //
343 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
344 description = "Select policies with a given type identity.") //
345 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
346 @Parameter(name = Consts.RIC_ID_PARAM, required = false,
347 description = "Select policies for a given Near-RT RIC identity.") //
348 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
349 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
350 description = "Select policies owned by a given service.") //
351 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
352 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
353 description = "Select policies of a given type name (type identity has the format <typename_version>)") //
354 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
355 throws EntityNotFoundException //
357 if ((typeId != null && this.policyTypes.get(typeId) == null)) {
358 throw new EntityNotFoundException("Policy type identity not found");
360 if ((ric != null && this.rics.get(ric) == null)) {
361 throw new EntityNotFoundException("Near-RT RIC not found");
364 String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
365 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
368 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
369 @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
370 @ApiResponses(value = { //
371 @ApiResponse(responseCode = "200", //
372 description = "Policy identities", //
373 content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
374 @ApiResponse(responseCode = "404", //
375 description = "Near-RT RIC or type not found", //
376 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
378 public ResponseEntity<Object> getPolicyIds( //
379 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
380 description = "Select policies of a given policy type identity.") //
381 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
382 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
383 description = "Select policies of a given Near-RT RIC identity.") //
384 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
385 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
386 description = "Select policies owned by a given service.") //
387 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
388 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
389 description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
390 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
391 throws EntityNotFoundException //
393 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
394 throw new EntityNotFoundException("Policy type not found");
396 if ((ricId != null && this.rics.get(ricId) == null)) {
397 throw new EntityNotFoundException("Near-RT RIC not found");
400 String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
401 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
404 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
405 @Operation(summary = "Returns a policy status") //
406 @ApiResponses(value = { //
407 @ApiResponse(responseCode = "200", //
408 description = "Policy status", //
409 content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
410 @ApiResponse(responseCode = "404", //
411 description = "Policy is not found", //
412 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
414 public Mono<ResponseEntity<Object>> getPolicyStatus( //
415 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
416 Policy policy = policies.getPolicy(policyId);
418 return a1ClientFactory.createA1Client(policy.getRic()) //
419 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
420 .flatMap(status -> createPolicyStatus(policy, status)) //
421 .onErrorResume(this::handleException);
425 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
426 PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
427 String str = gson.toJson(info);
428 return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
431 private void keepServiceAlive(String name) {
432 Service s = this.services.get(name);
438 private PolicyInfo toPolicyInfo(Policy p) {
439 PolicyInfo policyInfo = new PolicyInfo();
440 policyInfo.policyId = p.getId();
441 policyInfo.policyData = fromJson(p.getJson());
442 policyInfo.ricId = p.getRic().id();
443 policyInfo.policyTypeId = p.getType().getId();
444 policyInfo.serviceId = p.getOwnerServiceId();
445 policyInfo.isTransient = p.isTransient();
446 if (!p.getStatusNotificationUri().isEmpty()) {
447 policyInfo.statusNotificationUri = p.getStatusNotificationUri();
449 if (!policyInfo.validate()) {
450 logger.error("BUG, all mandatory fields must be set");
456 private String policiesToJson(Collection<Policy> policies) {
457 List<PolicyInfo> v = new ArrayList<>(policies.size());
458 for (Policy p : policies) {
459 v.add(toPolicyInfo(p));
461 PolicyInfoList list = new PolicyInfoList(v);
462 return gson.toJson(list);
465 private Object fromJson(String jsonStr) {
466 return gson.fromJson(jsonStr, Object.class);
469 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
470 List<String> v = new ArrayList<>(types.size());
471 for (PolicyType t : types) {
474 PolicyTypeIdList ids = new PolicyTypeIdList(v);
475 return gson.toJson(ids);
478 private String toPolicyIdsJson(Collection<Policy> policies) {
479 List<String> v = new ArrayList<>(policies.size());
480 for (Policy p : policies) {
483 return gson.toJson(new PolicyIdList(v));