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