630be491343943273aa226695ea3926867f69d51
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
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
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.controllers.v2;
22
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;
28
29 import io.swagger.v3.oas.annotations.tags.Tag;
30
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;
36
37 import lombok.Getter;
38
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;
60
61 import org.springframework.web.server.ServerWebExchange;
62 import reactor.core.publisher.Flux;
63 import reactor.core.publisher.Mono;
64
65 @RestController("PolicyControllerV2")
66 @Tag(//
67         name = PolicyController.API_NAME, //
68         description = PolicyController.API_DESCRIPTION //
69 )
70 public class PolicyController implements A1PolicyManagementApi {
71
72     public static final String API_NAME = "A1 Policy Management";
73     public static final String API_DESCRIPTION = "";
74
75     public static class RejectionException extends Exception {
76         private static final long serialVersionUID = 1L;
77
78         @Getter
79         private final HttpStatus status;
80
81         public RejectionException(String message, HttpStatus status) {
82             super(message);
83             this.status = status;
84         }
85     }
86
87     @Autowired
88     private Rics rics;
89     @Autowired
90     private PolicyTypes policyTypes;
91     @Autowired
92     private Policies policies;
93     @Autowired
94     private A1ClientFactory a1ClientFactory;
95     @Autowired
96     private Services services;
97     @Autowired
98     private ObjectMapper objectMapper;
99     @Autowired
100     private AuthorizationCheck authorization;
101
102     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
103     private static Gson gson = new GsonBuilder() //
104             .create(); //
105
106     @Override
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));
113     }
114
115     @Override
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);
120         }
121
122         Collection<PolicyType> types =
123                 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
124
125         types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
126         return Mono.just(new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK));
127     }
128
129     @Override
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()));
136     }
137
138     @Override
139     public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {
140
141         Policy policy = policies.getPolicy(policyId);
142         keepServiceAlive(policy.getOwnerServiceId());
143
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);
149     }
150
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);
159     }
160
161     @Override
162     public Mono<ResponseEntity<Object>> putPolicy(final Mono<PolicyInfo> policyInfo, final ServerWebExchange exchange) {
163
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"))))
170                     .flatMap(tuple -> {
171                         Ric ric = tuple.getT1();
172                         PolicyType type = tuple.getT2();
173                         keepServiceAlive(policyInfoValue.getServiceId());
174                         Policy policy = Policy.builder()
175                                 .id(policyInfoValue.getPolicyId())
176                                 .json(jsonString)
177                                 .type(type)
178                                 .ric(ric)
179                                 .ownerServiceId(policyInfoValue.getServiceId())
180                                 .lastModified(Instant.now())
181                                 .isTransient(policyInfoValue.getTransient())
182                                 .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
183                                 .build();
184
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);
189         });
190     }
191
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();
195
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);
205
206     }
207
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());
221         } else {
222             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
223         }
224     }
225
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);
235         }
236         return Mono.just("{}");
237     }
238
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);
245         }
246         return Mono.just("{}");
247     }
248
249     private Mono<Object> checkRicStateIdle(Ric ric) {
250         if (ric.getState() == Ric.RicState.AVAILABLE) {
251             return Mono.just("{}");
252         } else {
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(),
256                     HttpStatus.LOCKED);
257             return Mono.error(e);
258         }
259     }
260
261     @Override
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");
265         }
266         if ((ricId != null && this.rics.get(ricId) == null)) {
267             throw new EntityNotFoundException("Near-RT RIC not found");
268         }
269
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())
275                 .collectList()
276                 .map(authPolicies -> new ResponseEntity<>(policiesToJson(authPolicies), HttpStatus.OK))
277                 .doOnError(error -> logger.error(error.getMessage()));
278     }
279
280     @Override
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");
284         }
285         if ((ricId != null && this.rics.get(ricId) == null)) {
286             throw new EntityNotFoundException("Near-RT RIC not found");
287         }
288
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())
294                 .collectList()
295                 .map(authPolicies -> new ResponseEntity<>(toPolicyIdsJson(authPolicies), HttpStatus.OK))
296                 .doOnError(error -> logger.error(error.getMessage()));
297     }
298
299     @Override
300     public Mono<ResponseEntity<PolicyStatusInfo>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
301         Policy policy = policies.getPolicy(policyId);
302
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()));
308     }
309
310     private Mono<ResponseEntity<PolicyStatusInfo>> createPolicyStatus(Policy policy, String statusFromNearRic) {
311
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));
316     }
317
318     private void keepServiceAlive(String name) {
319         Service s = this.services.get(name);
320         if (s != null) {
321             s.keepAlive();
322         }
323     }
324
325     private PolicyInfo toPolicyInfo(Policy policy) {
326         try {
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());
336             }
337             return policyInfo;
338         } catch (JsonProcessingException ex) {
339             throw new RuntimeException(ex);
340         }
341     }
342
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));
348         }
349         policyInfoList.setPolicies(policiesList);
350         return policyInfoList;
351     }
352
353     private Object fromJson(String jsonStr) {
354         return gson.fromJson(jsonStr, Object.class);
355     }
356
357     private PolicyTypeIdList toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) {
358
359         List<String> policyTypeList = new ArrayList<>(policyTypes.size());
360         PolicyTypeIdList idList = new PolicyTypeIdList();
361         for (PolicyType policyType : policyTypes) {
362             policyTypeList.add(policyType.getId());
363         }
364         idList.setPolicytypeIds(policyTypeList);
365         return idList;
366     }
367
368     private PolicyIdList toPolicyIdsJson(Collection<Policy> policies) {
369
370         List<String> policyIds = new ArrayList<>(policies.size());
371         PolicyIdList idList = new PolicyIdList();
372         for (Policy policy : policies) {
373             policyIds.add(policy.getId());
374         }
375         idList.setPolicyIds(policyIds);
376         return idList;
377     }
378 }