5f2f619352a5ba7597811b0be3ef38ae147cd435
[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.exceptions.ServiceException;
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.getSchema());
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 = "Select types for the given Near-RT RIC identity.") //
135             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
136
137             @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
138                     description = "Select types with the given type name (type identity has the format <typename_version>)") //
139             @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
140
141             @Parameter(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false, //
142                     description = "Select types that are compatible with the given version. This parameter is only applicable in conjunction with "
143                             + Consts.TYPE_NAME_PARAM
144                             + ". As an example version 1.9.1 is compatible with 1.0.0 but not the other way around."
145                             + " Matching types will be returned sorted in ascending order.") //
146             @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
147
148     ) throws ServiceException {
149
150         if (compatibleWithVersion != null && typeName == null) {
151             throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
152                     + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
153         }
154
155         Collection<PolicyType> types =
156                 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
157
158         types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
159         return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
160     }
161
162     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
163     @Operation(summary = "Returns a policy") //
164     @ApiResponses(value = { //
165             @ApiResponse(responseCode = "200", //
166                     description = "Policy found", //
167                     content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
168             @ApiResponse(responseCode = "404", //
169                     description = "Policy is not found", //
170                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
171     })
172     public ResponseEntity<Object> getPolicy( //
173             @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
174         Policy p = policies.getPolicy(id);
175         return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
176     }
177
178     @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
179     @Operation(summary = "Delete a policy")
180     @ApiResponses(value = { //
181             @ApiResponse(responseCode = "200", //
182                     description = "Not used", //
183                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
184             @ApiResponse(responseCode = "204", //
185                     description = "Policy deleted", //
186                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
187             @ApiResponse(responseCode = "404", //
188                     description = "Policy is not found", //
189                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
190             @ApiResponse(responseCode = "423", //
191                     description = "Near-RT RIC is not operational", //
192                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
193     })
194     public Mono<ResponseEntity<Object>> deletePolicy( //
195             @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
196         Policy policy = policies.getPolicy(policyId);
197         keepServiceAlive(policy.getOwnerServiceId());
198         Ric ric = policy.getRic();
199
200         return ric.getLock().lock(LockType.SHARED) //
201                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
202                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
203                 .doOnNext(notUsed -> policies.remove(policy)) //
204                 .flatMap(client -> client.deletePolicy(policy)) //
205                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
206                 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
207                 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
208                 .onErrorResume(this::handleException);
209     }
210
211     @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
212     @Operation(summary = "Create or update a policy")
213     @ApiResponses(value = { //
214             @ApiResponse(responseCode = "201", //
215                     description = "Policy created", //
216                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
217             @ApiResponse(responseCode = "200", //
218                     description = "Policy updated", //
219                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
220             @ApiResponse(responseCode = "423", //
221                     description = "Near-RT RIC is not operational", //
222                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
223             @ApiResponse(responseCode = "404", //
224                     description = "Near-RT RIC or policy type is not found", //
225                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
226     })
227     public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
228
229         if (!policyInfo.validate()) {
230             return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
231         }
232         String jsonString = gson.toJson(policyInfo.policyData);
233         Ric ric = rics.get(policyInfo.ricId);
234         PolicyType type = policyTypes.get(policyInfo.policyTypeId);
235         keepServiceAlive(policyInfo.serviceId);
236         if (ric == null || type == null) {
237             throw new EntityNotFoundException("Near-RT RIC or policy type not found");
238         }
239         Policy policy = Policy.builder() //
240                 .id(policyInfo.policyId) //
241                 .json(jsonString) //
242                 .type(type) //
243                 .ric(ric) //
244                 .ownerServiceId(policyInfo.serviceId) //
245                 .lastModified(Instant.now()) //
246                 .isTransient(policyInfo.isTransient) //
247                 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
248                 .build();
249
250         final boolean isCreate = this.policies.get(policy.getId()) == null;
251
252         return ric.getLock().lock(LockType.SHARED) //
253                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
254                 .flatMap(notUsed -> checkSupportedType(ric, type)) //
255                 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
256                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
257                 .flatMap(client -> client.putPolicy(policy)) //
258                 .doOnNext(notUsed -> policies.put(policy)) //
259                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
260                 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
261                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
262                 .onErrorResume(this::handleException);
263     }
264
265     private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
266         if (throwable instanceof WebClientResponseException) {
267             WebClientResponseException e = (WebClientResponseException) throwable;
268             return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
269         } else if (throwable instanceof RejectionException) {
270             RejectionException e = (RejectionException) throwable;
271             return ErrorResponse.createMono(e.getMessage(), e.getStatus());
272         } else {
273             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
274         }
275     }
276
277     private Mono<Object> validateModifiedPolicy(Policy policy) {
278         // Check that ric is not updated
279         Policy current = this.policies.get(policy.getId());
280         if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
281             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
282                     ", RIC ID: " + current.getRic().id() + //
283                     ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
284             logger.debug("Request rejected, {}", e.getMessage());
285             return Mono.error(e);
286         }
287         return Mono.just("{}");
288     }
289
290     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
291         if (!ric.isSupportingType(type.getId())) {
292             logger.debug("Request rejected, type not supported, RIC: {}", ric);
293             RejectionException e = new RejectionException(
294                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
295             return Mono.error(e);
296         }
297         return Mono.just("{}");
298     }
299
300     private Mono<Object> assertRicStateIdle(Ric ric) {
301         if (ric.getState() == Ric.RicState.AVAILABLE) {
302             return Mono.just("{}");
303         } else {
304             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
305             RejectionException e = new RejectionException(
306                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
307                     HttpStatus.LOCKED);
308             return Mono.error(e);
309         }
310     }
311
312     static final String GET_POLICIES_QUERY_DETAILS =
313             "Returns a list of A1 policies matching given search criteria. <br>" //
314                     + "If several query parameters are defined, the policies matching all conditions are returned.";
315
316     @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
317     @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
318     @ApiResponses(value = { //
319             @ApiResponse(responseCode = "200", //
320                     description = "Policies", //
321                     content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
322             @ApiResponse(responseCode = "404", //
323                     description = "Near-RT RIC, policy type or service not found", //
324                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
325     })
326     public ResponseEntity<Object> getPolicyInstances( //
327             @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
328                     description = "Select policies with a given type identity.") //
329             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
330             @Parameter(name = Consts.RIC_ID_PARAM, required = false,
331                     description = "Select policies for a given Near-RT RIC identity.") //
332             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
333             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
334                     description = "Select policies owned by a given service.") //
335             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
336             @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
337                     description = "Select policies of a given type name (type identity has the format <typename_version>)") //
338             @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
339             throws EntityNotFoundException //
340     {
341         if ((typeId != null && this.policyTypes.get(typeId) == null)) {
342             throw new EntityNotFoundException("Policy type identity not found");
343         }
344         if ((ric != null && this.rics.get(ric) == null)) {
345             throw new EntityNotFoundException("Near-RT RIC not found");
346         }
347
348         String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
349         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
350     }
351
352     @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
353     @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
354     @ApiResponses(value = { //
355             @ApiResponse(responseCode = "200", //
356                     description = "Policy identities", //
357                     content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
358             @ApiResponse(responseCode = "404", //
359                     description = "Near-RT RIC or type not found", //
360                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
361     })
362     public ResponseEntity<Object> getPolicyIds( //
363             @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
364                     description = "Select policies of a given policy type identity.") //
365             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
366             @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
367                     description = "Select policies of a given Near-RT RIC identity.") //
368             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
369             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
370                     description = "Select policies owned by a given service.") //
371             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
372             @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
373                     description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
374             @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
375             throws EntityNotFoundException //
376     {
377         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
378             throw new EntityNotFoundException("Policy type not found");
379         }
380         if ((ricId != null && this.rics.get(ricId) == null)) {
381             throw new EntityNotFoundException("Near-RT RIC not found");
382         }
383
384         String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
385         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
386     }
387
388     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
389     @Operation(summary = "Returns a policy status") //
390     @ApiResponses(value = { //
391             @ApiResponse(responseCode = "200", //
392                     description = "Policy status", //
393                     content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
394             @ApiResponse(responseCode = "404", //
395                     description = "Policy is not found", //
396                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
397     })
398     public Mono<ResponseEntity<Object>> getPolicyStatus( //
399             @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
400         Policy policy = policies.getPolicy(policyId);
401
402         return a1ClientFactory.createA1Client(policy.getRic()) //
403                 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
404                 .flatMap(status -> createPolicyStatus(policy, status)) //
405                 .onErrorResume(this::handleException);
406
407     }
408
409     private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
410         PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
411         String str = gson.toJson(info);
412         return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
413     }
414
415     private void keepServiceAlive(String name) {
416         Service s = this.services.get(name);
417         if (s != null) {
418             s.keepAlive();
419         }
420     }
421
422     private PolicyInfo toPolicyInfo(Policy p) {
423         PolicyInfo policyInfo = new PolicyInfo();
424         policyInfo.policyId = p.getId();
425         policyInfo.policyData = fromJson(p.getJson());
426         policyInfo.ricId = p.getRic().id();
427         policyInfo.policyTypeId = p.getType().getId();
428         policyInfo.serviceId = p.getOwnerServiceId();
429         policyInfo.isTransient = p.isTransient();
430         if (!p.getStatusNotificationUri().isEmpty()) {
431             policyInfo.statusNotificationUri = p.getStatusNotificationUri();
432         }
433         if (!policyInfo.validate()) {
434             logger.error("BUG, all mandatory fields must be set");
435         }
436
437         return policyInfo;
438     }
439
440     private String policiesToJson(Collection<Policy> policies) {
441         List<PolicyInfo> v = new ArrayList<>(policies.size());
442         for (Policy p : policies) {
443             v.add(toPolicyInfo(p));
444         }
445         PolicyInfoList list = new PolicyInfoList(v);
446         return gson.toJson(list);
447     }
448
449     private Object fromJson(String jsonStr) {
450         return gson.fromJson(jsonStr, Object.class);
451     }
452
453     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
454         List<String> v = new ArrayList<>(types.size());
455         for (PolicyType t : types) {
456             v.add(t.getId());
457         }
458         PolicyTypeIdList ids = new PolicyTypeIdList(v);
459         return gson.toJson(ids);
460     }
461
462     private String toPolicyIdsJson(Collection<Policy> policies) {
463         List<String> v = new ArrayList<>(policies.size());
464         for (Policy p : policies) {
465             v.add(p.getId());
466         }
467         return gson.toJson(new PolicyIdList(v));
468     }
469
470 }