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.util.ArrayList;
32 import java.util.Collection;
33 import java.util.List;
37 import org.oransc.policyagent.clients.A1ClientFactory;
38 import org.oransc.policyagent.exceptions.ServiceException;
39 import org.oransc.policyagent.repository.ImmutablePolicy;
40 import org.oransc.policyagent.repository.Lock.LockType;
41 import org.oransc.policyagent.repository.Policies;
42 import org.oransc.policyagent.repository.Policy;
43 import org.oransc.policyagent.repository.PolicyType;
44 import org.oransc.policyagent.repository.PolicyTypes;
45 import org.oransc.policyagent.repository.Ric;
46 import org.oransc.policyagent.repository.Rics;
47 import org.oransc.policyagent.repository.Service;
48 import org.oransc.policyagent.repository.Services;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.http.HttpStatus;
51 import org.springframework.http.ResponseEntity;
52 import org.springframework.web.bind.annotation.DeleteMapping;
53 import org.springframework.web.bind.annotation.GetMapping;
54 import org.springframework.web.bind.annotation.PutMapping;
55 import org.springframework.web.bind.annotation.RequestBody;
56 import org.springframework.web.bind.annotation.RequestParam;
57 import org.springframework.web.bind.annotation.RestController;
58 import org.springframework.web.reactive.function.client.WebClientResponseException;
59 import reactor.core.publisher.Mono;
62 @Api(tags = "A1 Policy Management")
63 public class PolicyController {
65 public static class RejectionException extends Exception {
66 private static final long serialVersionUID = 1L;
68 private final HttpStatus status;
70 public RejectionException(String message, HttpStatus status) {
79 private PolicyTypes policyTypes;
81 private Policies policies;
83 private A1ClientFactory a1ClientFactory;
85 private Services services;
87 private static Gson gson = new GsonBuilder() //
91 @GetMapping("/policy_schemas")
92 @ApiOperation(value = "Returns policy type schema definitions")
95 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
96 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
97 public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
98 synchronized (this.policyTypes) {
99 if (ricName == null) {
100 Collection<PolicyType> types = this.policyTypes.getAll();
101 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
104 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
105 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
106 } catch (ServiceException e) {
107 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
113 @GetMapping("/policy_schema")
114 @ApiOperation(value = "Returns one policy type schema definition")
117 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
118 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
119 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
121 PolicyType type = policyTypes.getType(id);
122 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
123 } catch (ServiceException e) {
124 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
128 @GetMapping("/policy_types")
129 @ApiOperation(value = "Query policy type names")
134 message = "Policy type names",
135 response = String.class,
136 responseContainer = "List"),
137 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
138 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
139 synchronized (this.policyTypes) {
140 if (ricName == null) {
141 Collection<PolicyType> types = this.policyTypes.getAll();
142 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
145 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
146 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
147 } catch (ServiceException e) {
148 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 = "instance", required = true) String instance) {
164 Policy p = policies.getPolicy(instance);
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 locked", response = String.class)})
178 public Mono<ResponseEntity<Object>> deletePolicy( //
179 @RequestParam(name = "instance", required = true) String id) {
182 policy = policies.getPolicy(id);
183 keepServiceAlive(policy.ownerServiceName());
184 if (policy.ric().getState() != Ric.RicState.IDLE) {
185 return Mono.just(new ResponseEntity<>("Busy, synchronizing", HttpStatus.LOCKED));
187 Ric ric = policy.ric();
188 return ric.getLock().lock(LockType.SHARED) // //
189 .flatMap(lock -> 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 = String.class)
205 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
206 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
207 @ApiResponse(code = 423, message = "RIC is locked", response = String.class), //
208 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
210 public Mono<ResponseEntity<Object>> putPolicy( //
211 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
212 @RequestParam(name = "instance", required = true) String instanceId, //
213 @RequestParam(name = "ric", required = true) String ricName, //
214 @RequestParam(name = "service", required = true) String service, //
215 @RequestBody Object jsonBody) {
217 String jsonString = gson.toJson(jsonBody);
218 Ric ric = rics.get(ricName);
219 PolicyType type = policyTypes.get(typeName);
220 keepServiceAlive(service);
221 if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) {
222 Policy policy = ImmutablePolicy.builder() //
227 .ownerServiceName(service) //
228 .lastModified(getTimeStampUtc()) //
231 final boolean isCreate = this.policies.get(policy.id()) == null;
233 return ric.getLock().lock(LockType.SHARED) //
234 .flatMap(p -> validateModifiedPolicy(policy)) //
235 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
236 .flatMap(client -> client.putPolicy(policy)) //
237 .doOnNext(notUsed -> policies.put(policy)) //
238 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
239 .doOnError(t -> ric.getLock().unlockBlocking()) //
240 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
241 .onErrorResume(this::handleException);
244 return ric == null || type == null ? Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND))
245 : Mono.just(new ResponseEntity<>(HttpStatus.LOCKED)); // Synchronizing
248 @SuppressWarnings({"unchecked"})
249 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
250 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
251 return Mono.just(re);
254 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
255 if (throwable instanceof WebClientResponseException) {
256 WebClientResponseException e = (WebClientResponseException) throwable;
257 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
258 } else if (throwable instanceof RejectionException) {
259 RejectionException e = (RejectionException) throwable;
260 return createResponseEntity(e.getMessage(), e.getStatus());
262 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
266 private Mono<Object> validateModifiedPolicy(Policy policy) {
267 // Check that ric is not updated
268 Policy current = this.policies.get(policy.id());
269 if (current != null && !current.ric().name().equals(policy.ric().name())) {
270 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
271 ", RIC name: " + current.ric().name() + //
272 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
273 return Mono.error(e);
275 return Mono.just("OK");
278 @GetMapping("/policies")
279 @ApiOperation(value = "Query policies")
282 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
283 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
284 public ResponseEntity<String> getPolicies( //
285 @RequestParam(name = "type", required = false) String type, //
286 @RequestParam(name = "ric", required = false) String ric, //
287 @RequestParam(name = "service", required = false) String service) //
289 if ((type != null && this.policyTypes.get(type) == null)) {
290 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
292 if ((ric != null && this.rics.get(ric) == null)) {
293 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
295 synchronized (policies) {
296 String filteredPolicies = policiesToJson(filter(type, ric, service));
297 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
301 @GetMapping("/policy_ids")
302 @ApiOperation(value = "Query policies, only IDs returned")
304 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
305 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
306 public ResponseEntity<String> getPolicyIds( //
307 @RequestParam(name = "type", required = false) String type, //
308 @RequestParam(name = "ric", required = false) String ric, //
309 @RequestParam(name = "service", required = false) String service) //
311 if ((type != null && this.policyTypes.get(type) == null)) {
312 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
314 if ((ric != null && this.rics.get(ric) == null)) {
315 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
317 synchronized (policies) {
318 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
319 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
323 @GetMapping("/policy_status")
324 @ApiOperation(value = "Returns a policy status") //
327 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
328 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
330 public Mono<ResponseEntity<String>> getPolicyStatus( //
331 @RequestParam(name = "instance", required = true) String instance) {
333 Policy policy = policies.getPolicy(instance);
335 return a1ClientFactory.createA1Client(policy.ric()) //
336 .flatMap(client -> client.getPolicyStatus(policy)) //
337 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
338 .onErrorResume(this::handleException);
339 } catch (ServiceException e) {
340 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
344 private void keepServiceAlive(String name) {
345 Service s = this.services.get(name);
351 private boolean include(String filter, String value) {
352 return filter == null || value.equals(filter);
355 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
356 if (type == null && ric == null && service == null) {
359 List<Policy> filtered = new ArrayList<>();
360 for (Policy p : collection) {
361 if (include(type, p.type().name()) && include(ric, p.ric().name())
362 && include(service, p.ownerServiceName())) {
369 private Collection<Policy> filter(String type, String ric, String service) {
370 synchronized (policies) {
372 return filter(policies.getForType(type), null, ric, service);
373 } else if (service != null) {
374 return filter(policies.getForService(service), type, ric, null);
375 } else if (ric != null) {
376 return filter(policies.getForRic(ric), type, null, service);
378 return policies.getAll();
383 private String policiesToJson(Collection<Policy> policies) {
384 List<PolicyInfo> v = new ArrayList<>(policies.size());
385 for (Policy p : policies) {
386 PolicyInfo policyInfo = new PolicyInfo();
387 policyInfo.id = p.id();
388 policyInfo.json = fromJson(p.json());
389 policyInfo.ric = p.ric().name();
390 policyInfo.type = p.type().name();
391 policyInfo.service = p.ownerServiceName();
392 policyInfo.lastModified = p.lastModified();
393 if (!policyInfo.validate()) {
394 throw new NullPointerException("BUG, all fields must be set");
398 return gson.toJson(v);
401 private Object fromJson(String jsonStr) {
402 return gson.fromJson(jsonStr, Object.class);
405 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
406 StringBuilder result = new StringBuilder();
408 boolean first = true;
409 for (PolicyType t : types) {
414 result.append(t.schema());
417 return result.toString();
420 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
421 List<String> v = new ArrayList<>(types.size());
422 for (PolicyType t : types) {
425 return gson.toJson(v);
428 private String toPolicyIdsJson(Collection<Policy> policies) {
429 List<String> v = new ArrayList<>(policies.size());
430 for (Policy p : policies) {
433 return gson.toJson(v);
436 private String getTimeStampUtc() {
437 return java.time.Instant.now().toString();