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