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.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import io.swagger.annotations.ApiParam;
29 import io.swagger.annotations.ApiResponse;
30 import io.swagger.annotations.ApiResponses;
32 import java.lang.invoke.MethodHandles;
33 import java.time.Instant;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.List;
40 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
41 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
42 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
43 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
44 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
45 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
46 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
48 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
49 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
50 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.http.HttpStatus;
57 import org.springframework.http.MediaType;
58 import org.springframework.http.ResponseEntity;
59 import org.springframework.web.bind.annotation.DeleteMapping;
60 import org.springframework.web.bind.annotation.GetMapping;
61 import org.springframework.web.bind.annotation.PutMapping;
62 import org.springframework.web.bind.annotation.RequestBody;
63 import org.springframework.web.bind.annotation.RequestParam;
64 import org.springframework.web.bind.annotation.RestController;
65 import org.springframework.web.reactive.function.client.WebClientResponseException;
66 import reactor.core.publisher.Mono;
68 @RestController("PolicyControllerV2")
69 @Api(tags = {Consts.V2_API_NAME})
70 public class PolicyController {
72 public static class RejectionException extends Exception {
73 private static final long serialVersionUID = 1L;
76 private final HttpStatus status;
78 public RejectionException(String message, HttpStatus status) {
87 private PolicyTypes policyTypes;
89 private Policies policies;
91 private A1ClientFactory a1ClientFactory;
93 private Services services;
95 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
96 private static Gson gson = new GsonBuilder() //
100 @GetMapping(path = Consts.V2_API_ROOT + "/policy-schemas", produces = MediaType.APPLICATION_JSON_VALUE)
101 @ApiOperation(value = "Returns policy type schema definitions")
102 @ApiResponses(value = { //
103 @ApiResponse(code = 200, message = "Policy schemas", response = PolicySchemaList.class), //
104 @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = ErrorResponse.ErrorInfo.class)})
105 public ResponseEntity<Object> getPolicySchemas( //
106 @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
107 value = "The identity of the Near-RT RIC to get the definitions for.") //
108 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
109 @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = true,
110 value = "The identity of the policy type to get the definition for. When this parameter is given, max one schema will be returned") //
111 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId) {
113 Ric ric = ricId == null ? null : rics.getRic(ricId);
114 if (ric == null && policyTypeId == null) {
115 Collection<PolicyType> types = this.policyTypes.getAll();
116 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
117 } else if (ric != null && policyTypeId != null) {
119 assertRicStateIdleSync(ric);
120 Collection<PolicyType> types = new ArrayList<>();
121 if (rics.getRic(ricId).isSupportingType(policyTypeId)) {
122 types.add(policyTypes.getType(policyTypeId));
124 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
126 } else if (ric != null) {
128 assertRicStateIdleSync(ric);
129 Collection<PolicyType> types = rics.getRic(ricId).getSupportedPolicyTypes();
130 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
133 Collection<PolicyType> types = new ArrayList<>();
134 types.add(policyTypes.getType(policyTypeId));
135 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
137 } catch (ServiceException e) {
138 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
142 @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
143 @ApiOperation(value = "Query policy type identities", produces = MediaType.APPLICATION_JSON_VALUE)
144 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy type IDs", response = PolicyTypeIdList.class),
145 @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = ErrorResponse.ErrorInfo.class)})
146 public ResponseEntity<Object> getPolicyTypes( //
147 @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
148 value = "The identity of the Near-RT RIC to get types for.") //
149 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId) {
151 Collection<PolicyType> types = this.policyTypes.getAll();
152 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
155 Collection<PolicyType> types = rics.getRic(ricId).getSupportedPolicyTypes();
156 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
157 } catch (ServiceException e) {
158 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
163 @GetMapping(path = Consts.V2_API_ROOT + "/policy", produces = MediaType.APPLICATION_JSON_VALUE)
164 @ApiOperation(value = "Returns a policy configuration") //
165 @ApiResponses(value = { //
166 @ApiResponse(code = 200, message = "Policy found", response = JsonObject.class), //
167 @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class)} //
169 public ResponseEntity<Object> getPolicy( //
170 @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy instance.") //
171 @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String id) {
173 Policy p = policies.getPolicy(id);
174 return new ResponseEntity<>(p.json(), HttpStatus.OK);
175 } catch (ServiceException e) {
176 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
180 @DeleteMapping(Consts.V2_API_ROOT + "/policy")
181 @ApiOperation(value = "Delete a policy")
182 @ApiResponses(value = { //
183 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
184 @ApiResponse(code = 204, message = "Policy deleted", response = VoidResponse.class),
185 @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class),
186 @ApiResponse(code = 423, message = "Near-RT RIC is not operational",
187 response = ErrorResponse.ErrorInfo.class)})
188 public Mono<ResponseEntity<Object>> deletePolicy( //
189 @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy instance.") //
190 @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String id) {
192 Policy policy = policies.getPolicy(id);
193 keepServiceAlive(policy.ownerServiceId());
194 Ric ric = policy.ric();
195 return ric.getLock().lock(LockType.SHARED) //
196 .flatMap(notUsed -> assertRicStateIdle(ric)) //
197 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
198 .doOnNext(notUsed -> policies.remove(policy)) //
199 .flatMap(client -> client.deletePolicy(policy)) //
200 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
201 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
202 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
203 .onErrorResume(this::handleException);
204 } catch (ServiceException e) {
205 return ErrorResponse.createMono(e, HttpStatus.NOT_FOUND);
209 @PutMapping(path = Consts.V2_API_ROOT + "/policy", produces = MediaType.APPLICATION_JSON_VALUE)
210 @ApiOperation(value = "Create or update a policy")
211 @ApiResponses(value = { //
212 @ApiResponse(code = 201, message = "Policy created", response = VoidResponse.class), //
213 @ApiResponse(code = 200, message = "Policy updated", response = VoidResponse.class), //
214 @ApiResponse(code = 423, message = "Near-RT RIC is not operational",
215 response = ErrorResponse.ErrorInfo.class), //
216 @ApiResponse(code = 404, message = "Near-RT RIC or policy type is not found",
217 response = ErrorResponse.ErrorInfo.class) //
219 public Mono<ResponseEntity<Object>> putPolicy( //
220 @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false, value = "The identity of the policy type.") //
221 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false, defaultValue = "") String policyTypeId, //
222 @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy instance.") //
223 @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String instanceId, //
224 @ApiParam(name = Consts.RIC_ID_PARAM, required = true,
225 value = "The identity of the Near-RT RIC where the policy will be " + //
227 @RequestParam(name = Consts.RIC_ID_PARAM, required = true) String ricId, //
228 @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true,
229 value = "The identity of the service creating the policy.") //
230 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceId, //
231 @ApiParam(name = Consts.TRANSIENT_PARAM, required = false,
232 value = "If the policy is transient or not (boolean " + //
233 "defaulted to false). A policy is transient if it will not be recreated in the Near-RT RIC "
235 "when it has been lost (for instance due to a restart)") //
236 @RequestParam(name = Consts.TRANSIENT_PARAM, required = false, defaultValue = "false") boolean isTransient, //
237 @RequestBody Object jsonBody) {
239 String jsonString = gson.toJson(jsonBody);
240 Ric ric = rics.get(ricId);
241 PolicyType type = policyTypes.get(policyTypeId);
242 keepServiceAlive(serviceId);
243 if (ric == null || type == null) {
244 return ErrorResponse.createMono("Near-RT RIC or policy type not found", HttpStatus.NOT_FOUND);
246 Policy policy = ImmutablePolicy.builder() //
251 .ownerServiceId(serviceId) //
252 .lastModified(Instant.now()) //
253 .isTransient(isTransient) //
256 final boolean isCreate = this.policies.get(policy.id()) == null;
258 return ric.getLock().lock(LockType.SHARED) //
259 .flatMap(notUsed -> assertRicStateIdle(ric)) //
260 .flatMap(notUsed -> checkSupportedType(ric, type)) //
261 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
262 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
263 .flatMap(client -> client.putPolicy(policy)) //
264 .doOnNext(notUsed -> policies.put(policy)) //
265 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
266 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
267 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
268 .onErrorResume(this::handleException);
271 private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
272 if (throwable instanceof WebClientResponseException) {
273 WebClientResponseException e = (WebClientResponseException) throwable;
274 return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
275 } else if (throwable instanceof RejectionException) {
276 RejectionException e = (RejectionException) throwable;
277 return ErrorResponse.createMono(e.getMessage(), e.getStatus());
279 return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
283 private Mono<Object> validateModifiedPolicy(Policy policy) {
284 // Check that ric is not updated
285 Policy current = this.policies.get(policy.id());
286 if (current != null && !current.ric().id().equals(policy.ric().id())) {
287 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
288 ", RIC ID: " + current.ric().id() + //
289 ", new ID: " + policy.ric().id(), HttpStatus.CONFLICT);
290 logger.debug("Request rejected, {}", e.getMessage());
291 return Mono.error(e);
293 return Mono.just("{}");
296 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
297 if (!ric.isSupportingType(type.id())) {
298 logger.debug("Request rejected, type not supported, RIC: {}", ric);
299 RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(),
300 HttpStatus.NOT_FOUND);
301 return Mono.error(e);
303 return Mono.just("{}");
306 private void assertRicStateIdleSync(Ric ric) throws ServiceException {
307 if (ric.getState() != Ric.RicState.AVAILABLE) {
308 throw new ServiceException("Near-RT RIC: " + ric.id() + " is " + ric.getState());
312 private Mono<Object> assertRicStateIdle(Ric ric) {
313 if (ric.getState() == Ric.RicState.AVAILABLE) {
314 return Mono.just("{}");
316 logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
317 RejectionException e = new RejectionException(
318 "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
320 return Mono.error(e);
324 static final String GET_POLICIES_QUERY_DETAILS =
325 "Returns a list of A1 policies matching given search criteria. <br>" //
326 + "If several query parameters are defined, the policies matching all conditions are returned.";
328 @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
329 @ApiOperation(value = "Query for existing A1 policies", notes = GET_POLICIES_QUERY_DETAILS)
330 @ApiResponses(value = { //
331 @ApiResponse(code = 200, message = "Policies", response = PolicyInfoList.class),
332 @ApiResponse(code = 404, message = "Near-RT RIC, policy type or service not found",
333 response = ErrorResponse.ErrorInfo.class)})
334 public ResponseEntity<Object> getPolicies( //
335 @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
336 value = "The identity of the policy type to get policies for.") //
337 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String type, //
338 @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
339 value = "The identity of the Near-RT RIC to get policies for.") //
340 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
341 @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false,
342 value = "The identity of the service to get policies for.") //
343 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service) //
345 if ((type != null && this.policyTypes.get(type) == null)) {
346 return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND);
348 if ((ric != null && this.rics.get(ric) == null)) {
349 return ErrorResponse.create("Near-RT RIC not found", HttpStatus.NOT_FOUND);
352 String filteredPolicies = policiesToJson(filter(type, ric, service));
353 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
356 @GetMapping(path = Consts.V2_API_ROOT + "/policy-ids", produces = MediaType.APPLICATION_JSON_VALUE)
357 @ApiOperation(value = "Query policies, only policy identities are returned", notes = GET_POLICIES_QUERY_DETAILS)
358 @ApiResponses(value = { //
359 @ApiResponse(code = 200, message = "Policy identities", response = PolicyIdList.class), @ApiResponse(
360 code = 404, message = "Near-RT RIC or type not found", response = ErrorResponse.ErrorInfo.class)})
361 public ResponseEntity<Object> getPolicyIds( //
362 @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
363 value = "The identity of the policy type to get policies for.") //
364 @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
365 @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
366 value = "The identity of the Near-RT RIC to get policies for.") //
367 @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
368 @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false,
369 value = "The identity of the service to get policies for.") //
370 @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId) //
372 if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
373 return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND);
375 if ((ricId != null && this.rics.get(ricId) == null)) {
376 return ErrorResponse.create("Near-RT RIC not found", HttpStatus.NOT_FOUND);
379 String policyIdsJson = toPolicyIdsJson(filter(policyTypeId, ricId, serviceId));
380 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
383 @GetMapping(path = Consts.V2_API_ROOT + "/policy-status", produces = MediaType.APPLICATION_JSON_VALUE)
384 @ApiOperation(value = "Returns a policy status") //
385 @ApiResponses(value = { //
386 @ApiResponse(code = 200, message = "Policy status", response = JsonObject.class), //
387 @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class)} //
389 public Mono<ResponseEntity<Object>> getPolicyStatus( //
390 @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy.") //
391 @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String policyId) {
393 Policy policy = policies.getPolicy(policyId);
395 return a1ClientFactory.createA1Client(policy.ric()) //
396 .flatMap(client -> client.getPolicyStatus(policy)) //
397 .flatMap(status -> Mono.just(new ResponseEntity<>((Object) status, HttpStatus.OK)))
398 .onErrorResume(this::handleException);
399 } catch (ServiceException e) {
400 return ErrorResponse.createMono(e, HttpStatus.NOT_FOUND);
404 private void keepServiceAlive(String name) {
405 Service s = this.services.get(name);
411 private boolean include(String filter, String value) {
412 return filter == null || value.equals(filter);
415 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
416 if (type == null && ric == null && service == null) {
419 List<Policy> filtered = new ArrayList<>();
420 for (Policy p : collection) {
421 if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) {
428 private Collection<Policy> filter(String type, String ric, String service) {
430 return filter(policies.getForType(type), null, ric, service);
431 } else if (service != null) {
432 return filter(policies.getForService(service), type, ric, null);
433 } else if (ric != null) {
434 return filter(policies.getForRic(ric), type, null, service);
436 return policies.getAll();
440 private String policiesToJson(Collection<Policy> policies) {
441 List<PolicyInfo> v = new ArrayList<>(policies.size());
442 for (Policy p : policies) {
443 PolicyInfo policyInfo = new PolicyInfo();
444 policyInfo.policyId = p.id();
445 policyInfo.policyData = fromJson(p.json());
446 policyInfo.ricId = p.ric().id();
447 policyInfo.policyTypeId = p.type().id();
448 policyInfo.serviceId = p.ownerServiceId();
449 policyInfo.lastModified = p.lastModified().toString();
450 if (!policyInfo.validate()) {
451 logger.error("BUG, all fields must be set");
455 PolicyInfoList list = new PolicyInfoList(v);
456 return gson.toJson(list);
459 private Object fromJson(String jsonStr) {
460 return gson.fromJson(jsonStr, Object.class);
463 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
465 Collection<String> schemas = new ArrayList<>();
466 for (PolicyType t : types) {
467 schemas.add(t.schema());
469 PolicySchemaList res = new PolicySchemaList(schemas);
470 return gson.toJson(res);
473 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
474 List<String> v = new ArrayList<>(types.size());
475 for (PolicyType t : types) {
478 PolicyTypeIdList ids = new PolicyTypeIdList(v);
479 return gson.toJson(ids);
482 private String toPolicyIdsJson(Collection<Policy> policies) {
483 List<String> v = new ArrayList<>(policies.size());
484 for (Policy p : policies) {
487 return gson.toJson(new PolicyIdList(v));