2 * ========================LICENSE_START=================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
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;
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;
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;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
48 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
49 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
50 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.MediaType;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.web.bind.annotation.DeleteMapping;
63 import org.springframework.web.bind.annotation.GetMapping;
64 import org.springframework.web.bind.annotation.PathVariable;
65 import org.springframework.web.bind.annotation.PutMapping;
66 import org.springframework.web.bind.annotation.RequestBody;
67 import org.springframework.web.bind.annotation.RequestParam;
68 import org.springframework.web.bind.annotation.RestController;
69 import org.springframework.web.reactive.function.client.WebClientResponseException;
70 import reactor.core.publisher.Mono;
72 @RestController("PolicyControllerV2")
74 name = PolicyController.API_NAME, //
75 description = PolicyController.API_DESCRIPTION //
77 public class PolicyController {
79 public static final String API_NAME = "A1 Policy Management";
80 public static final String API_DESCRIPTION = "";
82 public static class RejectionException extends Exception {
83 private static final long serialVersionUID = 1L;
86 private final HttpStatus status;
88 public RejectionException(String message, HttpStatus status) {
97 private PolicyTypes policyTypes;
99 private Policies policies;
101 private A1ClientFactory a1ClientFactory;
103 private Services services;
105 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
106 private static Gson gson = new GsonBuilder() //
109 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policytype_id:.+}") //
110 @Operation(summary = "Returns a policy type definition") //
111 @ApiResponses(value = { //
112 @ApiResponse(responseCode = "200", //
113 description = "Policy type", //
114 content = @Content(schema = @Schema(implementation = PolicyTypeInfo.class))), //
115 @ApiResponse(responseCode = "404", //
116 description = "Policy type is not found", //
117 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
119 public ResponseEntity<Object> getPolicyType( //
120 @PathVariable("policytype_id") String policyTypeId) throws EntityNotFoundException {
121 PolicyType type = policyTypes.getType(policyTypeId);
122 PolicyTypeInfo info = new PolicyTypeInfo(type.getSchema());
123 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
126 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
127 @Operation(summary = "Query policy type identities")
128 @ApiResponses(value = { //
129 @ApiResponse(responseCode = "200", //
130 description = "Policy type IDs", //
131 content = @Content(schema = @Schema(implementation = PolicyTypeIdList.class))), //
132 @ApiResponse(responseCode = "404", //
133 description = "Near-RT RIC is not found", //
134 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
136 public ResponseEntity<Object> getPolicyTypes( //
137 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
138 description = "Select types for the given Near-RT RIC identity.") //
139 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
141 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
142 description = "Select types with the given type name (type identity has the format <typename_version>)") //
143 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
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 + " Matching types will be returned sorted in ascending order.") //
150 @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
152 ) throws ServiceException {
154 if (compatibleWithVersion != null && typeName == null) {
155 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
156 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
159 Collection<PolicyType> types =
160 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
162 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
163 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
166 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
167 @Operation(summary = "Returns a policy") //
168 @ApiResponses(value = { //
169 @ApiResponse(responseCode = "200", //
170 description = "Policy found", //
171 content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
172 @ApiResponse(responseCode = "404", //
173 description = "Policy is not found", //
174 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
176 public ResponseEntity<Object> getPolicy( //
177 @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
178 Policy p = policies.getPolicy(id);
179 return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
182 @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
183 @Operation(summary = "Delete a policy")
184 @ApiResponses(value = { //
185 @ApiResponse(responseCode = "200", //
186 description = "Not used", //
187 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
188 @ApiResponse(responseCode = "204", //
189 description = "Policy deleted", //
190 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
191 @ApiResponse(responseCode = "404", //
192 description = "Policy is not found", //
193 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
194 @ApiResponse(responseCode = "423", //
195 description = "Near-RT RIC is not operational", //
196 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
198 public Mono<ResponseEntity<Object>> deletePolicy( //
199 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
200 Policy policy = policies.getPolicy(policyId);
201 keepServiceAlive(policy.getOwnerServiceId());
203 return policy.getRic().getLock().lock(LockType.SHARED, "deletePolicy") //
204 .flatMap(grant -> deletePolicy(grant, policy));
207 Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
208 return assertRicStateIdle(policy.getRic()) //
209 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
210 .doOnNext(notUsed -> policies.remove(policy)) //
211 .doFinally(x -> grant.unlockBlocking()) //
212 .flatMap(client -> client.deletePolicy(policy)) //
213 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
214 .onErrorResume(this::handleException);
217 @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
218 @Operation(summary = "Create or update a policy")
219 @ApiResponses(value = { //
220 @ApiResponse(responseCode = "201", //
221 description = "Policy created", //
222 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
223 @ApiResponse(responseCode = "200", //
224 description = "Policy updated", //
225 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
226 @ApiResponse(responseCode = "423", //
227 description = "Near-RT RIC is not operational", //
228 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
229 @ApiResponse(responseCode = "404", //
230 description = "Near-RT RIC or policy type is not found", //
231 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
233 public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
235 if (!policyInfo.validate()) {
236 return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
238 String jsonString = gson.toJson(policyInfo.policyData);
239 Ric ric = rics.get(policyInfo.ricId);
240 PolicyType type = policyTypes.get(policyInfo.policyTypeId);
241 keepServiceAlive(policyInfo.serviceId);
242 if (ric == null || type == null) {
243 throw new EntityNotFoundException("Near-RT RIC or policy type not found");
245 Policy policy = Policy.builder() //
246 .id(policyInfo.policyId) //
250 .ownerServiceId(policyInfo.serviceId) //
251 .lastModified(Instant.now()) //
252 .isTransient(policyInfo.isTransient) //
253 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
256 return ric.getLock().lock(LockType.SHARED, "putPolicy") //
257 .flatMap(grant -> putPolicy(grant, policy));
260 private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
261 final boolean isCreate = this.policies.get(policy.getId()) == null;
262 final Ric ric = policy.getRic();
264 return assertRicStateIdle(ric) //
265 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
266 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
267 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
268 .flatMap(client -> client.putPolicy(policy)) //
269 .doOnNext(notUsed -> policies.put(policy)) //
270 .doFinally(x -> grant.unlockBlocking()) //
271 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
272 .onErrorResume(this::handleException);
276 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
277 if (throwable instanceof WebClientResponseException) {
278 WebClientResponseException e = (WebClientResponseException) throwable;
279 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
280 } else if (throwable instanceof RejectionException) {
281 RejectionException e = (RejectionException) throwable;
282 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
284 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
288 private Mono<Object> validateModifiedPolicy(Policy policy) {
289 // Check that ric is not updated
290 Policy current = this.policies.get(policy.getId());
291 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
292 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
293 ", RIC ID: " + current.getRic().id() + //
294 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
295 logger.debug("Request rejected, {}", e.getMessage());
296 return Mono.error(e);
298 return Mono.just("{}");
301 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
302 if (!ric.isSupportingType(type.getId())) {
303 logger.debug("Request rejected, type not supported, RIC: {}", ric);
304 RejectionException e = new RejectionException(
305 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
306 return Mono.error(e);
308 return Mono.just("{}");
311 private Mono<Object> assertRicStateIdle(Ric ric) {
312 if (ric.getState() == Ric.RicState.AVAILABLE) {
313 return Mono.just("{}");
315 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
316 RejectionException e = new RejectionException(
317 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
319 return Mono.error(e);
323 static final String GET_POLICIES_QUERY_DETAILS =
324 "Returns a list of A1 policies matching given search criteria. <br>" //
325 + "If several query parameters are defined, the policies matching all conditions are returned.";
327 @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
328 @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
329 @ApiResponses(value = { //
330 @ApiResponse(responseCode = "200", //
331 description = "Policies", //
332 content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
333 @ApiResponse(responseCode = "404", //
334 description = "Near-RT RIC, policy type or service not found", //
335 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
337 public ResponseEntity<Object> getPolicyInstances( //
338 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
339 description = "Select policies with a given type identity.") //
340 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
341 @Parameter(name = Consts.RIC_ID_PARAM, required = false,
342 description = "Select policies for a given Near-RT RIC identity.") //
343 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
344 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
345 description = "Select policies owned by a given service.") //
346 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
347 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
348 description = "Select policies of a given type name (type identity has the format <typename_version>)") //
349 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
350 throws EntityNotFoundException //
352 if ((typeId != null && this.policyTypes.get(typeId) == null)) {
353 throw new EntityNotFoundException("Policy type identity not found");
355 if ((ric != null && this.rics.get(ric) == null)) {
356 throw new EntityNotFoundException("Near-RT RIC not found");
359 String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
360 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
363 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
364 @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
365 @ApiResponses(value = { //
366 @ApiResponse(responseCode = "200", //
367 description = "Policy identities", //
368 content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
369 @ApiResponse(responseCode = "404", //
370 description = "Near-RT RIC or type not found", //
371 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
373 public ResponseEntity<Object> getPolicyIds( //
374 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
375 description = "Select policies of a given policy type identity.") //
376 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
377 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
378 description = "Select policies of a given Near-RT RIC identity.") //
379 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
380 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
381 description = "Select policies owned by a given service.") //
382 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
383 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
384 description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
385 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
386 throws EntityNotFoundException //
388 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
389 throw new EntityNotFoundException("Policy type not found");
391 if ((ricId != null && this.rics.get(ricId) == null)) {
392 throw new EntityNotFoundException("Near-RT RIC not found");
395 String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
396 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
399 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
400 @Operation(summary = "Returns a policy status") //
401 @ApiResponses(value = { //
402 @ApiResponse(responseCode = "200", //
403 description = "Policy status", //
404 content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
405 @ApiResponse(responseCode = "404", //
406 description = "Policy is not found", //
407 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
409 public Mono<ResponseEntity<Object>> getPolicyStatus( //
410 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
411 Policy policy = policies.getPolicy(policyId);
413 return a1ClientFactory.createA1Client(policy.getRic()) //
414 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
415 .flatMap(status -> createPolicyStatus(policy, status)) //
416 .onErrorResume(this::handleException);
420 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
421 PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
422 String str = gson.toJson(info);
423 return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
426 private void keepServiceAlive(String name) {
427 Service s = this.services.get(name);
433 private PolicyInfo toPolicyInfo(Policy p) {
434 PolicyInfo policyInfo = new PolicyInfo();
435 policyInfo.policyId = p.getId();
436 policyInfo.policyData = fromJson(p.getJson());
437 policyInfo.ricId = p.getRic().id();
438 policyInfo.policyTypeId = p.getType().getId();
439 policyInfo.serviceId = p.getOwnerServiceId();
440 policyInfo.isTransient = p.isTransient();
441 if (!p.getStatusNotificationUri().isEmpty()) {
442 policyInfo.statusNotificationUri = p.getStatusNotificationUri();
444 if (!policyInfo.validate()) {
445 logger.error("BUG, all mandatory fields must be set");
451 private String policiesToJson(Collection<Policy> policies) {
452 List<PolicyInfo> v = new ArrayList<>(policies.size());
453 for (Policy p : policies) {
454 v.add(toPolicyInfo(p));
456 PolicyInfoList list = new PolicyInfoList(v);
457 return gson.toJson(list);
460 private Object fromJson(String jsonStr) {
461 return gson.fromJson(jsonStr, Object.class);
464 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
465 List<String> v = new ArrayList<>(types.size());
466 for (PolicyType t : types) {
469 PolicyTypeIdList ids = new PolicyTypeIdList(v);
470 return gson.toJson(ids);
473 private String toPolicyIdsJson(Collection<Policy> policies) {
474 List<String> v = new ArrayList<>(policies.size());
475 for (Policy p : policies) {
478 return gson.toJson(new PolicyIdList(v));