9299ffeb907f78e0c78aa422e7d99a7e527f98b3
[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 lombok.RequiredArgsConstructor;
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.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 @RequiredArgsConstructor
67 @Tag(//
68         name = PolicyController.API_NAME, //
69         description = PolicyController.API_DESCRIPTION //
70 )
71 public class PolicyController implements A1PolicyManagementApi {
72
73     public static final String API_NAME = "A1 Policy Management";
74     public static final String API_DESCRIPTION = "";
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     private final Rics rics;
88     private final PolicyTypes policyTypes;
89     private final Policies policies;
90     private final A1ClientFactory a1ClientFactory;
91     private final Services services;
92     private final ObjectMapper objectMapper;
93     private final AuthorizationCheck authorization;
94
95     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
96     private static final Gson gson = new GsonBuilder().create();
97
98     @Override
99     public Mono<ResponseEntity<PolicyTypeDefinition>> getPolicyTypeDefinition(String policyTypeId, ServerWebExchange exchange)
100             throws EntityNotFoundException, JsonProcessingException {
101         PolicyType type = policyTypes.getType(policyTypeId);
102         JsonNode node = objectMapper.readTree(type.getSchema());
103         PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition().policySchema(node);
104         return Mono.just(new ResponseEntity<>(policyTypeDefinition, HttpStatus.OK));
105     }
106
107     @Override
108     public Mono<ResponseEntity<PolicyTypeIdList>> getPolicyTypes(String ricId, String typeName, String compatibleWithVersion, ServerWebExchange exchange) throws Exception {
109         if (compatibleWithVersion != null && typeName == null) {
110             throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
111                     + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
112         }
113
114         Collection<PolicyType> types =
115                 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
116
117         types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
118         return Mono.just(new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK));
119     }
120
121     @Override
122     public Mono<ResponseEntity<PolicyInfo>> getPolicy(String policyId, final ServerWebExchange exchange)
123             throws EntityNotFoundException {
124         Policy policy = policies.getPolicy(policyId);
125         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
126                 .map(x -> new ResponseEntity<>(toPolicyInfo(policy), HttpStatus.OK)) //
127                 .doOnError(error -> logger.error(error.getMessage()));
128     }
129
130     @Override
131     public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {
132
133         Policy policy = policies.getPolicy(policyId);
134         keepServiceAlive(policy.getOwnerServiceId());
135
136         logger.trace("Policy to be deleted: {}", policy.getId());
137         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
138                 .flatMap(x -> policy.getRic().getLock().lock(Lock.LockType.SHARED, "deletePolicy"))
139                 .flatMap(grant -> deletePolicy(grant, policy))
140                 .onErrorResume(this::handleException);
141     }
142
143     Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
144         return checkRicStateIdle(policy.getRic()) //
145                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic()))
146                 .doOnNext(notUsed -> policies.remove(policy))
147                 .doFinally(x -> grant.unlockBlocking())
148                 .flatMap(client -> client.deletePolicy(policy))
149                 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT))
150                 .onErrorResume(this::handleException);
151     }
152
153     @Override
154     public Mono<ResponseEntity<Object>> putPolicy(final Mono<PolicyInfo> policyInfo, final ServerWebExchange exchange) {
155
156         return policyInfo.flatMap(policyInfoValue -> {
157             String jsonString = gson.toJson(policyInfoValue.getPolicyData());
158             return Mono.zip(Mono.justOrEmpty(rics.get(policyInfoValue.getRicId()))
159                                     .switchIfEmpty(Mono.error(new EntityNotFoundException("Near-RT RIC not found"))),
160                             Mono.justOrEmpty(policyTypes.get(policyInfoValue.getPolicytypeId()))
161                                     .switchIfEmpty(Mono.error(new EntityNotFoundException("policy type not found"))))
162                     .flatMap(tuple -> {
163                         Ric ric = tuple.getT1();
164                         PolicyType type = tuple.getT2();
165                         keepServiceAlive(policyInfoValue.getServiceId());
166                         Policy policy = Policy.builder()
167                                 .id(policyInfoValue.getPolicyId())
168                                 .json(jsonString)
169                                 .type(type)
170                                 .ric(ric)
171                                 .ownerServiceId(policyInfoValue.getServiceId())
172                                 .lastModified(Instant.now())
173                                 .isTransient(policyInfoValue.getTransient())
174                                 .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
175                                 .build();
176
177                         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
178                                 .flatMap(x -> ric.getLock().lock(Lock.LockType.SHARED, "putPolicy"))
179                                 .flatMap(grant -> putPolicy(grant, policy));
180                     }).onErrorResume(this::handleException);
181         });
182     }
183
184     private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
185         final boolean isCreate = this.policies.get(policy.getId()) == null;
186         final Ric ric = policy.getRic();
187
188         return checkRicStateIdle(ric) //
189                 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
190                 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
191                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
192                 .flatMap(client -> client.putPolicy(policy)) //
193                 .doOnNext(notUsed -> policies.put(policy)) //
194                 .doFinally(x -> grant.unlockBlocking()) //
195                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
196                 .onErrorResume(this::handleException);
197
198     }
199
200     private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
201         if (throwable instanceof WebClientResponseException) {
202             WebClientResponseException e = (WebClientResponseException) throwable;
203             return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
204         } else if (throwable instanceof WebClientException) {
205             WebClientException e = (WebClientException) throwable;
206             return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
207         } else if (throwable instanceof RejectionException) {
208             RejectionException e = (RejectionException) throwable;
209             return ErrorResponse.createMono(e.getMessage(), e.getStatus());
210         } else if (throwable instanceof ServiceException) {
211             ServiceException e = (ServiceException) throwable;
212             return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
213         } else {
214             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
215         }
216     }
217
218     private Mono<Object> validateModifiedPolicy(Policy policy) {
219         // Check that ric is not updated
220         Policy current = this.policies.get(policy.getId());
221         if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
222             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
223                     ", RIC ID: " + current.getRic().id() + //
224                     ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
225             logger.debug("Request rejected, {}", e.getMessage());
226             return Mono.error(e);
227         }
228         return Mono.just("{}");
229     }
230
231     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
232         if (!ric.isSupportingType(type.getId())) {
233             logger.debug("Request rejected, type not supported, RIC: {}", ric);
234             RejectionException e = new RejectionException(
235                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
236             return Mono.error(e);
237         }
238         return Mono.just("{}");
239     }
240
241     private Mono<Object> checkRicStateIdle(Ric ric) {
242         if (ric.getState() == Ric.RicState.AVAILABLE) {
243             return Mono.just("{}");
244         } else {
245             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
246             RejectionException e = new RejectionException(
247                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
248                     HttpStatus.LOCKED);
249             return Mono.error(e);
250         }
251     }
252
253     @Override
254     public Mono<ResponseEntity<PolicyInfoList>> getPolicyInstances(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
255         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
256             throw new EntityNotFoundException("Policy type identity not found");
257         }
258         if ((ricId != null && this.rics.get(ricId) == null)) {
259             throw new EntityNotFoundException("Near-RT RIC not found");
260         }
261
262         Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
263         return Flux.fromIterable(filtered) //
264                 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
265                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
266                 .onErrorResume(e -> Mono.empty())
267                 .collectList()
268                 .map(authPolicies -> new ResponseEntity<>(policiesToJson(authPolicies), HttpStatus.OK))
269                 .doOnError(error -> logger.error(error.getMessage()));
270     }
271
272     @Override
273     public Mono<ResponseEntity<PolicyIdList>> getPolicyIds(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
274         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
275             throw new EntityNotFoundException("Policy type not found");
276         }
277         if ((ricId != null && this.rics.get(ricId) == null)) {
278             throw new EntityNotFoundException("Near-RT RIC not found");
279         }
280
281         Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
282         return Flux.fromIterable(filtered)
283                 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
284                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
285                 .onErrorResume(e -> Mono.empty())
286                 .collectList()
287                 .map(authPolicies -> new ResponseEntity<>(toPolicyIdsJson(authPolicies), HttpStatus.OK))
288                 .doOnError(error -> logger.error(error.getMessage()));
289     }
290
291     @Override
292     public Mono<ResponseEntity<PolicyStatusInfo>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
293         Policy policy = policies.getPolicy(policyId);
294
295         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
296                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
297                 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
298                 .flatMap(status -> createPolicyStatus(policy, status))
299                 .doOnError(error -> logger.error(error.getMessage()));
300     }
301
302     private Mono<ResponseEntity<PolicyStatusInfo>> createPolicyStatus(Policy policy, String statusFromNearRic) {
303
304         PolicyStatusInfo policyStatusInfo = new PolicyStatusInfo();
305         policyStatusInfo.setLastModified(policy.getLastModified().toString());
306         policyStatusInfo.setStatus(fromJson(statusFromNearRic));
307         return Mono.just(new ResponseEntity<>(policyStatusInfo, HttpStatus.OK));
308     }
309
310     private void keepServiceAlive(String name) {
311         Service s = this.services.get(name);
312         if (s != null) {
313             s.keepAlive();
314         }
315     }
316
317     private PolicyInfo toPolicyInfo(Policy policy) {
318         try {
319             PolicyInfo policyInfo = new PolicyInfo()
320                     .policyId(policy.getId())
321                     .policyData(objectMapper.readTree(policy.getJson()))
322                     .ricId(policy.getRic().id())
323                     .policytypeId(policy.getType().getId())
324                     .serviceId(policy.getOwnerServiceId())
325                     ._transient(policy.isTransient());
326             if (!policy.getStatusNotificationUri().isEmpty()) {
327                 policyInfo.setStatusNotificationUri(policy.getStatusNotificationUri());
328             }
329             return policyInfo;
330         } catch (JsonProcessingException ex) {
331             throw new RuntimeException(ex);
332         }
333     }
334
335     private PolicyInfoList policiesToJson(Collection<Policy> policies) {
336         List<PolicyInfo> policiesList = new ArrayList<>(policies.size());
337         PolicyInfoList policyInfoList = new PolicyInfoList();
338         for (Policy policy : policies) {
339             policiesList.add(toPolicyInfo(policy));
340         }
341         policyInfoList.setPolicies(policiesList);
342         return policyInfoList;
343     }
344
345     private Object fromJson(String jsonStr) {
346         return gson.fromJson(jsonStr, Object.class);
347     }
348
349     private PolicyTypeIdList toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) {
350
351         List<String> policyTypeList = new ArrayList<>(policyTypes.size());
352         PolicyTypeIdList idList = new PolicyTypeIdList();
353         for (PolicyType policyType : policyTypes) {
354             policyTypeList.add(policyType.getId());
355         }
356         idList.setPolicytypeIds(policyTypeList);
357         return idList;
358     }
359
360     private PolicyIdList toPolicyIdsJson(Collection<Policy> policies) {
361
362         List<String> policyIds = new ArrayList<>(policies.size());
363         PolicyIdList idList = new PolicyIdList();
364         for (Policy policy : policies) {
365             policyIds.add(policy.getId());
366         }
367         idList.setPolicyIds(policyIds);
368         return idList;
369     }
370 }