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.v1;
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.ResponseEntity;
58 import org.springframework.web.bind.annotation.DeleteMapping;
59 import org.springframework.web.bind.annotation.GetMapping;
60 import org.springframework.web.bind.annotation.PutMapping;
61 import org.springframework.web.bind.annotation.RequestBody;
62 import org.springframework.web.bind.annotation.RequestParam;
63 import org.springframework.web.bind.annotation.RestController;
64 import org.springframework.web.reactive.function.client.WebClientResponseException;
65 import reactor.core.publisher.Mono;
68 @Api(tags = Consts.V1_API_NAME)
69 public class PolicyController {
71 public static class RejectionException extends Exception {
72 private static final long serialVersionUID = 1L;
74 private final HttpStatus status;
76 public RejectionException(String message, HttpStatus status) {
85 private PolicyTypes policyTypes;
87 private Policies policies;
89 private A1ClientFactory a1ClientFactory;
91 private Services services;
93 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
94 private static Gson gson = new GsonBuilder() //
98 @GetMapping("/policy_schemas")
99 @ApiOperation(value = "Returns policy type schema definitions")
100 @ApiResponses(value = {
101 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
102 @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = String.class)})
103 public ResponseEntity<String> getPolicySchemas( //
104 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get the definitions for.") //
105 @RequestParam(name = "ric", required = false) String ricName) {
106 if (ricName == null) {
107 Collection<PolicyType> types = this.policyTypes.getAll();
108 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
111 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
112 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
113 } catch (ServiceException e) {
114 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
119 @GetMapping("/policy_schema")
120 @ApiOperation(value = "Returns one policy type schema definition")
121 @ApiResponses(value = { //
122 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
123 @ApiResponse(code = 404, message = "The policy type is not found", response = String.class)})
124 public ResponseEntity<String> getPolicySchema( //
125 @ApiParam(name = "id", required = true,
126 value = "The identity of the policy type to get the definition for.") //
127 @RequestParam(name = "id", required = true) String id) {
129 PolicyType type = policyTypes.getType(id);
130 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
131 } catch (ServiceException e) {
132 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
136 @GetMapping("/policy_types")
137 @ApiOperation(value = "Query policy type names")
138 @ApiResponses(value = {
139 @ApiResponse(code = 200, message = "Policy type names", response = String.class,
140 responseContainer = "List"),
141 @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = String.class)})
142 public ResponseEntity<String> getPolicyTypes( //
143 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get types for.") //
144 @RequestParam(name = "ric", required = false) String ricName) {
145 if (ricName == null) {
146 Collection<PolicyType> types = this.policyTypes.getAll();
147 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
150 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
151 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
152 } catch (ServiceException e) {
153 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
158 @GetMapping("/policy")
159 @ApiOperation(value = "Returns a policy configuration") //
160 @ApiResponses(value = { //
161 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
162 @ApiResponse(code = 404, message = "Policy is not found")} //
164 public ResponseEntity<String> getPolicy( //
165 @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") //
166 @RequestParam(name = "id", required = true) String id) {
168 Policy p = policies.getPolicy(id);
169 return new ResponseEntity<>(p.json(), HttpStatus.OK);
170 } catch (ServiceException e) {
171 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
175 @DeleteMapping("/policy")
176 @ApiOperation(value = "Delete a policy", response = Object.class)
177 @ApiResponses(value = { //
178 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
179 @ApiResponse(code = 204, message = "Policy deleted", response = VoidResponse.class),
180 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
181 @ApiResponse(code = 423, message = "Near-RT RIC is not operational", response = String.class)})
182 public Mono<ResponseEntity<Object>> deletePolicy( //
183 @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") //
184 @RequestParam(name = "id", required = true) String id) {
186 Policy policy = policies.getPolicy(id);
187 keepServiceAlive(policy.ownerServiceId());
188 Ric ric = policy.ric();
189 return ric.getLock().lock(LockType.SHARED) //
190 .flatMap(notUsed -> assertRicStateIdle(ric)) //
191 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
192 .doOnNext(notUsed -> policies.remove(policy)) //
193 .flatMap(client -> client.deletePolicy(policy)) //
194 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
195 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
196 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
197 .onErrorResume(this::handleException);
198 } catch (ServiceException e) {
199 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
203 @PutMapping(path = "/policy")
204 @ApiOperation(value = "Put a policy", response = VoidResponse.class)
205 @ApiResponses(value = { //
206 @ApiResponse(code = 201, message = "Policy created", response = VoidResponse.class), //
207 @ApiResponse(code = 200, message = "Policy updated", response = VoidResponse.class), //
208 @ApiResponse(code = 423, message = "Near-RT RIC is not operational", response = String.class), //
209 @ApiResponse(code = 404, message = "Near-RT RIC or policy type is not found", response = String.class) //
211 public Mono<ResponseEntity<Object>> putPolicy( //
212 @ApiParam(name = "type", required = false, value = "The name of the policy type.") //
213 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
214 @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") //
215 @RequestParam(name = "id", required = true) String instanceId, //
216 @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " + //
218 @RequestParam(name = "ric", required = true) String ricName, //
219 @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") //
220 @RequestParam(name = "service", required = true) String service, //
221 @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " + //
222 "defaulted to false). A policy is transient if it will be forgotten when the service needs to " + //
223 "reconnect to the Near-RT RIC.") //
224 @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
225 @RequestBody Object jsonBody) {
227 String jsonString = gson.toJson(jsonBody);
228 Ric ric = rics.get(ricName);
229 PolicyType type = policyTypes.get(typeName);
230 keepServiceAlive(service);
231 if (ric == null || type == null) {
232 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
234 Policy policy = ImmutablePolicy.builder() //
239 .ownerServiceId(service) //
240 .lastModified(Instant.now()) //
241 .isTransient(isTransient) //
244 final boolean isCreate = this.policies.get(policy.id()) == null;
246 return ric.getLock().lock(LockType.SHARED) //
247 .flatMap(notUsed -> assertRicStateIdle(ric)) //
248 .flatMap(notUsed -> checkSupportedType(ric, type)) //
249 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
250 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
251 .flatMap(client -> client.putPolicy(policy)) //
252 .doOnNext(notUsed -> policies.put(policy)) //
253 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
254 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
255 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
256 .onErrorResume(this::handleException);
259 @SuppressWarnings({"unchecked"})
260 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
261 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
262 return Mono.just(re);
265 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
266 if (throwable instanceof WebClientResponseException) {
267 WebClientResponseException e = (WebClientResponseException) throwable;
268 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
269 } else if (throwable instanceof RejectionException) {
270 RejectionException e = (RejectionException) throwable;
271 return createResponseEntity(e.getMessage(), e.getStatus());
273 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
277 private Mono<Object> validateModifiedPolicy(Policy policy) {
278 // Check that ric is not updated
279 Policy current = this.policies.get(policy.id());
280 if (current != null && !current.ric().id().equals(policy.ric().id())) {
281 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
282 ", RIC name: " + current.ric().id() + //
283 ", new name: " + policy.ric().id(), HttpStatus.CONFLICT);
284 logger.debug("Request rejected, {}", e.getMessage());
285 return Mono.error(e);
287 return Mono.just("OK");
290 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
291 if (!ric.isSupportingType(type.id())) {
292 logger.debug("Request rejected, type not supported, RIC: {}", ric);
293 RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(),
294 HttpStatus.NOT_FOUND);
295 return Mono.error(e);
297 return Mono.just("OK");
300 private Mono<Object> assertRicStateIdle(Ric ric) {
301 if (ric.getState() == Ric.RicState.AVAILABLE) {
302 return Mono.just("OK");
304 logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
305 RejectionException e = new RejectionException(
306 "Ric is not operational, RIC name: " + ric.id() + ", state: " + ric.getState(), HttpStatus.LOCKED);
307 return Mono.error(e);
311 @GetMapping("/policies")
312 @ApiOperation(value = "Query policies")
313 @ApiResponses(value = {
314 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
315 @ApiResponse(code = 404, message = "Near-RT RIC or type not found", response = String.class)})
316 public ResponseEntity<String> getPolicies( //
317 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
318 @RequestParam(name = "type", required = false) String type, //
319 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
320 @RequestParam(name = "ric", required = false) String ric, //
321 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
322 @RequestParam(name = "service", required = false) String service) //
324 if ((type != null && this.policyTypes.get(type) == null)) {
325 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
327 if ((ric != null && this.rics.get(ric) == null)) {
328 return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
331 String filteredPolicies = policiesToJson(filter(type, ric, service));
332 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
335 @GetMapping("/policy_ids")
336 @ApiOperation(value = "Query policies, only policy identities returned")
337 @ApiResponses(value = {
338 @ApiResponse(code = 200, message = "Policy identitiess", response = String.class,
339 responseContainer = "List"),
340 @ApiResponse(code = 404, message = "Near-RT RIC or type not found", response = String.class)})
341 public ResponseEntity<String> getPolicyIds( //
342 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
343 @RequestParam(name = "type", required = false) String type, //
344 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
345 @RequestParam(name = "ric", required = false) String ric, //
346 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
347 @RequestParam(name = "service", required = false) String service) //
349 if ((type != null && this.policyTypes.get(type) == null)) {
350 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
352 if ((ric != null && this.rics.get(ric) == null)) {
353 return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
356 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
357 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
360 @GetMapping("/policy_status")
361 @ApiOperation(value = "Returns a policy status") //
362 @ApiResponses(value = { //
363 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
364 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
366 public Mono<ResponseEntity<String>> getPolicyStatus( //
367 @ApiParam(name = "id", required = true, value = "The identity of the policy.") @RequestParam(name = "id", //
368 required = true) String id) {
370 Policy policy = policies.getPolicy(id);
372 return a1ClientFactory.createA1Client(policy.ric()) //
373 .flatMap(client -> client.getPolicyStatus(policy)) //
374 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
375 .onErrorResume(this::handleException);
376 } catch (ServiceException e) {
377 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
381 private void keepServiceAlive(String name) {
382 Service s = this.services.get(name);
388 private boolean include(String filter, String value) {
389 return filter == null || value.equals(filter);
392 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
393 if (type == null && ric == null && service == null) {
396 List<Policy> filtered = new ArrayList<>();
397 for (Policy p : collection) {
398 if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) {
405 private Collection<Policy> filter(String type, String ric, String service) {
407 return filter(policies.getForType(type), null, ric, service);
408 } else if (service != null) {
409 return filter(policies.getForService(service), type, ric, null);
410 } else if (ric != null) {
411 return filter(policies.getForRic(ric), type, null, service);
413 return policies.getAll();
417 private String policiesToJson(Collection<Policy> policies) {
418 List<PolicyInfo> v = new ArrayList<>(policies.size());
419 for (Policy p : policies) {
420 PolicyInfo policyInfo = new PolicyInfo();
421 policyInfo.id = p.id();
422 policyInfo.json = fromJson(p.json());
423 policyInfo.ric = p.ric().id();
424 policyInfo.type = p.type().id();
425 policyInfo.service = p.ownerServiceId();
426 policyInfo.lastModified = p.lastModified().toString();
427 if (!policyInfo.validate()) {
428 logger.error("BUG, all fields must be set");
432 return gson.toJson(v);
435 private Object fromJson(String jsonStr) {
436 return gson.fromJson(jsonStr, Object.class);
439 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
440 StringBuilder result = new StringBuilder();
442 boolean first = true;
443 for (PolicyType t : types) {
448 result.append(t.schema());
451 return result.toString();
454 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
455 List<String> v = new ArrayList<>(types.size());
456 for (PolicyType t : types) {
459 return gson.toJson(v);
462 private String toPolicyIdsJson(Collection<Policy> policies) {
463 List<String> v = new ArrayList<>(policies.size());
464 for (Policy p : policies) {
467 return gson.toJson(v);