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.v1;
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.ArraySchema;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.responses.ApiResponses;
33 import io.swagger.v3.oas.annotations.tags.Tag;
35 import java.lang.invoke.MethodHandles;
36 import java.time.Instant;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.List;
43 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
44 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
45 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2.ErrorResponse;
46 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
48 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
49 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
50 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.http.HttpStatus;
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.PutMapping;
65 import org.springframework.web.bind.annotation.RequestBody;
66 import org.springframework.web.bind.annotation.RequestParam;
67 import org.springframework.web.bind.annotation.RestController;
68 import org.springframework.web.reactive.function.client.WebClientResponseException;
69 import reactor.core.publisher.Mono;
72 @Tag(name = Consts.V1_API_NAME)
73 public class PolicyController {
75 public static class RejectionException extends Exception {
76 private static final long serialVersionUID = 1L;
78 private final HttpStatus status;
80 public RejectionException(String message, HttpStatus status) {
89 private PolicyTypes policyTypes;
91 private Policies policies;
93 private A1ClientFactory a1ClientFactory;
95 private Services services;
97 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
98 private static Gson gson = new GsonBuilder().create();
100 @GetMapping("/policy_schemas") //
101 @Operation(summary = "Returns policy type schema definitions") //
102 @ApiResponses(value = { //
103 @ApiResponse(responseCode = "200", //
104 description = "Policy schemas", //
105 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Object.class)))), //
106 @ApiResponse(responseCode = "404", //
107 description = "Near-RT RIC is not found", //
108 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
110 public ResponseEntity<String> getPolicySchemas( //
111 @Parameter(name = "ric", required = false,
112 description = "The name of the Near-RT RIC to get the definitions for.") //
113 @RequestParam(name = "ric", required = false) String ricName) throws EntityNotFoundException {
114 if (ricName == null) {
115 Collection<PolicyType> types = this.policyTypes.getAll();
116 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
118 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
119 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
123 @GetMapping("/policy_schema")
124 @Operation(summary = "Returns one policy type schema definition")
125 @ApiResponses(value = { //
126 @ApiResponse(responseCode = "200", //
127 description = "Policy schema", //
128 content = @Content(schema = @Schema(implementation = Object.class))),
129 @ApiResponse(responseCode = "404", //
130 description = "The policy type is not found", //
131 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
133 public ResponseEntity<String> getPolicySchema( //
134 @Parameter(name = "id", required = true,
135 description = "The identity of the policy type to get the definition for.") //
136 @RequestParam(name = "id", required = true) String id) throws EntityNotFoundException {
137 PolicyType type = policyTypes.getType(id);
138 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
141 @GetMapping("/policy_types")
142 @Operation(summary = "Query policy type names")
143 @ApiResponses(value = { //
144 @ApiResponse(responseCode = "200", //
145 description = "Policy type names", //
146 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
147 @ApiResponse(responseCode = "404", //
148 description = "Near-RT RIC is not found", //
149 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
151 public ResponseEntity<String> getPolicyTypes( //
152 @Parameter(name = "ric", required = false, description = "The name of the Near-RT RIC to get types for.") //
153 @RequestParam(name = "ric", required = false) String ricName) throws EntityNotFoundException {
154 if (ricName == null) {
155 Collection<PolicyType> types = this.policyTypes.getAll();
156 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
158 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
159 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
163 @GetMapping("/policy")
164 @Operation(summary = "Returns a policy configuration") //
165 @ApiResponses(value = { //
166 @ApiResponse(responseCode = "200", //
167 description = "Policy found", //
168 content = @Content(schema = @Schema(implementation = Object.class))), //
169 @ApiResponse(responseCode = "404", //
170 description = "Policy is not found", //
171 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))//
174 public ResponseEntity<String> getPolicy( //
175 @Parameter(name = "id", required = true, description = "The identity of the policy instance.") //
176 @RequestParam(name = "id", required = true) String id) throws EntityNotFoundException {
177 Policy p = policies.getPolicy(id);
178 return new ResponseEntity<>(p.json(), HttpStatus.OK);
181 @DeleteMapping("/policy")
182 @Operation(summary = "Delete a policy")
183 @ApiResponses(value = { //
184 @ApiResponse(responseCode = "200", //
185 description = "Not used", //
186 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
187 @ApiResponse(responseCode = "204", //
188 description = "Policy deleted", //
189 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
190 @ApiResponse(responseCode = "404", //
191 description = "Policy is not found", //
192 content = @Content(schema = @Schema(implementation = String.class))),
193 @ApiResponse(responseCode = "423", //
194 description = "Near-RT RIC is not operational", //
195 content = @Content(schema = @Schema(implementation = String.class)))})
196 public Mono<ResponseEntity<Object>> deletePolicy( //
197 @Parameter(name = "id", required = true, description = "The identity of the policy instance.") //
198 @RequestParam(name = "id", required = true) String id) throws EntityNotFoundException {
199 Policy policy = policies.getPolicy(id);
200 keepServiceAlive(policy.ownerServiceId());
201 Ric ric = policy.ric();
202 return ric.getLock().lock(LockType.SHARED) //
203 .flatMap(notUsed -> assertRicStateIdle(ric)) //
204 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
205 .doOnNext(notUsed -> policies.remove(policy)) //
206 .flatMap(client -> client.deletePolicy(policy)) //
207 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
208 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
209 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
210 .onErrorResume(this::handleException);
213 @PutMapping(path = "/policy")
214 @Operation(summary = "Put a policy")
215 @ApiResponses(value = { //
216 @ApiResponse(responseCode = "201", //
217 description = "Policy created", //
218 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
219 @ApiResponse(responseCode = "200", //
220 description = "Policy updated", //
221 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
222 @ApiResponse(responseCode = "423", //
223 description = "Near-RT RIC is not operational", //
224 content = @Content(schema = @Schema(implementation = String.class))), //
225 @ApiResponse(responseCode = "404", //
226 description = "Near-RT RIC or policy type is not found", //
227 content = @Content(schema = @Schema(implementation = String.class))) //
229 public Mono<ResponseEntity<Object>> putPolicy( //
230 @Parameter(name = "type", required = false, description = "The name of the policy type.") //
231 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
232 @Parameter(name = "id", required = true, description = "The identity of the policy instance.") //
233 @RequestParam(name = "id", required = true) String instanceId, //
234 @Parameter(name = "ric", required = true,
235 description = "The name of the Near-RT RIC where the policy will be " + //
237 @RequestParam(name = "ric", required = true) String ricName, //
238 @Parameter(name = "service", required = true, description = "The name of the service creating the policy.") //
239 @RequestParam(name = "service", required = true) String service, //
240 @Parameter(name = "transient", required = false,
241 description = "If the policy is transient or not (boolean " + //
242 "defaulted to false). A policy is transient if it will be forgotten when the service needs to "
244 "reconnect to the Near-RT RIC.") //
245 @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
246 @RequestBody Object jsonBody) {
248 String jsonString = gson.toJson(jsonBody);
249 Ric ric = rics.get(ricName);
250 PolicyType type = policyTypes.get(typeName);
251 keepServiceAlive(service);
252 if (ric == null || type == null) {
253 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
255 Policy policy = ImmutablePolicy.builder() //
260 .ownerServiceId(service) //
261 .lastModified(Instant.now()) //
262 .isTransient(isTransient) //
263 .statusNotificationUri("") //
266 final boolean isCreate = this.policies.get(policy.id()) == null;
268 return ric.getLock().lock(LockType.SHARED) //
269 .flatMap(notUsed -> assertRicStateIdle(ric)) //
270 .flatMap(notUsed -> checkSupportedType(ric, type)) //
271 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
272 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
273 .flatMap(client -> client.putPolicy(policy)) //
274 .doOnNext(notUsed -> policies.put(policy)) //
275 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
276 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
277 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
278 .onErrorResume(this::handleException);
281 @SuppressWarnings({"unchecked"})
282 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
283 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
284 return Mono.just(re);
287 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
288 if (throwable instanceof WebClientResponseException) {
289 WebClientResponseException e = (WebClientResponseException) throwable;
290 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
291 } else if (throwable instanceof RejectionException) {
292 RejectionException e = (RejectionException) throwable;
293 return createResponseEntity(e.getMessage(), e.getStatus());
295 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
299 private Mono<Object> validateModifiedPolicy(Policy policy) {
300 // Check that ric is not updated
301 Policy current = this.policies.get(policy.id());
302 if (current != null && !current.ric().id().equals(policy.ric().id())) {
303 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
304 ", RIC name: " + current.ric().id() + //
305 ", new name: " + policy.ric().id(), HttpStatus.CONFLICT);
306 logger.debug("Request rejected, {}", e.getMessage());
307 return Mono.error(e);
309 return Mono.just("OK");
312 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
313 if (!ric.isSupportingType(type.id())) {
314 logger.debug("Request rejected, type not supported, RIC: {}", ric);
315 RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(),
316 HttpStatus.NOT_FOUND);
317 return Mono.error(e);
319 return Mono.just("OK");
322 private Mono<Object> assertRicStateIdle(Ric ric) {
323 if (ric.getState() == Ric.RicState.AVAILABLE) {
324 return Mono.just("OK");
326 logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
327 RejectionException e = new RejectionException(
328 "Ric is not operational, RIC name: " + ric.id() + ", state: " + ric.getState(), HttpStatus.LOCKED);
329 return Mono.error(e);
333 @GetMapping("/policies")
334 @Operation(summary = "Query policies")
335 @ApiResponses(value = { //
336 @ApiResponse(responseCode = "200", //
337 description = "Policies", //
338 content = @Content(array = @ArraySchema(schema = @Schema(implementation = PolicyInfo.class)))), //
339 @ApiResponse(responseCode = "404", //
340 description = "Near-RT RIC or type not found", //
341 content = @Content(schema = @Schema(implementation = String.class)))})
342 public ResponseEntity<String> getPolicies( //
343 @Parameter(name = "type", required = false,
344 description = "The name of the policy type to get policies for.") //
345 @RequestParam(name = "type", required = false) String type, //
346 @Parameter(name = "ric", required = false, description = "The name of the Near-RT RIC to get policies for.") //
347 @RequestParam(name = "ric", required = false) String ric, //
348 @Parameter(name = "service", required = false, description = "The name of the service to get policies for.") //
349 @RequestParam(name = "service", required = false) String service) //
351 if ((type != null && this.policyTypes.get(type) == null)) {
352 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
354 if ((ric != null && this.rics.get(ric) == null)) {
355 return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
358 String filteredPolicies = policiesToJson(filter(type, ric, service));
359 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
362 @GetMapping("/policy_ids")
363 @Operation(summary = "Query policies, only policy identities returned")
364 @ApiResponses(value = { //
365 @ApiResponse(responseCode = "200", //
366 description = "Policy identitiess", //
367 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
368 @ApiResponse(responseCode = "404", //
369 description = "Near-RT RIC or type not found", //
370 content = @Content(schema = @Schema(implementation = String.class)))})
371 public ResponseEntity<String> getPolicyIds( //
372 @Parameter(name = "type", required = false,
373 description = "The name of the policy type to get policies for.") //
374 @RequestParam(name = "type", required = false) String type, //
375 @Parameter(name = "ric", required = false, description = "The name of the Near-RT RIC to get policies for.") //
376 @RequestParam(name = "ric", required = false) String ric, //
377 @Parameter(name = "service", required = false, description = "The name of the service to get policies for.") //
378 @RequestParam(name = "service", required = false) String service) //
380 if ((type != null && this.policyTypes.get(type) == null)) {
381 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
383 if ((ric != null && this.rics.get(ric) == null)) {
384 return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
387 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
388 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
391 @GetMapping("/policy_status")
392 @Operation(summary = "Returns a policy status") //
393 @ApiResponses(value = { //
394 @ApiResponse(responseCode = "200", //
395 description = "Policy status", //
396 content = @Content(schema = @Schema(implementation = Object.class))), //
397 @ApiResponse(responseCode = "404", //
398 description = "Policy is not found", //
399 content = @Content(schema = @Schema(implementation = String.class))) //
401 public Mono<ResponseEntity<String>> getPolicyStatus( //
402 @Parameter(name = "id", required = true, description = "The identity of the policy.") @RequestParam(
404 required = true) String id)
405 throws EntityNotFoundException {
406 Policy policy = policies.getPolicy(id);
408 return a1ClientFactory.createA1Client(policy.ric()) //
409 .flatMap(client -> client.getPolicyStatus(policy)) //
410 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
411 .onErrorResume(this::handleException);
414 private void keepServiceAlive(String name) {
415 Service s = this.services.get(name);
421 private boolean include(String filter, String value) {
422 return filter == null || value.equals(filter);
425 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
426 if (type == null && ric == null && service == null) {
429 List<Policy> filtered = new ArrayList<>();
430 for (Policy p : collection) {
431 if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) {
438 private Collection<Policy> filter(String type, String ric, String service) {
440 return filter(policies.getForType(type), null, ric, service);
441 } else if (service != null) {
442 return filter(policies.getForService(service), type, ric, null);
443 } else if (ric != null) {
444 return filter(policies.getForRic(ric), type, null, service);
446 return policies.getAll();
450 private String policiesToJson(Collection<Policy> policies) {
451 List<PolicyInfo> v = new ArrayList<>(policies.size());
452 for (Policy p : policies) {
453 PolicyInfo policyInfo = new PolicyInfo();
454 policyInfo.id = p.id();
455 policyInfo.json = fromJson(p.json());
456 policyInfo.ric = p.ric().id();
457 policyInfo.type = p.type().id();
458 policyInfo.service = p.ownerServiceId();
459 policyInfo.lastModified = p.lastModified().toString();
460 if (!policyInfo.validate()) {
461 logger.error("BUG, all fields must be set");
465 return gson.toJson(v);
468 private Object fromJson(String jsonStr) {
469 return gson.fromJson(jsonStr, Object.class);
472 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
473 StringBuilder result = new StringBuilder();
475 boolean first = true;
476 for (PolicyType t : types) {
481 result.append(t.schema());
484 return result.toString();
487 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
488 List<String> v = new ArrayList<>(types.size());
489 for (PolicyType t : types) {
492 return gson.toJson(v);
495 private String toPolicyIdsJson(Collection<Policy> policies) {
496 List<String> v = new ArrayList<>(policies.size());
497 for (Policy p : policies) {
500 return gson.toJson(v);