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().create();
96 @GetMapping("/policy_schemas")
97 @ApiOperation(value = "Returns policy type schema definitions")
98 @ApiResponses(value = {
99 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
100 @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = String.class)})
101 public ResponseEntity<String> getPolicySchemas( //
102 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get the definitions for.") //
103 @RequestParam(name = "ric", required = false) String ricName) {
104 if (ricName == null) {
105 Collection<PolicyType> types = this.policyTypes.getAll();
106 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
109 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
110 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
111 } catch (ServiceException e) {
112 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
117 @GetMapping("/policy_schema")
118 @ApiOperation(value = "Returns one policy type schema definition")
119 @ApiResponses(value = { //
120 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
121 @ApiResponse(code = 404, message = "The policy type is not found", response = String.class)})
122 public ResponseEntity<String> getPolicySchema( //
123 @ApiParam(name = "id", required = true,
124 value = "The identity of the policy type to get the definition for.") //
125 @RequestParam(name = "id", required = true) String id) {
127 PolicyType type = policyTypes.getType(id);
128 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
129 } catch (ServiceException e) {
130 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
134 @GetMapping("/policy_types")
135 @ApiOperation(value = "Query policy type names")
136 @ApiResponses(value = {
137 @ApiResponse(code = 200, message = "Policy type names", response = String.class,
138 responseContainer = "List"),
139 @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = String.class)})
140 public ResponseEntity<String> getPolicyTypes( //
141 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get types for.") //
142 @RequestParam(name = "ric", required = false) String ricName) {
143 if (ricName == null) {
144 Collection<PolicyType> types = this.policyTypes.getAll();
145 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
148 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
149 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
150 } catch (ServiceException e) {
151 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
156 @GetMapping("/policy")
157 @ApiOperation(value = "Returns a policy configuration") //
158 @ApiResponses(value = { //
159 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
160 @ApiResponse(code = 404, message = "Policy is not found")} //
162 public ResponseEntity<String> getPolicy( //
163 @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") //
164 @RequestParam(name = "id", required = true) String id) {
166 Policy p = policies.getPolicy(id);
167 return new ResponseEntity<>(p.json(), HttpStatus.OK);
168 } catch (ServiceException e) {
169 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
173 @DeleteMapping("/policy")
174 @ApiOperation(value = "Delete a policy", response = Object.class)
175 @ApiResponses(value = { //
176 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
177 @ApiResponse(code = 204, message = "Policy deleted", response = VoidResponse.class),
178 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
179 @ApiResponse(code = 423, message = "Near-RT RIC is not operational", response = String.class)})
180 public Mono<ResponseEntity<Object>> deletePolicy( //
181 @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") //
182 @RequestParam(name = "id", required = true) String id) {
184 Policy policy = policies.getPolicy(id);
185 keepServiceAlive(policy.ownerServiceId());
186 Ric ric = policy.ric();
187 return ric.getLock().lock(LockType.SHARED) //
188 .flatMap(notUsed -> assertRicStateIdle(ric)) //
189 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
190 .doOnNext(notUsed -> policies.remove(policy)) //
191 .flatMap(client -> client.deletePolicy(policy)) //
192 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
193 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
194 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
195 .onErrorResume(this::handleException);
196 } catch (ServiceException e) {
197 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
201 @PutMapping(path = "/policy")
202 @ApiOperation(value = "Put a policy", response = VoidResponse.class)
203 @ApiResponses(value = { //
204 @ApiResponse(code = 201, message = "Policy created", response = VoidResponse.class), //
205 @ApiResponse(code = 200, message = "Policy updated", response = VoidResponse.class), //
206 @ApiResponse(code = 423, message = "Near-RT RIC is not operational", response = String.class), //
207 @ApiResponse(code = 404, message = "Near-RT RIC or policy type is not found", response = String.class) //
209 public Mono<ResponseEntity<Object>> putPolicy( //
210 @ApiParam(name = "type", required = false, value = "The name of the policy type.") //
211 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
212 @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") //
213 @RequestParam(name = "id", required = true) String instanceId, //
214 @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " + //
216 @RequestParam(name = "ric", required = true) String ricName, //
217 @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") //
218 @RequestParam(name = "service", required = true) String service, //
219 @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " + //
220 "defaulted to false). A policy is transient if it will be forgotten when the service needs to " + //
221 "reconnect to the Near-RT RIC.") //
222 @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
223 @RequestBody Object jsonBody) {
225 String jsonString = gson.toJson(jsonBody);
226 Ric ric = rics.get(ricName);
227 PolicyType type = policyTypes.get(typeName);
228 keepServiceAlive(service);
229 if (ric == null || type == null) {
230 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
232 Policy policy = ImmutablePolicy.builder() //
237 .ownerServiceId(service) //
238 .lastModified(Instant.now()) //
239 .isTransient(isTransient) //
240 .statusNotificationUri("") //
243 final boolean isCreate = this.policies.get(policy.id()) == null;
245 return ric.getLock().lock(LockType.SHARED) //
246 .flatMap(notUsed -> assertRicStateIdle(ric)) //
247 .flatMap(notUsed -> checkSupportedType(ric, type)) //
248 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
249 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
250 .flatMap(client -> client.putPolicy(policy)) //
251 .doOnNext(notUsed -> policies.put(policy)) //
252 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
253 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
254 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
255 .onErrorResume(this::handleException);
258 @SuppressWarnings({"unchecked"})
259 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
260 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
261 return Mono.just(re);
264 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
265 if (throwable instanceof WebClientResponseException) {
266 WebClientResponseException e = (WebClientResponseException) throwable;
267 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
268 } else if (throwable instanceof RejectionException) {
269 RejectionException e = (RejectionException) throwable;
270 return createResponseEntity(e.getMessage(), e.getStatus());
272 return createResponseEntity(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.id());
279 if (current != null && !current.ric().id().equals(policy.ric().id())) {
280 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
281 ", RIC name: " + current.ric().id() + //
282 ", new name: " + policy.ric().id(), HttpStatus.CONFLICT);
283 logger.debug("Request rejected, {}", e.getMessage());
284 return Mono.error(e);
286 return Mono.just("OK");
289 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
290 if (!ric.isSupportingType(type.id())) {
291 logger.debug("Request rejected, type not supported, RIC: {}", ric);
292 RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(),
293 HttpStatus.NOT_FOUND);
294 return Mono.error(e);
296 return Mono.just("OK");
299 private Mono<Object> assertRicStateIdle(Ric ric) {
300 if (ric.getState() == Ric.RicState.AVAILABLE) {
301 return Mono.just("OK");
303 logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
304 RejectionException e = new RejectionException(
305 "Ric is not operational, RIC name: " + ric.id() + ", state: " + ric.getState(), HttpStatus.LOCKED);
306 return Mono.error(e);
310 @GetMapping("/policies")
311 @ApiOperation(value = "Query policies")
312 @ApiResponses(value = {
313 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
314 @ApiResponse(code = 404, message = "Near-RT RIC or type not found", response = String.class)})
315 public ResponseEntity<String> getPolicies( //
316 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
317 @RequestParam(name = "type", required = false) String type, //
318 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
319 @RequestParam(name = "ric", required = false) String ric, //
320 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
321 @RequestParam(name = "service", required = false) String service) //
323 if ((type != null && this.policyTypes.get(type) == null)) {
324 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
326 if ((ric != null && this.rics.get(ric) == null)) {
327 return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
330 String filteredPolicies = policiesToJson(filter(type, ric, service));
331 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
334 @GetMapping("/policy_ids")
335 @ApiOperation(value = "Query policies, only policy identities returned")
336 @ApiResponses(value = {
337 @ApiResponse(code = 200, message = "Policy identitiess", response = String.class,
338 responseContainer = "List"),
339 @ApiResponse(code = 404, message = "Near-RT RIC or type not found", response = String.class)})
340 public ResponseEntity<String> getPolicyIds( //
341 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
342 @RequestParam(name = "type", required = false) String type, //
343 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
344 @RequestParam(name = "ric", required = false) String ric, //
345 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
346 @RequestParam(name = "service", required = false) String service) //
348 if ((type != null && this.policyTypes.get(type) == null)) {
349 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
351 if ((ric != null && this.rics.get(ric) == null)) {
352 return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
355 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
356 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
359 @GetMapping("/policy_status")
360 @ApiOperation(value = "Returns a policy status") //
361 @ApiResponses(value = { //
362 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
363 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
365 public Mono<ResponseEntity<String>> getPolicyStatus( //
366 @ApiParam(name = "id", required = true, value = "The identity of the policy.") @RequestParam(name = "id", //
367 required = true) String id) {
369 Policy policy = policies.getPolicy(id);
371 return a1ClientFactory.createA1Client(policy.ric()) //
372 .flatMap(client -> client.getPolicyStatus(policy)) //
373 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
374 .onErrorResume(this::handleException);
375 } catch (ServiceException e) {
376 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
380 private void keepServiceAlive(String name) {
381 Service s = this.services.get(name);
387 private boolean include(String filter, String value) {
388 return filter == null || value.equals(filter);
391 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
392 if (type == null && ric == null && service == null) {
395 List<Policy> filtered = new ArrayList<>();
396 for (Policy p : collection) {
397 if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) {
404 private Collection<Policy> filter(String type, String ric, String service) {
406 return filter(policies.getForType(type), null, ric, service);
407 } else if (service != null) {
408 return filter(policies.getForService(service), type, ric, null);
409 } else if (ric != null) {
410 return filter(policies.getForRic(ric), type, null, service);
412 return policies.getAll();
416 private String policiesToJson(Collection<Policy> policies) {
417 List<PolicyInfo> v = new ArrayList<>(policies.size());
418 for (Policy p : policies) {
419 PolicyInfo policyInfo = new PolicyInfo();
420 policyInfo.id = p.id();
421 policyInfo.json = fromJson(p.json());
422 policyInfo.ric = p.ric().id();
423 policyInfo.type = p.type().id();
424 policyInfo.service = p.ownerServiceId();
425 policyInfo.lastModified = p.lastModified().toString();
426 if (!policyInfo.validate()) {
427 logger.error("BUG, all fields must be set");
431 return gson.toJson(v);
434 private Object fromJson(String jsonStr) {
435 return gson.fromJson(jsonStr, Object.class);
438 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
439 StringBuilder result = new StringBuilder();
441 boolean first = true;
442 for (PolicyType t : types) {
447 result.append(t.schema());
450 return result.toString();
453 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
454 List<String> v = new ArrayList<>(types.size());
455 for (PolicyType t : types) {
458 return gson.toJson(v);
461 private String toPolicyIdsJson(Collection<Policy> policies) {
462 List<String> v = new ArrayList<>(policies.size());
463 for (Policy p : policies) {
466 return gson.toJson(v);