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