2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2023 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.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
29 import io.swagger.v3.oas.annotations.tags.Tag;
31 import java.lang.invoke.MethodHandles;
32 import java.time.Instant;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
39 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
40 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.api.v2.A1PolicyManagementApi;
41 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.AuthorizationCheck;
42 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
43 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
44 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
45 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyTypeDefinition;
46 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfo;
47 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyTypeIdList;
48 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfoList;
49 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyIdList;
50 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyStatusInfo;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
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.ResponseEntity;
57 import org.springframework.web.bind.annotation.RestController;
58 import org.springframework.web.reactive.function.client.WebClientException;
59 import org.springframework.web.reactive.function.client.WebClientResponseException;
61 import org.springframework.web.server.ServerWebExchange;
62 import reactor.core.publisher.Flux;
63 import reactor.core.publisher.Mono;
65 @RestController("PolicyControllerV2")
67 name = PolicyController.API_NAME, //
68 description = PolicyController.API_DESCRIPTION //
70 public class PolicyController implements A1PolicyManagementApi {
72 public static final String API_NAME = "A1 Policy Management";
73 public static final String API_DESCRIPTION = "";
75 public static class RejectionException extends Exception {
76 private static final long serialVersionUID = 1L;
79 private final HttpStatus status;
81 public RejectionException(String message, HttpStatus status) {
90 private PolicyTypes policyTypes;
92 private Policies policies;
94 private A1ClientFactory a1ClientFactory;
96 private Services services;
98 private ObjectMapper objectMapper;
100 private AuthorizationCheck authorization;
102 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
103 private static Gson gson = new GsonBuilder() //
107 public Mono<ResponseEntity<PolicyTypeDefinition>> getPolicyTypeDefinition(String policyTypeId, ServerWebExchange exchange)
108 throws EntityNotFoundException, JsonProcessingException {
109 PolicyType type = policyTypes.getType(policyTypeId);
110 JsonNode node = objectMapper.readTree(type.getSchema());
111 PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition().policySchema(node);
112 return Mono.just(new ResponseEntity<>(policyTypeDefinition, HttpStatus.OK));
116 public Mono<ResponseEntity<PolicyTypeIdList>> getPolicyTypes(String ricId, String typeName, String compatibleWithVersion, ServerWebExchange exchange) throws Exception {
117 if (compatibleWithVersion != null && typeName == null) {
118 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
119 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
122 Collection<PolicyType> types =
123 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
125 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
126 return Mono.just(new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK));
131 public Mono<ResponseEntity<PolicyInfo>> getPolicy(String policyId, final ServerWebExchange exchange)
132 throws EntityNotFoundException {
133 Policy policy = policies.getPolicy(policyId);
134 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
135 .map(x -> new ResponseEntity<>(toPolicyInfo(policy), HttpStatus.OK)) //
136 .doOnError(error -> logger.error(error.getMessage()));
140 public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {
142 Policy policy = policies.getPolicy(policyId);
143 keepServiceAlive(policy.getOwnerServiceId());
145 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
146 .flatMap(x -> policy.getRic().getLock().lock(Lock.LockType.SHARED, "deletePolicy"))
147 .flatMap(grant -> deletePolicy(grant, policy))
148 .onErrorResume(this::handleException);
151 Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
152 return checkRicStateIdle(policy.getRic()) //
153 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic()))
154 .doOnNext(notUsed -> policies.remove(policy))
155 .doFinally(x -> grant.unlockBlocking())
156 .flatMap(client -> client.deletePolicy(policy))
157 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT))
158 .onErrorResume(this::handleException);
162 public Mono<ResponseEntity<Object>> putPolicy(final Mono<PolicyInfo> policyInfo, final ServerWebExchange exchange) {
164 return policyInfo.flatMap(policyInfoValue -> {
165 String jsonString = gson.toJson(policyInfoValue.getPolicyData());
167 Mono.justOrEmpty(rics.get(policyInfoValue.getRicId()))
168 .switchIfEmpty(Mono.error(new EntityNotFoundException("Near-RT RIC not found"))),
169 Mono.justOrEmpty(policyTypes.get(policyInfoValue.getPolicytypeId()))
170 .switchIfEmpty(Mono.error(new EntityNotFoundException("policy type not found")))
173 Ric ric = tuple.getT1();
174 PolicyType type = tuple.getT2();
175 keepServiceAlive(policyInfoValue.getServiceId());
176 Policy policy = Policy.builder()
177 .id(policyInfoValue.getPolicyId())
181 .ownerServiceId(policyInfoValue.getServiceId())
182 .lastModified(Instant.now())
183 .isTransient(policyInfoValue.getTransient())
184 .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
187 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
188 .flatMap(x -> ric.getLock().lock(Lock.LockType.SHARED, "putPolicy"))
189 .flatMap(grant -> putPolicy(grant, policy));
191 .onErrorResume(this::handleException);
197 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
198 final boolean isCreate = this.policies.get(policy.getId()) == null;
199 final Ric ric = policy.getRic();
201 return checkRicStateIdle(ric) //
202 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
203 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
204 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
205 .flatMap(client -> client.putPolicy(policy)) //
206 .doOnNext(notUsed -> policies.put(policy)) //
207 .doFinally(x -> grant.unlockBlocking()) //
208 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
209 .onErrorResume(this::handleException);
213 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
214 if (throwable instanceof WebClientResponseException) {
215 WebClientResponseException e = (WebClientResponseException) throwable;
216 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
217 } else if (throwable instanceof WebClientException) {
218 WebClientException e = (WebClientException) throwable;
219 return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
220 } else if (throwable instanceof RejectionException) {
221 RejectionException e = (RejectionException) throwable;
222 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
223 } else if (throwable instanceof ServiceException) {
224 ServiceException e = (ServiceException) throwable;
225 return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
227 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
231 private Mono<Object> validateModifiedPolicy(Policy policy) {
232 // Check that ric is not updated
233 Policy current = this.policies.get(policy.getId());
234 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
235 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
236 ", RIC ID: " + current.getRic().id() + //
237 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
238 logger.debug("Request rejected, {}", e.getMessage());
239 return Mono.error(e);
241 return Mono.just("{}");
244 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
245 if (!ric.isSupportingType(type.getId())) {
246 logger.debug("Request rejected, type not supported, RIC: {}", ric);
247 RejectionException e = new RejectionException(
248 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
249 return Mono.error(e);
251 return Mono.just("{}");
254 private Mono<Object> checkRicStateIdle(Ric ric) {
255 if (ric.getState() == Ric.RicState.AVAILABLE) {
256 return Mono.just("{}");
258 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
259 RejectionException e = new RejectionException(
260 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
262 return Mono.error(e);
267 public Mono<ResponseEntity<PolicyInfoList>> getPolicyInstances(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
268 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
269 throw new EntityNotFoundException("Policy type identity not found");
271 if ((ricId != null && this.rics.get(ricId) == null)) {
272 throw new EntityNotFoundException("Near-RT RIC not found");
275 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
276 return Flux.fromIterable(filtered) //
277 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
278 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
279 .onErrorResume(e -> Mono.empty())
281 .map(authPolicies -> new ResponseEntity<>(policiesToJson(authPolicies), HttpStatus.OK))
282 .doOnError(error -> logger.error(error.getMessage()));
286 public Mono<ResponseEntity<PolicyIdList>> getPolicyIds(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
287 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
288 throw new EntityNotFoundException("Policy type not found");
290 if ((ricId != null && this.rics.get(ricId) == null)) {
291 throw new EntityNotFoundException("Near-RT RIC not found");
294 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
295 return Flux.fromIterable(filtered)
296 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
297 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
298 .onErrorResume(e -> Mono.empty())
300 .map(authPolicies -> new ResponseEntity<>(toPolicyIdsJson(authPolicies), HttpStatus.OK))
301 .doOnError(error -> logger.error(error.getMessage()));
305 public Mono<ResponseEntity<PolicyStatusInfo>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
306 Policy policy = policies.getPolicy(policyId);
308 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
309 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
310 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
311 .flatMap(status -> createPolicyStatus(policy, status))
312 .doOnError(error -> logger.error(error.getMessage()));
315 private Mono<ResponseEntity<PolicyStatusInfo>> createPolicyStatus(Policy policy, String statusFromNearRic) {
317 PolicyStatusInfo policyStatusInfo = new PolicyStatusInfo();
318 policyStatusInfo.setLastModified(policy.getLastModified().toString());
319 policyStatusInfo.setStatus(fromJson(statusFromNearRic));
320 return Mono.just(new ResponseEntity<>(policyStatusInfo, HttpStatus.OK));
323 private void keepServiceAlive(String name) {
324 Service s = this.services.get(name);
330 private PolicyInfo toPolicyInfo(Policy policy) {
332 PolicyInfo policyInfo = new PolicyInfo()
333 .policyId(policy.getId())
334 .policyData(objectMapper.readTree(policy.getJson()))
335 .ricId(policy.getRic().id())
336 .policytypeId(policy.getType().getId())
337 .serviceId(policy.getOwnerServiceId())
338 ._transient(policy.isTransient());
339 if (!policy.getStatusNotificationUri().isEmpty()) {
340 policyInfo.setStatusNotificationUri(policy.getStatusNotificationUri());
343 } catch (JsonProcessingException ex) {
344 throw new RuntimeException(ex);
348 private PolicyInfoList policiesToJson(Collection<Policy> policies) {
350 List<PolicyInfo> policiesList = new ArrayList<>(policies.size());
351 PolicyInfoList policyInfoList = new PolicyInfoList();
352 for (Policy policy : policies) {
353 policiesList.add(toPolicyInfo(policy));
355 policyInfoList.setPolicies(policiesList);
356 return policyInfoList;
359 private Object fromJson(String jsonStr) {
360 return gson.fromJson(jsonStr, Object.class);
363 private PolicyTypeIdList toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) {
365 List<String> policyTypeList = new ArrayList<>(policyTypes.size());
366 PolicyTypeIdList idList = new PolicyTypeIdList();
367 for (PolicyType policyType : policyTypes) {
368 policyTypeList.add(policyType.getId());
370 idList.setPolicytypeIds(policyTypeList);
374 private PolicyIdList toPolicyIdsJson(Collection<Policy> policies) {
376 List<String> policyIds = new ArrayList<>(policies.size());
377 PolicyIdList idList = new PolicyIdList();
378 for (Policy policy : policies) {
379 policyIds.add(policy.getId());
381 idList.setPolicyIds(policyIds);