2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2024 OpenInfra Foundation Europe. 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.service.v3;
23 import com.google.gson.Gson;
24 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
25 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
26 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2.Consts;
27 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
28 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
29 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyInformation;
30 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
31 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyTypeInformation;
32 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
33 import org.onap.ccsdk.oran.a1policymanagementservice.util.v3.Helper;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.stereotype.Service;
40 import org.springframework.web.server.ServerWebExchange;
41 import reactor.core.publisher.Flux;
42 import reactor.core.publisher.Mono;
44 import java.lang.invoke.MethodHandles;
45 import java.util.ArrayList;
46 import java.util.Collection;
50 public class PolicyService {
52 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
54 private Helper helper;
60 private PolicyTypes policyTypes;
63 private Policies policies;
66 private AuthorizationService authorizationService;
69 private A1ClientFactory a1ClientFactory;
72 private ErrorHandlingService errorHandlingService;
77 public Mono<ResponseEntity<PolicyObjectInformation>> createPolicyService
78 (PolicyObjectInformation policyObjectInfo, ServerWebExchange serverWebExchange) {
80 if (!helper.jsonSchemaValidation(gson.toJson(policyObjectInfo.getPolicyObject(), Map.class)))
81 return Mono.error(new ServiceException("Schema validation failed", HttpStatus.BAD_REQUEST));
82 Ric ric = rics.getRic(policyObjectInfo.getNearRtRicId());
83 PolicyType policyType = policyTypes.getType(policyObjectInfo.getPolicyTypeId());
84 Policy policy = helper.buildPolicy(policyObjectInfo, policyType, ric, helper.policyIdGeneration(policyObjectInfo));
85 return helper.isPolicyAlreadyCreated(policy,policies)
86 .doOnError(error -> errorHandlingService.handleError(error))
87 .flatMap(policyBuilt -> authorizationService.authCheck(serverWebExchange, policy, AccessType.WRITE)
88 .doOnError(error -> errorHandlingService.handleError(error))
89 .flatMap(policyNotUsed -> ric.getLock().lock(Lock.LockType.SHARED, "createPolicy"))
90 .flatMap(grant -> postPolicy(policy, grant))
91 .map(locationHeaderValue ->
92 new ResponseEntity<PolicyObjectInformation>(policyObjectInfo,helper.createHttpHeaders(
93 "location",helper.buildURI(policy.getId(), serverWebExchange)), HttpStatus.CREATED))
94 .doOnError(error -> errorHandlingService.handleError(error)));
95 } catch (Exception ex) {
96 return Mono.error(ex);
101 private Mono<String> postPolicy(Policy policy, Lock.Grant grant) {
102 return helper.checkRicStateIdle(policy.getRic())
103 .doOnError(error -> errorHandlingService.handleError(error))
104 .flatMap(ric -> helper.checkSupportedType(ric, policy.getType()))
105 .doOnError(error -> errorHandlingService.handleError(error))
106 .flatMap(ric -> a1ClientFactory.createA1Client(ric))
107 .flatMap(a1Client -> a1Client.putPolicy(policy))
108 .doOnError(error -> errorHandlingService.handleError(error))
109 .doOnNext(policyString -> policies.put(policy))
110 .doFinally(releaseLock -> grant.unlockBlocking())
111 .doOnError(error -> errorHandlingService.handleError(error));
114 public Mono<ResponseEntity<Object>> putPolicyService(String policyId, Object body, ServerWebExchange exchange) {
116 Policy existingPolicy = policies.getPolicy(policyId);
117 PolicyObjectInformation pos =
118 new PolicyObjectInformation(existingPolicy.getRic().getConfig().getRicId(), body, existingPolicy.getType().getId());
119 Policy updatedPolicy = helper.buildPolicy(pos, existingPolicy.getType(), existingPolicy.getRic(), policyId);
120 Ric ric = existingPolicy.getRic();
121 return authorizationService.authCheck(exchange, updatedPolicy, AccessType.WRITE)
122 .doOnError(error -> errorHandlingService.handleError(error))
123 .flatMap(policy -> ric.getLock().lock(Lock.LockType.SHARED, "updatePolicy"))
124 .doOnError(error -> errorHandlingService.handleError(error))
125 .flatMap(grant -> postPolicy(updatedPolicy, grant))
126 .map(header -> new ResponseEntity<Object>(policies.get(updatedPolicy.getId()).getJson(), HttpStatus.OK))
127 .doOnError(error -> errorHandlingService.handleError(error));
128 } catch(Exception ex) {
129 return Mono.error(ex);
133 public Mono<ResponseEntity<Flux<PolicyTypeInformation>>> getPolicyTypesService(String nearRtRicId, String typeName,
134 String compatibleWithVersion,
135 ServerWebExchange webExchange) throws Exception {
136 if (compatibleWithVersion != null && typeName == null) {
137 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
138 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
140 Collection<PolicyTypeInformation> listOfPolicyTypes = new ArrayList<>();
141 if (nearRtRicId == null || nearRtRicId.isEmpty() || nearRtRicId.isBlank()) {
142 for(Ric ric : rics.getRics()) {
143 Collection<PolicyType> policyTypes = PolicyTypes.filterTypes(ric.getSupportedPolicyTypes(), typeName,
144 compatibleWithVersion);
145 listOfPolicyTypes.addAll(helper.toPolicyTypeInfoCollection(policyTypes, ric));
148 Ric ric = rics.get(nearRtRicId);
150 throw new EntityNotFoundException("Near-RT RIC not Found using ID: " +nearRtRicId);
151 Collection<PolicyType> policyTypes = PolicyTypes.filterTypes(ric.getSupportedPolicyTypes(), typeName,
152 compatibleWithVersion);
153 listOfPolicyTypes.addAll(helper.toPolicyTypeInfoCollection(policyTypes, ric));
155 return Mono.just(new ResponseEntity<>(Flux.fromIterable(listOfPolicyTypes), HttpStatus.OK));
158 public Mono<ResponseEntity<Flux<PolicyInformation>>> getPolicyIdsService(String policyTypeId, String nearRtRicId,
159 String serviceId, String typeName,
160 ServerWebExchange exchange) throws EntityNotFoundException {
161 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null))
162 throw new EntityNotFoundException("Policy type not found using ID: " +policyTypeId);
163 if ((nearRtRicId != null && this.rics.get(nearRtRicId) == null))
164 throw new EntityNotFoundException("Near-RT RIC not found using ID: " +nearRtRicId);
166 Collection<Policy> filtered = policies.filterPolicies(policyTypeId, nearRtRicId, serviceId, typeName);
167 return Flux.fromIterable(filtered)
168 .flatMap(policy -> authorizationService.authCheck(exchange, policy, AccessType.READ))
169 .onErrorContinue((error,item) -> logger.warn("Error occurred during authorization check for " +
170 "policy {}: {}", item, error.getMessage()))
172 .map(authPolicies -> new ResponseEntity<>(helper.toFluxPolicyInformation(authPolicies), HttpStatus.OK))
173 .doOnError(error -> logger.error(error.getMessage()));
176 public Mono<ResponseEntity<Object>> getPolicyService(String policyId, ServerWebExchange serverWebExchange)
177 throws EntityNotFoundException{
178 Policy policy = policies.getPolicy(policyId);
179 return authorizationService.authCheck(serverWebExchange, policy, AccessType.READ)
180 .map(x -> new ResponseEntity<Object>(policy.getJson(), HttpStatus.OK))
181 .doOnError(error -> errorHandlingService.handleError(error));
184 public Mono<ResponseEntity<Object>> getPolicyTypeDefinitionService(String policyTypeId)
185 throws EntityNotFoundException{
186 PolicyType singlePolicyType = policyTypes.get(policyTypeId);
187 if (singlePolicyType == null)
188 throw new EntityNotFoundException("PolicyType not found with ID: " + policyTypeId);
189 return Mono.just(new ResponseEntity<Object>(singlePolicyType.getSchema(), HttpStatus.OK));
192 public Mono<ResponseEntity<Void>> deletePolicyService(String policyId, ServerWebExchange serverWebExchange)
193 throws EntityNotFoundException {
194 Policy singlePolicy = policies.getPolicy(policyId);
195 return authorizationService.authCheck(serverWebExchange, singlePolicy, AccessType.WRITE)
196 .doOnError(error -> errorHandlingService.handleError(error))
197 .flatMap(policy -> policy.getRic().getLock().lock(Lock.LockType.SHARED, "deletePolicy"))
198 .flatMap(grant -> deletePolicy(singlePolicy, grant))
199 .doOnError(error -> errorHandlingService.handleError(error));
202 private Mono<ResponseEntity<Void>> deletePolicy(Policy policy, Lock.Grant grant) {
203 return helper.checkRicStateIdle(policy.getRic())
204 .doOnError(error -> errorHandlingService.handleError(error))
205 .flatMap(ric -> helper.checkSupportedType(ric, policy.getType()))
206 .doOnError(error -> errorHandlingService.handleError(error))
207 .flatMap(ric -> a1ClientFactory.createA1Client(ric))
208 .doOnError(error -> errorHandlingService.handleError(error))
209 .flatMap(a1Client -> a1Client.deletePolicy(policy))
210 .doOnError(error -> errorHandlingService.handleError(error))
211 .doOnNext(policyString -> policies.remove(policy))
212 .doFinally(releaseLock -> grant.unlockBlocking())
213 .map(successResponse -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT))
214 .doOnError(error -> errorHandlingService.handleError(error));