66b5ae0cd54881efdf4a00c918481390429ef81d
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.service.v3;
22
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;
43
44 import java.lang.invoke.MethodHandles;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.Map;
48
49 @Service
50 public class PolicyService {
51
52     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
53     @Autowired
54     private Helper helper;
55
56     @Autowired
57     private Rics rics;
58
59     @Autowired
60     private PolicyTypes policyTypes;
61
62     @Autowired
63     private Policies policies;
64
65     @Autowired
66     private AuthorizationService authorizationService;
67
68     @Autowired
69     private A1ClientFactory a1ClientFactory;
70
71     @Autowired
72     private ErrorHandlingService errorHandlingService;
73
74     @Autowired
75     private Gson gson;
76
77     public Mono<ResponseEntity<PolicyObjectInformation>> createPolicyService
78             (PolicyObjectInformation policyObjectInfo, ServerWebExchange serverWebExchange) {
79         try {
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());
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);
97         }
98
99     }
100
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));
112     }
113
114     public Mono<ResponseEntity<Object>> putPolicyService(String policyId, Object body, ServerWebExchange exchange) {
115
116         try {
117             Policy existingPolicy = policies.getPolicy(policyId);
118             PolicyObjectInformation pos =
119                     new PolicyObjectInformation(existingPolicy.getRic().getConfig().getRicId(), body, existingPolicy.getType().getId());
120             Policy updatedPolicy = helper.buildPolicy(pos, existingPolicy.getType(), existingPolicy.getRic(), policyId);
121             Ric ric = existingPolicy.getRic();
122              ric.getLock().lock(Lock.LockType.SHARED, "updatePolicy")
123                     .flatMap(grant -> postPolicy(updatedPolicy, grant))
124                     .doOnError(error -> errorHandlingService.handleError(error));
125              return Mono.just(new ResponseEntity<>(policies.getPolicy(policyId), HttpStatus.OK));
126         } catch(Exception ex) {
127             return Mono.error(ex);
128         }
129     }
130
131     public Mono<ResponseEntity<Flux<PolicyTypeInformation>>> getPolicyTypesService(String nearRtRicId, String typeName,
132                                                                                    String compatibleWithVersion,
133                                                                                    ServerWebExchange webExchange) throws Exception {
134         if (compatibleWithVersion != null && typeName == null) {
135             throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
136                     + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
137         }
138         Collection<PolicyTypeInformation> listOfPolicyTypes = new ArrayList<>();
139         if (nearRtRicId == null || nearRtRicId.isEmpty() || nearRtRicId.isBlank()) {
140             for(Ric ric : rics.getRics()) {
141                 Collection<PolicyType> policyTypes = PolicyTypes.filterTypes(ric.getSupportedPolicyTypes(), typeName,
142                         compatibleWithVersion);
143                 listOfPolicyTypes.addAll(helper.toPolicyTypeInfoCollection(policyTypes, ric));
144             }
145         } else {
146             Ric ric = rics.get(nearRtRicId);
147             if (ric == null)
148                 throw new EntityNotFoundException("Near-RT RIC not Found using ID: " +nearRtRicId);
149             Collection<PolicyType> policyTypes = PolicyTypes.filterTypes(ric.getSupportedPolicyTypes(), typeName,
150                     compatibleWithVersion);
151             listOfPolicyTypes.addAll(helper.toPolicyTypeInfoCollection(policyTypes, ric));
152         }
153         return Mono.just(new ResponseEntity<>(Flux.fromIterable(listOfPolicyTypes), HttpStatus.OK));
154     }
155
156     public Mono<ResponseEntity<Flux<PolicyInformation>>> getPolicyIdsService(String policyTypeId, String nearRtRicId,
157                                                                              String serviceId, String typeName,
158                                                                              ServerWebExchange exchange) throws EntityNotFoundException {
159         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null))
160             throw new EntityNotFoundException("Policy type not found using ID: " +policyTypeId);
161         if ((nearRtRicId != null && this.rics.get(nearRtRicId) == null))
162             throw new EntityNotFoundException("Near-RT RIC not found using ID: " +nearRtRicId);
163
164         Collection<Policy> filtered = policies.filterPolicies(policyTypeId, nearRtRicId, serviceId, typeName);
165         return Flux.fromIterable(filtered)
166                 .flatMap(policy -> authorizationService.authCheck(exchange, policy, AccessType.READ))
167                 .onErrorContinue((error,item) -> logger.warn("Error occurred during authorization check for " +
168                         "policy {}: {}", item, error.getMessage()))
169                 .collectList()
170                 .map(authPolicies -> new ResponseEntity<>(helper.toFluxPolicyInformation(authPolicies), HttpStatus.OK))
171                 .doOnError(error -> logger.error(error.getMessage()));
172     }
173
174     public Mono<ResponseEntity<Object>> getPolicyService(String policyId, ServerWebExchange serverWebExchange)
175             throws EntityNotFoundException{
176             Policy policy = policies.getPolicy(policyId);
177         return authorizationService.authCheck(serverWebExchange, policy, AccessType.READ)
178                 .map(x -> new ResponseEntity<Object>(policy.getJson(), HttpStatus.OK))
179                 .doOnError(error -> errorHandlingService.handleError(error));
180     }
181
182     public Mono<ResponseEntity<Object>> getPolicyTypeDefinitionService(String policyTypeId)
183             throws EntityNotFoundException{
184         PolicyType singlePolicyType = policyTypes.get(policyTypeId);
185         if (singlePolicyType == null)
186             throw new EntityNotFoundException("PolicyType not found with ID: " + policyTypeId);
187         return Mono.just(new ResponseEntity<Object>(singlePolicyType.getSchema(), HttpStatus.OK));
188     }
189
190     public Mono<ResponseEntity<Void>> deletePolicyService(String policyId, ServerWebExchange serverWebExchange)
191             throws EntityNotFoundException {
192         Policy singlePolicy = policies.getPolicy(policyId);
193         return authorizationService.authCheck(serverWebExchange, singlePolicy, AccessType.WRITE)
194                 .doOnError(error -> errorHandlingService.handleError(error))
195                 .flatMap(policy -> policy.getRic().getLock().lock(Lock.LockType.SHARED, "deletePolicy"))
196                 .flatMap(grant -> deletePolicy(singlePolicy, grant))
197                 .doOnError(error -> errorHandlingService.handleError(error));
198     }
199
200     private Mono<ResponseEntity<Void>> deletePolicy(Policy policy, Lock.Grant grant) {
201         System.out.println();
202         return  helper.checkRicStateIdle(policy.getRic())
203                 .doOnError(error -> errorHandlingService.handleError(error))
204                 .flatMap(ric -> helper.checkSupportedType(ric, policy.getType()))
205                 .doOnError(error -> errorHandlingService.handleError(error))
206                 .flatMap(ric -> a1ClientFactory.createA1Client(ric))
207                 .flatMap(a1Client -> a1Client.deletePolicy(policy))
208                 .doOnError(error -> errorHandlingService.handleError(error))
209                 .doOnNext(policyString -> policies.remove(policy))
210                 .doFinally(releaseLock -> grant.unlockBlocking())
211                 .map(successResponse -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT))
212                 .doOnError(error -> errorHandlingService.handleError(error));
213     }
214 }