ab9b669287ae4728b604af0ee7baad7a827d9410
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 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.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.Content;
29 import io.swagger.v3.oas.annotations.media.Schema;
30 import io.swagger.v3.oas.annotations.responses.ApiResponse;
31 import io.swagger.v3.oas.annotations.responses.ApiResponses;
32 import io.swagger.v3.oas.annotations.tags.Tag;
33
34 import java.lang.invoke.MethodHandles;
35 import java.time.Instant;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.List;
39
40 import lombok.Getter;
41
42 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
43 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
44 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
45 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
46 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
48 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
49 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
50 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.http.MediaType;
59 import org.springframework.http.ResponseEntity;
60 import org.springframework.web.bind.annotation.DeleteMapping;
61 import org.springframework.web.bind.annotation.GetMapping;
62 import org.springframework.web.bind.annotation.PathVariable;
63 import org.springframework.web.bind.annotation.PutMapping;
64 import org.springframework.web.bind.annotation.RequestBody;
65 import org.springframework.web.bind.annotation.RequestParam;
66 import org.springframework.web.bind.annotation.RestController;
67 import org.springframework.web.reactive.function.client.WebClientResponseException;
68 import reactor.core.publisher.Mono;
69
70 @RestController("PolicyControllerV2")
71 @Tag(name = PolicyController.API_NAME)
72 public class PolicyController {
73
74     public static final String API_NAME = "A1 Policy Management";
75     public static final String API_DESCRIPTION = "";
76
77     public static class RejectionException extends Exception {
78         private static final long serialVersionUID = 1L;
79
80         @Getter
81         private final HttpStatus status;
82
83         public RejectionException(String message, HttpStatus status) {
84             super(message);
85             this.status = status;
86         }
87     }
88
89     @Autowired
90     private Rics rics;
91     @Autowired
92     private PolicyTypes policyTypes;
93     @Autowired
94     private Policies policies;
95     @Autowired
96     private A1ClientFactory a1ClientFactory;
97     @Autowired
98     private Services services;
99
100     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
101     private static Gson gson = new GsonBuilder() //
102             .create(); //
103
104     @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policytype_id:.+}") //
105     @Operation(summary = "Returns a policy type definition") //
106     @ApiResponses(value = { //
107             @ApiResponse(responseCode = "200", //
108                     description = "Policy type", //
109                     content = @Content(schema = @Schema(implementation = PolicyTypeInfo.class))), //
110             @ApiResponse(responseCode = "404", //
111                     description = "Policy type is not found", //
112                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
113     })
114     public ResponseEntity<Object> getPolicyType( //
115             @PathVariable("policytype_id") String policyTypeId) throws EntityNotFoundException {
116         PolicyType type = policyTypes.getType(policyTypeId);
117         PolicyTypeInfo info = new PolicyTypeInfo(type.getSchema());
118         return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
119     }
120
121     @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
122     @Operation(summary = "Query policy type identities")
123     @ApiResponses(value = { //
124             @ApiResponse(responseCode = "200", //
125                     description = "Policy type IDs", //
126                     content = @Content(schema = @Schema(implementation = PolicyTypeIdList.class))), //
127             @ApiResponse(responseCode = "404", //
128                     description = "Near-RT RIC is not found", //
129                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
130     })
131     public ResponseEntity<Object> getPolicyTypes( //
132             @Parameter(name = Consts.RIC_ID_PARAM, required = false,
133                     description = "The identity of the Near-RT RIC to get types for.") //
134             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId) throws EntityNotFoundException {
135         if (ricId == null) {
136             Collection<PolicyType> types = this.policyTypes.getAll();
137             return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
138         } else {
139             Collection<PolicyType> types = rics.getRic(ricId).getSupportedPolicyTypes();
140             return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
141         }
142     }
143
144     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
145     @Operation(summary = "Returns a policy") //
146     @ApiResponses(value = { //
147             @ApiResponse(responseCode = "200", //
148                     description = "Policy found", //
149                     content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
150             @ApiResponse(responseCode = "404", //
151                     description = "Policy is not found", //
152                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
153     })
154     public ResponseEntity<Object> getPolicy( //
155             @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
156         Policy p = policies.getPolicy(id);
157         return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
158     }
159
160     @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
161     @Operation(summary = "Delete a policy")
162     @ApiResponses(value = { //
163             @ApiResponse(responseCode = "200", //
164                     description = "Not used", //
165                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
166             @ApiResponse(responseCode = "204", //
167                     description = "Policy deleted", //
168                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
169             @ApiResponse(responseCode = "404", //
170                     description = "Policy is not found", //
171                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
172             @ApiResponse(responseCode = "423", //
173                     description = "Near-RT RIC is not operational", //
174                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
175     })
176     public Mono<ResponseEntity<Object>> deletePolicy( //
177             @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
178         Policy policy = policies.getPolicy(policyId);
179         keepServiceAlive(policy.getOwnerServiceId());
180         Ric ric = policy.getRic();
181
182         return ric.getLock().lock(LockType.SHARED) //
183                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
184                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
185                 .doOnNext(notUsed -> policies.remove(policy)) //
186                 .flatMap(client -> client.deletePolicy(policy)) //
187                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
188                 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
189                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
190                 .onErrorResume(this::handleException);
191     }
192
193     @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
194     @Operation(summary = "Create or update a policy")
195     @ApiResponses(value = { //
196             @ApiResponse(responseCode = "201", //
197                     description = "Policy created", //
198                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
199             @ApiResponse(responseCode = "200", //
200                     description = "Policy updated", //
201                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
202             @ApiResponse(responseCode = "423", //
203                     description = "Near-RT RIC is not operational", //
204                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
205             @ApiResponse(responseCode = "404", //
206                     description = "Near-RT RIC or policy type is not found", //
207                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
208     })
209     public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
210
211         if (!policyInfo.validate()) {
212             return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
213         }
214         String jsonString = gson.toJson(policyInfo.policyData);
215         Ric ric = rics.get(policyInfo.ricId);
216         PolicyType type = policyTypes.get(policyInfo.policyTypeId);
217         keepServiceAlive(policyInfo.serviceId);
218         if (ric == null || type == null) {
219             throw new EntityNotFoundException("Near-RT RIC or policy type not found");
220         }
221         Policy policy = Policy.builder() //
222                 .id(policyInfo.policyId) //
223                 .json(jsonString) //
224                 .type(type) //
225                 .ric(ric) //
226                 .ownerServiceId(policyInfo.serviceId) //
227                 .lastModified(Instant.now()) //
228                 .isTransient(policyInfo.isTransient) //
229                 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
230                 .build();
231
232         final boolean isCreate = this.policies.get(policy.getId()) == null;
233
234         return ric.getLock().lock(LockType.SHARED) //
235                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
236                 .flatMap(notUsed -> checkSupportedType(ric, type)) //
237                 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
238                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
239                 .flatMap(client -> client.putPolicy(policy)) //
240                 .doOnNext(notUsed -> policies.put(policy)) //
241                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
242                 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
243                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
244                 .onErrorResume(this::handleException);
245     }
246
247     private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
248         if (throwable instanceof WebClientResponseException) {
249             WebClientResponseException e = (WebClientResponseException) throwable;
250             return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
251         } else if (throwable instanceof RejectionException) {
252             RejectionException e = (RejectionException) throwable;
253             return ErrorResponse.createMono(e.getMessage(), e.getStatus());
254         } else {
255             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
256         }
257     }
258
259     private Mono<Object> validateModifiedPolicy(Policy policy) {
260         // Check that ric is not updated
261         Policy current = this.policies.get(policy.getId());
262         if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
263             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
264                     ", RIC ID: " + current.getRic().id() + //
265                     ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
266             logger.debug("Request rejected, {}", e.getMessage());
267             return Mono.error(e);
268         }
269         return Mono.just("{}");
270     }
271
272     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
273         if (!ric.isSupportingType(type.getId())) {
274             logger.debug("Request rejected, type not supported, RIC: {}", ric);
275             RejectionException e = new RejectionException(
276                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
277             return Mono.error(e);
278         }
279         return Mono.just("{}");
280     }
281
282     private Mono<Object> assertRicStateIdle(Ric ric) {
283         if (ric.getState() == Ric.RicState.AVAILABLE) {
284             return Mono.just("{}");
285         } else {
286             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
287             RejectionException e = new RejectionException(
288                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
289                     HttpStatus.LOCKED);
290             return Mono.error(e);
291         }
292     }
293
294     static final String GET_POLICIES_QUERY_DETAILS =
295             "Returns a list of A1 policies matching given search criteria. <br>" //
296                     + "If several query parameters are defined, the policies matching all conditions are returned.";
297
298     @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
299     @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
300     @ApiResponses(value = { //
301             @ApiResponse(responseCode = "200", //
302                     description = "Policies", //
303                     content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
304             @ApiResponse(responseCode = "404", //
305                     description = "Near-RT RIC, policy type or service not found", //
306                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
307     })
308     public ResponseEntity<Object> getPolicyInstances( //
309             @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
310                     description = "The identity of the policy type to get policies for.") //
311             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String type, //
312             @Parameter(name = Consts.RIC_ID_PARAM, required = false,
313                     description = "The identity of the Near-RT RIC to get policies for.") //
314             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
315             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
316                     description = "The identity of the service to get policies for.") //
317             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service)
318             throws EntityNotFoundException //
319     {
320         if ((type != null && this.policyTypes.get(type) == null)) {
321             throw new EntityNotFoundException("Policy type not found");
322         }
323         if ((ric != null && this.rics.get(ric) == null)) {
324             throw new EntityNotFoundException("Near-RT RIC not found");
325         }
326
327         String filteredPolicies = policiesToJson(filter(type, ric, service));
328         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
329     }
330
331     @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
332     @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
333     @ApiResponses(value = { //
334             @ApiResponse(responseCode = "200", //
335                     description = "Policy identities", //
336                     content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
337             @ApiResponse(responseCode = "404", //
338                     description = "Near-RT RIC or type not found", //
339                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
340     })
341     public ResponseEntity<Object> getPolicyIds( //
342             @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
343                     description = "The identity of the policy type to get policies for.") //
344             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
345             @Parameter(name = Consts.RIC_ID_PARAM, required = false,
346                     description = "The identity of the Near-RT RIC to get policies for.") //
347             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
348             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
349                     description = "The identity of the service to get policies for.") //
350             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId)
351             throws EntityNotFoundException //
352     {
353         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
354             throw new EntityNotFoundException("Policy type not found");
355         }
356         if ((ricId != null && this.rics.get(ricId) == null)) {
357             throw new EntityNotFoundException("Near-RT RIC not found");
358         }
359
360         String policyIdsJson = toPolicyIdsJson(filter(policyTypeId, ricId, serviceId));
361         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
362     }
363
364     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
365     @Operation(summary = "Returns a policy status") //
366     @ApiResponses(value = { //
367             @ApiResponse(responseCode = "200", //
368                     description = "Policy status", //
369                     content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
370             @ApiResponse(responseCode = "404", //
371                     description = "Policy is not found", //
372                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
373     })
374     public Mono<ResponseEntity<Object>> getPolicyStatus( //
375             @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
376         Policy policy = policies.getPolicy(policyId);
377
378         return a1ClientFactory.createA1Client(policy.getRic()) //
379                 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
380                 .flatMap(status -> createPolicyStatus(policy, status)) //
381                 .onErrorResume(this::handleException);
382
383     }
384
385     private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
386         PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
387         String str = gson.toJson(info);
388         return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
389     }
390
391     private void keepServiceAlive(String name) {
392         Service s = this.services.get(name);
393         if (s != null) {
394             s.keepAlive();
395         }
396     }
397
398     private boolean include(String filter, String value) {
399         return filter == null || value.equals(filter);
400     }
401
402     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
403         if (type == null && ric == null && service == null) {
404             return collection;
405         }
406         List<Policy> filtered = new ArrayList<>();
407         for (Policy p : collection) {
408             if (include(type, p.getType().getId()) && include(ric, p.getRic().id())
409                     && include(service, p.getOwnerServiceId())) {
410                 filtered.add(p);
411             }
412         }
413         return filtered;
414     }
415
416     private Collection<Policy> filter(String type, String ric, String service) {
417         if (type != null) {
418             return filter(policies.getForType(type), null, ric, service);
419         } else if (service != null) {
420             return filter(policies.getForService(service), type, ric, null);
421         } else if (ric != null) {
422             return filter(policies.getForRic(ric), type, null, service);
423         } else {
424             return policies.getAll();
425         }
426     }
427
428     private PolicyInfo toPolicyInfo(Policy p) {
429         PolicyInfo policyInfo = new PolicyInfo();
430         policyInfo.policyId = p.getId();
431         policyInfo.policyData = fromJson(p.getJson());
432         policyInfo.ricId = p.getRic().id();
433         policyInfo.policyTypeId = p.getType().getId();
434         policyInfo.serviceId = p.getOwnerServiceId();
435         policyInfo.isTransient = p.isTransient();
436         if (!p.getStatusNotificationUri().isEmpty()) {
437             policyInfo.statusNotificationUri = p.getStatusNotificationUri();
438         }
439         if (!policyInfo.validate()) {
440             logger.error("BUG, all mandatory fields must be set");
441         }
442
443         return policyInfo;
444     }
445
446     private String policiesToJson(Collection<Policy> policies) {
447         List<PolicyInfo> v = new ArrayList<>(policies.size());
448         for (Policy p : policies) {
449             v.add(toPolicyInfo(p));
450         }
451         PolicyInfoList list = new PolicyInfoList(v);
452         return gson.toJson(list);
453     }
454
455     private Object fromJson(String jsonStr) {
456         return gson.fromJson(jsonStr, Object.class);
457     }
458
459     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
460         List<String> v = new ArrayList<>(types.size());
461         for (PolicyType t : types) {
462             v.add(t.getId());
463         }
464         PolicyTypeIdList ids = new PolicyTypeIdList(v);
465         return gson.toJson(ids);
466     }
467
468     private String toPolicyIdsJson(Collection<Policy> policies) {
469         List<String> v = new ArrayList<>(policies.size());
470         for (Policy p : policies) {
471             v.add(p.getId());
472         }
473         return gson.toJson(new PolicyIdList(v));
474     }
475
476 }