2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent.controllers;
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.ApiResponse;
29 import io.swagger.annotations.ApiResponses;
31 import java.lang.invoke.MethodHandles;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.List;
38 import org.oransc.policyagent.clients.A1ClientFactory;
39 import org.oransc.policyagent.exceptions.ServiceException;
40 import org.oransc.policyagent.repository.ImmutablePolicy;
41 import org.oransc.policyagent.repository.Lock.LockType;
42 import org.oransc.policyagent.repository.Policies;
43 import org.oransc.policyagent.repository.Policy;
44 import org.oransc.policyagent.repository.PolicyType;
45 import org.oransc.policyagent.repository.PolicyTypes;
46 import org.oransc.policyagent.repository.Ric;
47 import org.oransc.policyagent.repository.Rics;
48 import org.oransc.policyagent.repository.Service;
49 import org.oransc.policyagent.repository.Services;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.http.HttpStatus;
54 import org.springframework.http.ResponseEntity;
55 import org.springframework.web.bind.annotation.DeleteMapping;
56 import org.springframework.web.bind.annotation.GetMapping;
57 import org.springframework.web.bind.annotation.PutMapping;
58 import org.springframework.web.bind.annotation.RequestBody;
59 import org.springframework.web.bind.annotation.RequestParam;
60 import org.springframework.web.bind.annotation.RestController;
61 import org.springframework.web.reactive.function.client.WebClientResponseException;
62 import reactor.core.publisher.Mono;
65 @Api(tags = "A1 Policy Management")
66 public class PolicyController {
68 public static class RejectionException extends Exception {
69 private static final long serialVersionUID = 1L;
71 private final HttpStatus status;
73 public RejectionException(String message, HttpStatus status) {
82 private PolicyTypes policyTypes;
84 private Policies policies;
86 private A1ClientFactory a1ClientFactory;
88 private Services services;
90 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
91 private static Gson gson = new GsonBuilder() //
95 @GetMapping("/policy_schemas")
96 @ApiOperation(value = "Returns policy type schema definitions")
99 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
100 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
101 public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
102 if (ricName == null) {
103 Collection<PolicyType> types = this.policyTypes.getAll();
104 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
107 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
108 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
109 } catch (ServiceException e) {
110 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
115 @GetMapping("/policy_schema")
116 @ApiOperation(value = "Returns one policy type schema definition")
119 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
120 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
121 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
123 PolicyType type = policyTypes.getType(id);
124 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
125 } catch (ServiceException e) {
126 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
130 @GetMapping("/policy_types")
131 @ApiOperation(value = "Query policy type names")
136 message = "Policy type names",
137 response = String.class,
138 responseContainer = "List"),
139 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
140 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
141 if (ricName == null) {
142 Collection<PolicyType> types = this.policyTypes.getAll();
143 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
146 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
147 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
148 } catch (ServiceException e) {
149 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
154 @GetMapping("/policy")
155 @ApiOperation(value = "Returns a policy configuration") //
158 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
159 @ApiResponse(code = 404, message = "Policy is not found")} //
161 public ResponseEntity<String> getPolicy( //
162 @RequestParam(name = "id", required = true) String id) {
164 Policy p = policies.getPolicy(id);
165 return new ResponseEntity<>(p.json(), HttpStatus.OK);
166 } catch (ServiceException e) {
167 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
171 @DeleteMapping("/policy")
172 @ApiOperation(value = "Delete a policy", response = Object.class)
175 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
176 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
177 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
178 public Mono<ResponseEntity<Object>> deletePolicy( //
179 @RequestParam(name = "id", required = true) String id) {
181 Policy policy = policies.getPolicy(id);
182 keepServiceAlive(policy.ownerServiceName());
183 Ric ric = policy.ric();
184 return ric.getLock().lock(LockType.SHARED) //
185 .flatMap(notUsed -> assertRicStateIdle(ric)) //
186 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
187 .doOnNext(notUsed -> policies.remove(policy)) //
188 .flatMap(client -> client.deletePolicy(policy)) //
189 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
190 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
191 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
192 .onErrorResume(this::handleException);
193 } catch (ServiceException e) {
194 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
198 @PutMapping(path = "/policy")
199 @ApiOperation(value = "Put a policy", response = String.class)
202 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
203 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
204 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
205 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
207 public Mono<ResponseEntity<Object>> putPolicy( //
208 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
209 @RequestParam(name = "id", required = true) String instanceId, //
210 @RequestParam(name = "ric", required = true) String ricName, //
211 @RequestParam(name = "service", required = true) String service, //
212 @RequestBody Object jsonBody) {
214 String jsonString = gson.toJson(jsonBody);
215 Ric ric = rics.get(ricName);
216 PolicyType type = policyTypes.get(typeName);
217 keepServiceAlive(service);
218 if (ric == null || type == null) {
219 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
221 Policy policy = ImmutablePolicy.builder() //
226 .ownerServiceName(service) //
227 .lastModified(getTimeStampUtc()) //
230 final boolean isCreate = this.policies.get(policy.id()) == null;
232 return ric.getLock().lock(LockType.SHARED) //
233 .flatMap(notUsed -> assertRicStateIdle(ric)) //
234 .flatMap(notUsed -> checkSupportedType(ric, type)) //
235 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
236 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
237 .flatMap(client -> client.putPolicy(policy)) //
238 .doOnNext(notUsed -> policies.put(policy)) //
239 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
240 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
241 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
242 .onErrorResume(this::handleException);
245 @SuppressWarnings({"unchecked"})
246 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
247 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
248 return Mono.just(re);
251 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
252 if (throwable instanceof WebClientResponseException) {
253 WebClientResponseException e = (WebClientResponseException) throwable;
254 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
255 } else if (throwable instanceof RejectionException) {
256 RejectionException e = (RejectionException) throwable;
257 return createResponseEntity(e.getMessage(), e.getStatus());
259 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
263 private Mono<Object> validateModifiedPolicy(Policy policy) {
264 // Check that ric is not updated
265 Policy current = this.policies.get(policy.id());
266 if (current != null && !current.ric().name().equals(policy.ric().name())) {
267 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
268 ", RIC name: " + current.ric().name() + //
269 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
270 return Mono.error(e);
272 return Mono.just("OK");
275 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
276 if (!ric.isSupportingType(type.name())) {
277 RejectionException e = new RejectionException(
278 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
279 return Mono.error(e);
281 return Mono.just("OK");
284 private Mono<Object> assertRicStateIdle(Ric ric) {
285 if (ric.getState() == Ric.RicState.AVAILABLE) {
286 return Mono.just("OK");
288 RejectionException e = new RejectionException(
289 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
290 return Mono.error(e);
294 @GetMapping("/policies")
295 @ApiOperation(value = "Query policies")
298 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
299 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
300 public ResponseEntity<String> getPolicies( //
301 @RequestParam(name = "type", required = false) String type, //
302 @RequestParam(name = "ric", required = false) String ric, //
303 @RequestParam(name = "service", required = false) String service) //
305 if ((type != null && this.policyTypes.get(type) == null)) {
306 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
308 if ((ric != null && this.rics.get(ric) == null)) {
309 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
312 String filteredPolicies = policiesToJson(filter(type, ric, service));
313 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
316 @GetMapping("/policy_ids")
317 @ApiOperation(value = "Query policies, only IDs returned")
319 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
320 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
321 public ResponseEntity<String> getPolicyIds( //
322 @RequestParam(name = "type", required = false) String type, //
323 @RequestParam(name = "ric", required = false) String ric, //
324 @RequestParam(name = "service", required = false) String service) //
326 if ((type != null && this.policyTypes.get(type) == null)) {
327 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
329 if ((ric != null && this.rics.get(ric) == null)) {
330 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
333 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
334 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
337 @GetMapping("/policy_status")
338 @ApiOperation(value = "Returns a policy status") //
341 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
342 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
344 public Mono<ResponseEntity<String>> getPolicyStatus( //
345 @RequestParam(name = "id", required = true) String id) {
347 Policy policy = policies.getPolicy(id);
349 return a1ClientFactory.createA1Client(policy.ric()) //
350 .flatMap(client -> client.getPolicyStatus(policy)) //
351 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
352 .onErrorResume(this::handleException);
353 } catch (ServiceException e) {
354 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
358 private void keepServiceAlive(String name) {
359 Service s = this.services.get(name);
365 private boolean include(String filter, String value) {
366 return filter == null || value.equals(filter);
369 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
370 if (type == null && ric == null && service == null) {
373 List<Policy> filtered = new ArrayList<>();
374 for (Policy p : collection) {
375 if (include(type, p.type().name()) && include(ric, p.ric().name())
376 && include(service, p.ownerServiceName())) {
383 private Collection<Policy> filter(String type, String ric, String service) {
385 return filter(policies.getForType(type), null, ric, service);
386 } else if (service != null) {
387 return filter(policies.getForService(service), type, ric, null);
388 } else if (ric != null) {
389 return filter(policies.getForRic(ric), type, null, service);
391 return policies.getAll();
395 private String policiesToJson(Collection<Policy> policies) {
396 List<PolicyInfo> v = new ArrayList<>(policies.size());
397 for (Policy p : policies) {
398 PolicyInfo policyInfo = new PolicyInfo();
399 policyInfo.id = p.id();
400 policyInfo.json = fromJson(p.json());
401 policyInfo.ric = p.ric().name();
402 policyInfo.type = p.type().name();
403 policyInfo.service = p.ownerServiceName();
404 policyInfo.lastModified = p.lastModified();
405 if (!policyInfo.validate()) {
406 logger.error("BUG, all fields must be set");
410 return gson.toJson(v);
413 private Object fromJson(String jsonStr) {
414 return gson.fromJson(jsonStr, Object.class);
417 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
418 StringBuilder result = new StringBuilder();
420 boolean first = true;
421 for (PolicyType t : types) {
426 result.append(t.schema());
429 return result.toString();
432 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
433 List<String> v = new ArrayList<>(types.size());
434 for (PolicyType t : types) {
437 return gson.toJson(v);
440 private String toPolicyIdsJson(Collection<Policy> policies) {
441 List<String> v = new ArrayList<>(policies.size());
442 for (Policy p : policies) {
445 return gson.toJson(v);
448 private String getTimeStampUtc() {
449 return java.time.Instant.now().toString();