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;
40 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
41 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.api.v2.A1PolicyManagementApi;
42 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.AuthorizationCheck;
43 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
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.models.v2.PolicyTypeDefinition;
47 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfo;
48 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyTypeIdList;
49 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfoList;
50 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyIdList;
51 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyStatusInfo;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.http.HttpStatus;
57 import org.springframework.http.ResponseEntity;
58 import org.springframework.web.bind.annotation.RestController;
59 import org.springframework.web.reactive.function.client.WebClientException;
60 import org.springframework.web.reactive.function.client.WebClientResponseException;
62 import org.springframework.web.server.ServerWebExchange;
63 import reactor.core.publisher.Flux;
64 import reactor.core.publisher.Mono;
66 @RestController("PolicyControllerV2")
68 name = PolicyController.API_NAME, //
69 description = PolicyController.API_DESCRIPTION //
71 public class PolicyController implements A1PolicyManagementApi {
73 public static final String API_NAME = "A1 Policy Management";
74 public static final String API_DESCRIPTION = "";
76 public static class RejectionException extends Exception {
77 private static final long serialVersionUID = 1L;
80 private final HttpStatus status;
82 public RejectionException(String message, HttpStatus status) {
91 private PolicyTypes policyTypes;
93 private Policies policies;
95 private A1ClientFactory a1ClientFactory;
97 private Services services;
99 private ObjectMapper objectMapper;
101 private AuthorizationCheck authorization;
103 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
104 private static Gson gson = new GsonBuilder() //
108 public Mono<ResponseEntity<Object>> getPolicyTypeDefinition(String policyTypeId, ServerWebExchange exchange)
109 throws EntityNotFoundException, JsonProcessingException {
110 PolicyType type = policyTypes.getType(policyTypeId);
111 JsonNode node = objectMapper.readTree(type.getSchema());
112 PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition().policySchema(node);
113 return Mono.just(new ResponseEntity<>(policyTypeDefinition, HttpStatus.OK));
117 public Mono<ResponseEntity<Object>> getPolicyTypes(String ricId, String typeName, String compatibleWithVersion, ServerWebExchange exchange) throws Exception {
118 if (compatibleWithVersion != null && typeName == null) {
119 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
120 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
123 Collection<PolicyType> types =
124 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
126 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
127 return Mono.just(new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK));
132 public Mono<ResponseEntity<Object>> getPolicy(String policyId, final ServerWebExchange exchange)
133 throws EntityNotFoundException {
134 Policy policy = policies.getPolicy(policyId);
135 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
136 .map(x -> new ResponseEntity<>((Object) toPolicyInfo(policy), HttpStatus.OK)) //
137 .onErrorResume(this::handleException);
141 public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {
143 Policy policy = policies.getPolicy(policyId);
144 keepServiceAlive(policy.getOwnerServiceId());
146 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
147 .flatMap(x -> policy.getRic().getLock().lock(Lock.LockType.SHARED, "deletePolicy"))
148 .flatMap(grant -> deletePolicy(grant, policy))
149 .onErrorResume(this::handleException);
152 Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
153 return checkRicStateIdle(policy.getRic()) //
154 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic()))
155 .doOnNext(notUsed -> policies.remove(policy))
156 .doFinally(x -> grant.unlockBlocking())
157 .flatMap(client -> client.deletePolicy(policy))
158 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT))
159 .onErrorResume(this::handleException);
163 public Mono<ResponseEntity<Object>> putPolicy(final Mono<PolicyInfo> policyInfo, final ServerWebExchange exchange) {
165 return policyInfo.flatMap(policyInfoValue -> {
166 String jsonString = gson.toJson(policyInfoValue.getPolicyData());
168 Mono.justOrEmpty(rics.get(policyInfoValue.getRicId()))
169 .switchIfEmpty(Mono.error(new EntityNotFoundException("Near-RT RIC not found"))),
170 Mono.justOrEmpty(policyTypes.get(policyInfoValue.getPolicytypeId()))
171 .switchIfEmpty(Mono.error(new EntityNotFoundException("policy type not found")))
174 Ric ric = tuple.getT1();
175 PolicyType type = tuple.getT2();
177 Policy policy = Policy.builder()
178 .id(policyInfoValue.getPolicyId())
182 .ownerServiceId(policyInfoValue.getServiceId())
183 .lastModified(Instant.now())
184 .isTransient(policyInfoValue.getTransient())
185 .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
188 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
189 .flatMap(x -> ric.getLock().lock(Lock.LockType.SHARED, "putPolicy"))
190 .flatMap(grant -> putPolicy(grant, policy));
192 .onErrorResume(this::handleException);
198 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
199 final boolean isCreate = this.policies.get(policy.getId()) == null;
200 final Ric ric = policy.getRic();
202 return checkRicStateIdle(ric) //
203 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
204 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
205 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
206 .flatMap(client -> client.putPolicy(policy)) //
207 .doOnNext(notUsed -> policies.put(policy)) //
208 .doFinally(x -> grant.unlockBlocking()) //
209 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
210 .onErrorResume(this::handleException);
214 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
215 if (throwable instanceof WebClientResponseException) {
216 WebClientResponseException e = (WebClientResponseException) throwable;
217 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
218 } else if (throwable instanceof WebClientException) {
219 WebClientException e = (WebClientException) throwable;
220 return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
221 } else if (throwable instanceof RejectionException) {
222 RejectionException e = (RejectionException) throwable;
223 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
224 } else if (throwable instanceof ServiceException) {
225 ServiceException e = (ServiceException) throwable;
226 return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
228 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
232 private Mono<Object> validateModifiedPolicy(Policy policy) {
233 // Check that ric is not updated
234 Policy current = this.policies.get(policy.getId());
235 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
236 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
237 ", RIC ID: " + current.getRic().id() + //
238 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
239 logger.debug("Request rejected, {}", e.getMessage());
240 return Mono.error(e);
242 return Mono.just("{}");
245 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
246 if (!ric.isSupportingType(type.getId())) {
247 logger.debug("Request rejected, type not supported, RIC: {}", ric);
248 RejectionException e = new RejectionException(
249 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
250 return Mono.error(e);
252 return Mono.just("{}");
255 private Mono<Object> checkRicStateIdle(Ric ric) {
256 if (ric.getState() == Ric.RicState.AVAILABLE) {
257 return Mono.just("{}");
259 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
260 RejectionException e = new RejectionException(
261 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
263 return Mono.error(e);
268 public Mono<ResponseEntity<Object>> getPolicyInstances(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
269 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
270 throw new EntityNotFoundException("Policy type identity not found");
272 if ((ricId != null && this.rics.get(ricId) == null)) {
273 throw new EntityNotFoundException("Near-RT RIC not found");
276 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
277 return Flux.fromIterable(filtered) //
278 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
279 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
280 .onErrorResume(e -> Mono.empty())
282 .map(authPolicies -> new ResponseEntity<>((Object) policiesToJson(authPolicies), HttpStatus.OK))
283 .onErrorResume(this::handleException);
287 public Mono<ResponseEntity<Object>> getPolicyIds(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
288 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
289 throw new EntityNotFoundException("Policy type not found");
291 if ((ricId != null && this.rics.get(ricId) == null)) {
292 throw new EntityNotFoundException("Near-RT RIC not found");
295 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
296 return Flux.fromIterable(filtered)
297 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
298 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
299 .onErrorResume(e -> Mono.empty())
301 .map(authPolicies -> new ResponseEntity<>((Object)toPolicyIdsJson(authPolicies), HttpStatus.OK))
302 .onErrorResume(this::handleException);
306 public Mono<ResponseEntity<Object>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
307 Policy policy = policies.getPolicy(policyId);
309 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
310 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
311 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
312 .flatMap(status -> createPolicyStatus(policy, status))
313 .onErrorResume(this::handleException);
316 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
319 PolicyStatusInfo policyStatusInfo = new PolicyStatusInfo();
320 policyStatusInfo.setLastModified(policy.getLastModified().toString());
321 policyStatusInfo.setStatus(fromJson(statusFromNearRic));
322 String policyStatusInfoAsString = objectMapper.writeValueAsString(policyStatusInfo);
323 return Mono.just(new ResponseEntity<>(policyStatusInfoAsString, HttpStatus.OK));
324 } catch (JsonProcessingException ex) {
325 throw new RuntimeException(ex);
329 private void keepServiceAlive(String name) {
330 Service s = this.services.get(name);
336 private PolicyInfo toPolicyInfo(Policy policy) {
337 PolicyInfo policyInfo = new PolicyInfo()
338 .policyId(policy.getId())
339 .policyData(gson.fromJson(policy.getJson(), Map.class))
340 .ricId(policy.getRic().id())
341 .policytypeId(policy.getType().getId())
342 .serviceId(policy.getOwnerServiceId())
343 ._transient(policy.isTransient());
344 if (!policy.getStatusNotificationUri().isEmpty()) {
345 policyInfo.setStatusNotificationUri(policy.getStatusNotificationUri());
350 private String toPolicyInfoString(Policy policy) {
353 return objectMapper.writeValueAsString(toPolicyInfo(policy));
354 } catch (JsonProcessingException ex) {
355 throw new RuntimeException(ex);
359 private String policiesToJson(Collection<Policy> policies) {
362 List<PolicyInfo> policiesList = new ArrayList<>(policies.size());
363 PolicyInfoList policyInfoList = new PolicyInfoList();
364 for (Policy policy : policies) {
365 policiesList.add(toPolicyInfo(policy));
367 policyInfoList.setPolicies(policiesList);
368 return objectMapper.writeValueAsString(policyInfoList);
369 } catch(JsonProcessingException ex) {
370 throw new RuntimeException(ex);
374 private Object fromJson(String jsonStr) {
375 return gson.fromJson(jsonStr, Object.class);
378 private String toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) throws JsonProcessingException {
380 PolicyTypeIdList idList = new PolicyTypeIdList();
381 for (PolicyType policyType : policyTypes) {
382 idList.addPolicytypeIdsItem(policyType.getId());
385 return objectMapper.writeValueAsString(idList);
388 private String toPolicyIdsJson(Collection<Policy> policies) {
391 List<String> policyIds = new ArrayList<>(policies.size());
392 PolicyIdList idList = new PolicyIdList();
393 for (Policy policy : policies) {
394 policyIds.add(policy.getId());
396 idList.setPolicyIds(policyIds);
397 return objectMapper.writeValueAsString(idList);
398 } catch (JsonProcessingException ex) {
399 throw new RuntimeException(ex);