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));
130 public Mono<ResponseEntity<PolicyInfo>> getPolicy(String policyId, final ServerWebExchange exchange)
131 throws EntityNotFoundException {
132 Policy policy = policies.getPolicy(policyId);
133 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
134 .map(x -> new ResponseEntity<>(toPolicyInfo(policy), HttpStatus.OK)) //
135 .doOnError(error -> logger.error(error.getMessage()));
139 public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {
141 Policy policy = policies.getPolicy(policyId);
142 keepServiceAlive(policy.getOwnerServiceId());
144 logger.trace("Policy to be deleted: {}", policy.getId());
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());
166 return Mono.zip(Mono.justOrEmpty(rics.get(policyInfoValue.getRicId()))
167 .switchIfEmpty(Mono.error(new EntityNotFoundException("Near-RT RIC not found"))),
168 Mono.justOrEmpty(policyTypes.get(policyInfoValue.getPolicytypeId()))
169 .switchIfEmpty(Mono.error(new EntityNotFoundException("policy type not found"))))
171 Ric ric = tuple.getT1();
172 PolicyType type = tuple.getT2();
173 keepServiceAlive(policyInfoValue.getServiceId());
174 Policy policy = Policy.builder()
175 .id(policyInfoValue.getPolicyId())
179 .ownerServiceId(policyInfoValue.getServiceId())
180 .lastModified(Instant.now())
181 .isTransient(policyInfoValue.getTransient())
182 .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
185 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
186 .flatMap(x -> ric.getLock().lock(Lock.LockType.SHARED, "putPolicy"))
187 .flatMap(grant -> putPolicy(grant, policy));
188 }).onErrorResume(this::handleException);
192 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
193 final boolean isCreate = this.policies.get(policy.getId()) == null;
194 final Ric ric = policy.getRic();
196 return checkRicStateIdle(ric) //
197 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
198 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
199 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
200 .flatMap(client -> client.putPolicy(policy)) //
201 .doOnNext(notUsed -> policies.put(policy)) //
202 .doFinally(x -> grant.unlockBlocking()) //
203 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
204 .onErrorResume(this::handleException);
208 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
209 if (throwable instanceof WebClientResponseException) {
210 WebClientResponseException e = (WebClientResponseException) throwable;
211 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
212 } else if (throwable instanceof WebClientException) {
213 WebClientException e = (WebClientException) throwable;
214 return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
215 } else if (throwable instanceof RejectionException) {
216 RejectionException e = (RejectionException) throwable;
217 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
218 } else if (throwable instanceof ServiceException) {
219 ServiceException e = (ServiceException) throwable;
220 return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
222 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
226 private Mono<Object> validateModifiedPolicy(Policy policy) {
227 // Check that ric is not updated
228 Policy current = this.policies.get(policy.getId());
229 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
230 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
231 ", RIC ID: " + current.getRic().id() + //
232 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
233 logger.debug("Request rejected, {}", e.getMessage());
234 return Mono.error(e);
236 return Mono.just("{}");
239 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
240 if (!ric.isSupportingType(type.getId())) {
241 logger.debug("Request rejected, type not supported, RIC: {}", ric);
242 RejectionException e = new RejectionException(
243 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
244 return Mono.error(e);
246 return Mono.just("{}");
249 private Mono<Object> checkRicStateIdle(Ric ric) {
250 if (ric.getState() == Ric.RicState.AVAILABLE) {
251 return Mono.just("{}");
253 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
254 RejectionException e = new RejectionException(
255 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
257 return Mono.error(e);
262 public Mono<ResponseEntity<PolicyInfoList>> getPolicyInstances(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
263 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
264 throw new EntityNotFoundException("Policy type identity not found");
266 if ((ricId != null && this.rics.get(ricId) == null)) {
267 throw new EntityNotFoundException("Near-RT RIC not found");
270 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
271 return Flux.fromIterable(filtered) //
272 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
273 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
274 .onErrorResume(e -> Mono.empty())
276 .map(authPolicies -> new ResponseEntity<>(policiesToJson(authPolicies), HttpStatus.OK))
277 .doOnError(error -> logger.error(error.getMessage()));
281 public Mono<ResponseEntity<PolicyIdList>> getPolicyIds(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
282 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
283 throw new EntityNotFoundException("Policy type not found");
285 if ((ricId != null && this.rics.get(ricId) == null)) {
286 throw new EntityNotFoundException("Near-RT RIC not found");
289 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
290 return Flux.fromIterable(filtered)
291 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
292 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
293 .onErrorResume(e -> Mono.empty())
295 .map(authPolicies -> new ResponseEntity<>(toPolicyIdsJson(authPolicies), HttpStatus.OK))
296 .doOnError(error -> logger.error(error.getMessage()));
300 public Mono<ResponseEntity<PolicyStatusInfo>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
301 Policy policy = policies.getPolicy(policyId);
303 return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
304 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
305 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
306 .flatMap(status -> createPolicyStatus(policy, status))
307 .doOnError(error -> logger.error(error.getMessage()));
310 private Mono<ResponseEntity<PolicyStatusInfo>> createPolicyStatus(Policy policy, String statusFromNearRic) {
312 PolicyStatusInfo policyStatusInfo = new PolicyStatusInfo();
313 policyStatusInfo.setLastModified(policy.getLastModified().toString());
314 policyStatusInfo.setStatus(fromJson(statusFromNearRic));
315 return Mono.just(new ResponseEntity<>(policyStatusInfo, HttpStatus.OK));
318 private void keepServiceAlive(String name) {
319 Service s = this.services.get(name);
325 private PolicyInfo toPolicyInfo(Policy policy) {
327 PolicyInfo policyInfo = new PolicyInfo()
328 .policyId(policy.getId())
329 .policyData(objectMapper.readTree(policy.getJson()))
330 .ricId(policy.getRic().id())
331 .policytypeId(policy.getType().getId())
332 .serviceId(policy.getOwnerServiceId())
333 ._transient(policy.isTransient());
334 if (!policy.getStatusNotificationUri().isEmpty()) {
335 policyInfo.setStatusNotificationUri(policy.getStatusNotificationUri());
338 } catch (JsonProcessingException ex) {
339 throw new RuntimeException(ex);
343 private PolicyInfoList policiesToJson(Collection<Policy> policies) {
344 List<PolicyInfo> policiesList = new ArrayList<>(policies.size());
345 PolicyInfoList policyInfoList = new PolicyInfoList();
346 for (Policy policy : policies) {
347 policiesList.add(toPolicyInfo(policy));
349 policyInfoList.setPolicies(policiesList);
350 return policyInfoList;
353 private Object fromJson(String jsonStr) {
354 return gson.fromJson(jsonStr, Object.class);
357 private PolicyTypeIdList toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) {
359 List<String> policyTypeList = new ArrayList<>(policyTypes.size());
360 PolicyTypeIdList idList = new PolicyTypeIdList();
361 for (PolicyType policyType : policyTypes) {
362 policyTypeList.add(policyType.getId());
364 idList.setPolicytypeIds(policyTypeList);
368 private PolicyIdList toPolicyIdsJson(Collection<Policy> policies) {
370 List<String> policyIds = new ArrayList<>(policies.size());
371 PolicyIdList idList = new PolicyIdList();
372 for (Policy policy : policies) {
373 policyIds.add(policy.getId());
375 idList.setPolicyIds(policyIds);