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.WebClientResponseException;
70 import reactor.core.publisher.Mono;
72 @RestController("PolicyControllerV2")
73 @Tag(name = PolicyController.API_NAME)
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 RejectionException) {
278 RejectionException e = (RejectionException) throwable;
279 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
281 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
285 private Mono<Object> validateModifiedPolicy(Policy policy) {
286 // Check that ric is not updated
287 Policy current = this.policies.get(policy.getId());
288 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
289 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
290 ", RIC ID: " + current.getRic().id() + //
291 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
292 logger.debug("Request rejected, {}", e.getMessage());
293 return Mono.error(e);
295 return Mono.just("{}");
298 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
299 if (!ric.isSupportingType(type.getId())) {
300 logger.debug("Request rejected, type not supported, RIC: {}", ric);
301 RejectionException e = new RejectionException(
302 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
303 return Mono.error(e);
305 return Mono.just("{}");
308 private Mono<Object> assertRicStateIdle(Ric ric) {
309 if (ric.getState() == Ric.RicState.AVAILABLE) {
310 return Mono.just("{}");
312 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
313 RejectionException e = new RejectionException(
314 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
316 return Mono.error(e);
320 static final String GET_POLICIES_QUERY_DETAILS =
321 "Returns a list of A1 policies matching given search criteria. <br>" //
322 + "If several query parameters are defined, the policies matching all conditions are returned.";
324 @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
325 @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
326 @ApiResponses(value = { //
327 @ApiResponse(responseCode = "200", //
328 description = "Policies", //
329 content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
330 @ApiResponse(responseCode = "404", //
331 description = "Near-RT RIC, policy type or service not found", //
332 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
334 public ResponseEntity<Object> getPolicyInstances( //
335 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
336 description = "Select policies with a given type identity.") //
337 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
338 @Parameter(name = Consts.RIC_ID_PARAM, required = false,
339 description = "Select policies for a given Near-RT RIC identity.") //
340 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
341 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
342 description = "Select policies owned by a given service.") //
343 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
344 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
345 description = "Select policies of a given type name (type identity has the format <typename_version>)") //
346 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
347 throws EntityNotFoundException //
349 if ((typeId != null && this.policyTypes.get(typeId) == null)) {
350 throw new EntityNotFoundException("Policy type identity not found");
352 if ((ric != null && this.rics.get(ric) == null)) {
353 throw new EntityNotFoundException("Near-RT RIC not found");
356 String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
357 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
360 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
361 @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
362 @ApiResponses(value = { //
363 @ApiResponse(responseCode = "200", //
364 description = "Policy identities", //
365 content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
366 @ApiResponse(responseCode = "404", //
367 description = "Near-RT RIC or type not found", //
368 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
370 public ResponseEntity<Object> getPolicyIds( //
371 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
372 description = "Select policies of a given policy type identity.") //
373 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
374 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
375 description = "Select policies of a given Near-RT RIC identity.") //
376 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
377 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
378 description = "Select policies owned by a given service.") //
379 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
380 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
381 description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
382 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
383 throws EntityNotFoundException //
385 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
386 throw new EntityNotFoundException("Policy type not found");
388 if ((ricId != null && this.rics.get(ricId) == null)) {
389 throw new EntityNotFoundException("Near-RT RIC not found");
392 String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
393 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
396 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
397 @Operation(summary = "Returns a policy status") //
398 @ApiResponses(value = { //
399 @ApiResponse(responseCode = "200", //
400 description = "Policy status", //
401 content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
402 @ApiResponse(responseCode = "404", //
403 description = "Policy is not found", //
404 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
406 public Mono<ResponseEntity<Object>> getPolicyStatus( //
407 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
408 Policy policy = policies.getPolicy(policyId);
410 return a1ClientFactory.createA1Client(policy.getRic()) //
411 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
412 .flatMap(status -> createPolicyStatus(policy, status)) //
413 .onErrorResume(this::handleException);
417 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
418 PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
419 String str = gson.toJson(info);
420 return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
423 private void keepServiceAlive(String name) {
424 Service s = this.services.get(name);
430 private PolicyInfo toPolicyInfo(Policy p) {
431 PolicyInfo policyInfo = new PolicyInfo();
432 policyInfo.policyId = p.getId();
433 policyInfo.policyData = fromJson(p.getJson());
434 policyInfo.ricId = p.getRic().id();
435 policyInfo.policyTypeId = p.getType().getId();
436 policyInfo.serviceId = p.getOwnerServiceId();
437 policyInfo.isTransient = p.isTransient();
438 if (!p.getStatusNotificationUri().isEmpty()) {
439 policyInfo.statusNotificationUri = p.getStatusNotificationUri();
441 if (!policyInfo.validate()) {
442 logger.error("BUG, all mandatory fields must be set");
448 private String policiesToJson(Collection<Policy> policies) {
449 List<PolicyInfo> v = new ArrayList<>(policies.size());
450 for (Policy p : policies) {
451 v.add(toPolicyInfo(p));
453 PolicyInfoList list = new PolicyInfoList(v);
454 return gson.toJson(list);
457 private Object fromJson(String jsonStr) {
458 return gson.fromJson(jsonStr, Object.class);
461 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
462 List<String> v = new ArrayList<>(types.size());
463 for (PolicyType t : types) {
466 PolicyTypeIdList ids = new PolicyTypeIdList(v);
467 return gson.toJson(ids);
470 private String toPolicyIdsJson(Collection<Policy> policies) {
471 List<String> v = new ArrayList<>(policies.size());
472 for (Policy p : policies) {
475 return gson.toJson(new PolicyIdList(v));