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.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;
71 @RestController("PolicyControllerV2")
72 @Tag(name = PolicyController.API_NAME)
73 public class PolicyController {
75 public static final String API_NAME = "A1 Policy Management";
76 public static final String API_DESCRIPTION = "";
78 public static class RejectionException extends Exception {
79 private static final long serialVersionUID = 1L;
82 private final HttpStatus status;
84 public RejectionException(String message, HttpStatus status) {
93 private PolicyTypes policyTypes;
95 private Policies policies;
97 private A1ClientFactory a1ClientFactory;
99 private Services services;
101 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
102 private static Gson gson = new GsonBuilder() //
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)))//
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);
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))) //
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,
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,
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 @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
147 ) throws ServiceException {
149 if (compatibleWithVersion != null && typeName == null) {
150 throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
151 + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
154 Collection<PolicyType> types =
155 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
157 types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
158 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
161 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
162 @Operation(summary = "Returns a policy") //
163 @ApiResponses(value = { //
164 @ApiResponse(responseCode = "200", //
165 description = "Policy found", //
166 content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
167 @ApiResponse(responseCode = "404", //
168 description = "Policy is not found", //
169 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
171 public ResponseEntity<Object> getPolicy( //
172 @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) throws EntityNotFoundException {
173 Policy p = policies.getPolicy(id);
174 return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
177 @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
178 @Operation(summary = "Delete a policy")
179 @ApiResponses(value = { //
180 @ApiResponse(responseCode = "200", //
181 description = "Not used", //
182 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
183 @ApiResponse(responseCode = "204", //
184 description = "Policy deleted", //
185 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
186 @ApiResponse(responseCode = "404", //
187 description = "Policy is not found", //
188 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
189 @ApiResponse(responseCode = "423", //
190 description = "Near-RT RIC is not operational", //
191 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
193 public Mono<ResponseEntity<Object>> deletePolicy( //
194 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
195 Policy policy = policies.getPolicy(policyId);
196 keepServiceAlive(policy.getOwnerServiceId());
197 Ric ric = policy.getRic();
199 return ric.getLock().lock(LockType.SHARED) //
200 .flatMap(notUsed -> assertRicStateIdle(ric)) //
201 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
202 .doOnNext(notUsed -> policies.remove(policy)) //
203 .flatMap(client -> client.deletePolicy(policy)) //
204 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
205 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
206 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
207 .onErrorResume(this::handleException);
210 @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
211 @Operation(summary = "Create or update a policy")
212 @ApiResponses(value = { //
213 @ApiResponse(responseCode = "201", //
214 description = "Policy created", //
215 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
216 @ApiResponse(responseCode = "200", //
217 description = "Policy updated", //
218 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
219 @ApiResponse(responseCode = "423", //
220 description = "Near-RT RIC is not operational", //
221 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
222 @ApiResponse(responseCode = "404", //
223 description = "Near-RT RIC or policy type is not found", //
224 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
226 public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) throws EntityNotFoundException {
228 if (!policyInfo.validate()) {
229 return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
231 String jsonString = gson.toJson(policyInfo.policyData);
232 Ric ric = rics.get(policyInfo.ricId);
233 PolicyType type = policyTypes.get(policyInfo.policyTypeId);
234 keepServiceAlive(policyInfo.serviceId);
235 if (ric == null || type == null) {
236 throw new EntityNotFoundException("Near-RT RIC or policy type not found");
238 Policy policy = Policy.builder() //
239 .id(policyInfo.policyId) //
243 .ownerServiceId(policyInfo.serviceId) //
244 .lastModified(Instant.now()) //
245 .isTransient(policyInfo.isTransient) //
246 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
249 final boolean isCreate = this.policies.get(policy.getId()) == null;
251 return ric.getLock().lock(LockType.SHARED) //
252 .flatMap(notUsed -> assertRicStateIdle(ric)) //
253 .flatMap(notUsed -> checkSupportedType(ric, type)) //
254 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
255 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
256 .flatMap(client -> client.putPolicy(policy)) //
257 .doOnNext(notUsed -> policies.put(policy)) //
258 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
259 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
260 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
261 .onErrorResume(this::handleException);
264 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
265 if (throwable instanceof WebClientResponseException) {
266 WebClientResponseException e = (WebClientResponseException) throwable;
267 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
268 } else if (throwable instanceof RejectionException) {
269 RejectionException e = (RejectionException) throwable;
270 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
272 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
276 private Mono<Object> validateModifiedPolicy(Policy policy) {
277 // Check that ric is not updated
278 Policy current = this.policies.get(policy.getId());
279 if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
280 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
281 ", RIC ID: " + current.getRic().id() + //
282 ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
283 logger.debug("Request rejected, {}", e.getMessage());
284 return Mono.error(e);
286 return Mono.just("{}");
289 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
290 if (!ric.isSupportingType(type.getId())) {
291 logger.debug("Request rejected, type not supported, RIC: {}", ric);
292 RejectionException e = new RejectionException(
293 "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
294 return Mono.error(e);
296 return Mono.just("{}");
299 private Mono<Object> assertRicStateIdle(Ric ric) {
300 if (ric.getState() == Ric.RicState.AVAILABLE) {
301 return Mono.just("{}");
303 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
304 RejectionException e = new RejectionException(
305 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
307 return Mono.error(e);
311 static final String GET_POLICIES_QUERY_DETAILS =
312 "Returns a list of A1 policies matching given search criteria. <br>" //
313 + "If several query parameters are defined, the policies matching all conditions are returned.";
315 @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
316 @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
317 @ApiResponses(value = { //
318 @ApiResponse(responseCode = "200", //
319 description = "Policies", //
320 content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
321 @ApiResponse(responseCode = "404", //
322 description = "Near-RT RIC, policy type or service not found", //
323 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
325 public ResponseEntity<Object> getPolicyInstances( //
326 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
327 description = "Select policies with a given type identity.") //
328 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
329 @Parameter(name = Consts.RIC_ID_PARAM, required = false,
330 description = "Select policies for a given Near-RT RIC identity.") //
331 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
332 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
333 description = "Select policies owned by a given service.") //
334 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
335 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
336 description = "Select policies of a given type name (type identity has the format <typename_version>)") //
337 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
338 throws EntityNotFoundException //
340 if ((typeId != null && this.policyTypes.get(typeId) == null)) {
341 throw new EntityNotFoundException("Policy type identity not found");
343 if ((ric != null && this.rics.get(ric) == null)) {
344 throw new EntityNotFoundException("Near-RT RIC not found");
347 String filteredPolicies = policiesToJson(policies.filterPolicies(typeId, ric, service, typeName));
348 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
351 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
352 @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
353 @ApiResponses(value = { //
354 @ApiResponse(responseCode = "200", //
355 description = "Policy identities", //
356 content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
357 @ApiResponse(responseCode = "404", //
358 description = "Near-RT RIC or type not found", //
359 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
361 public ResponseEntity<Object> getPolicyIds( //
362 @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
363 description = "Select policies of a given policy type identity.") //
364 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
365 @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
366 description = "Select policies of a given Near-RT RIC identity.") //
367 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
368 @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
369 description = "Select policies owned by a given service.") //
370 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
371 @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
372 description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
373 @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName)
374 throws EntityNotFoundException //
376 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
377 throw new EntityNotFoundException("Policy type not found");
379 if ((ricId != null && this.rics.get(ricId) == null)) {
380 throw new EntityNotFoundException("Near-RT RIC not found");
383 String policyIdsJson = toPolicyIdsJson(policies.filterPolicies(policyTypeId, ricId, serviceId, typeName));
384 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
387 @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
388 @Operation(summary = "Returns a policy status") //
389 @ApiResponses(value = { //
390 @ApiResponse(responseCode = "200", //
391 description = "Policy status", //
392 content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
393 @ApiResponse(responseCode = "404", //
394 description = "Policy is not found", //
395 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
397 public Mono<ResponseEntity<Object>> getPolicyStatus( //
398 @PathVariable(Consts.POLICY_ID_PARAM) String policyId) throws EntityNotFoundException {
399 Policy policy = policies.getPolicy(policyId);
401 return a1ClientFactory.createA1Client(policy.getRic()) //
402 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
403 .flatMap(status -> createPolicyStatus(policy, status)) //
404 .onErrorResume(this::handleException);
408 private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
409 PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
410 String str = gson.toJson(info);
411 return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
414 private void keepServiceAlive(String name) {
415 Service s = this.services.get(name);
421 private PolicyInfo toPolicyInfo(Policy p) {
422 PolicyInfo policyInfo = new PolicyInfo();
423 policyInfo.policyId = p.getId();
424 policyInfo.policyData = fromJson(p.getJson());
425 policyInfo.ricId = p.getRic().id();
426 policyInfo.policyTypeId = p.getType().getId();
427 policyInfo.serviceId = p.getOwnerServiceId();
428 policyInfo.isTransient = p.isTransient();
429 if (!p.getStatusNotificationUri().isEmpty()) {
430 policyInfo.statusNotificationUri = p.getStatusNotificationUri();
432 if (!policyInfo.validate()) {
433 logger.error("BUG, all mandatory fields must be set");
439 private String policiesToJson(Collection<Policy> policies) {
440 List<PolicyInfo> v = new ArrayList<>(policies.size());
441 for (Policy p : policies) {
442 v.add(toPolicyInfo(p));
444 PolicyInfoList list = new PolicyInfoList(v);
445 return gson.toJson(list);
448 private Object fromJson(String jsonStr) {
449 return gson.fromJson(jsonStr, Object.class);
452 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
453 List<String> v = new ArrayList<>(types.size());
454 for (PolicyType t : types) {
457 PolicyTypeIdList ids = new PolicyTypeIdList(v);
458 return gson.toJson(ids);
461 private String toPolicyIdsJson(Collection<Policy> policies) {
462 List<String> v = new ArrayList<>(policies.size());
463 for (Policy p : policies) {
466 return gson.toJson(new PolicyIdList(v));