53cf62a25aa2d5ecdeb43e37848ac15fe4d8bf30
[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
130     @Override
131     public Mono<ResponseEntity<PolicyInfo>> getPolicy(String policyId, final ServerWebExchange exchange)
132             throws EntityNotFoundException {
133         Policy policy = policies.getPolicy(policyId);
134         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
135                 .map(x -> new ResponseEntity<>(toPolicyInfo(policy), HttpStatus.OK)) //
136                 .doOnError(error -> logger.error(error.getMessage()));
137     }
138
139     @Override
140     public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {
141
142         Policy policy = policies.getPolicy(policyId);
143         keepServiceAlive(policy.getOwnerServiceId());
144
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(
167                             Mono.justOrEmpty(rics.get(policyInfoValue.getRicId()))
168                                     .switchIfEmpty(Mono.error(new EntityNotFoundException("Near-RT RIC not found"))),
169                             Mono.justOrEmpty(policyTypes.get(policyInfoValue.getPolicytypeId()))
170                                     .switchIfEmpty(Mono.error(new EntityNotFoundException("policy type not found")))
171                     )
172                     .flatMap(tuple -> {
173                         Ric ric = tuple.getT1();
174                         PolicyType type = tuple.getT2();
175                         keepServiceAlive(policyInfoValue.getServiceId());
176                         Policy policy = Policy.builder()
177                                 .id(policyInfoValue.getPolicyId())
178                                 .json(jsonString)
179                                 .type(type)
180                                 .ric(ric)
181                                 .ownerServiceId(policyInfoValue.getServiceId())
182                                 .lastModified(Instant.now())
183                                 .isTransient(policyInfoValue.getTransient())
184                                 .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
185                                 .build();
186
187                         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
188                                 .flatMap(x -> ric.getLock().lock(Lock.LockType.SHARED, "putPolicy"))
189                                 .flatMap(grant -> putPolicy(grant, policy));
190                     })
191                     .onErrorResume(this::handleException);
192         });
193     }
194
195
196
197     private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
198         final boolean isCreate = this.policies.get(policy.getId()) == null;
199         final Ric ric = policy.getRic();
200
201         return checkRicStateIdle(ric) //
202                 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
203                 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
204                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
205                 .flatMap(client -> client.putPolicy(policy)) //
206                 .doOnNext(notUsed -> policies.put(policy)) //
207                 .doFinally(x -> grant.unlockBlocking()) //
208                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
209                 .onErrorResume(this::handleException);
210
211     }
212
213     private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
214         if (throwable instanceof WebClientResponseException) {
215             WebClientResponseException e = (WebClientResponseException) throwable;
216             return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
217         } else if (throwable instanceof WebClientException) {
218             WebClientException e = (WebClientException) throwable;
219             return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
220         } else if (throwable instanceof RejectionException) {
221             RejectionException e = (RejectionException) throwable;
222             return ErrorResponse.createMono(e.getMessage(), e.getStatus());
223         } else if (throwable instanceof ServiceException) {
224             ServiceException e = (ServiceException) throwable;
225             return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
226         } else {
227             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
228         }
229     }
230
231     private Mono<Object> validateModifiedPolicy(Policy policy) {
232         // Check that ric is not updated
233         Policy current = this.policies.get(policy.getId());
234         if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
235             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
236                     ", RIC ID: " + current.getRic().id() + //
237                     ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
238             logger.debug("Request rejected, {}", e.getMessage());
239             return Mono.error(e);
240         }
241         return Mono.just("{}");
242     }
243
244     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
245         if (!ric.isSupportingType(type.getId())) {
246             logger.debug("Request rejected, type not supported, RIC: {}", ric);
247             RejectionException e = new RejectionException(
248                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
249             return Mono.error(e);
250         }
251         return Mono.just("{}");
252     }
253
254     private Mono<Object> checkRicStateIdle(Ric ric) {
255         if (ric.getState() == Ric.RicState.AVAILABLE) {
256             return Mono.just("{}");
257         } else {
258             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
259             RejectionException e = new RejectionException(
260                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
261                     HttpStatus.LOCKED);
262             return Mono.error(e);
263         }
264     }
265
266     @Override
267     public Mono<ResponseEntity<PolicyInfoList>> getPolicyInstances(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
268         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
269             throw new EntityNotFoundException("Policy type identity not found");
270         }
271         if ((ricId != null && this.rics.get(ricId) == null)) {
272             throw new EntityNotFoundException("Near-RT RIC not found");
273         }
274
275         Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
276         return Flux.fromIterable(filtered) //
277                 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
278                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
279                 .onErrorResume(e -> Mono.empty())
280                 .collectList()
281                 .map(authPolicies -> new ResponseEntity<>(policiesToJson(authPolicies), HttpStatus.OK))
282                 .doOnError(error -> logger.error(error.getMessage()));
283     }
284
285     @Override
286     public Mono<ResponseEntity<PolicyIdList>> getPolicyIds(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
287         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
288             throw new EntityNotFoundException("Policy type not found");
289         }
290         if ((ricId != null && this.rics.get(ricId) == null)) {
291             throw new EntityNotFoundException("Near-RT RIC not found");
292         }
293
294         Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
295         return Flux.fromIterable(filtered)
296                 .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
297                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
298                 .onErrorResume(e -> Mono.empty())
299                 .collectList()
300                 .map(authPolicies -> new ResponseEntity<>(toPolicyIdsJson(authPolicies), HttpStatus.OK))
301                 .doOnError(error -> logger.error(error.getMessage()));
302     }
303
304     @Override
305     public Mono<ResponseEntity<PolicyStatusInfo>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
306         Policy policy = policies.getPolicy(policyId);
307
308         return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
309                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
310                 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
311                 .flatMap(status -> createPolicyStatus(policy, status))
312                 .doOnError(error -> logger.error(error.getMessage()));
313     }
314
315     private Mono<ResponseEntity<PolicyStatusInfo>> createPolicyStatus(Policy policy, String statusFromNearRic) {
316
317         PolicyStatusInfo policyStatusInfo = new PolicyStatusInfo();
318         policyStatusInfo.setLastModified(policy.getLastModified().toString());
319         policyStatusInfo.setStatus(fromJson(statusFromNearRic));
320         return Mono.just(new ResponseEntity<>(policyStatusInfo, HttpStatus.OK));
321     }
322
323     private void keepServiceAlive(String name) {
324         Service s = this.services.get(name);
325         if (s != null) {
326             s.keepAlive();
327         }
328     }
329
330     private PolicyInfo toPolicyInfo(Policy policy) {
331        try {
332            PolicyInfo policyInfo = new PolicyInfo()
333                    .policyId(policy.getId())
334                    .policyData(objectMapper.readTree(policy.getJson()))
335                    .ricId(policy.getRic().id())
336                    .policytypeId(policy.getType().getId())
337                    .serviceId(policy.getOwnerServiceId())
338                    ._transient(policy.isTransient());
339            if (!policy.getStatusNotificationUri().isEmpty()) {
340                policyInfo.setStatusNotificationUri(policy.getStatusNotificationUri());
341            }
342            return policyInfo;
343        } catch (JsonProcessingException ex) {
344            throw new RuntimeException(ex);
345        }
346     }
347
348     private PolicyInfoList policiesToJson(Collection<Policy> policies) {
349
350                 List<PolicyInfo> policiesList = new ArrayList<>(policies.size());
351                 PolicyInfoList policyInfoList = new PolicyInfoList();
352                 for (Policy policy : policies) {
353                     policiesList.add(toPolicyInfo(policy));
354                 }
355                 policyInfoList.setPolicies(policiesList);
356                 return policyInfoList;
357     }
358
359     private Object fromJson(String jsonStr) {
360         return gson.fromJson(jsonStr, Object.class);
361     }
362
363     private PolicyTypeIdList toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) {
364
365         List<String> policyTypeList = new ArrayList<>(policyTypes.size());
366         PolicyTypeIdList idList = new PolicyTypeIdList();
367         for (PolicyType policyType : policyTypes) {
368             policyTypeList.add(policyType.getId());
369         }
370         idList.setPolicytypeIds(policyTypeList);
371         return idList;
372     }
373
374     private PolicyIdList toPolicyIdsJson(Collection<Policy> policies) {
375
376             List<String> policyIds = new ArrayList<>(policies.size());
377             PolicyIdList idList = new PolicyIdList();
378             for (Policy policy : policies) {
379                 policyIds.add(policy.getId());
380             }
381             idList.setPolicyIds(policyIds);
382             return idList;
383     }
384 }